content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | run `brew audit` before uploading | 9057a630212d95b57e7ee5492f7662a2340ff288 | <ide><path>Library/Homebrew/dev-cmd/pr-upload.rb
<ide> def pr_upload
<ide>
<ide> safe_system HOMEBREW_BREW_FILE, *bottle_args
<ide>
<add> # Check the bottle commits did not break `brew audit`
<add> unless args.no_commit?
<add> audit_args = ["bottle", "--merge", "--write"]
<add> audit_args << "--verbose" if args.verbose?
<add> audit_args << "--debug" if args.debug?
<add> safe_system HOMEBREW_BREW_FILE, *audit_args
<add> end
<add>
<ide> if github_releases?(bottles_hash)
<ide> # Handle uploading to GitHub Releases.
<ide> bottles_hash.each_value do |bottle_hash| | 1 |
Go | Go | allow user in builder | a3c4ab9b657018cf6fc33e70a44c790563c16043 | <ide><path>builder/dockerfile/evaluator_windows.go
<ide> import "fmt"
<ide> // a command not supported on the platform.
<ide> func platformSupports(command string) error {
<ide> switch command {
<del> case "user", "stopsignal":
<add> case "stopsignal":
<ide> return fmt.Errorf("The daemon on this platform does not support the command '%s'", command)
<ide> }
<ide> return nil
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildOpaqueDirectory(c *check.C) {
<ide> _, err := buildImage("testopaquedirectory", dockerFile, false)
<ide> c.Assert(err, checker.IsNil)
<ide> }
<add>
<add>// Windows test for USER in dockerfile
<add>func (s *DockerSuite) TestBuildWindowsUser(c *check.C) {
<add> testRequires(c, DaemonIsWindows)
<add> name := "testbuildwindowsuser"
<add> _, out, err := buildImageWithOut(name,
<add> `FROM `+WindowsBaseImage+`
<add> RUN net user user /add
<add> USER user
<add> RUN set username
<add> `,
<add> true)
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add> c.Assert(strings.ToLower(out), checker.Contains, "username=user")
<add>} | 2 |
Javascript | Javascript | manage percent character at unescape | 3b925219c341062a9fc648049e217fea79f0ea3d | <ide><path>lib/querystring.js
<ide> function unescapeBuffer(s, decodeSpaces) {
<ide> hexHigh = unhexTable[currentChar];
<ide> if (!(hexHigh >= 0)) {
<ide> out[outIndex++] = 37; // '%'
<add> continue;
<ide> } else {
<ide> nextChar = s.charCodeAt(++index);
<ide> hexLow = unhexTable[nextChar];
<ide> if (!(hexLow >= 0)) {
<ide> out[outIndex++] = 37; // '%'
<del> out[outIndex++] = currentChar;
<del> currentChar = nextChar;
<add> index--;
<ide> } else {
<ide> hasHex = true;
<ide> currentChar = hexHigh * 16 + hexLow;
<ide><path>test/parallel/test-querystring.js
<ide> const qsUnescapeTestCases = [
<ide> ['there%2Qare%0-fake%escaped values in%%%%this%9Hstring',
<ide> 'there%2Qare%0-fake%escaped values in%%%%this%9Hstring'],
<ide> ['%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F%30%31%32%33%34%35%36%37',
<del> ' !"#$%&\'()*+,-./01234567']
<add> ' !"#$%&\'()*+,-./01234567'],
<add> ['%%2a', '%*'],
<add> ['%2sf%2a', '%2sf*'],
<add> ['%2%2af%2a', '%2*f*']
<ide> ];
<ide>
<ide> assert.strictEqual(qs.parse('id=918854443121279438895193').id, | 2 |
Javascript | Javascript | verify registry built for ember.application | 00e517f36eba5db96f420f758647e53d233780a0 | <ide><path>packages/ember-application/tests/system/application_test.js
<ide> /*globals EmberDev */
<ide> import VERSION from 'ember/version';
<ide> import { ENV, context } from 'ember-environment';
<add>import isEnabled from 'ember-metal/features';
<ide> import run from 'ember-metal/run_loop';
<ide> import libraries from 'ember-metal/libraries';
<ide> import Application, { _resetLegacyAddonWarnings } from 'ember-application/system/application';
<ide> import compile from 'ember-template-compiler/system/compile';
<ide> import { _loaded } from 'ember-runtime/system/lazy_load';
<ide> import { getDebugFunction, setDebugFunction } from 'ember-metal/debug';
<ide> import { setTemplates, set as setTemplate } from 'ember-htmlbars/template_registry';
<add>import { privatize as P } from 'container/registry';
<add>import { verifyInjection, verifyRegistration } from '../test-helpers/registry-check';
<ide>
<ide> var trim = jQuery.trim;
<ide>
<ide> QUnit.test('includes deprecated access to `application.registry`', function() {
<ide> }, /Using `Application.registry.register` is deprecated. Please use `Application.register` instead./);
<ide> });
<ide>
<add>QUnit.test('builds a registry', function() {
<add> strictEqual(application.resolveRegistration('application:main'), application, `application:main is registered`);
<add> deepEqual(application.registeredOptionsForType('component'), { singleton: false }, `optionsForType 'component'`);
<add> deepEqual(application.registeredOptionsForType('view'), { singleton: false }, `optionsForType 'view'`);
<add> verifyInjection(application, 'renderer', 'dom', 'service:-dom-helper');
<add> verifyRegistration(application, 'controller:basic');
<add> verifyInjection(application, 'service:-dom-helper', 'document', 'service:-document');
<add> verifyRegistration(application, '-view-registry:main');
<add> verifyInjection(application, 'view', '_viewRegistry', '-view-registry:main');
<add> verifyInjection(application, 'route', '_topLevelViewTemplate', 'template:-outlet');
<add> verifyRegistration(application, 'route:basic');
<add> verifyRegistration(application, 'event_dispatcher:main');
<add> verifyInjection(application, 'router:main', 'namespace', 'application:main');
<add> verifyInjection(application, 'view:-outlet', 'namespace', 'application:main');
<add>
<add> verifyRegistration(application, 'location:auto');
<add> verifyRegistration(application, 'location:hash');
<add> verifyRegistration(application, 'location:history');
<add> verifyRegistration(application, 'location:none');
<add>
<add> verifyInjection(application, 'controller', 'target', 'router:main');
<add> verifyInjection(application, 'controller', 'namespace', 'application:main');
<add>
<add> verifyRegistration(application, P`-bucket-cache:main`);
<add> verifyInjection(application, 'router', '_bucketCache', P`-bucket-cache:main`);
<add> verifyInjection(application, 'route', '_bucketCache', P`-bucket-cache:main`);
<add> verifyInjection(application, 'controller', '_bucketCache', P`-bucket-cache:main`);
<add>
<add> verifyInjection(application, 'route', 'router', 'router:main');
<add>
<add> verifyRegistration(application, 'component:-text-field');
<add> verifyRegistration(application, 'component:-text-area');
<add> verifyRegistration(application, 'component:-checkbox');
<add> verifyRegistration(application, 'component:link-to');
<add>
<add> verifyRegistration(application, 'service:-routing');
<add> verifyInjection(application, 'service:-routing', 'router', 'router:main');
<add>
<add> // DEBUGGING
<add> verifyRegistration(application, 'resolver-for-debugging:main');
<add> verifyInjection(application, 'container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
<add> verifyInjection(application, 'data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
<add> verifyRegistration(application, 'container-debug-adapter:main');
<add>
<add> if (isEnabled('ember-glimmer')) {
<add> verifyRegistration(application, 'service:-glimmer-environment');
<add> verifyInjection(application, 'service:-glimmer-environment', 'dom', 'service:-dom-helper');
<add> verifyInjection(application, 'renderer', 'env', 'service:-glimmer-environment');
<add> verifyRegistration(application, 'view:-outlet');
<add> verifyRegistration(application, 'renderer:-dom');
<add> verifyRegistration(application, 'renderer:-inert');
<add> verifyRegistration(application, 'service:-dom-helper');
<add> verifyRegistration(application, P`template:components/-default`);
<add> verifyRegistration(application, 'template:-outlet');
<add> verifyInjection(application, 'view:-outlet', 'template', 'template:-outlet');
<add> verifyInjection(application, 'template', 'env', 'service:-glimmer-environment');
<add> deepEqual(application.registeredOptionsForType('helper'), { instantiate: false }, `optionsForType 'helper'`);
<add> } else {
<add> deepEqual(application.registeredOptionsForType('template'), { instantiate: false }, `optionsForType 'template'`);
<add> verifyRegistration(application, 'view:-outlet');
<add> verifyRegistration(application, 'renderer:-dom');
<add> verifyRegistration(application, 'renderer:-inert');
<add> verifyRegistration(application, 'service:-dom-helper');
<add> verifyRegistration(application, 'template:-outlet');
<add> verifyRegistration(application, 'view:toplevel');
<add> }
<add>});
<add>
<ide> const originalLogVersion = ENV.LOG_VERSION;
<ide>
<ide> QUnit.module('Ember.Application initialization', { | 1 |
Python | Python | fix part of ticket #893 | 2c7654ad26fb9e374ce062461d3986c31d609a49 | <ide><path>numpy/ma/core.py
<ide> def get_data(a, subok=True):
<ide> if not subok:
<ide> return data.view(ndarray)
<ide> return data
<add>
<ide> getdata = get_data
<ide>
<ide> def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
<ide> def __init__ (self, mbfunc, fillx=0, filly=0):
<ide> self.__name__ = getattr(mbfunc, "__name__", str(mbfunc))
<ide> ufunc_domain[mbfunc] = None
<ide> ufunc_fills[mbfunc] = (fillx, filly)
<del> #
<add>
<ide> def __call__ (self, a, b, *args, **kwargs):
<ide> "Execute the call behavior."
<ide> m = mask_or(getmask(a), getmask(b))
<ide> def __call__ (self, a, b, *args, **kwargs):
<ide> elif m:
<ide> return masked
<ide> return result
<del> #
<add>
<ide> def reduce(self, target, axis=0, dtype=None):
<ide> """Reduce `target` along the given `axis`."""
<ide> if isinstance(target, MaskedArray):
<ide> def inner(a, b):
<ide> if len(fb.shape) == 0:
<ide> fb.shape = (1,)
<ide> return np.inner(fa, fb).view(MaskedArray)
<del>inner.__doc__ = np.inner.__doc__
<del>inner.__doc__ += doc_note("Masked values are replaced by 0.")
<add>
<ide> innerproduct = inner
<add>if np.inner.__doc__ is not None :
<add> notes = doc_note("Masked values are replaced by 0.")
<add> inner.__doc__ = np.inner.__doc__ + notes
<ide>
<ide> def outer(a, b):
<ide> "maskedarray version of the numpy function."
<ide> def outer(a, b):
<ide> mb = getmaskarray(b)
<ide> m = make_mask(1-np.outer(1-ma, 1-mb), copy=0)
<ide> return masked_array(d, mask=m)
<del>outer.__doc__ = np.outer.__doc__
<del>outer.__doc__ += doc_note("Masked values are replaced by 0.")
<add>
<ide> outerproduct = outer
<add>if np.outer.__doc__ is not None :
<add> notes = doc_note("Masked values are replaced by 0.")
<add> outer.__doc__ = np.outer.__doc__ + notes
<ide>
<ide> def allequal (a, b, fill_value=True):
<ide> """Return True if all entries of a and b are equal, using | 1 |
PHP | PHP | move view\error to view\exception | c1b5187c8b71d15ae8c561d47500dfba3408fc07 | <ide><path>src/Error/ExceptionRenderer.php
<ide> use Cake\Network\Response;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Inflector;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingViewException;
<ide> use Exception;
<ide>
<ide> /**
<ide><path>src/View/Cell.php
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Utility\Inflector;
<del>use Cake\View\Error\MissingCellViewException;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingCellViewException;
<add>use Cake\View\Exception\MissingViewException;
<ide> use Cake\View\ViewVarsTrait;
<ide>
<ide> /**
<ide> public function __construct(Request $request = null, Response $response = null,
<ide> * @param string $template Custom template name to render. If not provided (null), the last
<ide> * value will be used. This value is automatically set by `CellTrait::cell()`.
<ide> * @return void
<del> * @throws \Cake\View\Error\MissingCellViewException When a MissingViewException is raised during rendering.
<add> * @throws \Cake\View\Exception\MissingCellViewException When a MissingViewException is raised during rendering.
<ide> */
<ide> public function render($template = null) {
<ide> if ($template !== null && strpos($template, '/') === false) {
<ide><path>src/View/CellTrait.php
<ide> trait CellTrait {
<ide> * `cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Cell\TagCloud::smallList(v1, v2)`
<ide> * @param array $options Options for Cell's constructor
<ide> * @return \Cake\View\Cell The cell instance
<del> * @throws \Cake\View\Error\MissingCellException If Cell class was not found.
<add> * @throws \Cake\View\Exception\MissingCellException If Cell class was not found.
<ide> * @throws \BadMethodCallException If Cell class does not specified cell action.
<ide> */
<ide> public function cell($cell, array $data = [], array $options = []) {
<ide> public function cell($cell, array $data = [], array $options = []) {
<ide> $className = App::className($pluginAndCell, 'View/Cell', 'Cell');
<ide>
<ide> if (!$className) {
<del> throw new Error\MissingCellException(array('className' => $pluginAndCell . 'Cell'));
<add> throw new Exception\MissingCellException(array('className' => $pluginAndCell . 'Cell'));
<ide> }
<ide>
<ide> $cell = $this->_createCell($className, $action, $plugin, $options);
<add><path>src/View/Exception/MissingCellException.php
<del><path>src/View/Error/MissingCellException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<add><path>src/View/Exception/MissingCellViewException.php
<del><path>src/View/Error/MissingCellViewException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<add><path>src/View/Exception/MissingElementException.php
<del><path>src/View/Error/MissingElementException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<add><path>src/View/Exception/MissingHelperException.php
<del><path>src/View/Error/MissingHelperException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<add><path>src/View/Exception/MissingLayoutException.php
<del><path>src/View/Error/MissingLayoutException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<add><path>src/View/Exception/MissingViewException.php
<del><path>src/View/Error/MissingViewException.php
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Error;
<add>namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide>
<ide><path>src/View/HelperRegistry.php
<ide> namespace Cake\View;
<ide>
<ide> use Cake\Core\App;
<del>use Cake\Event\EventManagerTrait;
<ide> use Cake\Core\ObjectRegistry;
<add>use Cake\Event\EventManagerTrait;
<ide> use Cake\View\View;
<ide>
<ide> /**
<ide> public function __construct(View $view) {
<ide> *
<ide> * @param string $helper The helper name to be loaded
<ide> * @return bool whether the helper could be loaded or not
<del> * @throws \Cake\View\Error\MissingHelperException When a helper could not be found.
<add> * @throws \Cake\View\Exception\MissingHelperException When a helper could not be found.
<ide> * App helpers are searched, and then plugin helpers.
<ide> */
<ide> public function __isset($helper) {
<ide> protected function _resolveClassName($class) {
<ide> * @param string $class The classname that is missing.
<ide> * @param string $plugin The plugin the helper is missing in.
<ide> * @return void
<del> * @throws \Cake\View\Error\MissingHelperException
<add> * @throws \Cake\View\Exception\MissingHelperException
<ide> */
<ide> protected function _throwMissingClassError($class, $plugin) {
<del> throw new Error\MissingHelperException([
<add> throw new Exception\MissingHelperException([
<ide> 'class' => $class . 'Helper',
<ide> 'plugin' => $plugin
<ide> ]);
<ide><path>src/View/View.php
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Core\Exception\Exception;
<ide> use Cake\Event\Event;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\CellTrait;
<ide> use Cake\View\ViewVarsTrait;
<add>use InvalidArgumentException;
<add>use LogicException;
<ide>
<ide> /**
<ide> * View, the V in the MVC triad. View interacts with Helpers and view variables passed
<ide> public function __construct(Request $request = null, Response $response = null,
<ide> * Defaults to false.
<ide> * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
<ide> * @return string Rendered Element
<del> * @throws \Cake\View\Error\MissingElementException When an element is missing and `ignoreMissing`
<add> * @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
<ide> * is false.
<ide> */
<ide> public function element($name, array $data = array(), array $options = array()) {
<ide> public function element($name, array $data = array(), array $options = array())
<ide> list ($plugin, $name) = pluginSplit($name, true);
<ide> $name = str_replace('/', DS, $name);
<ide> $file = $plugin . 'Element' . DS . $name . $this->_ext;
<del> throw new Error\MissingElementException($file);
<add> throw new Exception\MissingElementException($file);
<ide> }
<ide> }
<ide>
<ide> public function loadHelpers() {
<ide> * array of data. Handles parent/extended views.
<ide> *
<ide> * @param string $viewFile Filename of the view
<del> * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
<add> * @param array $data Data to include in rendered view. If empty the current
<add> * View::$viewVars will be used.
<ide> * @return string Rendered output
<del> * @throws \Cake\Core\Exception\Exception when a block is left open.
<add> * @throws \LogicException When a block is left open.
<ide> */
<ide> protected function _render($viewFile, $data = array()) {
<ide> if (empty($data)) {
<ide> protected function _render($viewFile, $data = array()) {
<ide> $remainingBlocks = count($this->Blocks->unclosed());
<ide>
<ide> if ($initialBlocks !== $remainingBlocks) {
<del> throw new Exception(sprintf(
<add> throw new LogicException(sprintf(
<ide> 'The "%s" block was left open. Blocks are not allowed to cross files.',
<ide> $this->Blocks->active()
<ide> ));
<ide> public function addHelper($helperName, array $config = []) {
<ide> *
<ide> * @param string $name Controller action to find template filename for
<ide> * @return string Template filename
<del> * @throws \Cake\View\Error\MissingViewException when a view file could not be found.
<add> * @throws \Cake\View\Exception\MissingViewException when a view file could not be found.
<ide> */
<ide> protected function _getViewFileName($name = null) {
<ide> $subDir = null;
<ide> protected function _getViewFileName($name = null) {
<ide> return $this->_checkFilePath($path . $name . $this->_ext, $path);
<ide> }
<ide> }
<del> throw new Error\MissingViewException(array('file' => $name . $this->_ext));
<add> throw new Exception\MissingViewException(array('file' => $name . $this->_ext));
<ide> }
<ide>
<ide> /**
<ide> protected function _getViewFileName($name = null) {
<ide> * @param string $file The path to the template file.
<ide> * @param string $path Base path that $file should be inside of.
<ide> * @return string The file path
<del> * @throws \Cake\Core\Exception\Exception
<add> * @throws \InvalidArgumentException
<ide> */
<ide> protected function _checkFilePath($file, $path) {
<ide> if (strpos($file, '..') === false) {
<ide> return $file;
<ide> }
<ide> $absolute = realpath($file);
<ide> if (strpos($absolute, $path) !== 0) {
<del> $msg = sprintf('Cannot use "%s" as a template, it is not within any view template path.', $file);
<del> throw new Exception($msg);
<add> throw new InvalidArgumentException(sprintf(
<add> 'Cannot use "%s" as a template, it is not within any view template path.',
<add> $file
<add> ));
<ide> }
<ide> return $absolute;
<ide> }
<ide> public function pluginSplit($name, $fallback = true) {
<ide> *
<ide> * @param string $name The name of the layout to find.
<ide> * @return string Filename for layout file (.ctp).
<del> * @throws \Cake\View\Error\MissingLayoutException when a layout cannot be located
<add> * @throws \Cake\View\Exception\MissingLayoutException when a layout cannot be located
<ide> */
<ide> protected function _getLayoutFileName($name = null) {
<ide> if ($name === null) {
<ide> protected function _getLayoutFileName($name = null) {
<ide> }
<ide> }
<ide> }
<del> throw new Error\MissingLayoutException(array(
<add> throw new Exception\MissingLayoutException(array(
<ide> 'file' => $layoutPaths[0] . $name . $this->_ext
<ide> ));
<ide> }
<ide><path>tests/TestCase/Controller/PagesControllerTest.php
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingViewException;
<ide> use TestApp\Controller\PagesController;
<ide>
<ide> /**
<ide> public function testMissingView() {
<ide> /**
<ide> * Test that missing view in debug mode renders missing_view error page
<ide> *
<del> * @expectedException \Cake\View\Error\MissingViewException
<add> * @expectedException \Cake\View\Exception\MissingViewException
<ide> * @expectedExceptionCode 500
<ide> * @return void
<ide> */
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> use Cake\ORM\Error\MissingBehaviorException;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\View\Error\MissingHelperException;
<del>use Cake\View\Error\MissingLayoutException;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingHelperException;
<add>use Cake\View\Exception\MissingLayoutException;
<add>use Cake\View\Exception\MissingViewException;
<ide>
<ide> /**
<ide> * BlueberryComponent class
<ide><path>tests/TestCase/Network/Email/EmailTest.php
<ide> use Cake\Network\Email\Email;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\File;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingViewException;
<ide>
<ide> /**
<ide> * Help to test Email
<ide> public function testSendRenderPlugin() {
<ide> $this->assertContains('Here is your value: 12345', $result['message']);
<ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']);
<ide>
<del> $this->setExpectedException('Cake\View\Error\MissingViewException');
<add> $this->setExpectedException('Cake\View\Exception\MissingViewException');
<ide> $this->CakeEmail->template('test_plugin_tpl', 'plug_default')->send();
<ide> }
<ide>
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function testCellManualRender() {
<ide> /**
<ide> * Tests manual render() invocation with error
<ide> *
<del> * @expectedException \Cake\View\Error\MissingCellViewException
<add> * @expectedException \Cake\View\Exception\MissingCellViewException
<ide> * @return void
<ide> */
<ide> public function testCellManualRenderError() {
<ide> public function testPluginCellAlternateTemplateRenderParam() {
<ide> /**
<ide> * Tests that using an unexisting cell throws an exception.
<ide> *
<del> * @expectedException \Cake\View\Error\MissingCellException
<add> * @expectedException \Cake\View\Exception\MissingCellException
<ide> * @return void
<ide> */
<ide> public function testUnexistingCell() {
<ide><path>tests/TestCase/View/HelperRegistryTest.php
<ide> public function testLazyLoad() {
<ide> /**
<ide> * test lazy loading of helpers
<ide> *
<del> * @expectedException \Cake\View\Error\MissingHelperException
<add> * @expectedException \Cake\View\Exception\MissingHelperException
<ide> * @return void
<ide> */
<ide> public function testLazyLoadException() {
<ide> public function testLoadWithEnabledFalse() {
<ide> /**
<ide> * test missinghelper exception
<ide> *
<del> * @expectedException \Cake\View\Error\MissingHelperException
<add> * @expectedException \Cake\View\Exception\MissingHelperException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingHelper() {
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testGetLayoutFileNameDirectoryTraversal() {
<ide> /**
<ide> * Test for missing views
<ide> *
<del> * @expectedException \Cake\View\Error\MissingViewException
<add> * @expectedException \Cake\View\Exception\MissingViewException
<ide> * @return void
<ide> */
<ide> public function testMissingView() {
<ide> public function testMissingView() {
<ide> /**
<ide> * Test for missing layouts
<ide> *
<del> * @expectedException \Cake\View\Error\MissingLayoutException
<add> * @expectedException \Cake\View\Exception\MissingLayoutException
<ide> * @return void
<ide> */
<ide> public function testMissingLayout() {
<ide> public function testElement() {
<ide> /**
<ide> * Test elementInexistent method
<ide> *
<del> * @expectedException Cake\View\Error\MissingElementException
<add> * @expectedException Cake\View\Exception\MissingElementException
<ide> * @return void
<ide> */
<ide> public function testElementInexistent() {
<ide> public function testElementInexistent() {
<ide> /**
<ide> * Test elementInexistent3 method
<ide> *
<del> * @expectedException Cake\View\Error\MissingElementException
<add> * @expectedException Cake\View\Exception\MissingElementException
<ide> * @return void
<ide> */
<ide> public function testElementInexistent3() {
<ide><path>tests/test_app/TestApp/Controller/PagesController.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Network\Exception\NotFoundException;
<ide> use Cake\Utility\Inflector;
<del>use Cake\View\Error\MissingViewException;
<add>use Cake\View\Exception\MissingViewException;
<ide>
<ide> /**
<ide> * Static content controller
<ide> class PagesController extends AppController {
<ide> * @param mixed What page to display
<ide> * @return void
<ide> * @throws Cake\Network\Exception\NotFoundException When the view file could not be found
<del> * or Cake\View\Error\MissingViewException in debug mode.
<add> * or Cake\View\Exception\MissingViewException in debug mode.
<ide> */
<ide> public function display() {
<ide> $path = func_get_args(); | 18 |
Go | Go | use pivot_root instead of chroot" | 82f797f14096430c3edbace1cd30e04a483ec41f | <ide><path>pkg/libcontainer/nsinit/mount.go
<ide> package nsinit
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/pkg/system"
<del> "io/ioutil"
<ide> "os"
<ide> "path/filepath"
<ide> "syscall"
<ide> func setupNewMountNamespace(rootfs, console string, readonly bool) error {
<ide> if err := system.Chdir(rootfs); err != nil {
<ide> return fmt.Errorf("chdir into %s %s", rootfs, err)
<ide> }
<del>
<del> pivotDir, err := ioutil.TempDir(rootfs, ".pivot_root")
<del> if err != nil {
<del> return fmt.Errorf("can't create pivot_root dir %s", pivotDir, err)
<add> if err := system.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil {
<add> return fmt.Errorf("mount move %s into / %s", rootfs, err)
<ide> }
<del> if err := system.Pivotroot(rootfs, pivotDir); err != nil {
<del> return fmt.Errorf("pivot_root %s", err)
<add> if err := system.Chroot("."); err != nil {
<add> return fmt.Errorf("chroot . %s", err)
<ide> }
<ide> if err := system.Chdir("/"); err != nil {
<ide> return fmt.Errorf("chdir / %s", err)
<ide> }
<ide>
<del> // path to pivot dir now changed, update
<del> pivotDir = filepath.Join("/", filepath.Base(pivotDir))
<del>
<del> if err := system.Unmount(pivotDir, syscall.MNT_DETACH); err != nil {
<del> return fmt.Errorf("unmount pivot_root dir %s", err)
<del> }
<del>
<del> if err := os.Remove(pivotDir); err != nil {
<del> return fmt.Errorf("remove pivot_root dir %s", err)
<del> }
<del>
<ide> system.Umask(0022)
<ide>
<ide> return nil | 1 |
PHP | PHP | move abstract method to top | 29bb5c44d19038c80f90cd573fc519277767e344 | <ide><path>src/Illuminate/Foundation/Publishing/Publisher.php
<ide> public function __construct(Filesystem $files, $publishPath)
<ide> $this->publishPath = $publishPath;
<ide> }
<ide>
<add> /**
<add> * Get the source directory to publish.
<add> *
<add> * @param string $package
<add> * @param string $packagePath
<add> * @return string
<add> *
<add> * @throws \InvalidArgumentException
<add> */
<add> abstract protected function getSource($package, $packagePath);
<add>
<ide> /**
<ide> * Publish files from a given path.
<ide> *
<ide> public function setPackagePath($packagePath)
<ide> $this->packagePath = $packagePath;
<ide> }
<ide>
<del> /**
<del> * Get the source directory to publish.
<del> *
<del> * @param string $package
<del> * @param string $packagePath
<del> * @return string
<del> *
<del> * @throws \InvalidArgumentException
<del> */
<del> abstract protected function getSource($package, $packagePath);
<del>
<ide> } | 1 |
Text | Text | fix syntax typo in changelog | 34489b2c50308052a2d180b4207a7b081c5e6173 | <ide><path>railties/CHANGELOG.md
<ide> view templates too. This change will enable view template caching by
<ide> adding this to the generated `environments/test.rb`:
<ide>
<del> ````ruby
<add> ```ruby
<ide> config.action_view.cache_template_loading = true
<del> ````
<add> ```
<ide>
<ide> *Jorge Manrubia*
<ide> | 1 |
PHP | PHP | remove unset() and clean up tests | 6ea4e739a8e933d2e641888557e158a652e545c0 | <ide><path>src/Database/Connection.php
<ide> public function __construct($config)
<ide> public function __destruct()
<ide> {
<ide> if ($this->_transactionStarted && class_exists('Cake\Log\Log')) {
<del> Log::warning('The connection is going to be closed but the transaction is still active.');
<add> Log::warning('The connection is going to be closed but there is an active transaction.');
<ide> }
<del> unset($this->_driver);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testSimpleTransactions()
<ide> *
<ide> * @return void
<ide> */
<del> public function testCloseConnectionWithUncommittedTransaction()
<add> public function testDestructorWithUncommittedTransaction()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<del> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<del> ->setMethods(['connect'])
<del> ->setConstructorArgs([['driver' => $driver]])
<del> ->getMock();
<add> $connection = new Connection(['driver' => $driver]);
<add> $connection->begin();
<add> $this->assertTrue($connection->inTransaction());
<ide>
<del> // The returned value of getMock() is referenced by TestCase,
<del> // so it's impossible(or difficult) to call __destruct() of it during the test.
<del> // Instead, use cloned object.
<del> $clonedConnection = clone $connection;
<del> $clonedConnection->begin();
<del> $this->assertTrue($clonedConnection->inTransaction());
<del>
<del> Log::setConfig('debug', [
<del> 'engine' => 'File',
<del> 'path' => LOGS,
<del> 'levels' => ['notice', 'info', 'debug'],
<del> 'file' => 'debug',
<del> ]);
<del> Log::setConfig('error', [
<del> 'engine' => 'File',
<del> 'path' => LOGS,
<del> 'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
<del> 'file' => 'error',
<del> ]);
<del> $errorLogFile = LOGS . 'error.log';
<del> if (file_exists($errorLogFile)) {
<del> unlink($errorLogFile);
<del> }
<add> $logger = $this->createMock('Psr\Log\AbstractLogger');
<add> $logger->expects($this->once())
<add> ->method('log')
<add> ->with('warning', $this->stringContains('The connection is going to be closed'));
<add>
<add> Log::setConfig('error', $logger);
<ide>
<del> // a warning log will be generated by __destruct of Connection.
<del> unset($clonedConnection);
<del> $this->assertFileExists($errorLogFile);
<del> $logContent = file_get_contents($errorLogFile);
<del> $this->assertStringMatchesFormat('%AWarning: The connection is going to be closed but the transaction is still active.%A', $logContent);
<add> // Destroy the connection
<add> unset($connection);
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | fix the link for sharing images via repositories | c76f8ff1d4f0bbc273eca7cba4447b06e2da9c0c | <ide><path>docs/reference/commandline/tag.md
<ide> periods and dashes. A tag name may not start with a period or a dash and may
<ide> contain a maximum of 128 characters.
<ide>
<ide> You can group your images together using names and tags, and then upload them
<del>to [*Share Images via Repositories*](../../tutorials/dockerrepos.md#contributing-to-docker-hub).
<add>to [*Share Images via Repositories*](https://docs.docker.com/docker-hub/repos/).
<ide>
<ide> # Examples
<ide> | 1 |
PHP | PHP | use str class instead of string helper functions | 15251e41212ee47cf2f4be13dd36d07c1a892925 | <ide><path>src/Illuminate/Auth/DatabaseUserProvider.php
<ide>
<ide> namespace Illuminate\Auth;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Auth\UserProvider;
<ide> use Illuminate\Database\ConnectionInterface;
<ide> use Illuminate\Contracts\Hashing\Hasher as HasherContract;
<ide> public function retrieveByCredentials(array $credentials)
<ide> $query = $this->conn->table($this->table);
<ide>
<ide> foreach ($credentials as $key => $value) {
<del> if (!str_contains($key, 'password')) {
<add> if (!Str::contains($key, 'password')) {
<ide> $query->where($key, $value);
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/EloquentUserProvider.php
<ide>
<ide> namespace Illuminate\Auth;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Auth\UserProvider;
<ide> use Illuminate\Contracts\Hashing\Hasher as HasherContract;
<ide> use Illuminate\Contracts\Auth\Authenticatable as UserContract;
<ide> public function retrieveByCredentials(array $credentials)
<ide> $query = $this->createModel()->newQuery();
<ide>
<ide> foreach ($credentials as $key => $value) {
<del> if (!str_contains($key, 'password')) {
<add> if (!Str::contains($key, 'password')) {
<ide> $query->where($key, $value);
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/Guard.php
<ide> namespace Illuminate\Auth;
<ide>
<ide> use RuntimeException;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Auth\UserProvider;
<ide> use Symfony\Component\HttpFoundation\Request;
<ide> protected function getRecallerId()
<ide> */
<ide> protected function validRecaller($recaller)
<ide> {
<del> if (!is_string($recaller) || !str_contains($recaller, '|')) {
<add> if (!is_string($recaller) || !Str::contains($recaller, '|')) {
<ide> return false;
<ide> }
<ide>
<ide> protected function clearUserDataFromStorage()
<ide> */
<ide> protected function refreshRememberToken(UserContract $user)
<ide> {
<del> $user->setRememberToken($token = str_random(60));
<add> $user->setRememberToken($token = Str::random(60));
<ide>
<ide> $this->provider->updateRememberToken($user, $token);
<ide> }
<ide><path>src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php
<ide> namespace Illuminate\Auth\Passwords;
<ide>
<ide> use Carbon\Carbon;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Database\ConnectionInterface;
<ide> use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
<ide>
<ide> public function deleteExpired()
<ide> */
<ide> public function createNewToken()
<ide> {
<del> return hash_hmac('sha256', str_random(40), $this->hashKey);
<add> return hash_hmac('sha256', Str::random(40), $this->hashKey);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Console/GeneratorCommand.php
<ide>
<ide> namespace Illuminate\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Symfony\Component\Console\Input\InputArgument;
<ide>
<ide> protected function parseName($name)
<ide> {
<ide> $rootNamespace = $this->laravel->getNamespace();
<ide>
<del> if (starts_with($name, $rootNamespace)) {
<add> if (Str::startsWith($name, $rootNamespace)) {
<ide> return $name;
<ide> }
<ide>
<del> if (str_contains($name, '/')) {
<add> if (Str::contains($name, '/')) {
<ide> $name = str_replace('/', '\\', $name);
<ide> }
<ide>
<ide><path>src/Illuminate/Console/Parser.php
<ide>
<ide> namespace Illuminate\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide> use Symfony\Component\Console\Input\InputArgument;
<ide> public static function parse($expression)
<ide> protected static function arguments(array $tokens)
<ide> {
<ide> return array_values(array_filter(array_map(function ($token) {
<del> if (starts_with($token, '{') && !starts_with($token, '{--')) {
<add> if (Str::startsWith($token, '{') && !Str::startsWith($token, '{--')) {
<ide> return static::parseArgument(trim($token, '{}'));
<ide> }
<ide> }, $tokens)));
<ide> protected static function arguments(array $tokens)
<ide> protected static function options(array $tokens)
<ide> {
<ide> return array_values(array_filter(array_map(function ($token) {
<del> if (starts_with($token, '{--')) {
<add> if (Str::startsWith($token, '{--')) {
<ide> return static::parseOption(ltrim(trim($token, '{}'), '-'));
<ide> }
<ide> }, $tokens)));
<ide> protected static function parseArgument($token)
<ide> {
<ide> $description = null;
<ide>
<del> if (str_contains($token, ' : ')) {
<add> if (Str::contains($token, ' : ')) {
<ide> list($token, $description) = explode(' : ', $token, 2);
<ide>
<ide> $token = trim($token);
<ide> protected static function parseOption($token)
<ide> {
<ide> $description = null;
<ide>
<del> if (str_contains($token, ' : ')) {
<add> if (Str::contains($token, ' : ')) {
<ide> list($token, $description) = explode(' : ', $token);
<ide>
<ide> $token = trim($token);
<ide><path>src/Illuminate/Database/Connection.php
<ide> use LogicException;
<ide> use RuntimeException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Database\Query\Processors\Processor;
<ide> protected function causedByLostConnection(QueryException $e)
<ide> {
<ide> $message = $e->getPrevious()->getMessage();
<ide>
<del> return str_contains($message, [
<add> return Str::contains($message, [
<ide> 'server has gone away',
<ide> 'no connection to the server',
<ide> 'Lost connection',
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide>
<ide> use Closure;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Pagination\Paginator;
<ide> use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Pagination\LengthAwarePaginator;
<ide> protected function nestedRelations($relation)
<ide> */
<ide> protected function isNested($name, $relation)
<ide> {
<del> $dots = str_contains($name, '.');
<add> $dots = Str::contains($name, '.');
<ide>
<del> return $dots && starts_with($name, $relation.'.');
<add> return $dots && Str::startsWith($name, $relation.'.');
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> use LogicException;
<ide> use JsonSerializable;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
<ide> // foreign key name by using the name of the relationship function, which
<ide> // when combined with an "_id" should conventionally match the columns.
<ide> if (is_null($foreignKey)) {
<del> $foreignKey = snake_case($relation).'_id';
<add> $foreignKey = Str::snake($relation).'_id';
<ide> }
<ide>
<ide> $instance = new $related;
<ide> public function morphTo($name = null, $type = null, $id = null)
<ide> if (is_null($name)) {
<ide> list(, $caller) = debug_backtrace(false, 2);
<ide>
<del> $name = snake_case($caller['function']);
<add> $name = Str::snake($caller['function']);
<ide> }
<ide>
<ide> list($type, $id) = $this->getMorphs($name, $type, $id);
<ide> public function morphToMany($related, $name, $table = null, $foreignKey = null,
<ide> // appropriate query constraints then entirely manages the hydrations.
<ide> $query = $instance->newQuery();
<ide>
<del> $table = $table ?: str_plural($name);
<add> $table = $table ?: Str::plural($name);
<ide>
<ide> return new MorphToMany(
<ide> $query, $this, $name, $table, $foreignKey,
<ide> public function joiningTable($related)
<ide> // The joining table name, by convention, is simply the snake cased models
<ide> // sorted alphabetically and concatenated with an underscore, so we can
<ide> // just sort the models and join them together to get the table name.
<del> $base = snake_case(class_basename($this));
<add> $base = Str::snake(class_basename($this));
<ide>
<del> $related = snake_case(class_basename($related));
<add> $related = Str::snake(class_basename($related));
<ide>
<ide> $models = [$related, $base];
<ide>
<ide> public function getTable()
<ide> return $this->table;
<ide> }
<ide>
<del> return str_replace('\\', '', snake_case(str_plural(class_basename($this))));
<add> return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
<ide> }
<ide>
<ide> /**
<ide> public function setPerPage($perPage)
<ide> */
<ide> public function getForeignKey()
<ide> {
<del> return snake_case(class_basename($this)).'_id';
<add> return Str::snake(class_basename($this)).'_id';
<ide> }
<ide>
<ide> /**
<ide> public function isFillable($key)
<ide> return false;
<ide> }
<ide>
<del> return empty($this->fillable) && !starts_with($key, '_');
<add> return empty($this->fillable) && !Str::startsWith($key, '_');
<ide> }
<ide>
<ide> /**
<ide> public function totallyGuarded()
<ide> */
<ide> protected function removeTableFromKey($key)
<ide> {
<del> if (!str_contains($key, '.')) {
<add> if (!Str::contains($key, '.')) {
<ide> return $key;
<ide> }
<ide>
<ide> public function relationsToArray()
<ide> // key so that the relation attribute is snake cased in this returned
<ide> // array to the developers, making this consistent with attributes.
<ide> if (static::$snakeAttributes) {
<del> $key = snake_case($key);
<add> $key = Str::snake($key);
<ide> }
<ide>
<ide> // If the relation value has been set, we will set it on this attributes
<ide> protected function getRelationshipFromMethod($method)
<ide> */
<ide> public function hasGetMutator($key)
<ide> {
<del> return method_exists($this, 'get'.studly_case($key).'Attribute');
<add> return method_exists($this, 'get'.Str::studly($key).'Attribute');
<ide> }
<ide>
<ide> /**
<ide> public function hasGetMutator($key)
<ide> */
<ide> protected function mutateAttribute($key, $value)
<ide> {
<del> return $this->{'get'.studly_case($key).'Attribute'}($value);
<add> return $this->{'get'.Str::studly($key).'Attribute'}($value);
<ide> }
<ide>
<ide> /**
<ide> public function setAttribute($key, $value)
<ide> // which simply lets the developers tweak the attribute as it is set on
<ide> // the model, such as "json_encoding" an listing of data for storage.
<ide> if ($this->hasSetMutator($key)) {
<del> $method = 'set'.studly_case($key).'Attribute';
<add> $method = 'set'.Str::studly($key).'Attribute';
<ide>
<ide> return $this->{$method}($value);
<ide> }
<ide> public function setAttribute($key, $value)
<ide> */
<ide> public function hasSetMutator($key)
<ide> {
<del> return method_exists($this, 'set'.studly_case($key).'Attribute');
<add> return method_exists($this, 'set'.Str::studly($key).'Attribute');
<ide> }
<ide>
<ide> /**
<ide> public static function cacheMutatedAttributes($class)
<ide> if (strpos($method, 'Attribute') !== false &&
<ide> preg_match('/^get(.+)Attribute$/', $method, $matches)) {
<ide> if (static::$snakeAttributes) {
<del> $matches[1] = snake_case($matches[1]);
<add> $matches[1] = Str::snake($matches[1]);
<ide> }
<ide>
<ide> $mutatedAttributes[] = lcfirst($matches[1]);
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> namespace Illuminate\Database\Eloquent\Relations;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Eloquent\Builder;
<ide> use Illuminate\Database\Query\Expression;
<ide> protected function touchingParent()
<ide> */
<ide> protected function guessInverseRelation()
<ide> {
<del> return camel_case(str_plural(class_basename($this->getParent())));
<add> return Str::camel(Str::plural(class_basename($this->getParent())));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Migrations/MigrationCreator.php
<ide> namespace Illuminate\Database\Migrations;
<ide>
<ide> use Closure;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Filesystem\Filesystem;
<ide>
<ide> class MigrationCreator
<ide> protected function populateStub($name, $stub, $table)
<ide> */
<ide> protected function getClassName($name)
<ide> {
<del> return studly_case($name);
<add> return Str::studly($name);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Migrations/Migrator.php
<ide>
<ide> namespace Illuminate\Database\Migrations;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Database\ConnectionResolverInterface as Resolver;
<ide>
<ide> public function resolve($file)
<ide> {
<ide> $file = implode('_', array_slice(explode('_', $file), 4));
<ide>
<del> $class = studly_case($file);
<add> $class = Str::studly($file);
<ide>
<ide> return new $class;
<ide> }
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> use Closure;
<ide> use BadMethodCallException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Support\Collection;
<ide> use Illuminate\Pagination\Paginator;
<ide> protected function addDynamic($segment, $connector, $parameters, $index)
<ide> // clause on the query. Then we'll increment the parameter index values.
<ide> $bool = strtolower($connector);
<ide>
<del> $this->where(snake_case($segment), '=', $parameters[$index], $bool);
<add> $this->where(Str::snake($segment), '=', $parameters[$index], $bool);
<ide> }
<ide>
<ide> /**
<ide> public function useWritePdo()
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> if (starts_with($method, 'where')) {
<add> if (Str::startsWith($method, 'where')) {
<ide> return $this->dynamicWhere($method, $parameters);
<ide> }
<ide>
<ide><path>src/Illuminate/Events/Dispatcher.php
<ide>
<ide> use Exception;
<ide> use ReflectionClass;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
<ide> use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
<ide> public function __construct(ContainerContract $container = null)
<ide> public function listen($events, $listener, $priority = 0)
<ide> {
<ide> foreach ((array) $events as $event) {
<del> if (str_contains($event, '*')) {
<add> if (Str::contains($event, '*')) {
<ide> $this->setupWildcardListen($event, $listener);
<ide> } else {
<ide> $this->listeners[$event][$priority][] = $this->makeListener($listener);
<ide> protected function getWildcardListeners($eventName)
<ide> $wildcards = [];
<ide>
<ide> foreach ($this->wildcards as $key => $listeners) {
<del> if (str_is($key, $eventName)) {
<add> if (Str::is($key, $eventName)) {
<ide> $wildcards = array_merge($wildcards, $listeners);
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Application.php
<ide> use Closure;
<ide> use RuntimeException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> public function environment()
<ide> $patterns = is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args();
<ide>
<ide> foreach ($patterns as $pattern) {
<del> if (str_is($pattern, $this['env'])) {
<add> if (Str::is($pattern, $this['env'])) {
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Console/EventGenerateCommand.php
<ide>
<ide> namespace Illuminate\Foundation\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Console\Command;
<ide>
<ide> class EventGenerateCommand extends Command
<ide> public function fire()
<ide> );
<ide>
<ide> foreach ($provider->listens() as $event => $listeners) {
<del> if (!str_contains($event, '\\')) {
<add> if (!Str::contains($event, '\\')) {
<ide> continue;
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/Console/HandlerEventCommand.php
<ide>
<ide> namespace Illuminate\Foundation\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Console\GeneratorCommand;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> protected function buildClass($name)
<ide>
<ide> $event = $this->option('event');
<ide>
<del> if (!starts_with($event, $this->laravel->getNamespace())) {
<add> if (!Str::startsWith($event, $this->laravel->getNamespace())) {
<ide> $event = $this->laravel->getNamespace().'Events\\'.$event;
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php
<ide>
<ide> namespace Illuminate\Foundation\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Console\Command;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> public function fire()
<ide> protected function getRandomKey($cipher)
<ide> {
<ide> if ($cipher === 'AES-128-CBC') {
<del> return str_random(16);
<add> return Str::random(16);
<ide> }
<ide>
<del> return str_random(32);
<add> return Str::random(32);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Console/ListenerMakeCommand.php
<ide>
<ide> namespace Illuminate\Foundation\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Console\GeneratorCommand;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> protected function buildClass($name)
<ide>
<ide> $event = $this->option('event');
<ide>
<del> if (!starts_with($event, $this->laravel->getNamespace())) {
<add> if (!Str::startsWith($event, $this->laravel->getNamespace())) {
<ide> $event = $this->laravel->getNamespace().'Events\\'.$event;
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php
<ide>
<ide> namespace Illuminate\Foundation\Console;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Console\GeneratorCommand;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> public function fire()
<ide> {
<ide> if (parent::fire() !== false) {
<ide> if ($this->option('migration')) {
<del> $table = str_plural(snake_case(class_basename($this->argument('name'))));
<add> $table = Str::plural(Str::snake(class_basename($this->argument('name'))));
<ide>
<ide> $this->call('make:migration', ['name' => "create_{$table}_table", '--create' => $table]);
<ide> }
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php
<ide> namespace Illuminate\Foundation\Console;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Routing\Route;
<ide> use Illuminate\Routing\Router;
<ide> protected function getMethodPatterns($uri, $method)
<ide> */
<ide> protected function filterRoute(array $route)
<ide> {
<del> if (($this->option('name') && !str_contains($route['name'], $this->option('name'))) ||
<del> $this->option('path') && !str_contains($route['uri'], $this->option('path'))) {
<add> if (($this->option('name') && !Str::contains($route['name'], $this->option('name'))) ||
<add> $this->option('path') && !Str::contains($route['uri'], $this->option('path'))) {
<ide> return;
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/EnvironmentDetector.php
<ide>
<ide> use Closure;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide>
<ide> class EnvironmentDetector
<ide> {
<ide> protected function detectConsoleEnvironment(Closure $callback, array $args)
<ide> protected function getEnvironmentArgument(array $args)
<ide> {
<ide> return Arr::first($args, function ($k, $v) {
<del> return starts_with($v, '--env');
<add> return Str::startsWith($v, '--env');
<ide> });
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php
<ide>
<ide> namespace Illuminate\Foundation\Testing;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use InvalidArgumentException;
<ide> use Symfony\Component\DomCrawler\Form;
<ide> protected function seeJsonContains(array $data)
<ide> $expected = $this->formatToExpectedJson($key, $value);
<ide>
<ide> $this->assertTrue(
<del> str_contains($actual, $this->formatToExpectedJson($key, $value)),
<add> Str::contains($actual, $this->formatToExpectedJson($key, $value)),
<ide> "Unable to find JSON fragment [{$expected}] within [{$actual}]."
<ide> );
<ide> }
<ide> protected function formatToExpectedJson($key, $value)
<ide> {
<ide> $expected = json_encode([$key => $value]);
<ide>
<del> if (starts_with($expected, '{')) {
<add> if (Str::startsWith($expected, '{')) {
<ide> $expected = substr($expected, 1);
<ide> }
<ide>
<ide> public function route($method, $name, $routeParameters = [], $parameters = [], $
<ide> */
<ide> protected function prepareUrlForRequest($uri)
<ide> {
<del> if (starts_with($uri, '/')) {
<add> if (Str::startsWith($uri, '/')) {
<ide> $uri = substr($uri, 1);
<ide> }
<ide>
<del> if (!starts_with($uri, 'http')) {
<add> if (!Str::startsWith($uri, 'http')) {
<ide> $uri = $this->baseUrl.'/'.$uri;
<ide> }
<ide>
<ide><path>src/Illuminate/Http/RedirectResponse.php
<ide> namespace Illuminate\Http;
<ide>
<ide> use BadMethodCallException;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Support\MessageBag;
<ide> use Illuminate\Support\ViewErrorBag;
<ide> use Illuminate\Session\Store as SessionStore;
<ide> public function setSession(SessionStore $session)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> if (starts_with($method, 'with')) {
<del> return $this->with(snake_case(substr($method, 4)), $parameters[0]);
<add> if (Str::startsWith($method, 'with')) {
<add> return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
<ide> }
<ide>
<ide> throw new BadMethodCallException("Method [$method] does not exist on Redirect.");
<ide><path>src/Illuminate/Http/Request.php
<ide> use SplFileInfo;
<ide> use RuntimeException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Symfony\Component\HttpFoundation\ParameterBag;
<ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
<ide>
<ide> public function segments()
<ide> public function is()
<ide> {
<ide> foreach (func_get_args() as $pattern) {
<del> if (str_is($pattern, urldecode($this->path()))) {
<add> if (Str::is($pattern, urldecode($this->path()))) {
<ide> return true;
<ide> }
<ide> }
<ide> protected function getInputSource()
<ide> */
<ide> public function isJson()
<ide> {
<del> return str_contains($this->header('CONTENT_TYPE'), '/json');
<add> return Str::contains($this->header('CONTENT_TYPE'), '/json');
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Mail/Mailer.php
<ide> use Swift_Mailer;
<ide> use Swift_Message;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use SuperClosure\Serializer;
<ide> use Psr\Log\LoggerInterface;
<ide> use InvalidArgumentException;
<ide> public function handleQueuedMessage($job, $data)
<ide> */
<ide> protected function getQueuedCallable(array $data)
<ide> {
<del> if (str_contains($data['callback'], 'SerializableClosure')) {
<add> if (Str::contains($data['callback'], 'SerializableClosure')) {
<ide> return unserialize($data['callback'])->getClosure();
<ide> }
<ide>
<ide><path>src/Illuminate/Queue/Console/SubscribeCommand.php
<ide>
<ide> use Exception;
<ide> use RuntimeException;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Queue\IronQueue;
<ide> use Illuminate\Console\Command;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide> protected function getSubscriberList()
<ide>
<ide> $url = $this->argument('url');
<ide>
<del> if (!starts_with($url, ['http://', 'https://'])) {
<add> if (!Str::startsWith($url, ['http://', 'https://'])) {
<ide> $url = $this->laravel['url']->to($url);
<ide> }
<ide>
<ide><path>src/Illuminate/Queue/Jobs/Job.php
<ide> namespace Illuminate\Queue\Jobs;
<ide>
<ide> use DateTime;
<add>use Illuminate\Support\Str;
<ide>
<ide> abstract class Job
<ide> {
<ide> protected function resolveQueueableEntities($data)
<ide> */
<ide> protected function resolveQueueableEntity($value)
<ide> {
<del> if (is_string($value) && starts_with($value, '::entity::')) {
<add> if (is_string($value) && Str::startsWith($value, '::entity::')) {
<ide> list($marker, $type, $id) = explode('|', $value, 3);
<ide>
<ide> return $this->getEntityResolver()->resolve($type, $id);
<ide><path>src/Illuminate/Queue/RedisQueue.php
<ide> namespace Illuminate\Queue;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Redis\Database;
<ide> use Illuminate\Queue\Jobs\RedisJob;
<ide> use Illuminate\Contracts\Queue\Queue as QueueContract;
<ide> protected function createPayload($job, $data = '', $queue = null)
<ide> */
<ide> protected function getRandomId()
<ide> {
<del> return str_random(32);
<add> return Str::random(32);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/Controller.php
<ide>
<ide> use Closure;
<ide> use BadMethodCallException;
<add>use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
<ide>
<ide> protected function registerInstanceFilter($filter)
<ide> */
<ide> protected function isInstanceFilter($filter)
<ide> {
<del> if (is_string($filter) && starts_with($filter, '@')) {
<add> if (is_string($filter) && Str::startsWith($filter, '@')) {
<ide> if (method_exists($this, substr($filter, 1))) {
<ide> return true;
<ide> }
<ide><path>src/Illuminate/Routing/ControllerInspector.php
<ide>
<ide> use ReflectionClass;
<ide> use ReflectionMethod;
<add>use Illuminate\Support\Str;
<ide>
<ide> class ControllerInspector
<ide> {
<ide> public function isRoutable(ReflectionMethod $method)
<ide> return false;
<ide> }
<ide>
<del> return starts_with($method->name, $this->verbs);
<add> return Str::startsWith($method->name, $this->verbs);
<ide> }
<ide>
<ide> /**
<ide> protected function getIndexData($data, $prefix)
<ide> */
<ide> public function getVerb($name)
<ide> {
<del> return head(explode('_', snake_case($name)));
<add> return head(explode('_', Str::snake($name)));
<ide> }
<ide>
<ide> /**
<ide> public function getVerb($name)
<ide> */
<ide> public function getPlainUri($name, $prefix)
<ide> {
<del> return $prefix.'/'.implode('-', array_slice(explode('_', snake_case($name)), 1));
<add> return $prefix.'/'.implode('-', array_slice(explode('_', Str::snake($name)), 1));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/ResourceRegistrar.php
<ide>
<ide> namespace Illuminate\Routing;
<ide>
<add>use Illuminate\Support\Str;
<add>
<ide> class ResourceRegistrar
<ide> {
<ide> /**
<ide> public function register($name, $controller, array $options = [])
<ide> // If the resource name contains a slash, we will assume the developer wishes to
<ide> // register these resource routes with a prefix so we will set that up out of
<ide> // the box so they don't have to mess with it. Otherwise, we will continue.
<del> if (str_contains($name, '/')) {
<add> if (Str::contains($name, '/')) {
<ide> $this->prefixedResource($name, $controller, $options);
<ide>
<ide> return;
<ide> protected function getResourceMethods($defaults, $options)
<ide> */
<ide> public function getResourceUri($resource)
<ide> {
<del> if (!str_contains($resource, '.')) {
<add> if (!Str::contains($resource, '.')) {
<ide> return $resource;
<ide> }
<ide>
<ide><path>src/Illuminate/Routing/Route.php
<ide> use LogicException;
<ide> use ReflectionFunction;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use UnexpectedValueException;
<ide> use Illuminate\Container\Container;
<ide> protected static function explodeArrayFilters(array $filters)
<ide> */
<ide> public static function parseFilter($filter)
<ide> {
<del> if (!str_contains($filter, ':')) {
<add> if (!Str::contains($filter, ':')) {
<ide> return [$filter, []];
<ide> }
<ide>
<ide> protected function parseAction($action)
<ide> $action['uses'] = $this->findCallable($action);
<ide> }
<ide>
<del> if (is_string($action['uses']) && ! str_contains($action['uses'], '@')) {
<add> if (is_string($action['uses']) && ! Str::contains($action['uses'], '@')) {
<ide> throw new UnexpectedValueException(sprintf(
<ide> 'Invalid route action: [%s]', $action['uses']
<ide> ));
<ide><path>src/Illuminate/Routing/Router.php
<ide>
<ide> use Closure;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Http\Response;
<ide> use Illuminate\Pipeline\Pipeline;
<ide> public function filter($name, $callback)
<ide> */
<ide> protected function parseFilter($callback)
<ide> {
<del> if (is_string($callback) && !str_contains($callback, '@')) {
<add> if (is_string($callback) && !Str::contains($callback, '@')) {
<ide> return $callback.'@filter';
<ide> }
<ide>
<ide> public function findPatternFilters($request)
<ide> // To find the patterned middlewares for a request, we just need to check these
<ide> // registered patterns against the path info for the current request to this
<ide> // applications, and when it matches we will merge into these middlewares.
<del> if (str_is($pattern, $path)) {
<add> if (Str::is($pattern, $path)) {
<ide> $merge = $this->patternsByMethod($method, $filters);
<ide>
<ide> $results = array_merge($results, $merge);
<ide> public function currentRouteName()
<ide> public function is()
<ide> {
<ide> foreach (func_get_args() as $pattern) {
<del> if (str_is($pattern, $this->currentRouteName())) {
<add> if (Str::is($pattern, $this->currentRouteName())) {
<ide> return true;
<ide> }
<ide> }
<ide> public function currentRouteAction()
<ide> public function uses()
<ide> {
<ide> foreach (func_get_args() as $pattern) {
<del> if (str_is($pattern, $this->currentRouteAction())) {
<add> if (Str::is($pattern, $this->currentRouteAction())) {
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> namespace Illuminate\Routing;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Contracts\Routing\UrlRoutable;
<ide> protected function removeIndex($root)
<ide> {
<ide> $i = 'index.php';
<ide>
<del> return str_contains($root, $i) ? str_replace('/'.$i, '', $root) : $root;
<add> return Str::contains($root, $i) ? str_replace('/'.$i, '', $root) : $root;
<ide> }
<ide>
<ide> /**
<ide> protected function getRootUrl($scheme, $root = null)
<ide> $root = $this->cachedRoot;
<ide> }
<ide>
<del> $start = starts_with($root, 'http://') ? 'http://' : 'https://';
<add> $start = Str::startsWith($root, 'http://') ? 'http://' : 'https://';
<ide>
<ide> return preg_replace('~'.$start.'~', $scheme, $root, 1);
<ide> }
<ide> public function forceRootUrl($root)
<ide> */
<ide> public function isValidUrl($path)
<ide> {
<del> if (starts_with($path, ['#', '//', 'mailto:', 'tel:', 'http://', 'https://'])) {
<add> if (Str::startsWith($path, ['#', '//', 'mailto:', 'tel:', 'http://', 'https://'])) {
<ide> return true;
<ide> }
<ide>
<ide><path>src/Illuminate/Session/Store.php
<ide> namespace Illuminate\Session;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use SessionHandlerInterface;
<ide> use InvalidArgumentException;
<ide> use Symfony\Component\HttpFoundation\Request;
<ide> public function isValidId($id)
<ide> */
<ide> protected function generateSessionId()
<ide> {
<del> return sha1(uniqid('', true).str_random(25).microtime(true));
<add> return sha1(uniqid('', true).Str::random(25).microtime(true));
<ide> }
<ide>
<ide> /**
<ide> public function getToken()
<ide> */
<ide> public function regenerateToken()
<ide> {
<del> $this->put('_token', str_random(40));
<add> $this->put('_token', Str::random(40));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Validation/Factory.php
<ide> namespace Illuminate\Validation;
<ide>
<ide> use Closure;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Container\Container;
<ide> use Symfony\Component\Translation\TranslatorInterface;
<ide> use Illuminate\Contracts\Validation\Factory as FactoryContract;
<ide> public function extend($rule, $extension, $message = null)
<ide> $this->extensions[$rule] = $extension;
<ide>
<ide> if ($message) {
<del> $this->fallbackMessages[snake_case($rule)] = $message;
<add> $this->fallbackMessages[Str::snake($rule)] = $message;
<ide> }
<ide> }
<ide>
<ide> public function extendImplicit($rule, $extension, $message = null)
<ide> $this->implicitExtensions[$rule] = $extension;
<ide>
<ide> if ($message) {
<del> $this->fallbackMessages[snake_case($rule)] = $message;
<add> $this->fallbackMessages[Str::snake($rule)] = $message;
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Validation/Validator.php
<ide> use DateTimeZone;
<ide> use RuntimeException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use BadMethodCallException;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Support\Fluent;
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> */
<ide> protected function parseUniqueTable($table)
<ide> {
<del> return str_contains($table, '.') ? explode('.', $table, 2) : [null, $table];
<add> return Str::contains($table, '.') ? explode('.', $table, 2) : [null, $table];
<ide> }
<ide>
<ide> /**
<ide> protected function getDateFormat($attribute)
<ide> */
<ide> protected function getMessage($attribute, $rule)
<ide> {
<del> $lowerRule = snake_case($rule);
<add> $lowerRule = Str::snake($rule);
<ide>
<ide> $inlineMessage = $this->getInlineMessage($attribute, $lowerRule);
<ide>
<ide> protected function getInlineMessage($attribute, $lowerRule, $source = null)
<ide> */
<ide> protected function getSizeMessage($attribute, $rule)
<ide> {
<del> $lowerRule = snake_case($rule);
<add> $lowerRule = Str::snake($rule);
<ide>
<ide> // There are three different types of size validations. The attribute may be
<ide> // either a number, file, or string so we will check a few things to know
<ide> protected function doReplacements($message, $attribute, $rule, $parameters)
<ide> {
<ide> $message = str_replace(':attribute', $this->getAttribute($attribute), $message);
<ide>
<del> if (isset($this->replacers[snake_case($rule)])) {
<del> $message = $this->callReplacer($message, $attribute, snake_case($rule), $parameters);
<add> if (isset($this->replacers[Str::snake($rule)])) {
<add> $message = $this->callReplacer($message, $attribute, Str::snake($rule), $parameters);
<ide> } elseif (method_exists($this, $replacer = "replace{$rule}")) {
<ide> $message = $this->$replacer($message, $attribute, $rule, $parameters);
<ide> }
<ide> protected function getAttribute($attribute)
<ide> // If no language line has been specified for the attribute all of the
<ide> // underscores are removed from the attribute name and that will be
<ide> // used as default versions of the attribute's displayable names.
<del> return str_replace('_', ' ', snake_case($attribute));
<add> return str_replace('_', ' ', Str::snake($attribute));
<ide> }
<ide>
<ide> /**
<ide> protected function parseRule($rules)
<ide> */
<ide> protected function parseArrayRule(array $rules)
<ide> {
<del> return [studly_case(trim(Arr::get($rules, 0))), array_slice($rules, 1)];
<add> return [Str::studly(trim(Arr::get($rules, 0))), array_slice($rules, 1)];
<ide> }
<ide>
<ide> /**
<ide> protected function parseStringRule($rules)
<ide> $parameters = $this->parseParameters($rules, $parameter);
<ide> }
<ide>
<del> return [studly_case(trim($rules)), $parameters];
<add> return [Str::studly(trim($rules)), $parameters];
<ide> }
<ide>
<ide> /**
<ide> public function getExtensions()
<ide> public function addExtensions(array $extensions)
<ide> {
<ide> if ($extensions) {
<del> $keys = array_map('snake_case', array_keys($extensions));
<add> $keys = array_map('\Illuminate\Support\Str::snake', array_keys($extensions));
<ide>
<ide> $extensions = array_combine($keys, array_values($extensions));
<ide> }
<ide> public function addImplicitExtensions(array $extensions)
<ide> $this->addExtensions($extensions);
<ide>
<ide> foreach ($extensions as $rule => $extension) {
<del> $this->implicitRules[] = studly_case($rule);
<add> $this->implicitRules[] = Str::studly($rule);
<ide> }
<ide> }
<ide>
<ide> public function addImplicitExtensions(array $extensions)
<ide> */
<ide> public function addExtension($rule, $extension)
<ide> {
<del> $this->extensions[snake_case($rule)] = $extension;
<add> $this->extensions[Str::snake($rule)] = $extension;
<ide> }
<ide>
<ide> /**
<ide> public function addImplicitExtension($rule, $extension)
<ide> {
<ide> $this->addExtension($rule, $extension);
<ide>
<del> $this->implicitRules[] = studly_case($rule);
<add> $this->implicitRules[] = Str::studly($rule);
<ide> }
<ide>
<ide> /**
<ide> public function getReplacers()
<ide> public function addReplacers(array $replacers)
<ide> {
<ide> if ($replacers) {
<del> $keys = array_map('snake_case', array_keys($replacers));
<add> $keys = array_map('\Illuminate\Support\Str::snake', array_keys($replacers));
<ide>
<ide> $replacers = array_combine($keys, array_values($replacers));
<ide> }
<ide> public function addReplacers(array $replacers)
<ide> */
<ide> public function addReplacer($rule, $replacer)
<ide> {
<del> $this->replacers[snake_case($rule)] = $replacer;
<add> $this->replacers[Str::snake($rule)] = $replacer;
<ide> }
<ide>
<ide> /**
<ide> protected function requireParameterCount($count, $parameters, $rule)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> $rule = snake_case(substr($method, 8));
<add> $rule = Str::snake(substr($method, 8));
<ide>
<ide> if (isset($this->extensions[$rule])) {
<ide> return $this->callExtension($rule, $parameters);
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> namespace Illuminate\View\Compilers;
<ide>
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide>
<ide> class BladeCompiler extends Compiler implements CompilerInterface
<ide> {
<ide> protected function compileEndforelse($expression)
<ide> */
<ide> protected function compileExtends($expression)
<ide> {
<del> if (starts_with($expression, '(')) {
<add> if (Str::startsWith($expression, '(')) {
<ide> $expression = substr($expression, 1, -1);
<ide> }
<ide>
<ide> protected function compileExtends($expression)
<ide> */
<ide> protected function compileInclude($expression)
<ide> {
<del> if (starts_with($expression, '(')) {
<add> if (Str::startsWith($expression, '(')) {
<ide> $expression = substr($expression, 1, -1);
<ide> }
<ide>
<ide><path>src/Illuminate/View/Factory.php
<ide>
<ide> use Closure;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\View\Engines\EngineResolver;
<ide> public function renderEach($view, $data, $iterator, $empty = 'raw|')
<ide> // view. Alternatively, the "empty view" could be a raw string that begins
<ide> // with "raw|" for convenience and to let this know that it is a string.
<ide> else {
<del> if (starts_with($empty, 'raw|')) {
<add> if (Str::startsWith($empty, 'raw|')) {
<ide> $result = substr($empty, 4);
<ide> } else {
<ide> $result = $this->make($empty)->render();
<ide> protected function buildClassEventCallback($class, $prefix)
<ide> */
<ide> protected function parseClassEvent($class, $prefix)
<ide> {
<del> if (str_contains($class, '@')) {
<add> if (Str::contains($class, '@')) {
<ide> return explode('@', $class);
<ide> }
<ide>
<del> $method = str_contains($prefix, 'composing') ? 'compose' : 'create';
<add> $method = Str::contains($prefix, 'composing') ? 'compose' : 'create';
<ide>
<ide> return [$class, $method];
<ide> }
<ide><path>src/Illuminate/View/View.php
<ide> use Closure;
<ide> use ArrayAccess;
<ide> use BadMethodCallException;
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Support\MessageBag;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\View\Engines\EngineInterface;
<ide> public function __unset($key)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> if (starts_with($method, 'with')) {
<del> return $this->with(snake_case(substr($method, 4)), $parameters[0]);
<add> if (Str::startsWith($method, 'with')) {
<add> return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
<ide> }
<ide>
<ide> throw new BadMethodCallException("Method [$method] does not exist on view.");
<ide><path>tests/Encryption/EncrypterTest.php
<ide> <?php
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Encryption\Encrypter;
<ide>
<ide> class EncrypterTest extends PHPUnit_Framework_TestCase
<ide> public function testExceptionThrownWithDifferentKey()
<ide>
<ide> public function testOpenSslEncrypterCanDecryptMcryptedData()
<ide> {
<del> $key = str_random(32);
<add> $key = Str::random(32);
<ide> $encrypter = new Illuminate\Encryption\McryptEncrypter($key);
<ide> $encrypted = $encrypter->encrypt('foo');
<ide> $openSslEncrypter = new Illuminate\Encryption\Encrypter($key, 'AES-256-CBC');
<ide><path>tests/Support/SupportHelpersTest.php
<ide> <?php
<ide>
<ide> use Mockery as m;
<add>use Illuminate\Support\Str;
<ide>
<ide> class SupportHelpersTest extends PHPUnit_Framework_TestCase
<ide> {
<ide> public function testArrayFlatten()
<ide>
<ide> public function testStrIs()
<ide> {
<del> $this->assertTrue(str_is('*.dev', 'localhost.dev'));
<del> $this->assertTrue(str_is('a', 'a'));
<del> $this->assertTrue(str_is('/', '/'));
<del> $this->assertTrue(str_is('*dev*', 'localhost.dev'));
<del> $this->assertTrue(str_is('foo?bar', 'foo?bar'));
<del> $this->assertFalse(str_is('*something', 'foobar'));
<del> $this->assertFalse(str_is('foo', 'bar'));
<del> $this->assertFalse(str_is('foo.*', 'foobar'));
<del> $this->assertFalse(str_is('foo.ar', 'foobar'));
<del> $this->assertFalse(str_is('foo?bar', 'foobar'));
<del> $this->assertFalse(str_is('foo?bar', 'fobar'));
<add> $this->assertTrue(Str::is('*.dev', 'localhost.dev'));
<add> $this->assertTrue(Str::is('a', 'a'));
<add> $this->assertTrue(Str::is('/', '/'));
<add> $this->assertTrue(Str::is('*dev*', 'localhost.dev'));
<add> $this->assertTrue(Str::is('foo?bar', 'foo?bar'));
<add> $this->assertFalse(Str::is('*something', 'foobar'));
<add> $this->assertFalse(Str::is('foo', 'bar'));
<add> $this->assertFalse(Str::is('foo.*', 'foobar'));
<add> $this->assertFalse(Str::is('foo.ar', 'foobar'));
<add> $this->assertFalse(Str::is('foo?bar', 'foobar'));
<add> $this->assertFalse(Str::is('foo?bar', 'fobar'));
<ide> }
<ide>
<ide> public function testStrRandom()
<ide> {
<del> $result = str_random(20);
<add> $result = Str::random(20);
<ide> $this->assertTrue(is_string($result));
<ide> $this->assertEquals(20, strlen($result));
<ide> }
<ide>
<ide> public function testStartsWith()
<ide> {
<del> $this->assertTrue(starts_with('jason', 'jas'));
<del> $this->assertTrue(starts_with('jason', ['jas']));
<del> $this->assertFalse(starts_with('jason', 'day'));
<del> $this->assertFalse(starts_with('jason', ['day']));
<add> $this->assertTrue(Str::startsWith('jason', 'jas'));
<add> $this->assertTrue(Str::startsWith('jason', ['jas']));
<add> $this->assertFalse(Str::startsWith('jason', 'day'));
<add> $this->assertFalse(Str::startsWith('jason', ['day']));
<ide> }
<ide>
<ide> public function testE()
<ide> public function testEndsWith()
<ide>
<ide> public function testStrContains()
<ide> {
<del> $this->assertTrue(str_contains('taylor', 'ylo'));
<del> $this->assertTrue(str_contains('taylor', ['ylo']));
<del> $this->assertFalse(str_contains('taylor', 'xxx'));
<del> $this->assertFalse(str_contains('taylor', ['xxx']));
<del> $this->assertTrue(str_contains('taylor', ['xxx', 'taylor']));
<add> $this->assertTrue(Str::contains('taylor', 'ylo'));
<add> $this->assertTrue(Str::contains('taylor', ['ylo']));
<add> $this->assertFalse(Str::contains('taylor', 'xxx'));
<add> $this->assertFalse(Str::contains('taylor', ['xxx']));
<add> $this->assertTrue(Str::contains('taylor', ['xxx', 'taylor']));
<ide> }
<ide>
<ide> public function testStrFinish()
<ide> {
<del> $this->assertEquals('test/string/', str_finish('test/string', '/'));
<del> $this->assertEquals('test/string/', str_finish('test/string/', '/'));
<del> $this->assertEquals('test/string/', str_finish('test/string//', '/'));
<add> $this->assertEquals('test/string/', Str::finish('test/string', '/'));
<add> $this->assertEquals('test/string/', Str::finish('test/string/', '/'));
<add> $this->assertEquals('test/string/', Str::finish('test/string//', '/'));
<ide> }
<ide>
<ide> public function testSnakeCase()
<ide> {
<del> $this->assertEquals('foo_bar', snake_case('fooBar'));
<del> $this->assertEquals('foo_bar', snake_case('fooBar')); // test cache
<add> $this->assertEquals('foo_bar', Str::snake('fooBar'));
<add> $this->assertEquals('foo_bar', Str::snake('fooBar')); // test cache
<ide> }
<ide>
<ide> public function testStrLimit()
<ide> {
<ide> $string = 'The PHP framework for web artisans.';
<del> $this->assertEquals('The PHP...', str_limit($string, 7));
<del> $this->assertEquals('The PHP', str_limit($string, 7, ''));
<del> $this->assertEquals('The PHP framework for web artisans.', str_limit($string, 100));
<add> $this->assertEquals('The PHP...', Str::limit($string, 7));
<add> $this->assertEquals('The PHP', Str::limit($string, 7, ''));
<add> $this->assertEquals('The PHP framework for web artisans.', Str::limit($string, 100));
<ide>
<ide> $nonAsciiString = '这是一段中文';
<del> $this->assertEquals('这是一...', str_limit($nonAsciiString, 6));
<del> $this->assertEquals('这是一', str_limit($nonAsciiString, 6, ''));
<add> $this->assertEquals('这是一...', Str::limit($nonAsciiString, 6));
<add> $this->assertEquals('这是一', Str::limit($nonAsciiString, 6, ''));
<ide> }
<ide>
<ide> public function testCamelCase()
<ide> public function testCamelCase()
<ide>
<ide> public function testStudlyCase()
<ide> {
<del> $this->assertEquals('FooBar', studly_case('fooBar'));
<del> $this->assertEquals('FooBar', studly_case('foo_bar'));
<del> $this->assertEquals('FooBar', studly_case('foo_bar')); // test cache
<del> $this->assertEquals('FooBarBaz', studly_case('foo-barBaz'));
<del> $this->assertEquals('FooBarBaz', studly_case('foo-bar_baz'));
<add> $this->assertEquals('FooBar', Str::studly('fooBar'));
<add> $this->assertEquals('FooBar', Str::studly('foo_bar'));
<add> $this->assertEquals('FooBar', Str::studly('foo_bar')); // test cache
<add> $this->assertEquals('FooBarBaz', Str::studly('foo-barBaz'));
<add> $this->assertEquals('FooBarBaz', Str::studly('foo-bar_baz'));
<ide> }
<ide>
<ide> public function testClassBasename()
<ide><path>tests/Support/SupportPluralizerTest.php
<ide> <?php
<ide>
<add>use Illuminate\Support\Str;
<add>
<ide> class SupportPluralizerTest extends PHPUnit_Framework_TestCase
<ide> {
<ide> public function testBasicSingular()
<ide> {
<del> $this->assertEquals('child', str_singular('children'));
<add> $this->assertEquals('child', Str::singular('children'));
<ide> }
<ide>
<ide> public function testBasicPlural()
<ide> {
<del> $this->assertEquals('children', str_plural('child'));
<add> $this->assertEquals('children', Str::plural('child'));
<ide> }
<ide>
<ide> public function testCaseSensitiveSingularUsage()
<ide> {
<del> $this->assertEquals('Child', str_singular('Children'));
<del> $this->assertEquals('CHILD', str_singular('CHILDREN'));
<del> $this->assertEquals('Test', str_singular('Tests'));
<add> $this->assertEquals('Child', Str::singular('Children'));
<add> $this->assertEquals('CHILD', Str::singular('CHILDREN'));
<add> $this->assertEquals('Test', Str::singular('Tests'));
<ide> }
<ide>
<ide> public function testCaseSensitiveSingularPlural()
<ide> {
<del> $this->assertEquals('Children', str_plural('Child'));
<del> $this->assertEquals('CHILDREN', str_plural('CHILD'));
<del> $this->assertEquals('Tests', str_plural('Test'));
<add> $this->assertEquals('Children', Str::plural('Child'));
<add> $this->assertEquals('CHILDREN', Str::plural('CHILD'));
<add> $this->assertEquals('Tests', Str::plural('Test'));
<ide> }
<ide>
<ide> public function testIfEndOfWordPlural()
<ide> {
<del> $this->assertEquals('VortexFields', str_plural('VortexField'));
<del> $this->assertEquals('MatrixFields', str_plural('MatrixField'));
<del> $this->assertEquals('IndexFields', str_plural('IndexField'));
<del> $this->assertEquals('VertexFields', str_plural('VertexField'));
<add> $this->assertEquals('VortexFields', Str::plural('VortexField'));
<add> $this->assertEquals('MatrixFields', Str::plural('MatrixField'));
<add> $this->assertEquals('IndexFields', Str::plural('IndexField'));
<add> $this->assertEquals('VertexFields', Str::plural('VertexField'));
<ide> }
<ide> } | 44 |
Python | Python | extend lemmatizer rules for all upos tags | 4fa96705379b10b761a7097b1adb12145402cb1f | <ide><path>spacy/lemmatizer.py
<ide> from .symbols import NOUN, VERB, ADJ, PUNCT, PROPN
<ide> from .errors import Errors
<ide> from .lookups import Lookups
<add>from .parts_of_speech import NAMES as UPOS_NAMES
<ide>
<ide>
<ide> class Lemmatizer(object):
<ide> def __call__(self, string, univ_pos, morphology=None):
<ide> lookup_table = self.lookups.get_table("lemma_lookup", {})
<ide> if "lemma_rules" not in self.lookups:
<ide> return [lookup_table.get(string, string)]
<del> if univ_pos in (NOUN, "NOUN", "noun"):
<del> univ_pos = "noun"
<del> elif univ_pos in (VERB, "VERB", "verb"):
<del> univ_pos = "verb"
<del> elif univ_pos in (ADJ, "ADJ", "adj"):
<del> univ_pos = "adj"
<del> elif univ_pos in (PUNCT, "PUNCT", "punct"):
<del> univ_pos = "punct"
<del> elif univ_pos in (PROPN, "PROPN"):
<del> return [string]
<del> else:
<add> if isinstance(univ_pos, int):
<add> univ_pos = UPOS_NAMES.get(univ_pos, "X")
<add> univ_pos = univ_pos.lower()
<add>
<add> if univ_pos in ("", "eol", "space"):
<ide> return [string.lower()]
<ide> # See Issue #435 for example of where this logic is requied.
<ide> if self.is_base_form(univ_pos, morphology): | 1 |
Ruby | Ruby | fix comment typo | d345483de164e062727f95d3fbd575433d735548 | <ide><path>Library/Homebrew/formulary.rb
<ide> require "tap"
<ide>
<ide> # The Formulary is responsible for creating instances of Formula.
<del># It is not meant to be used directy from formulae.
<add># It is not meant to be used directly from formulae.
<ide>
<ide> class Formulary
<ide> FORMULAE = {} | 1 |
Javascript | Javascript | move the contents of these files into angular.js | af0ad6561c0d75c4f155b07e9cfc36a983af55bd | <ide><path>angularFiles.js
<ide> angularFiles = {
<ide> 'src/Angular.js',
<ide> 'src/loader.js',
<ide> 'src/AngularPublic.js',
<del> 'src/JSON.js',
<ide> 'src/jqLite.js',
<ide> 'src/apis.js',
<ide>
<ide><path>src/Angular.js
<ide> function bind(self, fn) {
<ide> }
<ide> }
<ide>
<add>
<add>function toJsonReplacer(key, value) {
<add> var val = value;
<add>
<add> if (/^\$+/.test(key)) {
<add> val = undefined;
<add> } else if (isWindow(value)) {
<add> val = '$WINDOW';
<add> } else if (value && document === value) {
<add> val = '$DOCUMENT';
<add> } else if (isScope(value)) {
<add> val = '$SCOPE';
<add> }
<add>
<add> return val;
<add>};
<add>
<add>
<add>/**
<add> * @ngdoc function
<add> * @name angular.toJson
<add> * @function
<add> *
<add> * @description
<add> * Serializes input into a JSON-formatted string.
<add> *
<add> * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
<add> * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
<add> * @returns {string} Jsonified string representing `obj`.
<add> */
<add>function toJson(obj, pretty) {
<add> return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
<add>}
<add>
<add>
<add>/**
<add> * @ngdoc function
<add> * @name angular.fromJson
<add> * @function
<add> *
<add> * @description
<add> * Deserializes a JSON string.
<add> *
<add> * @param {string} json JSON string to deserialize.
<add> * @returns {Object|Array|Date|string|number} Deserialized thingy.
<add> */
<add>function fromJson(json) {
<add> return isString(json)
<add> ? JSON.parse(json)
<add> : json;
<add>}
<add>
<add>
<ide> function toBoolean(value) {
<ide> if (value && value.length !== 0) {
<ide> var v = lowercase("" + value);
<ide><path>src/JSON.js
<del>'use strict';
<del>
<del>var jsonReplacer = function(key, value) {
<del> var val = value;
<del> if (/^\$+/.test(key)) {
<del> val = undefined;
<del> } else if (isWindow(value)) {
<del> val = '$WINDOW';
<del> } else if (value && document === value) {
<del> val = '$DOCUMENT';
<del> } else if (isScope(value)) {
<del> val = '$SCOPE';
<del> }
<del>
<del> return val;
<del>};
<del>
<del>/**
<del> * @ngdoc function
<del> * @name angular.toJson
<del> * @function
<del> *
<del> * @description
<del> * Serializes input into a JSON-formatted string.
<del> *
<del> * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
<del> * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
<del> * @returns {string} Jsonified string representing `obj`.
<del> */
<del>function toJson(obj, pretty) {
<del> return JSON.stringify(obj, jsonReplacer, pretty ? ' ' : null);
<del>}
<del>
<del>/**
<del> * @ngdoc function
<del> * @name angular.fromJson
<del> * @function
<del> *
<del> * @description
<del> * Deserializes a JSON string.
<del> *
<del> * @param {string} json JSON string to deserialize.
<del> * @returns {Object|Array|Date|string|number} Deserialized thingy.
<del> */
<del>function fromJson(json) {
<del> return isString(json)
<del> ? JSON.parse(json)
<del> : json;
<del>}
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles');
<ide> });
<ide> });
<add>
<add>
<add> describe('fromJson', function() {
<add>
<add> it('should delegate to JSON.parse', function() {
<add> var spy = spyOn(JSON, 'parse').andCallThrough();
<add>
<add> expect(fromJson('{}')).toEqual({});
<add> expect(spy).toHaveBeenCalled();
<add> });
<add> });
<add>
<add>
<add> describe('toJson', function() {
<add>
<add> it('should delegate to JSON.stringify', function() {
<add> var spy = spyOn(JSON, 'stringify').andCallThrough();
<add>
<add> expect(toJson({})).toEqual('{}');
<add> expect(spy).toHaveBeenCalled();
<add> });
<add>
<add>
<add> it('should format objects pretty', function() {
<add> expect(toJson({a: 1, b: 2}, true)).
<add> toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}');
<add> expect(toJson({a: {b: 2}}, true)).
<add> toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}');
<add> });
<add>
<add>
<add> it('should not serialize properties starting with $', function() {
<add> expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}');
<add> });
<add>
<add>
<add> it('should not serialize $window object', function() {
<add> expect(toJson(window)).toEqual('"$WINDOW"');
<add> });
<add>
<add>
<add> it('should not serialize $document object', function() {
<add> expect(toJson(document)).toEqual('"$DOCUMENT"');
<add> });
<add>
<add>
<add> it('should not serialize scope instances', inject(function($rootScope) {
<add> expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
<add> }));
<add> });
<ide> });
<ide><path>test/JsonSpec.js
<del>'use strict';
<del>
<del>describe('json', function() {
<del>
<del> describe('fromJson', function() {
<del>
<del> it('should delegate to JSON.parse', function() {
<del> var spy = spyOn(JSON, 'parse').andCallThrough();
<del>
<del> expect(fromJson('{}')).toEqual({});
<del> expect(spy).toHaveBeenCalled();
<del> });
<del> });
<del>
<del>
<del> describe('toJson', function() {
<del>
<del> it('should delegate to JSON.stringify', function() {
<del> var spy = spyOn(JSON, 'stringify').andCallThrough();
<del>
<del> expect(toJson({})).toEqual('{}');
<del> expect(spy).toHaveBeenCalled();
<del> });
<del>
<del>
<del> it('should format objects pretty', function() {
<del> expect(toJson({a: 1, b: 2}, true)).
<del> toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}');
<del> expect(toJson({a: {b: 2}}, true)).
<del> toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}');
<del> });
<del>
<del>
<del> it('should not serialize properties starting with $', function() {
<del> expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}');
<del> });
<del>
<del>
<del> it('should not serialize undefined values', function() {
<del> expect(angular.toJson({A:undefined})).toEqual('{}');
<del> });
<del>
<del>
<del> it('should not serialize $window object', function() {
<del> expect(toJson(window)).toEqual('"$WINDOW"');
<del> });
<del>
<del>
<del> it('should not serialize $document object', function() {
<del> expect(toJson(document)).toEqual('"$DOCUMENT"');
<del> });
<del>
<del>
<del> it('should not serialize scope instances', inject(function($rootScope) {
<del> expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
<del> }));
<del> });
<del>}); | 5 |
Go | Go | fix imagetree test | 08623dc216227d6377cb4558caedd75cacf68755 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> }
<ide>
<ide> var outs []APIImages
<del> err = json.Unmarshal(body, &outs)
<del> if err != nil {
<add> if err := json.Unmarshal(body, &outs); err != nil {
<ide> return err
<ide> }
<ide>
<del> var startImageArg = cmd.Arg(0)
<del> var startImage APIImages
<add> var (
<add> startImageArg = cmd.Arg(0)
<add> startImage APIImages
<add>
<add> roots []APIImages
<add> byParent = make(map[string][]APIImages)
<add> )
<ide>
<del> var roots []APIImages
<del> var byParent = make(map[string][]APIImages)
<ide> for _, image := range outs {
<ide> if image.ParentId == "" {
<ide> roots = append(roots, image)
<ide><path>commands_test.go
<ide> func TestImagesTree(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> cmdOutput := string(cmdOutputBytes)
<del>
<ide> regexpStrings := []string{
<ide> fmt.Sprintf("└─%s Size: (\\d+.\\d+ MB) \\(virtual \\d+.\\d+ MB\\) Tags: %s:latest", unitTestImageIDShort, unitTestImageName),
<del> "(?m)^ └─[0-9a-f]+",
<del> "(?m)^ └─[0-9a-f]+",
<del> "(?m)^ └─[0-9a-f]+",
<del> fmt.Sprintf(" └─%s Size: \\d+ B \\(virtual \\d+.\\d+ MB\\) Tags: test:latest", utils.TruncateID(image.ID)),
<add> "(?m) └─[0-9a-f]+.*",
<add> "(?m) └─[0-9a-f]+.*",
<add> "(?m) └─[0-9a-f]+.*",
<add> fmt.Sprintf("(?m)^ └─%s Size: \\d+.\\d+ MB \\(virtual \\d+.\\d+ MB\\) Tags: test:latest", utils.TruncateID(image.ID)),
<ide> }
<ide>
<ide> compiledRegexps := []*regexp.Regexp{} | 2 |
Ruby | Ruby | find version number in *-src.tarball | a3668bef76d66cd3295280b771d2ff2ffac0b58d | <ide><path>Library/Homebrew/pathname+yeast.rb
<ide> def version
<ide> # eg. foobar4.5.1
<ide> /((\d+\.)*\d+)$/.match stem
<ide> return $1 if $1
<del>
<add>
<ide> # eg foobar-4.5.0-bin
<del> /-((\d+\.)*\d+-bin)$/.match stem
<add> /-((\d+\.)+\d+)-(bin|src)$/.match stem
<ide> return $1 if $1
<del>
<add>
<ide> # eg. otp_src_R13B (this is erlang's style)
<ide> # eg. astyle_1.23_macosx.tar.gz
<ide> stem.scan /_([^_]+)/ do |match|
<ide><path>Library/Homebrew/unittest.rb
<ide> HOMEBREW_CACHE=HOMEBREW_PREFIX.parent+"cache"
<ide> HOMEBREW_CELLAR=HOMEBREW_PREFIX.parent+"cellar"
<ide> HOMEBREW_USER_AGENT="Homebrew"
<add>MACOS_VERSION=10.6
<ide>
<ide> (HOMEBREW_PREFIX+'Library'+'Formula').mkpath
<ide> Dir.chdir HOMEBREW_PREFIX
<ide> def test_pathname_plus_yeast
<ide> assert_raises(RuntimeError) {Pathname.getwd.install 'non_existant_file'}
<ide> end
<ide>
<add> def test_omega_version_style
<add> f=MockFormula.new 'http://www.alcyone.com/binaries/omega/omega-0.80.2-src.tar.gz'
<add> assert_equal '0.80.2', f.version
<add> end
<add>
<ide> def test_formula_class_func
<ide> assert_equal Formula.class_s('s-lang'), 'SLang'
<ide> assert_equal Formula.class_s('pkg-config'), 'PkgConfig' | 2 |
Text | Text | simplify meteor readme | 30f169af10b038e79e1334aaf667c2dddb391f67 | <ide><path>meteor/README.md
<ide> Packaging [Moment](momentjs.org) for [Meteor.js](http://meteor.com).
<ide>
<del>
<del># Meteor
<del>
<del>If you're new to Meteor, here's what the excitement is all about -
<del>[watch the first two minutes](https://www.youtube.com/watch?v=fsi0aJ9yr2o); you'll be hooked by 1:28.
<del>
<del>That screencast is from 2012. In the meantime, Meteor has become a mature JavaScript-everywhere web
<del>development framework. Read more at [Why Meteor](http://www.meteorpedia.com/read/Why_Meteor).
<del>
<del>
<ide> # Issues
<ide>
<ide> If you encounter an issue while using this package, please CC @dandv when you file it in this repo.
<del>
<del>
<del># DONE
<del>
<del>* Simple test. Should be enough.
<del>
<del>
<del># TODO
<del>
<del>* Add other tests; however, that is overkill, and the responsibiity of Moment, not of the Meteor integration. | 1 |
Text | Text | add a note to `buf.fill()` description | c1ac57888199ba13df7eda4912cdb53dcfb5a2ee | <ide><path>doc/api/buffer.md
<ide> console.log(b.toString());
<ide> // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
<ide> ```
<ide>
<del>`value` is coerced to a `uint32` value if it is not a string or integer.
<add>`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
<add>integer. If the resulting integer is greater than `255` (decimal), `buf` will be
<add>filled with `0`.
<ide>
<ide> If the final write of a `fill()` operation falls on a multi-byte character,
<ide> then only the bytes of that character that fit into `buf` are written: | 1 |
Ruby | Ruby | inline a method used by render_partial. closes | e9a4e4d88b6377ce1b6167149ea45767018dac65 | <ide><path>actionpack/lib/action_view/partials.rb
<ide> def add_counter_to_local_assigns!(partial_name, local_assigns)
<ide> end
<ide>
<ide> def add_object_to_local_assigns!(partial_name, local_assigns, object)
<del> local_assigns[partial_name.intern] ||= unwrap_object(object) || controller.instance_variable_get("@#{partial_name}")
<del> end
<del>
<del> def unwrap_object(object)
<del> if object.is_a?(ActionView::Base::ObjectWrapper)
<del> object.value
<del> else
<del> object
<del> end
<add> local_assigns[partial_name.intern] ||=
<add> if object.is_a?(ActionView::Base::ObjectWrapper)
<add> object.value
<add> else
<add> object
<add> end || controller.instance_variable_get("@#{partial_name}")
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix dead link in pushnotificationios docs | 6068c07e989613a59648d8e62171202c904249ba | <ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> var NOTIF_REGISTER_EVENT = 'remoteNotificationsRegistered';
<ide> * Handle push notifications for your app, including permission handling and
<ide> * icon badge number.
<ide> *
<del> * To get up and running, [configure your notifications with Apple](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringPushNotifications/ConfiguringPushNotifications.html)
<add> * To get up and running, [configure your notifications with Apple](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW6)
<ide> * and your server-side system. To get an idea, [this is the Parse guide](https://parse.com/tutorials/ios-push-notifications).
<ide> */
<ide> class PushNotificationIOS { | 1 |
Javascript | Javascript | improve _http_outgoing coverage | f4d174aa0da662761c846d9d88b68e0471c84c64 | <ide><path>test/parallel/test-http-outgoing-internal-headernames-getter.js
<ide> const common = require('../common');
<ide>
<ide> const { OutgoingMessage } = require('http');
<add>const assert = require('assert');
<ide>
<ide> const warn = 'OutgoingMessage.prototype._headerNames is deprecated';
<ide> common.expectWarning('DeprecationWarning', warn, 'DEP0066');
<ide> common.expectWarning('DeprecationWarning', warn, 'DEP0066');
<ide> const outgoingMessage = new OutgoingMessage();
<ide> outgoingMessage._headerNames; // eslint-disable-line no-unused-expressions
<ide> }
<add>
<add>{
<add> // Tests _headerNames getter result after setting a header.
<add> const outgoingMessage = new OutgoingMessage();
<add> outgoingMessage.setHeader('key', 'value');
<add> const expect = Object.create(null);
<add> expect.key = 'key';
<add> assert.deepStrictEqual(outgoingMessage._headerNames, expect);
<add>} | 1 |
Javascript | Javascript | use special nodename_ impl only for ie<9 | 0d2d7025e60095afc3497c6cd4a4af9e0cd9b90e | <ide><path>src/Angular.js
<ide> function HTML(html, option) {
<ide> };
<ide> }
<ide>
<del>if (msie) {
<add>if (msie < 9) {
<ide> nodeName_ = function(element) {
<ide> element = element.nodeName ? element : element[0];
<ide> return (element.scopeName && element.scopeName != 'HTML' ) ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
<ide><path>test/AngularSpec.js
<ide> describe('angular', function(){
<ide> expect(scope.greeting).toEqual('hello world');
<ide> });
<ide> });
<add>
<add>
<add> describe('nodeName_', function() {
<add> it('should correctly detect node name with "namespace" when xmlns is defined', function() {
<add> var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
<add> '<ngtest:foo ngtest:attr="bar"></ng:test>' +
<add> '</div>')[0];
<add> expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
<add> expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
<add> });
<add>
<add> if (!msie || msie >= 9) {
<add> it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() {
<add> var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
<add> '<ngtest:foo ngtest:attr="bar"></ng:test>' +
<add> '</div>')[0];
<add> expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
<add> expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
<add> });
<add> }
<add> });
<ide> }); | 2 |
Ruby | Ruby | use the content_type method on the request object | 27daea82d77a81a866ca20f547ab66e0f47d6380 | <ide><path>actionpack/lib/action_controller/metal.rb
<ide> def content_type=(type)
<ide> end
<ide>
<ide> def content_type
<del> headers["Content-Type"]
<add> request.content_type
<ide> end
<ide>
<ide> def location | 1 |
Javascript | Javascript | add fragment as a named export to react | 4ce5da7aee90a373f2f36d1beb559097af30952e | <ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegration-test.js
<ide> describe('ReactDOMServerIntegration', () => {
<ide> expect(parent.childNodes[2].tagName).toBe('P');
<ide> });
<ide>
<add> itRenders('a fragment with one child', async render => {
<add> let e = await render(<React.Fragment><div>text1</div></React.Fragment>);
<add> let parent = e.parentNode;
<add> expect(parent.childNodes[0].tagName).toBe('DIV');
<add> });
<add>
<add> itRenders('a fragment with several children', async render => {
<add> let Header = props => {
<add> return <p>header</p>;
<add> };
<add> let Footer = props => {
<add> return <React.Fragment><h2>footer</h2><h3>about</h3></React.Fragment>;
<add> };
<add> let e = await render(
<add> <React.Fragment>
<add> <div>text1</div>
<add> <span>text2</span>
<add> <Header />
<add> <Footer />
<add> </React.Fragment>,
<add> );
<add> let parent = e.parentNode;
<add> expect(parent.childNodes[0].tagName).toBe('DIV');
<add> expect(parent.childNodes[1].tagName).toBe('SPAN');
<add> expect(parent.childNodes[2].tagName).toBe('P');
<add> expect(parent.childNodes[3].tagName).toBe('H2');
<add> expect(parent.childNodes[4].tagName).toBe('H3');
<add> });
<add>
<add> itRenders('a nested fragment', async render => {
<add> let e = await render(
<add> <React.Fragment>
<add> <React.Fragment>
<add> <div>text1</div>
<add> </React.Fragment>
<add> <span>text2</span>
<add> <React.Fragment>
<add> <React.Fragment>
<add> <React.Fragment>{null}<p /></React.Fragment>{false}
<add> </React.Fragment>
<add> </React.Fragment>
<add> </React.Fragment>,
<add> );
<add> let parent = e.parentNode;
<add> expect(parent.childNodes[0].tagName).toBe('DIV');
<add> expect(parent.childNodes[1].tagName).toBe('SPAN');
<add> expect(parent.childNodes[2].tagName).toBe('P');
<add> });
<add>
<ide> itRenders('an iterable', async render => {
<ide> const threeDivIterable = {
<ide> '@@iterator': function() {
<ide> describe('ReactDOMServerIntegration', () => {
<ide> // but server returns empty HTML. So we compare parent text.
<ide> expect((await render(<div>{''}</div>)).textContent).toBe('');
<ide>
<add> expect(await render(<React.Fragment />)).toBe(null);
<ide> expect(await render([])).toBe(null);
<ide> expect(await render(false)).toBe(null);
<ide> expect(await render(true)).toBe(null);
<ide><path>packages/react-dom/src/server/ReactPartialRenderer.js
<ide> var escapeTextContentForBrowser = require('../shared/escapeTextContentForBrowser
<ide> var isCustomComponent = require('../shared/isCustomComponent');
<ide> var omittedCloseTags = require('../shared/omittedCloseTags');
<ide>
<add>var REACT_FRAGMENT_TYPE =
<add> (typeof Symbol === 'function' &&
<add> Symbol.for &&
<add> Symbol.for('react.fragment')) ||
<add> 0xeacb;
<add>
<ide> // Based on reading the React.Children implementation. TODO: type this somewhere?
<ide> type ReactNode = string | number | ReactElement;
<ide> type FlatReactChildren = Array<null | ReactNode>;
<ide> function getNonChildrenInnerMarkup(props) {
<ide> return null;
<ide> }
<ide>
<add>function flattenTopLevelChildren(children: mixed): FlatReactChildren {
<add> if (!React.isValidElement(children)) {
<add> return toArray(children);
<add> }
<add> const element = ((children: any): ReactElement);
<add> if (element.type !== REACT_FRAGMENT_TYPE) {
<add> return [element];
<add> }
<add> const fragmentChildren = element.props.children;
<add> if (!React.isValidElement(fragmentChildren)) {
<add> return toArray(fragmentChildren);
<add> }
<add> const fragmentChildElement = ((fragmentChildren: any): ReactElement);
<add> return [fragmentChildElement];
<add>}
<add>
<ide> function flattenOptionChildren(children: mixed): string {
<ide> var content = '';
<ide> // Flatten children and warn if they aren't strings or numbers;
<ide> class ReactDOMServerRenderer {
<ide> makeStaticMarkup: boolean;
<ide>
<ide> constructor(children: mixed, makeStaticMarkup: boolean) {
<del> var flatChildren;
<del> if (React.isValidElement(children)) {
<del> // Safe because we just checked it's an element.
<del> var element = ((children: any): ReactElement);
<del> flatChildren = [element];
<del> } else {
<del> flatChildren = toArray(children);
<del> }
<add> const flatChildren = flattenTopLevelChildren(children);
<add>
<ide> var topFrame: Frame = {
<ide> // Assume all trees start in the HTML namespace (not totally true, but
<ide> // this is what we did historically)
<ide> class ReactDOMServerRenderer {
<ide> ({child: nextChild, context} = resolve(child, context));
<ide> if (nextChild === null || nextChild === false) {
<ide> return '';
<del> } else {
<del> if (React.isValidElement(nextChild)) {
<del> // Safe because we just checked it's an element.
<del> var nextElement = ((nextChild: any): ReactElement);
<del> return this.renderDOM(nextElement, context, parentNamespace);
<del> } else {
<del> var nextChildren = toArray(nextChild);
<del> var frame: Frame = {
<del> domNamespace: parentNamespace,
<del> children: nextChildren,
<del> childIndex: 0,
<del> context: context,
<del> footer: '',
<del> };
<del> if (__DEV__) {
<del> ((frame: any): FrameDev).debugElementStack = [];
<del> }
<del> this.stack.push(frame);
<del> return '';
<add> } else if (!React.isValidElement(nextChild)) {
<add> const nextChildren = toArray(nextChild);
<add> const frame: Frame = {
<add> domNamespace: parentNamespace,
<add> children: nextChildren,
<add> childIndex: 0,
<add> context: context,
<add> footer: '',
<add> };
<add> if (__DEV__) {
<add> ((frame: any): FrameDev).debugElementStack = [];
<ide> }
<add> this.stack.push(frame);
<add> return '';
<add> } else if (
<add> ((nextChild: any): ReactElement).type === REACT_FRAGMENT_TYPE
<add> ) {
<add> const nextChildren = toArray(
<add> ((nextChild: any): ReactElement).props.children,
<add> );
<add> const frame: Frame = {
<add> domNamespace: parentNamespace,
<add> children: nextChildren,
<add> childIndex: 0,
<add> context: context,
<add> footer: '',
<add> };
<add> if (__DEV__) {
<add> ((frame: any): FrameDev).debugElementStack = [];
<add> }
<add> this.stack.push(frame);
<add> return '';
<add> } else {
<add> // Safe because we just checked it's an element.
<add> var nextElement = ((nextChild: any): ReactElement);
<add> return this.renderDOM(nextElement, context, parentNamespace);
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-noop-renderer/src/ReactNoop.js
<ide> var ReactNoop = {
<ide> log(
<ide> ' '.repeat(depth) +
<ide> '- ' +
<del> (fiber.type ? fiber.type.name || fiber.type : '[root]'),
<add> // need to explicitly coerce Symbol to a string
<add> (fiber.type ? fiber.type.name || fiber.type.toString() : '[root]'),
<ide> '[' + fiber.expirationTime + (fiber.pendingProps ? '*' : '') + ']',
<ide> );
<ide> if (fiber.updateQueue) {
<ide><path>packages/react-reconciler/src/ReactChildFiber.js
<ide> const FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
<ide> var REACT_ELEMENT_TYPE;
<ide> var REACT_CALL_TYPE;
<ide> var REACT_RETURN_TYPE;
<add>var REACT_FRAGMENT_TYPE;
<ide> if (typeof Symbol === 'function' && Symbol.for) {
<ide> REACT_ELEMENT_TYPE = Symbol.for('react.element');
<ide> REACT_CALL_TYPE = Symbol.for('react.call');
<ide> REACT_RETURN_TYPE = Symbol.for('react.return');
<add> REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
<ide> } else {
<ide> REACT_ELEMENT_TYPE = 0xeac7;
<ide> REACT_CALL_TYPE = 0xeac8;
<ide> REACT_RETURN_TYPE = 0xeac9;
<add> REACT_FRAGMENT_TYPE = 0xeacb;
<ide> }
<ide>
<ide> function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<*> {
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> element: ReactElement,
<ide> expirationTime: ExpirationTime,
<ide> ): Fiber {
<del> if (current === null || current.type !== element.type) {
<del> // Insert
<del> const created = createFiberFromElement(
<del> element,
<del> returnFiber.internalContextTag,
<del> expirationTime,
<del> );
<del> created.ref = coerceRef(current, element);
<del> created.return = returnFiber;
<del> return created;
<del> } else {
<add> if (current !== null && current.type === element.type) {
<ide> // Move based on index
<ide> const existing = useFiber(current, expirationTime);
<ide> existing.ref = coerceRef(current, element);
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> existing._debugOwner = element._owner;
<ide> }
<ide> return existing;
<add> } else {
<add> // Insert
<add> const created = createFiberFromElement(
<add> element,
<add> returnFiber.internalContextTag,
<add> expirationTime,
<add> );
<add> created.ref = coerceRef(current, element);
<add> created.return = returnFiber;
<add> return created;
<ide> }
<ide> }
<ide>
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> current: Fiber | null,
<ide> fragment: Iterable<*>,
<ide> expirationTime: ExpirationTime,
<add> key: null | string,
<ide> ): Fiber {
<ide> if (current === null || current.tag !== Fragment) {
<ide> // Insert
<ide> const created = createFiberFromFragment(
<ide> fragment,
<ide> returnFiber.internalContextTag,
<ide> expirationTime,
<add> key,
<ide> );
<ide> created.return = returnFiber;
<ide> return created;
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> if (typeof newChild === 'object' && newChild !== null) {
<ide> switch (newChild.$$typeof) {
<ide> case REACT_ELEMENT_TYPE: {
<del> const created = createFiberFromElement(
<del> newChild,
<del> returnFiber.internalContextTag,
<del> expirationTime,
<del> );
<del> created.ref = coerceRef(null, newChild);
<del> created.return = returnFiber;
<del> return created;
<add> if (newChild.type === REACT_FRAGMENT_TYPE) {
<add> const created = createFiberFromFragment(
<add> newChild.props.children,
<add> returnFiber.internalContextTag,
<add> expirationTime,
<add> newChild.key,
<add> );
<add> created.return = returnFiber;
<add> return created;
<add> } else {
<add> const created = createFiberFromElement(
<add> newChild,
<add> returnFiber.internalContextTag,
<add> expirationTime,
<add> );
<add> created.ref = coerceRef(null, newChild);
<add> created.return = returnFiber;
<add> return created;
<add> }
<ide> }
<ide>
<ide> case REACT_CALL_TYPE: {
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> newChild,
<ide> returnFiber.internalContextTag,
<ide> expirationTime,
<add> null,
<ide> );
<ide> created.return = returnFiber;
<ide> return created;
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> switch (newChild.$$typeof) {
<ide> case REACT_ELEMENT_TYPE: {
<ide> if (newChild.key === key) {
<add> if (newChild.type === REACT_FRAGMENT_TYPE) {
<add> return updateFragment(
<add> returnFiber,
<add> oldFiber,
<add> newChild.props.children,
<add> expirationTime,
<add> key,
<add> );
<add> }
<ide> return updateElement(
<ide> returnFiber,
<ide> oldFiber,
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> }
<ide>
<ide> if (isArray(newChild) || getIteratorFn(newChild)) {
<del> // Fragments don't have keys so if the previous key is implicit we can
<del> // update it.
<ide> if (key !== null) {
<ide> return null;
<ide> }
<del> return updateFragment(returnFiber, oldFiber, newChild, expirationTime);
<add>
<add> return updateFragment(
<add> returnFiber,
<add> oldFiber,
<add> newChild,
<add> expirationTime,
<add> null,
<add> );
<ide> }
<ide>
<ide> throwOnInvalidObjectType(returnFiber, newChild);
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> existingChildren.get(
<ide> newChild.key === null ? newIdx : newChild.key,
<ide> ) || null;
<add> if (newChild.type === REACT_FRAGMENT_TYPE) {
<add> return updateFragment(
<add> returnFiber,
<add> matchedFiber,
<add> newChild.props.children,
<add> expirationTime,
<add> newChild.key,
<add> );
<add> }
<ide> return updateElement(
<ide> returnFiber,
<ide> matchedFiber,
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> matchedFiber,
<ide> newChild,
<ide> expirationTime,
<add> null,
<ide> );
<ide> }
<ide>
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> // TODO: If key === null and child.key === null, then this only applies to
<ide> // the first item in the list.
<ide> if (child.key === key) {
<del> if (child.type === element.type) {
<add> if (
<add> child.tag === Fragment
<add> ? element.type === REACT_FRAGMENT_TYPE
<add> : child.type === element.type
<add> ) {
<ide> deleteRemainingChildren(returnFiber, child.sibling);
<ide> const existing = useFiber(child, expirationTime);
<ide> existing.ref = coerceRef(child, element);
<del> existing.pendingProps = element.props;
<add> existing.pendingProps = element.type === REACT_FRAGMENT_TYPE
<add> ? element.props.children
<add> : element.props;
<ide> existing.return = returnFiber;
<ide> if (__DEV__) {
<ide> existing._debugSource = element._source;
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> child = child.sibling;
<ide> }
<ide>
<del> const created = createFiberFromElement(
<del> element,
<del> returnFiber.internalContextTag,
<del> expirationTime,
<del> );
<del> created.ref = coerceRef(currentFirstChild, element);
<del> created.return = returnFiber;
<del> return created;
<add> if (element.type === REACT_FRAGMENT_TYPE) {
<add> const created = createFiberFromFragment(
<add> element.props.children,
<add> returnFiber.internalContextTag,
<add> expirationTime,
<add> element.key,
<add> );
<add> created.return = returnFiber;
<add> return created;
<add> } else {
<add> const created = createFiberFromElement(
<add> element,
<add> returnFiber.internalContextTag,
<add> expirationTime,
<add> );
<add> created.ref = coerceRef(currentFirstChild, element);
<add> created.return = returnFiber;
<add> return created;
<add> }
<ide> }
<ide>
<ide> function reconcileSingleCall(
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> // not as a fragment. Nested arrays on the other hand will be treated as
<ide> // fragment nodes. Recursion happens at the normal flow.
<ide>
<add> // Handle top level unkeyed fragments as if they were arrays.
<add> // This leads to an ambiguity between <>{[...]}</> and <>...</>.
<add> // We treat the ambiguous cases above the same.
<add> if (
<add> typeof newChild === 'object' &&
<add> newChild !== null &&
<add> newChild.type === REACT_FRAGMENT_TYPE &&
<add> newChild.key === null
<add> ) {
<add> newChild = newChild.props.children;
<add> }
<add>
<ide> // Handle object types
<ide> const isObject = typeof newChild === 'object' && newChild !== null;
<add>
<ide> if (isObject) {
<ide> switch (newChild.$$typeof) {
<ide> case REACT_ELEMENT_TYPE:
<ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) {
<ide> expirationTime,
<ide> ),
<ide> );
<del>
<ide> case REACT_PORTAL_TYPE:
<ide> return placeSingleChild(
<ide> reconcileSinglePortal(
<ide><path>packages/react-reconciler/src/ReactFiber.js
<ide> exports.createFiberFromElement = function(
<ide> owner = element._owner;
<ide> }
<ide>
<del> const fiber = createFiberFromElementType(
<del> element.type,
<del> element.key,
<del> internalContextTag,
<del> owner,
<del> );
<del> fiber.pendingProps = element.props;
<del> fiber.expirationTime = expirationTime;
<del>
<del> if (__DEV__) {
<del> fiber._debugSource = element._source;
<del> fiber._debugOwner = element._owner;
<del> }
<del>
<del> return fiber;
<del>};
<del>
<del>exports.createFiberFromFragment = function(
<del> elements: ReactFragment,
<del> internalContextTag: TypeOfInternalContext,
<del> expirationTime: ExpirationTime,
<del>): Fiber {
<del> // TODO: Consider supporting keyed fragments. Technically, we accidentally
<del> // support that in the existing React.
<del> const fiber = createFiber(Fragment, null, internalContextTag);
<del> fiber.pendingProps = elements;
<del> fiber.expirationTime = expirationTime;
<del> return fiber;
<del>};
<del>
<del>exports.createFiberFromText = function(
<del> content: string,
<del> internalContextTag: TypeOfInternalContext,
<del> expirationTime: ExpirationTime,
<del>): Fiber {
<del> const fiber = createFiber(HostText, null, internalContextTag);
<del> fiber.pendingProps = content;
<del> fiber.expirationTime = expirationTime;
<del> return fiber;
<del>};
<del>
<del>function createFiberFromElementType(
<del> type: mixed,
<del> key: null | string,
<del> internalContextTag: TypeOfInternalContext,
<del> debugOwner: null | Fiber,
<del>): Fiber {
<ide> let fiber;
<add> const {type, key} = element;
<ide> if (typeof type === 'function') {
<ide> fiber = shouldConstruct(type)
<ide> ? createFiber(ClassComponent, key, internalContextTag)
<ide> : createFiber(IndeterminateComponent, key, internalContextTag);
<ide> fiber.type = type;
<add> fiber.pendingProps = element.props;
<ide> } else if (typeof type === 'string') {
<ide> fiber = createFiber(HostComponent, key, internalContextTag);
<ide> fiber.type = type;
<add> fiber.pendingProps = element.props;
<ide> } else if (
<ide> typeof type === 'object' &&
<ide> type !== null &&
<ide> function createFiberFromElementType(
<ide> // we don't know if we can reuse that fiber or if we need to clone it.
<ide> // There is probably a clever way to restructure this.
<ide> fiber = ((type: any): Fiber);
<add> fiber.pendingProps = element.props;
<ide> } else {
<ide> let info = '';
<ide> if (__DEV__) {
<ide> function createFiberFromElementType(
<ide> ' You likely forgot to export your component from the file ' +
<ide> "it's defined in.";
<ide> }
<del> const ownerName = debugOwner ? getComponentName(debugOwner) : null;
<add> const ownerName = owner ? getComponentName(owner) : null;
<ide> if (ownerName) {
<ide> info += '\n\nCheck the render method of `' + ownerName + '`.';
<ide> }
<ide> function createFiberFromElementType(
<ide> info,
<ide> );
<ide> }
<add>
<add> if (__DEV__) {
<add> fiber._debugSource = element._source;
<add> fiber._debugOwner = element._owner;
<add> }
<add>
<add> fiber.expirationTime = expirationTime;
<add>
<add> return fiber;
<add>};
<add>
<add>function createFiberFromFragment(
<add> elements: ReactFragment,
<add> internalContextTag: TypeOfInternalContext,
<add> expirationTime: ExpirationTime,
<add> key: null | string,
<add>): Fiber {
<add> const fiber = createFiber(Fragment, key, internalContextTag);
<add> fiber.pendingProps = elements;
<add> fiber.expirationTime = expirationTime;
<ide> return fiber;
<ide> }
<ide>
<del>exports.createFiberFromElementType = createFiberFromElementType;
<add>exports.createFiberFromFragment = createFiberFromFragment;
<add>
<add>exports.createFiberFromText = function(
<add> content: string,
<add> internalContextTag: TypeOfInternalContext,
<add> expirationTime: ExpirationTime,
<add>): Fiber {
<add> const fiber = createFiber(HostText, null, internalContextTag);
<add> fiber.pendingProps = content;
<add> fiber.expirationTime = expirationTime;
<add> return fiber;
<add>};
<ide>
<ide> exports.createFiberFromHostInstanceForDeletion = function(): Fiber {
<ide> const fiber = createFiber(HostComponent, null, NoContext);
<ide><path>packages/react-reconciler/src/__tests__/ReactFragment-test.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> */
<add>'use strict';
<add>
<add>let React;
<add>let ReactNoop;
<add>
<add>describe('ReactFragment', () => {
<add> beforeEach(function() {
<add> jest.resetModules();
<add> React = require('react');
<add> ReactNoop = require('react-noop-renderer');
<add> });
<add>
<add> function span(prop) {
<add> return {type: 'span', children: [], prop};
<add> }
<add>
<add> function text(val) {
<add> return {text: val};
<add> }
<add>
<add> function div(...children) {
<add> children = children.map(c => (typeof c === 'string' ? {text: c} : c));
<add> return {type: 'div', children, prop: undefined};
<add> }
<add>
<add> it('should render a single child via noop renderer', () => {
<add> const element = (
<add> <React.Fragment>
<add> <span>foo</span>
<add> </React.Fragment>
<add> );
<add>
<add> ReactNoop.render(element);
<add> ReactNoop.flush();
<add>
<add> expect(ReactNoop.getChildren()).toEqual([span()]);
<add> });
<add>
<add> it('should render zero children via noop renderer', () => {
<add> const element = <React.Fragment />;
<add>
<add> ReactNoop.render(element);
<add> ReactNoop.flush();
<add>
<add> expect(ReactNoop.getChildren()).toEqual([]);
<add> });
<add>
<add> it('should render multiple children via noop renderer', () => {
<add> const element = (
<add> <React.Fragment>
<add> hello <span>world</span>
<add> </React.Fragment>
<add> );
<add>
<add> ReactNoop.render(element);
<add> ReactNoop.flush();
<add>
<add> expect(ReactNoop.getChildren()).toEqual([text('hello '), span()]);
<add> });
<add>
<add> it('should render an iterable via noop renderer', () => {
<add> const element = (
<add> <React.Fragment>
<add> {new Set([<span key="a">hi</span>, <span key="b">bye</span>])}
<add> </React.Fragment>
<add> );
<add>
<add> ReactNoop.render(element);
<add> ReactNoop.flush();
<add>
<add> expect(ReactNoop.getChildren()).toEqual([span(), span()]);
<add> });
<add>
<add> it('should preserve state of children with 1 level nesting', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <Stateful key="a" />
<add> : <React.Fragment>
<add> <Stateful key="a" />
<add> <div key="b">World</div>
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div(), div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state between top-level fragments', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>
<add> <Stateful />
<add> </React.Fragment>
<add> : <React.Fragment>
<add> <Stateful />
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state of children nested at same level', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>
<add> <React.Fragment>
<add> <React.Fragment>
<add> <Stateful key="a" />
<add> </React.Fragment>
<add> </React.Fragment>
<add> </React.Fragment>
<add> : <React.Fragment>
<add> <React.Fragment>
<add> <React.Fragment>
<add> <div />
<add> <Stateful key="a" />
<add> </React.Fragment>
<add> </React.Fragment>
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div(), div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state in non-top-level fragment nesting', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>
<add> <React.Fragment><Stateful key="a" /></React.Fragment>
<add> </React.Fragment>
<add> : <React.Fragment><Stateful key="a" /></React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state of children if nested 2 levels without siblings', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <Stateful key="a" />
<add> : <React.Fragment>
<add> <React.Fragment>
<add> <Stateful key="a" />
<add> </React.Fragment>
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state of children if nested 2 levels with siblings', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <Stateful key="a" />
<add> : <React.Fragment>
<add> <React.Fragment>
<add> <Stateful key="a" />
<add> </React.Fragment>
<add> <div />
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div(), div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state between array nested in fragment and fragment', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>
<add> <Stateful key="a" />
<add> </React.Fragment>
<add> : <React.Fragment>
<add> {[<Stateful key="a" />]}
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state between top level fragment and array', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? [<Stateful key="a" />]
<add> : <React.Fragment>
<add> <Stateful key="a" />
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state between array nested in fragment and double nested fragment', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>{[<Stateful key="a" />]}</React.Fragment>
<add> : <React.Fragment>
<add> <React.Fragment><Stateful key="a" /></React.Fragment>
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state between array nested in fragment and double nested array', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>{[<Stateful key="a" />]}</React.Fragment>
<add> : [[<Stateful key="a" />]];
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state between double nested fragment and double nested array', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment>
<add> <React.Fragment><Stateful key="a" /></React.Fragment>
<add> </React.Fragment>
<add> : [[<Stateful key="a" />]];
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state of children when the keys are different', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment key="a">
<add> <Stateful />
<add> </React.Fragment>
<add> : <React.Fragment key="b">
<add> <Stateful />
<add> <span>World</span>
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div(), span()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should not preserve state between unkeyed and keyed fragment', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <React.Fragment key="a">
<add> <Stateful />
<add> </React.Fragment>
<add> : <React.Fragment>
<add> <Stateful />
<add> </React.Fragment>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div()]);
<add> });
<add>
<add> it('should preserve state with reordering in multiple levels', function() {
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <div>
<add> <React.Fragment key="c">
<add> <span>foo</span>
<add> <div key="b">
<add> <Stateful key="a" />
<add> </div>
<add> </React.Fragment>
<add> <span>boop</span>
<add> </div>
<add> : <div>
<add> <span>beep</span>
<add> <React.Fragment key="c">
<add> <div key="b">
<add> <Stateful key="a" />
<add> </div>
<add> <span>bar</span>
<add> </React.Fragment>
<add> </div>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div(span(), div(div()), span())]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([div(span(), div(div()), span())]);
<add> });
<add>
<add> it('should not preserve state when switching to a keyed fragment to an array', function() {
<add> spyOn(console, 'error');
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? <div>
<add> {<React.Fragment key="foo"><Stateful /></React.Fragment>}<span />
<add> </div>
<add> : <div>{[<Stateful />]}<span /></div>;
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div(div(), span())]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual([]);
<add> expect(ReactNoop.getChildren()).toEqual([div(div(), span())]);
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<add> 'Each child in an array or iterator should have a unique "key" prop.',
<add> );
<add> });
<add>
<add> it('should preserve state when it does not change positions', function() {
<add> spyOn(console, 'error');
<add> var ops = [];
<add>
<add> class Stateful extends React.Component {
<add> componentDidUpdate() {
<add> ops.push('Update Stateful');
<add> }
<add>
<add> render() {
<add> return <div>Hello</div>;
<add> }
<add> }
<add>
<add> function Foo({condition}) {
<add> return condition
<add> ? [<span />, <React.Fragment><Stateful /></React.Fragment>]
<add> : [<span />, <React.Fragment><Stateful /></React.Fragment>];
<add> }
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> ReactNoop.render(<Foo condition={false} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([span(), div()]);
<add>
<add> ReactNoop.render(<Foo condition={true} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
<add> expect(ReactNoop.getChildren()).toEqual([span(), div()]);
<add> expectDev(console.error.calls.count()).toBe(3);
<add> for (let errorIndex = 0; errorIndex < 3; ++errorIndex) {
<add> expectDev(console.error.calls.argsFor(errorIndex)[0]).toContain(
<add> 'Each child in an array or iterator should have a unique "key" prop.',
<add> );
<add> }
<add> });
<add>});
<ide><path>packages/react/src/React.js
<ide> if (__DEV__) {
<ide> cloneElement = ReactElementValidator.cloneElement;
<ide> }
<ide>
<add>const REACT_FRAGMENT_TYPE =
<add> (typeof Symbol === 'function' &&
<add> Symbol.for &&
<add> Symbol.for('react.fragment')) ||
<add> 0xeacb;
<add>
<ide> var React = {
<ide> Children: {
<ide> map: ReactChildren.map,
<ide> var React = {
<ide> Component: ReactBaseClasses.Component,
<ide> PureComponent: ReactBaseClasses.PureComponent,
<ide> unstable_AsyncComponent: ReactBaseClasses.AsyncComponent,
<add> Fragment: REACT_FRAGMENT_TYPE,
<ide>
<ide> createElement: createElement,
<ide> cloneElement: cloneElement,
<ide><path>packages/react/src/ReactElementValidator.js
<ide> if (__DEV__) {
<ide> return '#text';
<ide> } else if (typeof element.type === 'string') {
<ide> return element.type;
<add> } else if (element.type === REACT_FRAGMENT_TYPE) {
<add> return 'React.Fragment';
<ide> } else {
<ide> return element.type.displayName || element.type.name || 'Unknown';
<ide> }
<ide> if (__DEV__) {
<ide> stack += ReactDebugCurrentFrame.getStackAddendum() || '';
<ide> return stack;
<ide> };
<add>
<add> var REACT_FRAGMENT_TYPE =
<add> (typeof Symbol === 'function' &&
<add> Symbol.for &&
<add> Symbol.for('react.fragment')) ||
<add> 0xeacb;
<add>
<add> var VALID_FRAGMENT_PROPS = new Map([['children', true], ['key', true]]);
<ide> }
<ide>
<ide> var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
<ide> function validatePropTypes(element) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Given a fragment, validate that it can only be provided with fragment props
<add> * @param {ReactElement} fragment
<add> */
<add>function validateFragmentProps(fragment) {
<add> currentlyValidatingElement = fragment;
<add>
<add> for (const key of Object.keys(fragment.props)) {
<add> if (!VALID_FRAGMENT_PROPS.has(key)) {
<add> warning(
<add> false,
<add> 'Invalid prop `%s` supplied to `React.Fragment`. ' +
<add> 'React.Fragment can only have `key` and `children` props.%s',
<add> key,
<add> getStackAddendum(),
<add> );
<add> break;
<add> }
<add> }
<add>
<add> if (fragment.ref !== null) {
<add> warning(
<add> false,
<add> 'Invalid attribute `ref` supplied to `React.Fragment`.%s',
<add> getStackAddendum(),
<add> );
<add> }
<add>
<add> currentlyValidatingElement = null;
<add>}
<add>
<ide> var ReactElementValidator = {
<ide> createElement: function(type, props, children) {
<del> var validType = typeof type === 'string' || typeof type === 'function';
<add> var validType =
<add> typeof type === 'string' ||
<add> typeof type === 'function' ||
<add> typeof type === 'symbol' ||
<add> typeof type === 'number';
<ide> // We warn in this case but don't throw. We expect the element creation to
<ide> // succeed and there will likely be errors in render.
<ide> if (!validType) {
<ide> var ReactElementValidator = {
<ide> }
<ide> }
<ide>
<del> validatePropTypes(element);
<add> if (typeof type === 'symbol' && type === REACT_FRAGMENT_TYPE) {
<add> validateFragmentProps(element);
<add> } else {
<add> validatePropTypes(element);
<add> }
<ide>
<ide> return element;
<ide> },
<ide><path>packages/react/src/__tests__/ReactElementValidator-test.js
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(undefined);
<ide> React.createElement(null);
<ide> React.createElement(true);
<del> React.createElement(123);
<ide> React.createElement({x: 17});
<ide> React.createElement({});
<del> expectDev(console.error.calls.count()).toBe(6);
<add> expectDev(console.error.calls.count()).toBe(5);
<ide> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: React.createElement: type is invalid -- expected a string ' +
<ide> '(for built-in components) or a class/function (for composite ' +
<ide> describe('ReactElementValidator', () => {
<ide> 'components) but got: boolean.',
<ide> );
<ide> expectDev(console.error.calls.argsFor(3)[0]).toBe(
<del> 'Warning: React.createElement: type is invalid -- expected a string ' +
<del> '(for built-in components) or a class/function (for composite ' +
<del> 'components) but got: number.',
<del> );
<del> expectDev(console.error.calls.argsFor(4)[0]).toBe(
<ide> 'Warning: React.createElement: type is invalid -- expected a string ' +
<ide> '(for built-in components) or a class/function (for composite ' +
<ide> 'components) but got: object.',
<ide> );
<del> expectDev(console.error.calls.argsFor(5)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(4)[0]).toBe(
<ide> 'Warning: React.createElement: type is invalid -- expected a string ' +
<ide> '(for built-in components) or a class/function (for composite ' +
<ide> 'components) but got: object. You likely forgot to export your ' +
<ide> "component from the file it's defined in.",
<ide> );
<ide> React.createElement('div');
<del> expectDev(console.error.calls.count()).toBe(6);
<add> expectDev(console.error.calls.count()).toBe(5);
<ide> });
<ide>
<ide> it('includes the owner name when passing null, undefined, boolean, or number', () => {
<ide><path>packages/react/src/__tests__/ReactJSXElementValidator-test.js
<ide>
<ide> // TODO: All these warnings should become static errors using Flow instead
<ide> // of dynamic errors when using JSX with Flow.
<del>
<ide> var React;
<ide> var ReactDOM;
<ide> var ReactTestUtils;
<ide> describe('ReactJSXElementValidator', () => {
<ide> it('warns for keys for arrays of elements in children position', () => {
<ide> spyOn(console, 'error');
<ide>
<del> void <Component>{[<Component />, <Component />]}</Component>;
<add> ReactTestUtils.renderIntoDocument(
<add> <Component>{[<Component />, <Component />]}</Component>,
<add> );
<ide>
<ide> expectDev(console.error.calls.count()).toBe(1);
<ide> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> describe('ReactJSXElementValidator', () => {
<ide> );
<ide> });
<ide>
<add> it('warns for fragments with illegal attributes', () => {
<add> spyOn(console, 'error');
<add>
<add> class Foo extends React.Component {
<add> render() {
<add> return <React.Fragment a={1} b={2}>hello</React.Fragment>;
<add> }
<add> }
<add>
<add> ReactTestUtils.renderIntoDocument(<Foo />);
<add>
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('Invalid prop `');
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<add> '` supplied to `React.Fragment`. React.Fragment ' +
<add> 'can only have `key` and `children` props.',
<add> );
<add> });
<add>
<add> it('warns for fragments with refs', () => {
<add> spyOn(console, 'error');
<add>
<add> class Foo extends React.Component {
<add> render() {
<add> return (
<add> <React.Fragment
<add> ref={bar => {
<add> this.foo = bar;
<add> }}>
<add> hello
<add> </React.Fragment>
<add> );
<add> }
<add> }
<add>
<add> ReactTestUtils.renderIntoDocument(<Foo />);
<add>
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<add> 'Invalid attribute `ref` supplied to `React.Fragment`.',
<add> );
<add> });
<add>
<ide> it('warns for keys for iterables of elements in rest args', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> describe('ReactJSXElementValidator', () => {
<ide> },
<ide> };
<ide>
<del> void <Component>{iterable}</Component>;
<add> ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>);
<ide>
<ide> expectDev(console.error.calls.count()).toBe(1);
<ide> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.',
<ide> );
<ide> });
<ide>
<del> it('does not warns for arrays of elements with keys', () => {
<add> it('does not warn for fragments of multiple elements without keys', () => {
<add> ReactTestUtils.renderIntoDocument(
<add> <React.Fragment>
<add> <span>1</span>
<add> <span>2</span>
<add> </React.Fragment>,
<add> );
<add> });
<add>
<add> it('warns for fragments of multiple elements with same key', () => {
<ide> spyOn(console, 'error');
<ide>
<del> void (
<del> <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>
<add> ReactTestUtils.renderIntoDocument(
<add> <React.Fragment>
<add> <span key="a">1</span>
<add> <span key="a">2</span>
<add> <span key="b">3</span>
<add> </React.Fragment>,
<add> );
<add>
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<add> 'Encountered two children with the same key, `a`.',
<add> );
<add> });
<add>
<add> it('does not warn for arrays of elements with keys', () => {
<add> spyOn(console, 'error');
<add>
<add> ReactTestUtils.renderIntoDocument(
<add> <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>,
<ide> );
<ide>
<ide> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<del> it('does not warns for iterable elements with keys', () => {
<add> it('does not warn for iterable elements with keys', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> var iterable = {
<ide> describe('ReactJSXElementValidator', () => {
<ide> },
<ide> };
<ide>
<del> void <Component>{iterable}</Component>;
<add> ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>);
<ide>
<ide> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide> describe('ReactJSXElementValidator', () => {
<ide> };
<ide> iterable.entries = iterable['@@iterator'];
<ide>
<del> void <Component>{iterable}</Component>;
<add> ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>);
<ide>
<ide> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the element is directly as children', () => {
<del> spyOn(console, 'error');
<del>
<del> void <Component><Component /><Component /></Component>;
<del>
<del> expectDev(console.error.calls.count()).toBe(0);
<add> ReactTestUtils.renderIntoDocument(
<add> <Component>
<add> <Component />
<add> <Component />
<add> </Component>,
<add> );
<ide> });
<ide>
<ide> it('does not warn when the child array contains non-elements', () => {
<del> spyOn(console, 'error');
<del>
<ide> void <Component>{[{}, {}]}</Component>;
<del>
<del> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should give context for PropType errors in nested components.', () => {
<ide> describe('ReactJSXElementValidator', () => {
<ide> var Undefined = undefined;
<ide> var Null = null;
<ide> var True = true;
<del> var Num = 123;
<ide> var Div = 'div';
<ide> spyOn(console, 'error');
<ide> void <Undefined />;
<ide> void <Null />;
<ide> void <True />;
<del> void <Num />;
<del> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.count()).toBe(3);
<ide> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: React.createElement: type is invalid -- expected a string ' +
<ide> '(for built-in components) or a class/function (for composite ' +
<ide> describe('ReactJSXElementValidator', () => {
<ide> 'components) but got: boolean.' +
<ide> '\n\nCheck your code at **.',
<ide> );
<del> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(3)[0])).toBe(
<del> 'Warning: React.createElement: type is invalid -- expected a string ' +
<del> '(for built-in components) or a class/function (for composite ' +
<del> 'components) but got: number.' +
<del> '\n\nCheck your code at **.',
<del> );
<ide> void <Div />;
<del> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.count()).toBe(3);
<ide> });
<ide>
<ide> it('should check default prop values', () => { | 10 |
Go | Go | make ipam work even without a backing store | 4289ea637a9025837327fa733cc4fac27715ff49 | <ide><path>libnetwork/ipam/allocator.go
<ide> func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) {
<ide> {localAddressSpace, lcDs},
<ide> {globalAddressSpace, glDs},
<ide> } {
<del> if aspc.ds == nil {
<del> continue
<del> }
<ide> a.initializeAddressSpace(aspc.as, aspc.ds)
<ide> }
<ide>
<ide> func (a *Allocator) checkConsistency(as string) {
<ide> }
<ide>
<ide> func (a *Allocator) initializeAddressSpace(as string, ds datastore.DataStore) error {
<add> scope := ""
<add> if ds != nil {
<add> scope = ds.Scope()
<add> }
<add>
<ide> a.Lock()
<ide> if _, ok := a.addrSpaces[as]; ok {
<ide> a.Unlock()
<ide> func (a *Allocator) initializeAddressSpace(as string, ds datastore.DataStore) er
<ide> a.addrSpaces[as] = &addrSpace{
<ide> subnets: map[SubnetKey]*PoolData{},
<ide> id: dsConfigKey + "/" + as,
<del> scope: ds.Scope(),
<add> scope: scope,
<ide> ds: ds,
<ide> alloc: a,
<ide> }
<ide> func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error {
<ide> //log.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String())
<ide>
<ide> store := a.getStore(key.AddressSpace)
<del> if store == nil {
<del> return types.InternalErrorf("could not find store for address space %s while inserting bit mask", key.AddressSpace)
<del> }
<del>
<ide> ipVer := getAddressVersion(pool.IP)
<ide> ones, bits := pool.Mask.Size()
<ide> numAddresses := uint64(1 << uint(bits-ones))
<ide><path>libnetwork/ipam/store.go
<ide> func (a *Allocator) getStore(as string) datastore.DataStore {
<ide>
<ide> func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) {
<ide> store := a.getStore(as)
<add>
<add> // IPAM may not have a valid store. In such cases it is just in-memory state.
<ide> if store == nil {
<del> return nil, types.InternalErrorf("store for address space %s not found", as)
<add> return nil, nil
<ide> }
<ide>
<ide> pc := &addrSpace{id: dsConfigKey + "/" + as, ds: store, alloc: a}
<ide> func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) {
<ide>
<ide> func (a *Allocator) writeToStore(aSpace *addrSpace) error {
<ide> store := aSpace.store()
<add>
<add> // IPAM may not have a valid store. In such cases it is just in-memory state.
<ide> if store == nil {
<del> return types.InternalErrorf("invalid store while trying to write %s address space", aSpace.DataScope())
<add> return nil
<ide> }
<ide>
<ide> err := store.PutObjectAtomic(aSpace)
<ide> func (a *Allocator) writeToStore(aSpace *addrSpace) error {
<ide>
<ide> func (a *Allocator) deleteFromStore(aSpace *addrSpace) error {
<ide> store := aSpace.store()
<add>
<add> // IPAM may not have a valid store. In such cases it is just in-memory state.
<ide> if store == nil {
<del> return types.InternalErrorf("invalid store while trying to delete %s address space", aSpace.DataScope())
<add> return nil
<ide> }
<ide>
<ide> return store.DeleteObjectAtomic(aSpace) | 2 |
Javascript | Javascript | remove create-subscription from the list | df5d32f230fea7b2ca1e1ddcb78efd6c3f8d7ef2 | <ide><path>ReactVersions.js
<ide> const ReactVersion = '18.1.0';
<ide> const nextChannelLabel = 'next';
<ide>
<ide> const stablePackages = {
<del> 'create-subscription': ReactVersion,
<ide> 'eslint-plugin-react-hooks': '4.5.0',
<ide> 'jest-react': '0.13.1',
<ide> react: ReactVersion, | 1 |
Go | Go | add better comments to utils/stdcopy.go | e32debcf5fb6bf056a871930a8a88d545653e96f | <ide><path>utils/stdcopy.go
<ide> func (w *StdWriter) Write(buf []byte) (n int, err error) {
<ide> return n - StdWriterPrefixLen, err
<ide> }
<ide>
<del>// NewStdWriter instanciate a new Writer based on the given type `t`.
<del>// the utils package contains the valid parametres for `t`:
<add>// NewStdWriter instanciates a new Writer.
<add>// Everything written to it will be encapsulated using a custom format,
<add>// and written to the underlying `w` stream.
<add>// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection.
<add>// `t` indicates the id of the stream to encapsulate.
<add>// It can be utils.Stdin, utils.Stdout, utils.Stderr.
<ide> func NewStdWriter(w io.Writer, t StdType) *StdWriter {
<ide> if len(t) != StdWriterPrefixLen {
<ide> return nil
<ide> var ErrInvalidStdHeader = errors.New("Unrecognized input header")
<ide>
<ide> // StdCopy is a modified version of io.Copy.
<ide> //
<del>// StdCopy copies from src to dstout or dsterr until either EOF is reached
<del>// on src or an error occurs. It returns the number of bytes
<del>// copied and the first error encountered while copying, if any.
<add>// StdCopy will demultiplex `src`, assuming that it contains two streams,
<add>// previously multiplexed together using a StdWriter instance.
<add>// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`.
<ide> //
<del>// A successful Copy returns err == nil, not err == EOF.
<del>// Because Copy is defined to read from src until EOF, it does
<del>// not treat an EOF from Read as an error to be reported.
<add>// StdCopy will read until it hits EOF on `src`. It will then return a nil error.
<add>// In other words: if `err` is non nil, it indicates a real underlying error.
<ide> //
<del>// The source needs to be writter via StdWriter, dstout or dsterr is selected
<del>// based on the prefix added by StdWriter
<add>// `written` will hold the total number of bytes written to `dstout` and `dsterr`.
<ide> func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) {
<ide> var (
<ide> buf = make([]byte, 32*1024+StdWriterPrefixLen+1) | 1 |
Ruby | Ruby | add two new unpack strategies | 2a63d363c2d49c6fbf4f6f5a53cd73701a63e997 | <ide><path>Library/Homebrew/unpack_strategy.rb
<ide> class UnpackStrategy
<ide> def self.strategies
<ide> @strategies ||= [
<ide> JarUnpackStrategy,
<add> LuaRockUnpackStrategy,
<add> MicrosoftOfficeXmlUnpackStrategy,
<ide> ZipUnpackStrategy,
<ide> XarUnpackStrategy,
<ide> CompressUnpackStrategy,
<ide> def extract_to_dir(unpack_dir, basename:)
<ide> end
<ide> end
<ide>
<add>class MicrosoftOfficeXmlUnpackStrategy < UncompressedUnpackStrategy
<add> def self.can_extract?(path:, magic_number:)
<add> return false unless ZipUnpackStrategy.can_extract?(path: path, magic_number: magic_number)
<add>
<add> # Check further if the ZIP is a Microsoft Office XML document.
<add> magic_number.match?(/\APK\003\004/n) &&
<add> magic_number.match?(%r{\A.{30}(\[Content_Types\]\.xml|_rels/\.rels)}n)
<add> end
<add>end
<add>
<add>class LuaRockUnpackStrategy < UncompressedUnpackStrategy
<add> def self.can_extract?(path:, magic_number:)
<add> return false unless ZipUnpackStrategy.can_extract?(path: path, magic_number: magic_number)
<add>
<add> # Check further if the ZIP is a LuaRocks package.
<add> out, _, status = Open3.capture3("zipinfo", "-1", path)
<add> status.success? && out.split("\n").any? { |line| line.match?(%r{\A[^/]+.rockspec\Z}) }
<add> end
<add>end
<add>
<ide> class JarUnpackStrategy < UncompressedUnpackStrategy
<ide> def self.can_extract?(path:, magic_number:)
<ide> return false unless ZipUnpackStrategy.can_extract?(path: path, magic_number: magic_number) | 1 |
Java | Java | eliminate need for rxjava in json encoder | b11bef7a26bb7733868df2b92d6e0f41856d71d6 | <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/codec/encoder/JsonObjectEncoder.java
<ide>
<ide> package org.springframework.reactive.codec.encoder;
<ide>
<del>import java.nio.ByteBuffer;
<del>
<ide> import org.reactivestreams.Publisher;
<del>import reactor.rx.Promise;
<del>import rx.Observable;
<del>import rx.RxReactiveStreams;
<del>
<add>import org.reactivestreams.Subscriber;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.reactive.codec.decoder.JsonObjectDecoder;
<add>import org.springframework.util.ClassUtils;
<add>
<add>import reactor.core.subscriber.SubscriberBarrier;
<add>import reactor.io.buffer.Buffer;
<add>import reactor.rx.Promise;
<add>import rx.Observable;
<add>
<add>import java.nio.ByteBuffer;
<add>import java.util.Arrays;
<add>
<add>import static reactor.Publishers.*;
<ide>
<ide> /**
<ide> * Encode a bye stream of individual JSON element to a byte stream representing a single
<ide> * JSON array when {@code Hints.ENCODE_AS_ARRAY} is enabled.
<ide> *
<ide> * @author Sebastien Deleuze
<add> * @author Stephane Maldini
<add> *
<ide> * @see JsonObjectDecoder
<ide> */
<ide> public class JsonObjectEncoder implements MessageToByteEncoder<ByteBuffer> {
<ide>
<del> private final ByteBuffer START_ARRAY = ByteBuffer.wrap("[".getBytes());
<add> private static final boolean rxJava1Present =
<add> ClassUtils.isPresent("rx.Observable", JsonObjectEncoder.class.getClassLoader());
<add>
<add> private static final boolean reactorPresent =
<add> ClassUtils.isPresent("reactor.rx.Promise", JsonObjectEncoder.class.getClassLoader());
<ide>
<del> private final ByteBuffer END_ARRAY = ByteBuffer.wrap("]".getBytes());
<add> final ByteBuffer START_ARRAY = ByteBuffer.wrap("[".getBytes());
<ide>
<del> private final ByteBuffer COMMA = ByteBuffer.wrap(",".getBytes());
<add> final ByteBuffer END_ARRAY = ByteBuffer.wrap("]".getBytes());
<add>
<add> final ByteBuffer COMMA = ByteBuffer.wrap(",".getBytes());
<ide>
<ide>
<ide> @Override
<ide> public boolean canEncode(ResolvableType type, MediaType mediaType, Object... hints) {
<del> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) && !Promise.class.isAssignableFrom(type.getRawClass()) &&
<del> (Observable.class.isAssignableFrom(type.getRawClass()) || Publisher.class.isAssignableFrom(type.getRawClass()));
<add> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) &&
<add> !(reactorPresent && Promise.class.isAssignableFrom(type.getRawClass())) &&
<add> (rxJava1Present && Observable.class.isAssignableFrom(type.getRawClass())
<add> || Publisher.class.isAssignableFrom(type.getRawClass()));
<ide> }
<ide>
<ide> @Override
<del> public Publisher<ByteBuffer> encode(Publisher<? extends ByteBuffer> messageStream, ResolvableType type, MediaType mediaType, Object... hints) {
<del> // TODO We use RxJava Observable because there is no skipLast() operator in Reactor
<del> // TODO Merge some chunks, there is no need to have chunks with only '[', ']' or ',' characters
<del> return RxReactiveStreams.toPublisher(
<del> Observable.concat(
<del> Observable.just(START_ARRAY),
<del> RxReactiveStreams.toObservable(messageStream).flatMap(b -> Observable.just(b, COMMA)).skipLast(1),
<del> Observable.just(END_ARRAY)));
<add> public Publisher<ByteBuffer> encode(Publisher<? extends ByteBuffer> messageStream, ResolvableType type, MediaType
<add> mediaType, Object... hints) {
<add> //TODO Merge some chunks, there is no need to have chunks with only '[', ']' or ',' characters
<add> return
<add> concat(
<add> from(
<add> Arrays.<Publisher<ByteBuffer>>asList(
<add> just(START_ARRAY),
<add> lift(
<add> flatMap(messageStream, (ByteBuffer b) -> from(Arrays.asList(b, COMMA))),
<add> sub -> new SkipLastBarrier(sub)
<add> ),
<add> just(END_ARRAY)
<add> )
<add> )
<add> );
<ide> }
<ide>
<add> private static class SkipLastBarrier extends SubscriberBarrier<ByteBuffer, ByteBuffer> {
<add>
<add> public SkipLastBarrier(Subscriber<? super ByteBuffer> subscriber) {
<add> super(subscriber);
<add> }
<add>
<add> ByteBuffer prev = null;
<add>
<add> @Override
<add> protected void doNext(ByteBuffer next) {
<add> if (prev == null) {
<add> prev = next;
<add> doRequest(1);
<add> return;
<add> }
<add>
<add> ByteBuffer tmp = prev;
<add> prev = next;
<add> subscriber.onNext(tmp);
<add> }
<add>
<add> }
<ide> } | 1 |
Go | Go | fix private pulls on buildkit | c693d45acf74b87680ace0db8615f97bd6853598 | <ide><path>builder/builder-next/adapters/containerimage/pull.go
<ide> func (is *imageSource) ID() string {
<ide>
<ide> func (is *imageSource) getResolver(ctx context.Context, rfn resolver.ResolveOptionsFunc, ref string) remotes.Resolver {
<ide> opt := docker.ResolverOptions{
<del> Client: tracing.DefaultClient,
<del> Credentials: is.getCredentialsFromSession(ctx),
<add> Client: tracing.DefaultClient,
<ide> }
<ide> if rfn != nil {
<ide> opt = rfn(ref)
<ide> }
<add> opt.Credentials = is.getCredentialsFromSession(ctx)
<ide> r := docker.NewResolver(opt)
<ide> return r
<ide> } | 1 |
Text | Text | fix typo in rails 5.0 release notes – “when when” | 4c0c7cba2b112765ac9e515e353c7daadffd3d8a | <ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][active-record] for detailed changes.
<ide> gem. ([Pull Request](https://github.com/rails/rails/pull/21161))
<ide>
<ide> * Removed support for the legacy `mysql` database adapter from core. Most users should
<del> be able to use `mysql2`. It will be converted to a separate gem when when we find someone
<add> be able to use `mysql2`. It will be converted to a separate gem when we find someone
<ide> to maintain it. ([Pull Request 1](https://github.com/rails/rails/pull/22642),
<ide> [Pull Request 2](https://github.com/rails/rails/pull/22715))
<ide> | 1 |
Text | Text | move changelog to right place [skip ci] | 75216b533b301d89c3bb04768a2d0da511ee1a4e | <ide><path>activerecord/CHANGELOG.md
<del>* Save many-to-many objects based on association primary key.
<del>
<del> Fixes #20995.
<del>
<del> *himesh-r*
<del>
<ide> * Fix an issue when preloading associations with extensions.
<ide> Previously every association with extension methods was transformed into an
<ide> instance dependent scope. This is no longer the case.
<ide>
<ide> ## Rails 5.0.0.beta3 (February 24, 2016) ##
<ide>
<add>* Save many-to-many objects based on association primary key.
<add>
<add> Fixes #20995.
<add>
<add> *himesh-r*
<add>
<ide> * Ensure that mutations of the array returned from `ActiveRecord::Relation#to_a`
<ide> do not affect the original relation, by returning a duplicate array each time.
<ide> | 1 |
Text | Text | add freshbooks to list of user | 875b9ff321449414af3f59b3a9b3bfaa26287220 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * Chartboost [[@cgelman](https://github.com/cgelman) & [@dclubb](https://github.com/dclubb)]
<ide> * [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<ide> * Easy Taxi [[@caique-lima](https://github.com/caique-lima)]
<add>* [FreshBooks](https://github.com/freshbooks) [[@DinoCow](https://github.com/DinoCow)]
<ide> * [Handy](http://www.handy.com/careers/73115?gh_jid=73115&gh_src=o5qcxn) [[@marcintustin](https://github.com/marcintustin) / [@mtustin-handy](https://github.com/mtustin-handy)]
<ide> * [Jampp](https://github.com/jampp)
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)] | 1 |
Javascript | Javascript | remove sauce labs stuff for now | db299ed7614396d01a933bfb851be6e5906e598b | <ide><path>grunt/config/webdriver-jasmine.js
<del>// https://saucelabs.com/docs/platforms
<del>
<del>var browsers = [
<del> { browserName: 'chrome', platform: 'linux' },
<del>
<del> // { browserName: 'android', platform: 'Linux', version: '4.0', 'device-type': 'tablet', 'device-orientation': 'portrait' },
<del> // { browserName: 'android', platform: 'Linux', version: '4.0' },
<del> //
<del> // { browserName: 'ipad', platform: 'OS X 10.6', version: '4' },
<del> // { browserName: 'ipad', platform: 'OS X 10.8', version: '5.1' },
<del> // { browserName: 'iphone', platform: 'OS X 10.8', version: '6.1' },
<del> //
<del> // { browserName: 'firefox', version: '24', platform: 'Windows 7' },
<del> // { browserName: 'firefox', version: '19', platform: 'Windows XP' },
<del> // { browserName: 'firefox', version: '3', platform: 'Linux' },
<del> //
<del> // { browserName: 'opera', platform: 'Windows 2008', version: '12' },
<del> //
<del> // { browserName: 'internet explorer', platform: 'Windows 8', version: '10' },
<del> // { browserName: 'internet explorer', platform: 'Windows 7', version: '9' },
<del> // { browserName: 'internet explorer', platform: 'Windows 7', version: '8' },
<del> // { browserName: 'internet explorer', platform: 'Windows XP', version: '8' },
<del> // { browserName: 'internet explorer', platform: 'Windows XP', version: '7' },
<del> // { browserName: 'internet explorer', platform: 'Windows XP', version: '6' },
<del> //
<del> // { browserName: 'safari', platform: 'OS X 10.8', version: '6' },
<del> // { browserName: 'safari', platform: 'OS X 10.6', version: '5' },
<del>];
<del>
<ide> exports.local = {
<ide> webdriver: {
<ide> remote: {
<ide> exports.local = {
<ide> console.log('report.passed', report.passed)
<ide> }
<ide> }
<del>
<del>if (false)
<del>exports.saucelabs = {
<del> webdriver: {
<del> remote:{
<del> // https://github.com/admc/wd/blob/master/README.md#named-parameters
<del> user: process.env.SAUCE_USERNAME,
<del> pwd: process.env.SAUCE_ACCESS_KEY,
<del>
<del> protocol: 'http:',
<del> hostname: 'ondemand.saucelabs.com',
<del> port: '80',
<del> path: '/wd/hub'
<del> }
<del> },
<del> url: "http://127.0.0.1:9999/test/sauce-harness.html",
<del> onComplete: function(report){
<del> var browser = this;
<del> // .then(function(report){return browser.sauceJobStatus(report.passed);})
<del> }
<del>} | 1 |
Text | Text | release notes for 1.7.9 | 27460db1dbb4b957825f774c0ab22803a98b714b | <ide><path>CHANGELOG.md
<add><a name="1.7.9"></a>
<add># 1.7.9 pollution-eradication (2019-11-19)
<add>
<add>## Bug Fixes
<add>- **angular.merge:** do not merge __proto__ property
<add> ([726f49](https://github.com/angular/angular.js/commit/726f49dcf6c23106ddaf5cfd5e2e592841db743a))
<add>- **ngStyle:** correctly remove old style when new style value is invalid
<add> ([5edd25](https://github.com/angular/angular.js/commit/5edd25364f617083363dc2bd61f9230b38267578),
<add> [#16860](https://github.com/angular/angular.js/issues/16860),
<add> [#16868](https://github.com/angular/angular.js/issues/16868))
<add>
<add>
<ide> <a name="1.7.8"></a>
<ide> # 1.7.8 enthusiastic-oblation (2019-03-11)
<ide> | 1 |
Text | Text | set status to "accepted" | 16f442e932e044b344cb24e46e3a61e27b736561 | <ide><path>docs/rfcs/004-decoration-ordering.md
<ide>
<ide> ## Status
<ide>
<del>Proposed
<add>Accepted
<ide>
<ide> ## Summary
<ide> | 1 |
Ruby | Ruby | define activemodel api compliance | 5ffaaa71d149c9807260c950c9a61d01fe734827 | <ide><path>actionpack/lib/action_controller/routing/generation/polymorphic_routes.rb
<ide> def polymorphic_url(record_or_hash_or_array, options = {})
<ide> end
<ide>
<ide> record = extract_record(record_or_hash_or_array)
<add> record = record.to_model if record.respond_to?(:to_model)
<ide> namespace = extract_namespace(record_or_hash_or_array)
<ide>
<ide> args = case record_or_hash_or_array
<ide><path>actionpack/lib/action_view/helpers/active_record_helper.rb
<ide> def input(record_name, method, options = {})
<ide> # * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update").
<ide> def form(record_name, options = {})
<ide> record = instance_variable_get("@#{record_name}")
<add> record = record.to_model if record.respond_to?(:to_model)
<ide>
<ide> options = options.symbolize_keys
<ide> options[:action] ||= record.new_record? ? "create" : "update"
<ide> def error_message_on(object, method, *args)
<ide> end
<ide> options.reverse_merge!(:prepend_text => '', :append_text => '', :css_class => 'formError')
<ide>
<add> object = object.to_model if object.respond_to?(:to_model)
<add>
<ide> if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) &&
<ide> (errors = obj.errors[method])
<ide> content_tag("div",
<ide> def error_messages_for(*params)
<ide> objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
<ide> end
<ide>
<add> objects.map! {|o| o.respond_to?(:to_model) ? o.to_model : o }
<add>
<ide> count = objects.inject(0) {|sum, object| sum + object.errors.count }
<ide> unless count.zero?
<ide> html = {}
<ide> def default_input_block
<ide> end
<ide> end
<ide>
<del> class InstanceTag #:nodoc:
<add> module ActiveRecordInstanceTag
<add> def object
<add> @active_model_object ||= begin
<add> object = super
<add> object.respond_to?(:to_model) ? object.to_model : object
<add> end
<add> end
<add>
<ide> def to_tag(options = {})
<ide> case column_type
<ide> when :string
<ide> def to_tag(options = {})
<ide> end
<ide>
<ide> %w(tag content_tag to_date_select_tag to_datetime_select_tag to_time_select_tag).each do |meth|
<del> without = "#{meth}_without_error_wrapping"
<del> define_method "#{meth}_with_error_wrapping" do |*args|
<del> error_wrapping(send(without, *args))
<add> define_method meth do |*|
<add> error_wrapping(super)
<ide> end
<del> alias_method_chain meth, :error_wrapping
<ide> end
<ide>
<ide> def error_wrapping(html_tag)
<ide> def column_type
<ide> object.send(:column_for_attribute, @method_name).type
<ide> end
<ide> end
<add>
<add> class InstanceTag
<add> include ActiveRecordInstanceTag
<add> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> def text_area(object_name, method, options = {})
<ide>
<ide> # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
<ide> # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
<del> # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
<del> # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
<add> # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
<add> # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
<ide> # while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
<ide> #
<ide> # ==== Gotcha
<ide> def radio_button(object_name, method, tag_value, options = {})
<ide> end
<ide> end
<ide>
<del> class InstanceTag #:nodoc:
<add> module InstanceTagMethods #:nodoc:
<add> extend ActiveSupport::Concern
<ide> include Helpers::TagHelper, Helpers::FormTagHelper
<ide>
<ide> attr_reader :method_name, :object_name
<ide> def value_before_type_cast(object)
<ide> self.class.value_before_type_cast(object, @method_name)
<ide> end
<ide>
<del> class << self
<add> module ClassMethods
<ide> def value(object, method_name)
<ide> object.send method_name unless object.nil?
<ide> end
<ide> def sanitized_method_name
<ide> end
<ide> end
<ide>
<add> class InstanceTag
<add> include InstanceTagMethods
<add> end
<add>
<ide> class FormBuilder #:nodoc:
<ide> # The methods which wrap a form helper call.
<ide> class_inheritable_accessor :field_helpers
<ide><path>actionpack/test/abstract_unit.rb
<ide> require 'action_view/test_case'
<ide> require 'action_controller/testing/integration'
<ide> require 'active_support/dependencies'
<add>require 'active_model'
<ide>
<ide> $tags[:new_base] = true
<ide>
<ide><path>actionpack/test/activerecord/render_partial_with_record_identification_test.rb
<ide> def render_with_record_collection
<ide> end
<ide>
<ide> class Game < Struct.new(:name, :id)
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> def to_param
<ide> id.to_s
<ide> end
<ide><path>actionpack/test/controller/record_identifier_test.rb
<ide> require 'abstract_unit'
<ide>
<ide> class Comment
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide>
<ide> attr_reader :id
<ide> def save; @id = 1 end
<ide><path>actionpack/test/controller/redirect_test.rb
<ide> class WorkshopsController < ActionController::Base
<ide> end
<ide>
<ide> class Workshop
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> attr_accessor :id, :new_record
<ide>
<ide> def initialize(id, new_record)
<ide><path>actionpack/test/lib/controller/fake_models.rb
<ide> require "active_model"
<ide>
<ide> class Customer < Struct.new(:name, :id)
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide>
<ide> def to_param
<ide> id.to_s
<ide> class GoodCustomer < Customer
<ide>
<ide> module Quiz
<ide> class Question < Struct.new(:name, :id)
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide>
<ide> def to_param
<ide> id.to_s
<ide><path>actionpack/test/template/active_record_helper_test.rb
<ide> class ActiveRecordHelperTest < ActionView::TestCase
<ide> tests ActionView::Helpers::ActiveRecordHelper
<ide>
<ide> silence_warnings do
<del> Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on)
<del> Post.class_eval do
<del> alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast)
<del> alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast)
<del> alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast)
<add> class Post < Struct.new(:title, :author_name, :body, :secret, :written_on)
<add> extend ActiveModel::APICompliant
<ide> end
<ide>
<del> User = Struct.new("User", :email)
<del> User.class_eval do
<del> alias_method :email_before_type_cast, :email unless respond_to?(:email_before_type_cast)
<add> class User < Struct.new(:email)
<add> extend ActiveModel::APICompliant
<ide> end
<ide>
<del> Column = Struct.new("Column", :type, :name, :human_name)
<add> class Column < Struct.new(:type, :name, :human_name)
<add> extend ActiveModel::APICompliant
<add> end
<ide> end
<ide>
<ide> class DirtyPost
<ide><path>actionpack/test/template/atom_feed_helper_test.rb
<ide> require 'abstract_unit'
<ide>
<del>Scroll = Struct.new(:id, :to_param, :title, :body, :updated_at, :created_at)
<del>Scroll.extend ActiveModel::Naming
<add>class Scroll < Struct.new(:id, :to_param, :title, :body, :updated_at, :created_at)
<add> extend ActiveModel::APICompliant
<add>
<add> def new_record?
<add> true
<add> end
<add>end
<ide>
<ide> class ScrollsController < ActionController::Base
<ide> FEEDS = {}
<ide><path>actionpack/test/template/prototype_helper_test.rb
<ide> require 'abstract_unit'
<add>require 'active_model'
<ide>
<ide> Bunny = Struct.new(:Bunny, :id)
<del>Bunny.extend ActiveModel::Naming
<add>Bunny.extend ActiveModel::APICompliant
<ide>
<ide> class Author
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<add>
<ide> attr_reader :id
<ide> def save; @id = 1 end
<ide> def new_record?; @id.nil? end
<ide> def name
<ide> end
<ide>
<ide> class Article
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> attr_reader :id
<ide> attr_reader :author_id
<ide> def save; @id = 1; @author_id = 1 end
<ide><path>actionpack/test/template/record_tag_helper_test.rb
<ide> require 'abstract_unit'
<ide>
<ide> class Post
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> def id
<ide> 45
<ide> end
<ide><path>actionpack/test/template/test_test.rb
<ide> def test_homepage_url
<ide>
<ide> def test_link_to_person
<ide> person = mock(:name => "David")
<del> person.class.extend ActiveModel::Naming
<add> person.class.extend ActiveModel::APICompliant
<ide> expects(:mocha_mock_path).with(person).returns("/people/1")
<ide> assert_equal '<a href="/people/1">David</a>', link_to_person(person)
<ide> end
<ide><path>actionpack/test/template/url_helper_test.rb
<ide> def with_restful_routing
<ide> end
<ide>
<ide> class Workshop
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> attr_accessor :id, :new_record
<ide>
<ide> def initialize(id, new_record)
<ide> def to_s
<ide> end
<ide>
<ide> class Session
<del> extend ActiveModel::Naming
<add> extend ActiveModel::APICompliant
<ide> attr_accessor :id, :workshop_id, :new_record
<ide>
<ide> def initialize(id, new_record)
<ide><path>activemodel/lib/active_model.rb
<ide> require 'active_support'
<ide>
<ide> module ActiveModel
<add> autoload :APICompliant, 'active_model/api_compliant'
<ide> autoload :Attributes, 'active_model/attributes'
<ide> autoload :Base, 'active_model/base'
<ide> autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
<ide><path>activemodel/lib/active_model/api_compliant.rb
<add>module ActiveModel
<add> module APICompliant
<add> include Naming
<add>
<add> def self.extended(klass)
<add> klass.class_eval do
<add> include Validations
<add> include InstanceMethods
<add> end
<add> end
<add>
<add> module InstanceMethods
<add> def to_model
<add> if respond_to?(:new_record?)
<add> self.class.class_eval { def to_model() self end }
<add> to_model
<add> else
<add> raise "In order to be ActiveModel API compliant, you need to define " \
<add> "a new_record? method, which should return true if it has not " \
<add> "yet been persisted."
<add> end
<add> end
<add> end
<add> end
<add>end
<ide>\ No newline at end of file
<ide><path>activerecord/lib/active_record/base.rb
<ide> def to_param
<ide> (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes
<ide> end
<ide>
<add> # Returns the ActiveRecord object when asked for its
<add> # ActiveModel-compliant representation, because ActiveRecord is
<add> # ActiveModel-compliant.
<add> def to_model
<add> self
<add> end
<add>
<ide> # Returns a cache key that can be used to identify this record.
<ide> #
<ide> # ==== Examples | 17 |
PHP | PHP | use implode instead of alias | 6b190c3d0862f9de9432edf28e939cb5e3f8637d | <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> protected function whereRowValues(Builder $query, $where)
<ide> {
<ide> $values = $this->parameterize($where['values']);
<ide>
<del> return '('.join(', ', $where['columns']).') '.$where['operator'].' ('.$values.')';
<add> return '('.implode(', ', $where['columns']).') '.$where['operator'].' ('.$values.')';
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | add git revision to extension manifests | 94810b2b5acc6b860df4dfa2881b62030806d518 | <ide><path>shells/browser/shared/build.js
<ide>
<ide> const AdmZip = require('adm-zip');
<ide> const { execSync } = require('child_process');
<add>const { readFileSync, writeFileSync } = require('fs');
<ide> const { copy, ensureDir, move, remove } = require('fs-extra');
<ide> const { join } = require('path');
<add>const { getGitCommit } = require('../../utils');
<ide>
<ide> // These files are copied along with Webpack-bundled files
<ide> // to produce the final web extension
<ide> const build = async (tempPath, manifestPath) => {
<ide> // Make temp dir
<ide> await ensureDir(zipPath);
<ide>
<add> const copiedManifestPath = join(zipPath, 'manifest.json');
<add>
<ide> // Copy unbuilt source files to zip dir to be packaged:
<ide> await copy(binPath, join(zipPath, 'build'));
<del> await copy(manifestPath, join(zipPath, 'manifest.json'));
<add> await copy(manifestPath, copiedManifestPath);
<ide> await Promise.all(
<ide> STATIC_FILES.map(file => copy(join(__dirname, file), join(zipPath, file)))
<ide> );
<ide>
<add> let manifest = JSON.parse(readFileSync(copiedManifestPath).toString());
<add> manifest.description += `\n\nCreated from revision ${getGitCommit()}`;
<add> writeFileSync(copiedManifestPath, JSON.stringify(manifest, null, 2));
<add>
<ide> // Pack the extension
<ide> const zip = new AdmZip();
<ide> zip.addLocalFolder(zipPath);
<ide><path>shells/utils.js
<ide> const { execSync } = require('child_process');
<ide> const { readFileSync } = require('fs');
<ide> const { resolve } = require('path');
<ide>
<add>function getGitCommit() {
<add> return execSync('git show -s --format=%h')
<add> .toString()
<add> .trim();
<add>}
<add>
<ide> function getGitHubURL() {
<ide> // TODO potentially replac this with an fb.me URL (if it can forward the query params)
<ide> return execSync('git remote get-url origin')
<ide> function getVersionString() {
<ide> readFileSync(resolve(__dirname, '../package.json'))
<ide> ).version;
<ide>
<del> const commit = execSync('git show -s --format=%h')
<del> .toString()
<del> .trim();
<add> const commit = getGitCommit();
<ide>
<ide> return `${packageVersion}-${commit}`;
<ide> }
<ide>
<del>module.exports = { getGitHubURL, getVersionString };
<add>module.exports = { getGitCommit, getGitHubURL, getVersionString }; | 2 |
Javascript | Javascript | fix typo in a comment | c34602007cc53211697ba7cda0b6a60a558c0bd9 | <ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> }
<ide> }
<ide>
<del> //it is less complicated to use a flag than managing and cancelling
<add> //it is less complicated to use a flag than managing and canceling
<ide> //timeouts containing multiple callbacks.
<ide> function fireDOMOperation() {
<ide> if(!fireDOMOperation.hasBeenRun) { | 1 |
Java | Java | add doonevent to single & completable | eddc153f936069c7ab94a214d04adc88fd76d93a | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> public final Completable doOnError(Consumer<? super Throwable> onError) {
<ide> Functions.EMPTY_ACTION, Functions.EMPTY_ACTION);
<ide> }
<ide>
<add> /**
<add> * Returns a Completable which calls the given onEvent callback with the (throwable) for an onError
<add> * or (null) for an onComplete signal from this Completable before delivering said signal to the downstream.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param onEvent the event callback
<add> * @return the new Completable instance
<add> * @throws NullPointerException if onEvent is null
<add> */
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Completable doOnEvent(final Consumer<? super Throwable> onEvent) {
<add> ObjectHelper.requireNonNull(onEvent, "onEvent is null");
<add> return doOnLifecycle(Functions.emptyConsumer(), new Consumer<Throwable>() {
<add> @Override
<add> public void accept(final Throwable throwable) throws Exception {
<add> onEvent.accept(throwable);
<add> }
<add> }, new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> onEvent.accept(null);
<add> }
<add> }, Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.EMPTY_ACTION);
<add> }
<add>
<ide> /**
<ide> * Returns a Completable instance that calls the various callbacks on the specific
<ide> * lifecycle events.
<ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public final Maybe<T> doOnError(Consumer<? super Throwable> onError) {
<ide> }
<ide>
<ide> /**
<del> * Calls the given onEvent callback with the (success value, null) for an onSuccess, (null, throwabe) for
<add> * Calls the given onEvent callback with the (success value, null) for an onSuccess, (null, throwable) for
<ide> * an onError or (null, null) for an onComplete signal from this Maybe before delivering said
<ide> * signal to the downstream.
<ide> * <p>
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> doOnSuccess(final Consumer<? super T> onSuccess) {
<ide> return RxJavaPlugins.onAssembly(new SingleDoOnSuccess<T>(this, onSuccess));
<ide> }
<ide>
<add> /**
<add> * Calls the shared consumer with the error sent via onError or the value
<add> * via onSuccess for each SingleObserver that subscribes to the current Single.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param onEvent the consumer called with the success value of onEvent
<add> * @return the new Single instance
<add> * @since 2.0
<add> */
<add> public final Single<T> doOnEvent(final BiConsumer<? super T, ? super Throwable> onEvent) {
<add> ObjectHelper.requireNonNull(onEvent, "onEvent is null");
<add> return RxJavaPlugins.onAssembly(new SingleDoOnEvent<T>(this, onEvent));
<add> }
<add>
<ide> /**
<ide> * Calls the shared consumer with the error sent via onError for each
<ide> * SingleObserver that subscribes to the current Single.
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDoOnEvent.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import io.reactivex.Single;
<add>import io.reactivex.SingleObserver;
<add>import io.reactivex.SingleSource;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.BiConsumer;
<add>
<add>public final class SingleDoOnEvent<T> extends Single<T> {
<add> final SingleSource<T> source;
<add>
<add> final BiConsumer<? super T, ? super Throwable> onEvent;
<add>
<add> public SingleDoOnEvent(SingleSource<T> source, BiConsumer<? super T, ? super Throwable> onEvent) {
<add> this.source = source;
<add> this.onEvent = onEvent;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(final SingleObserver<? super T> s) {
<add>
<add> source.subscribe(new SingleObserver<T>() {
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> s.onSubscribe(d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(T value) {
<add> try {
<add> onEvent.accept(value, null);
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> s.onError(ex);
<add> return;
<add> }
<add>
<add> s.onSuccess(value);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> try {
<add> onEvent.accept(null, e);
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> e = new CompositeException(ex, e);
<add> }
<add> s.onError(e);
<add> }
<add> });
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/completable/CompletableTest.java
<ide> public void run() {
<ide> exec.shutdown();
<ide> }
<ide> }
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void doOnEventNullEvent() {
<add> Completable.complete().doOnEvent(null);
<add> }
<add>
<add> @Test
<add> public void doOnEventComplete() {
<add> final AtomicInteger atomicInteger = new AtomicInteger(0);
<add>
<add> Completable.complete().doOnEvent(new Consumer<Throwable>() {
<add> @Override
<add> public void accept(final Throwable throwable) throws Exception {
<add> if (throwable == null) {
<add> atomicInteger.incrementAndGet();
<add> }
<add> }
<add> }).subscribe();
<add>
<add> assertEquals(1, atomicInteger.get());
<add> }
<add>
<add> @Test
<add> public void doOnEventError() {
<add> final AtomicInteger atomicInteger = new AtomicInteger(0);
<add>
<add> Completable.error(new RuntimeException()).doOnEvent(new Consumer<Throwable>() {
<add> @Override
<add> public void accept(final Throwable throwable) throws Exception {
<add> if (throwable != null) {
<add> atomicInteger.incrementAndGet();
<add> }
<add> }
<add> }).subscribe();
<add>
<add> assertEquals(1, atomicInteger.get());
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/single/SingleTest.java
<ide> public void testToObservable() {
<ide> ts.assertNoErrors();
<ide> ts.assertComplete();
<ide> }
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void doOnEventNullEvent() {
<add> Single.just(1).doOnEvent(null);
<add> }
<add>
<add> @Test
<add> public void doOnEventComplete() {
<add> final AtomicInteger atomicInteger = new AtomicInteger(0);
<add>
<add> Single.just(1).doOnEvent(new BiConsumer<Integer, Throwable>() {
<add> @Override
<add> public void accept(final Integer integer, final Throwable throwable) throws Exception {
<add> if (integer != null) {
<add> atomicInteger.incrementAndGet();
<add> }
<add> }
<add> }).subscribe();
<add>
<add> assertEquals(1, atomicInteger.get());
<add> }
<add>
<add> @Test
<add> public void doOnEventError() {
<add> final AtomicInteger atomicInteger = new AtomicInteger(0);
<add>
<add> Single.error(new RuntimeException()).doOnEvent(new BiConsumer<Object, Throwable>() {
<add> @Override
<add> public void accept(final Object o, final Throwable throwable) throws Exception {
<add> if (throwable != null) {
<add> atomicInteger.incrementAndGet();
<add> }
<add> }
<add> }).subscribe();
<add>
<add> assertEquals(1, atomicInteger.get());
<add> }
<ide> }
<ide> | 6 |
Javascript | Javascript | remove unused vendor assert.js | 9139df5779f6354aee03d06c458c78764a20a4be | <ide><path>vendor/assert.js
<del>// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
<del>//
<del>// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
<del>//
<del>// Originally from narwhal.js (http://narwhaljs.org)
<del>// Copyright (c) 2009 Thomas Robinson <280north.com>
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a copy
<del>// of this software and associated documentation files (the 'Software'), to
<del>// deal in the Software without restriction, including without limitation the
<del>// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
<del>// sell copies of the Software, and to permit persons to whom the Software is
<del>// furnished to do so, subject to the following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included in
<del>// all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<del>// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<del>// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<del>// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
<del>// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
<del>// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>// UTILITY
<del>// var util = require('util');
<del>var pSlice = Array.prototype.slice;
<del>
<del>// 1. The assert module provides functions that throw
<del>// AssertionError's when particular conditions are not met. The
<del>// assert module must conform to the following interface.
<del>
<del>var assert = exports;
<del>
<del>// 2. The AssertionError is defined in assert.
<del>// new assert.AssertionError({ message: message,
<del>// actual: actual,
<del>// expected: expected })
<del>
<del>assert.AssertionError = function AssertionError(options) {
<del> this.name = 'AssertionError';
<del> this.message = options.message;
<del> this.actual = options.actual;
<del> this.expected = options.expected;
<del> this.operator = options.operator;
<del> var stackStartFunction = options.stackStartFunction || fail;
<del>
<del> if (Error.captureStackTrace) {
<del> Error.captureStackTrace(this, stackStartFunction);
<del> }
<del>};
<del>// util.inherits(assert.AssertionError, Error);
<del>
<del>function replacer(key, value) {
<del> if (value === undefined) {
<del> return '' + value;
<del> }
<del> if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
<del> return value.toString();
<del> }
<del> if (typeof value === 'function' || value instanceof RegExp) {
<del> return value.toString();
<del> }
<del> return value;
<del>}
<del>
<del>function truncate(s, n) {
<del> if (typeof s == 'string') {
<del> return s.length < n ? s : s.slice(0, n);
<del> } else {
<del> return s;
<del> }
<del>}
<del>
<del>assert.AssertionError.prototype.toString = function() {
<del> if (this.message) {
<del> return [ this.name + ':', this.message ].join(' ');
<del> } else {
<del> return [
<del> this.name + ':',
<del> truncate(JSON.stringify(this.actual, replacer), 128),
<del> this.operator,
<del> truncate(JSON.stringify(this.expected, replacer), 128)
<del> ].join(' ');
<del> }
<del>};
<del>
<del>// assert.AssertionError instanceof Error
<del>
<del>assert.AssertionError.__proto__ = Error.prototype;
<del>
<del>// At present only the three keys mentioned above are used and
<del>// understood by the spec. Implementations or sub modules can pass
<del>// other keys to the AssertionError's constructor - they will be
<del>// ignored.
<del>
<del>// 3. All of the following functions must throw an AssertionError
<del>// when a corresponding condition is not met, with a message that
<del>// may be undefined if not provided. All assertion methods provide
<del>// both the actual and expected values to the assertion error for
<del>// display purposes.
<del>
<del>function fail(actual, expected, message, operator, stackStartFunction) {
<del> throw new assert.AssertionError({
<del> message: message,
<del> actual: actual,
<del> expected: expected,
<del> operator: operator,
<del> stackStartFunction: stackStartFunction
<del> });
<del>}
<del>
<del>// EXTENSION! allows for well behaved errors defined elsewhere.
<del>assert.fail = fail;
<del>
<del>// 4. Pure assertion tests whether a value is truthy, as determined
<del>// by !!guard.
<del>// assert.ok(guard, message_opt);
<del>// This statement is equivalent to assert.equal(true, guard,
<del>// message_opt);. To test strictly for the value true, use
<del>// assert.strictEqual(true, guard, message_opt);.
<del>
<del>assert.ok = function ok(value, message) {
<del> if (!!!value) fail(value, true, message, '==', assert.ok);
<del>};
<del>
<del>// 5. The equality assertion tests shallow, coercive equality with
<del>// ==.
<del>// assert.equal(actual, expected, message_opt);
<del>
<del>assert.equal = function equal(actual, expected, message) {
<del> if (actual != expected) fail(actual, expected, message, '==', assert.equal);
<del>};
<del>
<del>// 6. The non-equality assertion tests for whether two objects are not equal
<del>// with != assert.notEqual(actual, expected, message_opt);
<del>
<del>assert.notEqual = function notEqual(actual, expected, message) {
<del> if (actual == expected) {
<del> fail(actual, expected, message, '!=', assert.notEqual);
<del> }
<del>};
<del>
<del>// 7. The equivalence assertion tests a deep equality relation.
<del>// assert.deepEqual(actual, expected, message_opt);
<del>
<del>assert.deepEqual = function deepEqual(actual, expected, message) {
<del> if (!_deepEqual(actual, expected)) {
<del> fail(actual, expected, message, 'deepEqual', assert.deepEqual);
<del> }
<del>};
<del>
<del>function _deepEqual(actual, expected) {
<del> // 7.1. All identical values are equivalent, as determined by ===.
<del> if (actual === expected) {
<del> return true;
<del>
<del> } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
<del> if (actual.length != expected.length) return false;
<del>
<del> for (var i = 0; i < actual.length; i++) {
<del> if (actual[i] !== expected[i]) return false;
<del> }
<del>
<del> return true;
<del>
<del> // 7.2. If the expected value is a Date object, the actual value is
<del> // equivalent if it is also a Date object that refers to the same time.
<del> } else if (actual instanceof Date && expected instanceof Date) {
<del> return actual.getTime() === expected.getTime();
<del>
<del> // 7.3. Other pairs that do not both pass typeof value == 'object',
<del> // equivalence is determined by ==.
<del> } else if (typeof actual != 'object' && typeof expected != 'object') {
<del> return actual == expected;
<del>
<del> // 7.4. For all other Object pairs, including Array objects, equivalence is
<del> // determined by having the same number of owned properties (as verified
<del> // with Object.prototype.hasOwnProperty.call), the same set of keys
<del> // (although not necessarily the same order), equivalent values for every
<del> // corresponding key, and an identical 'prototype' property. Note: this
<del> // accounts for both named and indexed properties on Arrays.
<del> } else {
<del> return objEquiv(actual, expected);
<del> }
<del>}
<del>
<del>function isUndefinedOrNull(value) {
<del> return value === null || value === undefined;
<del>}
<del>
<del>function isArguments(object) {
<del> return Object.prototype.toString.call(object) == '[object Arguments]';
<del>}
<del>
<del>function objEquiv(a, b) {
<del> if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
<del> return false;
<del> // an identical 'prototype' property.
<del> if (a.prototype !== b.prototype) return false;
<del> //~~~I've managed to break Object.keys through screwy arguments passing.
<del> // Converting to array solves the problem.
<del> if (isArguments(a)) {
<del> if (!isArguments(b)) {
<del> return false;
<del> }
<del> a = pSlice.call(a);
<del> b = pSlice.call(b);
<del> return _deepEqual(a, b);
<del> }
<del> try {
<del> var ka = Object.keys(a),
<del> kb = Object.keys(b),
<del> key, i;
<del> } catch (e) {//happens when one is a string literal and the other isn't
<del> return false;
<del> }
<del> // having the same number of owned properties (keys incorporates
<del> // hasOwnProperty)
<del> if (ka.length != kb.length)
<del> return false;
<del> //the same set of keys (although not necessarily the same order),
<del> ka.sort();
<del> kb.sort();
<del> //~~~cheap key test
<del> for (i = ka.length - 1; i >= 0; i--) {
<del> if (ka[i] != kb[i])
<del> return false;
<del> }
<del> //equivalent values for every corresponding key, and
<del> //~~~possibly expensive deep test
<del> for (i = ka.length - 1; i >= 0; i--) {
<del> key = ka[i];
<del> if (!_deepEqual(a[key], b[key])) return false;
<del> }
<del> return true;
<del>}
<del>
<del>// 8. The non-equivalence assertion tests for any deep inequality.
<del>// assert.notDeepEqual(actual, expected, message_opt);
<del>
<del>assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
<del> if (_deepEqual(actual, expected)) {
<del> fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
<del> }
<del>};
<del>
<del>// 9. The strict equality assertion tests strict equality, as determined by ===.
<del>// assert.strictEqual(actual, expected, message_opt);
<del>
<del>assert.strictEqual = function strictEqual(actual, expected, message) {
<del> if (actual !== expected) {
<del> fail(actual, expected, message, '===', assert.strictEqual);
<del> }
<del>};
<del>
<del>// 10. The strict non-equality assertion tests for strict inequality, as
<del>// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
<del>
<del>assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
<del> if (actual === expected) {
<del> fail(actual, expected, message, '!==', assert.notStrictEqual);
<del> }
<del>};
<del>
<del>function expectedException(actual, expected) {
<del> if (!actual || !expected) {
<del> return false;
<del> }
<del>
<del> if (expected instanceof RegExp) {
<del> return expected.test(actual);
<del> } else if (actual instanceof expected) {
<del> return true;
<del> } else if (expected.call({}, actual) === true) {
<del> return true;
<del> }
<del>
<del> return false;
<del>}
<del>
<del>function _throws(shouldThrow, block, expected, message) {
<del> var actual;
<del>
<del> if (typeof expected === 'string') {
<del> message = expected;
<del> expected = null;
<del> }
<del>
<del> try {
<del> block();
<del> } catch (e) {
<del> actual = e;
<del> }
<del>
<del> message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
<del> (message ? ' ' + message : '.');
<del>
<del> if (shouldThrow && !actual) {
<del> fail('Missing expected exception' + message);
<del> }
<del>
<del> if (!shouldThrow && expectedException(actual, expected)) {
<del> fail('Got unwanted exception' + message);
<del> }
<del>
<del> if ((shouldThrow && actual && expected &&
<del> !expectedException(actual, expected)) || (!shouldThrow && actual)) {
<del> throw actual;
<del> }
<del>}
<del>
<del>// 11. Expected to throw an error:
<del>// assert.throws(block, Error_opt, message_opt);
<del>
<del>assert.throws = function(block, /*optional*/error, /*optional*/message) {
<del> _throws.apply(this, [true].concat(pSlice.call(arguments)));
<del>};
<del>
<del>// EXTENSION! This is annoying to write outside this module.
<del>assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
<del> _throws.apply(this, [false].concat(pSlice.call(arguments)));
<del>};
<del>
<del>assert.ifError = function(err) { if (err) {throw err;}}; | 1 |
Text | Text | add element to create-a-stack tests | f5eb0d55fbcf5b9b2609673dcc1e5ba438043cc7 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/create-a-stack-class.md
<ide> The `peek` method should return the top element of the stack
<ide> assert(
<ide> (function () {
<ide> var test = new Stack();
<add> test.push('CS61');
<ide> test.push('CS50');
<del> return test.peek() === 'CS50';
<add> return test.peek() === 'CS50' && test.peek() === 'CS50';
<ide> })()
<ide> );
<ide> ```
<ide> The `pop` method should remove and return the top element of the stack
<ide> assert(
<ide> (function () {
<ide> var test = new Stack();
<add> test.push('CS61');
<ide> test.push('CS50');
<del> return test.pop() === 'CS50';
<add> return test.pop() === 'CS50' && test.pop() === 'CS61';
<ide> })()
<ide> );
<ide> ```
<ide> The `clear` method should remove all element from the stack
<ide> assert(
<ide> (function () {
<ide> var test = new Stack();
<add> test.push('CS61');
<ide> test.push('CS50');
<ide> test.clear();
<ide> return test.isEmpty(); | 1 |
Javascript | Javascript | check links in api docs | 91837e9fbbd27fce37719b2decaf3a3196a31171 | <ide><path>tools/doc/checkLinks.js
<ide> function findMarkdownFilesRecursively(dirPath) {
<ide>
<ide> if (
<ide> entry.isDirectory() &&
<del> entry.name !== 'api' &&
<ide> entry.name !== 'build' &&
<ide> entry.name !== 'changelogs' &&
<ide> entry.name !== 'deps' && | 1 |
Javascript | Javascript | remove onevent compatibility | ed926da691b223c23e62f8e5cdf28152038ee2b9 | <ide><path>src/events.js
<ide> emitter.listeners = function (type, listener) {
<ide> * See events.cc
<ide> */
<ide> emitter.emit = function (type, args) {
<del> if (this["on" + type] instanceof Function) {
<del> this["on" + type].apply(this, args);
<del> }
<ide> if (!this._events) return;
<ide> if (!this._events.hasOwnProperty(type)) return;
<del> for (var i = 0; i < this._events[type].length; i++) {
<del> var listener = this._events[type][i];
<del> listener.apply(this, args);
<add> var listeners = this._events[type];
<add> var length = listeners.length;
<add> for (var i = 0; i < length; i++) {
<add> listeners[i].apply(this, args);
<ide> }
<ide> };
<ide>
<ide><path>src/http.js
<ide> node.http.cat = function (url, encoding, callback) {
<ide> var status = res.statusCode == 200 ? 0 : -1;
<ide> res.setBodyEncoding(encoding);
<ide> var content = "";
<del> res.onBody = function (chunk) {
<add> res.addListener("Body", function (chunk) {
<ide> content += chunk;
<del> };
<del> res.onBodyComplete = function () {
<add> });
<add> res.addListener("BodyComplete", function () {
<ide> callback(status, content);
<del> };
<add> });
<ide> });
<ide> };
<ide>
<ide><path>test/mjsunit/test-http-client-race.js
<ide> var body2 = "";
<ide> client.get("/1").finish(function (res1) {
<ide> res1.setBodyEncoding("utf8");
<ide>
<del> res1.onBody = function (chunk) { body1 += chunk; };
<add> res1.addListener("Body", function (chunk) {
<add> body1 += chunk;
<add> });
<ide>
<del> res1.onBodyComplete = function () {
<add> res1.addListener("BodyComplete", function () {
<ide> client.get("/2").finish(function (res2) {
<ide> res2.setBodyEncoding("utf8");
<del> res2.onBody = function (chunk) { body2 += chunk; };
<del> res2.onBodyComplete = function () {
<del> server.close();
<del> };
<add> res2.addListener("Body", function (chunk) { body2 += chunk; });
<add> res2.addListener("BodyComplete", function () { server.close(); });
<ide> });
<del> };
<add> });
<ide> });
<ide>
<ide> function onExit () {
<ide><path>test/mjsunit/test-http-proxy.js
<ide> var proxy = node.http.createServer(function (req, res) {
<ide> var proxy_req = proxy_client.get(req.uri.path);
<ide> proxy_req.finish(function(proxy_res) {
<ide> res.sendHeader(proxy_res.statusCode, proxy_res.headers);
<del> proxy_res.onBody = function(chunk) {
<add> proxy_res.addListener("Body", function(chunk) {
<ide> res.sendBody(chunk);
<del> };
<del> proxy_res.onBodyComplete = function() {
<add> });
<add> proxy_res.addListener("BodyComplete", function() {
<ide> res.finish();
<ide> // node.debug("proxy res");
<del> };
<add> });
<ide> });
<ide> });
<ide> // node.debug("listen proxy")
<ide> function onLoad () {
<ide> // node.debug("got res");
<ide> assertEquals(200, res.statusCode);
<ide> res.setBodyEncoding("utf8");
<del> res.onBody = function (chunk) { body += chunk; };
<del> res.onBodyComplete = function () {
<add> res.addListener("Body", function (chunk) { body += chunk; });
<add> res.addListener("BodyComplete", function () {
<ide> proxy.close();
<ide> backend.close();
<ide> // node.debug("closed both");
<del> };
<add> });
<ide> });
<ide> }
<ide>
<ide><path>test/mjsunit/test-http-server.js
<ide> function onLoad() {
<ide>
<ide> var c = new node.tcp.Connection();
<ide> c.setEncoding("utf8");
<del> c.onConnect = function () {
<add> c.addListener("Connect", function () {
<ide> c.send( "GET /hello HTTP/1.1\r\n\r\n" );
<ide> requests_sent += 1;
<del> };
<add> });
<ide>
<del> c.onReceive = function (chunk) {
<add> c.addListener("Receive", function (chunk) {
<ide> server_response += chunk;
<ide>
<ide> if (requests_sent == 1) {
<ide> function onLoad() {
<ide> assertEquals(c.readyState, "readOnly");
<ide> requests_sent += 1;
<ide> }
<del> };
<add> });
<ide>
<del> c.onEOF = function () {
<add> c.addListener("EOF", function () {
<ide> client_got_eof = true;
<del> };
<add> });
<ide>
<del> c.onDisconnect = function () {
<add> c.addListener("Disconnect", function () {
<ide> assertEquals(c.readyState, "closed");
<del> };
<add> });
<ide>
<ide> c.connect(port);
<ide> }
<ide><path>test/mjsunit/test-http.js
<ide> function onLoad () {
<ide> this.close();
<ide> }
<ide>
<del> req.onBodyComplete = function () {
<add> req.addListener("BodyComplete", function () {
<ide> res.sendHeader(200, [["Content-Type", "text/plain"]]);
<ide> res.sendBody("The path was " + req.uri.path);
<ide> res.finish();
<ide> responses_sent += 1;
<del> };
<add> });
<ide>
<ide> //assertEquals("127.0.0.1", res.connection.remoteAddress);
<ide> }).listen(PORT);
<ide> function onLoad () {
<ide> assertEquals(200, res.statusCode);
<ide> responses_recvd += 1;
<ide> res.setBodyEncoding("utf8");
<del> res.onBody = function (chunk) { body0 += chunk; };
<add> res.addListener("Body", function (chunk) { body0 += chunk; });
<ide> });
<ide>
<ide> setTimeout(function () {
<ide> function onLoad () {
<ide> assertEquals(200, res.statusCode);
<ide> responses_recvd += 1;
<ide> res.setBodyEncoding("utf8");
<del> res.onBody = function (chunk) { body1 += chunk; };
<add> res.addListener("Body", function (chunk) { body1 += chunk; });
<ide> });
<ide> }, 1);
<ide> }
<ide><path>test/mjsunit/test-process-buffering.js
<ide> var pwd_called = false;
<ide> function pwd (callback) {
<ide> var output = "";
<ide> var process = new node.Process("pwd");
<del> process.onOutput = function (s) {
<add> process.addListener("Output", function (s) {
<ide> if (s) output += s;
<del> };
<del> process.onExit = function(c) {
<add> });
<add> process.addListener("Exit", function(c) {
<ide> assertEquals(0, c);
<ide> callback(output);
<ide> pwd_called = true;
<del> };
<add> });
<ide> }
<ide>
<ide>
<ide><path>test/mjsunit/test-process-kill.js
<ide> var exit_status = -1;
<ide> function onLoad () {
<ide> var cat = new node.Process("cat");
<ide>
<del> cat.onOutput = function (chunk) { assertEquals(null, chunk); };
<del> cat.onError = function (chunk) { assertEquals(null, chunk); };
<del> cat.onExit = function (status) { exit_status = status; };
<add> cat.addListener("Output", function (chunk) { assertEquals(null, chunk); });
<add> cat.addListener("Error", function (chunk) { assertEquals(null, chunk); });
<add> cat.addListener("Exit", function (status) { exit_status = status; });
<ide>
<ide> cat.kill();
<ide> }
<ide><path>test/mjsunit/test-process-simple.js
<ide> var cat = new node.Process("cat");
<ide> var response = "";
<ide> var exit_status = -1;
<ide>
<del>cat.onOutput = function (chunk) {
<add>cat.addListener("Output", function (chunk) {
<ide> if (chunk) {
<ide> response += chunk;
<ide> if (response === "hello world") cat.close();
<ide> }
<del>};
<del>cat.onError = function (chunk) {
<add>});
<add>cat.addListener("Error", function (chunk) {
<ide> assertEquals(null, chunk);
<del>};
<del>cat.onExit = function (status) { exit_status = status; };
<add>});
<add>cat.addListener("Exit", function (status) { exit_status = status; });
<ide>
<ide> function onLoad () {
<ide> cat.write("hello");
<ide><path>test/mjsunit/test-process-spawn-loop.js
<ide> function spawn (i) {
<ide> var p = new node.Process('python -c "print 500 * 1024 * \'C\'"');
<ide> var output = "";
<ide>
<del> p.onOutput = function(chunk) {
<add> p.addListener("Output", function(chunk) {
<ide> if (chunk) output += chunk;
<del> };
<add> });
<ide>
<del> p.onExit = function () {
<add> p.addListener("Exit", function () {
<ide> //puts(output);
<ide> if (i < N)
<ide> spawn(i+1);
<ide> else
<ide> finished = true;
<del> };
<add> });
<ide> }
<ide>
<ide> function onLoad () {
<ide><path>test/mjsunit/test-reconnecting-socket.js
<ide> var client_recv_count = 0;
<ide> function onLoad () {
<ide>
<ide> var server = node.tcp.createServer(function (socket) {
<del> socket.onConnect = function () {
<add> socket.addListener("Connect", function () {
<ide> socket.send("hello\r\n");
<del> };
<add> });
<ide>
<del> socket.onEOF = function () {
<add> socket.addListener("EOF", function () {
<ide> socket.close();
<del> };
<add> });
<ide>
<del> socket.onDisconnect = function (had_error) {
<add> socket.addListener("Disconnect", function (had_error) {
<ide> //puts("server had_error: " + JSON.stringify(had_error));
<ide> assertFalse(had_error);
<del> };
<add> });
<ide> });
<ide> server.listen(port);
<ide> var client = new node.tcp.Connection();
<ide>
<ide> client.setEncoding("UTF8");
<del> client.onConnect = function () {
<del> };
<add> client.addListener("Connect", function () {
<add> });
<ide>
<del> client.onReceive = function (chunk) {
<add> client.addListener("Receive", function (chunk) {
<ide> client_recv_count += 1;
<ide> assertEquals("hello\r\n", chunk);
<ide> client.fullClose();
<del> };
<add> });
<ide>
<del> client.onDisconnect = function (had_error) {
<add> client.addListener("Disconnect", function (had_error) {
<ide> assertFalse(had_error);
<ide> if (disconnect_count++ < N)
<ide> client.connect(port); // reconnect
<ide> else
<ide> server.close();
<del> };
<add> });
<ide>
<ide> client.connect(port);
<ide> }
<ide><path>test/mjsunit/test-tcp-pingpong.js
<ide> function pingPongTest (port, host, on_complete) {
<ide> socket.setEncoding("utf8");
<ide> socket.timeout = 0;
<ide>
<del> socket.onReceive = function (data) {
<add> socket.addListener("Receive", function (data) {
<ide> assertEquals("open", socket.readyState);
<ide> assertTrue(count <= N);
<ide> if (/PING/.exec(data)) {
<ide> socket.send("PONG");
<ide> }
<del> };
<add> });
<ide>
<del> socket.onEOF = function () {
<add> socket.addListener("EOF", function () {
<ide> assertEquals("writeOnly", socket.readyState);
<ide> socket.close();
<del> };
<add> });
<ide>
<del> socket.onDisconnect = function (had_error) {
<add> socket.addListener("Disconnect", function (had_error) {
<ide> assertFalse(had_error);
<ide> assertEquals("closed", socket.readyState);
<ide> socket.server.close();
<del> };
<add> });
<ide> });
<ide> server.listen(port, host);
<ide>
<ide> function pingPongTest (port, host, on_complete) {
<ide>
<ide> client.setEncoding("utf8");
<ide>
<del> client.onConnect = function () {
<add> client.addListener("Connect", function () {
<ide> assertEquals("open", client.readyState);
<ide> client.send("PING");
<del> };
<add> });
<ide>
<del> client.onReceive = function (data) {
<add> client.addListener("Receive", function (data) {
<ide> assertEquals("PONG", data);
<ide> count += 1;
<ide>
<ide> function pingPongTest (port, host, on_complete) {
<ide> client.send("PING");
<ide> client.close();
<ide> }
<del> };
<add> });
<ide>
<del> client.onDisconnect = function () {
<add> client.addListener("Disconnect", function () {
<ide> assertEquals(N+1, count);
<ide> assertTrue(sent_final_ping);
<ide> if (on_complete) on_complete();
<ide> tests_run += 1;
<del> };
<add> });
<ide>
<ide> assertEquals("closed", client.readyState);
<ide> client.connect(port, host); | 12 |
Ruby | Ruby | fix env.m32 when ldflags already exists | 7ec2874746bf504425946045bcbae7a103f151f8 | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def cxx
<ide>
<ide> def m64
<ide> append_to_cflags '-m64'
<del> ENV['LDFLAGS'] += '-arch x86_64'
<add> ENV.append 'LDFLAGS', '-arch x86_64'
<ide> end
<ide> def m32
<ide> append_to_cflags '-m32'
<del> ENV['LDFLAGS'] += '-arch i386'
<add> ENV.append 'LDFLAGS', '-arch i386'
<ide> end
<ide>
<ide> # i386 and x86_64 only, no PPC | 1 |
PHP | PHP | check route before calling method | ab569fb44bdb83ba250fa1cd800b6543a1414ee0 | <ide><path>src/Illuminate/Http/Request.php
<ide> public function __get($key)
<ide> {
<ide> return $this->input($key);
<ide> }
<del> else
<add> elseif ( ! is_null($this->route()))
<ide> {
<ide> return $this->route()->parameter($key);
<ide> } | 1 |
Text | Text | add subtitle to the list of all esm imports | 655c635191328f5e4d0ddf2adb9ff46d0760f301 | <ide><path>docs/getting-started/integration.md
<ide> import {
<ide> Filler,
<ide> Legend,
<ide> Title,
<del> Tooltip
<add> Tooltip,
<add> SubTitle
<ide> } from 'chart.js';
<ide>
<ide> Chart.register(
<ide> Chart.register(
<ide> Filler,
<ide> Legend,
<ide> Title,
<del> Tooltip
<add> Tooltip,
<add> SubTitle
<ide> );
<ide>
<ide> var myChart = new Chart(ctx, {...}); | 1 |
Text | Text | add guide for converting a textmate bundle | 220fe36167111a2e5fe4871f71b4cec6646432af | <ide><path>docs/converting-a-textmate-bundle.md
<add>## Converting a TextMate Bundle
<add>
<add>This guide will show you how to convert a [TextMate][TextMate] bundle to an
<add>Atom package.
<add>
<add>Converting a TextMate bundle will allow you to use its editor preferences,
<add>snippets, and colorization inside Atom.
<add>
<add>### Install apm
<add>
<add>The `apm` command line utility that ships with Atom supports converting
<add>a TextMate bundle to an Atom package.
<add>
<add>Check that you have `apm` installed by running the following command in your
<add>terminal:
<add>
<add>```sh
<add>apm help init
<add>```
<add>
<add>You should see a message print out with all the possible `apm` commands.
<add>
<add>If you do not, launch Atom and run the _Atom > Install Shell Commmands_ menu
<add>to install the `apm` and `atom` commands.
<add>
<add>### Convert the Package
<add>
<add>Let's convert the TextMate bundle for the [R][R] programming language. You can find other existing TextMate bundles [here][TextMateOrg].
<add>
<add>You can convert the R bundle with the following command:
<add>
<add>```sh
<add>apm init --package ~/.atom/packages/language-r --convert https://github.com/textmate/r.tmbundle
<add>```
<add>
<add>You can now browse to `~/.atom/packages/language-r` to see the converted bundle.
<add>
<add>:tada: Your new package is now ready to use, launch Atom and open a `.r` file in
<add>the editor to see it in action!
<add>
<add>:bulb: Consider using `apm publish` to publish this package to
<add>[atom.io][atomio].
<add>
<add>[atomio]: https://atom.io
<add>[CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets
<add>[LESS]: http://lesscss.org
<add>[plist]: http://en.wikipedia.org/wiki/Property_list
<add>[R]: http://en.wikipedia.org/wiki/R_(programming_language)
<add>[TextMate]: http://macromates.com
<add>[TextMateOrg]: https://github.com/textmate/r.tmbundle | 1 |
PHP | PHP | handle array keys with dots, fixes | 75e8cf11296c8754fc16ed118ef7aac7dbbdfcf9 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> public function __construct(TranslatorInterface $translator, array $data, array
<ide> {
<ide> $this->translator = $translator;
<ide> $this->customMessages = $messages;
<del> $this->data = $this->parseData($data);
<add> $this->data = $this->hydrateFiles($this->parseData($data));
<ide> $this->customAttributes = $customAttributes;
<ide> $this->initialRules = $rules;
<ide>
<ide> $this->setRules($rules);
<ide> }
<ide>
<ide> /**
<del> * Parse the data and hydrate the files array.
<add> * Parse the data array.
<add> *
<add> * @param array $data
<add> * @return array
<add> */
<add> public function parseData(array $data)
<add> {
<add> $newData = [];
<add>
<add> foreach ($data as $key => $value) {
<add> if (is_array($value)) {
<add> $value = $this->parseData($value);
<add> }
<add>
<add> if (Str::contains($key, '.')) {
<add> $newData[str_replace('.', '->', $key)] = $value;
<add> } else {
<add> $newData[$key] = $value;
<add> }
<add> }
<add>
<add> return $newData;
<add> }
<add>
<add> /**
<add> * Hydrate the files array.
<ide> *
<ide> * @param array $data
<ide> * @param string $arrayKey
<ide> * @return array
<ide> */
<del> protected function parseData(array $data, $arrayKey = null)
<add> protected function hydrateFiles(array $data, $arrayKey = null)
<ide> {
<ide> if (is_null($arrayKey)) {
<ide> $this->files = [];
<ide> protected function parseData(array $data, $arrayKey = null)
<ide>
<ide> unset($data[$key]);
<ide> } elseif (is_array($value)) {
<del> $this->parseData($value, $key);
<add> $this->hydrateFiles($value, $key);
<ide> }
<ide> }
<ide>
<ide> public function passes()
<ide> // rule. Any error messages will be added to the containers with each of
<ide> // the other error messages, returning true if we don't have messages.
<ide> foreach ($this->rules as $attribute => $rules) {
<add> $attribute = str_replace('\.', '->', $attribute);
<add>
<ide> foreach ($rules as $rule) {
<ide> $this->validateAttribute($attribute, $rule);
<ide>
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateImplicitEachWithAsterisksForRequiredNonExistingKey()
<ide> $this->assertFalse($v->passes());
<ide> }
<ide>
<add> public function testParsingArrayKeysWithDot()
<add> {
<add> $trans = $this->getRealTranslator();
<add>
<add> $v = new Validator($trans, ['foo' => ['bar' => ''], 'foo.bar' => 'valid'], ['foo.bar' => 'required']);
<add> $this->assertTrue($v->fails());
<add>
<add> $v = new Validator($trans, ['foo' => ['bar' => 'valid'], 'foo.bar' => ''], ['foo\.bar' => 'required']);
<add> $this->assertTrue($v->fails());
<add>
<add> $v = new Validator($trans, ['foo' => ['bar.baz' => '']], ['foo.bar\.baz' => 'required']);
<add> $this->assertTrue($v->fails());
<add>
<add> $v = new Validator($trans, ['foo' => [['bar.baz' => ''], ['bar.baz' => '']]], ['foo.*.bar\.baz' => 'required']);
<add> $this->assertTrue($v->fails());
<add> }
<add>
<ide> public function testImplicitEachWithAsterisksWithArrayValues()
<ide> {
<ide> $trans = $this->getRealTranslator(); | 2 |
Javascript | Javascript | remove test for modifier capabilities deprecation | 4c633b00e2567ea5a7a4178d770d332854f763a7 | <ide><path>packages/@ember/-internals/glimmer/tests/integration/custom-modifier-manager-test.js
<ide> moduleFor(
<ide> runTask(() => set(this.context, 'truthy', true));
<ide> }
<ide>
<del> '@test requires modifier capabilities'() {
<del> class WithoutCapabilities extends CustomModifierManager {
<del> constructor(owner) {
<del> super(owner);
<del> this.capabilities = undefined;
<del> }
<del> }
<del>
<del> let ModifierClass = setModifierManager(
<del> owner => {
<del> return new WithoutCapabilities(owner);
<del> },
<del> EmberObject.extend({
<del> didInsertElement() {},
<del> didUpdate() {},
<del> willDestroyElement() {},
<del> })
<del> );
<del>
<del> this.registerModifier(
<del> 'foo-bar',
<del> ModifierClass.extend({
<del> didUpdate() {},
<del> didInsertElement() {},
<del> willDestroyElement() {},
<del> })
<del> );
<del>
<del> expectDeprecation(() => {
<del> this.render('<h1 {{foo-bar truthy}}>hello world</h1>');
<del> }, /Custom modifier managers must define their capabilities/);
<del> }
<del>
<ide> '@test associates manager even through an inheritance structure'(assert) {
<ide> assert.expect(5);
<ide> let ModifierClass = setModifierManager( | 1 |
Ruby | Ruby | improve text_executable heuristic | dd4302ae9bd75f05be2b9a1a3b44f8925d1ea700 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def compression_type
<ide> end
<ide>
<ide> def text_executable?
<del> %r[^#!\s*.+] === open('r') { |f| f.readline }
<del> rescue EOFError
<del> false
<add> %r[^#!\s*\S+] === open('r') { |f| f.read(1024) }
<ide> end
<ide>
<ide> def incremental_hash(hasher) | 1 |
Text | Text | add small improvements to the webpacker guide | 31ad146c16bec0e1e27088d48b5cbf513c50e3ee | <ide><path>guides/source/webpacker.md
<ide> Webpacker
<ide> =========
<ide>
<del>This guide will show you how to install and use Webpacker to package JavaScript, CSS, and other assets for the client-side of your Rails application.
<add>This guide will show you how to install and use Webpacker to package JavaScript, CSS, and other assets for the client-side of your Rails application.
<ide>
<ide> After reading this guide, you will know:
<ide>
<ide> Webpacker is a Rails wrapper around the [webpack](https://webpack.js.org) build
<ide>
<ide> ### What is webpack?
<ide>
<del>The goal of webpack, or any front-end build system, is to allow you to write your front-end code in a way that is convenient for developers and then package that code in a way that is convenient for browsers. With webpack, you can manage JavaScript, CSS, and static assets like files or fonts. Webpack will allow you to write your code, reference other code in your application, transform your code, and combine your code into easily downloadable packs.
<add>The goal of webpack, or any front-end build system, is to allow you to write your front-end code in a way that is convenient for developers and then package that code in a way that is convenient for browsers. With webpack, you can manage JavaScript, CSS, and static assets like images or fonts. Webpack will allow you to write your code, reference other code in your application, transform your code, and combine your code into easily downloadable packs.
<ide>
<ide> See the [webpack documentation](https://webpack.js.org) for information.
<add>
<ide> ### How is Webpacker Different from Sprockets?
<ide>
<ide> Rails also ships with Sprockets, an asset-packaging tool whose features overlap with Webpacker. Both tools will compile your JavaScript into browser-friendly files, and minify and fingerprint them in production. Both tools allow you to incrementally change files in development.
<ide> Sprockets, which was designed to be used with Rails, is somewhat simpler to inte
<ide>
<ide> You should choose webpacker over Sprockets on a new project if you want to use NPM packages, and if you want access to the most current JavaScript features and tools. You should choose Sprockets over Webpacker for legacy applications where migration might be costly, if you want to integrate using Gems, or if you have a very small amount of code to package.
<ide>
<del>If you are familiar with Sprockets, the following guide might give you some idea of how to translate. Please note that each tool has a slightly different structure, and the concepts don't directly map onto each other
<add>If you are familiar with Sprockets, the following guide might give you some idea of how to translate. Please note that each tool has a slightly different structure, and the concepts don't directly map onto each other.
<ide>
<ide> |Task | Sprockets | Webpacker |
<ide> |------------------|-------------------|-------------------|
<ide> To use Webpacker, you must install the Yarn package manager, version 1.x or up,
<ide>
<ide> NOTE: Webpacker depends on NPM and Yarn. NPM, the Node package manager registry, is the primary repository for publishing and downloading open-source JavaScript projects, both for Node.js and browser runtimes. It is analogous to rubygems.org for Ruby gems. Yarn is a command-line utility that enables installation and management of JavaScript dependencies, much like Bundler does for Ruby.
<ide>
<del>Webpacker is installed by default in Rails 6.0 and up. In an older version, you can install it when a new project is created by adding `--webpack` to a `rails new` command. In an existing project, webpacker can be added by installing `bundle exec rails webpacker:install`. This installation command creates local files:
<add>Webpacker is installed by default in Rails 6.0 and up. In some older versions, you can install it with a new project by adding `--webpack` to the `rails new` command. In an existing project, webpacker can be added by running `bundle exec rails webpacker:install`. This installation command creates following local files:
<ide>
<del>|File |Location |Explanation |
<del>|------------------------|------------------------|------------------------------------------------------------|
<del>|Javascript Folder | `app/javascript` |A place for your front-end source |
<del>|Webpacker Configuration | `config/webpacker.yml` |Configure the Webpacker gem |
<del>|Babel Configuration | `babel.config.js` |Configuration for the https://babeljs.io JavaScript Compiler|
<del>|PostCSS Configuration | `postcss.config.js` |Configuration for the https://postcss.org CSS Post-Processor|
<del>|Browserlist | `.browserslistrc` |https://github.com/browserslist/browserslist |
<add>|File |Location |Explanation |
<add>|------------------------|------------------------|----------------------------------------------------------------------------------------------------|
<add>|Javascript Folder | `app/javascript` |A place for your front-end source |
<add>|Webpacker Configuration | `config/webpacker.yml` |Configure the Webpacker gem |
<add>|Babel Configuration | `babel.config.js` |Configuration for the [Babel](https://babeljs.io) JavaScript Compiler |
<add>|PostCSS Configuration | `postcss.config.js` |Configuration for the [PostCSS](https://postcss.org) CSS Post-Processor |
<add>|Browserlist | `.browserslistrc` |[Browserlist](https://github.com/browserslist/browserslist) manages target browsers configuration |
<ide>
<ide>
<ide> The installation also calls the `yarn` package manager, creates a `package.json` file with a basic set of packages listed, and uses Yarn to install these dependencies.
<ide> For more information about the existing integrations, see https://github.com/rai
<ide>
<ide> Usage
<ide> -----
<add>
<ide> ### Using Webpacker for JavaScript
<ide>
<ide> With Webpacker installed, by default any JavaScript file in the `app/javascripts/packs` directory will get compiled to its own pack file.
<ide> If you are using a CSS framework, you can add it to Webpacker by following the i
<ide> ### Using Webpacker for Static Assets
<ide>
<ide> The default Webpacker [configuration](https://github.com/rails/webpacker/blob/master/lib/install/config/webpacker.yml#L21) should work out of the box for static assets.
<del>The configuration includes several image and font file format extensions, allowing Webpack to include them in the generated `manifest.json` file.
<add>The configuration includes several image and font file format extensions, allowing webpack to include them in the generated `manifest.json` file.
<ide>
<ide> With webpack, static assets can be imported directly in JavaScript files. The imported value represents the URL to the asset. For example:
<ide>
<ide> As of Webpacker version 5, Webpacker is not "engine-aware," which means Webpacke
<ide>
<ide> Gem authors of Rails engines who wish to support consumers using Webpacker are encouraged to distribute frontend assets as an NPM package in addition to the gem itself and provide instructions (or an installer) to demonstrate how host apps should integrate. A good example of this approach is [Alchemy CMS](https://github.com/AlchemyCMS/alchemy_cms).
<ide>
<del>### Hot module replacement
<add>### Hot Module Replacement (HMR)
<ide>
<ide> Webpacker out-of-the-box supports HMR with webpack-dev-server and you can toggle it by setting dev_server/hmr option inside webpacker.yml.
<ide>
<del>Check out this guide for more information:
<del>
<del>https://webpack.js.org/configuration/dev-server/#devserver-hot
<del>To support HMR with React you would need to add react-hot-loader. Check out this guide for more information:
<add>Check out [webpack's documentation on DevServer](https://webpack.js.org/configuration/dev-server/#devserver-hot) for more information.
<ide>
<del>https://gaearon.github.io/react-hot-loader/getstarted/
<add>To support HMR with React you would need to add react-hot-loader. Check out [React Hot Loader's _Getting Started_ guide](https://gaearon.github.io/react-hot-loader/getstarted/).
<ide>
<del>Don't forget to disable HMR if you are not running webpack-dev-server otherwise you will get not found error for stylesheets.
<add>Don't forget to disable HMR if you are not running webpack-dev-server otherwise you will get "not found error" for stylesheets.
<ide>
<ide> Webpacker in Different Environments
<ide> -----------------------------------
<ide> Windows users will need to run these commands in a terminal separate from `bundl
<ide>
<ide> Once you start this development server, Webpacker will automatically start proxying all webpack asset requests to this server. When you stop the server, it'll revert to on-demand compilation.
<ide>
<del>The Webpacker [Documentation](https://github.com/rails/webpacker) gives information on environment variables you can use to control `webpack-dev-server`. See additional notes in the [rails/webpacker docs on the webpack-dev-server usage](https://github.com/rails/webpacker#development).
<add>The [Webpacker Documentation](https://github.com/rails/webpacker) gives information on environment variables you can use to control `webpack-dev-server`. See additional notes in the [rails/webpacker docs on the webpack-dev-server usage](https://github.com/rails/webpacker#development).
<ide>
<ide> ### Deploying Webpacker
<ide>
<del>Webpacker adds a `Webpacker:compile` task to the `assets:precompile` rake task, so any existing deploy pipeline that was using `assets:precompile` should work. The compile task will compile the packs and place them in `public/packs`.
<add>Webpacker adds a `webpacker:compile` task to the `assets:precompile` rake task, so any existing deploy pipeline that was using `assets:precompile` should work. The compile task will compile the packs and place them in `public/packs`.
<ide>
<ide> Additional Documentation
<ide> ------------------------ | 1 |
Text | Text | add area/bundles tothe list of area labels | b94d429f19b900850c3c4a91083d87dc190d4b98 | <ide><path>project/ISSUE-TRIAGE.md
<ide> have:
<ide> |---------------------------|
<ide> | area/api |
<ide> | area/builder |
<add>| area/bundles |
<ide> | area/cli |
<ide> | area/daemon |
<ide> | area/distribution | | 1 |
Python | Python | remove unneeded import | 0c7b0805b45c887733ff11a386267d5a4c6a7ecb | <ide><path>numpy/lib/recfunctions.py
<ide> from numpy import ndarray, recarray
<ide> from numpy.ma import MaskedArray
<ide> from numpy.ma.mrecords import MaskedRecords
<del>
<ide> from numpy.lib._iotools import _is_string_like
<ide>
<del>import sys
<del>if sys.version_info[0] >= 3:
<del> iterizip = zip
<del>
<ide> _check_fill_value = np.ma.core._check_fill_value
<ide>
<ide> __all__ = ['append_fields', | 1 |
Javascript | Javascript | remove yellow box from systrace | d334cdd5907359d2af0f36efd0e351bba0ec14d3 | <ide><path>Libraries/ReactNative/AppContainer.js
<ide> class AppContainer extends React.Component {
<ide>
<ide> componentDidMount(): void {
<ide> if (__DEV__) {
<del> this._subscription = RCTDeviceEventEmitter.addListener(
<del> 'toggleElementInspector',
<del> () => {
<del> const Inspector = require('Inspector');
<del> const inspector = this.state.inspector
<del> ? null
<del> : <Inspector
<del> inspectedViewTag={ReactNative.findNodeHandle(this._mainRef)}
<del> onRequestRerenderApp={(updateInspectedViewTag) => {
<del> this.setState(
<del> (s) => ({mainKey: s.mainKey + 1}),
<del> () => updateInspectedViewTag(
<del> ReactNative.findNodeHandle(this._mainRef)
<del> )
<del> );
<del> }}
<del> />;
<del> this.setState({inspector});
<del> },
<del> );
<add> if (global.__RCTProfileIsProfiling) {
<add> this._subscription = RCTDeviceEventEmitter.addListener(
<add> 'toggleElementInspector',
<add> () => {
<add> const Inspector = require('Inspector');
<add> const inspector = this.state.inspector
<add> ? null
<add> : <Inspector
<add> inspectedViewTag={ReactNative.findNodeHandle(this._mainRef)}
<add> onRequestRerenderApp={(updateInspectedViewTag) => {
<add> this.setState(
<add> (s) => ({mainKey: s.mainKey + 1}),
<add> () => updateInspectedViewTag(
<add> ReactNative.findNodeHandle(this._mainRef)
<add> )
<add> );
<add> }}
<add> />;
<add> this.setState({inspector});
<add> },
<add> );
<add> }
<ide> }
<ide> }
<ide>
<ide> class AppContainer extends React.Component {
<ide> render(): React.Element<*> {
<ide> let yellowBox = null;
<ide> if (__DEV__) {
<del> const YellowBox = require('YellowBox');
<del> yellowBox = <YellowBox />;
<add> if (!global.__RCTProfileIsProfiling) {
<add> const YellowBox = require('YellowBox');
<add> yellowBox = <YellowBox />;
<add> }
<ide> }
<ide>
<ide> return ( | 1 |
Python | Python | fix warnings imports in fixtures tests | 65c557115f6e76293c39ce7b73b62216911f9489 | <ide><path>tests/fixtures_model_package/tests.py
<ide> from __future__ import unicode_literals
<ide>
<add>import warnings
<add>
<ide> from django.core import management
<ide> from django.db import transaction
<ide> from django.test import TestCase, TransactionTestCase
<ide> def test_loaddata(self):
<ide> )
<ide>
<ide> # Load a fixture that doesn't exist
<del> import warnings
<ide> with warnings.catch_warnings(record=True):
<ide> management.call_command("loaddata", "unknown.json", verbosity=0, commit=False)
<ide>
<ide><path>tests/fixtures_regress/tests.py
<ide>
<ide> import os
<ide> import re
<add>import warnings
<ide>
<ide> from django.core.serializers.base import DeserializationError
<ide> from django.core import management
<ide> def test_loaddata_no_fixture_specified(self):
<ide>
<ide> def test_loaddata_not_existant_fixture_file(self):
<ide> stdout_output = StringIO()
<del> import warnings
<ide> with warnings.catch_warnings(record=True):
<ide> management.call_command(
<ide> 'loaddata', | 2 |
Python | Python | remove outdated merge exception | 5648119b667bf932d6f502e4c2b7c44bbbe80047 | <ide><path>keras/layers/core.py
<ide> def __init__(self, layers, mode='sum'):
<ide> '''
<ide> if len(layers) < 2:
<ide> raise Exception("Please specify two or more input layers (or containers) to merge")
<del> elif len(layers) > 2 and mode == 'mul':
<del> raise Exception("Elemwise multiplication mode can only merge two layers")
<ide> self.mode = mode
<ide> self.layers = layers
<ide> self.params = [] | 1 |
Ruby | Ruby | update 10.11 clang expectation | b505c65b78fdb481c1c40f7a1655663aabf56548 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def installed?
<ide>
<ide> def latest_version
<ide> case MacOS.version
<del> when "10.11" then "700.0.65"
<add> when "10.11" then "700.0.72"
<ide> when "10.10" then "602.0.53"
<ide> when "10.9" then "600.0.57"
<ide> when "10.8" then "503.0.40" | 1 |
Python | Python | fix typo in example of dprreader | b5995badc97230c1c57a612bcf6e76d3cb64be70 | <ide><path>src/transformers/models/dpr/modeling_dpr.py
<ide> def forward(
<ide> ... return_tensors='pt'
<ide> ... )
<ide> >>> outputs = model(**encoded_inputs)
<del> >>> start_logits = outputs.stat_logits
<add> >>> start_logits = outputs.start_logits
<ide> >>> end_logits = outputs.end_logits
<ide> >>> relevance_logits = outputs.relevance_logits
<ide> | 1 |
PHP | PHP | add merge method | 9a912d6f7da4d15144d73afc9213a5ef0f8db3e2 | <ide><path>src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php
<ide> protected function filter($data)
<ide> }
<ide>
<ide> if (is_numeric($key) && $value instanceof MergeValue) {
<del> return $this->merge($data, $index, $this->filter($value->data), $numericKeys);
<add> return $this->mergeData($data, $index, $this->filter($value->data), $numericKeys);
<ide> }
<ide>
<ide> if ($value instanceof self && is_null($value->resource)) {
<ide> protected function filter($data)
<ide> * @param bool $numericKeys
<ide> * @return array
<ide> */
<del> protected function merge($data, $index, $merge, $numericKeys)
<add> protected function mergeData($data, $index, $merge, $numericKeys)
<ide> {
<ide> if ($numericKeys) {
<ide> return $this->removeMissingValues(array_merge(
<ide> protected function when($condition, $value, $default = null)
<ide> return func_num_args() === 3 ? value($default) : new MissingValue;
<ide> }
<ide>
<add> /**
<add> * Merge a value into the array.
<add> *
<add> * @param mixed $value
<add> * @return \Illuminate\Http\Resources\MergeValue|mixed
<add> */
<add> protected function merge($value)
<add> {
<add> return $this->mergeWhen(true, $value);
<add> }
<add>
<ide> /**
<ide> * Merge a value based on a given condition.
<ide> *
<ide> * @param bool $condition
<ide> * @param mixed $value
<del> * @return \Illuminate\Http\Resources\MissingValue|mixed
<add> * @return \Illuminate\Http\Resources\MergeValue|mixed
<ide> */
<ide> protected function mergeWhen($condition, $value)
<ide> { | 1 |
PHP | PHP | add atom and textmate editor urls | aa8975c9624082fc2287359f95a68bc0f2990d64 | <ide><path>src/Error/Debugger.php
<ide> class Debugger
<ide> * @var array
<ide> */
<ide> protected $editors = [
<del> 'sublime' => 'subl://open?url=file://{file}&line={line}',
<del> 'phpstorm' => 'phpstorm://open?file={file}&line={line}',
<del> 'macvim' => 'mvim://open/?url=file://{file}&line={line}',
<add> 'atom' => 'atom://core/open/file?filename={file}&line={line}',
<ide> 'emacs' => 'emacs://open?url=file://{file}&line={line}',
<add> 'macvim' => 'mvim://open/?url=file://{file}&line={line}',
<add> 'phpstorm' => 'phpstorm://open?file={file}&line={line}',
<add> 'sublime' => 'subl://open?url=file://{file}&line={line}',
<add> 'textmate' => 'txmt://open?url=file://{file}&line={line}',
<ide> 'vscode' => 'vscode://file/{file}:{line}',
<ide> ];
<ide> | 1 |
Python | Python | fix formatting and remove unused code | d7898d586f6186459f3e8b4c016a78872fd159bc | <ide><path>spacy/util.py
<ide> import re
<ide> import os.path
<ide> import pathlib
<del>
<ide> import six
<ide> from .attrs import TAG, HEAD, DEP, ENT_IOB, ENT_TYPE
<ide>
<add>
<ide> try:
<ide> basestring
<ide> except NameError:
<ide> def split_data_name(name):
<ide> return name.split('-', 1) if '-' in name else (name, '')
<ide>
<ide>
<del>def constraint_match(constraint_string, version):
<del> # From http://github.com/spacy-io/sputnik
<del> if not constraint_string:
<del> return True
<del>
<del> constraints = [c.strip() for c in constraint_string.split(',') if c.strip()]
<del>
<del> for c in constraints:
<del> if not re.match(r'[><=][=]?\d+(\.\d+)*', c):
<del> raise ValueError('invalid constraint: %s' % c)
<del>
<del> return all(semver.match(version, c) for c in constraints)
<del>
<del>
<ide> def read_regex(path):
<ide> path = path if not isinstance(path, basestring) else pathlib.Path(path)
<ide> with path.open() as file_: | 1 |
Javascript | Javascript | fix optimizer bailing on performdocumentupdate | ada645aaa16c51b49357b161d81af51903d07cc3 | <ide><path>src/view-registry.js
<ide> class ViewRegistry {
<ide> this.nextUpdatePromise = null
<ide> this.resolveNextUpdatePromise = null
<ide>
<del> let writer
<del> while ((writer = this.documentWriters.shift())) { writer() }
<add> var writer = this.documentWriters.shift()
<add> while (writer) {
<add> writer()
<add> writer = this.documentWriters.shift()
<add> }
<ide>
<del> let reader
<add> var reader = this.documentReaders.shift()
<ide> this.documentReadInProgress = true
<del> while ((reader = this.documentReaders.shift())) { reader() }
<add> while (reader) {
<add> reader()
<add> reader = this.documentReaders.shift()
<add> }
<ide> this.documentReadInProgress = false
<ide>
<ide> // process updates requested as a result of reads
<del> while ((writer = this.documentWriters.shift())) { writer() }
<add> writer = this.documentWriters.shift()
<add> while (writer) {
<add> writer()
<add> writer = this.documentWriters.shift()
<add> }
<ide>
<ide> if (resolveNextUpdatePromise) { resolveNextUpdatePromise() }
<ide> } | 1 |
Javascript | Javascript | add skewx and skewy to the transform style options | 74f467b00a12ba2ff7008443b958e445d74dfa8d | <ide><path>Libraries/StyleSheet/TransformPropTypes.js
<ide> var TransformPropTypes = {
<ide> ReactPropTypes.shape({scaleX: ReactPropTypes.number}),
<ide> ReactPropTypes.shape({scaleY: ReactPropTypes.number}),
<ide> ReactPropTypes.shape({translateX: ReactPropTypes.number}),
<del> ReactPropTypes.shape({translateY: ReactPropTypes.number})
<add> ReactPropTypes.shape({translateY: ReactPropTypes.number}),
<add> ReactPropTypes.shape({skewX: ReactPropTypes.string}),
<add> ReactPropTypes.shape({skewY: ReactPropTypes.string})
<ide> ])
<ide> ),
<ide> transformMatrix: ReactPropTypes.arrayOf(ReactPropTypes.number),
<ide><path>Libraries/StyleSheet/precomputeStyle.js
<ide> function _precomputeTransforms(style: Object): Object {
<ide> case 'translateY':
<ide> _multiplyTransform(result, MatrixMath.reuseTranslate2dCommand, [0, value]);
<ide> break;
<add> case 'skewX':
<add> _multiplyTransform(result, MatrixMath.reuseSkewXCommand, [_convertToRadians(value)]);
<add> break;
<add> case 'skewY':
<add> _multiplyTransform(result, MatrixMath.reuseSkewYCommand, [_convertToRadians(value)]);
<add> break;
<ide> default:
<ide> throw new Error('Invalid transform name: ' + key);
<ide> }
<ide> function _validateTransform(key, value, transformation) {
<ide> case 'rotateY':
<ide> case 'rotateZ':
<ide> case 'rotate':
<add> case 'skewX':
<add> case 'skewY':
<ide> invariant(
<ide> typeof value === 'string',
<ide> 'Transform with key of "%s" must be a string: %s',
<ide><path>Libraries/Utilities/MatrixMath.js
<ide> var MatrixMath = {
<ide> return mat;
<ide> },
<ide>
<add> reuseSkewXCommand: function(matrixCommand, radians) {
<add> matrixCommand[4] = Math.sin(radians);
<add> matrixCommand[5] = Math.cos(radians);
<add> },
<add>
<add> reuseSkewYCommand: function(matrixCommand, radians) {
<add> matrixCommand[0] = Math.cos(radians);
<add> matrixCommand[1] = Math.sin(radians);
<add> },
<add>
<ide> multiplyInto: function(out, a, b) {
<ide> var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
<ide> a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], | 3 |
Javascript | Javascript | remove circular dependencies from helpers | b6c22d269a16097bc8c55d7cc01d37b7369391d4 | <ide><path>src/helpers/helpers.canvas.js
<del>import {
<del> isArray, isNullOrUndef, PI, TAU, HALF_PI, QUARTER_PI,
<del> TWO_THIRDS_PI, RAD_PER_DEG
<del>} from './index';
<add>import {isArray, isNullOrUndef} from './helpers.core';
<add>import {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math';
<ide>
<ide> /**
<ide> * @typedef { import("../core/core.controller").default } Chart
<ide><path>src/helpers/helpers.dom.js
<del>import {INFINITY} from './index';
<add>import {INFINITY} from './helpers.math';
<ide>
<ide> /**
<ide> * @private
<ide><path>src/helpers/helpers.easing.js
<del>import {PI, TAU, HALF_PI} from './index';
<add>import {PI, TAU, HALF_PI} from './helpers.math';
<ide>
<ide> /**
<ide> * Easing functions adapted from Robert Penner's easing equations. | 3 |
Ruby | Ruby | remove the mounted_helpers respond_to check | 1e7f28c985b8df78058403f6ee5df42427ccc8c1 | <ide><path>actionpack/lib/action_dispatch/testing/integration.rb
<ide> def initialize(app)
<ide> if app.respond_to?(:routes)
<ide> singleton_class.class_eval do
<ide> include app.routes.url_helpers
<del> include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
<add> include app.routes.mounted_helpers
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | remove unused code | 59e5de59d75a8d02ef64fa72c774bcf1eb89ea86 | <ide><path>lib/APIPlugin.js
<ide> const REPLACEMENT_TYPES = {
<ide> __webpack_nonce__: "string" // eslint-disable-line camelcase
<ide> };
<ide>
<del>const IGNORES = [];
<del>
<ide> class APIPlugin {
<del>
<ide> apply(compiler) {
<ide> compiler.plugin("compilation", (compilation, params) => {
<ide> compilation.dependencyFactories.set(ConstDependency, new NullFactory());
<ide> class APIPlugin {
<ide> parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
<ide> parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
<ide> });
<del> IGNORES.forEach(key => {
<del> parser.plugin(key, ParserHelpers.skipTraversal);
<del> });
<ide> });
<ide> });
<ide> }
<ide><path>lib/Dependency.js
<ide> class Dependency {
<ide> this.module = null;
<ide> }
<ide>
<add> // TODO: remove in webpack 3
<ide> compare(a, b) {
<ide> return compareLocations(a.loc, b.loc);
<ide> }
<ide><path>lib/FlagDependencyUsagePlugin.js
<ide> class FlagDependencyUsagePlugin {
<ide> }
<ide>
<ide> function processDependenciesBlock(depBlock, usedExports) {
<del> depBlock.dependencies.forEach(dep => processDependency(dep, usedExports));
<del> depBlock.variables.forEach(variable => variable.dependencies.forEach(dep => processDependency(dep, usedExports)));
<add> depBlock.dependencies.forEach(dep => processDependency(dep));
<add> depBlock.variables.forEach(variable => variable.dependencies.forEach(dep => processDependency(dep)));
<ide> depBlock.blocks.forEach(block => queue.push([block, usedExports]));
<ide> }
<ide>
<del> function processDependency(dep, usedExports) {
<add> function processDependency(dep) {
<ide> const reference = dep.getReference && dep.getReference();
<ide> if(!reference) return;
<ide> const module = reference.module;
<ide><path>lib/TemplatedPathPlugin.js
<ide> const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"),
<ide> REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"),
<ide> REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i");
<ide>
<add>// TODO: remove in webpack 3
<ide> // Backwards compatibility; expose regexes on Template object
<ide> const Template = require("./Template");
<ide> Template.REGEXP_HASH = REGEXP_HASH; | 4 |
Javascript | Javascript | remove some hardcoded glue | 4d155983c51127001df51c3e3598b642b6a6a7e8 | <ide><path>fonts.js
<ide> var Font = (function () {
<ide> idDeltas + idRangeOffsets + glyphsIds);
<ide> };
<ide>
<del> function createOS2Table() {
<add> function createOS2Table(properties) {
<ide> return "\x00\x03" + // version
<ide> "\x02\x24" + // xAvgCharWidth
<ide> "\x01\xF4" + // usWeightClass
<ide> var Font = (function () {
<ide> "\x00\x03" + // sTypoAscender
<ide> "\x00\x20" + // sTypeDescender
<ide> "\x00\x38" + // sTypoLineGap
<del> "\x00\x5A" + // usWinAscent
<del> "\x02\xB4" + // usWinDescent
<del> "\x00\xCE\x00\x00" + // ulCodePageRange1 (Bits 0-31)
<del> "\x00\x01\x00\x00" + // ulCodePageRange2 (Bits 32-63)
<del> "\x00\x00" + // sxHeight
<del> "\x00\x00" + // sCapHeight
<del> "\x00\x01" + // usDefaultChar
<del> "\x00\xCD" + // usBreakChar
<del> "\x00\x02"; // usMaxContext
<add> string16(properties.ascent) + // usWinAscent
<add> string16(properties.descent) + // usWinDescent
<add> "\x00\xCE\x00\x00" + // ulCodePageRange1 (Bits 0-31)
<add> "\x00\x01\x00\x00" + // ulCodePageRange2 (Bits 32-63)
<add> string16(properties.xHeight) + // sxHeight
<add> string16(properties.capHeight) + // sCapHeight
<add> "\x00\x01" + // usDefaultChar
<add> "\x00\xCD" + // usBreakChar
<add> "\x00\x02"; // usMaxContext
<ide> };
<ide>
<del> function createPostTable() {
<add> function createPostTable(properties) {
<ide> TODO("Fill with real values from the font dict");
<ide>
<del> return "\x00\x03\x00\x00" + // Version number
<del> "\x00\x00\x01\x00" + // italicAngle
<del> "\x00\x00" + // underlinePosition
<del> "\x00\x00" + // underlineThickness
<del> "\x00\x00\x00\x00" + // isFixedPitch
<del> "\x00\x00\x00\x00" + // minMemType42
<del> "\x00\x00\x00\x00" + // maxMemType42
<del> "\x00\x00\x00\x00" + // minMemType1
<del> "\x00\x00\x00\x00"; // maxMemType1
<add> return "\x00\x03\x00\x00" + // Version number
<add> string32(properties.italicAngle) + // italicAngle
<add> "\x00\x00" + // underlinePosition
<add> "\x00\x00" + // underlineThickness
<add> "\x00\x00\x00\x00" + // isFixedPitch
<add> "\x00\x00\x00\x00" + // minMemType42
<add> "\x00\x00\x00\x00" + // maxMemType42
<add> "\x00\x00\x00\x00" + // minMemType1
<add> "\x00\x00\x00\x00"; // maxMemType1
<ide> };
<ide>
<ide> constructor.prototype = {
<ide> var Font = (function () {
<ide> (format == 6 && numTables == 1 && !properties.encoding.empty)) {
<ide> // Format 0 alone is not allowed by the sanitizer so let's rewrite
<ide> // that to a 3-1-4 Unicode BMP table
<add> TODO("Use an other source of informations than charset here, it is not reliable");
<ide> var charset = properties.charset;
<ide> var glyphs = [];
<ide> for (var j = 0; j < charset.length; j++) {
<ide> var Font = (function () {
<ide> // Insert the missing table
<ide> tables.push({
<ide> tag: "OS/2",
<del> data: stringToArray(createOS2Table())
<add> data: stringToArray(createOS2Table(properties))
<ide> });
<ide>
<ide> // Replace the old CMAP table with a shiny new one
<ide> var Font = (function () {
<ide> if (!post) {
<ide> tables.push({
<ide> tag: "post",
<del> data: stringToArray(createPostTable())
<add> data: stringToArray(createPostTable(properties))
<ide> });
<ide> }
<ide>
<ide> var Font = (function () {
<ide> createTableEntry(otf, offsets, "CFF ", CFF);
<ide>
<ide> /** OS/2 */
<del> OS2 = stringToArray(createOS2Table());
<add> OS2 = stringToArray(createOS2Table(properties));
<ide> createTableEntry(otf, offsets, "OS/2", OS2);
<ide>
<del> //XXX Getting charstrings here seems wrong since this is another CFF glue
<del> var charstrings = font.getOrderedCharStrings(properties.glyphs);
<del>
<ide> /** CMAP */
<del> cmap = createCMapTable(charstrings);
<add> var charstrings = font.charstrings;
<add> cmap = createCMapTable(font.charstrings);
<ide> createTableEntry(otf, offsets, "cmap", cmap);
<ide>
<ide> /** HEAD */
<ide> var Font = (function () {
<ide> createTableEntry(otf, offsets, "name", name);
<ide>
<ide> /** POST */
<del> post = stringToArray(createPostTable());
<add> post = stringToArray(createPostTable(properties));
<ide> createTableEntry(otf, offsets, "post", post);
<ide>
<ide> // Once all the table entries header are written, dump the data!
<ide> var CFFStrings = [
<ide> "001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"
<ide> ];
<ide>
<add>var type1Parser = new Type1Parser();
<add>
<ide> var CFF = function(name, file, properties) {
<ide> // Get the data block containing glyphs and subrs informations
<ide> var length1 = file.dict.get("Length1");
<ide> var length2 = file.dict.get("Length2");
<ide> file.skip(length1);
<ide> var eexecBlock = file.getBytes(length2);
<ide>
<del> // Decrypt the data blocks and retrieve the informations from it
<del> var parser = new Type1Parser();
<del> var fontInfo = parser.extractFontProgram(eexecBlock);
<add> // Decrypt the data blocks and retrieve it's content
<add> var data = type1Parser.extractFontProgram(eexecBlock);
<ide>
<del> properties.subrs = fontInfo.subrs;
<del> properties.glyphs = fontInfo.charstrings;
<del> this.data = this.wrap(name, properties);
<add> this.charstrings = this.getOrderedCharStrings(data.charstrings);
<add> this.data = this.wrap(name, this.charstrings, data.subrs, properties);
<ide> };
<ide>
<ide> CFF.prototype = {
<ide> CFF.prototype = {
<ide> charstrings.push({
<ide> glyph: glyph,
<ide> unicode: unicode,
<del> charstring: glyphs[i].data.slice()
<add> charstring: glyphs[i].data
<ide> });
<ide> }
<ide> };
<ide> CFF.prototype = {
<ide> if (obj.charAt) {
<ide> switch (obj) {
<ide> case "callsubr":
<del> var subr = subrs[charstring[i - 1]].slice();
<add> var subr = subrs[charstring[i - 1]];
<ide> if (subr.length > 1) {
<ide> subr = this.flattenCharstring(glyph, subr, subrs);
<ide> subr.pop();
<ide> CFF.prototype = {
<ide> error("failing with i = " + i + " in charstring:" + charstring + "(" + charstring.length + ")");
<ide> },
<ide>
<del> wrap: function wrap(name, properties) {
<del> var charstrings = this.getOrderedCharStrings(properties.glyphs);
<del>
<add> wrap: function wrap(name, charstrings, subrs, properties) {
<ide> // Starts the conversion of the Type1 charstrings to Type2
<ide> var charstringsCount = 0;
<ide> var charstringsDataLength = 0;
<ide> var glyphs = [];
<ide> for (var i = 0; i < charstrings.length; i++) {
<del> var charstring = charstrings[i].charstring.slice();
<add> var charstring = charstrings[i].charstring;
<ide> var glyph = charstrings[i].glyph;
<ide>
<del> var flattened = this.flattenCharstring(glyph, charstring, properties.subrs);
<add> var flattened = this.flattenCharstring(glyph, charstring, subrs);
<ide> glyphs.push(flattened);
<ide> charstringsCount++;
<ide> charstringsDataLength += flattened.length;
<ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> error("Unknown font encoding");
<ide>
<ide> var index = 0;
<del> for (var j = 0; j < encoding.length; j++) {
<add> for (var j = 0; j < encoding.length; j++)
<ide> encodingMap[index++] = GlyphsUnicode[encoding[j]];
<del> }
<ide>
<ide> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar"));
<ide> var widths = xref.fetchIfRef(fontDict.get("Widths"));
<ide> var CanvasGraphics = (function() {
<ide> }
<ide>
<ide> var subType = fontDict.get("Subtype");
<del> var bbox = descriptor.get("FontBBox");
<del> assertWellFormed(IsName(subType) && IsArray(bbox),
<del> "invalid font Subtype or FontBBox");
<add> assertWellFormed(IsName(subType), "invalid font Subtype");
<ide>
<ide> var properties = {
<ide> type: subType.name,
<ide> encoding: encodingMap,
<ide> charset: charset,
<del> bbox: bbox
<add> bbox: descriptor.get("FontBBox"),
<add> ascent: descriptor.get("Ascent"),
<add> descent: descriptor.get("Descent"),
<add> xHeight: descriptor.get("XHeight"),
<add> capHeight: descriptor.get("CapHeight"),
<add> flags: descriptor.get("Flags"),
<add> italicAngle: descriptor.get("ItalicAngle")
<ide> };
<ide>
<ide> return { | 2 |
Ruby | Ruby | add stable url, tag and revision to json output | 82fde4e1e520934635aa9a6212c7954e9d68a134 | <ide><path>Library/Homebrew/formula.rb
<ide> def to_hash
<ide> "head" => head&.version&.to_s,
<ide> "bottle" => !bottle_specification.checksums.empty?,
<ide> },
<add> "urls" => {
<add> "stable" => {
<add> "url" => stable.url,
<add> "tag" => stable.specs&.dig(:tag),
<add> "revision" => stable.specs&.dig(:revision),
<add> },
<add> },
<ide> "revision" => revision,
<ide> "version_scheme" => version_scheme,
<ide> "bottle" => {}, | 1 |
Text | Text | translate description section to arabic | de1ab3dc65700d33362514498e0a1bd072094fd2 | <ide><path>curriculum/challenges/arabic/01-responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element.arabic.md
<ide> localeTitle: ''
<ide> ---
<ide>
<ide> ## Description
<del>undefined
<add>احياناً تحتاج إلى إجراء تعديل على عنصر ما بحيث أن يكون كل واحد من جهاته له <code>padding</code> بِسُمكٍ مختلف عن الآخر. تتيح لك الـ CSS بالتحكم بِسُمك الـ padding الخاص بكل جهة بِشكل مستقل عن الآخر بإستخدام الخواص <code>padding-top</code>، <code>padding-right</code>، <code>padding-bottom</code> و <code>padding-left</code>.
<ide>
<ide> ## Instructions
<ide> undefined | 1 |
PHP | PHP | fix inverted condition | fd50f0aadf3e81fd336c0ddaf0b4058650ac7ad1 | <ide><path>src/Network/Response.php
<ide> public function sendHeaders()
<ide> $this->_setCookies();
<ide> $this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
<ide>
<del> if (in_array($this->_status, [304, 204])) {
<add> if (!in_array($this->_status, [304, 204])) {
<ide> $this->_setContentType();
<ide> }
<ide> | 1 |
Text | Text | add docs about the keybindings tab | 61021b6a13bca0fec55a7279752a478b918582fc | <ide><path>docs/customizing-atom.md
<ide> By default, `~/.atom/keymap.cson` is loaded when Atom is started. It will always
<ide> be loaded last, giving you the chance to override bindings that are defined by
<ide> Atom's core keymaps or third-party packages.
<ide>
<add>You'll want to know all the commands available to you. Open the Settings panel
<add>(`cmd-,`) and select the _Keybindings_ tab. It will show you all the keybindings
<add>currently in use.
<add>
<ide> ## Advanced Configuration
<ide>
<ide> Atom loads configuration settings from the `config.cson` file in your _~/.atom_ | 1 |
Javascript | Javascript | remove deprecated lifecycles usage | ba61267015567bf180dd3272a295dc262b3e2c97 | <ide><path>Libraries/Animated/createAnimatedComponent.js
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> );
<ide>
<ide> class AnimatedComponent extends React.Component<Object> {
<add> constructor(props) {
<add> super(props);
<add> this._waitForUpdate();
<add> this._attachProps(this.props);
<add> this._lastProps = this.props;
<add> }
<add>
<ide> _component: any; // TODO T53738161: flow type this, and the whole file
<ide> _invokeAnimatedPropsCallbackOnMount: boolean = false;
<add> _lastProps: Object;
<ide> _prevComponent: any;
<ide> _propsAnimated: AnimatedProps;
<ide> _eventDetachers: Array<Function> = [];
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> _attachProps(nextProps) {
<ide> const oldPropsAnimated = this._propsAnimated;
<ide>
<del> if (nextProps === oldPropsAnimated) {
<del> return;
<del> }
<del>
<ide> this._propsAnimated = new AnimatedProps(
<ide> nextProps,
<ide> this._animatedPropsCallback,
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> });
<ide>
<ide> render() {
<add> if (this._lastProps !== this.props) {
<add> this._waitForUpdate();
<add> this._attachProps(this.props);
<add> this._lastProps = this.props;
<add> }
<ide> const {style = {}, ...props} = this._propsAnimated.__getValue() || {};
<ide> const {style: passthruStyle = {}, ...passthruProps} =
<ide> this.props.passthroughAnimatedPropExplicitValues || {};
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> );
<ide> }
<ide>
<del> UNSAFE_componentWillMount() {
<del> this._waitForUpdate();
<del> this._attachProps(this.props);
<del> }
<del>
<ide> componentDidMount() {
<ide> if (this._invokeAnimatedPropsCallbackOnMount) {
<ide> this._invokeAnimatedPropsCallbackOnMount = false;
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> this._markUpdateComplete();
<ide> }
<ide>
<del> UNSAFE_componentWillReceiveProps(newProps) {
<del> this._waitForUpdate();
<del> this._attachProps(newProps);
<del> }
<del>
<ide> componentDidUpdate(prevProps) {
<ide> if (this._component !== this._prevComponent) {
<ide> this._propsAnimated.setNativeView(this._component);
<ide><path>packages/rn-tester/js/examples/Animated/AnimatedExample.js
<ide>
<ide> const RNTesterButton = require('../../components/RNTesterButton');
<ide> const React = require('react');
<del>const {Animated, Easing, StyleSheet, Text, View} = require('react-native');
<add>const {
<add> Animated,
<add> Easing,
<add> Pressable,
<add> StyleSheet,
<add> Text,
<add> View,
<add>} = require('react-native');
<ide>
<ide> import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<ide>
<ide> exports.examples = ([
<ide> }
<ide>
<ide> type Props = $ReadOnly<{||}>;
<del> type State = {|show: boolean|};
<add> type State = {|
<add> disabled: boolean,
<add> pressCount: number,
<add> show: boolean,
<add> |};
<ide> class FadeInExample extends React.Component<Props, State> {
<ide> constructor(props: Props) {
<ide> super(props);
<ide> this.state = {
<add> disabled: true,
<add> pressCount: 0,
<ide> show: true,
<ide> };
<ide> }
<ide> exports.examples = ([
<ide> <RNTesterButton
<ide> testID="toggle-button"
<ide> onPress={() => {
<del> this.setState(state => ({show: !state.show}));
<add> this.setState(state => ({pressCount: 0, show: !state.show}));
<ide> }}>
<ide> Press to {this.state.show ? 'Hide' : 'Show'}
<ide> </RNTesterButton>
<add> <RNTesterButton
<add> testID="toggle-pressable"
<add> onPress={() => {
<add> this.setState(state => ({disabled: !state.disabled}));
<add> }}>
<add> Press to {this.state.disabled ? 'Enable' : 'Disable'}
<add> </RNTesterButton>
<ide> {this.state.show && (
<ide> <FadeInView>
<del> <View testID="fade-in-view" style={styles.content}>
<del> <Text>FadeInView</Text>
<del> </View>
<add> <Pressable
<add> testID="fade-in-view"
<add> style={styles.content}
<add> disabled={this.state.disabled}
<add> onPress={() => {
<add> this.setState(state => ({
<add> pressCount: this.state.pressCount + 1,
<add> }));
<add> }}>
<add> <Text>
<add> FadeInView
<add> {this.state.disabled
<add> ? ''
<add> : ` Pressable: ${this.state.pressCount}`}
<add> </Text>
<add> </Pressable>
<ide> </FadeInView>
<ide> )}
<ide> </View> | 2 |
Javascript | Javascript | fix arguments order in assert.strictequal() | e201c305f0c2f9abec9f3c8511879252426104ca | <ide><path>test/parallel/test-http-1.0.js
<ide> function test(handler, request_generator, response_validator) {
<ide>
<ide> {
<ide> function handler(req, res) {
<del> assert.strictEqual('1.0', req.httpVersion);
<del> assert.strictEqual(1, req.httpVersionMajor);
<del> assert.strictEqual(0, req.httpVersionMinor);
<add> assert.strictEqual(req.httpVersion, '1.0');
<add> assert.strictEqual(req.httpVersionMajor, 1);
<add> assert.strictEqual(req.httpVersionMinor, 0);
<ide> res.writeHead(200, { 'Content-Type': 'text/plain' });
<ide> res.end(body);
<ide> }
<ide> function test(handler, request_generator, response_validator) {
<ide> function response_validator(server_response, client_got_eof, timed_out) {
<ide> const m = server_response.split('\r\n\r\n');
<ide> assert.strictEqual(m[1], body);
<del> assert.strictEqual(true, client_got_eof);
<del> assert.strictEqual(false, timed_out);
<add> assert.strictEqual(client_got_eof, true);
<add> assert.strictEqual(timed_out, false);
<ide> }
<ide>
<ide> test(handler, request_generator, response_validator);
<ide> function test(handler, request_generator, response_validator) {
<ide> //
<ide> {
<ide> function handler(req, res) {
<del> assert.strictEqual('1.0', req.httpVersion);
<del> assert.strictEqual(1, req.httpVersionMajor);
<del> assert.strictEqual(0, req.httpVersionMinor);
<add> assert.strictEqual(req.httpVersion, '1.0');
<add> assert.strictEqual(req.httpVersionMajor, 1);
<add> assert.strictEqual(req.httpVersionMinor, 0);
<ide> res.sendDate = false;
<ide> res.writeHead(200, { 'Content-Type': 'text/plain' });
<ide> res.write('Hello, '); res._send('');
<ide> function test(handler, request_generator, response_validator) {
<ide> '\r\n' +
<ide> 'Hello, world!';
<ide>
<del> assert.strictEqual(expected_response, server_response);
<del> assert.strictEqual(true, client_got_eof);
<del> assert.strictEqual(false, timed_out);
<add> assert.strictEqual(server_response, expected_response);
<add> assert.strictEqual(client_got_eof, true);
<add> assert.strictEqual(timed_out, false);
<ide> }
<ide>
<ide> test(handler, request_generator, response_validator);
<ide> }
<ide>
<ide> {
<ide> function handler(req, res) {
<del> assert.strictEqual('1.1', req.httpVersion);
<del> assert.strictEqual(1, req.httpVersionMajor);
<del> assert.strictEqual(1, req.httpVersionMinor);
<add> assert.strictEqual(req.httpVersion, '1.1');
<add> assert.strictEqual(req.httpVersionMajor, 1);
<add> assert.strictEqual(req.httpVersionMinor, 1);
<ide> res.sendDate = false;
<ide> res.writeHead(200, { 'Content-Type': 'text/plain' });
<ide> res.write('Hello, '); res._send('');
<ide> function test(handler, request_generator, response_validator) {
<ide> '0\r\n' +
<ide> '\r\n';
<ide>
<del> assert.strictEqual(expected_response, server_response);
<del> assert.strictEqual(true, client_got_eof);
<del> assert.strictEqual(false, timed_out);
<add> assert.strictEqual(server_response, expected_response);
<add> assert.strictEqual(client_got_eof, true);
<add> assert.strictEqual(timed_out, false);
<ide> }
<ide>
<ide> test(handler, request_generator, response_validator); | 1 |
Javascript | Javascript | leave top level scope when traversing class nodes | b8815a941596c1167b3dcbdc05d082687185e8b3 | <ide><path>lib/Parser.js
<ide> class Parser extends Tapable {
<ide> if(classy.superClass)
<ide> this.walkExpression(classy.superClass);
<ide> if(classy.body && classy.body.type === "ClassBody") {
<del> for(const methodDefinition of classy.body.body)
<add> const wasTopLevel = this.scope.topLevelScope;
<add> this.scope.topLevelScope = false;
<add> for(const methodDefinition of classy.body.body) {
<ide> if(methodDefinition.type === "MethodDefinition")
<ide> this.walkMethodDefinition(methodDefinition);
<add> }
<add> this.scope.topLevelScope = wasTopLevel;
<ide> }
<ide> }
<ide>
<ide><path>test/configCases/parsing/harmony-this/abc.js
<ide> export class C {
<ide> foo() {
<ide> return this.x;
<ide> }
<add> bar(x = this.x) {
<add> return x;
<add> }
<add>}
<add>
<add>export const extendThisClass = () => {
<add> return class extends this.Buffer {};
<ide> }
<ide>
<ide> export function D() {
<ide><path>test/configCases/parsing/harmony-this/index.js
<ide> "use strict";
<ide>
<del>import d, {a, b as B, C as _C, D as _D, returnThisArrow, returnThisMember, that} from "./abc";
<add>import d, {a, b as B, C as _C, D as _D, extendThisClass, returnThisArrow, returnThisMember, that} from "./abc";
<ide>
<ide> import * as abc from "./abc";
<ide>
<ide> it("should have this = undefined on harmony modules", function() {
<ide> (function() {
<ide> abc.returnThisMember();
<ide> }).should.throw();
<add> (function() {
<add> extendThisClass();
<add> }).should.throw();
<ide> });
<ide>
<ide> it("should not break classes and functions", function() {
<ide> (new _C).foo().should.be.eql("bar");
<add> (new _C).bar().should.be.eql("bar");
<ide> (new _D).prop().should.be.eql("ok");
<ide> });
<ide> | 3 |
Go | Go | fix ineffassign linting | ddd8a6572d36a6d0db2aa21d697018f419a7b424 | <ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide>
<ide> source, err := inspectMountSourceField(id, vol)
<add> c.Assert(err, checker.IsNil)
<ide> _, err = os.Stat(source)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestContainerKillCustomStopSignal(c *check.C) {
<ide> defer res.Body.Close()
<ide>
<ide> b, err := ioutil.ReadAll(res.Body)
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent, check.Commentf(string(b)))
<ide> err = waitInspect(id, "{{.State.Running}} {{.State.Restarting}}", "false false", 30*time.Second)
<ide> c.Assert(err, checker.IsNil)
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
<ide> ADD foo.txt /x/`
<ide> targetFile = "foo.txt"
<ide> )
<del> var (
<del> name = "test-link-absolute-volume"
<del> dockerfile = ""
<del> )
<ide>
<ide> tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
<ide> if err != nil {
<ide> c.Fatalf("failed to create temporary directory: %s", tempDir)
<ide> }
<ide> defer os.RemoveAll(tempDir)
<ide>
<del> dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
<add> dockerfile := fmt.Sprintf(dockerfileTemplate, tempDir)
<ide> nonExistingFile := filepath.Join(tempDir, targetFile)
<ide>
<ide> ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile))
<ide> func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
<add> buildImageSuccessfully(c, "test-link-absolute-volume", build.WithExternalBuildContext(ctx))
<ide> if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
<ide> c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
<ide> }
<ide><path>integration-cli/docker_cli_commit_test.go
<ide> func (s *DockerSuite) TestCommitPausedContainer(c *check.C) {
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> dockerCmd(c, "pause", cleanedContainerID)
<del>
<del> out, _ = dockerCmd(c, "commit", cleanedContainerID)
<add> dockerCmd(c, "commit", cleanedContainerID)
<ide>
<ide> out = inspectField(c, cleanedContainerID, "State.Paused")
<ide> // commit should not unpause a paused container
<ide><path>integration-cli/docker_cli_config_create_test.go
<ide> func (s *DockerSwarmSuite) TestConfigCreateResolve(c *check.C) {
<ide> c.Assert(out, checker.Contains, fake)
<ide>
<ide> out, err = d.Cmd("config", "rm", id)
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, id)
<ide>
<ide> // Fake one will remain
<ide> func (s *DockerSwarmSuite) TestConfigCreateResolve(c *check.C) {
<ide> // - Full Name
<ide> // - Partial ID (prefix)
<ide> out, err = d.Cmd("config", "rm", id[:5])
<add> c.Assert(err, checker.Not(checker.IsNil))
<ide> c.Assert(out, checker.Not(checker.Contains), id)
<ide> out, err = d.Cmd("config", "ls")
<ide> c.Assert(err, checker.IsNil)
<ide> func (s *DockerSwarmSuite) TestConfigCreateResolve(c *check.C) {
<ide>
<ide> // Remove based on ID prefix of the fake one should succeed
<ide> out, err = d.Cmd("config", "rm", fake[:5])
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, fake[:5])
<ide> out, err = d.Cmd("config", "ls")
<ide> c.Assert(err, checker.IsNil)
<ide><path>integration-cli/docker_cli_cp_test.go
<ide> func (s *DockerSuite) TestCpSpecialFiles(c *check.C) {
<ide>
<ide> expected := readContainerFile(c, containerID, "resolv.conf")
<ide> actual, err := ioutil.ReadFile(outDir + "/resolv.conf")
<add> c.Assert(err, checker.IsNil)
<ide>
<ide> // Expected copied file to be duplicate of the container resolvconf
<ide> c.Assert(bytes.Equal(actual, expected), checker.True)
<ide> func (s *DockerSuite) TestCpSpecialFiles(c *check.C) {
<ide>
<ide> expected = readContainerFile(c, containerID, "hosts")
<ide> actual, err = ioutil.ReadFile(outDir + "/hosts")
<add> c.Assert(err, checker.IsNil)
<ide>
<ide> // Expected copied file to be duplicate of the container hosts
<ide> c.Assert(bytes.Equal(actual, expected), checker.True)
<ide> func (s *DockerSuite) TestCpSymlinkFromConToHostFollowSymlink(c *check.C) {
<ide>
<ide> expected := []byte(cpContainerContents)
<ide> actual, err := ioutil.ReadFile(expectedPath)
<add> c.Assert(err, checker.IsNil)
<ide>
<ide> if !bytes.Equal(actual, expected) {
<ide> c.Fatalf("Expected copied file to be duplicate of the container symbol link target")
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) {
<ide>
<ide> s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64")
<ide>
<del> out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox")
<add> _, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox")
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
<add> out, err := s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff")
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) {
<ide> defer d.Cmd("stop", "bb")
<ide>
<ide> out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
<add> c.Assert(err, check.IsNil)
<ide> c.Assert(out, checker.Equals, "10.2.2.0\n")
<ide>
<ide> out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
<ide> test2ID := strings.TrimSpace(out)
<ide>
<ide> out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
<add> c.Assert(err, check.IsNil)
<ide> test3ID := strings.TrimSpace(out)
<ide>
<ide> s.d.Restart(c)
<ide>
<del> out, err = s.d.Cmd("create", "--name=test", "busybox")
<add> _, err = s.d.Cmd("create", "--name=test", "busybox")
<ide> c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
<ide> // this one is no longer needed, removing simplifies the remainder of the test
<ide> out, err = s.d.Cmd("rm", "-f", "test")
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C)
<ide> c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out))
<ide>
<ide> out, err = s.d.Cmd("ps")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running"))
<ide> c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running"))
<ide>
<ide> func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) {
<ide> // captured, so `.State.Error` is empty.
<ide> // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426,
<ide> // and https://github.com/docker/docker/pull/26061#r78054578 for more information.
<del> out, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto")
<add> _, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto")
<ide> c.Assert(err, checker.NotNil)
<ide>
<ide> // Check that those values were saved on disk
<del> out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
<add> out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
<ide> out = strings.TrimSpace(out)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Equals, "127")
<ide><path>integration-cli/docker_cli_health_test.go
<ide> func (s *DockerSuite) TestHealth(c *check.C) {
<ide> dockerCmd(c, "rm", "-f", name)
<ide>
<ide> // Disable the check from the CLI
<del> out, _ = dockerCmd(c, "create", "--name=noh", "--no-healthcheck", imageName)
<add> dockerCmd(c, "create", "--name=noh", "--no-healthcheck", imageName)
<ide> out, _ = dockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "noh")
<ide> c.Check(out, checker.Equals, "[NONE]\n")
<ide> dockerCmd(c, "rm", "noh")
<ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
<ide> // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now.
<ide> testRequires(c, DaemonIsLinux)
<ide> name := "testlogssincefuturefollow"
<del> out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
<add> dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
<ide>
<ide> // Extract one timestamp from the log file to give us a starting point for
<ide> // our `--since` argument. Because the log producer runs in the background,
<ide> // we need to check repeatedly for some output to be produced.
<ide> var timestamp string
<ide> for i := 0; i != 100 && timestamp == ""; i++ {
<del> if out, _ = dockerCmd(c, "logs", "-t", name); out == "" {
<add> if out, _ := dockerCmd(c, "logs", "-t", name); out == "" {
<ide> time.Sleep(time.Millisecond * 100) // Retry
<ide> } else {
<ide> timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0]
<ide> func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> since := t.Unix() + 2
<del> out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
<add> out, _ := dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
<ide> c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log"))
<ide> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> for _, v := range lines {
<ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
<ide> out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
<ide> assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
<ide>
<del> out, _ = dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
<add> dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
<ide> assertNwIsAvailable(c, testNet)
<ide>
<ide> out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
<ide> func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
<ide> out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
<ide> cid2 := strings.TrimSpace(out)
<ide>
<del> hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
<del>
<ide> // verify first container etc/hosts file has not changed
<ide> hosts1post := readContainerFileWithExec(c, cid1, hostsFile)
<ide> c.Assert(string(hosts1), checker.Equals, string(hosts1post),
<ide> func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
<ide>
<ide> dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
<ide>
<del> hosts2 = readContainerFileWithExec(c, cid2, hostsFile)
<add> hosts2 := readContainerFileWithExec(c, cid2, hostsFile)
<ide> hosts1post = readContainerFileWithExec(c, cid1, hostsFile)
<ide> c.Assert(string(hosts1), checker.Equals, string(hosts1post),
<ide> check.Commentf("Unexpected %s change on container connect", hostsFile))
<ide><path>integration-cli/docker_cli_plugins_test.go
<ide> func (ps *DockerPluginSuite) TestPluginBasicOps(c *check.C) {
<ide> func (ps *DockerPluginSuite) TestPluginForceRemove(c *check.C) {
<ide> pNameWithTag := ps.getPluginRepoWithTag()
<ide>
<del> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
<add> _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag)
<add> out, _, _ := dockerCmdWithError("plugin", "remove", pNameWithTag)
<ide> c.Assert(out, checker.Contains, "is enabled")
<ide>
<ide> out, _, err = dockerCmdWithError("plugin", "remove", "--force", pNameWithTag)
<ide> func (s *DockerSuite) TestPluginActive(c *check.C) {
<ide> _, _, err = dockerCmdWithError("volume", "create", "-d", pNameWithTag, "--name", "testvol1")
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, _, err := dockerCmdWithError("plugin", "disable", pNameWithTag)
<add> out, _, _ := dockerCmdWithError("plugin", "disable", pNameWithTag)
<ide> c.Assert(out, checker.Contains, "in use")
<ide>
<ide> _, _, err = dockerCmdWithError("volume", "rm", "testvol1")
<ide> func (s *DockerSuite) TestPluginActive(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestPluginActiveNetwork(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, IsAmd64, Network)
<del> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
<add> _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, _, err = dockerCmdWithError("network", "create", "-d", npNameWithTag, "test")
<add> out, _, err := dockerCmdWithError("network", "create", "-d", npNameWithTag, "test")
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> nID := strings.TrimSpace(out)
<ide>
<del> out, _, err = dockerCmdWithError("plugin", "remove", npNameWithTag)
<add> out, _, _ = dockerCmdWithError("plugin", "remove", npNameWithTag)
<ide> c.Assert(out, checker.Contains, "is in use")
<ide>
<ide> _, _, err = dockerCmdWithError("network", "rm", nID)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, _, err = dockerCmdWithError("plugin", "remove", npNameWithTag)
<add> out, _, _ = dockerCmdWithError("plugin", "remove", npNameWithTag)
<ide> c.Assert(out, checker.Contains, "is enabled")
<ide>
<ide> _, _, err = dockerCmdWithError("plugin", "disable", npNameWithTag)
<ide> func (ps *DockerPluginSuite) TestPluginIDPrefix(c *check.C) {
<ide> c.Assert(out, checker.Contains, "false")
<ide>
<ide> // Remove
<del> out, _, err = dockerCmdWithError("plugin", "remove", id[:5])
<add> _, _, err = dockerCmdWithError("plugin", "remove", id[:5])
<ide> c.Assert(err, checker.IsNil)
<ide> // List returns none
<ide> out, _, err = dockerCmdWithError("plugin", "ls")
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPsByOrder(c *check.C) {
<del> name1 := "xyz-abc"
<del> out := runSleepingContainer(c, "--name", name1)
<add> out := runSleepingContainer(c, "--name", "xyz-abc")
<ide> container1 := strings.TrimSpace(out)
<ide>
<del> name2 := "xyz-123"
<del> out = runSleepingContainer(c, "--name", name2)
<add> out = runSleepingContainer(c, "--name", "xyz-123")
<ide> container2 := strings.TrimSpace(out)
<ide>
<del> name3 := "789-abc"
<del> out = runSleepingContainer(c, "--name", name3)
<del>
<del> name4 := "789-123"
<del> out = runSleepingContainer(c, "--name", name4)
<add> runSleepingContainer(c, "--name", "789-abc")
<add> runSleepingContainer(c, "--name", "789-123")
<ide>
<ide> // Run multiple time should have the same result
<ide> out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined()
<ide><path>integration-cli/docker_cli_restart_test.go
<ide> func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> err = waitInspect("second", "{{.State.Status}}", "running", 5*time.Second)
<add> c.Assert(err, check.IsNil)
<ide>
<ide> // ping to first and its alias foo must still succeed
<ide> _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
<ide> // Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...)
<ide> testRequires(c, DaemonIsLinux)
<ide> workingDirectory, err := ioutil.TempDir("", "TestRunCreateVolumeWithSymlink")
<add> c.Assert(err, checker.IsNil)
<ide> image := "docker-test-createvolumewithsymlink"
<ide>
<ide> buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
<ide><path>integration-cli/docker_cli_secret_create_test.go
<ide> func (s *DockerSwarmSuite) TestSecretCreateResolve(c *check.C) {
<ide> c.Assert(out, checker.Contains, fake)
<ide>
<ide> out, err = d.Cmd("secret", "rm", id)
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, id)
<ide>
<ide> // Fake one will remain
<ide> func (s *DockerSwarmSuite) TestSecretCreateResolve(c *check.C) {
<ide> // - Full Name
<ide> // - Partial ID (prefix)
<ide> out, err = d.Cmd("secret", "rm", id[:5])
<add> c.Assert(err, checker.Not(checker.IsNil))
<ide> c.Assert(out, checker.Not(checker.Contains), id)
<ide> out, err = d.Cmd("secret", "ls")
<ide> c.Assert(err, checker.IsNil)
<ide> func (s *DockerSwarmSuite) TestSecretCreateResolve(c *check.C) {
<ide>
<ide> // Remove based on ID prefix of the fake one should succeed
<ide> out, err = d.Cmd("secret", "rm", fake[:5])
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, fake[:5])
<ide> out, err = d.Cmd("secret", "ls")
<ide> c.Assert(err, checker.IsNil)
<ide><path>integration-cli/docker_cli_service_scale_test.go
<ide> func (s *DockerSwarmSuite) TestServiceScale(c *check.C) {
<ide> service2Args := append([]string{"service", "create", "--detach", "--no-resolve-image", "--name", service2Name, "--mode=global", defaultSleepImage}, sleepCommandForDaemonPlatform()...)
<ide>
<ide> // Create services
<del> out, err := d.Cmd(service1Args...)
<add> _, err := d.Cmd(service1Args...)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd(service2Args...)
<add> _, err = d.Cmd(service2Args...)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "scale", "TestService1=2")
<add> _, err = d.Cmd("service", "scale", "TestService1=2")
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "scale", "TestService1=foobar")
<add> out, err := d.Cmd("service", "scale", "TestService1=foobar")
<ide> c.Assert(err, checker.NotNil)
<ide>
<ide> str := fmt.Sprintf("%s: invalid replicas value %s", service1Name, "foobar")
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<ide>
<del> out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
<add> _, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
<add> _, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", "--publish-add", "80:20", name)
<add> _, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", "--publish-add", "80:20", name)
<ide> c.Assert(err, checker.NotNil)
<ide>
<ide> out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name)
<ide> func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *check.C) {
<ide>
<ide> // Without --tty
<ide> expectedOutput := "none"
<del> out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", ttyCheck)
<add> _, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", ttyCheck)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> // Make sure task has been deployed.
<ide> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
<ide>
<ide> // We need to get the container id.
<del> out, err = d.Cmd("ps", "-q", "--no-trunc")
<add> out, err := d.Cmd("ps", "-q", "--no-trunc")
<ide> c.Assert(err, checker.IsNil)
<ide> id := strings.TrimSpace(out)
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *check.C) {
<ide> c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
<ide>
<ide> // Remove service
<del> out, err = d.Cmd("service", "rm", name)
<add> _, err = d.Cmd("service", "rm", name)
<ide> c.Assert(err, checker.IsNil)
<ide> // Make sure container has been destroyed.
<ide> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0)
<ide>
<ide> // With --tty
<ide> expectedOutput = "TTY"
<del> out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck)
<add> _, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> // Make sure task has been deployed.
<ide> func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) {
<ide> c.Assert(unlockKey, checker.Not(checker.Equals), "")
<ide>
<ide> outs, err = d.Cmd("swarm", "unlock-key", "-q")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(outs, checker.Equals, unlockKey+"\n")
<ide>
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
<ide> func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
<ide> c.Assert(unlockKey, checker.Not(checker.Equals), "")
<ide>
<ide> outs, err = d1.Cmd("swarm", "unlock-key", "-q")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(outs, checker.Equals, unlockKey+"\n")
<ide>
<ide> // The ones that got the cluster update should be set to locked
<ide> func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
<ide> c.Assert(unlockKey, checker.Not(checker.Equals), "")
<ide>
<ide> outs, err = d1.Cmd("swarm", "unlock-key", "-q")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(outs, checker.Equals, unlockKey+"\n")
<ide>
<ide> // joined workers start off unlocked
<ide> func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
<ide> c.Assert(unlockKey, checker.Not(checker.Equals), "")
<ide>
<ide> outs, err = d.Cmd("swarm", "unlock-key", "-q")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(outs, checker.Equals, unlockKey+"\n")
<ide>
<ide> // Rotate multiple times
<ide> func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
<ide> c.Assert(unlockKey, checker.Not(checker.Equals), "")
<ide>
<ide> outs, err = d1.Cmd("swarm", "unlock-key", "-q")
<add> c.Assert(err, checker.IsNil)
<ide> c.Assert(outs, checker.Equals, unlockKey+"\n")
<ide>
<ide> // Rotate multiple times
<ide><path>integration-cli/docker_cli_swarm_unix_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *check.C) {
<ide>
<ide> // create a dummy volume to trigger lazy loading of the plugin
<ide> out, err = d.Cmd("volume", "create", "-d", "customvolumedriver", "hello")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide>
<ide> // TODO(aaronl): It will take about 15 seconds for swarm to realize the
<ide> // plugin was loaded. Switching the test over to plugin v2 would avoid
<ide><path>integration-cli/docker_cli_update_unix_test.go
<ide> func (s *DockerSuite) TestUpdateWithNanoCPUs(c *check.C) {
<ide> c.Assert(err, checker.NotNil)
<ide> c.Assert(out, checker.Contains, "Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
<ide>
<del> out, _ = dockerCmd(c, "update", "--cpus", "0.8", "top")
<add> dockerCmd(c, "update", "--cpus", "0.8", "top")
<ide> inspect, err = clt.ContainerInspect(context.Background(), "top")
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(inspect.HostConfig.NanoCPUs, checker.Equals, int64(800000000))
<ide><path>integration-cli/docker_cli_userns_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonUserNamespaceRootSetting(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf("Could not inspect running container: out: %q", pid))
<ide> // check the uid and gid maps for the PID to ensure root is remapped
<ide> // (cmd = cat /proc/<pid>/uid_map | grep -E '0\s+9999\s+1')
<del> out, err = RunCommandPipelineWithOutput(
<add> _, err = RunCommandPipelineWithOutput(
<ide> exec.Command("cat", "/proc/"+strings.TrimSpace(pid)+"/uid_map"),
<ide> exec.Command("grep", "-E", fmt.Sprintf("0[[:space:]]+%d[[:space:]]+", uid)))
<ide> c.Assert(err, check.IsNil)
<ide>
<del> out, err = RunCommandPipelineWithOutput(
<add> _, err = RunCommandPipelineWithOutput(
<ide> exec.Command("cat", "/proc/"+strings.TrimSpace(pid)+"/gid_map"),
<ide> exec.Command("grep", "-E", fmt.Sprintf("0[[:space:]]+%d[[:space:]]+", gid)))
<ide> c.Assert(err, check.IsNil)
<ide><path>integration-cli/docker_cli_volume_test.go
<ide> func (s *DockerSuite) TestVolumeCLICreateLabel(c *check.C) {
<ide> testLabel := "foo"
<ide> testValue := "bar"
<ide>
<del> out, _, err := dockerCmdWithError("volume", "create", "--label", testLabel+"="+testValue, testVol)
<add> _, _, err := dockerCmdWithError("volume", "create", "--label", testLabel+"="+testValue, testVol)
<ide> c.Assert(err, check.IsNil)
<ide>
<del> out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+testLabel+" }}", testVol)
<add> out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+testLabel+" }}", testVol)
<ide> c.Assert(strings.TrimSpace(out), check.Equals, testValue)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestVolumeCLICreateLabelMultiple(c *check.C) {
<ide> args = append(args, "--label", k+"="+v)
<ide> }
<ide>
<del> out, _, err := dockerCmdWithError(args...)
<add> _, _, err := dockerCmdWithError(args...)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> for k, v := range testLabels {
<del> out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+k+" }}", testVol)
<add> out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+k+" }}", testVol)
<ide> c.Assert(strings.TrimSpace(out), check.Equals, v)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestVolumeCLILsFilterLabels(c *check.C) {
<ide> testVol1 := "testvolcreatelabel-1"
<del> out, _, err := dockerCmdWithError("volume", "create", "--label", "foo=bar1", testVol1)
<add> _, _, err := dockerCmdWithError("volume", "create", "--label", "foo=bar1", testVol1)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> testVol2 := "testvolcreatelabel-2"
<del> out, _, err = dockerCmdWithError("volume", "create", "--label", "foo=bar2", testVol2)
<add> _, _, err = dockerCmdWithError("volume", "create", "--label", "foo=bar2", testVol2)
<ide> c.Assert(err, check.IsNil)
<ide>
<del> out, _ = dockerCmd(c, "volume", "ls", "--filter", "label=foo")
<add> out, _ := dockerCmd(c, "volume", "ls", "--filter", "label=foo")
<ide>
<ide> // filter with label=key
<ide> c.Assert(out, checker.Contains, "testvolcreatelabel-1\n", check.Commentf("expected volume 'testvolcreatelabel-1' in output"))
<ide> func (s *DockerSuite) TestVolumeCLILsFilterLabels(c *check.C) {
<ide> func (s *DockerSuite) TestVolumeCLILsFilterDrivers(c *check.C) {
<ide> // using default volume driver local to create volumes
<ide> testVol1 := "testvol-1"
<del> out, _, err := dockerCmdWithError("volume", "create", testVol1)
<add> _, _, err := dockerCmdWithError("volume", "create", testVol1)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> testVol2 := "testvol-2"
<del> out, _, err = dockerCmdWithError("volume", "create", testVol2)
<add> _, _, err = dockerCmdWithError("volume", "create", testVol2)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // filter with driver=local
<del> out, _ = dockerCmd(c, "volume", "ls", "--filter", "driver=local")
<add> out, _ := dockerCmd(c, "volume", "ls", "--filter", "driver=local")
<ide> c.Assert(out, checker.Contains, "testvol-1\n", check.Commentf("expected volume 'testvol-1' in output"))
<ide> c.Assert(out, checker.Contains, "testvol-2\n", check.Commentf("expected volume 'testvol-2' in output"))
<ide>
<ide> func (s *DockerSuite) TestVolumeCLIRmForceInUse(c *check.C) {
<ide> c.Assert(id, checker.Equals, name)
<ide>
<ide> prefix, slash := getPrefixAndSlashFromDaemonPlatform()
<del> out, e := dockerCmd(c, "create", "-v", "testvolume:"+prefix+slash+"foo", "busybox")
<add> out, _ = dockerCmd(c, "create", "-v", "testvolume:"+prefix+slash+"foo", "busybox")
<ide> cid := strings.TrimSpace(out)
<ide>
<ide> _, _, err := dockerCmdWithError("volume", "rm", "-f", name)
<ide> func (s *DockerSuite) TestVolumeCLIRmForceInUse(c *check.C) {
<ide> c.Assert(out, checker.Contains, name)
<ide>
<ide> // Verify removing the volume after the container is removed works
<del> _, e = dockerCmd(c, "rm", cid)
<add> _, e := dockerCmd(c, "rm", cid)
<ide> c.Assert(e, check.Equals, 0)
<ide>
<ide> _, e = dockerCmd(c, "volume", "rm", "-f", name) | 20 |
Java | Java | add doonterminate to single/maybe for consistency | 6e266af1000083f25dcae9defdcfe41e4ea2b97b | <ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe) {
<ide> ));
<ide> }
<ide>
<add> /**
<add> * Returns a Maybe instance that calls the given onTerminate callback
<add> * just before this Maybe completes normally or with an exception.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt="">
<add> * <p>
<add> * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or
<add> * {@code onError} notification.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError}
<add> * @return the new Maybe instance
<add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<add> * @see #doOnTerminate(Action)
<add> * @since 2.2.7 - experimental
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Maybe<T> doOnTerminate(final Action onTerminate) {
<add> ObjectHelper.requireNonNull(onTerminate, "onTerminate is null");
<add> return RxJavaPlugins.onAssembly(new MaybeDoOnTerminate<T>(this, onTerminate));
<add> }
<add>
<ide> /**
<ide> * Calls the shared consumer with the success value sent via onSuccess for each
<ide> * MaybeObserver that subscribes to the current Maybe.
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscr
<ide> return RxJavaPlugins.onAssembly(new SingleDoOnSubscribe<T>(this, onSubscribe));
<ide> }
<ide>
<add> /**
<add> * Returns a Single instance that calls the given onTerminate callback
<add> * just before this Single completes normally or with an exception.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt="">
<add> * <p>
<add> * This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or
<add> * {@code onError} notification.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError}
<add> * @return the new Single instance
<add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<add> * @see #doOnTerminate(Action)
<add> * @since 2.2.7 - experimental
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @NonNull
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Single<T> doOnTerminate(final Action onTerminate) {
<add> ObjectHelper.requireNonNull(onTerminate, "onTerminate is null");
<add> return RxJavaPlugins.onAssembly(new SingleDoOnTerminate<T>(this, onTerminate));
<add> }
<add>
<ide> /**
<ide> * Calls the shared consumer with the success value sent via onSuccess for each
<ide> * SingleObserver that subscribes to the current Single.
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminate.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import io.reactivex.Maybe;
<add>import io.reactivex.MaybeObserver;
<add>import io.reactivex.MaybeSource;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Action;
<add>
<add>public final class MaybeDoOnTerminate<T> extends Maybe<T> {
<add>
<add> final MaybeSource<T> source;
<add>
<add> final Action onTerminate;
<add>
<add> public MaybeDoOnTerminate(MaybeSource<T> source, Action onTerminate) {
<add> this.source = source;
<add> this.onTerminate = onTerminate;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> source.subscribe(new DoOnTerminate(observer));
<add> }
<add>
<add> final class DoOnTerminate implements MaybeObserver<T> {
<add> final MaybeObserver<? super T> downstream;
<add>
<add> DoOnTerminate(MaybeObserver<? super T> observer) {
<add> this.downstream = observer;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> downstream.onSubscribe(d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(T value) {
<add> try {
<add> onTerminate.run();
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> downstream.onError(ex);
<add> return;
<add> }
<add>
<add> downstream.onSuccess(value);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> try {
<add> onTerminate.run();
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> e = new CompositeException(e, ex);
<add> }
<add>
<add> downstream.onError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> try {
<add> onTerminate.run();
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> downstream.onError(ex);
<add> return;
<add> }
<add>
<add> downstream.onComplete();
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDoOnTerminate.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import io.reactivex.Single;
<add>import io.reactivex.SingleObserver;
<add>import io.reactivex.SingleSource;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Action;
<add>
<add>public final class SingleDoOnTerminate<T> extends Single<T> {
<add>
<add> final SingleSource<T> source;
<add>
<add> final Action onTerminate;
<add>
<add> public SingleDoOnTerminate(SingleSource<T> source, Action onTerminate) {
<add> this.source = source;
<add> this.onTerminate = onTerminate;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(final SingleObserver<? super T> observer) {
<add> source.subscribe(new DoOnTerminate(observer));
<add> }
<add>
<add> final class DoOnTerminate implements SingleObserver<T> {
<add>
<add> final SingleObserver<? super T> downstream;
<add>
<add> DoOnTerminate(SingleObserver<? super T> observer) {
<add> this.downstream = observer;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> downstream.onSubscribe(d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(T value) {
<add> try {
<add> onTerminate.run();
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> downstream.onError(ex);
<add> return;
<add> }
<add>
<add> downstream.onSuccess(value);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> try {
<add> onTerminate.run();
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> e = new CompositeException(e, ex);
<add> }
<add>
<add> downstream.onError(e);
<add> }
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeDoOnTerminateTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import io.reactivex.Maybe;
<add>import io.reactivex.TestHelper;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Action;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.PublishSubject;
<add>import org.junit.Test;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>
<add>import static org.junit.Assert.assertTrue;
<add>
<add>public class MaybeDoOnTerminateTest {
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void doOnTerminate() {
<add> Maybe.just(1).doOnTerminate(null);
<add> }
<add>
<add> @Test
<add> public void doOnTerminateSuccess() {
<add> final AtomicBoolean atomicBoolean = new AtomicBoolean();
<add> Maybe.just(1).doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> atomicBoolean.set(true);
<add> }
<add> })
<add> .test()
<add> .assertResult(1);
<add>
<add> assertTrue(atomicBoolean.get());
<add> }
<add>
<add> @Test
<add> public void doOnTerminateError() {
<add> final AtomicBoolean atomicBoolean = new AtomicBoolean();
<add> Maybe.error(new TestException()).doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> atomicBoolean.set(true);
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> assertTrue(atomicBoolean.get());
<add> }
<add>
<add> @Test
<add> public void doOnTerminateComplete() {
<add> final AtomicBoolean atomicBoolean = new AtomicBoolean();
<add> Maybe.empty().doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> atomicBoolean.set(true);
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add>
<add> assertTrue(atomicBoolean.get());
<add> }
<add>
<add> @Test
<add> public void doOnTerminateSuccessCrash() {
<add> Maybe.just(1).doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doOnTerminateErrorCrash() {
<add> TestObserver<Object> to = Maybe.error(new TestException("Outer"))
<add> .doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> throw new TestException("Inner");
<add> }
<add> })
<add> .test()
<add> .assertFailure(CompositeException.class);
<add>
<add> List<Throwable> errors = TestHelper.compositeList(to.errors().get(0));
<add> TestHelper.assertError(errors, 0, TestException.class, "Outer");
<add> TestHelper.assertError(errors, 1, TestException.class, "Inner");
<add> }
<add>
<add> @Test
<add> public void doOnTerminateCompleteCrash() {
<add> Maybe.empty()
<add> .doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleDoOnTerminateTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import io.reactivex.Single;
<add>import io.reactivex.TestHelper;
<add>import io.reactivex.exceptions.CompositeException;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Action;
<add>import io.reactivex.observers.TestObserver;
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>
<add>import static org.junit.Assert.assertTrue;
<add>
<add>public class SingleDoOnTerminateTest {
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void doOnTerminate() {
<add> Single.just(1).doOnTerminate(null);
<add> }
<add>
<add> @Test
<add> public void doOnTerminateSuccess() {
<add> final AtomicBoolean atomicBoolean = new AtomicBoolean();
<add>
<add> Single.just(1).doOnTerminate(new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> atomicBoolean.set(true);
<add> }
<add> })
<add> .test()
<add> .assertResult(1);
<add>
<add> assertTrue(atomicBoolean.get());
<add> }
<add>
<add> @Test
<add> public void doOnTerminateError() {
<add> final AtomicBoolean atomicBoolean = new AtomicBoolean();
<add> Single.error(new TestException()).doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> atomicBoolean.set(true);
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> assertTrue(atomicBoolean.get());
<add> }
<add>
<add> @Test
<add> public void doOnTerminateSuccessCrash() {
<add> Single.just(1).doOnTerminate(new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doOnTerminateErrorCrash() {
<add> TestObserver<Object> to = Single.error(new TestException("Outer")).doOnTerminate(new Action() {
<add> @Override
<add> public void run() {
<add> throw new TestException("Inner");
<add> }
<add> })
<add> .test()
<add> .assertFailure(CompositeException.class);
<add>
<add> List<Throwable> errors = TestHelper.compositeList(to.errors().get(0));
<add>
<add> TestHelper.assertError(errors, 0, TestException.class, "Outer");
<add> TestHelper.assertError(errors, 1, TestException.class, "Inner");
<add> }
<add>} | 6 |
Javascript | Javascript | remove unused parameters and fix jslint warnings | b321768f595d2290a9ec80d2b96e46d0feb3b62c | <ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> var font = xref.fetchIfRef(fontRef);
<ide> assertWellFormed(isDict(font));
<ide> if (!font.translated) {
<del> font.translated = self.translateFont(font, xref, resources, handler,
<del> uniquePrefix, dependency);
<add> font.translated = self.translateFont(font, xref, resources,
<add> dependency);
<ide> if (font.translated) {
<ide> // keep track of each font we translated so the caller can
<ide> // load them asynchronously before calling display on a page
<del> loadedName = 'font_' + uniquePrefix + ++self.objIdCounter;
<add> loadedName = 'font_' + uniquePrefix + (++self.objIdCounter);
<ide> font.translated.properties.loadedName = loadedName;
<ide> font.loadedName = loadedName;
<ide>
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> var h = dict.get('Height', 'H');
<ide>
<ide> if (image instanceof JpegStream) {
<del> var objId = 'img_' + uniquePrefix + ++self.objIdCounter;
<add> var objId = 'img_' + uniquePrefix + (++self.objIdCounter);
<ide> handler.send('obj', [objId, 'JpegStream', image.getIR()]);
<ide>
<ide> // Add the dependency on the image object.
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> var glyphsWidths = {};
<ide> var widths = xref.fetchIfRef(dict.get('W'));
<ide> if (widths) {
<del> var start = 0, end = 0;
<add> var start = 0;
<ide> for (var i = 0, ii = widths.length; i < ii; i++) {
<ide> var code = widths[i];
<ide> if (isArray(code)) {
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> // special case for symbols
<ide> var encoding = Encodings.symbolsEncoding.slice();
<ide> for (var i = 0, n = encoding.length, j; i < n; i++) {
<del> if (!(j = encoding[i]))
<add> j = encoding[i];
<add> if (!j)
<ide> continue;
<ide> map[i] = GlyphsUnicode[j] || 0;
<ide> }
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> },
<ide>
<ide> translateFont: function partialEvaluatorTranslateFont(dict, xref, resources,
<del> queue, handler, uniquePrefix, dependency) {
<add> dependency) {
<ide> var baseDict = dict;
<ide> var type = dict.get('Subtype');
<ide> assertWellFormed(isName(type), 'invalid font Subtype'); | 1 |
Javascript | Javascript | fix retina scale when display size is implicit | 6b449a9e7c56d873edc28b3e2dcf976b2ea27404 | <ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide>
<ide> canvas.width = chart.width = newWidth;
<ide> canvas.height = chart.height = newHeight;
<del>
<del> helpers.retinaScale(chart);
<del>
<ide> canvas.style.width = newWidth + 'px';
<ide> canvas.style.height = newHeight + 'px';
<ide>
<add> helpers.retinaScale(chart);
<add>
<ide> // Notify any plugins about the resize
<ide> var newSize = {width: newWidth, height: newHeight};
<ide> Chart.plugins.notify('resize', [me, newSize]);
<ide><path>src/core/core.helpers.js
<ide> module.exports = function(Chart) {
<ide> document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
<ide> };
<ide> helpers.retinaScale = function(chart) {
<del> var ctx = chart.ctx;
<del> var canvas = chart.canvas;
<del> var width = canvas.width;
<del> var height = canvas.height;
<ide> var pixelRatio = chart.currentDevicePixelRatio = window.devicePixelRatio || 1;
<del>
<del> if (pixelRatio !== 1) {
<del> canvas.height = height * pixelRatio;
<del> canvas.width = width * pixelRatio;
<del> ctx.scale(pixelRatio, pixelRatio);
<add> if (pixelRatio === 1) {
<add> return;
<ide> }
<add>
<add> var canvas = chart.canvas;
<add> var height = chart.height;
<add> var width = chart.width;
<add>
<add> canvas.height = height * pixelRatio;
<add> canvas.width = width * pixelRatio;
<add> chart.ctx.scale(pixelRatio, pixelRatio);
<add>
<add> // If no style has been set on the canvas, the render size is used as display size,
<add> // making the chart visually bigger, so let's enforce it to the "correct" values.
<add> // See https://github.com/chartjs/Chart.js/issues/3575
<add> canvas.style.height = height + 'px';
<add> canvas.style.width = width + 'px';
<ide> };
<ide> // -- Canvas methods
<ide> helpers.clear = function(chart) {
<ide><path>test/core.controller.tests.js
<ide> describe('Chart.Controller', function() {
<ide> expect(data.datasets.length).toBe(0);
<ide> });
<ide>
<del> it('should NOT alter config.data references', function() {
<add> it('should not alter config.data references', function() {
<ide> var ds0 = {data: [10, 11, 12, 13]};
<ide> var ds1 = {data: [20, 21, 22, 23]};
<ide> var datasets = [ds0, ds1];
<ide> describe('Chart.Controller', function() {
<ide> });
<ide> });
<ide>
<del> it('should NOT apply aspect ratio when height specified', function() {
<add> it('should not apply aspect ratio when height specified', function() {
<ide> var chart = acquireChart({
<ide> options: {
<ide> responsive: false,
<ide> describe('Chart.Controller', function() {
<ide> });
<ide> });
<ide>
<del> it('should NOT inject the resizer element', function() {
<add> it('should not inject the resizer element', function() {
<ide> var chart = acquireChart({
<ide> options: {
<ide> responsive: false
<ide> describe('Chart.Controller', function() {
<ide> });
<ide> });
<ide>
<del> it('should NOT include parent padding when resizing the canvas', function(done) {
<add> it('should not include parent padding when resizing the canvas', function(done) {
<ide> var chart = acquireChart({
<ide> type: 'line',
<ide> options: {
<ide> describe('Chart.Controller', function() {
<ide> });
<ide> });
<ide>
<del> it('should NOT resize the canvas when parent height changes', function(done) {
<add> it('should not resize the canvas when parent height changes', function(done) {
<ide> var chart = acquireChart({
<ide> options: {
<ide> responsive: true,
<ide> describe('Chart.Controller', function() {
<ide> });
<ide> });
<ide>
<add> describe('Retina scale (a.k.a. device pixel ratio)', function() {
<add> beforeEach(function() {
<add> this.devicePixelRatio = window.devicePixelRatio;
<add> window.devicePixelRatio = 3;
<add> });
<add>
<add> afterEach(function() {
<add> window.devicePixelRatio = this.devicePixelRatio;
<add> });
<add>
<add> // see https://github.com/chartjs/Chart.js/issues/3575
<add> it ('should scale the render size but not the "implicit" display size', function() {
<add> var chart = acquireChart({
<add> options: {
<add> responsive: false
<add> }
<add> }, {
<add> canvas: {
<add> width: 320,
<add> height: 240,
<add> }
<add> });
<add>
<add> expect(chart).toBeChartOfSize({
<add> dw: 320, dh: 240,
<add> rw: 960, rh: 720,
<add> });
<add> });
<add>
<add> it ('should scale the render size but not the "explicit" display size', function() {
<add> var chart = acquireChart({
<add> options: {
<add> responsive: false
<add> }
<add> }, {
<add> canvas: {
<add> style: 'width: 320px; height: 240px'
<add> }
<add> });
<add>
<add> expect(chart).toBeChartOfSize({
<add> dw: 320, dh: 240,
<add> rw: 960, rh: 720,
<add> });
<add> });
<add> });
<add>
<ide> describe('controller.destroy', function() {
<ide> it('should reset context to default values', function() {
<ide> var chart = acquireChart({});
<ide><path>test/mockContext.js
<ide> var chart = actual.chart;
<ide> var canvas = chart.ctx.canvas;
<ide> var style = getComputedStyle(canvas);
<add> var pixelRatio = window.devicePixelRatio;
<ide> var dh = parseInt(style.height, 10);
<ide> var dw = parseInt(style.width, 10);
<ide> var rh = canvas.height;
<ide> var rw = canvas.width;
<add> var orh = rh / pixelRatio;
<add> var orw = rw / pixelRatio;
<ide>
<ide> // sanity checks
<del> if (chart.height !== rh) {
<del> message = 'Expected chart height ' + chart.height + ' to be equal to render height ' + rh;
<del> } else if (chart.width !== rw) {
<del> message = 'Expected chart width ' + chart.width + ' to be equal to render width ' + rw;
<add> if (chart.height !== orh) {
<add> message = 'Expected chart height ' + chart.height + ' to be equal to original render height ' + orh;
<add> } else if (chart.width !== orw) {
<add> message = 'Expected chart width ' + chart.width + ' to be equal to original render width ' + orw;
<ide> }
<ide>
<ide> // validity checks | 4 |
Python | Python | fix encode plus | 3d57c51111054adb01b2ea94bfd45237eb282431 | <ide><path>transformers/tokenization_utils.py
<ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok
<ide> return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
<ide> or PyTorch torch.Tensor instead of a list of python integers.
<ide> return_token_type_ids: (optional) Set to False to avoid returning token_type_ids (default True).
<del> return_attention_mask: (optional) Set to False to avoir returning attention mask (default True)
<add> return_attention_mask: (optional) Set to False to avoid returning attention mask (default True)
<ide> return_overflowing_tokens: (optional) Set to True to return overflowing token information (default False).
<ide> return_special_tokens_mask: (optional) Set to True to return special tokens mask information (default False).
<ide>
<ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok
<ide> if add_special_tokens:
<ide> sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
<ide> token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
<del> special_tokens_mask = self.get_special_tokens_mask(ids, pair_ids)
<ide> else:
<ide> sequence = ids + pair_ids if pair else ids
<ide> token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
<del> special_tokens_mask = [0] * (len(ids) + (len(pair_ids) if pair else 0))
<add>
<ide> if return_special_tokens_mask:
<ide> encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
<ide>
<del> # Prepare inputs as tensors if asked
<del> if return_tensors == 'tf' and is_tf_available():
<del> sequence = tf.constant([sequence])
<del> token_type_ids = tf.constant([token_type_ids])
<del> elif return_tensors == 'pt' and is_torch_available():
<del> sequence = torch.tensor([sequence])
<del> token_type_ids = torch.tensor([token_type_ids])
<del> elif return_tensors is not None:
<del> logger.warning("Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(return_tensors))
<del>
<ide> encoded_inputs["input_ids"] = sequence
<ide> if return_token_type_ids:
<ide> encoded_inputs["token_type_ids"] = token_type_ids
<ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok
<ide> if return_special_tokens_mask:
<ide> encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
<ide> encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
<del>
<ide> elif self.padding_side == 'left':
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
<add> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
<ide> if return_token_type_ids:
<ide> encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs["token_type_ids"]
<ide> if return_special_tokens_mask:
<ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok
<ide>
<ide> elif return_attention_mask:
<ide> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
<del>
<add>
<add> # Prepare inputs as tensors if asked
<add> if return_tensors == 'tf' and is_tf_available():
<add> encoded_inputs["input_ids"] = tf.constant([encoded_inputs["input_ids"]])
<add> encoded_inputs["token_type_ids"] = tf.constant([encoded_inputs["token_type_ids"]])
<add>
<add> if "attention_mask" in encoded_inputs:
<add> encoded_inputs["attention_mask"] = tf.constant([encoded_inputs["attention_mask"]])
<add>
<add> elif return_tensors == 'pt' and is_torch_available():
<add> encoded_inputs["input_ids"] = torch.tensor([encoded_inputs["input_ids"]])
<add> encoded_inputs["token_type_ids"] = torch.tensor([encoded_inputs["token_type_ids"]])
<add>
<add> if "attention_mask" in encoded_inputs:
<add> encoded_inputs["attention_mask"] = torch.tensor([encoded_inputs["attention_mask"]])
<add> elif return_tensors is not None:
<add> logger.warning(
<add> "Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(
<add> return_tensors))
<add>
<ide> return encoded_inputs
<ide>
<ide> def truncate_sequences(self, ids, pair_ids=None, num_tokens_to_remove=0, truncation_strategy='longest_first', stride=0): | 1 |
Ruby | Ruby | avoid duplicate coverage reports | 65203bbd1ea4513b4db3b7ed151626e1338ae70a | <ide><path>Library/Homebrew/dev-cmd/test-bot.rb
<ide> # as raw bytes instead of re-encoding in UTF-8.
<ide> # --fast: Don't install any packages, but run e.g. audit anyway.
<ide> # --keep-tmp: Keep temporary files written by main installs and tests that are run.
<del># --no-pull Don't use `brew pull` when possible.
<add># --no-pull: Don't use `brew pull` when possible.
<add># --coverage: Generate coverage report and send it to Coveralls.
<ide> #
<ide> # --ci-master: Shortcut for Homebrew master branch CI options.
<ide> # --ci-pr: Shortcut for Homebrew pull request CI options.
<ide> def homebrew
<ide>
<ide> if @tap.nil?
<ide> tests_args = []
<del> tests_args_coverage = []
<add> tests_args_no_compat = []
<ide> if RUBY_TWO
<ide> tests_args << "--official-cmd-taps"
<del> tests_args_coverage << "--coverage" if ENV["TRAVIS"]
<add> tests_args_no_compat << "--coverage" if ARGV.include?("--coverage")
<ide> end
<ide> test "brew", "tests", *tests_args
<ide> test "brew", "tests", "--generic", *tests_args
<del> test "brew", "tests", "--no-compat", *tests_args_coverage
<add> test "brew", "tests", "--no-compat", *tests_args_no_compat
<ide> test "brew", "readall", "--syntax"
<ide> # TODO: try to fix this on Linux at some stage.
<ide> if OS.mac?
<ide> def sanitize_ARGV_and_ENV
<ide> ARGV << "--verbose"
<ide> ARGV << "--ci-master" if ENV["TRAVIS_PULL_REQUEST"] == "false"
<ide> ENV["HOMEBREW_VERBOSE_USING_DOTS"] = "1"
<add>
<add> # Only report coverage if build runs on macOS and this is indeed Homebrew,
<add> # as we don't want this to be averaged with inferior Linux test coverage.
<add> repo = ENV["TRAVIS_REPO_SLUG"]
<add> if repo && repo.start_with?("Homebrew/") && ENV["OSX"]
<add> ARGV << "--coverage"
<add> end
<ide> end
<ide>
<ide> if ARGV.include?("--ci-master") || ARGV.include?("--ci-pr") \ | 1 |
Text | Text | add changelog entry for [ci skip] | 7b9ca16394faf535535e2d926a7e2db7f4766f76 | <ide><path>activerecord/CHANGELOG.md
<add>* Allow `where` references association names as joined table name aliases.
<add>
<add> ```ruby
<add> class Comment < ActiveRecord::Base
<add> enum label: [:default, :child]
<add> has_many :children, class_name: "Comment", foreign_key: :parent_id
<add> end
<add>
<add> # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1
<add> Comment.includes(:children).where("children.label": "child")
<add> ```
<add>
<add> *Ryuta Kamizono*
<add>
<ide> * Support storing demodulized class name for polymorphic type.
<ide>
<ide> Before Rails 6.1, storing demodulized class name is supported only for STI type | 1 |
Text | Text | add dash to handle apostrophe in title | f8b48cf3caa96c531f1bb572d9ad8986a03fe367 | <ide><path>docs/faq/Performance.md
<ide> hide_title: true
<ide> ## Table of Contents
<ide>
<ide> - [How well does Redux “scale” in terms of performance and architecture?](#how-well-does-redux-scale-in-terms-of-performance-and-architecture)
<del>- [Won't calling “all my reducers” for each action be slow?](#wont-calling-all-my-reducers-for-each-action-be-slow)
<add>- [Won't calling “all my reducers” for each action be slow?](#won-t-calling-all-my-reducers-for-each-action-be-slow)
<ide> - [Do I have to deep-clone my state in a reducer? Isn't copying my state going to be slow?](#do-i-have-to-deep-clone-my-state-in-a-reducer-isnt-copying-my-state-going-to-be-slow)
<ide> - [How can I reduce the number of store update events?](#how-can-i-reduce-the-number-of-store-update-events)
<ide> - [Will having “one state tree” cause memory problems? Will dispatching many actions take up memory?](#will-having-one-state-tree-cause-memory-problems-will-dispatching-many-actions-take-up-memory) | 1 |
Java | Java | allow customization of spel method resolution | 90bed9718f17bfd8f3d9dbe6cd2b3cf7ed2e6573 | <ide><path>org.springframework.expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2011 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public MethodExecutor resolve(EvaluationContext context, Object targetObject, St
<ide> try {
<ide> TypeConverter typeConverter = context.getTypeConverter();
<ide> Class<?> type = (targetObject instanceof Class ? (Class<?>) targetObject : targetObject.getClass());
<del> Method[] methods = type.getMethods();
<add> Method[] methods = getMethods(type);
<ide>
<ide> // If a filter is registered for this type, call it
<ide> MethodFilter filter = (this.filters != null ? this.filters.get(type) : null);
<ide> public void registerMethodFilter(Class<?> type, MethodFilter filter) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Return the set of methods for this type. The default implementation returns the
<add> * result of Class#getMethods for the given {@code type}, but subclasses may override
<add> * in order to alter the results, e.g. specifying static methods declared elsewhere.
<add> *
<add> * @param type the class for which to return the methods
<add> * @since 3.1.1
<add> */
<add> protected Method[] getMethods(Class<?> type) {
<add> return type.getMethods();
<add> }
<add>
<ide> }
<ide><path>org.springframework.expression/src/test/java/org/springframework/expression/spel/SpringEL300Tests.java
<ide> package org.springframework.expression.spel;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.fail;
<ide>
<ide> import java.lang.reflect.Field;
<add>import java.lang.reflect.Method;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> import org.springframework.expression.Expression;
<ide> import org.springframework.expression.ExpressionParser;
<ide> import org.springframework.expression.MethodExecutor;
<add>import org.springframework.expression.MethodResolver;
<ide> import org.springframework.expression.ParserContext;
<ide> import org.springframework.expression.PropertyAccessor;
<ide> import org.springframework.expression.TypedValue;
<ide> public ContextObject() {
<ide> public Map<String, String> getFourthContext() {return fourthContext;}
<ide> }
<ide>
<add> /**
<add> * Test the ability to subclass the ReflectiveMethodResolver and change how it
<add> * determines the set of methods for a type.
<add> */
<add> @Test
<add> public void testCustomStaticFunctions_SPR9038() {
<add> try {
<add> ExpressionParser parser = new SpelExpressionParser();
<add> StandardEvaluationContext context = new StandardEvaluationContext();
<add> List<MethodResolver> methodResolvers = new ArrayList<MethodResolver>();
<add> methodResolvers.add(new ReflectiveMethodResolver() {
<add> @Override
<add> protected Method[] getMethods(Class<?> type) {
<add> try {
<add> return new Method[] {
<add> Integer.class.getDeclaredMethod("parseInt", new Class[] {
<add> String.class, Integer.TYPE }) };
<add> } catch (NoSuchMethodException e1) {
<add> return new Method[0];
<add> }
<add> }
<add> });
<add>
<add> context.setMethodResolvers(methodResolvers);
<add> org.springframework.expression.Expression expression =
<add> parser.parseExpression("parseInt('-FF', 16)");
<add>
<add> Integer result = expression.getValue(context, "", Integer.class);
<add> assertEquals("Equal assertion failed: ", -255, result.intValue());
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> fail("Unexpected exception: "+e.toString());
<add> }
<add> }
<add>
<ide> }
<ide>
<ide> | 2 |
Go | Go | move "create" to daemon/create.go | 80f3272ee9957c537271462a688a7de88aaa92c0 | <ide><path>daemon/create.go
<add>package daemon
<add>
<add>import (
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/graph"
<add> "github.com/docker/docker/pkg/parsers"
<add> "github.com/docker/docker/runconfig"
<add>)
<add>
<add>func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status {
<add> var name string
<add> if len(job.Args) == 1 {
<add> name = job.Args[0]
<add> } else if len(job.Args) > 1 {
<add> return job.Errorf("Usage: %s", job.Name)
<add> }
<add> config := runconfig.ContainerConfigFromJob(job)
<add> if config.Memory != 0 && config.Memory < 524288 {
<add> return job.Errorf("Minimum memory limit allowed is 512k")
<add> }
<add> if config.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
<add> job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n")
<add> config.Memory = 0
<add> }
<add> if config.Memory > 0 && !daemon.SystemConfig().SwapLimit {
<add> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n")
<add> config.MemorySwap = -1
<add> }
<add> container, buildWarnings, err := daemon.Create(config, name)
<add> if err != nil {
<add> if daemon.Graph().IsNotExist(err) {
<add> _, tag := parsers.ParseRepositoryTag(config.Image)
<add> if tag == "" {
<add> tag = graph.DEFAULTTAG
<add> }
<add> return job.Errorf("No such image: %s (tag: %s)", config.Image, tag)
<add> }
<add> return job.Error(err)
<add> }
<add> if !container.Config.NetworkDisabled && daemon.SystemConfig().IPv4ForwardingDisabled {
<add> job.Errorf("IPv4 forwarding is disabled.\n")
<add> }
<add> job.Eng.Job("log", "create", container.ID, daemon.Repositories().ImageName(container.Image)).Run()
<add> // FIXME: this is necessary because daemon.Create might return a nil container
<add> // with a non-nil error. This should not happen! Once it's fixed we
<add> // can remove this workaround.
<add> if container != nil {
<add> job.Printf("%s\n", container.ID)
<add> }
<add> for _, warning := range buildWarnings {
<add> job.Errorf("%s\n", warning)
<add> }
<add> return engine.StatusOK
<add>}
<add>
<add>// Create creates a new container from the given configuration with a given name.
<add>func (daemon *Daemon) Create(config *runconfig.Config, name string) (*Container, []string, error) {
<add> var (
<add> container *Container
<add> warnings []string
<add> )
<add>
<add> img, err := daemon.repositories.LookupImage(config.Image)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add> if err := daemon.checkImageDepth(img); err != nil {
<add> return nil, nil, err
<add> }
<add> if warnings, err = daemon.mergeAndVerifyConfig(config, img); err != nil {
<add> return nil, nil, err
<add> }
<add> if container, err = daemon.newContainer(name, config, img); err != nil {
<add> return nil, nil, err
<add> }
<add> if err := daemon.createRootfs(container, img); err != nil {
<add> return nil, nil, err
<add> }
<add> if err := container.ToDisk(); err != nil {
<add> return nil, nil, err
<add> }
<add> if err := daemon.Register(container); err != nil {
<add> return nil, nil, err
<add> }
<add> return container, warnings, nil
<add>}
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> if err := eng.Register("export", daemon.ContainerExport); err != nil {
<ide> return err
<ide> }
<add> if err := eng.Register("create", daemon.ContainerCreate); err != nil {
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide> func (daemon *Daemon) restore() error {
<ide> return nil
<ide> }
<ide>
<del>// Create creates a new container from the given configuration with a given name.
<del>func (daemon *Daemon) Create(config *runconfig.Config, name string) (*Container, []string, error) {
<del> var (
<del> container *Container
<del> warnings []string
<del> )
<del>
<del> img, err := daemon.repositories.LookupImage(config.Image)
<del> if err != nil {
<del> return nil, nil, err
<del> }
<del> if err := daemon.checkImageDepth(img); err != nil {
<del> return nil, nil, err
<del> }
<del> if warnings, err = daemon.mergeAndVerifyConfig(config, img); err != nil {
<del> return nil, nil, err
<del> }
<del> if container, err = daemon.newContainer(name, config, img); err != nil {
<del> return nil, nil, err
<del> }
<del> if err := daemon.createRootfs(container, img); err != nil {
<del> return nil, nil, err
<del> }
<del> if err := container.ToDisk(); err != nil {
<del> return nil, nil, err
<del> }
<del> if err := daemon.Register(container); err != nil {
<del> return nil, nil, err
<del> }
<del> return container, warnings, nil
<del>}
<del>
<ide> func (daemon *Daemon) checkImageDepth(img *image.Image) error {
<ide> // We add 2 layers to the depth because the container's rw and
<ide> // init layer add to the restriction
<ide><path>server/container.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/pkg/graphdb"
<del> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/tailfile"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> func (srv *Server) ContainerCommit(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>func (srv *Server) ContainerCreate(job *engine.Job) engine.Status {
<del> var name string
<del> if len(job.Args) == 1 {
<del> name = job.Args[0]
<del> } else if len(job.Args) > 1 {
<del> return job.Errorf("Usage: %s", job.Name)
<del> }
<del> config := runconfig.ContainerConfigFromJob(job)
<del> if config.Memory != 0 && config.Memory < 524288 {
<del> return job.Errorf("Minimum memory limit allowed is 512k")
<del> }
<del> if config.Memory > 0 && !srv.daemon.SystemConfig().MemoryLimit {
<del> job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n")
<del> config.Memory = 0
<del> }
<del> if config.Memory > 0 && !srv.daemon.SystemConfig().SwapLimit {
<del> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n")
<del> config.MemorySwap = -1
<del> }
<del> container, buildWarnings, err := srv.daemon.Create(config, name)
<del> if err != nil {
<del> if srv.daemon.Graph().IsNotExist(err) {
<del> _, tag := parsers.ParseRepositoryTag(config.Image)
<del> if tag == "" {
<del> tag = graph.DEFAULTTAG
<del> }
<del> return job.Errorf("No such image: %s (tag: %s)", config.Image, tag)
<del> }
<del> return job.Error(err)
<del> }
<del> if !container.Config.NetworkDisabled && srv.daemon.SystemConfig().IPv4ForwardingDisabled {
<del> job.Errorf("IPv4 forwarding is disabled.\n")
<del> }
<del> srv.LogEvent("create", container.ID, srv.daemon.Repositories().ImageName(container.Image))
<del> // FIXME: this is necessary because daemon.Create might return a nil container
<del> // with a non-nil error. This should not happen! Once it's fixed we
<del> // can remove this workaround.
<del> if container != nil {
<del> job.Printf("%s\n", container.ID)
<del> }
<del> for _, warning := range buildWarnings {
<del> job.Errorf("%s\n", warning)
<del> }
<del> return engine.StatusOK
<del>}
<del>
<ide> func (srv *Server) ContainerRestart(job *engine.Job) engine.Status {
<ide> if len(job.Args) != 1 {
<ide> return job.Errorf("Usage: %s CONTAINER\n", job.Name)
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> job.Eng.Hack_SetGlobalVar("httpapi.daemon", srv.daemon)
<ide>
<ide> for name, handler := range map[string]engine.Handler{
<del> "create": srv.ContainerCreate,
<ide> "stop": srv.ContainerStop,
<ide> "restart": srv.ContainerRestart,
<ide> "start": srv.ContainerStart, | 4 |
Javascript | Javascript | add getattributens to domstubs for svg example | 4f22ba54bf9779226dfee4c44d5c7bcd056e5662 | <ide><path>examples/node/domstubs.js
<ide> function DOMElement(name) {
<ide>
<ide> DOMElement.prototype = {
<ide>
<add> getAttributeNS: function DOMElement_getAttributeNS(NS, name) {
<add> return name in this.attributes ? this.attributes[name] : null;
<add> },
<add>
<ide> setAttributeNS: function DOMElement_setAttributeNS(NS, name, value) {
<ide> value = value || '';
<ide> value = xmlEncode(value); | 1 |
Javascript | Javascript | remove unused assignment | 1d525f55bc9f090a167acc286529b9a424dd0d5a | <ide><path>lib/fs.js
<ide> function rmdir(path, options, callback) {
<ide> path = pathModule.toNamespacedPath(getValidatedPath(path));
<ide>
<ide> if (options && options.recursive) {
<del> options = validateRmOptions(
<add> validateRmOptions(
<ide> path,
<ide> { ...options, force: true },
<ide> true, | 1 |
Python | Python | modernize tokenizer tests for contractions | aafc894285f1a3bb5fd6c2bb3ce8e65da5bb408e | <ide><path>spacy/tests/tokenizer/test_contractions.py
<ide> from __future__ import unicode_literals
<add>from ...en import English
<ide> import pytest
<ide>
<add>@pytest.fixture
<add>def en_tokenizer():
<add> return English.Defaults.create_tokenizer()
<ide>
<del>def test_possess(en_tokenizer):
<del> tokens = en_tokenizer("Mike's")
<del> assert en_tokenizer.vocab.strings[tokens[0].orth] == "Mike"
<del> assert en_tokenizer.vocab.strings[tokens[1].orth] == "'s"
<add>
<add>@pytest.mark.parametrize('inputs', [("Robin's", "Robin"), ("Alexis's", "Alexis")])
<add>def test_tokenizer_handles_poss_contraction(en_tokenizer, inputs):
<add> text_poss, text = inputs
<add> tokens = en_tokenizer(text_poss)
<ide> assert len(tokens) == 2
<add> assert tokens[0].text == text
<add> assert tokens[1].text == "'s"
<ide>
<ide>
<del>def test_apostrophe(en_tokenizer):
<del> tokens = en_tokenizer("schools'")
<add>@pytest.mark.parametrize('text', ["schools'", "Alexis'"])
<add>def test_tokenizer_splits_trailing_apos(en_tokenizer, text):
<add> tokens = en_tokenizer(text)
<ide> assert len(tokens) == 2
<del> assert tokens[1].orth_ == "'"
<del> assert tokens[0].orth_ == "schools"
<add> assert tokens[0].text == text.split("'")[0]
<add> assert tokens[1].text == "'"
<add>
<add>
<add>@pytest.mark.parametrize('text', ["'em", "nothin'", "ol'"])
<add>def text_tokenizer_doesnt_split_apos_exc(en_tokenizer, text):
<add> tokens = en_tokenizer(text)
<add> assert len(tokens) == 1
<add> assert tokens[0].text == text
<ide>
<ide>
<del>def test_LL(en_tokenizer):
<del> tokens = en_tokenizer("we'll")
<add>@pytest.mark.parametrize('text', ["we'll", "You'll", "there'll"])
<add>def test_tokenizer_handles_ll_contraction(en_tokenizer, text):
<add> tokens = en_tokenizer(text)
<ide> assert len(tokens) == 2
<del> assert tokens[1].orth_ == "'ll"
<add> assert tokens[0].text == text.split("'")[0]
<add> assert tokens[1].text == "'ll"
<ide> assert tokens[1].lemma_ == "will"
<del> assert tokens[0].orth_ == "we"
<ide>
<ide>
<del>def test_aint(en_tokenizer):
<del> tokens = en_tokenizer("ain't")
<del> assert len(tokens) == 2
<del> assert tokens[0].orth_ == "ai"
<del> assert tokens[0].lemma_ == "be"
<del> assert tokens[1].orth_ == "n't"
<del> assert tokens[1].lemma_ == "not"
<add>@pytest.mark.parametrize('inputs', [("can't", "Can't"), ("ain't", "Ain't")])
<add>def test_tokenizer_handles_capitalization(en_tokenizer, inputs):
<add> text_lower, text_title = inputs
<add> tokens_lower = en_tokenizer(text_lower)
<add> tokens_title = en_tokenizer(text_title)
<add> assert tokens_title[0].text == tokens_lower[0].text.title()
<add> assert tokens_lower[0].text == tokens_title[0].text.lower()
<add> assert tokens_lower[1].text == tokens_title[1].text
<ide>
<del>def test_capitalized(en_tokenizer):
<del> tokens = en_tokenizer("can't")
<del> assert len(tokens) == 2
<del> tokens = en_tokenizer("Can't")
<del> assert len(tokens) == 2
<del> tokens = en_tokenizer("Ain't")
<del> assert len(tokens) == 2
<del> assert tokens[0].orth_ == "Ai"
<del> assert tokens[0].lemma_ == "be"
<ide>
<add>@pytest.mark.parametrize('pron', ["I", "You", "He", "She", "It", "We", "They"])
<add>def test_tokenizer_keeps_title_case(en_tokenizer, pron):
<add> for contraction in ["'ll", "'d"]:
<add> tokens = en_tokenizer(pron + contraction)
<add> assert tokens[0].text == pron
<add> assert tokens[1].text == contraction
<ide>
<del>def test_punct(en_tokenizer):
<del> tokens = en_tokenizer("We've")
<del> assert len(tokens) == 2
<del> tokens = en_tokenizer("``We've")
<del> assert len(tokens) == 3
<ide>
<add>@pytest.mark.parametrize('exc', ["Ill", "ill", "Hell", "hell", "Well", "well"])
<add>def test_tokenizer_excludes_ambiguous(en_tokenizer, exc):
<add> tokens = en_tokenizer(exc)
<add> assert len(tokens) == 1
<ide>
<del>@pytest.mark.xfail
<del>def test_therell(en_tokenizer):
<del> tokens = en_tokenizer("there'll")
<add>
<add>@pytest.mark.parametrize('inputs', [("We've", "``We've"), ("couldn't", "couldn't)")])
<add>def test_tokenizer_splits_defined_punct(en_tokenizer, inputs):
<add> wo_punct, w_punct = inputs
<add> tokens = en_tokenizer(wo_punct)
<ide> assert len(tokens) == 2
<del> assert tokens[0].text == "there"
<del> assert tokens[1].text == "there"
<add> tokens = en_tokenizer(w_punct)
<add> assert len(tokens) == 3 | 1 |
Ruby | Ruby | add new unit tests | dd898e58b836c0d39b705a5043dd90294d7543c1 | <ide><path>Library/Homebrew/test/keg_relocate/grep_spec.rb
<add># typed: false
<add># frozen_string_literal: true
<add>
<add>require "keg_relocate"
<add>
<add>describe Keg do
<add> subject(:keg) { described_class.new(HOMEBREW_CELLAR/"foo/1.0.0") }
<add>
<add> let(:dir) { HOMEBREW_CELLAR/"foo/1.0.0" }
<add> let(:text_file) { dir/"file.txt" }
<add> let(:binary_file) { dir/"file.bin" }
<add>
<add> before do
<add> dir.mkpath
<add> end
<add>
<add> def setup_text_file
<add> text_file.atomic_write <<~EOS
<add> #{dir}/file.txt
<add> /foo#{dir}/file.txt
<add> foo/bar:#{dir}/file.txt
<add> foo/bar:/foo#{dir}/file.txt
<add> #{dir}/bar.txt:#{dir}/baz.txt
<add> EOS
<add> end
<add>
<add> def setup_binary_file
<add> binary_file.atomic_write <<~EOS
<add> \x00
<add> EOS
<add> end
<add>
<add> describe "#each_unique_file_matching" do
<add> specify "find string matches to path" do
<add> setup_text_file
<add>
<add> string_matches = Set.new
<add> keg.each_unique_file_matching(dir) do |file|
<add> string_matches << file
<add> end
<add>
<add> expect(string_matches.size).to eq 1
<add> end
<add> end
<add>
<add> describe "#each_unique_binary_file" do
<add> specify "find null bytes in binaries" do
<add> setup_binary_file
<add>
<add> binary_matches = Set.new
<add> keg.each_unique_binary_file do |file|
<add> binary_matches << file
<add> end
<add>
<add> expect(binary_matches.size).to eq 1
<add> end
<add> end
<add>end | 1 |
Javascript | Javascript | add blueprints for mu instance initializer | ab27246721029814ca3feb1264d09f3965b7d734 | <ide><path>blueprints/instance-initializer-test/index.js
<ide> const path = require('path');
<ide> const stringUtils = require('ember-cli-string-utils');
<ide>
<ide> const useTestFrameworkDetector = require('../test-framework-detector');
<add>const isModuleUnificationProject = require('../module-unification').isModuleUnificationProject;
<ide>
<ide> module.exports = useTestFrameworkDetector({
<ide> description: 'Generates an instance initializer unit test.',
<add>
<add> fileMapTokens: function() {
<add> if (isModuleUnificationProject(this.project)) {
<add> return {
<add> __root__(options) {
<add> if (options.pod) {
<add> throw new Error('Pods arenʼt supported within a module unification app');
<add> } else if (options.inDummy) {
<add> return path.join('tests', 'dummy', 'src', 'init');
<add> }
<add> return path.join('src', 'init');
<add> },
<add> __testType__() {
<add> return '';
<add> },
<add> };
<add> } else {
<add> return {
<add> __root__() {
<add> return 'tests';
<add> },
<add> __testType__() {
<add> return 'unit';
<add> },
<add> };
<add> }
<add> },
<ide> locals: function(options) {
<add> let modulePrefix = stringUtils.dasherize(options.project.config().modulePrefix);
<add> if (isModuleUnificationProject(this.project)) {
<add> modulePrefix += '/init';
<add> }
<ide> return {
<ide> friendlyTestName: ['Unit', 'Instance Initializer', options.entity.name].join(' | '),
<del> dasherizedModulePrefix: stringUtils.dasherize(options.project.config().modulePrefix),
<add> modulePrefix,
<ide> destroyAppExists: fs.existsSync(
<ide> path.join(this.project.root, '/tests/helpers/destroy-app.js')
<ide> ),
<add><path>blueprints/instance-initializer-test/mocha-files/__root__/__testType__/__path__/__name__-test.js
<del><path>blueprints/instance-initializer-test/mocha-files/tests/unit/instance-initializers/__name__-test.js
<ide> import { expect } from 'chai';
<ide> import { describe, it, beforeEach } from 'mocha';
<ide> import Application from '@ember/application';
<ide> import { run } from '@ember/runloop';
<del>import { initialize } from '<%= dasherizedModulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<add>import { initialize } from '<%= modulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<ide> import destroyApp from '../../helpers/destroy-app';
<ide>
<ide> describe('<%= friendlyTestName %>', function() {
<add><path>blueprints/instance-initializer-test/qunit-files/__root__/__testType__/__path__/__name__-test.js
<del><path>blueprints/instance-initializer-test/qunit-files/tests/unit/instance-initializers/__name__-test.js
<ide> import Application from '@ember/application';
<ide> import { run } from '@ember/runloop';
<del>import { initialize } from '<%= dasherizedModulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<add>import { initialize } from '<%= modulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<ide> import { module, test } from 'qunit';<% if (destroyAppExists) { %>
<ide> import destroyApp from '../../helpers/destroy-app';<% } %>
<ide>
<add><path>blueprints/instance-initializer-test/qunit-rfc-232-files/__root__/__testType__/__path__/__name__-test.js
<del><path>blueprints/instance-initializer-test/qunit-rfc-232-files/tests/unit/instance-initializers/__name__-test.js
<ide> import Application from '@ember/application';
<ide>
<del>import { initialize } from '<%= dasherizedModulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<add>import { initialize } from '<%= modulePrefix %>/instance-initializers/<%= dasherizedModuleName %>';
<ide> import { module, test } from 'qunit';
<ide> <% if (destroyAppExists) { %>import destroyApp from '../../helpers/destroy-app';<% } else { %>import { run } from '@ember/runloop';<% } %>
<ide>
<ide><path>blueprints/instance-initializer/index.js
<ide> 'use strict';
<ide>
<add>const path = require('path');
<add>const isModuleUnificationProject = require('../module-unification').isModuleUnificationProject;
<add>
<ide> module.exports = {
<ide> description: 'Generates an instance initializer.',
<add>
<add> fileMapTokens() {
<add> if (isModuleUnificationProject(this.project)) {
<add> return {
<add> __root__(options) {
<add> if (options.pod) {
<add> throw new Error('Pods arenʼt supported within a module unification app');
<add> } else if (options.inDummy) {
<add> return path.join('tests', 'dummy', 'src/init');
<add> }
<add> return 'src/init';
<add> },
<add> };
<add> }
<add> },
<ide> };
<ide><path>node-tests/blueprints/instance-initializer-test-test.js
<ide> const expect = chai.expect;
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const fixture = require('../helpers/fixture');
<add>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> });
<ide> });
<ide> });
<add>
<add> describe('in app - module unification', function() {
<add> beforeEach(function() {
<add> return emberNew().then(() => fs.ensureDirSync('src'));
<add> });
<add>
<add> describe('with [email protected]', function() {
<add> beforeEach(function() {
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<add>
<add> it('instance-initializer-test foo', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.equal(
<add> fixture('instance-initializer-test/module-unification/default.js')
<add> );
<add> });
<add> });
<add> });
<add>
<add> describe('with [email protected]', function() {
<add> beforeEach(function() {
<add> generateFakePackageManifest('ember-cli-qunit', '4.2.0');
<add> });
<add>
<add> it('instance-initializer-test foo', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.equal(
<add> fixture('instance-initializer-test/module-unification/rfc232.js')
<add> );
<add> });
<add> });
<add> });
<add>
<add> describe('with ember-cli-mocha', function() {
<add> beforeEach(function() {
<add> modifyPackages([
<add> { name: 'ember-cli-qunit', delete: true },
<add> { name: 'ember-cli-mocha', dev: true },
<add> ]);
<add> });
<add>
<add> it('instance-initializer-test foo for mocha', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.equal(
<add> fixture('instance-initializer-test/module-unification/mocha.js')
<add> );
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe('in addon - module unification', function() {
<add> beforeEach(function() {
<add> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> });
<add>
<add> describe('with [email protected]', function() {
<add> beforeEach(function() {
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<add>
<add> it('instance-initializer-test foo', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.equal(
<add> fixture('instance-initializer-test/module-unification/dummy.js')
<add> );
<add> });
<add> });
<add>
<add> it('instance-initializer-test foo --dummy', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo', '--dummy'], _file => {
<add> expect(_file('tests/dummy/src/init/instance-initializers/foo-test.js')).to.equal(
<add> fixture('instance-initializer-test/module-unification/dummy.js')
<add> );
<add> });
<add> });
<add> });
<add> });
<ide> });
<ide><path>node-tests/blueprints/instance-initializer-test.js
<ide> const setupTestHooks = blueprintHelpers.setupTestHooks;
<ide> const emberNew = blueprintHelpers.emberNew;
<ide> const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
<ide> const setupPodConfig = blueprintHelpers.setupPodConfig;
<add>const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<add>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const fixture = require('../helpers/fixture');
<ide> describe('Blueprint: instance-initializer', function() {
<ide> );
<ide> });
<ide> });
<add>
<add> describe('in app - module unification', function() {
<add> beforeEach(function() {
<add> return emberNew()
<add> .then(() => fs.ensureDirSync('src'))
<add> .then(() => generateFakePackageManifest('ember-cli-qunit', '4.1.0'));
<add> });
<add>
<add> it('instance-initializer foo', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer.js')
<add> );
<add>
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.contain(
<add> "import { initialize } from 'my-app/init/instance-initializers/foo';"
<add> );
<add> });
<add> });
<add>
<add> it('instance-initializer foo/bar', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo/bar'], _file => {
<add> expect(_file('src/init/instance-initializers/foo/bar.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer-nested.js')
<add> );
<add>
<add> expect(_file('src/init/instance-initializers/foo/bar-test.js')).to.contain(
<add> "import { initialize } from 'my-app/init/instance-initializers/foo/bar';"
<add> );
<add> });
<add> });
<add>
<add> it('instance-initializer foo --pod', function() {
<add> return expectError(
<add> emberGenerateDestroy(['instance-initializer', 'foo', '--pod']),
<add> 'Pods arenʼt supported within a module unification app'
<add> );
<add> });
<add>
<add> it('instance-initializer foo/bar --pod', function() {
<add> return expectError(
<add> emberGenerateDestroy(['instance-initializer', 'foo/bar', '--pod']),
<add> 'Pods arenʼt supported within a module unification app'
<add> );
<add> });
<add>
<add> describe('with podModulePrefix', function() {
<add> beforeEach(function() {
<add> setupPodConfig({ podModulePrefix: true });
<add> });
<add>
<add> it('instance-initializer foo --pod', function() {
<add> return expectError(
<add> emberGenerateDestroy(['instance-initializer', 'foo', '--pod']),
<add> 'Pods arenʼt supported within a module unification app'
<add> );
<add> });
<add>
<add> it('instance-initializer foo/bar --pod', function() {
<add> return expectError(
<add> emberGenerateDestroy(['instance-initializer', 'foo/bar', '--pod']),
<add> 'Pods arenʼt supported within a module unification app'
<add> );
<add> });
<add> });
<add> });
<add> describe('in addon - module unification', function() {
<add> beforeEach(function() {
<add> return emberNew({ target: 'addon' })
<add> .then(() => fs.ensureDirSync('src'))
<add> .then(() => generateFakePackageManifest('ember-cli-qunit', '4.1.0'));
<add> });
<add>
<add> it('instance-initializer foo', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo'], _file => {
<add> expect(_file('src/init/instance-initializers/foo.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer.js')
<add> );
<add>
<add> expect(_file('tests/unit/instance-initializers/foo-test.js'));
<add> });
<add> });
<add>
<add> it('instance-initializer foo/bar', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo/bar'], _file => {
<add> expect(_file('src/init/instance-initializers/foo/bar.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer-nested.js')
<add> );
<add>
<add> expect(_file('src/init/instance-initializers/foo/bar-test.js'));
<add> });
<add> });
<add>
<add> it('instance-initializer foo --dummy', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo', '--dummy'], _file => {
<add> expect(_file('tests/dummy/src/init/instance-initializers/foo.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer.js')
<add> );
<add>
<add> expect(_file('src/init/instance-initializers/foo.js')).to.not.exist;
<add>
<add> expect(_file('src/init/instance-initializers/foo-test.js')).to.not.exist;
<add> });
<add> });
<add>
<add> it('instance-initializer foo/bar --dummy', function() {
<add> return emberGenerateDestroy(['instance-initializer', 'foo/bar', '--dummy'], _file => {
<add> expect(_file('tests/dummy/src/init/instance-initializers/foo/bar.js')).to.equal(
<add> fixture('instance-initializer/instance-initializer-nested.js')
<add> );
<add>
<add> expect(_file('src/init/instance-initializers/foo/bar.js')).to.not.exist;
<add>
<add> expect(_file('src/init/instance-initializers/foo/bar-test.js')).to.not.exist;
<add> });
<add> });
<add> });
<ide> });
<ide><path>node-tests/fixtures/instance-initializer-test/module-unification/default.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>import { initialize } from 'my-app/init/instance-initializers/foo';
<add>import { module, test } from 'qunit';
<add>
<add>module('Unit | Instance Initializer | foo', {
<add> beforeEach() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.appInstance = this.application.buildInstance();
<add> });
<add> },
<add> afterEach() {
<add> run(this.appInstance, 'destroy');
<add> run(this.application, 'destroy');
<add> }
<add>});
<add>
<add>// Replace this with your real tests.
<add>test('it works', function(assert) {
<add> initialize(this.appInstance);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add>});
<ide><path>node-tests/fixtures/instance-initializer-test/module-unification/dummy.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>import { initialize } from 'dummy/init/instance-initializers/foo';
<add>import { module, test } from 'qunit';
<add>
<add>module('Unit | Instance Initializer | foo', {
<add> beforeEach() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.appInstance = this.application.buildInstance();
<add> });
<add> },
<add> afterEach() {
<add> run(this.appInstance, 'destroy');
<add> run(this.application, 'destroy');
<add> }
<add>});
<add>
<add>// Replace this with your real tests.
<add>test('it works', function(assert) {
<add> initialize(this.appInstance);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add>});
<ide><path>node-tests/fixtures/instance-initializer-test/module-unification/mocha.js
<add>import { expect } from 'chai';
<add>import { describe, it, beforeEach } from 'mocha';
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>import { initialize } from 'my-app/init/instance-initializers/foo';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>describe('Unit | Instance Initializer | foo', function() {
<add> let application, appInstance;
<add>
<add> beforeEach(function() {
<add> run(function() {
<add> application = Application.create();
<add> appInstance = application.buildInstance();
<add> });
<add> });
<add>
<add> afterEach(function() {
<add> run(appInstance, 'destroy');
<add> destroyApp(application);
<add> });
<add>
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> initialize(appInstance);
<add>
<add> // you would normally confirm the results of the initializer here
<add> expect(true).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/fixtures/instance-initializer-test/module-unification/rfc232.js
<add>import Application from '@ember/application';
<add>
<add>import { initialize } from 'my-app/init/instance-initializers/foo';
<add>import { module, test } from 'qunit';
<add>import { run } from '@ember/runloop';
<add>
<add>module('Unit | Instance Initializer | foo', function(hooks) {
<add> hooks.beforeEach(function() {
<add> this.TestApplication = Application.extend();
<add> this.TestApplication.instanceInitializer({
<add> name: 'initializer under test',
<add> initialize
<add> });
<add> this.application = this.TestApplication.create({ autoboot: false });
<add> this.instance = this.application.buildInstance();
<add> });
<add> hooks.afterEach(function() {
<add> run(this.application, 'destroy');
<add> run(this.instance, 'destroy');
<add> });
<add>
<add> // Replace this with your real tests.
<add> test('it works', async function(assert) {
<add> await this.instance.boot();
<add>
<add> assert.ok(true);
<add> });
<add>}); | 11 |
Go | Go | use containerd/sys to detect usernamespaces | 4534a7afc31abb39730f41e9311f0eee6b4eda25 | <ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/containerd/containerd/defaults"
<ide> "github.com/containerd/containerd/pkg/dialer"
<ide> "github.com/containerd/containerd/remotes/docker"
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/api/types"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> bkconfig "github.com/moby/buildkit/cmd/buildkitd/config"
<ide> "github.com/moby/buildkit/util/resolver"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/sirupsen/logrus"
<ide>
<ide> // register graph drivers
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> sysInfo := d.RawSysInfo(false)
<ide> // Check if Devices cgroup is mounted, it is hard requirement for container security,
<ide> // on Linux.
<del> if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled && !rsystem.RunningInUserNS() {
<add> if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled && !sys.RunningInUserNS() {
<ide> return nil, errors.New("Devices cgroup isn't mounted")
<ide> }
<ide>
<ide><path>daemon/daemon_unix.go
<ide> import (
<ide>
<ide> statsV1 "github.com/containerd/cgroups/stats/v1"
<ide> statsV2 "github.com/containerd/cgroups/v2/stats"
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/blkiodev"
<ide> pblkiodev "github.com/docker/docker/api/types/blkiodev"
<ide> import (
<ide> lntypes "github.com/docker/libnetwork/types"
<ide> "github.com/moby/sys/mount"
<ide> "github.com/opencontainers/runc/libcontainer/cgroups"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> "github.com/pkg/errors"
<ide> func setMayDetachMounts() error {
<ide> // Setting may_detach_mounts does not work in an
<ide> // unprivileged container. Ignore the error, but log
<ide> // it if we appear not to be in that situation.
<del> if !rsystem.RunningInUserNS() {
<add> if !sys.RunningInUserNS() {
<ide> logrus.Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
<ide> }
<ide> return nil
<ide> func setupOOMScoreAdj(score int) error {
<ide> // Setting oom_score_adj does not work in an
<ide> // unprivileged container. Ignore the error, but log
<ide> // it if we appear not to be in that situation.
<del> if !rsystem.RunningInUserNS() {
<add> if !sys.RunningInUserNS() {
<ide> logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
<ide> }
<ide> return nil
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> import (
<ide> "strings"
<ide> "sync"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/chrootarchive"
<ide> import (
<ide> "github.com/docker/docker/pkg/locker"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/sys/mount"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> func supportsAufs() error {
<ide> // proc/filesystems for when aufs is supported
<ide> exec.Command("modprobe", "aufs").Run()
<ide>
<del> if rsystem.RunningInUserNS() {
<add> if sys.RunningInUserNS() {
<ide> return ErrAufsNested
<ide> }
<ide>
<ide><path>daemon/graphdriver/copy/copy.go
<ide> import (
<ide> "syscall"
<ide> "time"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/system"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "golang.org/x/sys/unix"
<ide> )
<ide>
<ide> func DirCopy(srcDir, dstDir string, copyMode Mode, copyXattrs bool) error {
<ide> }
<ide>
<ide> case mode&os.ModeDevice != 0:
<del> if rsystem.RunningInUserNS() {
<add> if sys.RunningInUserNS() {
<ide> // cannot create a device if running in user namespace
<ide> return nil
<ide> }
<ide><path>daemon/graphdriver/fuse-overlayfs/fuseoverlayfs.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/daemon/graphdriver/overlayutils"
<ide> "github.com/docker/docker/pkg/archive"
<ide> import (
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/sys/mount"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64
<ide> GIDMaps: d.gidMaps,
<ide> // Use AUFS whiteout format: https://github.com/containers/storage/blob/39a8d5ed9843844eafb5d2ba6e6a7510e0126f40/drivers/overlay/overlay.go#L1084-L1089
<ide> WhiteoutFormat: archive.AUFSWhiteoutFormat,
<del> InUserNS: rsystem.RunningInUserNS(),
<add> InUserNS: sys.RunningInUserNS(),
<ide> }); err != nil {
<ide> return 0, err
<ide> }
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> import (
<ide> "strings"
<ide> "sync"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/daemon/graphdriver/overlayutils"
<ide> "github.com/docker/docker/daemon/graphdriver/quota"
<ide> import (
<ide> "github.com/docker/docker/pkg/system"
<ide> units "github.com/docker/go-units"
<ide> "github.com/moby/sys/mount"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/opencontainers/selinux/go-selinux/label"
<ide> "github.com/sirupsen/logrus"
<ide> "golang.org/x/sys/unix"
<ide> func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64
<ide> UIDMaps: d.uidMaps,
<ide> GIDMaps: d.gidMaps,
<ide> WhiteoutFormat: archive.OverlayWhiteoutFormat,
<del> InUserNS: rsystem.RunningInUserNS(),
<add> InUserNS: sys.RunningInUserNS(),
<ide> }); err != nil {
<ide> return 0, err
<ide> }
<ide><path>daemon/graphdriver/quota/projectquota.go
<ide> import (
<ide> "path/filepath"
<ide> "unsafe"
<ide>
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> "golang.org/x/sys/unix"
<ide> func NewControl(basePath string) (*Control, error) {
<ide> // If we are running in a user namespace quota won't be supported for
<ide> // now since makeBackingFsDev() will try to mknod().
<ide> //
<del> if rsystem.RunningInUserNS() {
<add> if sys.RunningInUserNS() {
<ide> return nil, ErrQuotaNotSupported
<ide> }
<ide>
<ide><path>daemon/oci_linux.go
<ide> import (
<ide>
<ide> "github.com/containerd/containerd/containers"
<ide> coci "github.com/containerd/containerd/oci"
<add> "github.com/containerd/containerd/sys"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<ide> daemonconfig "github.com/docker/docker/daemon/config"
<ide> import (
<ide> "github.com/opencontainers/runc/libcontainer/apparmor"
<ide> "github.com/opencontainers/runc/libcontainer/cgroups"
<ide> "github.com/opencontainers/runc/libcontainer/devices"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/opencontainers/runc/libcontainer/user"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/pkg/errors"
<ide> func WithDevices(daemon *Daemon, c *container.Container) coci.SpecOpts {
<ide> var devs []specs.LinuxDevice
<ide> devPermissions := s.Linux.Resources.Devices
<ide>
<del> if c.HostConfig.Privileged && !rsystem.RunningInUserNS() {
<add> if c.HostConfig.Privileged && !sys.RunningInUserNS() {
<ide> hostDevices, err := devices.HostDevices()
<ide> if err != nil {
<ide> return err | 8 |
Text | Text | remove precomputing style | e09378d92dbaef3e3a9bb32e70b5482cc39eb48b | <ide><path>docs/DirectManipulation.md
<ide> that call back to the `TouchableOpacity` component.
<ide> `TouchableHighlight`, in contrast, is backed by a native view and only
<ide> requires that we implement `setNativeProps`.
<ide>
<del>## Precomputing style
<del>
<del>We learned above that `setNativeProps` is a wrapper around
<del>`RCTUIManager.updateView`, which is also used internally by React to
<del>perform updates on re-render. One important difference is that
<del>`setNativeProps` does not call `precomputeStyle`, which is done
<del>internally by React, and so the `transform` property will not work if
<del>you try to update it manually with `setNativeProps`. To fix this,
<del>you can call `precomputeStyle` on your object first:
<del>
<del>```javascript
<del>var precomputeStyle = require('precomputeStyle');
<del>
<del>var App = React.createClass({
<del> componentDidMount() {
<del> var nativeProps = precomputeStyle({transform: [{rotate: '45deg'}]});
<del> this._root.setNativeProps(nativeProps);
<del> },
<del>
<del> render() {
<del> return (
<del> <View ref={component => this._root = component}
<del> style={styles.container}>
<del> <Text>Precompute style!</Text>
<del> </View>
<del> )
<del> },
<del>});
<del>```
<del>[Run this example](https://rnplay.org/apps/8_mIAA)
<del>
<ide> ## setNativeProps to clear TextInput value
<ide>
<ide> Another very common use case of `setNativeProps` is to clear the value | 1 |
Javascript | Javascript | add tred.com to the showcase page | e99c001d58a6257941f36b8f63d0f8ae3fffc6d7 | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> infoLink: 'https://techcrunch.com/2016/02/01/refinery29-debuts-its-first-app-a-morning-news-round-up-called-refinery29-am/',
<ide> infoTitle: 'Refinery29 debuts its first app',
<ide> },
<add> {
<add> name: 'TRED - Sell your car for more',
<add> icon: 'http://a1.mzstatic.com/us/r30/Purple20/v4/b0/0c/07/b00c07d2-a057-06bc-6044-9fdab97f370f/icon175x175.jpeg',
<add> linkAppStore: 'https://itunes.apple.com/us/app/tred-sell-my-car-for-more!/id1070071394?mt=8',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.tredmobile&hl=en',
<add> infoLink: 'http://www.geekwire.com/2015/mobile-dealership-tred-raises-another-1m-to-help-used-car-owners-make-more-money/',
<add> infoTitle: 'Sell your car for thousands more than Craigslist or the dealer with TRED',
<add> },
<ide> {
<ide> name: 'Bitt Wallet',
<ide> icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/5b/00/34/5b003497-cc85-a0d0-0d3e-4fb3bc6f95cd/icon175x175.jpeg', | 1 |
Ruby | Ruby | simplify verbose pathname extension | 56fa23e07ee4ee27cd22babb1c1ce57bb5d2a7c6 | <ide><path>Library/Homebrew/cleaner.rb
<ide> def clean_file_permissions path
<ide> # Clean a single folder (non-recursively)
<ide> def clean_dir d
<ide> d.find do |path|
<del> path.extend(NoiseyPathname) if ARGV.verbose?
<add> path.extend(NoisyPathname) if ARGV.verbose?
<ide>
<ide> if path.directory?
<ide> # Stop cleaning this subtree if protected
<ide> def clean_dir d
<ide>
<ide> end
<ide>
<del>
<del>class Pathname
<del> alias_method :orig_unlink, :unlink
<del>end
<del>
<del>module NoiseyPathname
<add>module NoisyPathname
<ide> def unlink
<ide> puts "rm: #{self}"
<del> orig_unlink
<add> super
<ide> end
<ide> end | 1 |
Javascript | Javascript | simplify logic for mutable workinprogresssources | 21dc41c3205b4f721ba97d2e54f1d3b5c38cb79a | <ide><path>packages/react-reconciler/src/ReactMutableSource.new.js
<ide> import {isPrimaryRenderer} from './ReactFiberHostConfig';
<ide> // Work in progress version numbers only apply to a single render,
<ide> // and should be reset before starting a new render.
<ide> // This tracks which mutable sources need to be reset after a render.
<del>const workInProgressPrimarySources: Array<MutableSource<any>> = [];
<del>const workInProgressSecondarySources: Array<MutableSource<any>> = [];
<add>const workInProgressSources: Array<MutableSource<any>> = [];
<ide>
<ide> let rendererSigil;
<ide> if (__DEV__) {
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> export function markSourceAsDirty(mutableSource: MutableSource<any>): void {
<del> if (isPrimaryRenderer) {
<del> workInProgressPrimarySources.push(mutableSource);
<del> } else {
<del> workInProgressSecondarySources.push(mutableSource);
<del> }
<add> workInProgressSources.push(mutableSource);
<ide> }
<ide>
<ide> export function resetWorkInProgressVersions(): void {
<del> if (isPrimaryRenderer) {
<del> for (let i = 0; i < workInProgressPrimarySources.length; i++) {
<del> const mutableSource = workInProgressPrimarySources[i];
<add> for (let i = 0; i < workInProgressSources.length; i++) {
<add> const mutableSource = workInProgressSources[i];
<add> if (isPrimaryRenderer) {
<ide> mutableSource._workInProgressVersionPrimary = null;
<del> }
<del> workInProgressPrimarySources.length = 0;
<del> } else {
<del> for (let i = 0; i < workInProgressSecondarySources.length; i++) {
<del> const mutableSource = workInProgressSecondarySources[i];
<add> } else {
<ide> mutableSource._workInProgressVersionSecondary = null;
<ide> }
<del> workInProgressSecondarySources.length = 0;
<ide> }
<add> workInProgressSources.length = 0;
<ide> }
<ide>
<ide> export function getWorkInProgressVersion(
<ide> export function setWorkInProgressVersion(
<ide> ): void {
<ide> if (isPrimaryRenderer) {
<ide> mutableSource._workInProgressVersionPrimary = version;
<del> workInProgressPrimarySources.push(mutableSource);
<ide> } else {
<ide> mutableSource._workInProgressVersionSecondary = version;
<del> workInProgressSecondarySources.push(mutableSource);
<ide> }
<add> workInProgressSources.push(mutableSource);
<ide> }
<ide>
<ide> export function warnAboutMultipleRenderersDEV(
<ide><path>packages/react-reconciler/src/ReactMutableSource.old.js
<ide> import {NoWork} from './ReactFiberExpirationTime.old';
<ide> // Work in progress version numbers only apply to a single render,
<ide> // and should be reset before starting a new render.
<ide> // This tracks which mutable sources need to be reset after a render.
<del>const workInProgressPrimarySources: Array<MutableSource<any>> = [];
<del>const workInProgressSecondarySources: Array<MutableSource<any>> = [];
<add>const workInProgressSources: Array<MutableSource<any>> = [];
<ide>
<ide> let rendererSigil;
<ide> if (__DEV__) {
<ide> export function setPendingExpirationTime(
<ide> }
<ide>
<ide> export function markSourceAsDirty(mutableSource: MutableSource<any>): void {
<del> if (isPrimaryRenderer) {
<del> workInProgressPrimarySources.push(mutableSource);
<del> } else {
<del> workInProgressSecondarySources.push(mutableSource);
<del> }
<add> workInProgressSources.push(mutableSource);
<ide> }
<ide>
<ide> export function resetWorkInProgressVersions(): void {
<del> if (isPrimaryRenderer) {
<del> for (let i = 0; i < workInProgressPrimarySources.length; i++) {
<del> const mutableSource = workInProgressPrimarySources[i];
<add> for (let i = 0; i < workInProgressSources.length; i++) {
<add> const mutableSource = workInProgressSources[i];
<add> if (isPrimaryRenderer) {
<ide> mutableSource._workInProgressVersionPrimary = null;
<del> }
<del> workInProgressPrimarySources.length = 0;
<del> } else {
<del> for (let i = 0; i < workInProgressSecondarySources.length; i++) {
<del> const mutableSource = workInProgressSecondarySources[i];
<add> } else {
<ide> mutableSource._workInProgressVersionSecondary = null;
<ide> }
<del> workInProgressSecondarySources.length = 0;
<ide> }
<add> workInProgressSources.length = 0;
<ide> }
<ide>
<ide> export function getWorkInProgressVersion(
<ide> export function setWorkInProgressVersion(
<ide> ): void {
<ide> if (isPrimaryRenderer) {
<ide> mutableSource._workInProgressVersionPrimary = version;
<del> workInProgressPrimarySources.push(mutableSource);
<ide> } else {
<ide> mutableSource._workInProgressVersionSecondary = version;
<del> workInProgressSecondarySources.push(mutableSource);
<ide> }
<add> workInProgressSources.push(mutableSource);
<ide> }
<ide>
<ide> export function warnAboutMultipleRenderersDEV( | 2 |
Ruby | Ruby | remove some warnings | 900758145d65438190a69f0fd227f62e01fa7bd2 | <ide><path>railties/test/application/configuration_test.rb
<ide> def assert_utf8
<ide> end
<ide>
<ide> test "Use key_generator when secret_key_base is set" do
<del> make_basic_app do |app|
<del> app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<del> app.config.session_store :disabled
<add> make_basic_app do |application|
<add> application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<add> application.config.session_store :disabled
<ide> end
<ide>
<ide> class ::OmgController < ActionController::Base
<ide> def index
<ide> end
<ide>
<ide> test "application verifier can be used in the entire application" do
<del> make_basic_app do |app|
<del> app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<del> app.config.session_store :disabled
<add> make_basic_app do |application|
<add> application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<add> application.config.session_store :disabled
<ide> end
<ide>
<ide> message = app.message_verifier(:sensitive_value).generate("some_value")
<ide> def index
<ide> end
<ide>
<ide> test "application verifier can build different verifiers" do
<del> make_basic_app do |app|
<del> app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<del> app.config.session_store :disabled
<add> make_basic_app do |application|
<add> application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<add> application.config.session_store :disabled
<ide> end
<ide>
<ide> default_verifier = app.message_verifier(:sensitive_value)
<ide> def form_authenticity_token; token; end # stub the authenticy token
<ide> end
<ide>
<ide> test "request forgery token param can be changed" do
<del> make_basic_app do
<del> app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
<add> make_basic_app do |application|
<add> application.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
<ide> end
<ide>
<ide> class ::OmgController < ActionController::Base
<ide> def index
<ide> end
<ide>
<ide> test "sets ActionDispatch::Response.default_charset" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.default_charset = "utf-16"
<add> make_basic_app do |application|
<add> application.config.action_dispatch.default_charset = "utf-16"
<ide> end
<ide>
<ide> assert_equal "utf-16", ActionDispatch::Response.default_charset
<ide> def index
<ide> end
<ide>
<ide> test "config.action_dispatch.show_exceptions is sent in env" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.show_exceptions = true
<add> make_basic_app do |application|
<add> application.config.action_dispatch.show_exceptions = true
<ide> end
<ide>
<ide> class ::OmgController < ActionController::Base
<ide> def create
<ide> end
<ide>
<ide> test "config.action_dispatch.ignore_accept_header" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.ignore_accept_header = true
<add> make_basic_app do |application|
<add> application.config.action_dispatch.ignore_accept_header = true
<ide> end
<ide>
<ide> class ::OmgController < ActionController::Base
<ide> def index
<ide>
<ide> test "config.session_store with :active_record_store with activerecord-session_store gem" do
<ide> begin
<del> make_basic_app do |app|
<add> make_basic_app do |application|
<ide> ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore)
<del> app.config.session_store :active_record_store
<add> application.config.session_store :active_record_store
<ide> end
<ide> ensure
<ide> ActionDispatch::Session.send :remove_const, :ActiveRecordStore
<ide> def index
<ide>
<ide> test "config.session_store with :active_record_store without activerecord-session_store gem" do
<ide> assert_raise RuntimeError, /activerecord-session_store/ do
<del> make_basic_app do |app|
<del> app.config.session_store :active_record_store
<add> make_basic_app do |application|
<add> application.config.session_store :active_record_store
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "Blank config.log_level is not deprecated for non-production environment" do
<ide> with_rails_env "development" do
<ide> assert_not_deprecated do
<del> make_basic_app do |app|
<del> app.config.log_level = nil
<add> make_basic_app do |application|
<add> application.config.log_level = nil
<ide> end
<ide> end
<ide> end
<ide> def index
<ide> test "Blank config.log_level is deprecated for the production environment" do
<ide> with_rails_env "production" do
<ide> assert_deprecated(/log_level/) do
<del> make_basic_app do |app|
<del> app.config.log_level = nil
<add> make_basic_app do |application|
<add> application.config.log_level = nil
<ide> end
<ide> end
<ide> end
<ide> def index
<ide> test "Not blank config.log_level is not deprecated for the production environment" do
<ide> with_rails_env "production" do
<ide> assert_not_deprecated do
<del> make_basic_app do |app|
<del> app.config.log_level = :info
<add> make_basic_app do |application|
<add> application.config.log_level = :info
<ide> end
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "config.log_level with custom logger" do
<del> make_basic_app do |app|
<del> app.config.logger = Logger.new(STDOUT)
<del> app.config.log_level = :info
<add> make_basic_app do |application|
<add> application.config.logger = Logger.new(STDOUT)
<add> application.config.log_level = :info
<ide> end
<ide> assert_equal Logger::INFO, Rails.logger.level
<ide> end
<ide> def index
<ide> end
<ide>
<ide> test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do
<del> make_basic_app do |app|
<del> app.config.annotations.register_extensions("coffee") do |tag|
<add> make_basic_app do |application|
<add> application.config.annotations.register_extensions("coffee") do |tag|
<ide> /#\s*(#{tag}):?\s*(.*)$/
<ide> end
<ide> end | 1 |
Ruby | Ruby | fix variable not initialized warnings | 879918b586535e2a76f345113fa1282daaf395ac | <ide><path>activesupport/test/concern_test.rb
<ide> module Baz
<ide> extend ActiveSupport::Concern
<ide>
<ide> class_methods do
<add> attr_accessor :included_ran, :prepended_ran
<add>
<ide> def baz
<ide> "baz"
<ide> end
<del>
<del> def included_ran=(value)
<del> @included_ran = value
<del> end
<del>
<del> def included_ran
<del> @included_ran
<del> end
<del>
<del> def prepended_ran=(value)
<del> @prepended_ran = value
<del> end
<del>
<del> def prepended_ran
<del> @prepended_ran
<del> end
<ide> end
<ide>
<ide> included do | 1 |
Go | Go | add benchmarks on trucnindex.delete | 7c8445826fdce3e46253a6e194a33407ed9bd154 | <ide><path>pkg/truncindex/truncindex_test.go
<ide> func BenchmarkTruncIndexGet500(b *testing.B) {
<ide> }
<ide> }
<ide>
<add>func BenchmarkTruncIndexDelete100(b *testing.B) {
<add> var testSet []string
<add> for i := 0; i < 100; i++ {
<add> testSet = append(testSet, utils.GenerateRandomID())
<add> }
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> b.StopTimer()
<add> index := NewTruncIndex([]string{})
<add> for _, id := range testSet {
<add> if err := index.Add(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> b.StartTimer()
<add> for _, id := range testSet {
<add> if err := index.Delete(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> }
<add>}
<add>
<add>func BenchmarkTruncIndexDelete250(b *testing.B) {
<add> var testSet []string
<add> for i := 0; i < 250; i++ {
<add> testSet = append(testSet, utils.GenerateRandomID())
<add> }
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> b.StopTimer()
<add> index := NewTruncIndex([]string{})
<add> for _, id := range testSet {
<add> if err := index.Add(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> b.StartTimer()
<add> for _, id := range testSet {
<add> if err := index.Delete(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> }
<add>}
<add>
<add>func BenchmarkTruncIndexDelete500(b *testing.B) {
<add> var testSet []string
<add> for i := 0; i < 500; i++ {
<add> testSet = append(testSet, utils.GenerateRandomID())
<add> }
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> b.StopTimer()
<add> index := NewTruncIndex([]string{})
<add> for _, id := range testSet {
<add> if err := index.Add(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> b.StartTimer()
<add> for _, id := range testSet {
<add> if err := index.Delete(id); err != nil {
<add> b.Fatal(err)
<add> }
<add> }
<add> }
<add>}
<add>
<ide> func BenchmarkTruncIndexNew100(b *testing.B) {
<ide> var testSet []string
<ide> for i := 0; i < 100; i++ { | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.