content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | trigger an event when authentication is throttled | eefb41ef2c2606b2e88adf33e7e43a135346be8c | <ide><path>src/Illuminate/Auth/Events/Lockout.php
<add><?php
<add>
<add>namespace Illuminate\Auth\Events;
<add>
<add>use Illuminate\Http\Request;
<add>
<add>class Lockout
<add>{
<add> /**
<add> * The throttled request.
<add> *
<add> * @var \Illuminate\Http\Request
<add> */
<add> public $request;
<add>
<add> /**
<add> * Create a new event instance.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return void
<add> */
<add> public function __construct(Request $request)
<add> {
<add> $this->request = $request;
<add> }
<add>}
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
<ide> public function login(Request $request)
<ide> $throttles = $this->isUsingThrottlesLoginsTrait();
<ide>
<ide> if ($throttles && $this->hasTooManyLoginAttempts($request)) {
<add> $this->fireLockoutEvent($request);
<add>
<ide> return $this->sendLockoutResponse($request);
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php
<ide>
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Cache\RateLimiter;
<add>use Illuminate\Auth\Events\Lockout;
<ide> use Illuminate\Support\Facades\Lang;
<ide>
<ide> trait ThrottlesLogins
<ide> protected function clearLoginAttempts(Request $request)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Fire an event when a lockout occurs.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return void
<add> */
<add> protected function fireLockoutEvent(Request $request)
<add> {
<add> event(new Lockout($request));
<add> }
<add>
<ide> /**
<ide> * Get the throttle key for the given request.
<ide> * | 3 |
Javascript | Javascript | add unit test for face3 | 0e886bf700f880b25f956eda49150fb8c384e5aa | <ide><path>test/unit/core/Face3.js
<add>/**
<add> * @author simonThiele / https://github.com/simonThiele
<add> */
<add>
<add>module( "Face3" );
<add>
<add>test( "copy", function() {
<add> var instance = new THREE.Face3(0, 1, 2, new THREE.Vector3(0, 1, 0), new THREE.Color(0.25, 0.5, 0.75), 2);
<add> var copiedInstance = instance.copy(instance);
<add>
<add> checkCopy(copiedInstance);
<add> checkVertexAndColors(copiedInstance);
<add>});
<add>
<add>test( "copy", function() {
<add> var instance = new THREE.Face3(0, 1, 2,
<add> [new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 1)],
<add> [new THREE.Color(0.25, 0.5, 0.75), new THREE.Color(1, 0, 0.4)],
<add> 2);
<add> var copiedInstance = instance.copy(instance);
<add>
<add> checkCopy(copiedInstance);
<add> checkVertexAndColorArrays(copiedInstance);
<add>});
<add>
<add>test( "clone", function() {
<add> var instance = new THREE.Face3(0, 1, 2, new THREE.Vector3(0, 1, 0), new THREE.Color(0.25, 0.5, 0.75), 2);
<add> var copiedInstance = instance.clone();
<add>
<add> checkCopy(copiedInstance);
<add> checkVertexAndColors(copiedInstance);
<add>});
<add>
<add>function checkCopy(copiedInstance) {
<add> ok( copiedInstance instanceof THREE.Face3, "copy created the correct type" );
<add> ok(
<add> copiedInstance.a === 0 &&
<add> copiedInstance.b === 1 &&
<add> copiedInstance.c === 2 &&
<add> copiedInstance.materialIndex === 2
<add> ,"properties where copied" );
<add>}
<add>
<add>function checkVertexAndColors(copiedInstance) {
<add> ok(
<add> copiedInstance.normal.x === 0 && copiedInstance.normal.y === 1 && copiedInstance.normal.z === 0 &&
<add> copiedInstance.color.r === 0.25 && copiedInstance.color.g === 0.5 && copiedInstance.color.b === 0.75
<add> ,"properties where copied" );
<add>}
<add>
<add>function checkVertexAndColorArrays(copiedInstance) {
<add> ok(
<add> copiedInstance.vertexNormals[0].x === 0 && copiedInstance.vertexNormals[0].y === 1 && copiedInstance.vertexNormals[0].z === 0 &&
<add> copiedInstance.vertexNormals[1].x === 1 && copiedInstance.vertexNormals[1].y === 0 && copiedInstance.vertexNormals[1].z === 1 &&
<add> copiedInstance.vertexColors[0].r === 0.25 && copiedInstance.vertexColors[0].g === 0.5 && copiedInstance.vertexColors[0].b === 0.75 &&
<add> copiedInstance.vertexColors[1].r === 1 && copiedInstance.vertexColors[1].g === 0 && copiedInstance.vertexColors[1].b === 0.4
<add> ,"properties where copied" );
<add>} | 1 |
Python | Python | fix bug in deserialization of convolutional layers | 3b76158c490f32e20df1f100ef7308ab000b20e0 | <ide><path>keras/layers/convolutional.py
<ide> def __init__(self, nb_filter, stack_size, nb_row, nb_col,
<ide> super(Convolution2D, self).__init__()
<ide> self.init = initializations.get(init)
<ide> self.activation = activations.get(activation)
<del> self.subsample = subsample
<add> self.subsample = tuple(subsample)
<ide> self.border_mode = border_mode
<ide> self.nb_filter = nb_filter
<ide> self.stack_size = stack_size
<ide> class MaxPooling2D(Layer):
<ide> def __init__(self, poolsize=(2, 2), stride=None, ignore_border=True):
<ide> super(MaxPooling2D, self).__init__()
<ide> self.input = T.tensor4()
<del> self.poolsize = poolsize
<add> self.poolsize = tuple(poolsize)
<ide> self.stride = stride
<ide> self.ignore_border = ignore_border
<ide>
<ide> class UpSample2D(Layer):
<ide> def __init__(self, size=(2, 2)):
<ide> super(UpSample2D, self).__init__()
<ide> self.input = T.tensor4()
<del> self.size = size
<add> self.size = tuple(size)
<ide>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> def get_config(self):
<ide> class ZeroPadding2D(Layer):
<ide> def __init__(self, pad=(1, 1)):
<ide> super(ZeroPadding2D, self).__init__()
<del> self.pad = pad
<add> self.pad = tuple(pad)
<ide> self.input = T.tensor4()
<ide>
<ide> def get_output(self, train): | 1 |
PHP | PHP | improve code to avoid accessing session | 65c8ce3963668aa18093778e29fdcaebc27b4814 | <ide><path>src/Auth/Storage/SessionStorage.php
<ide> class SessionStorage implements StorageInterface
<ide> /**
<ide> * User record.
<ide> *
<del> * @var array
<add> * Stores user record array if fetched from session or false if session
<add> * does not have user record.
<add> *
<add> * @var array|bool
<ide> */
<ide> protected $_user;
<ide>
<ide> class SessionStorage implements StorageInterface
<ide> protected $_session;
<ide>
<ide> /**
<del> * Default configuration for this class
<add> * Default configuration for this class.
<ide> *
<ide> * @var array
<ide> */
<ide> public function __construct(Request $request, array $config = [])
<ide> */
<ide> public function get()
<ide> {
<del> if ($this->_user) {
<del> return $this->_user;
<add> if ($this->_user !== null) {
<add> return $this->_user ?: null;
<ide> }
<ide>
<del> $this->_user = $this->_session->read($this->_config['key']);
<add> $this->_user = $this->_session->read($this->_config['key']) ?: false;
<ide> return $this->_user;
<ide> }
<ide>
<ide> public function set(array $user)
<ide> */
<ide> public function remove()
<ide> {
<del> $this->_user = null;
<add> $this->_user = false;
<ide>
<ide> $this->_session->delete($this->_config['key']);
<ide> $this->_session->renew();
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testRedirectVarClearing()
<ide> $this->Auth->startup($event);
<ide> $this->assertEquals('/auth_test/add', $this->Auth->session->read('Auth.redirect'));
<ide>
<del> $this->Auth->session->write('Auth.User', ['username' => 'admad']);
<add> $this->Auth->storage()->set(['username' => 'admad']);
<ide> $this->Auth->startup($event, $this->Controller);
<ide> $this->assertNull($this->Auth->session->read('Auth.redirect'));
<ide> } | 2 |
Ruby | Ruby | find patch nodes nested inside blocks | ffb1cc8e19abf6da810470d4ce266ab05fe69115 | <ide><path>Library/Homebrew/rubocops/patches.rb
<ide> def audit_formula(node, _class_node, _parent_class_node, body)
<ide> patch_problems(url_string)
<ide> end
<ide>
<del> inline_patches = find_method_calls_by_name(body, :patch)
<add> inline_patches = find_every_method_call_by_name(body, :patch)
<ide> inline_patches.each { |patch| inline_patch_problems(patch) }
<ide>
<ide> if inline_patches.empty? && patch_end?
<ide><path>Library/Homebrew/test/rubocops/patches_spec.rb
<ide> class Foo < Formula
<ide> RUBY
<ide> end
<ide>
<add> it "reports no offenses for valid nested inline patches" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> url 'https://brew.sh/foo-1.0.tgz'
<add> stable do
<add> patch :DATA
<add> end
<add> end
<add> __END__
<add> patch content here
<add> RUBY
<add> end
<add>
<ide> it "reports an offense when DATA is found with no __END__" do
<ide> expect_offense(<<~RUBY)
<ide> class Foo < Formula | 2 |
Javascript | Javascript | fix potential permanent deopt | e374e44a8a1bed599379fdcf4b5fe142c5e5187d | <ide><path>lib/events.js
<ide> EventEmitter.prototype.prependListener =
<ide> };
<ide>
<ide> function onceWrapper() {
<del> this.target.removeListener(this.type, this.wrapFn);
<ide> if (!this.fired) {
<add> this.target.removeListener(this.type, this.wrapFn);
<ide> this.fired = true;
<del> this.listener.apply(this.target, arguments);
<add> switch (arguments.length) {
<add> case 0:
<add> return this.listener.call(this.target);
<add> case 1:
<add> return this.listener.call(this.target, arguments[0]);
<add> case 2:
<add> return this.listener.call(this.target, arguments[0], arguments[1]);
<add> case 3:
<add> return this.listener.call(this.target, arguments[0], arguments[1],
<add> arguments[2]);
<add> default:
<add> const args = new Array(arguments.length);
<add> for (var i = 0; i < args.length; ++i)
<add> args[i] = arguments[i];
<add> this.listener.apply(this.target, args);
<add> }
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | add new matching logic and add tests | 0e5cf92fdbc71086a54aa28317b402cdb3ddeb8b | <ide><path>src/Routing/RouteBuilder.php
<ide> public function applyMiddleware(...$names)
<ide> * Apply a set of middleware to a group
<ide> *
<ide> * @param string $name Name of the middleware group
<del> * @param array $names Names of the middleware
<add> * @param array $middlewareNames Names of the middleware
<ide> * @return $this
<ide> */
<ide> public function middlewareGroup($name, array $middlewareNames)
<ide><path>src/Routing/RouteCollection.php
<ide> public function registerMiddleware($name, callable $middleware)
<ide> * Add middleware to a middleware group
<ide> *
<ide> * @param string $name Name of the middleware group
<del> * @param array $names Names of the middleware
<add> * @param array $middlewareNames Names of the middleware
<ide> * @return $this
<ide> */
<ide> public function middlewareGroup($name, $middlewareNames)
<ide> public function applyMiddleware($path, array $middleware)
<ide> {
<ide> foreach ($middleware as $name) {
<ide> if (!$this->hasMiddleware($name) && !$this->hasMiddlewareGroup($name)) {
<del> if (!$this->hasMiddleware($name)) {
<del> $message = "Cannot apply '$name' middleware to path '$path'. It has not been registered.";
<del> throw new RuntimeException($message);
<del> }
<del> if (!$this->hasMiddlewareGroup($name)) {
<del> $message = "Cannot apply '$name' middleware group to path '$path'. It has not been added.";
<del> throw new RuntimeException($message);
<del> }
<add> $message = "Cannot apply '$name' middleware or middleware group to path '$path'. It has not been registered.";
<add> throw new RuntimeException($message);
<ide> }
<ide> }
<ide> // Matches route element pattern in Cake\Routing\Route
<ide> public function applyMiddleware($path, array $middleware)
<ide> /**
<ide> * Get an array of middleware that matches the provided URL.
<ide> *
<del> * All middleware lists that match the URL will be merged together from shortest
<del> * path to longest path. If a middleware would be added to the set more than
<del> * once because it is connected to multiple path substrings match, it will only
<del> * be added once at its first occurrence.
<add> * Only the middlewrae applied to the longest matching scope will be used.
<ide> *
<ide> * @param string $needle The URL path to find middleware for.
<ide> * @return array
<ide> */
<ide> public function getMatchingMiddleware($needle)
<ide> {
<del> $matching = [];
<del> foreach ($this->_middlewarePaths as $pattern => $middleware) {
<add> $paths = $this->_middlewarePaths;
<add> $keys = array_map('strlen', array_keys($paths));
<add> array_multisort($keys, SORT_DESC, $paths);
<add>
<add> foreach ($paths as $pattern => &$middleware) {
<add> $matching = [];
<add>
<add> foreach ($middleware as $key => $name) {
<add> if ($this->hasMiddlewareGroup($name)) {
<add> unset($middleware[$key]);
<add> $middleware = array_merge($middleware, $this->_middlewareGroups[$name]);
<add> }
<add> }
<add>
<ide> if (preg_match($pattern, $needle)) {
<ide> $matching = array_merge($matching, $middleware);
<del> }
<del> }
<add> foreach ($matching as $name) {
<add> $resolved[] = $this->_middleware[$name];
<add> }
<ide>
<del> $resolved = [];
<del> foreach ($matching as $name) {
<del> if (!isset($resolved[$name])) {
<del> $resolved[$name] = $this->_middleware[$name];
<add> return array_values($resolved);
<ide> }
<ide> }
<ide>
<del> return array_values($resolved);
<add> return [];
<ide> }
<ide> }
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> public function testInvokeScopedMiddleware()
<ide> public function testInvokeScopedMiddlewareReturnResponse()
<ide> {
<ide> $this->counter = 0;
<del> Router::scope('/api', function ($routes) {
<add> Router::scope('/', function ($routes) {
<add> $routes->registerMiddleware('first', function ($req, $res, $next) {
<add> $this->log[] = 'first';
<add>
<add> return $next($req, $res);
<add> });
<add> $routes->registerMiddleware('second', function ($req, $res, $next) {
<add> $this->log[] = 'second';
<add>
<add> return $res;
<add> });
<add>
<add> $routes->applyMiddleware('first');
<add> $routes->connect('/', ['controller' => 'Home']);
<add>
<add> $routes->scope('/api', function ($routes) {
<add> $routes->applyMiddleware('second');
<add> $routes->connect('/articles', ['controller' => 'Articles']);
<add> });
<add> });
<add>
<add> $request = ServerRequestFactory::fromGlobals([
<add> 'REQUEST_METHOD' => 'GET',
<add> 'REQUEST_URI' => '/api/articles'
<add> ]);
<add> $response = new Response();
<add> $next = function ($req, $res) {
<add> $this->fail('Should not be invoked as first should be ignored.');
<add> };
<add> $middleware = new RoutingMiddleware();
<add> $result = $middleware($request, $response, $next);
<add>
<add> $this->assertSame($response, $result, 'Should return result');
<add> $this->assertSame(['second'], $this->log);
<add> }
<add>
<add> /**
<add> * Test control flow in scoped middleware.
<add> *
<add> * @return void
<add> */
<add> public function testInvokeScopedMiddlewareReturnResponseMainScope()
<add> {
<add> $this->counter = 0;
<add> Router::scope('/', function ($routes) {
<ide> $routes->registerMiddleware('first', function ($req, $res, $next) {
<ide> $this->log[] = 'first';
<ide>
<ide> public function testInvokeScopedMiddlewareReturnResponse()
<ide> return $next($req, $res);
<ide> });
<ide>
<del> $routes->applyMiddleware('second');
<del> $routes->connect('/ping', ['controller' => 'Pings']);
<add> $routes->applyMiddleware('first');
<add> $routes->connect('/', ['controller' => 'Home']);
<ide>
<del> $routes->scope('/v1', function ($routes) {
<del> $routes->applyMiddleware('first');
<add> $routes->scope('/api', function ($routes) {
<add> $routes->applyMiddleware('second');
<ide> $routes->connect('/articles', ['controller' => 'Articles']);
<ide> });
<ide> });
<ide>
<ide> $request = ServerRequestFactory::fromGlobals([
<ide> 'REQUEST_METHOD' => 'GET',
<del> 'REQUEST_URI' => '/api/v1/articles'
<add> 'REQUEST_URI' => '/'
<ide> ]);
<ide> $response = new Response();
<ide> $next = function ($req, $res) {
<del> $this->fail('Should not be invoked as second returns a response');
<add> $this->fail('Should not be invoked as second should be ignored.');
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $result = $middleware($request, $response, $next);
<ide>
<ide> $this->assertSame($response, $result, 'Should return result');
<del> $this->assertSame(['second', 'first'], $this->log);
<add> $this->assertSame(['first'], $this->log);
<ide> }
<ide> }
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testRegisterMiddlewareString()
<ide> $routes->registerMiddleware('bad', 'strlen');
<ide> }
<ide>
<del>
<ide> /**
<ide> * Test middleware group
<ide> *
<ide> public function testMiddlewareGroup()
<ide> $routes->registerMiddleware('test_two', $func);
<ide> $result = $routes->middlewareGroup('group', ['test', 'test_two']);
<ide>
<del>
<ide> $this->assertSame($result, $routes);
<ide> $this->assertTrue($this->collection->hasMiddlewareGroup('group'));
<ide> }
<ide> public function testMiddlewareGroupOverlap()
<ide> * Test applying middleware to a scope when it doesn't exist
<ide> *
<ide> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot apply 'bad' middleware to path '/api'. It has not been registered.
<add> * @expectedExceptionMessage Cannot apply 'bad' middleware or middleware group to path '/api'. It has not been registered.
<ide> * @return void
<ide> */
<ide> public function testApplyMiddlewareInvalidName()
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public function testRegisterMiddleware()
<ide> */
<ide> public function testMiddlewareGroup()
<ide> {
<del> $this->collection->registerMiddleware('closure', function () {});
<add> $this->collection->registerMiddleware('closure', function () {
<add> });
<ide>
<ide> $mock = $this->getMockBuilder('\stdClass')
<ide> ->setMethods(['__invoke'])
<ide> ->getMock();
<ide> $result = $this->collection->registerMiddleware('callable', $mock);
<ide> $this->collection->registerMiddleware('callable', $mock);
<ide>
<del> $routes->groupMiddleware('group', ['closure', 'callable']);
<add> $this->collection->middlewareGroup('group', ['closure', 'callable']);
<ide>
<ide> $this->assertTrue($this->collection->hasMiddlewareGroup('group'));
<ide> }
<ide>
<add> /**
<add> * Test adding a middleware group with the same name twice fails.
<add> *
<add> * @expectedException \RuntimeException
<add> * @expectedExceptionMessage Cannot add middle ware group 'group' . A middleware group by this name has already been added.
<add> * @return void
<add> */
<add> public function testMiddlewareGroupDuplicate()
<add> {
<add> $this->collection->registerMiddleware('closure', function () {
<add> });
<add>
<add> $mock = $this->getMockBuilder('\stdClass')
<add> ->setMethods(['__invoke'])
<add> ->getMock();
<add> $result = $this->collection->registerMiddleware('callable', $mock);
<add> $this->collection->registerMiddleware('callable', $mock);
<add>
<add> $this->collection->middlewareGroup('group', ['closure', 'callable']);
<add> $this->collection->middlewareGroup('group', ['closure', 'callable']);
<add> }
<add>
<add> /**
<add> * Test adding ab unregistered middleware to a middleware group fails.
<add> *
<add> * @expectedException \RuntimeException
<add> * @expectedExceptionMessage Cannot add 'bad' middleware to group 'group'. It has not been registered.
<add> * @return void
<add> */
<add> public function testMiddlewareGroupUnregisteredMiddleware()
<add> {
<add> $this->collection->middlewareGroup('group', ['bad']);
<add> }
<add>
<ide> /**
<ide> * Test adding middleware with a placeholder in the path.
<ide> *
<ide> public function testGetMatchingMiddlewareMultiplePaths()
<ide> $this->assertCount(0, $middleware);
<ide>
<ide> $middleware = $this->collection->getMatchingMiddleware('/api/v1/articles/1');
<del> $this->assertCount(2, $middleware);
<del> $this->assertEquals([$mock, $mockTwo], $middleware, 'Both middleware match');
<add> $this->assertCount(1, $middleware);
<add> $this->assertEquals([$mock], $middleware, 'Should only match the strongest scope');
<ide>
<ide> $middleware = $this->collection->getMatchingMiddleware('/api/v1/comments');
<ide> $this->assertCount(1, $middleware);
<ide> public function testApplyMiddlewareWithPlaceholder()
<ide> * Test applying middleware to a scope when it doesn't exist
<ide> *
<ide> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot apply 'bad' middleware to path '/api'. It has not been registered.
<add> * @expectedExceptionMessage Cannot apply 'bad' middleware or middleware group to path '/api'. It has not been registered.
<ide> * @return void
<ide> */
<ide> public function testApplyMiddlewareUnregistered() | 5 |
Go | Go | replace custom waiting code with a waitgroup | 33286589291a56fe0a4728f8b45ad3feb5494226 | <ide><path>graph/push.go
<ide> import (
<ide> "io/ioutil"
<ide> "os"
<ide> "path"
<add> "sync"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/engine"
<ide> func (s *TagStore) pushRepository(r *registry.Session, out io.Writer, repoInfo *
<ide> if tag == "" {
<ide> nTag = len(localRepo)
<ide> }
<del> completed := make(chan bool)
<add> var wg sync.WaitGroup
<ide> needsPush := make([]bool, len(imgList))
<ide> for _, ep := range repoData.Endpoints {
<ide> out.Write(sf.FormatStatus("", "Pushing repository %s (%d tags)", repoInfo.CanonicalName, nTag))
<ide>
<ide> for i, imgId := range imgList {
<add> wg.Add(1)
<ide> go func(i int, imgId string) {
<add> defer wg.Done()
<ide> if err := r.LookupRemoteImage(imgId, ep, repoData.Tokens); err == nil {
<ide> out.Write(sf.FormatStatus("", "Image %s already pushed, skipping", utils.TruncateID(imgId)))
<ide> needsPush[i] = false
<ide> func (s *TagStore) pushRepository(r *registry.Session, out io.Writer, repoInfo *
<ide> out.Write(sf.FormatStatus("", "Image %s not pushed, adding to queue", utils.TruncateID(imgId)))
<ide> needsPush[i] = true
<ide> }
<del> completed <- true
<ide> }(i, imgId)
<ide> }
<del> for i := 0; i < len(imgList); i++ {
<del> <-completed
<del> }
<add>
<add> wg.Wait()
<add>
<ide> for i, imgId := range imgList {
<ide> if needsPush[i] {
<ide> if _, err := s.pushImage(r, out, remoteName, imgId, ep, repoData.Tokens, sf); err != nil { | 1 |
Javascript | Javascript | fix weight accumulation | 9e625f42488260f19d7a1af768b0312bfdc17e6c | <ide><path>examples/js/postprocessing/MSAAPass.js
<ide> THREE.MSAAPass.prototype = {
<ide>
<ide> // this accumulation strategy is used to prevent decimation at low bit depths with lots of samples.
<ide> this.uniforms[ "scale" ].value = weight;
<del> weight *= 0.5;
<add> weight = 1.0 / (i+1);
<ide>
<ide> // clear on the first render, accumulate the others
<ide> var autoClear = renderer.autoClear; | 1 |
Text | Text | add model cards for finbert. | 11d8bcc9d7c98cf4aedbb75ee799c1639f0839ea | <ide><path>model_cards/TurkuNLP/bert-base-finnish-cased-v1/README.md
<add>---
<add>language: finnish
<add>---
<add>
<add>## Quickstart
<add>
<add>**Release 1.0** (November 25, 2019)
<add>
<add>Download the models here:
<add>
<add>* Cased Finnish BERT Base: [bert-base-finnish-cased-v1.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-cased-v1.zip)
<add>* Uncased Finnish BERT Base: [bert-base-finnish-uncased-v1.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-uncased-v1.zip)
<add>
<add>We generally recommend the use of the cased model.
<add>
<add>Paper presenting Finnish BERT: [arXiv:1912.07076](https://arxiv.org/abs/1912.07076)
<add>
<add>## What's this?
<add>
<add>A version of Google's [BERT](https://github.com/google-research/bert) deep transfer learning model for Finnish. The model can be fine-tuned to achieve state-of-the-art results for various Finnish natural language processing tasks.
<add>
<add>FinBERT features a custom 50,000 wordpiece vocabulary that has much better coverage of Finnish words than e.g. the previously released [multilingual BERT](https://github.com/google-research/bert/blob/master/multilingual.md) models from Google:
<add>
<add>| Vocabulary | Example |
<add>|------------|---------|
<add>| FinBERT | Suomessa vaihtuu kesän aikana sekä pääministeri että valtiovarain ##ministeri . |
<add>| Multilingual BERT | Suomessa vai ##htuu kes ##än aikana sekä p ##ää ##minister ##i että valt ##io ##vara ##in ##minister ##i . |
<add>
<add>FinBERT has been pre-trained for 1 million steps on over 3 billion tokens (24B characters) of Finnish text drawn from news, online discussion, and internet crawls. By contrast, Multilingual BERT was trained on Wikipedia texts, where the Finnish Wikipedia text is approximately 3% of the amount used to train FinBERT.
<add>
<add>These features allow FinBERT to outperform not only Multilingual BERT but also all previously proposed models when fine-tuned for Finnish natural language processing tasks.
<add>
<add>## Results
<add>
<add>### Document classification
<add>
<add>
<add>
<add>FinBERT outperforms multilingual BERT (M-BERT) on document classification over a range of training set sizes on the Yle news (left) and Ylilauta online discussion (right) corpora. (Baseline classification performance with [FastText](https://fasttext.cc/) included for reference.)
<add>
<add>[[code](https://github.com/spyysalo/finbert-text-classification)][[Yle data](https://github.com/spyysalo/yle-corpus)] [[Ylilauta data](https://github.com/spyysalo/ylilauta-corpus)]
<add>
<add>### Named Entity Recognition
<add>
<add>Evaluation on FiNER corpus ([Ruokolainen et al 2019](https://arxiv.org/abs/1908.04212))
<add>
<add>| Model | Accuracy |
<add>|--------------------|----------|
<add>| **FinBERT** | **92.40%** |
<add>| Multilingual BERT | 90.29% |
<add>| [FiNER-tagger](https://github.com/Traubert/FiNer-rules) (rule-based) | 86.82% |
<add>
<add>(FiNER tagger results from [Ruokolainen et al. 2019](https://arxiv.org/pdf/1908.04212.pdf))
<add>
<add>[[code](https://github.com/jouniluoma/keras-bert-ner)][[data](https://github.com/mpsilfve/finer-data)]
<add>
<add>### Part of speech tagging
<add>
<add>Evaluation on three Finnish corpora annotated with [Universal Dependencies](https://universaldependencies.org/) part-of-speech tags: the Turku Dependency Treebank (TDT), FinnTreeBank (FTB), and Parallel UD treebank (PUD)
<add>
<add>| Model | TDT | FTB | PUD |
<add>|-------------------|-------------|-------------|-------------|
<add>| **FinBERT** | **98.23%** | **98.39%** | **98.08%** |
<add>| Multilingual BERT | 96.97% | 95.87% | 97.58% |
<add>
<add>[[code](https://github.com/spyysalo/bert-pos)][[data](http://hdl.handle.net/11234/1-2837)]
<add>
<add>## Use with PyTorch
<add>
<add>If you want to use the model with the huggingface/transformers library, follow the steps in [huggingface_transformers.md](https://github.com/TurkuNLP/FinBERT/blob/master/huggingface_transformers.md)
<add>
<add>## Previous releases
<add>
<add>### Release 0.2
<add>
<add>**October 24, 2019** Beta version of the BERT base uncased model trained from scratch on a corpus of Finnish news, online discussions, and crawled data.
<add>
<add>Download the model here: [bert-base-finnish-uncased.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-uncased.zip)
<add>
<add>### Release 0.1
<add>
<add>**September 30, 2019** We release a beta version of the BERT base cased model trained from scratch on a corpus of Finnish news, online discussions, and crawled data.
<add>
<add>Download the model here: [bert-base-finnish-cased.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-cased.zip)
<ide><path>model_cards/TurkuNLP/bert-base-finnish-uncased-v1/README.md
<add>---
<add>language: finnish
<add>---
<add>
<add>## Quickstart
<add>
<add>**Release 1.0** (November 25, 2019)
<add>
<add>Download the models here:
<add>
<add>* Cased Finnish BERT Base: [bert-base-finnish-cased-v1.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-cased-v1.zip)
<add>* Uncased Finnish BERT Base: [bert-base-finnish-uncased-v1.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-uncased-v1.zip)
<add>
<add>We generally recommend the use of the cased model.
<add>
<add>Paper presenting Finnish BERT: [arXiv:1912.07076](https://arxiv.org/abs/1912.07076)
<add>
<add>## What's this?
<add>
<add>A version of Google's [BERT](https://github.com/google-research/bert) deep transfer learning model for Finnish. The model can be fine-tuned to achieve state-of-the-art results for various Finnish natural language processing tasks.
<add>
<add>FinBERT features a custom 50,000 wordpiece vocabulary that has much better coverage of Finnish words than e.g. the previously released [multilingual BERT](https://github.com/google-research/bert/blob/master/multilingual.md) models from Google:
<add>
<add>| Vocabulary | Example |
<add>|------------|---------|
<add>| FinBERT | Suomessa vaihtuu kesän aikana sekä pääministeri että valtiovarain ##ministeri . |
<add>| Multilingual BERT | Suomessa vai ##htuu kes ##än aikana sekä p ##ää ##minister ##i että valt ##io ##vara ##in ##minister ##i . |
<add>
<add>FinBERT has been pre-trained for 1 million steps on over 3 billion tokens (24B characters) of Finnish text drawn from news, online discussion, and internet crawls. By contrast, Multilingual BERT was trained on Wikipedia texts, where the Finnish Wikipedia text is approximately 3% of the amount used to train FinBERT.
<add>
<add>These features allow FinBERT to outperform not only Multilingual BERT but also all previously proposed models when fine-tuned for Finnish natural language processing tasks.
<add>
<add>## Results
<add>
<add>### Document classification
<add>
<add>
<add>
<add>FinBERT outperforms multilingual BERT (M-BERT) on document classification over a range of training set sizes on the Yle news (left) and Ylilauta online discussion (right) corpora. (Baseline classification performance with [FastText](https://fasttext.cc/) included for reference.)
<add>
<add>[[code](https://github.com/spyysalo/finbert-text-classification)][[Yle data](https://github.com/spyysalo/yle-corpus)] [[Ylilauta data](https://github.com/spyysalo/ylilauta-corpus)]
<add>
<add>### Named Entity Recognition
<add>
<add>Evaluation on FiNER corpus ([Ruokolainen et al 2019](https://arxiv.org/abs/1908.04212))
<add>
<add>| Model | Accuracy |
<add>|--------------------|----------|
<add>| **FinBERT** | **92.40%** |
<add>| Multilingual BERT | 90.29% |
<add>| [FiNER-tagger](https://github.com/Traubert/FiNer-rules) (rule-based) | 86.82% |
<add>
<add>(FiNER tagger results from [Ruokolainen et al. 2019](https://arxiv.org/pdf/1908.04212.pdf))
<add>
<add>[[code](https://github.com/jouniluoma/keras-bert-ner)][[data](https://github.com/mpsilfve/finer-data)]
<add>
<add>### Part of speech tagging
<add>
<add>Evaluation on three Finnish corpora annotated with [Universal Dependencies](https://universaldependencies.org/) part-of-speech tags: the Turku Dependency Treebank (TDT), FinnTreeBank (FTB), and Parallel UD treebank (PUD)
<add>
<add>| Model | TDT | FTB | PUD |
<add>|-------------------|-------------|-------------|-------------|
<add>| **FinBERT** | **98.23%** | **98.39%** | **98.08%** |
<add>| Multilingual BERT | 96.97% | 95.87% | 97.58% |
<add>
<add>[[code](https://github.com/spyysalo/bert-pos)][[data](http://hdl.handle.net/11234/1-2837)]
<add>
<add>## Use with PyTorch
<add>
<add>If you want to use the model with the huggingface/transformers library, follow the steps in [huggingface_transformers.md](https://github.com/TurkuNLP/FinBERT/blob/master/huggingface_transformers.md)
<add>
<add>## Previous releases
<add>
<add>### Release 0.2
<add>
<add>**October 24, 2019** Beta version of the BERT base uncased model trained from scratch on a corpus of Finnish news, online discussions, and crawled data.
<add>
<add>Download the model here: [bert-base-finnish-uncased.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-uncased.zip)
<add>
<add>### Release 0.1
<add>
<add>**September 30, 2019** We release a beta version of the BERT base cased model trained from scratch on a corpus of Finnish news, online discussions, and crawled data.
<add>
<add>Download the model here: [bert-base-finnish-cased.zip](http://dl.turkunlp.org/finbert/bert-base-finnish-cased.zip) | 2 |
PHP | PHP | use readline in console when supported | 916d9921621fb7b278b28a7f2e35d9dc0b412dfe | <ide><path>lib/Cake/Console/ConsoleInput.php
<ide> class ConsoleInput {
<ide> * @var resource
<ide> */
<ide> protected $_input;
<add>/**
<add> * Can this instance use readline?
<add> * Two conditions must be met:
<add> * 1. Readline support must be enabled.
<add> * 2. Handle we are attached to must be stdin.
<add> * Allows rich editing with arrow keys and history when inputting a string.
<add> *
<add> * @var bool
<add> */
<add> private $_can_readline;
<ide>
<ide> /**
<ide> * Constructor
<ide> *
<ide> * @param string $handle The location of the stream to use as input.
<ide> */
<ide> public function __construct($handle = 'php://stdin') {
<add> $this->_can_readline = extension_loaded('readline') && $handle == 'php://stdin' ? true : false;
<ide> $this->_input = fopen($handle, 'r');
<ide> }
<ide>
<ide> public function __construct($handle = 'php://stdin') {
<ide> * @return mixed The value of the stream
<ide> */
<ide> public function read() {
<add> if ($this->_can_readline) {
<add> $line = readline('');
<add> if (!empty($line)) {
<add> readline_add_history($line);
<add> }
<add> return $line;
<add> }
<ide> return fgets($this->_input);
<ide> }
<ide> | 1 |
Python | Python | enable token match | 62443d495a877ecadcdbe28e368a2a70adc79728 | <ide><path>spacy/lang/id/__init__.py
<ide>
<ide> from .stop_words import STOP_WORDS
<ide> from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES
<del>from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<add>from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS, TOKEN_MATCH
<ide> from .norm_exceptions import NORM_EXCEPTIONS
<ide> from .lex_attrs import LEX_ATTRS
<ide>
<ide> class IndonesianDefaults(Language.Defaults):
<ide>
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<ide> stop_words = set(STOP_WORDS)
<add> token_match = TOKEN_MATCH
<ide> prefixes = tuple(TOKENIZER_PREFIXES)
<ide> suffixes = tuple(TOKENIZER_SUFFIXES)
<ide> infixes = tuple(TOKENIZER_INFIXES) | 1 |
Python | Python | improve computation of scaled companion matrices | 0650d04078666997c3dac3beec6fe872dca797dd | <ide><path>numpy/polynomial/hermite.py
<ide> def hermcompanion(c):
<ide>
<ide> n = len(c) - 1
<ide> mat = np.zeros((n, n), dtype=c.dtype)
<del> scl = np.hstack((1., np.sqrt(2.*np.arange(1, n))))
<del> scl = np.multiply.accumulate(scl)
<add> scl = np.hstack((1., 1./np.sqrt(2.*np.arange(n - 1, 0, -1))))
<add> scl = np.multiply.accumulate(scl)[::-1]
<ide> top = mat.reshape(-1)[1::n+1]
<ide> bot = mat.reshape(-1)[n::n+1]
<ide> top[...] = np.sqrt(.5*np.arange(1, n))
<ide> bot[...] = top
<del> mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
<add> mat[:, -1] -= scl*c[:-1]/(2.0 *c[-1])
<ide> return mat
<ide>
<ide>
<ide><path>numpy/polynomial/hermite_e.py
<ide> def hermecompanion(c):
<ide>
<ide> n = len(c) - 1
<ide> mat = np.zeros((n, n), dtype=c.dtype)
<del> scl = np.hstack((1., np.sqrt(np.arange(1, n))))
<del> scl = np.multiply.accumulate(scl)
<add> scl = np.hstack((1., 1./np.sqrt(np.arange(n - 1, 0, -1))))
<add> scl = np.multiply.accumulate(scl)[::-1]
<ide> top = mat.reshape(-1)[1::n+1]
<ide> bot = mat.reshape(-1)[n::n+1]
<ide> top[...] = np.sqrt(np.arange(1, n))
<ide> bot[...] = top
<del> mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])
<add> mat[:, -1] -= scl*c[:-1]/c[-1]
<ide> return mat
<ide>
<ide> | 2 |
Javascript | Javascript | use forced tests | 009772cb20bed0d5fb192b39fac48a2a84b03ad2 | <ide><path>test/ConfigTestCases.test.js
<ide> "use strict";
<ide>
<del>/* globals describe it */
<del>require("should");
<add>/* globals describe expect it fit */
<ide> const path = require("path");
<ide> const fs = require("fs");
<ide> const vm = require("vm");
<ide> const mkdirp = require("mkdirp");
<del>const Test = require("mocha/lib/test");
<ide> const checkArrayExpectation = require("./checkArrayExpectation");
<add>const async = require("async");
<ide>
<ide> const Stats = require("../lib/Stats");
<ide> const webpack = require("../lib/webpack");
<ide> describe("ConfigTestCases", () => {
<ide> categories.forEach((category) => {
<ide> describe(category.name, () => {
<ide> category.tests.forEach((testName) => {
<del> const suite = describe(testName, () => {});
<del> it(testName + " should compile", function(done) {
<del> const testDirectory = path.join(casesPath, category.name, testName);
<del> const outputDirectory = path.join(__dirname, "js", "config", category.name, testName);
<del> const options = prepareOptions(require(path.join(testDirectory, "webpack.config.js")));
<del> const optionsArr = [].concat(options);
<del> optionsArr.forEach((options, idx) => {
<del> if(!options.context) options.context = testDirectory;
<del> if(!options.mode) options.mode = "production";
<del> if(!options.optimization) options.optimization = {};
<del> if(options.optimization.minimize === undefined) options.optimization.minimize = false;
<del> if(!options.entry) options.entry = "./index.js";
<del> if(!options.target) options.target = "async-node";
<del> if(!options.output) options.output = {};
<del> if(!options.output.path) options.output.path = outputDirectory;
<del> if(typeof options.output.pathinfo === "undefined") options.output.pathinfo = true;
<del> if(!options.output.filename) options.output.filename = "bundle" + idx + ".js";
<del> });
<del> let testConfig = {
<del> findBundle: function(i, options) {
<del> if(fs.existsSync(path.join(options.output.path, "bundle" + i + ".js"))) {
<del> return "./bundle" + i + ".js";
<add> describe(testName, () => {
<add> it(testName + " should compile", (done) => {
<add> const testDirectory = path.join(casesPath, category.name, testName);
<add> const outputDirectory = path.join(__dirname, "js", "config", category.name, testName);
<add> const options = prepareOptions(require(path.join(testDirectory, "webpack.config.js")));
<add> const optionsArr = [].concat(options);
<add> optionsArr.forEach((options, idx) => {
<add> if(!options.context) options.context = testDirectory;
<add> if(!options.mode) options.mode = "production";
<add> if(!options.optimization) options.optimization = {};
<add> if(options.optimization.minimize === undefined) options.optimization.minimize = false;
<add> if(!options.entry) options.entry = "./index.js";
<add> if(!options.target) options.target = "async-node";
<add> if(!options.output) options.output = {};
<add> if(!options.output.path) options.output.path = outputDirectory;
<add> if(typeof options.output.pathinfo === "undefined") options.output.pathinfo = true;
<add> if(!options.output.filename) options.output.filename = "bundle" + idx + ".js";
<add> });
<add> let testConfig = {
<add> findBundle: function(i, options) {
<add> if(fs.existsSync(path.join(options.output.path, "bundle" + i + ".js"))) {
<add> return "./bundle" + i + ".js";
<add> }
<add> },
<add> timeout: 30000
<add> };
<add> try {
<add> // try to load a test file
<add> testConfig = Object.assign(testConfig, require(path.join(testDirectory, "test.config.js")));
<add> } catch(e) {}
<add>
<add> // this.timeout(testConfig.timeout);
<add>
<add> webpack(options, (err, stats) => {
<add> if(err) {
<add> const fakeStats = {
<add> errors: [err.stack]
<add> };
<add> if(checkArrayExpectation(testDirectory, fakeStats, "error", "Error", done)) return;
<add> // Wait for uncatched errors to occur
<add> return setTimeout(done, 200);
<ide> }
<del> },
<del> timeout: 30000
<del> };
<del> try {
<del> // try to load a test file
<del> testConfig = Object.assign(testConfig, require(path.join(testDirectory, "test.config.js")));
<del> } catch(e) {}
<add> const statOptions = Stats.presetToOptions("verbose");
<add> statOptions.colors = false;
<add> mkdirp.sync(outputDirectory);
<add> fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(statOptions), "utf-8");
<add> const jsonStats = stats.toJson({
<add> errorDetails: true
<add> });
<add> if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
<add> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
<add> let exportedTests = [];
<ide>
<del> this.timeout(testConfig.timeout);
<add> function _it(title, fn) {
<add> exportedTests.push(fit(title, fn));
<add> }
<ide>
<del> webpack(options, (err, stats) => {
<del> if(err) {
<del> const fakeStats = {
<del> errors: [err.stack]
<add> const globalContext = {
<add> console: console
<ide> };
<del> if(checkArrayExpectation(testDirectory, fakeStats, "error", "Error", done)) return;
<del> // Wait for uncatched errors to occur
<del> return setTimeout(done, 200);
<del> }
<del> const statOptions = Stats.presetToOptions("verbose");
<del> statOptions.colors = false;
<del> mkdirp.sync(outputDirectory);
<del> fs.writeFileSync(path.join(outputDirectory, "stats.txt"), stats.toString(statOptions), "utf-8");
<del> const jsonStats = stats.toJson({
<del> errorDetails: true
<del> });
<del> if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
<del> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
<del> let exportedTests = 0;
<del>
<del> function _it(title, fn) {
<del> const test = new Test(title, fn);
<del> suite.addTest(test);
<del> exportedTests++;
<del> return test;
<del> }
<ide>
<del> const globalContext = {
<del> console: console
<del> };
<add> function _require(currentDirectory, module) {
<add> if(Array.isArray(module) || /^\.\.?\//.test(module)) {
<add> let fn;
<add> let content;
<add> let p;
<add> if(Array.isArray(module)) {
<add> p = path.join(currentDirectory, module[0]);
<add> content = module.map((arg) => {
<add> p = path.join(currentDirectory, arg);
<add> return fs.readFileSync(p, "utf-8");
<add> }).join("\n");
<add> } else {
<add> p = path.join(currentDirectory, module);
<add> content = fs.readFileSync(p, "utf-8");
<add> }
<add> if(options.target === "web" || options.target === "webworker") {
<add> fn = vm.runInNewContext("(function(require, module, exports, __dirname, __filename, it, expect, window) {" + content + "\n})", globalContext, p);
<add> } else {
<add> fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it, expect) {" + content + "\n})", p);
<add> }
<add> const m = {
<add> exports: {}
<add> };
<add> fn.call(m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, _it, expect, globalContext);
<add> return m.exports;
<add> } else if(testConfig.modules && module in testConfig.modules) {
<add> return testConfig.modules[module];
<add> } else return require(module);
<add> }
<add> let filesCount = 0;
<ide>
<del> function _require(currentDirectory, module) {
<del> if(Array.isArray(module) || /^\.\.?\//.test(module)) {
<del> let fn;
<del> let content;
<del> let p;
<del> if(Array.isArray(module)) {
<del> p = path.join(currentDirectory, module[0]);
<del> content = module.map((arg) => {
<del> p = path.join(currentDirectory, arg);
<del> return fs.readFileSync(p, "utf-8");
<del> }).join("\n");
<del> } else {
<del> p = path.join(currentDirectory, module);
<del> content = fs.readFileSync(p, "utf-8");
<add> if(testConfig.noTests) return process.nextTick(done);
<add> for(let i = 0; i < optionsArr.length; i++) {
<add> const bundlePath = testConfig.findBundle(i, optionsArr[i]);
<add> if(bundlePath) {
<add> filesCount++;
<add> _require(outputDirectory, bundlePath);
<ide> }
<del> if(options.target === "web" || options.target === "webworker") {
<del> fn = vm.runInNewContext("(function(require, module, exports, __dirname, __filename, it, window) {" + content + "\n})", globalContext, p);
<del> } else {
<del> fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it) {" + content + "\n})", p);
<del> }
<del> const m = {
<del> exports: {}
<del> };
<del> fn.call(m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, _it, globalContext);
<del> return m.exports;
<del> } else if(testConfig.modules && module in testConfig.modules) {
<del> return testConfig.modules[module];
<del> } else return require(module);
<del> }
<del> let filesCount = 0;
<del>
<del> if(testConfig.noTests) return process.nextTick(done);
<del> for(let i = 0; i < optionsArr.length; i++) {
<del> const bundlePath = testConfig.findBundle(i, optionsArr[i]);
<del> if(bundlePath) {
<del> filesCount++;
<del> _require(outputDirectory, bundlePath);
<ide> }
<del> }
<del> // give a free pass to compilation that generated an error
<del> if(!jsonStats.errors.length && filesCount !== optionsArr.length) return done(new Error("Should have found at least one bundle file per webpack config"));
<del> if(exportedTests < filesCount) return done(new Error("No tests exported by test case"));
<del> process.nextTick(done);
<add> // give a free pass to compilation that generated an error
<add> if(!jsonStats.errors.length && filesCount !== optionsArr.length) return done(new Error("Should have found at least one bundle file per webpack config"));
<add> if(exportedTests.length < filesCount) return done(new Error("No tests exported by test case"));
<add> async.waterfall(
<add> exportedTests.map(test => (callback) => test.execute(callback, true)),
<add> done
<add> );
<add> });
<ide> });
<ide> });
<ide> });
<ide><path>test/HotTestCases.test.js
<ide> "use strict";
<ide>
<del>require("should");
<add>/* globals expect fit */
<ide> const path = require("path");
<ide> const fs = require("fs");
<ide> const vm = require("vm");
<del>const Test = require("mocha/lib/test");
<ide> const checkArrayExpectation = require("./checkArrayExpectation");
<add>const async = require("async");
<ide>
<ide> const webpack = require("../lib/webpack");
<ide>
<del>function createNestableIt(done) {
<del> let counter = 0;
<del> let aborted = false;
<del> return (title, fn) => {
<del> counter++;
<del> fn((err) => {
<del> if(aborted) {
<del> return;
<del> }
<del> if(err) {
<del> aborted = true;
<del> done(err);
<del> } else {
<del> counter--;
<del> if(counter === 0) {
<del> done();
<del> }
<del> }
<del> });
<del> }
<del>}
<del>
<ide> describe("HotTestCases", () => {
<ide> const casesPath = path.join(__dirname, "hotCases");
<ide> let categories = fs.readdirSync(casesPath).filter((dir) =>
<ide> describe("HotTestCases", () => {
<ide> categories.forEach((category) => {
<ide> describe(category.name, () => {
<ide> category.tests.forEach((testName) => {
<del> it(testName + " should compile", (done) => {
<del> const testDirectory = path.join(casesPath, category.name, testName);
<del> const outputDirectory = path.join(__dirname, "js", "hot-cases", category.name, testName);
<del> const recordsPath = path.join(outputDirectory, "records.json");
<del> if(fs.existsSync(recordsPath))
<del> fs.unlinkSync(recordsPath);
<del> const fakeUpdateLoaderOptions = {
<del> updateIndex: 0
<del> };
<del> const configPath = path.join(testDirectory, "webpack.config.js");
<del> let options = {};
<del> if(fs.existsSync(configPath))
<del> options = require(configPath);
<del> if(!options.mode) options.mode = "development";
<del> if(!options.context) options.context = testDirectory;
<del> if(!options.entry) options.entry = "./index.js";
<del> if(!options.output) options.output = {};
<del> if(!options.output.path) options.output.path = outputDirectory;
<del> if(!options.output.filename) options.output.filename = "bundle.js";
<del> if(options.output.pathinfo === undefined) options.output.pathinfo = true;
<del> if(!options.module) options.module = {};
<del> if(!options.module.rules) options.module.rules = [];
<del> options.module.rules.push({
<del> test: /\.js$/,
<del> loader: path.join(__dirname, "hotCases", "fake-update-loader.js"),
<del> enforce: "pre"
<del> });
<del> if(!options.target) options.target = "async-node";
<del> if(!options.plugins) options.plugins = [];
<del> options.plugins.push(
<del> new webpack.HotModuleReplacementPlugin(),
<del> new webpack.NamedModulesPlugin(),
<del> new webpack.LoaderOptionsPlugin(fakeUpdateLoaderOptions)
<del> );
<del> if(!options.recordsPath) options.recordsPath = recordsPath;
<del> const compiler = webpack(options);
<del> compiler.run((err, stats) => {
<del> if(err) return done(err);
<del> const jsonStats = stats.toJson({
<del> errorDetails: true
<add> describe(testName, () => {
<add> it(testName + " should compile", (done) => {
<add> const testDirectory = path.join(casesPath, category.name, testName);
<add> const outputDirectory = path.join(__dirname, "js", "hot-cases", category.name, testName);
<add> const recordsPath = path.join(outputDirectory, "records.json");
<add> if(fs.existsSync(recordsPath))
<add> fs.unlinkSync(recordsPath);
<add> const fakeUpdateLoaderOptions = {
<add> updateIndex: 0
<add> };
<add> const configPath = path.join(testDirectory, "webpack.config.js");
<add> let options = {};
<add> if(fs.existsSync(configPath))
<add> options = require(configPath);
<add> if(!options.mode) options.mode = "development";
<add> if(!options.context) options.context = testDirectory;
<add> if(!options.entry) options.entry = "./index.js";
<add> if(!options.output) options.output = {};
<add> if(!options.output.path) options.output.path = outputDirectory;
<add> if(!options.output.filename) options.output.filename = "bundle.js";
<add> if(options.output.pathinfo === undefined) options.output.pathinfo = true;
<add> if(!options.module) options.module = {};
<add> if(!options.module.rules) options.module.rules = [];
<add> options.module.rules.push({
<add> test: /\.js$/,
<add> loader: path.join(__dirname, "hotCases", "fake-update-loader.js"),
<add> enforce: "pre"
<ide> });
<del> if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
<del> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
<del> let exportedTests = 0;
<add> if(!options.target) options.target = "async-node";
<add> if(!options.plugins) options.plugins = [];
<add> options.plugins.push(
<add> new webpack.HotModuleReplacementPlugin(),
<add> new webpack.NamedModulesPlugin(),
<add> new webpack.LoaderOptionsPlugin(fakeUpdateLoaderOptions)
<add> );
<add> if(!options.recordsPath) options.recordsPath = recordsPath;
<add> const compiler = webpack(options);
<add> compiler.run((err, stats) => {
<add> if(err) return done(err);
<add> const jsonStats = stats.toJson({
<add> errorDetails: true
<add> });
<add> if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
<add> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
<add> let exportedTests = [];
<ide>
<del> const __it = createNestableIt(done);
<del> function _it(title, fn) {
<del> __it(title, fn);
<del> exportedTests++;
<del> }
<add> function _it(title, fn) {
<add> exportedTests.push(fit(title, fn));
<add> }
<ide>
<del> function _next(callback) {
<del> fakeUpdateLoaderOptions.updateIndex++;
<del> compiler.run((err, stats) => {
<del> if(err) return done(err);
<del> const jsonStats = stats.toJson({
<del> errorDetails: true
<add> function _next(callback) {
<add> fakeUpdateLoaderOptions.updateIndex++;
<add> compiler.run((err, stats) => {
<add> if(err) return done(err);
<add> const jsonStats = stats.toJson({
<add> errorDetails: true
<add> });
<add> if(checkArrayExpectation(testDirectory, jsonStats, "error", "errors" + fakeUpdateLoaderOptions.updateIndex, "Error", done)) return;
<add> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "warnings" + fakeUpdateLoaderOptions.updateIndex, "Warning", done)) return;
<add> if(callback) callback(jsonStats);
<ide> });
<del> if(checkArrayExpectation(testDirectory, jsonStats, "error", "errors" + fakeUpdateLoaderOptions.updateIndex, "Error", done)) return;
<del> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "warnings" + fakeUpdateLoaderOptions.updateIndex, "Warning", done)) return;
<del> if(callback) callback(jsonStats);
<del> });
<del> }
<add> }
<ide>
<del> function _require(module) {
<del> if(module.substr(0, 2) === "./") {
<del> const p = path.join(outputDirectory, module);
<del> const fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it, expect, NEXT, STATS) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
<del> const m = {
<del> exports: {}
<del> };
<del> fn.call(m.exports, _require, m, m.exports, outputDirectory, p, _it, expect, _next, jsonStats);
<del> return m.exports;
<del> } else return require(module);
<del> }
<del> _require("./bundle.js");
<del> if(exportedTests < 1) return done(new Error("No tests exported by test case"));
<add> function _require(module) {
<add> if(module.substr(0, 2) === "./") {
<add> const p = path.join(outputDirectory, module);
<add> const fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it, expect, NEXT, STATS) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
<add> const m = {
<add> exports: {}
<add> };
<add> fn.call(m.exports, _require, m, m.exports, outputDirectory, p, _it, expect, _next, jsonStats);
<add> return m.exports;
<add> } else return require(module);
<add> }
<add> _require("./bundle.js");
<add> if(exportedTests.length < 1) return done(new Error("No tests exported by test case"));
<add> async.waterfall(
<add> exportedTests.map(test => (callback) => test.execute(callback, true)),
<add> done
<add> );
<add> });
<ide> });
<ide> });
<ide> }); | 2 |
PHP | PHP | fix typo and move below other where methods | 77c577a4ac1c431c6012d24e6c64cdc59e9e9327 | <ide><path>src/Illuminate/Testing/Fluent/Concerns/Matching.php
<ide>
<ide> trait Matching
<ide> {
<del> /**
<del> * Assets that all values exist and match their expected values.
<del> *
<del> * @param string $key
<del> * @param array|string $expected
<del> *
<del> * @return $this
<del> */
<del> public function whereHas(string $key, $expected)
<del> {
<del> $actual = Collection::make(
<del> $this->prop($key) ?? $this->prop()
<del> );
<del>
<del> $missing = Collection::make($expected)->reject(function ($search) use ($key, $actual) {
<del> if ($actual->containsStrict($key, $search)) {
<del> return true;
<del> }
<del>
<del> return $actual->containsStrict($search);
<del> })->toArray();
<del>
<del> $values = array_values($missing);
<del>
<del> PHPUnit::assertEmpty(
<del> $missing,
<del> sprintf(
<del> 'Property [%s] does not contain [%s].',
<del> $key,
<del> implode(', ', $values)
<del> )
<del> );
<del>
<del> return $this;
<del> }
<del>
<ide> /**
<ide> * Asserts that the property matches the expected value.
<ide> *
<ide> public function whereAllType(array $bindings): self
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Asserts that all values exist and match their expected values.
<add> *
<add> * @param string $key
<add> * @param array|string $expected
<add> *
<add> * @return $this
<add> */
<add> public function whereHas(string $key, $expected)
<add> {
<add> $actual = Collection::make(
<add> $this->prop($key) ?? $this->prop()
<add> );
<add>
<add> $missing = Collection::make($expected)->reject(function ($search) use ($key, $actual) {
<add> if ($actual->containsStrict($key, $search)) {
<add> return true;
<add> }
<add>
<add> return $actual->containsStrict($search);
<add> })->toArray();
<add>
<add> $values = array_values($missing);
<add>
<add> PHPUnit::assertEmpty(
<add> $missing,
<add> sprintf(
<add> 'Property [%s] does not contain [%s].',
<add> $key,
<add> implode(', ', $values)
<add> )
<add> );
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Ensures that all properties are sorted the same way, recursively.
<ide> * | 1 |
Java | Java | combine refcount tests | 9e353ffe8c8fcb11585c824eeed93728f769cb06 | <ide><path>src/test/java/rx/RefCountTests.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx;
<del>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.mockito.Matchers.any;
<del>import static org.mockito.Mockito.inOrder;
<del>import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.never;
<del>import static org.mockito.Mockito.verify;
<del>
<del>import java.util.ArrayList;
<del>import java.util.Arrays;
<del>import java.util.List;
<del>import java.util.concurrent.TimeUnit;
<del>import java.util.concurrent.atomic.AtomicInteger;
<del>
<del>import org.junit.Before;
<del>import org.junit.Test;
<del>import org.mockito.InOrder;
<del>import org.mockito.MockitoAnnotations;
<del>
<del>import rx.Observable.OnSubscribe;
<del>import rx.functions.Action0;
<del>import rx.functions.Action1;
<del>import rx.functions.Func2;
<del>import rx.observers.Subscribers;
<del>import rx.observers.TestSubscriber;
<del>import rx.schedulers.TestScheduler;
<del>import rx.subjects.ReplaySubject;
<del>import rx.subscriptions.Subscriptions;
<del>
<del>public class RefCountTests {
<del>
<del> @Before
<del> public void setUp() {
<del> MockitoAnnotations.initMocks(this);
<del> }
<del>
<del> @Test
<del> public void onlyFirstShouldSubscribeAndLastUnsubscribe() {
<del> final AtomicInteger subscriptionCount = new AtomicInteger();
<del> final AtomicInteger unsubscriptionCount = new AtomicInteger();
<del> Observable<Integer> observable = Observable.create(new OnSubscribe<Integer>() {
<del> @Override
<del> public void call(Subscriber<? super Integer> observer) {
<del> subscriptionCount.incrementAndGet();
<del> observer.add(Subscriptions.create(new Action0() {
<del> @Override
<del> public void call() {
<del> unsubscriptionCount.incrementAndGet();
<del> }
<del> }));
<del> }
<del> });
<del> Observable<Integer> refCounted = observable.publish().refCount();
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> observer = mock(Observer.class);
<del> Subscription first = refCounted.subscribe(observer);
<del> assertEquals(1, subscriptionCount.get());
<del> Subscription second = refCounted.subscribe(observer);
<del> assertEquals(1, subscriptionCount.get());
<del> first.unsubscribe();
<del> assertEquals(0, unsubscriptionCount.get());
<del> second.unsubscribe();
<del> assertEquals(1, unsubscriptionCount.get());
<del> }
<del>
<del> @Test
<del> public void testRefCount() {
<del> TestScheduler s = new TestScheduler();
<del> Observable<Long> interval = Observable.interval(100, TimeUnit.MILLISECONDS, s).publish().refCount();
<del>
<del> // subscribe list1
<del> final List<Long> list1 = new ArrayList<Long>();
<del> Subscription s1 = interval.subscribe(new Action1<Long>() {
<del>
<del> @Override
<del> public void call(Long t1) {
<del> list1.add(t1);
<del> }
<del>
<del> });
<del> s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
<del>
<del> assertEquals(2, list1.size());
<del> assertEquals(0L, list1.get(0).longValue());
<del> assertEquals(1L, list1.get(1).longValue());
<del>
<del> // subscribe list2
<del> final List<Long> list2 = new ArrayList<Long>();
<del> Subscription s2 = interval.subscribe(new Action1<Long>() {
<del>
<del> @Override
<del> public void call(Long t1) {
<del> list2.add(t1);
<del> }
<del>
<del> });
<del> s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
<del>
<del> // list 1 should have 5 items
<del> assertEquals(5, list1.size());
<del> assertEquals(2L, list1.get(2).longValue());
<del> assertEquals(3L, list1.get(3).longValue());
<del> assertEquals(4L, list1.get(4).longValue());
<del>
<del> // list 2 should only have 3 items
<del> assertEquals(3, list2.size());
<del> assertEquals(2L, list2.get(0).longValue());
<del> assertEquals(3L, list2.get(1).longValue());
<del> assertEquals(4L, list2.get(2).longValue());
<del>
<del> // unsubscribe list1
<del> s1.unsubscribe();
<del>
<del> // advance further
<del> s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
<del>
<del> // list 1 should still have 5 items
<del> assertEquals(5, list1.size());
<del>
<del> // list 2 should have 6 items
<del> assertEquals(6, list2.size());
<del> assertEquals(5L, list2.get(3).longValue());
<del> assertEquals(6L, list2.get(4).longValue());
<del> assertEquals(7L, list2.get(5).longValue());
<del>
<del> // unsubscribe list2
<del> s2.unsubscribe();
<del>
<del> // advance further
<del> s.advanceTimeBy(1000, TimeUnit.MILLISECONDS);
<del>
<del> // subscribing a new one should start over because the source should have been unsubscribed
<del> // subscribe list3
<del> final List<Long> list3 = new ArrayList<Long>();
<del> interval.subscribe(new Action1<Long>() {
<del>
<del> @Override
<del> public void call(Long t1) {
<del> list3.add(t1);
<del> }
<del>
<del> });
<del> s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
<del>
<del> assertEquals(2, list3.size());
<del> assertEquals(0L, list3.get(0).longValue());
<del> assertEquals(1L, list3.get(1).longValue());
<del>
<del> }
<del>
<del> @Test
<del> public void testAlreadyUnsubscribedClient() {
<del> Subscriber<Integer> done = Subscribers.empty();
<del> done.unsubscribe();
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> o = mock(Observer.class);
<del>
<del> Observable<Integer> result = Observable.just(1).publish().refCount();
<del>
<del> result.subscribe(done);
<del>
<del> result.subscribe(o);
<del>
<del> verify(o).onNext(1);
<del> verify(o).onCompleted();
<del> verify(o, never()).onError(any(Throwable.class));
<del> }
<del> @Test
<del> public void testAlreadyUnsubscribedInterleavesWithClient() {
<del> ReplaySubject<Integer> source = ReplaySubject.create();
<del>
<del> Subscriber<Integer> done = Subscribers.empty();
<del> done.unsubscribe();
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> o = mock(Observer.class);
<del> InOrder inOrder = inOrder(o);
<del>
<del> Observable<Integer> result = source.publish().refCount();
<del>
<del> result.subscribe(o);
<del>
<del> source.onNext(1);
<del>
<del> result.subscribe(done);
<del>
<del> source.onNext(2);
<del> source.onCompleted();
<del>
<del> inOrder.verify(o).onNext(1);
<del> inOrder.verify(o).onNext(2);
<del> inOrder.verify(o).onCompleted();
<del> verify(o, never()).onError(any(Throwable.class));
<del> }
<del>
<del> @Test
<del> public void testConnectDisconnectConnectAndSubjectState() {
<del> Observable<Integer> o1 = Observable.just(10);
<del> Observable<Integer> o2 = Observable.just(20);
<del> Observable<Integer> combined = Observable.combineLatest(o1, o2, new Func2<Integer, Integer, Integer>() {
<del>
<del> @Override
<del> public Integer call(Integer t1, Integer t2) {
<del> return t1 + t2;
<del> }
<del>
<del> }).publish().refCount();
<del>
<del> TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>();
<del> TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>();
<del>
<del> combined.subscribe(ts1);
<del> combined.subscribe(ts2);
<del>
<del> ts1.assertTerminalEvent();
<del> ts1.assertNoErrors();
<del> ts1.assertReceivedOnNext(Arrays.asList(30));
<del>
<del> ts2.assertTerminalEvent();
<del> ts2.assertNoErrors();
<del> ts2.assertReceivedOnNext(Arrays.asList(30));
<del> }
<del>}
<ide><path>src/test/java/rx/internal/operators/OnSubscribeRefCountTest.java
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.junit.Assert.fail;
<del>
<add>import static org.mockito.Matchers.any;
<add>import static org.mockito.Mockito.inOrder;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.never;
<add>import static org.mockito.Mockito.verify;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<ide> import java.util.concurrent.CountDownLatch;
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<add>import org.junit.Before;
<ide> import org.junit.Test;
<add>import org.mockito.InOrder;
<add>import org.mockito.MockitoAnnotations;
<ide>
<ide> import rx.Observable;
<ide> import rx.Observable.OnSubscribe;
<add>import rx.Observer;
<ide> import rx.Subscriber;
<ide> import rx.Subscription;
<ide> import rx.functions.Action0;
<ide> import rx.functions.Action1;
<add>import rx.functions.Func2;
<add>import rx.observers.Subscribers;
<ide> import rx.observers.TestSubscriber;
<ide> import rx.schedulers.Schedulers;
<add>import rx.schedulers.TestScheduler;
<add>import rx.subjects.ReplaySubject;
<add>import rx.subscriptions.Subscriptions;
<ide>
<ide> public class OnSubscribeRefCountTest {
<ide>
<add> @Before
<add> public void setUp() {
<add> MockitoAnnotations.initMocks(this);
<add> }
<add>
<ide> @Test
<ide> public void testRefCountAsync() {
<ide> final AtomicInteger subscribeCount = new AtomicInteger();
<ide> public void call(Subscriber<? super Long> subscriber) {
<ide> }
<ide>
<ide> @Test
<del> public void testConcurrency() {
<add> public void onlyFirstShouldSubscribeAndLastUnsubscribe() {
<add> final AtomicInteger subscriptionCount = new AtomicInteger();
<add> final AtomicInteger unsubscriptionCount = new AtomicInteger();
<add> Observable<Integer> observable = Observable.create(new OnSubscribe<Integer>() {
<add> @Override
<add> public void call(Subscriber<? super Integer> observer) {
<add> subscriptionCount.incrementAndGet();
<add> observer.add(Subscriptions.create(new Action0() {
<add> @Override
<add> public void call() {
<add> unsubscriptionCount.incrementAndGet();
<add> }
<add> }));
<add> }
<add> });
<add> Observable<Integer> refCounted = observable.publish().refCount();
<add> @SuppressWarnings("unchecked")
<add> Observer<Integer> observer = mock(Observer.class);
<add> Subscription first = refCounted.subscribe(observer);
<add> assertEquals(1, subscriptionCount.get());
<add> Subscription second = refCounted.subscribe(observer);
<add> assertEquals(1, subscriptionCount.get());
<add> first.unsubscribe();
<add> assertEquals(0, unsubscriptionCount.get());
<add> second.unsubscribe();
<add> assertEquals(1, unsubscriptionCount.get());
<add> }
<add>
<add> @Test
<add> public void testRefCount() {
<add> TestScheduler s = new TestScheduler();
<add> Observable<Long> interval = Observable.interval(100, TimeUnit.MILLISECONDS, s).publish().refCount();
<add>
<add> // subscribe list1
<add> final List<Long> list1 = new ArrayList<Long>();
<add> Subscription s1 = interval.subscribe(new Action1<Long>() {
<add>
<add> @Override
<add> public void call(Long t1) {
<add> list1.add(t1);
<add> }
<add>
<add> });
<add> s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
<add>
<add> assertEquals(2, list1.size());
<add> assertEquals(0L, list1.get(0).longValue());
<add> assertEquals(1L, list1.get(1).longValue());
<add>
<add> // subscribe list2
<add> final List<Long> list2 = new ArrayList<Long>();
<add> Subscription s2 = interval.subscribe(new Action1<Long>() {
<add>
<add> @Override
<add> public void call(Long t1) {
<add> list2.add(t1);
<add> }
<add>
<add> });
<add> s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
<add>
<add> // list 1 should have 5 items
<add> assertEquals(5, list1.size());
<add> assertEquals(2L, list1.get(2).longValue());
<add> assertEquals(3L, list1.get(3).longValue());
<add> assertEquals(4L, list1.get(4).longValue());
<add>
<add> // list 2 should only have 3 items
<add> assertEquals(3, list2.size());
<add> assertEquals(2L, list2.get(0).longValue());
<add> assertEquals(3L, list2.get(1).longValue());
<add> assertEquals(4L, list2.get(2).longValue());
<add>
<add> // unsubscribe list1
<add> s1.unsubscribe();
<add>
<add> // advance further
<add> s.advanceTimeBy(300, TimeUnit.MILLISECONDS);
<add>
<add> // list 1 should still have 5 items
<add> assertEquals(5, list1.size());
<add>
<add> // list 2 should have 6 items
<add> assertEquals(6, list2.size());
<add> assertEquals(5L, list2.get(3).longValue());
<add> assertEquals(6L, list2.get(4).longValue());
<add> assertEquals(7L, list2.get(5).longValue());
<add>
<add> // unsubscribe list2
<add> s2.unsubscribe();
<add>
<add> // advance further
<add> s.advanceTimeBy(1000, TimeUnit.MILLISECONDS);
<add>
<add> // subscribing a new one should start over because the source should have been unsubscribed
<add> // subscribe list3
<add> final List<Long> list3 = new ArrayList<Long>();
<add> interval.subscribe(new Action1<Long>() {
<add>
<add> @Override
<add> public void call(Long t1) {
<add> list3.add(t1);
<add> }
<add>
<add> });
<add> s.advanceTimeBy(200, TimeUnit.MILLISECONDS);
<add>
<add> assertEquals(2, list3.size());
<add> assertEquals(0L, list3.get(0).longValue());
<add> assertEquals(1L, list3.get(1).longValue());
<add>
<add> }
<add>
<add> @Test
<add> public void testAlreadyUnsubscribedClient() {
<add> Subscriber<Integer> done = Subscribers.empty();
<add> done.unsubscribe();
<add>
<add> @SuppressWarnings("unchecked")
<add> Observer<Integer> o = mock(Observer.class);
<add>
<add> Observable<Integer> result = Observable.just(1).publish().refCount();
<add>
<add> result.subscribe(done);
<add>
<add> result.subscribe(o);
<add>
<add> verify(o).onNext(1);
<add> verify(o).onCompleted();
<add> verify(o, never()).onError(any(Throwable.class));
<add> }
<add>
<add> @Test
<add> public void testAlreadyUnsubscribedInterleavesWithClient() {
<add> ReplaySubject<Integer> source = ReplaySubject.create();
<add>
<add> Subscriber<Integer> done = Subscribers.empty();
<add> done.unsubscribe();
<add>
<add> @SuppressWarnings("unchecked")
<add> Observer<Integer> o = mock(Observer.class);
<add> InOrder inOrder = inOrder(o);
<add>
<add> Observable<Integer> result = source.publish().refCount();
<add>
<add> result.subscribe(o);
<add>
<add> source.onNext(1);
<add>
<add> result.subscribe(done);
<add>
<add> source.onNext(2);
<add> source.onCompleted();
<add>
<add> inOrder.verify(o).onNext(1);
<add> inOrder.verify(o).onNext(2);
<add> inOrder.verify(o).onCompleted();
<add> verify(o, never()).onError(any(Throwable.class));
<add> }
<add>
<add> @Test
<add> public void testConnectDisconnectConnectAndSubjectState() {
<add> Observable<Integer> o1 = Observable.just(10);
<add> Observable<Integer> o2 = Observable.just(20);
<add> Observable<Integer> combined = Observable.combineLatest(o1, o2, new Func2<Integer, Integer, Integer>() {
<add>
<add> @Override
<add> public Integer call(Integer t1, Integer t2) {
<add> return t1 + t2;
<add> }
<add>
<add> }).publish().refCount();
<ide>
<add> TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>();
<add> TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>();
<add>
<add> combined.subscribe(ts1);
<add> combined.subscribe(ts2);
<add>
<add> ts1.assertTerminalEvent();
<add> ts1.assertNoErrors();
<add> ts1.assertReceivedOnNext(Arrays.asList(30));
<add>
<add> ts2.assertTerminalEvent();
<add> ts2.assertNoErrors();
<add> ts2.assertReceivedOnNext(Arrays.asList(30));
<ide> }
<add>
<ide> } | 2 |
Ruby | Ruby | add xcode 2.5 compiler | b31f6c0099e344253bf5dfb8bc1202d7b4c70f83 | <ide><path>Library/Homebrew/os/mac.rb
<ide> def preferred_arch
<ide> end
<ide>
<ide> STANDARD_COMPILERS = {
<add> "2.5" => { :gcc_40_build => 5370 },
<ide> "3.1.4" => { :gcc_40_build => 5493, :gcc_42_build => 5577 },
<ide> "3.2.6" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "1.7", :clang_build => 77 },
<ide> "4.0" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "2.0", :clang_build => 137 }, | 1 |
Text | Text | update v5.4 changelog | 7f7eb7cd089e72743702e02c278b2bf532d650b6 | <ide><path>CHANGELOG-5.4.md
<ide> # Release Notes for 5.4.x
<ide>
<add>## [Unreleased]
<add>
<add>### Changed
<add>- Renamed `MakeAuthCommand` to `AuthMakeCommand` ([#20216](https://github.com/laravel/framework/pull/20216))
<add>- Don't use `asset()` helper inside `mix()` ([#20197](https://github.com/laravel/framework/pull/20197))
<add>
<add>### Fixed
<add>- Make sure `Model::getDates()` returns unique columns ([#20193](https://github.com/laravel/framework/pull/20193))
<add>- Fixed pulled `doctrine/inflector` version ([#20227](https://github.com/laravel/framework/pull/20227))
<add>- Fixed issue with `chunkById()` when `orderByRaw()` is used ([#20236](https://github.com/laravel/framework/pull/20236))
<add>
<add>
<ide> ## v5.4.30 (2017-07-19)
<ide>
<ide> ### Fixed | 1 |
PHP | PHP | remove stub response | 4e924ff45ab92e2cfae56b649b784a8cc57b9e45 | <ide><path>src/TestSuite/Stub/Response.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @since 3.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\TestSuite\Stub;
<del>
<del>use Cake\Http\Response as Base;
<del>
<del>/**
<del> * A response class intended for test cases.
<del> */
<del>class Response extends Base
<del>{
<del>
<del> /**
<del> * Stub the send() method so headers and output are not sent.
<del> *
<del> * @return $this
<del> */
<del> public function send()
<del> {
<del> if ($this->hasHeader('Location') && $this->_status === 200) {
<del> $this->statusCode(302);
<del> }
<del> $this->_setContentType();
<del>
<del> return $this;
<del> }
<del>} | 1 |
Java | Java | add websocketclient for undertow | b4b7b163d1197caa338ea17c026ee862526b0ef5 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/UndertowWebSocketHandlerAdapter.java
<ide> import io.undertow.websockets.core.CloseMessage;
<ide> import io.undertow.websockets.core.WebSocketChannel;
<ide> import io.undertow.websockets.spi.WebSocketHttpExchange;
<add>
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<add>import reactor.core.publisher.MonoProcessor;
<add>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<ide> public class UndertowWebSocketHandlerAdapter extends WebSocketHandlerAdapterSupp
<ide>
<ide> private UndertowWebSocketSession delegateSession;
<ide>
<add> private final MonoProcessor<Void> completionMono;
<add>
<ide>
<ide> public UndertowWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo info,
<ide> DataBufferFactory bufferFactory) {
<ide>
<add> this(delegate, info, bufferFactory, null);
<add> }
<add>
<add> public UndertowWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo info,
<add> DataBufferFactory bufferFactory, MonoProcessor<Void> completionMono) {
<add>
<ide> super(delegate, info, bufferFactory);
<add> this.completionMono = completionMono;
<ide> }
<ide>
<ide>
<ide> else if (Type.PONG.equals(type)) {
<ide> throw new IllegalArgumentException("Unexpected message type: " + message);
<ide> }
<ide> }
<del>
<ide> }
<ide>
<add>
<ide> private final class HandlerResultSubscriber implements Subscriber<Void> {
<ide>
<ide> @Override
<ide> public void onNext(Void aVoid) {
<ide>
<ide> @Override
<ide> public void onError(Throwable ex) {
<add> if (completionMono != null) {
<add> completionMono.onError(ex);
<add> }
<ide> int code = CloseStatus.SERVER_ERROR.getCode();
<ide> delegateSession.close(new CloseStatus(code, ex.getMessage()));
<ide> }
<ide>
<ide> @Override
<ide> public void onComplete() {
<add> if (completionMono != null) {
<add> completionMono.onComplete();
<add> }
<ide> delegateSession.close();
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.reactive.socket.client;
<add>
<add>import java.io.IOException;
<add>import java.net.URI;
<add>import java.security.NoSuchAlgorithmException;
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Optional;
<add>import java.util.concurrent.CancellationException;
<add>import java.util.function.Function;
<add>
<add>import javax.net.ssl.SSLContext;
<add>
<add>import io.undertow.protocols.ssl.UndertowXnioSsl;
<add>import io.undertow.server.DefaultByteBufferPool;
<add>import io.undertow.websockets.WebSocketExtension;
<add>import io.undertow.websockets.client.WebSocketClientNegotiation;
<add>import io.undertow.websockets.core.WebSocketChannel;
<add>
<add>import org.xnio.IoFuture;
<add>import org.xnio.IoFuture.Notifier;
<add>import org.xnio.IoFuture.Status;
<add>import org.xnio.OptionMap;
<add>import org.xnio.Options;
<add>import org.xnio.Xnio;
<add>import org.xnio.XnioWorker;
<add>
<add>import reactor.core.publisher.Mono;
<add>import reactor.core.publisher.MonoProcessor;
<add>
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.WebSocketHandler;
<add>import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter;
<add>
<add>/**
<add> * An Undertow based implementation of {@link WebSocketClient}.
<add> *
<add> * @author Violeta Georgieva
<add> * @since 5.0
<add> */
<add>public class UndertowWebSocketClient extends WebSocketClientSupport implements WebSocketClient {
<add>
<add> private static final int DEFAULT_BUFFER_SIZE = 8192;
<add>
<add> private static XnioWorker worker;
<add>
<add> static {
<add> try {
<add> worker = Xnio.getInstance().createWorker(OptionMap.builder()
<add> .set(Options.WORKER_IO_THREADS, 2)
<add> .set(Options.CONNECTION_HIGH_WATER, 1000000)
<add> .set(Options.CONNECTION_LOW_WATER, 1000000)
<add> .set(Options.WORKER_TASK_CORE_THREADS, 30)
<add> .set(Options.WORKER_TASK_MAX_THREADS, 30)
<add> .set(Options.TCP_NODELAY, true)
<add> .set(Options.CORK, true)
<add> .getMap());
<add> }
<add> catch (IOException ex) {
<add> throw new RuntimeException(ex);
<add> }
<add> }
<add>
<add> private final Function<URI, io.undertow.websockets.client.WebSocketClient.ConnectionBuilder> builder;
<add>
<add>
<add> /**
<add> * Default constructor that uses
<add> * {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder(XnioWorker, ByteBufferPool, URI)}
<add> * to create a web socket connection.
<add> */
<add> public UndertowWebSocketClient() {
<add> this(UndertowWebSocketClient::createDefaultConnectionBuilder);
<add> }
<add>
<add> /**
<add> * Constructor that accepts an existing
<add> * {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder(XnioWorker, ByteBufferPool, URI)}
<add> * instance.
<add> * @param builder a connection builder that can be used to create a web socket connection.
<add> */
<add> public UndertowWebSocketClient(Function<URI,
<add> io.undertow.websockets.client.WebSocketClient.ConnectionBuilder> builder) {
<add> this.builder = builder;
<add> }
<add>
<add> private static io.undertow.websockets.client.WebSocketClient.ConnectionBuilder createDefaultConnectionBuilder(
<add> URI url) {
<add>
<add> io.undertow.websockets.client.WebSocketClient.ConnectionBuilder builder =
<add> io.undertow.websockets.client.WebSocketClient.connectionBuilder(
<add> worker, new DefaultByteBufferPool(false, DEFAULT_BUFFER_SIZE), url);
<add>
<add> boolean secure = "wss".equals(url.getScheme());
<add> if (secure) {
<add> try {
<add> UndertowXnioSsl ssl = new UndertowXnioSsl(Xnio.getInstance(),
<add> OptionMap.EMPTY, SSLContext.getDefault());
<add> builder.setSsl(ssl);
<add> }
<add> catch (NoSuchAlgorithmException ex) {
<add> throw new RuntimeException("Failed to create Undertow ConnectionBuilder for " + url, ex);
<add> }
<add> }
<add>
<add> return builder;
<add> }
<add>
<add>
<add> @Override
<add> public Mono<Void> execute(URI url, WebSocketHandler handler) {
<add> return execute(url, new HttpHeaders(), handler);
<add> }
<add>
<add> @Override
<add> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler) {
<add> return connectInternal(url, headers, handler);
<add> }
<add>
<add> private Mono<Void> connectInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
<add> MonoProcessor<Void> processor = MonoProcessor.create();
<add> return Mono.fromCallable(
<add> () -> {
<add> WSClientNegotiation clientNegotiation =
<add> new WSClientNegotiation(beforeHandshake(url, headers, handler),
<add> Collections.emptyList(), headers);
<add>
<add> io.undertow.websockets.client.WebSocketClient.ConnectionBuilder builder =
<add> this.builder.apply(url).setClientNegotiation(clientNegotiation);
<add>
<add> IoFuture<WebSocketChannel> future = builder.connect();
<add> future.addNotifier(new ResultNotifier(url, handler, clientNegotiation, processor), new Object());
<add> return future;
<add> })
<add> .then(processor);
<add> }
<add>
<add>
<add> private static final class ResultNotifier implements Notifier<WebSocketChannel, Object> {
<add>
<add> private final URI url;
<add>
<add> private final WebSocketHandler handler;
<add>
<add> private final WSClientNegotiation clientNegotiation;
<add>
<add> private final MonoProcessor<Void> processor;
<add>
<add> public ResultNotifier(URI url, WebSocketHandler handler,
<add> WSClientNegotiation clientNegotiation, MonoProcessor<Void> processor) {
<add> this.url = url;
<add> this.handler = handler;
<add> this.clientNegotiation = clientNegotiation;
<add> this.processor = processor;
<add> }
<add>
<add> @Override
<add> public void notify(IoFuture<? extends WebSocketChannel> ioFuture,
<add> Object attachment) {
<add> if (Status.CANCELLED.equals(ioFuture.getStatus())) {
<add> processor.onError(null);
<add> }
<add> else if (Status.FAILED.equals(ioFuture.getStatus())) {
<add> processor.onError(ioFuture.getException());
<add> }
<add> else if (Status.DONE.equals(ioFuture.getStatus())) {
<add> try {
<add> WebSocketChannel channel = ioFuture.get();
<add> DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
<add> HandshakeInfo info = new HandshakeInfo(url, clientNegotiation.getResponseHeaders(),
<add> Mono.empty(), Optional.ofNullable(channel.getSubProtocol()));
<add>
<add> UndertowWebSocketHandlerAdapter adapter =
<add> new UndertowWebSocketHandlerAdapter(handler,
<add> info, bufferFactory, processor);
<add> adapter.onConnect(null, channel);
<add> }
<add> catch (CancellationException | IOException ex) {
<add> processor.onError(ex);
<add> }
<add> }
<add> }
<add> }
<add>
<add>
<add> private static final class WSClientNegotiation extends WebSocketClientNegotiation {
<add>
<add> private final HttpHeaders requestHeaders;
<add>
<add> private HttpHeaders responseHeaders = new HttpHeaders();
<add>
<add> public WSClientNegotiation(String[] subProtocols,
<add> List<WebSocketExtension> extensions, HttpHeaders requestHeaders) {
<add> super(Arrays.asList(subProtocols), extensions);
<add> this.requestHeaders = requestHeaders;
<add> }
<add>
<add> @Override
<add> public void beforeRequest(Map<String, List<String>> headers) {
<add> requestHeaders.forEach((k, v) -> headers.put(k, v));
<add> }
<add>
<add> @Override
<add> public void afterRequest(Map<String, List<String>> headers) {
<add> headers.forEach((k, v) -> responseHeaders.put(k, v));
<add> }
<add>
<add> public HttpHeaders getResponseHeaders() {
<add> return responseHeaders;
<add> }
<add> }
<add>
<add>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java
<ide> package org.springframework.web.reactive.socket.server.upgrade;
<ide>
<ide> import java.security.Principal;
<del>import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/WebSocketIntegrationTests.java
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.server.reactive.bootstrap.RxNettyHttpServer;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
<ide> import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
<ide> import org.springframework.web.reactive.socket.client.RxNettyWebSocketClient;
<ide> import org.springframework.web.reactive.socket.client.StandardWebSocketClient;
<add>import org.springframework.web.reactive.socket.client.UndertowWebSocketClient;
<ide> import org.springframework.web.reactive.socket.client.WebSocketClient;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public void echoStandardClient() throws Exception {
<ide> testEcho(new StandardWebSocketClient());
<ide> }
<ide>
<add> @Test
<add> public void echoUndertowClient() throws Exception {
<add> if (server instanceof RxNettyHttpServer) {
<add> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400)
<add> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
<add>
<add> return;
<add> }
<add> testEcho(new UndertowWebSocketClient());
<add> }
<add>
<ide> private void testEcho(WebSocketClient client) throws URISyntaxException {
<ide> int count = 100;
<ide> Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
<ide> public void subProtocolStandardClient() throws Exception {
<ide> testSubProtocol(new StandardWebSocketClient());
<ide> }
<ide>
<add> @Test
<add> public void subProtocolUndertowClient() throws Exception {
<add> if (server instanceof RxNettyHttpServer) {
<add> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461)
<add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400)
<add> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
<add>
<add> return;
<add> }
<add> testSubProtocol(new UndertowWebSocketClient());
<add> }
<add>
<ide> private void testSubProtocol(WebSocketClient client) throws URISyntaxException {
<ide> String protocol = "echo-v1";
<ide> AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>(); | 4 |
Ruby | Ruby | convert two hash lookups into one | 25ed6627ddac95a95f1d58d3202518544cebdd35 | <ide><path>actionview/lib/action_view/helpers/tag_helper.rb
<ide> module TagHelper
<ide> visible).to_set
<ide>
<ide> BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym))
<add> BOOLEAN_ATTRIBUTES.freeze
<ide>
<del> TAG_PREFIXES = ["aria", "data", :aria, :data].to_set
<add> TAG_PREFIXES = ["aria", "data", :aria, :data].to_set.freeze
<add>
<add> TAG_TYPES = {}
<add> TAG_TYPES.merge! BOOLEAN_ATTRIBUTES.index_with(:boolean)
<add> TAG_TYPES.merge! TAG_PREFIXES.index_with(:prefix)
<add> TAG_TYPES.freeze
<ide>
<ide> PRE_CONTENT_STRINGS = Hash.new { "" }
<ide> PRE_CONTENT_STRINGS[:textarea] = "\n"
<ide> def tag_options(options, escape = true)
<ide> output = +""
<ide> sep = " "
<ide> options.each_pair do |key, value|
<del> if TAG_PREFIXES.include?(key) && value.is_a?(Hash)
<add> type = TAG_TYPES[key]
<add> if type == :prefix && value.is_a?(Hash)
<ide> value.each_pair do |k, v|
<ide> next if v.nil?
<ide> output << sep
<ide> output << prefix_tag_option(key, k, v, escape)
<ide> end
<del> elsif BOOLEAN_ATTRIBUTES.include?(key)
<add> elsif type == :boolean
<ide> if value
<ide> output << sep
<ide> output << boolean_tag_option(key) | 1 |
Javascript | Javascript | apply automatic lint fixes for _inspect.js | ea47bd2137eb5d2b8887748a237c11cb5d5a9897 | <ide><path>lib/internal/inspector/_inspect.js
<ide> class NodeInspector {
<ide>
<ide> print(text, appendNewline = false) {
<ide> this.clearLine();
<del> this.stdout.write(appendNewline ? `${text}\n` : text);
<add> this.stdout.write(appendNewline ? `${text}\n` : text);
<ide> }
<ide>
<del> #stdioBuffers = {stdout: '', stderr: ''};
<add> #stdioBuffers = { stdout: '', stderr: '' };
<ide> childPrint(text, which) {
<ide> const lines = (this.#stdioBuffers[which] + text)
<ide> .split(/\r\n|\r|\n/g);
<ide> class NodeInspector {
<ide> this.repl.displayPrompt(true);
<ide> }
<ide> }
<del>
<add>
<ide> if (textToPrint.endsWith('Waiting for the debugger to disconnect...\n')) {
<ide> this.killChild();
<ide> } | 1 |
Javascript | Javascript | improve angular.widget docs | e09a78438f9c4a43aec6fefed9efd58a0b4060de | <ide><path>src/widgets.js
<ide> * @name angular.widget
<ide> * @description
<ide> *
<del> * Widgets are custom DOM elements. An angular widget can be either a custom
<del> * attribute that modifies an existing DOM elements or an entirely new DOM element.
<add> * An angular widget can be either a custom attribute that modifies an existing DOM elements or an
<add> * entirely new DOM element.
<add> *
<add> * During html compilation, widgets are processed after {@link angular.markup markup}, but before
<add> * {@link angular.directive directives}.
<ide> *
<ide> * Following is the list of built-in angular widgets:
<ide> * | 1 |
Text | Text | add extends for derived classes | fd964de1b7df1d97b228b1196ecbc312e162ea8f | <ide><path>doc/api/fs.md
<ide> value is determined by the `options.encoding` passed to [`fs.readdir()`][] or
<ide> added: v0.5.8
<ide> -->
<ide>
<add>* Extends {EventEmitter}
<add>
<ide> A successful call to [`fs.watch()`][] method will return a new `fs.FSWatcher`
<ide> object.
<ide>
<del>All `fs.FSWatcher` objects are [`EventEmitter`][]'s that will emit a `'change'`
<del>event whenever a specific watched file is modified.
<add>All `fs.FSWatcher` objects emit a `'change'` event whenever a specific watched
<add>file is modified.
<ide>
<ide> ### Event: 'change'
<ide> <!-- YAML
<ide> Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the
<ide> added: v0.1.93
<ide> -->
<ide>
<add>* Extends: {stream.Readable}
<add>
<ide> A successful call to `fs.createReadStream()` will return a new `fs.ReadStream`
<ide> object.
<ide>
<del>All `fs.ReadStream` objects are [Readable Streams][].
<del>
<ide> ### Event: 'close'
<ide> <!-- YAML
<ide> added: v0.1.93
<ide> of 0.12, `ctime` is not "creation time", and on Unix systems, it never was.
<ide> added: v0.1.93
<ide> -->
<ide>
<del>`WriteStream` is a [Writable Stream][].
<add>* Extends {stream.Writable}
<ide>
<ide> ### Event: 'close'
<ide> <!-- YAML
<ide> changes:
<ide> * `start` {integer}
<ide> * `end` {integer} **Default:** `Infinity`
<ide> * `highWaterMark` {integer} **Default:** `64 * 1024`
<del>* Returns: {fs.ReadStream} See [Readable Streams][].
<add>* Returns: {fs.ReadStream}
<ide>
<ide> Unlike the 16 kb default `highWaterMark` for a readable stream, the stream
<ide> returned by this method has a default `highWaterMark` of 64 kb.
<ide> changes:
<ide> * `autoClose` {boolean} **Default:** `true`
<ide> * `emitClose` {boolean} **Default:** `false`
<ide> * `start` {integer}
<del>* Returns: {fs.WriteStream} See [Writable Stream][].
<add>* Returns: {fs.WriteStream}
<ide>
<ide> `options` may also include a `start` option to allow writing data at
<ide> some position past the beginning of the file, allowed values are in the
<ide> the file contents.
<ide> [`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/
<ide> [`Buffer.byteLength`]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
<ide> [`Buffer`]: buffer.html#buffer_buffer
<del>[`EventEmitter`]: events.html
<ide> [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
<ide> [`ReadDirectoryChangesW`]: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw
<ide> [`ReadStream`]: #fs_class_fs_readstream
<ide> the file contents.
<ide> [MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
<ide> [MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams
<ide> [Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
<del>[Readable Streams]: stream.html#stream_class_stream_readable
<del>[Writable Stream]: stream.html#stream_class_stream_writable
<ide> [chcp]: https://ss64.com/nt/chcp.html
<ide> [inode]: https://en.wikipedia.org/wiki/Inode
<ide> [support of file system `flags`]: #fs_file_system_flags | 1 |
Mixed | Text | fix typos and improve the documentation | 6345f31fbfb4a683f98a3d13dc73c20533d0e0b7 | <ide><path>activerecord/test/cases/connection_management_test.rb
<ide> def test_connections_closed_if_exception_and_explicitly_not_test
<ide> assert ActiveRecord::Base.connection_handler.active_connections?
<ide> end
<ide>
<del> test "proxy is polite to it's body and responds to it" do
<add> test "proxy is polite to its body and responds to it" do
<ide> body = Class.new(String) { def to_path; "/path"; end }.new
<ide> app = lambda { |_| [200, {}, body] }
<ide> response_body = ConnectionManagement.new(app).call(@env)[2]
<ide><path>activerecord/test/cases/connection_pool_test.rb
<ide> def test_checkout_behaviour
<ide> end
<ide>
<ide> # The connection pool is "fair" if threads waiting for
<del> # connections receive them the order in which they began
<add> # connections receive them in the order in which they began
<ide> # waiting. This ensures that we don't timeout one HTTP request
<ide> # even while well under capacity in a multi-threaded environment
<ide> # such as a Java servlet container.
<ide> #
<ide> # We don't need strict fairness: if two connections become
<del> # available at the same time, it's fine of two threads that were
<add> # available at the same time, it's fine if two threads that were
<ide> # waiting acquire the connections out of order.
<ide> #
<ide> # Thus this test prepares waiting threads and then trickles in
<ide><path>activesupport/lib/active_support/core_ext/module/concerning.rb
<ide> class Module
<ide> #
<ide> # == Mix-in noise exiled to its own file:
<ide> #
<del> # Once our chunk of behavior starts pushing the scroll-to-understand it's
<add> # Once our chunk of behavior starts pushing the scroll-to-understand-it
<ide> # boundary, we give in and move it to a separate file. At this size, the
<del> # overhead feels in good proportion to the size of our extraction, despite
<del> # diluting our at-a-glance sense of how things really work.
<add> # increased overhead can be a reasonable tradeoff even if it reduces our
<add> # at-a-glance perception of how things work.
<ide> #
<ide> # class Todo
<ide> # # Other todo implementation
<ide><path>guides/source/configuring.md
<ide> encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
<ide> end
<ide> ```
<ide>
<del>* `config.action_view.default_form_builder` tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`
<add>* `config.action_view.default_form_builder` tells Rails which form builder to
<add> use by default. The default is `ActionView::Helpers::FormBuilder`. If you
<add> want your form builder class to be loaded after initialization (so it's
<add> reloaded on each request in development), you can pass it as a `String`.
<ide>
<ide> * `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
<ide>
<ide> * `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`, which turns on trimming of tail spaces and newline when using `<%= -%>` or `<%= =%>`. See the [Erubis documentation](http://www.kuwata-lab.com/erubis/users-guide.06.html#topics-trimspaces) for more information.
<ide>
<del>* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true`
<add>* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to
<add> set the default behavior for `authenticity_token` in forms with `remote:
<add> true`. By default it's set to false, which means that remote forms will not
<add> include `authenticity_token`, which is helpful when you're fragment-caching
<add> the form. Remote forms get the authenticity from the `meta` tag, so embedding
<add> is unnecessary unless you support browsers without JavaScript. In such case
<add> you can either pass `authenticity_token: true` as a form option or set this
<add> config setting to `true`.
<ide>
<ide> * `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::ArticlesController` which renders this template:
<ide>
<ide> encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
<ide>
<ide> The default setting is `true`, which uses the partial at `/admin/articles/_article.erb`. Setting the value to `false` would render `/articles/_article.erb`, which is the same behavior as rendering from a non-namespaced controller such as `ArticlesController`.
<ide>
<del>* `config.action_view.raise_on_missing_translations` determines whether an error should be raised for missing translations
<add>* `config.action_view.raise_on_missing_translations` determines whether an
<add> error should be raised for missing translations.
<ide>
<ide> ### Configuring Action Mailer
<ide>
<ide> There are a few configuration options available in Active Support:
<ide> * `config.active_job.queue_name_prefix` allows you to set an optional, non-blank, queue name prefix for all jobs. By default it is blank and not used.
<ide>
<ide> The following configuration would queue the given job on the `production_high_priority` queue when run in production:
<del>
<add>
<ide> ```ruby
<ide> config.active_job.queue_name_prefix = Rails.env
<ide> ```
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
<ide>
<del>* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set - to `Rails.logger`
<add>* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set -
<add> to `Rails.logger`.
<ide>
<ide> * `active_job.set_configs` Sets up Active Job by using the settings in `config.active_job` by `send`'ing the method names as setters to `ActiveJob::Base` and passing the values through.
<ide>
<ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> A CHANGELOG entry should summarize what was changed and should end with the auth
<ide> *Your Name*
<ide> ```
<ide>
<del>Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.
<add>Your name can be added directly after the last word if there are no code
<add>examples or multiple paragraphs. Otherwise, it's best to make a new paragraph.
<ide>
<ide> ### Updating the Gemfile.lock
<ide>
<ide> Good commit message should be formatted according to the following example:
<ide> Short summary (ideally 50 characters or less)
<ide>
<ide> More detailed description, if necessary. It should be wrapped to 72
<del>characters. Try to be as descriptive as you can, even if you think that
<del>the commit content is obvious, it may not be obvious to others. You
<del>should add such description also if it's already present in bug tracker,
<del>it should not be necessary to visit a webpage to check the history.
<add>characters. Try to be as descriptive as you can; even if you think that the
<add>commit content is obvious, it may not be obvious to others. Add any description
<add>that is already present in relevant issues - it should not be necessary to visit
<add>a webpage to check the history.
<ide>
<del>Description can have multiple paragraphs and you can use code examples
<del>inside, just indent it with 4 spaces:
<add>The description section can have multiple paragraphs. Code examples can be
<add>embedded by indenting them with 4 spaces:
<ide>
<ide> class ArticlesController
<ide> def index
<ide> You can also add bullet points:
<ide> long to fit in 72 characters
<ide> ```
<ide>
<del>TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.
<add>TIP. Please squash your commits into a single commit when appropriate. This
<add>simplifies future cherry picks and also keeps the git log clean.
<ide>
<ide> ### Update Your Branch
<ide>
<ide><path>guides/source/debugging_rails_applications.md
<ide> TIP: By default, each log is created under `Rails.root/log/` and the log file is
<ide>
<ide> ### Log Levels
<ide>
<del>When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the `Rails.logger.level` method.
<del>
<del>The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`, corresponding to the log level numbers from 0 up to 5 respectively. To change the default log level, use
<add>When something is logged, it's printed into the corresponding log if the log
<add>level of the message is equal or higher than the configured log level. If you
<add>want to know the current log level, you can call the `Rails.logger.level`
<add>method.
<add>
<add>The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`,
<add>and `:unknown`, corresponding to the log level numbers from 0 up to 5,
<add>respectively. To change the default log level, use
<ide>
<ide> ```ruby
<ide> config.log_level = :warn # In any environment initializer, or
<ide><path>guides/source/getting_started.md
<ide> code while accomplishing more than many other languages and frameworks.
<ide> Experienced Rails developers also report that it makes web application
<ide> development more fun.
<ide>
<del>Rails is opinionated software. It makes the assumption that there is the "best"
<add>Rails is opinionated software. It makes the assumption that there is a "best"
<ide> way to do things, and it's designed to encourage that way - and in some cases to
<ide> discourage alternatives. If you learn "The Rails Way" you'll probably discover a
<ide> tremendous increase in productivity. If you persist in bringing old habits from
<ide><path>guides/source/i18n.md
<ide> NOTE: The default locale loading mechanism in Rails does not load locale files i
<ide> Overview of the I18n API Features
<ide> ---------------------------------
<ide>
<del>You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
<add>You should have a good understanding of using the i18n library now and know how
<add>to internationalize a basic Rails application. In the following chapters, we'll
<add>cover its features in more depth.
<ide>
<ide> These chapters will show examples using both the `I18n.translate` method as well as the [`translate` view helper method](http://api.rubyonrails.org/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate) (noting the additional feature provide by the view helper method).
<ide>
<ide><path>guides/source/layouts_and_rendering.md
<ide> One way to use partials is to treat them as the equivalent of subroutines: as a
<ide> <%= render "shared/footer" %>
<ide> ```
<ide>
<del>Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
<del>
<del>As you already could see from the previous sections of this guide, `yield` is a very powerful tool for cleaning up your layouts. Keep in mind that it's pure ruby, so you can use it almost everywhere. For example, we can use it to DRY form layout definition for several similar resources:
<add>Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain
<add>content that is shared by many pages in your application. You don't need to see
<add>the details of these sections when you're concentrating on a particular page.
<add>
<add>As seen in the previous sections of this guide, `yield` is a very powerful tool
<add>for cleaning up your layouts. Keep in mind that it's pure Ruby, so you can use
<add>it almost everywhere. For example, we can use it to DRY up form layout
<add>definitions for several similar resources:
<ide>
<ide> * `users/index.html.erb`
<ide>
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> end
<ide> The migration DSL has been expanded to support foreign key definitions. If
<ide> you've been using the Foreigner gem, you might want to consider removing it.
<ide> Note that the foreign key support of Rails is a subset of Foreigner. This means
<del>that not every Foreigner definition can be fully replaced by it's Rails
<add>that not every Foreigner definition can be fully replaced by its Rails
<ide> migration DSL counterpart.
<ide>
<ide> The migration procedure is as follows:
<ide><path>railties/CHANGELOG.md
<ide>
<ide> *Islam Wazery*
<ide>
<del>* Print `bundle install` output in `rails new` as soon as it's available
<add>* Print `bundle install` output in `rails new` as soon as it's available.
<ide>
<ide> Running `rails new` will now print the output of `bundle install` as
<ide> it is available, instead of waiting until all gems finish installing. | 11 |
Javascript | Javascript | fix jsdoc type expressions | 332e935048d161764046b43fe6599e1db2afc3b6 | <ide><path>src/Angular.js
<ide> function reverseParams(iteratorFn) {
<ide> * the number string gets longer over time, and it can also overflow, where as the nextId
<ide> * will grow much slower, it is a string, and it will never overflow.
<ide> *
<del> * @returns an unique alpha-numeric string
<add> * @returns {string} an unique alpha-numeric string
<ide> */
<ide> function nextUid() {
<ide> var index = uid.length;
<ide> function tryDecodeURIComponent(value) {
<ide>
<ide> /**
<ide> * Parses an escaped url query string into key-value pairs.
<del> * @returns Object.<(string|boolean)>
<add> * @returns {Object.<string,boolean|Array>}
<ide> */
<ide> function parseKeyValue(/**string*/keyValue) {
<ide> var obj = {}, key_value, key;
<ide> function assertNotHasOwnProperty(name, context) {
<ide> /**
<ide> * Return the value accessible from the object by path. Any undefined traversals are ignored
<ide> * @param {Object} obj starting object
<del> * @param {string} path path to traverse
<del> * @param {boolean=true} bindFnToScope
<del> * @returns value as accessible by path
<add> * @param {String} path path to traverse
<add> * @param {boolean} [bindFnToScope=true]
<add> * @returns {Object} value as accessible by path
<ide> */
<ide> //TODO(misko): this function needs to be removed
<ide> function getter(obj, path, bindFnToScope) {
<ide> function getter(obj, path, bindFnToScope) {
<ide> /**
<ide> * Return the DOM siblings between the first and last node in the given array.
<ide> * @param {Array} array like object
<del> * @returns jQlite object containing the elements
<add> * @returns {DOMElement} object containing the elements
<ide> */
<ide> function getBlockElements(nodes) {
<ide> var startNode = nodes[0],
<ide><path>src/apis.js
<ide> HashMap.prototype = {
<ide>
<ide> /**
<ide> * @param key
<del> * @returns the value for the key
<add> * @returns {Object} the value for the key
<ide> */
<ide> get: function(key) {
<ide> return this[hashKey(key)];
<ide><path>src/auto/injector.js
<ide> function annotate(fn) {
<ide> * @description
<ide> * Invoke the method and supply the method arguments from the `$injector`.
<ide> *
<del> * @param {!function} fn The function to invoke. Function parameters are injected according to the
<add> * @param {!Function} fn The function to invoke. Function parameters are injected according to the
<ide> * {@link guide/di $inject Annotation} rules.
<ide> * @param {Object=} self The `this` for the invoked method.
<ide> * @param {Object=} locals Optional object. If preset then any argument names are read from this
<ide> function annotate(fn) {
<ide> * operator and supplies all of the arguments to the constructor function as specified by the
<ide> * constructor annotation.
<ide> *
<del> * @param {function} Type Annotated constructor function.
<add> * @param {Function} Type Annotated constructor function.
<ide> * @param {Object=} locals Optional object. If preset then any argument names are read from this
<ide> * object first, before the `$injector` is consulted.
<ide> * @returns {Object} new instance of `Type`.
<ide> function annotate(fn) {
<ide> * ).toEqual(['$compile', '$rootScope']);
<ide> * ```
<ide> *
<del> * @param {function|Array.<string|Function>} fn Function for which dependent service names need to
<add> * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
<ide> * be retrieved as described above.
<ide> *
<ide> * @returns {Array.<string>} The names of the services which the function requires.
<ide><path>src/minErr.js
<ide> * should all be static strings, not variables or general expressions.
<ide> *
<ide> * @param {string} module The namespace to use for the new minErr instance.
<del> * @returns {function(string, string, ...): Error} instance
<add> * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
<ide> */
<ide>
<ide> function minErr(module) {
<ide><path>src/ng/animate.js
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * ```
<ide> *
<ide> * @param {string} name The name of the animation.
<del> * @param {function} factory The factory function that will be executed to return the animation
<add> * @param {Function} factory The factory function that will be executed to return the animation
<ide> * object.
<ide> */
<ide> this.register = function(name, factory) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * a child (if the after element is not present)
<ide> * @param {DOMElement} after the sibling element which will append the element
<ide> * after itself
<del> * @param {function=} done callback function that will be called after the element has been
<add> * @param {Function=} done callback function that will be called after the element has been
<ide> * inserted into the DOM
<ide> */
<ide> enter : function(element, parent, after, done) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * @description Removes the element from the DOM. Once complete, the done() callback will be
<ide> * fired (if provided).
<ide> * @param {DOMElement} element the element which will be removed from the DOM
<del> * @param {function=} done callback function that will be called after the element has been
<add> * @param {Function=} done callback function that will be called after the element has been
<ide> * removed from the DOM
<ide> */
<ide> leave : function(element, done) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * inserted into (if the after element is not present)
<ide> * @param {DOMElement} after the sibling element where the element will be
<ide> * positioned next to
<del> * @param {function=} done the callback function (if provided) that will be fired after the
<add> * @param {Function=} done the callback function (if provided) that will be fired after the
<ide> * element has been moved to its new position
<ide> */
<ide> move : function(element, parent, after, done) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * @param {DOMElement} element the element which will have the className value
<ide> * added to it
<ide> * @param {string} className the CSS class which will be added to the element
<del> * @param {function=} done the callback function (if provided) that will be fired after the
<add> * @param {Function=} done the callback function (if provided) that will be fired after the
<ide> * className value has been added to the element
<ide> */
<ide> addClass : function(element, className, done) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * @param {DOMElement} element the element which will have the className value
<ide> * removed from it
<ide> * @param {string} className the CSS class which will be removed from the element
<del> * @param {function=} done the callback function (if provided) that will be fired after the
<add> * @param {Function=} done the callback function (if provided) that will be fired after the
<ide> * className value has been removed from the element
<ide> */
<ide> removeClass : function(element, className, done) {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * removed from it
<ide> * @param {string} add the CSS classes which will be added to the element
<ide> * @param {string} remove the CSS class which will be removed from the element
<del> * @param {function=} done the callback function (if provided) that will be fired after the
<add> * @param {Function=} done the callback function (if provided) that will be fired after the
<ide> * CSS classes have been set on the element
<ide> */
<ide> setClass : function(element, add, remove, done) {
<ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide> * Returns current <base href>
<ide> * (always relative - without domain)
<ide> *
<del> * @returns {string=} current <base href>
<add> * @returns {string} The current base href
<ide> */
<ide> self.baseHref = function() {
<ide> var href = baseElement.attr('href');
<ide><path>src/ng/compile.js
<ide> *
<ide> *
<ide> * @param {string|DOMElement} element Element or HTML string to compile into a template function.
<del> * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
<add> * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
<ide> * @param {number} maxPriority only apply directives lower then given priority (Only effects the
<ide> * root element(s), not their children)
<del> * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
<add> * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
<ide> * (a DOM element/tree) to a scope. Where:
<ide> *
<ide> * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
<ide> * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
<ide> * names and the values are the factories.
<del> * @param {function|Array} directiveFactory An injectable directive factory function. See
<add> * @param {Function|Array} directiveFactory An injectable directive factory function. See
<ide> * {@link guide/directive} for more info.
<ide> * @returns {ng.$compileProvider} Self for chaining.
<ide> */
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * function, which is the a linking function for the node.
<ide> *
<ide> * @param {NodeList} nodeList an array of nodes or NodeList to compile
<del> * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
<add> * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
<ide> * scope argument is auto-generated to the new child of the transcluded parent scope.
<ide> * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
<ide> * the rootElement must be set the jqLite collection of the compile root. This is
<ide> * needed so that the jqLite collection items can be replaced with widgets.
<ide> * @param {number=} maxPriority Max directive priority.
<del> * @returns {?function} A composite linking function of all of the matched directives or null.
<add> * @returns {Function} A composite linking function of all of the matched directives or null.
<ide> */
<ide> function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
<ide> previousCompileContext) {
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * this needs to be pre-sorted by priority order.
<ide> * @param {Node} compileNode The raw DOM node to apply the compile functions to
<ide> * @param {Object} templateAttrs The shared attribute function
<del> * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
<add> * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
<ide> * scope argument is auto-generated to the new
<ide> * child of the transcluded parent scope.
<ide> * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * @param {Array.<Function>} postLinkFns
<ide> * @param {Object} previousCompileContext Context used for previous compilation of the current
<ide> * node
<del> * @returns linkFn
<add> * @returns {Function} linkFn
<ide> */
<ide> function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
<ide> jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * * `A': attribute
<ide> * * `C`: class
<ide> * * `M`: comment
<del> * @returns true if directive was added.
<add> * @returns {boolean} true if directive was added.
<ide> */
<ide> function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
<ide> endAttrName) {
<ide><path>src/ng/filter.js
<ide> * Register filter factory function.
<ide> *
<ide> * @param {String} name Name of the filter.
<del> * @param {function} fn The filter factory function which is injectable.
<add> * @param {Function} fn The filter factory function which is injectable.
<ide> */
<ide>
<ide>
<ide><path>src/ng/http.js
<ide> function headersGetter(headers) {
<ide> *
<ide> * @param {*} data Data to transform.
<ide> * @param {function(string=)} headers Http headers getter fn.
<del> * @param {(function|Array.<function>)} fns Function or an array of functions.
<add> * @param {(Function|Array.<Function>)} fns Function or an array of functions.
<ide> * @returns {*} Transformed data.
<ide> */
<ide> function transformData(data, headers, fns) {
<ide><path>src/ng/interval.js
<ide> function $IntervalProvider() {
<ide> * @returns {promise} A promise which will be notified on each iteration.
<ide> *
<ide> * @example
<del> <example module="time">
<del> <file name="index.html">
<del> <script>
<del> function Ctrl2($scope,$interval) {
<del> $scope.format = 'M/d/yy h:mm:ss a';
<del> $scope.blood_1 = 100;
<del> $scope.blood_2 = 120;
<del>
<del> var stop;
<del> $scope.fight = function() {
<del> // Don't start a new fight if we are already fighting
<del> if ( angular.isDefined(stop) ) return;
<del>
<del> stop = $interval(function() {
<del> if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
<del> $scope.blood_1 = $scope.blood_1 - 3;
<del> $scope.blood_2 = $scope.blood_2 - 4;
<del> } else {
<del> $scope.stopFight();
<del> }
<del> }, 100);
<del> };
<del>
<del> $scope.stopFight = function() {
<del> if (angular.isDefined(stop)) {
<del> $interval.cancel(stop);
<del> stop = undefined;
<del> }
<del> };
<del>
<del> $scope.resetFight = function() {
<del> $scope.blood_1 = 100;
<del> $scope.blood_2 = 120;
<del> }
<del>
<del> $scope.$on('$destroy', function() {
<del> // Make sure that the interval is destroyed too
<del> $scope.stopFight();
<del> });
<del> }
<del>
<del> angular.module('time', [])
<del> // Register the 'myCurrentTime' directive factory method.
<del> // We inject $interval and dateFilter service since the factory method is DI.
<del> .directive('myCurrentTime', function($interval, dateFilter) {
<del> // return the directive link function. (compile function not needed)
<del> return function(scope, element, attrs) {
<del> var format, // date format
<del> stopTime; // so that we can cancel the time updates
<del>
<del> // used to update the UI
<del> function updateTime() {
<del> element.text(dateFilter(new Date(), format));
<del> }
<del>
<del> // watch the expression, and update the UI on change.
<del> scope.$watch(attrs.myCurrentTime, function(value) {
<del> format = value;
<del> updateTime();
<del> });
<del>
<del> stopTime = $interval(updateTime, 1000);
<del>
<del> // listen on DOM destroy (removal) event, and cancel the next UI update
<del> // to prevent updating time ofter the DOM element was removed.
<del> element.bind('$destroy', function() {
<del> $interval.cancel(stopTime);
<del> });
<del> }
<del> });
<del> </script>
<del>
<del> <div>
<del> <div ng-controller="Ctrl2">
<del> Date format: <input ng-model="format"> <hr/>
<del> Current time is: <span my-current-time="format"></span>
<del> <hr/>
<del> Blood 1 : <font color='red'>{{blood_1}}</font>
<del> Blood 2 : <font color='red'>{{blood_2}}</font>
<del> <button type="button" data-ng-click="fight()">Fight</button>
<del> <button type="button" data-ng-click="stopFight()">StopFight</button>
<del> <button type="button" data-ng-click="resetFight()">resetFight</button>
<del> </div>
<del> </div>
<del>
<del> </file>
<del> </example>
<add> * <example module="time">
<add> * <file name="index.html">
<add> * <script>
<add> * function Ctrl2($scope,$interval) {
<add> * $scope.format = 'M/d/yy h:mm:ss a';
<add> * $scope.blood_1 = 100;
<add> * $scope.blood_2 = 120;
<add> *
<add> * var stop;
<add> * $scope.fight = function() {
<add> * // Don't start a new fight if we are already fighting
<add> * if ( angular.isDefined(stop) ) return;
<add> *
<add> * stop = $interval(function() {
<add> * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
<add> * $scope.blood_1 = $scope.blood_1 - 3;
<add> * $scope.blood_2 = $scope.blood_2 - 4;
<add> * } else {
<add> * $scope.stopFight();
<add> * }
<add> * }, 100);
<add> * };
<add> *
<add> * $scope.stopFight = function() {
<add> * if (angular.isDefined(stop)) {
<add> * $interval.cancel(stop);
<add> * stop = undefined;
<add> * }
<add> * };
<add> *
<add> * $scope.resetFight = function() {
<add> * $scope.blood_1 = 100;
<add> * $scope.blood_2 = 120;
<add> * }
<add> *
<add> * $scope.$on('$destroy', function() {
<add> * // Make sure that the interval is destroyed too
<add> * $scope.stopFight();
<add> * });
<add> * }
<add> *
<add> * angular.module('time', [])
<add> * // Register the 'myCurrentTime' directive factory method.
<add> * // We inject $interval and dateFilter service since the factory method is DI.
<add> * .directive('myCurrentTime', function($interval, dateFilter) {
<add> * // return the directive link function. (compile function not needed)
<add> * return function(scope, element, attrs) {
<add> * var format, // date format
<add> * stopTime; // so that we can cancel the time updates
<add> *
<add> * // used to update the UI
<add> * function updateTime() {
<add> * element.text(dateFilter(new Date(), format));
<add> * }
<add> *
<add> * // watch the expression, and update the UI on change.
<add> * scope.$watch(attrs.myCurrentTime, function(value) {
<add> * format = value;
<add> * updateTime();
<add> * });
<add> *
<add> * stopTime = $interval(updateTime, 1000);
<add> *
<add> * // listen on DOM destroy (removal) event, and cancel the next UI update
<add> * // to prevent updating time ofter the DOM element was removed.
<add> * element.bind('$destroy', function() {
<add> * $interval.cancel(stopTime);
<add> * });
<add> * }
<add> * });
<add> * </script>
<add> *
<add> * <div>
<add> * <div ng-controller="Ctrl2">
<add> * Date format: <input ng-model="format"> <hr/>
<add> * Current time is: <span my-current-time="format"></span>
<add> * <hr/>
<add> * Blood 1 : <font color='red'>{{blood_1}}</font>
<add> * Blood 2 : <font color='red'>{{blood_2}}</font>
<add> * <button type="button" data-ng-click="fight()">Fight</button>
<add> * <button type="button" data-ng-click="stopFight()">StopFight</button>
<add> * <button type="button" data-ng-click="resetFight()">resetFight</button>
<add> * </div>
<add> * </div>
<add> *
<add> * </file>
<add> * </example>
<ide> */
<ide> function interval(fn, delay, count, invokeApply) {
<ide> var setInterval = $window.setInterval,
<ide><path>src/ng/q.js
<ide> function $QProvider() {
<ide> /**
<ide> * Constructs a promise manager.
<ide> *
<del> * @param {function(function)} nextTick Function for executing functions in the next turn.
<add> * @param {function(Function)} nextTick Function for executing functions in the next turn.
<ide> * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
<ide> * debugging purposes.
<ide> * @returns {object} Promise manager.
<ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * ```
<ide> *
<ide> *
<del> * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The
<add> * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
<ide> * expression value should evaluate to an object or an array which is observed on each
<ide> * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
<ide> * collection will trigger a call to the `listener`.
<ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> * removed from it
<ide> * @param {string} add the CSS classes which will be added to the element
<ide> * @param {string} remove the CSS class which will be removed from the element
<del> * @param {function=} done the callback function (if provided) that will be fired after the
<add> * @param {Function=} done the callback function (if provided) that will be fired after the
<ide> * CSS classes have been set on the element
<ide> */
<ide> setClass : function(element, add, remove, doneCallback) {
<ide> angular.module('ngAnimate', ['ng'])
<ide> * @function
<ide> *
<ide> * @param {boolean=} value If provided then set the animation on or off.
<del> * @param {jQuery/jqLite element=} element If provided then the element will be used to represent the enable/disable operation
<add> * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation
<ide> * @return {boolean} Current animation state.
<ide> *
<ide> * @description
<ide><path>src/ngRoute/route.js
<ide> function $RouteProvider(){
<ide>
<ide>
<ide> /**
<del> * @returns the current active route, by matching it against the URL
<add> * @returns {Object} the current active route, by matching it against the URL
<ide> */
<ide> function parseRoute() {
<ide> // Match a route
<ide> function $RouteProvider(){
<ide> }
<ide>
<ide> /**
<del> * @returns interpolation of the redirect path with the parameters
<add> * @returns {string} interpolation of the redirect path with the parameters
<ide> */
<ide> function interpolate(string, params) {
<ide> var result = [];
<ide><path>src/ngSanitize/sanitize.js
<ide> function decodeEntities(value) {
<ide> * resulting string can be safely inserted into attribute or
<ide> * element text.
<ide> * @param value
<del> * @returns escaped text
<add> * @returns {string} escaped text
<ide> */
<ide> function encodeEntities(value) {
<ide> return value. | 15 |
Javascript | Javascript | set the tabindex on the input element | 408070e9138a8ee4cc2b30b8a16583058072e4d0 | <ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> style,
<ide> attributes,
<ide> dataset,
<del> tabIndex: this.tabIndex,
<add> tabIndex: -1,
<ide> on: {mousewheel: this.didMouseWheel}
<ide> },
<ide> $.div(
<ide> class TextEditorComponent {
<ide> scrollWidth: this.getScrollWidth(),
<ide> decorationsToRender: this.decorationsToRender,
<ide> cursorsBlinkedOff: this.cursorsBlinkedOff,
<del> hiddenInputPosition: this.hiddenInputPosition
<add> hiddenInputPosition: this.hiddenInputPosition,
<add> tabIndex: this.tabIndex
<ide> })
<ide> }
<ide>
<ide> class CursorsAndInputComponent {
<ide> const {
<ide> lineHeight, hiddenInputPosition, didBlurHiddenInput, didFocusHiddenInput,
<ide> didPaste, didTextInput, didKeydown, didKeyup, didKeypress,
<del> didCompositionStart, didCompositionUpdate, didCompositionEnd
<add> didCompositionStart, didCompositionUpdate, didCompositionEnd, tabIndex
<ide> } = this.props
<ide>
<ide> let top, left
<ide> class CursorsAndInputComponent {
<ide> compositionupdate: didCompositionUpdate,
<ide> compositionend: didCompositionEnd
<ide> },
<del> tabIndex: this.tabIndex,
<add> tabIndex: tabIndex,
<ide> style: {
<ide> position: 'absolute',
<ide> width: '1px', | 1 |
Javascript | Javascript | remove redundant condition | 180a997da5fffa619a468eec2f391cdd75aa06dc | <ide><path>src/ajax/jsonp.js
<ide> jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
<ide> rjsonp.test( data );
<ide>
<ide> // Handle iff the expected data type is "jsonp" or we have a parameter to set
<del> if ( s.dataTypes[ 0 ] === "jsonp" || hasCallback &&
<del> ( replaceInUrl || replaceInData ) ) {
<add> if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
<ide>
<ide> // Get callback name, remembering preexisting value associated with it
<ide> callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? | 1 |
Javascript | Javascript | fix coding style in make.js | 855b96990c7c3d9db73cb4cc60686461637ac1be | <ide><path>make.js
<ide> var DEFINES = {
<ide> target.all = function() {
<ide> // Don't do anything by default
<ide> echo('Please specify a target. Available targets:');
<del> for (var t in target)
<del> if (t !== 'all') echo(' ' + t);
<add> for (var t in target) {
<add> if (t !== 'all') {
<add> echo(' ' + t);
<add> }
<add> }
<ide> };
<ide>
<ide>
<ide> target.web = function() {
<ide> echo();
<ide> echo('### Creating web site');
<ide>
<del> if (test('-d', GH_PAGES_DIR))
<add> if (test('-d', GH_PAGES_DIR)) {
<ide> rm('-rf', GH_PAGES_DIR);
<add> }
<ide>
<ide> mkdir('-p', GH_PAGES_DIR + '/web');
<ide> mkdir('-p', GH_PAGES_DIR + '/web/images');
<ide> target.locale = function() {
<ide> for (var i = 0; i < subfolders.length; i++) {
<ide> var locale = subfolders[i];
<ide> var path = LOCALE_SRC_DIR + locale;
<del> if (!test('-d', path))
<add> if (!test('-d', path)) {
<ide> continue;
<del>
<add> }
<ide> if (!/^[a-z][a-z](-[A-Z][A-Z])?$/.test(locale)) {
<ide> echo('Skipping invalid locale: ' + locale);
<ide> continue;
<ide> target.bundle = function(args) {
<ide> BUNDLE_BUILD: bundleBuild}));
<ide> }
<ide>
<del> if (!test('-d', BUILD_DIR))
<add> if (!test('-d', BUILD_DIR)) {
<ide> mkdir(BUILD_DIR);
<add> }
<ide>
<ide> var SHARED_SRC_FILES = [
<ide> 'shared/util.js',
<ide> target.firefox = function() {
<ide>
<ide> // Remove '.DS_Store' and other hidden files
<ide> find(FIREFOX_BUILD_DIR).forEach(function(file) {
<del> if (file.match(/^\./))
<add> if (file.match(/^\./)) {
<ide> rm('-f', file);
<add> }
<ide> });
<ide>
<ide> // Update the build version number
<ide> target.mozcentral = function() {
<ide>
<ide> // Remove '.DS_Store' and other hidden files
<ide> find(MOZCENTRAL_DIR).forEach(function(file) {
<del> if (file.match(/^\./))
<add> if (file.match(/^\./)) {
<ide> rm('-f', file);
<add> }
<ide> });
<ide>
<ide> // Remove excluded files
<ide> target.chromium = function() {
<ide> var public_chrome_files = file_list.reduce(function(war, file) {
<ide> // Exclude directories (naive: Exclude paths without dot)
<ide> if (file.indexOf('.') !== -1) {
<del> // Only add a comma after the first file
<del> if (war)
<del> war += ',\n';
<del> war += JSON.stringify('content/' + file);
<add> // Only add a comma after the first file
<add> if (war) {
<add> war += ',\n';
<add> }
<add> war += JSON.stringify('content/' + file);
<ide> }
<ide> return war;
<ide> }, '');
<ide> target.baseline = function() {
<ide> exit(1);
<ide> }
<ide>
<del> if (!test('-d', BUILD_DIR))
<add> if (!test('-d', BUILD_DIR)) {
<ide> mkdir(BUILD_DIR);
<add> }
<ide>
<ide> var BASELINE_DIR = BUILD_DIR + 'baseline';
<ide> if (test('-d', BASELINE_DIR)) {
<ide> target.mozcentralbaseline = function() {
<ide>
<ide> var BASELINE_DIR = BUILD_DIR + 'baseline';
<ide> var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
<del> if (test('-d', MOZCENTRAL_BASELINE_DIR))
<add> if (test('-d', MOZCENTRAL_BASELINE_DIR)) {
<ide> rm('-rf', MOZCENTRAL_BASELINE_DIR);
<add> }
<ide>
<ide> cd(BASELINE_DIR);
<del> if (test('-d', 'build'))
<add> if (test('-d', 'build')) {
<ide> rm('-rf', 'build');
<add> }
<ide> exec('node make mozcentral');
<ide>
<ide> cd(ROOT_DIR);
<ide> target.mozcentraldiff = function() {
<ide> echo('### Creating mozcentral diff');
<ide>
<ide> var MOZCENTRAL_DIFF = BUILD_DIR + 'mozcentral.diff';
<del> if (test('-f', MOZCENTRAL_DIFF))
<add> if (test('-f', MOZCENTRAL_DIFF)) {
<ide> rm(MOZCENTRAL_DIFF);
<add> }
<ide>
<ide> var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
<ide> if (!test('-d', MOZCENTRAL_BASELINE_DIR)) { | 1 |
Ruby | Ruby | remove dead code | 7da98d0a590d74027e6595da8a85ea3b4195c51c | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def constraint_args(constraint, request)
<ide> class Mapping #:nodoc:
<ide> IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
<ide> ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
<del> WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
<ide>
<ide> attr_reader :scope, :options, :requirements, :conditions, :defaults
<ide> attr_reader :to, :default_controller, :default_action | 1 |
Javascript | Javascript | fix serviceworker call on http | 769cb49c309354429bd5161485c547fd3c7d9a40 | <ide><path>lib/router/router.js
<ide> if (typeof window !== 'undefined' && typeof navigator.serviceWorker !== 'undefin
<ide> registration.unregister()
<ide> })
<ide> })
<add> .catch(() => {})
<ide> }
<ide>
<ide> export default class Router { | 1 |
PHP | PHP | fix present count | 505957ad634e8d107507755075c8d41805c28098 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function getPresentCount($attributes)
<ide>
<ide> foreach ($attributes as $key)
<ide> {
<del> if ( ! is_null(array_get($this->data, $key, null)) || ! is_null(array_get($this->files, $key, null)))
<add> if (array_get($this->data, $key) || array_get($this->files, $key))
<ide> {
<ide> $count++;
<ide> } | 1 |
Go | Go | avoid recursive rlock | bd4f66c8f1f6ad4a2f228a957f293bc157e13d9c | <ide><path>daemon/cluster/tasks.go
<ide> import (
<ide>
<ide> // GetTasks returns a list of tasks matching the filter options.
<ide> func (c *Cluster) GetTasks(options apitypes.TaskListOptions) ([]types.Task, error) {
<del> c.mu.RLock()
<del> defer c.mu.RUnlock()
<add> var r *swarmapi.ListTasksResponse
<ide>
<del> state := c.currentNodeState()
<del> if !state.IsActiveManager() {
<del> return nil, c.errNoManager(state)
<del> }
<del>
<del> filterTransform := func(filter filters.Args) error {
<del> if filter.Include("service") {
<del> serviceFilters := filter.Get("service")
<del> for _, serviceFilter := range serviceFilters {
<del> service, err := c.GetService(serviceFilter, false)
<del> if err != nil {
<del> return err
<add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
<add> filterTransform := func(filter filters.Args) error {
<add> if filter.Include("service") {
<add> serviceFilters := filter.Get("service")
<add> for _, serviceFilter := range serviceFilters {
<add> service, err := getService(ctx, state.controlClient, serviceFilter, false)
<add> if err != nil {
<add> return err
<add> }
<add> filter.Del("service", serviceFilter)
<add> filter.Add("service", service.ID)
<ide> }
<del> filter.Del("service", serviceFilter)
<del> filter.Add("service", service.ID)
<ide> }
<del> }
<del> if filter.Include("node") {
<del> nodeFilters := filter.Get("node")
<del> for _, nodeFilter := range nodeFilters {
<del> node, err := c.GetNode(nodeFilter)
<del> if err != nil {
<del> return err
<add> if filter.Include("node") {
<add> nodeFilters := filter.Get("node")
<add> for _, nodeFilter := range nodeFilters {
<add> node, err := getNode(ctx, state.controlClient, nodeFilter)
<add> if err != nil {
<add> return err
<add> }
<add> filter.Del("node", nodeFilter)
<add> filter.Add("node", node.ID)
<ide> }
<del> filter.Del("node", nodeFilter)
<del> filter.Add("node", node.ID)
<ide> }
<add> if !filter.Include("runtime") {
<add> // default to only showing container tasks
<add> filter.Add("runtime", "container")
<add> filter.Add("runtime", "")
<add> }
<add> return nil
<ide> }
<del> if !filter.Include("runtime") {
<del> // default to only showing container tasks
<del> filter.Add("runtime", "container")
<del> filter.Add("runtime", "")
<del> }
<del> return nil
<del> }
<ide>
<del> filters, err := newListTasksFilters(options.Filters, filterTransform)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> ctx, cancel := c.getRequestContext()
<del> defer cancel()
<add> filters, err := newListTasksFilters(options.Filters, filterTransform)
<add> if err != nil {
<add> return err
<add> }
<ide>
<del> r, err := state.controlClient.ListTasks(
<del> ctx,
<del> &swarmapi.ListTasksRequest{Filters: filters})
<del> if err != nil {
<add> r, err = state.controlClient.ListTasks(
<add> ctx,
<add> &swarmapi.ListTasksRequest{Filters: filters})
<add> return err
<add> }); err != nil {
<ide> return nil, err
<ide> }
<ide> | 1 |
Text | Text | add other values of the target attribute | d2c2fa0ce61046b5aae2f7f9566dc7dbd661dc2e | <ide><path>guide/english/html/attributes/links/index.md
<ide> You use an anchor element/tag `<a>` to define your link, which also needs a dest
<ide> ```html
<ide> <a href="url">Link Text</a>
<ide> ```
<add>
<add>The target attribute can be used to tell the browser where to open the link. If you'd like your link to open in a new tab, you can use the `target` attribute along with the `_blank` value inside your opening `<a>` tag.
<add>
<ide> Here's a snippet that makes the phrase 'The freeCodeCamp Guide' a link:
<add>
<ide> ```html
<ide> <a href="https://guide.freecodecamp.org">The freeCodeCamp Guide</a>
<ide> ```
<add>
<ide> The link ends up looking like this: [The freeCodeCamp Guide](https://guide.freecodecamp.org)
<ide>
<del>### Links in a New Tab
<del>If you'd like your link to open in a new tab, you'll use the `target` attribute along with the `"_blank"`
<del>value inside your opening `<a>` tag. That looks like this:
<add>### `target` Attribute
<add>
<add>**Opening a page in a new tab**
<add>
<add>If you'd like your link to open in a new tab, you'll use the `target` attribute along with the `_blank`
<add>value inside your opening `<a>` tag:
<add>
<ide> ```html
<ide> <a href="url" target="_blank">Link Text</a>
<ide> ```
<del>Here is another example, using the official freeCodeCamp Guide as the `href=""` destination, and "The freeCodeCamp Guide" as the link text:
<add>Another example, using the official freeCodeCamp Guide as the `href=""` destination, and "The freeCodeCamp Guide" as the link text:
<add>
<ide> ```html
<ide> <!-- target="_blank" makes the link open in a new tab. -->
<ide> <a href="https://guide.freecodecamp.org" target="_blank">The freeCodeCamp Guide</a>
<ide> ```
<add>
<add>Other values of the target attribute include:
<add>- `_self` to open the linked document in the same frame
<add>- `_parent` to open it in the parent frame
<add>- `_top` opens the linked document in the full body of the window
<add>- `_targetframe` opens the linked document in a named targetframe
<add>
<ide> ### Links on the Same Page
<ide> When you need to guide users to a specific part of your webpage, let's assume the very bottom, you first need to create an html element with an `#id` that you want direct your user to - in this case the `<footer>` at the bottom of the webpage. For example:
<ide> ```html | 1 |
Javascript | Javascript | fix morphblendmesh setanimationfps() | 0ffea7b8f2a80eff8e8c4d90880b8c75e01a40f5 | <ide><path>src/extras/objects/MorphBlendMesh.js
<ide> THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fp
<ide>
<ide> var animation = {
<ide>
<del> startFrame: start,
<del> endFrame: end,
<add> start: start,
<add> end: end,
<ide>
<ide> length: end - start + 1,
<ide>
<ide> THREE.MorphBlendMesh.prototype.update = function ( delta ) {
<ide>
<ide> }
<ide>
<del> var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
<add> var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
<ide> var weight = animation.weight;
<ide>
<ide> if ( keyframe !== animation.currentFrame ) { | 1 |
PHP | PHP | append to helper instead | 222e5c62c7a013bd4cb0c749bfea69f0988943bd | <ide><path>src/Illuminate/Support/Facades/Config.php
<ide> */
<ide> class Config extends Facade {
<ide>
<del> /**
<del> * Assign high numeric IDs to a config item to force appending.
<del> *
<del> * @param array $array
<del> * @return array
<del> */
<del> public static function append(array $array)
<del> {
<del> $start = 9999;
<del>
<del> foreach ($array as $key => $value)
<del> {
<del> if (is_numeric($key))
<del> {
<del> $start++;
<del>
<del> $array[$start] = array_pull($array, $key);
<del> }
<del> }
<del>
<del> return $array;
<del> }
<del>
<ide> /**
<ide> * Get the registered name of the component.
<ide> *
<ide><path>src/Illuminate/Support/helpers.php
<ide> function app_path($path = '')
<ide> }
<ide> }
<ide>
<add>if ( ! function_exists('append_config'))
<add>{
<add> /**
<add> * Assign high numeric IDs to a config item to force appending.
<add> *
<add> * @param array $array
<add> * @return array
<add> */
<add> function append_config(array $array)
<add> {
<add> $start = 9999;
<add>
<add> foreach ($array as $key => $value)
<add> {
<add> if (is_numeric($key))
<add> {
<add> $start++;
<add>
<add> $array[$start] = array_pull($array, $key);
<add> }
<add> }
<add>
<add> return $array;
<add>
<add>}
<add>
<ide> if ( ! function_exists('array_add'))
<ide> {
<ide> /** | 2 |
PHP | PHP | add insert into ... select support | 9b15e82aa904828af7ae9a608328ff84a4e8bcda | <ide><path>lib/Cake/Model/Datasource/Database/Expression/ValuesExpression.php
<ide> */
<ide> namespace Cake\Model\Datasource\Database\Expression;
<ide>
<add>use Cake\Error;
<ide> use Cake\Model\Datasource\Database\Expression;
<ide> use Cake\Model\Datasource\Database\Query;
<ide> use \Countable;
<ide> class ValuesExpression implements Expression {
<ide>
<ide> protected $_values = [];
<ide> protected $_columns = [];
<add> protected $_hasQuery = false;
<ide>
<ide> public function __construct($columns) {
<ide> $this->_columns = $columns;
<ide> public function __construct($columns) {
<ide> /**
<ide> * Add a row of data to be inserted.
<ide> *
<del> * @param array $data Array of data to append into the insert.
<add> * @param array|Query $data Array of data to append into the insert, or
<add> * a query for doing INSERT INTO .. SELECT style commands
<ide> * @return void
<add> * @throws Cake\Error\Exception When mixing array + Query data types.
<ide> */
<ide> public function add($data) {
<add> if (
<add> count($this->_values) &&
<add> ($data instanceof Query || ($this->_hasQuery && is_array($data)))
<add> ) {
<add> throw new Error\Exception(
<add> __d('cake_dev', 'You cannot mix subqueries and array data in inserts.')
<add> );
<add> }
<add> if ($data instanceof Query) {
<add> $this->_hasQuery = true;
<add> }
<ide> $this->_values[] = $data;
<ide> }
<ide>
<ide> public function bindings() {
<ide> $i = 0;
<ide> $defaults = array_fill_keys($this->_columns, null);
<ide> foreach ($this->_values as $row) {
<del> $row = array_merge($defaults, $row);
<del> foreach ($row as $column => $value) {
<del> $bindings[] = [
<del> // TODO add types.
<del> 'type' => null,
<del> 'placeholder' => $i,
<del> 'value' => $value
<del> ];
<del> $i++;
<add> if (is_array($row)) {
<add> $row = array_merge($defaults, $row);
<add> foreach ($row as $column => $value) {
<add> $bindings[] = [
<add> // TODO add types.
<add> 'type' => null,
<add> 'placeholder' => $i,
<add> 'value' => $value
<add> ];
<add> $i++;
<add> }
<ide> }
<ide> }
<ide> return $bindings;
<ide> public function bindings() {
<ide> * @return string
<ide> */
<ide> public function sql() {
<add> if (empty($this->_values)) {
<add> return '';
<add> }
<add> if ($this->_hasQuery) {
<add> return ' ' . $this->_values[0]->sql();
<add> }
<ide> $placeholders = [];
<ide> $numColumns = count($this->_columns);
<add>
<ide> foreach ($this->_values as $row) {
<del> if (is_array($row)) {
<del> $placeholders[] = implode(', ', array_fill(0, $numColumns, '?'));
<del> }
<add> $placeholders[] = implode(', ', array_fill(0, $numColumns, '?'));
<add> }
<add> return sprintf(' VALUES (%s)', implode('), (', $placeholders));
<add> }
<add>
<add>/**
<add> * Traverse the values expression.
<add> *
<add> * This method will also traverse any queries that are to be used in the INSERT
<add> * values.
<add> *
<add> * @param callable $visitor The visitor to traverse the expression with.
<add> * @return void
<add> */
<add> public function traverse(callable $visitor) {
<add> if (!$this->_hasQuery) {
<add> return;
<ide> }
<del> return sprintf('(%s)', implode('), (', $placeholders));
<add> $this->_values[0]->traverse($visitor);
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Model/Datasource/Database/Query.php
<ide> class Query implements Expression, IteratorAggregate {
<ide> protected $_templates = [
<ide> 'delete' => 'DELETE',
<ide> 'update' => 'UPDATE %s',
<del> 'values' => ' VALUES %s',
<ide> 'where' => ' WHERE %s',
<ide> 'group' => ' GROUP BY %s ',
<ide> 'having' => ' HAVING %s ',
<ide> protected function _buildInsertPart($parts) {
<ide> * @return string SQL fragment.
<ide> */
<ide> protected function _buildValuesPart($parts) {
<del> $columns = $this->_parts['insert'][1];
<del> $defaults = array_fill_keys($columns, null);
<del> $placeholders = [];
<del> $values = [];
<del> foreach ($parts as $part) {
<del> if (is_array($part)) {
<del> $values[] = array_values($part + $defaults);
<del> $placeholders[] = implode(', ', array_fill(0, count($part), '?'));
<del> }
<del> }
<del> return sprintf(
<del> ' VALUES (%s)',
<del> implode('), (', $placeholders)
<del> );
<add> return implode('', $parts);
<ide> }
<ide>
<ide> /**
<ide> protected function _bindParams($statement) {
<ide> $expression->traverse($visitor);
<ide> }
<ide> if ($expression instanceof ValuesExpression) {
<add> $expression->traverse($binder);
<ide> $visitor($expression);
<ide> }
<ide> };
<ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php
<ide> public function testUpdateWithExpression() {
<ide> * You cannot call values() before insert() it causes all sorts of pain.
<ide> *
<ide> * @expectedException Cake\Error\Exception
<add> * @return void
<ide> */
<ide> public function testInsertValuesBeforeInsertFailure() {
<ide> $query = new Query($this->connection);
<ide> public function testInsertSimple() {
<ide> $result = $query->execute();
<ide> $this->assertCount(1, $result, '1 row should be inserted');
<ide>
<del> $result = (new Query($this->connection))->select('*')
<del> ->from('articles')
<del> ->execute();
<del> $this->assertCount(1, $result);
<del>
<ide> $expected = [
<del> 'id' => 1,
<del> 'author_id' => null,
<del> 'title' => 'mark',
<del> 'body' => 'test insert'
<add> [
<add> 'id' => 1,
<add> 'author_id' => null,
<add> 'title' => 'mark',
<add> 'body' => 'test insert'
<add> ]
<ide> ];
<del> $this->assertEquals($expected, $result->fetchAll('assoc')[0]);
<add> $this->assertTable('articles', 1, $expected);
<ide> }
<ide>
<ide> /**
<ide> public function testInsertSparseRow() {
<ide> $result = $query->execute();
<ide> $this->assertCount(1, $result, '1 row should be inserted');
<ide>
<del> $result = (new Query($this->connection))->select('*')
<del> ->from('articles')
<del> ->execute();
<del> $this->assertCount(1, $result);
<del>
<ide> $expected = [
<del> 'id' => null,
<del> 'author_id' => null,
<del> 'title' => 'mark',
<del> 'body' => 'test insert'
<add> [
<add> 'id' => null,
<add> 'author_id' => null,
<add> 'title' => 'mark',
<add> 'body' => 'test insert'
<add> ]
<ide> ];
<del> $this->assertEquals($expected, $result->fetchAll('assoc')[0]);
<add> $this->assertTable('articles', 1, $expected);
<ide> }
<ide>
<ide> /**
<del> * Test inserting multiple rows.
<add> * Test inserting multiple rows with sparse data.
<ide> *
<ide> * @return void
<ide> */
<del> public function testInsertMultipleRows() {
<add> public function testInsertMultipleRowsSparse() {
<ide> $this->_createAuthorsAndArticles();
<ide>
<ide> $query = new Query($this->connection);
<ide> $query->insert('articles', ['id', 'title', 'body'])
<ide> ->values([
<ide> 'id' => 1,
<del> 'title' => 'mark',
<ide> 'body' => 'test insert'
<ide> ])
<ide> ->values([
<ide> 'id' => 2,
<ide> 'title' => 'jose',
<del> 'body' => 'test insert'
<ide> ]);
<ide> $result = $query->sql(false);
<ide> $this->assertEquals(
<ide> public function testInsertMultipleRows() {
<ide> );
<ide>
<ide> $result = $query->execute();
<del> $this->assertCount(2, $result, '2 row should be inserted');
<del> }
<add> $this->assertCount(2, $result, '2 rows should be inserted');
<ide>
<del> public function testInsertMultipleRowsSparse() {
<del> $this->markTestIncomplete();
<add> $expected = [
<add> [
<add> 'id' => 1,
<add> 'author_id' => null,
<add> 'title' => null,
<add> 'body' => 'test insert'
<add> ],
<add> [
<add> 'id' => 2,
<add> 'author_id' => null,
<add> 'title' => 'jose',
<add> 'body' => null,
<add> ],
<add> ];
<add> $this->assertTable('articles', 2, $expected);
<ide> }
<ide>
<add>/**
<add> * Test that INSERT INTO ... SELECT works.
<add> *
<add> * @return void
<add> */
<ide> public function testInsertFromSelect() {
<del> $this->markTestIncomplete();
<add> $this->_insertTwoRecords();
<add> $select = (new Query($this->connection))->select('name, "some text", 99')
<add> ->from('authors')
<add> ->where(['id' => 1]);
<add>
<add> $query = new Query($this->connection);
<add> $query->insert('articles', ['title', 'body', 'author_id'])
<add> ->values($select);
<add>
<add> $result = $query->sql(false);
<add> $this->assertContains('INSERT INTO articles (title, body, author_id) SELECT', $result);
<add> $this->assertContains('SELECT name, "some text", 99 FROM authors', $result);
<add> $result = $query->execute();
<add>
<add> $this->assertCount(1, $result);
<add> $result = (new Query($this->connection))->select('*')
<add> ->from('articles')
<add> ->where(['author_id' => 99])
<add> ->execute();
<add> $this->assertCount(1, $result);
<add> $expected = [
<add> 'id' => null,
<add> 'title' => 'Chuck Norris',
<add> 'body' => 'some text',
<add> 'author_id' => 99,
<add> ];
<add> $this->assertEquals($expected, $result->fetch('assoc'));
<add> }
<add>
<add>/**
<add> * Assertion for comparing a table's contents with what is in it.
<add> *
<add> * @param string $table
<add> * @param int $count
<add> * @param array $rows
<add> * @return void
<add> */
<add> protected function assertTable($table, $count, $rows) {
<add> $result = (new Query($this->connection))->select('*')
<add> ->from($table)
<add> ->execute();
<add> $this->assertCount($count, $result, 'Row count is incorrect');
<add> $this->assertEquals($rows, $result->fetchAll('assoc'));
<ide> }
<ide>
<ide> } | 3 |
Text | Text | add watson to collaborators | 3dfce5cdad554d2eabd001a4a917efa143739711 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Vse Mozhet Byt** <vsemozhetbyt@gmail.com> (he/him)
<ide> * [watilde](https://github.com/watilde) -
<ide> **Daijiro Wachi** <daijiro.wachi@gmail.com> (he/him)
<add>* [watson](https://github.com/watson) -
<add>**Thomas Watson** <w@tson.dk>
<ide> * [whitlockjc](https://github.com/whitlockjc) -
<ide> **Jeremy Whitlock** <jwhitlock@apache.org>
<ide> * [XadillaX](https://github.com/XadillaX) - | 1 |
Ruby | Ruby | allow on_os blocks | 1f8ebf5d20f81aea87b95710a2841134dbfa4a32 | <ide><path>Library/Homebrew/extend/os/linux/resource.rb
<add># frozen_string_literal: true
<add>
<add>class Resource
<add> undef on_linux
<add>
<add> def on_linux(&_block)
<add> yield
<add> end
<add>end
<ide><path>Library/Homebrew/extend/os/mac/resource.rb
<add># frozen_string_literal: true
<add>
<add>class Resource
<add> undef on_macos
<add>
<add> def on_macos(&_block)
<add> yield
<add> end
<add>end
<ide><path>Library/Homebrew/extend/os/resource.rb
<add># frozen_string_literal: true
<add>
<add>if OS.mac?
<add> require "extend/os/mac/resource"
<add>elsif OS.linux?
<add> require "extend/os/linux/resource"
<add>end
<ide><path>Library/Homebrew/formula.rb
<ide> def uses_from_macos(dep, bounds = {})
<ide> specs.each { |spec| spec.uses_from_macos(dep, bounds) }
<ide> end
<ide>
<del> # Block executed only executed on macOS. No-op on Linux.
<add> # Block only executed on macOS. No-op on Linux.
<ide> # <pre>on_macos do
<ide> # depends_on "mac_only_dep"
<ide> # end</pre>
<ide> def on_macos(&_block); end
<ide>
<del> # Block executed only executed on Linux. No-op on macOS.
<add> # Block only executed on Linux. No-op on macOS.
<ide> # <pre>on_linux do
<ide> # depends_on "linux_only_dep"
<ide> # end</pre>
<ide><path>Library/Homebrew/resource.rb
<ide> def patch(strip = :p1, src = nil, &block)
<ide> patches << p
<ide> end
<ide>
<add> # Block only executed on macOS. No-op on Linux.
<add> # <pre>on_macos do
<add> # url "mac_only_url"
<add> # end</pre>
<add> def on_macos(&_block); end
<add>
<add> # Block only executed on Linux. No-op on macOS.
<add> # <pre>on_linux do
<add> # url "linux_only_url"
<add> # end</pre>
<add> def on_linux(&_block); end
<add>
<ide> protected
<ide>
<ide> def mktemp(prefix)
<ide> def to_s
<ide> "<#{self.class}: resource=#{resource} staging=#{staging}>"
<ide> end
<ide> end
<add>
<add>require "extend/os/resource"
<ide><path>Library/Homebrew/test/os/linux/formula_spec.rb
<ide> expect(f.patchlist.second.url).to eq("patch_linux")
<ide> end
<ide> end
<add>
<add> describe "#on_linux" do
<add> it "uses on_linux within a resource block" do
<add> f = formula do
<add> homepage "https://brew.sh"
<add>
<add> url "https://brew.sh/test-0.1.tbz"
<add> sha256 TEST_SHA256
<add>
<add> resource "test_resource" do
<add> on_linux do
<add> url "on_linux"
<add> end
<add> end
<add> end
<add> expect(f.resources.length).to eq(1)
<add> expect(f.resources.first.url).to eq("on_linux")
<add> end
<add> end
<ide> end
<ide><path>Library/Homebrew/test/os/mac/formula_spec.rb
<ide> expect(f.patchlist.second.url).to eq("patch_macos")
<ide> end
<ide> end
<add>
<add> describe "#on_macos" do
<add> it "uses on_macos within a resource block" do
<add> f = formula do
<add> homepage "https://brew.sh"
<add>
<add> url "https://brew.sh/test-0.1.tbz"
<add> sha256 TEST_SHA256
<add>
<add> resource "test_resource" do
<add> on_macos do
<add> url "resource_macos"
<add> end
<add> end
<add> end
<add> expect(f.resources.length).to eq(1)
<add> expect(f.resources.first.url).to eq("resource_macos")
<add> end
<add> end
<ide> end | 7 |
Java | Java | add missing license headers | 9315ec4176017d6ee44f38ec9947c337eff4f4bf | <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.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>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import java.util.*;
<ide><path>src/main/java/io/reactivex/internal/util/ArrayListSupplier.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>
<ide> package io.reactivex.internal.util;
<ide>
<ide> import java.util.*;
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatDelayErrorTest.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>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<ide> import static org.junit.Assert.*; | 3 |
Text | Text | add note about promise polyfill | 7cab0a05934512c90b9dfc7ea6d95935125b4077 | <ide><path>README.md
<ide> Check out webpack's quick [**Get Started**](https://webpack.js.org/get-started/)
<ide> ### Browser Compatibility
<ide>
<ide> Webpack supports all browsers that are [ES5-compliant](http://kangax.github.io/compat-table/es5/) (IE8 and below are not supported).
<add>webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to load a polyfill before using these expressions.
<ide>
<ide> <h2 align="center">Concepts</h2>
<ide> | 1 |
Python | Python | fix regression in pr . | b89ed2f338a5810ee785c3fd20c0fe057d3d4612 | <ide><path>celery/canvas.py
<ide> from celery.local import try_import
<ide> from celery.result import GroupResult, allow_join_result
<ide> from celery.utils import abstract
<add>from celery.utils.collections import ChainMap
<ide> from celery.utils.functional import _regen
<ide> from celery.utils.functional import chunks as _chunks
<ide> from celery.utils.functional import (is_list, maybe_list, regen,
<ide> def register_type(cls, name=None):
<ide> def _inner(subclass):
<ide> cls.TYPES[name or subclass.__name__] = subclass
<ide> return subclass
<add>
<ide> return _inner
<ide>
<ide> @classmethod
<ide> def _merge(self, args=None, kwargs=None, options=None, force=False):
<ide> options = options if options else {}
<ide> if self.immutable and not force:
<ide> return (self.args, self.kwargs,
<del> dict(self.options, **options) if options else self.options)
<add> dict(self.options,
<add> **options) if options else self.options)
<ide> return (tuple(args) + tuple(self.args) if args else self.args,
<ide> dict(self.kwargs, **kwargs) if kwargs else self.kwargs,
<ide> dict(self.options, **options) if options else self.options)
<ide> def clone(self, args=None, kwargs=None, **opts):
<ide> app=self._app)
<ide> signature._type = self._type
<ide> return signature
<add>
<ide> partial = clone
<ide>
<ide> def freeze(self, _id=None, group_id=None, chord=None,
<ide> def freeze(self, _id=None, group_id=None, chord=None,
<ide> # pylint: disable=too-many-function-args
<ide> # Borks on this, as it's a property.
<ide> return self.AsyncResult(tid)
<add>
<ide> _freeze = freeze
<ide>
<ide> def replace(self, args=None, kwargs=None, options=None):
<ide> def election(self):
<ide>
<ide> with app.producer_or_acquire(None) as producer:
<ide> props = type.backend.on_task_call(producer, tid)
<del> app.control.election(tid, 'task', self.clone(task_id=tid, **props),
<add> app.control.election(tid, 'task',
<add> self.clone(task_id=tid, **props),
<ide> connection=producer.connection)
<ide> return type.AsyncResult(tid)
<ide>
<ide> def _apply_async(self):
<ide> return self.type.apply_async
<ide> except KeyError:
<ide> return _partial(self.app.send_task, self['task'])
<add>
<ide> id = getitem_property('options.task_id', 'Task UUID')
<ide> parent_id = getitem_property('options.parent_id', 'Task parent UUID.')
<ide> root_id = getitem_property('options.root_id', 'Task root UUID.')
<ide> def _apply_async(self):
<ide> 'immutable', 'Flag set if no longer accepts new arguments')
<ide>
<ide>
<add>def _prepare_chain_from_options(options, tasks, use_link):
<add> # When we publish groups we reuse the same options dictionary for all of
<add> # the tasks in the group. See:
<add> # https://github.com/celery/celery/blob/fb37cb0b8/celery/canvas.py#L1022.
<add> # Issue #5354 reported that the following type of canvases
<add> # causes a Celery worker to hang:
<add> # group(
<add> # add.s(1, 1),
<add> # add.s(1, 1)
<add> # ) | tsum.s() | add.s(1) | group(add.s(1), add.s(1))
<add> # The resolution of #5354 in PR #5681 was to only set the `chain` key
<add> # in the options dictionary if it is not present.
<add> # Otherwise we extend the existing list of tasks in the chain with the new
<add> # tasks: options['chain'].extend(chain_).
<add> # Before PR #5681 we overrode the `chain` key in each iteration
<add> # of the loop which applies all the tasks in the group:
<add> # options['chain'] = tasks if not use_link else None
<add> # This caused Celery to execute chains correctly in most cases since
<add> # in each iteration the `chain` key would reset itself to a new value
<add> # and the side effect of mutating the key did not propagate
<add> # to the next task in the group.
<add> # Since we now mutated the `chain` key, a *list* which is passed
<add> # by *reference*, the next task in the group will extend the list
<add> # of tasks in the chain instead of setting a new one from the chain_
<add> # variable above.
<add> # This causes Celery to execute a chain, even though there might not be
<add> # one to begin with. Alternatively, it causes Celery to execute more tasks
<add> # that were previously present in the previous task in the group.
<add> # The solution is to be careful and never mutate the options dictionary
<add> # to begin with.
<add> # Here is an example of a canvas which triggers this issue:
<add> # add.s(5, 6) | group((add.s(1) | add.s(2), add.s(3))).
<add> # The expected result is [14, 14]. However, when we extend the `chain`
<add> # key the `add.s(3)` task erroneously has `add.s(2)` in its chain since
<add> # it was previously applied to `add.s(1)`.
<add> # Without being careful not to mutate the options dictionary, the result
<add> # in this case is [16, 14].
<add> # To avoid deep-copying the entire options dictionary every single time we
<add> # run a chain we use a ChainMap and ensure that we never mutate
<add> # the original `chain` key, hence we use list_a + list_b to create a new
<add> # list.
<add> if use_link:
<add> return ChainMap({'chain': None}, options)
<add> elif 'chain' not in options:
<add> return ChainMap({'chain': tasks}, options)
<add> elif tasks is not None:
<add> # chain option may already be set, resulting in
<add> # "multiple values for keyword argument 'chain'" error.
<add> # Issue #3379.
<add> # If a chain already exists, we need to extend it with the next
<add> # tasks in the chain.
<add> # Issue #5354.
<add> # WARNING: Be careful not to mutate `options['chain']`.
<add> return ChainMap({'chain': options['chain'] + tasks},
<add> options)
<add>
<add>
<ide> @Signature.register_type(name='chain')
<ide> @python_2_unicode_compatible
<ide> class _chain(Signature):
<ide> def run(self, args=None, kwargs=None, group_id=None, chord=None,
<ide> if link:
<ide> tasks[0].extend_list_option('link', link)
<ide> first_task = tasks.pop()
<del> # chain option may already be set, resulting in
<del> # "multiple values for keyword argument 'chain'" error.
<del> # Issue #3379.
<del> chain_ = tasks if not use_link else None
<del> if 'chain' not in options:
<del> options['chain'] = chain_
<del> elif chain_ is not None:
<del> # If a chain already exists, we need to extend it with the next
<del> # tasks in the chain.
<del> # Issue #5354.
<del> options['chain'].extend(chain_)
<add> options = _prepare_chain_from_options(options, tasks, use_link)
<ide>
<ide> first_task.apply_async(**options)
<ide> return results[0]
<ide> def freeze(self, _id=None, group_id=None, chord=None,
<ide> else:
<ide> self.tasks = new_tasks
<ide> return self.app.GroupResult(gid, results)
<add>
<ide> _freeze = freeze
<ide>
<ide> def _freeze_unroll(self, new_tasks, group_id, chord, root_id, parent_id): | 1 |
Javascript | Javascript | improve test coverage and fix minor issues found | f5b4a0fa3c933ac443b66cfa3e0198f4f342a410 | <ide><path>src/core/core.animations.js
<ide> export default class Animations {
<ide> animatedProps.set(prop, Object.assign({}, animDefaults, cfg));
<ide> } else if (prop === key) {
<ide> // Single property targetting config wins over multi-targetting.
<del> animatedProps.set(prop, Object.assign({}, animatedProps.get(prop), cfg));
<add> // eslint-disable-next-line no-unused-vars
<add> const {properties, ...inherited} = animatedProps.get(prop);
<add> animatedProps.set(prop, Object.assign({}, inherited, cfg));
<ide> }
<ide> });
<ide> });
<ide><path>src/core/core.registry.js
<ide> export class Registry {
<ide> return this._get(id, this.scales, 'scale');
<ide> }
<ide>
<add> /**
<add> * @param {...typeof DatasetController} args
<add> */
<add> removeControllers(...args) {
<add> this._each('unregister', args, this.controllers);
<add> }
<add>
<add> /**
<add> * @param {...typeof Element} args
<add> */
<add> removeElements(...args) {
<add> this._each('unregister', args, this.elements);
<add> }
<add>
<add> /**
<add> * @param {...any} args
<add> */
<add> removePlugins(...args) {
<add> this._each('unregister', args, this.plugins);
<add> }
<add>
<add> /**
<add> * @param {...typeof Scale} args
<add> */
<add> removeScales(...args) {
<add> this._each('unregister', args, this.scales);
<add> }
<add>
<ide> /**
<ide> * @private
<ide> */
<ide> _each(method, args, typedRegistry) {
<ide> const me = this;
<ide> [...args].forEach(arg => {
<ide> const reg = typedRegistry || me._getRegistryForType(arg);
<del> if (reg.isForType(arg) || (reg === me.plugins && arg.id)) {
<add> if (typedRegistry || reg.isForType(arg) || (reg === me.plugins && arg.id)) {
<ide> me._exec(method, reg, arg);
<ide> } else {
<ide> // Handle loopable args
<ide><path>src/core/core.typedRegistry.js
<ide> export default class TypedRegistry {
<ide> return scope;
<ide> }
<ide>
<add> if (Object.keys(defaults.get(scope)).length) {
<add> throw new Error('Can not register "' + id + '", because "defaults.' + scope + '" would collide with existing defaults');
<add> }
<add>
<ide> items[id] = item;
<ide> registerDefaults(item, scope, parentScope);
<ide>
<ide><path>test/specs/core.animation.tests.js
<add>describe('Chart.Animation', function() {
<add> it('should animate boolean', function() {
<add> const target = {prop: false};
<add> const anim = new Chart.Animation({duration: 1000}, target, 'prop', true);
<add> expect(anim.active()).toBeTrue();
<add>
<add> anim.tick(anim._start + 500);
<add> expect(anim.active()).toBeTrue();
<add> expect(target.prop).toBeFalse();
<add>
<add> anim.tick(anim._start + 501);
<add> expect(anim.active()).toBeTrue();
<add> expect(target.prop).toBeTrue();
<add>
<add> anim.tick(anim._start - 100);
<add> expect(anim.active()).toBeTrue();
<add> expect(target.prop).toBeFalse();
<add>
<add> anim.tick(anim._start + 1000);
<add> expect(anim.active()).toBeFalse();
<add> expect(target.prop).toBeTrue();
<add> });
<add>
<add> describe('color', function() {
<add> it('should fall back to transparent', function() {
<add> const target = {};
<add> const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'red');
<add> anim._from = undefined;
<add> anim.tick(anim._start + 500);
<add> expect(target.color).toEqual('#FF000080');
<add>
<add> anim._from = 'blue';
<add> anim._to = undefined;
<add> anim.tick(anim._start + 500);
<add> expect(target.color).toEqual('#0000FF80');
<add> });
<add>
<add> it('should not try to mix invalid color', function() {
<add> const target = {color: 'blue'};
<add> const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'invalid');
<add> anim.tick(anim._start + 500);
<add> expect(target.color).toEqual('invalid');
<add> });
<add> });
<add>
<add> it('should loop', function() {
<add> const target = {value: 0};
<add> const anim = new Chart.Animation({duration: 100, loop: true}, target, 'value', 10);
<add> anim.tick(anim._start + 50);
<add> expect(target.value).toEqual(5);
<add> anim.tick(anim._start + 100);
<add> expect(target.value).toEqual(10);
<add> anim.tick(anim._start + 150);
<add> expect(target.value).toEqual(5);
<add> anim.tick(anim._start + 400);
<add> expect(target.value).toEqual(0);
<add> });
<add>
<add> it('should update', function() {
<add> const target = {testColor: 'transparent'};
<add> const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red');
<add>
<add> anim.tick(anim._start + 50);
<add> expect(target.testColor).toEqual('#FF000080');
<add>
<add> anim.update({duration: 500}, 'blue', Date.now());
<add> anim.tick(anim._start + 250);
<add> expect(target.testColor).toEqual('#4000BFBF');
<add>
<add> anim.tick(anim._start + 500);
<add> expect(target.testColor).toEqual('blue');
<add> });
<add>
<add> it('should not update when finished', function() {
<add> const target = {testColor: 'transparent'};
<add> const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red');
<add>
<add> anim.tick(anim._start + 100);
<add> expect(target.testColor).toEqual('red');
<add> expect(anim.active()).toBeFalse();
<add>
<add> anim.update({duration: 500}, 'blue', Date.now());
<add> expect(anim._duration).toEqual(100);
<add> expect(anim._to).toEqual('red');
<add> });
<add>});
<ide><path>test/specs/core.animations.tests.js
<add>describe('Chart.animations', function() {
<add> it('should override property collection with property', function() {
<add> const chart = {};
<add> const anims = new Chart.Animations(chart, {
<add> collection1: {
<add> properties: ['property1', 'property2'],
<add> duration: 1000
<add> },
<add> property2: {
<add> duration: 2000
<add> }
<add> });
<add> expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
<add> expect(anims._properties.get('property2')).toEqual({duration: 2000});
<add> });
<add>
<add> it('should ignore duplicate definitions from collections', function() {
<add> const chart = {};
<add> const anims = new Chart.Animations(chart, {
<add> collection1: {
<add> properties: ['property1'],
<add> duration: 1000
<add> },
<add> collection2: {
<add> properties: ['property1', 'property2'],
<add> duration: 2000
<add> }
<add> });
<add> expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
<add> expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000}));
<add> });
<add>
<add> it('should not animate undefined options key', function() {
<add> const chart = {};
<add> const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
<add> const target = {
<add> value: 1,
<add> options: {
<add> option: 2
<add> }
<add> };
<add> expect(anims.update(target, {
<add> options: undefined
<add> })).toBeUndefined();
<add> });
<add>});
<ide><path>test/specs/core.animator.tests.js
<ide> describe('Chart.animator', function() {
<ide> },
<ide> });
<ide> });
<add>
<add> it('should not fail when adding no items', function() {
<add> const chart = {};
<add> Chart.animator.add(chart, undefined);
<add> Chart.animator.add(chart, []);
<add> Chart.animator.start(chart);
<add> expect(Chart.animator.running(chart)).toBeFalse();
<add> });
<ide> });
<ide><path>test/specs/core.element.tests.js
<add>describe('Chart.element', function() {
<add> describe('getProps', function() {
<add> it('should return requested properties', function() {
<add> const elem = new Chart.Element();
<add> elem.x = 10;
<add> elem.y = 1.5;
<add>
<add> expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
<add> expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
<add>
<add> elem.$animations = {x: {active: true, _to: 20}};
<add> expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
<add> expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 20, y: 1.5}));
<add> });
<add> });
<add>});
<ide><path>test/specs/core.registry.tests.js
<ide> describe('Chart.registry', function() {
<ide> expect(Chart.defaults.elements.myElement).not.toBeDefined();
<ide> });
<ide>
<del> it('should handle a classig plugin', function() {
<add> it('should handle a classic plugin', function() {
<ide> const CustomPlugin = {
<ide> id: 'customPlugin',
<ide> defaults: {
<ide> describe('Chart.registry', function() {
<ide> Chart.register(FaultyPlugin);
<ide> }).toThrow(new Error('class does not have id: class FaultyPlugin {}'));
<ide> });
<add>
<add> it('should not fail when unregistering an object that is not registered', function() {
<add> expect(function() {
<add> Chart.unregister({id: 'foo'});
<add> }).not.toThrow();
<add> });
<add>
<add> describe('Should allow registering explicitly', function() {
<add> class customExtension {}
<add> customExtension.id = 'custom';
<add> customExtension.defaults = {
<add> prop: true
<add> };
<add>
<add> it('as controller', function() {
<add> Chart.registry.addControllers(customExtension);
<add>
<add> expect(Chart.registry.getController('custom')).toEqual(customExtension);
<add> expect(Chart.defaults.custom).toEqual(customExtension.defaults);
<add>
<add> Chart.registry.removeControllers(customExtension);
<add>
<add> expect(function() {
<add> Chart.registry.getController('custom');
<add> }).toThrow(new Error('"custom" is not a registered controller.'));
<add> expect(Chart.defaults.custom).not.toBeDefined();
<add> });
<add>
<add> it('as scale', function() {
<add> Chart.registry.addScales(customExtension);
<add>
<add> expect(Chart.registry.getScale('custom')).toEqual(customExtension);
<add> expect(Chart.defaults.scales.custom).toEqual(customExtension.defaults);
<add>
<add> Chart.registry.removeScales(customExtension);
<add>
<add> expect(function() {
<add> Chart.registry.getScale('custom');
<add> }).toThrow(new Error('"custom" is not a registered scale.'));
<add> expect(Chart.defaults.scales.custom).not.toBeDefined();
<add> });
<add>
<add> it('as element', function() {
<add> Chart.registry.addElements(customExtension);
<add>
<add> expect(Chart.registry.getElement('custom')).toEqual(customExtension);
<add> expect(Chart.defaults.elements.custom).toEqual(customExtension.defaults);
<add>
<add> Chart.registry.removeElements(customExtension);
<add>
<add> expect(function() {
<add> Chart.registry.getElement('custom');
<add> }).toThrow(new Error('"custom" is not a registered element.'));
<add> expect(Chart.defaults.elements.custom).not.toBeDefined();
<add> });
<add>
<add> it('as plugin', function() {
<add> Chart.registry.addPlugins(customExtension);
<add>
<add> expect(Chart.registry.getPlugin('custom')).toEqual(customExtension);
<add> expect(Chart.defaults.plugins.custom).toEqual(customExtension.defaults);
<add>
<add> Chart.registry.removePlugins(customExtension);
<add>
<add> expect(function() {
<add> Chart.registry.getPlugin('custom');
<add> }).toThrow(new Error('"custom" is not a registered plugin.'));
<add> expect(Chart.defaults.plugins.custom).not.toBeDefined();
<add> });
<add> });
<add>
<add> it('should fire before/after callbacks', function() {
<add> let beforeRegisterCount = 0;
<add> let afterRegisterCount = 0;
<add> let beforeUnregisterCount = 0;
<add> let afterUnregisterCount = 0;
<add> class custom {}
<add> custom.id = 'custom';
<add> custom.beforeRegister = () => beforeRegisterCount++;
<add> custom.afterRegister = () => afterRegisterCount++;
<add> custom.beforeUnregister = () => beforeUnregisterCount++;
<add> custom.afterUnregister = () => afterUnregisterCount++;
<add>
<add> Chart.registry.addControllers(custom);
<add> expect(beforeRegisterCount).withContext('beforeRegister').toBe(1);
<add> expect(afterRegisterCount).withContext('afterRegister').toBe(1);
<add> Chart.registry.removeControllers(custom);
<add> expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(1);
<add> expect(afterUnregisterCount).withContext('afterUnregister').toBe(1);
<add>
<add> Chart.registry.addScales(custom);
<add> expect(beforeRegisterCount).withContext('beforeRegister').toBe(2);
<add> expect(afterRegisterCount).withContext('afterRegister').toBe(2);
<add> Chart.registry.removeScales(custom);
<add> expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(2);
<add> expect(afterUnregisterCount).withContext('afterUnregister').toBe(2);
<add>
<add> Chart.registry.addElements(custom);
<add> expect(beforeRegisterCount).withContext('beforeRegister').toBe(3);
<add> expect(afterRegisterCount).withContext('afterRegister').toBe(3);
<add> Chart.registry.removeElements(custom);
<add> expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(3);
<add> expect(afterUnregisterCount).withContext('afterUnregister').toBe(3);
<add>
<add> Chart.register(custom);
<add> expect(beforeRegisterCount).withContext('beforeRegister').toBe(4);
<add> expect(afterRegisterCount).withContext('afterRegister').toBe(4);
<add> Chart.unregister(custom);
<add> expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(4);
<add> expect(afterUnregisterCount).withContext('afterUnregister').toBe(4);
<add> });
<add>
<add> it('should not register anything that would collide with existing defaults', function() {
<add> class testController extends Chart.DatasetController {}
<add> testController.id = 'events';
<add> expect(function() {
<add> Chart.register(testController);
<add> }).toThrow(new Error('Can not register "events", because "defaults.events" would collide with existing defaults'));
<add> });
<add>
<add> describe('should handle multiple items', function() {
<add> class test1 extends Chart.DatasetController {}
<add> test1.id = 'test1';
<add> class test2 extends Chart.Scale {}
<add> test2.id = 'test2';
<add>
<add> it('separately', function() {
<add> Chart.register(test1, test2);
<add> expect(Chart.registry.getController('test1')).toEqual(test1);
<add> expect(Chart.registry.getScale('test2')).toEqual(test2);
<add> Chart.unregister(test1, test2);
<add> expect(function() {
<add> Chart.registry.getController('test1');
<add> }).toThrow();
<add> expect(function() {
<add> Chart.registry.getScale('test2');
<add> }).toThrow();
<add> });
<add>
<add> it('as array', function() {
<add> Chart.register([test1, test2]);
<add> expect(Chart.registry.getController('test1')).toEqual(test1);
<add> expect(Chart.registry.getScale('test2')).toEqual(test2);
<add> Chart.unregister([test1, test2]);
<add> expect(function() {
<add> Chart.registry.getController('test1');
<add> }).toThrow();
<add> expect(function() {
<add> Chart.registry.getScale('test2');
<add> }).toThrow();
<add> });
<add>
<add> it('as object', function() {
<add> Chart.register({test1, test2});
<add> expect(Chart.registry.getController('test1')).toEqual(test1);
<add> expect(Chart.registry.getScale('test2')).toEqual(test2);
<add> Chart.unregister({test1, test2});
<add> expect(function() {
<add> Chart.registry.getController('test1');
<add> }).toThrow();
<add> expect(function() {
<add> Chart.registry.getScale('test2');
<add> }).toThrow();
<add> });
<add> });
<ide> }); | 8 |
Java | Java | add missing license headers | 421f98e5a189dc60b4bc6f35523c78cb7731d345 | <ide><path>src/main/java/io/reactivex/observers/LambdaConsumerIntrospection.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>
<ide> package io.reactivex.observers;
<ide>
<ide> import io.reactivex.annotations.Experimental;
<ide><path>src/test/java/io/reactivex/internal/observers/CallbackCompletableObserverTest.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>
<ide> package io.reactivex.internal.observers;
<ide>
<ide> import io.reactivex.internal.functions.Functions;
<ide><path>src/test/java/io/reactivex/internal/observers/ConsumerSingleObserverTest.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>
<ide> package io.reactivex.internal.observers;
<ide>
<ide> import io.reactivex.internal.functions.Functions;
<ide><path>src/test/java/io/reactivex/internal/observers/EmptyCompletableObserverTest.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>
<ide> package io.reactivex.internal.observers;
<ide>
<ide> import org.junit.Test; | 4 |
Javascript | Javascript | update current route upon $route instantiation | 308598795af75c33a966ecb3124f4a640d72458d | <ide><path>src/ngRoute/route.js
<ide> function $RouteProvider(){
<ide> }
<ide> };
<ide>
<del> updateRoute();
<ide> $rootScope.$on('$locationChangeSuccess', updateRoute);
<ide>
<ide> return $route;
<ide><path>test/ngRoute/routeSpec.js
<ide> describe('$route', function() {
<ide> var onChangeSpy = jasmine.createSpy('onChange');
<ide>
<ide> $rootScope.$on('$routeChangeStart', onChangeSpy);
<del> expect($route.current).not.toBeUndefined();
<add> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/unknownRoute');
<ide> describe('$route', function() {
<ide>
<ide> // init
<ide> $rootScope.$on('$routeChangeStart', onChangeSpy);
<del> expect($route.current).not.toBeUndefined();
<add> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide>
<ide> // match otherwise route
<ide> $location.path('/unknownRoute');
<ide> $rootScope.$digest();
<ide>
<del> expect(currentRoute).not.toBeUndefined();
<add> expect(currentRoute).toBeUndefined();
<ide> expect(nextRoute.templateUrl).toBe('404.html');
<ide> expect($route.current.templateUrl).toBe('404.html');
<ide> expect(onChangeSpy).toHaveBeenCalled();
<ide> describe('$route', function() {
<ide> var onChangeSpy = jasmine.createSpy('onChange');
<ide>
<ide> $rootScope.$on('$routeChangeStart', onChangeSpy);
<del> expect($route.current).not.toBeUndefined();
<add> expect($route.current).toBeUndefined();
<ide> expect(onChangeSpy).not.toHaveBeenCalled();
<ide>
<ide> $location.path('/'); | 2 |
Python | Python | improve test_long_str and add documentation | 235d957a427bc2f18642475a9c65063cf0580d6c | <ide><path>numpy/lib/tests/test_format.py
<ide> def test_roundtrip():
<ide> yield assert_array_equal, arr, arr2
<ide>
<ide> def test_long_str():
<del> long_str_arr = np.ones(1, dtype=np.dtype((str, format.BUFFER_SIZE+1)))
<add> # check items larger than internal buffer size, gh-4027
<add> long_str_arr = np.ones(1, dtype=np.dtype((str, format.BUFFER_SIZE + 1)))
<ide> long_str_arr2 = roundtrip(long_str_arr)
<add> assert_array_equal(long_str_arr, long_str_arr2)
<ide>
<ide> @dec.slow
<ide> def test_memmap_roundtrip(): | 1 |
Javascript | Javascript | reduce memory retention when streaming small files | e3a47025ac0c8e89b73b91b137bb70f6b2f3d73a | <ide><path>lib/internal/fs/streams.js
<ide> const util = require('util');
<ide> const kMinPoolSpace = 128;
<ide>
<ide> let pool;
<add>// It can happen that we expect to read a large chunk of data, and reserve
<add>// a large chunk of the pool accordingly, but the read() call only filled
<add>// a portion of it. If a concurrently executing read() then uses the same pool,
<add>// the "reserved" portion cannot be used, so we allow it to be re-used as a
<add>// new pool later.
<add>const poolFragments = [];
<ide>
<ide> function allocNewPool(poolSize) {
<del> pool = Buffer.allocUnsafe(poolSize);
<add> if (poolFragments.length > 0)
<add> pool = poolFragments.pop();
<add> else
<add> pool = Buffer.allocUnsafe(poolSize);
<ide> pool.used = 0;
<ide> }
<ide>
<ide> ReadStream.prototype._read = function(n) {
<ide> this.emit('error', er);
<ide> } else {
<ide> let b = null;
<add> // Now that we know how much data we have actually read, re-wind the
<add> // 'used' field if we can, and otherwise allow the remainder of our
<add> // reservation to be used as a new pool later.
<add> if (start + toRead === thisPool.used && thisPool === pool)
<add> thisPool.used += bytesRead - toRead;
<add> else if (toRead - bytesRead > kMinPoolSpace)
<add> poolFragments.push(thisPool.slice(start + bytesRead, start + toRead));
<add>
<ide> if (bytesRead > 0) {
<ide> this.bytesRead += bytesRead;
<ide> b = thisPool.slice(start, start + bytesRead);
<ide><path>test/parallel/test-fs-read-stream-concurrent-reads.js
<add>'use strict';
<add>const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>
<add>// Test that concurrent file read streams don’t interfere with each other’s
<add>// contents, and that the chunks generated by the reads only retain a
<add>// 'reasonable' amount of memory.
<add>
<add>// Refs: https://github.com/nodejs/node/issues/21967
<add>
<add>const filename = fixtures.path('loop.js'); // Some small non-homogeneous file.
<add>const content = fs.readFileSync(filename);
<add>
<add>const N = 1000;
<add>let started = 0;
<add>let done = 0;
<add>
<add>const arrayBuffers = new Set();
<add>
<add>function startRead() {
<add> ++started;
<add> const chunks = [];
<add> fs.createReadStream(filename)
<add> .on('data', (chunk) => {
<add> chunks.push(chunk);
<add> arrayBuffers.add(chunk.buffer);
<add> if (started < N)
<add> startRead();
<add> })
<add> .on('end', common.mustCall(() => {
<add> assert.deepStrictEqual(Buffer.concat(chunks), content);
<add> if (++done === N) {
<add> const retainedMemory =
<add> [...arrayBuffers].map((ab) => ab.byteLength).reduce((a, b) => a + b);
<add> assert(retainedMemory / (N * content.length) <= 3,
<add> `Retaining ${retainedMemory} bytes in ABs for ${N} ` +
<add> `chunks of size ${content.length}`);
<add> }
<add> }));
<add>}
<add>
<add>// Don’t start the reads all at once – that way we would have to allocate
<add>// a large amount of memory upfront.
<add>for (let i = 0; i < 4; ++i)
<add> startRead(); | 2 |
Text | Text | add opensuse command line to pre-requisites | 4314e0b9b51b719cc86ae1b0f70e8b306ad8ff8f | <ide><path>README.md
<ide> Prerequisites
<ide> - **Windows**: [Visual Studio](http://www.visualstudio.com/downloads/download-visual-studio-vs#d-express-windows-8)
<ide> - **Ubuntu**: `sudo apt-get install build-essential`
<ide> - **Fedora**: `sudo yum groupinstall "Development Tools"`
<add> - **OpenSUSE**: `sudo zypper install --type pattern devel_basis`
<ide>
<del>**Note**: If you are new to Node.js or Express framework,
<add>:heavy_exclamation_mark: **Note**: If you are new to Node.js or Express framework,
<ide> I highly recommend watching [Node.js and Express 101](http://www.youtube.com/watch?v=BN0JlMZCtNU) screencast that teaches Node and Express from scratch.
<ide>
<ide> | 1 |
PHP | PHP | remove useless methods and make in_array typehint | 93ae9b92a721792927f553c47a95ece2e6e9896b | <ide><path>src/Utility/Text.php
<ide> public static function truncate($text, $length = 100, array $options = [])
<ide> preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
<ide> foreach ($tags as $tag) {
<ide> $contentLength = 0;
<del> if (!in_array($tag[2], static::$_defaultHtmlNoCount)) {
<add> if (!in_array($tag[2], static::$_defaultHtmlNoCount, true)) {
<ide> $contentLength = self::_strlen($tag[3], $options);
<ide> }
<ide>
<ide> public static function slug($string, $options = [])
<ide>
<ide> return $string;
<ide> }
<del>
<del> /**
<del> * Get default html tags not counted for truncate.
<del> *
<del> * @return array Html tags.
<del> */
<del> public static function getHtmlNoCount()
<del> {
<del> return static::$_defaultHtmlNoCount;
<del> }
<del>
<del> /**
<del> * Set html tags not counted for truncate.
<del> *
<del> * @param array $htmlNoCount New html tags not counted for truncate.
<del> * @return void
<del> */
<del> public static function setHtmlNoCount($htmlNoCount)
<del> {
<del> static::$_defaultHtmlNoCount = $htmlNoCount;
<del> }
<ide> } | 1 |
Javascript | Javascript | continue normalizing fixtures use | 9a5c3cf185c6e9c4fb9264cf8e61a74a5d697ff9 | <ide><path>test/async-hooks/test-graph.tls-write.js
<ide> if (!common.hasIPv6)
<ide>
<ide> const initHooks = require('./init-hooks');
<ide> const verifyGraph = require('./verify-graph');
<del>const fs = require('fs');
<ide> const tls = require('tls');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> const hooks = initHooks();
<ide> hooks.enable();
<ide> hooks.enable();
<ide> //
<ide> const server = tls
<ide> .createServer({
<del> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')),
<del> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'))
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> })
<ide> .on('listening', common.mustCall(onlistening))
<ide> .on('secureConnection', common.mustCall(onsecureConnection))
<ide><path>test/async-hooks/test-tlswrap.js
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const assert = require('assert');
<del>const fs = require('fs');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide> const tls = require('tls');
<ide>
<ide> const tick = require('./tick');
<ide> hooks.enable();
<ide> //
<ide> const server = tls
<ide> .createServer({
<del> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')),
<del> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'))
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> })
<ide> .on('listening', common.mustCall(onlistening))
<ide> .on('secureConnection', common.mustCall(onsecureConnection))
<ide><path>test/async-hooks/test-writewrap.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const initHooks = require('./init-hooks');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide> const { checkInvocations } = require('./hook-checks');
<ide> const tls = require('tls');
<ide>
<ide> hooks.enable();
<ide> //
<ide> const server = tls
<ide> .createServer({
<del> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`),
<del> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`)
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> })
<ide> .on('listening', common.mustCall(onlistening))
<ide> .on('secureConnection', common.mustCall(onsecureConnection))
<ide><path>test/doctool/test-doctool-html.js
<ide> try {
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide> const processIncludes = require('../../tools/doc/preprocess.js');
<ide> const html = require('../../tools/doc/html.js');
<ide>
<ide> const html = require('../../tools/doc/html.js');
<ide> // have an html parser.
<ide> const testData = [
<ide> {
<del> file: path.join(common.fixturesDir, 'sample_document.md'),
<add> file: fixtures.path('sample_document.md'),
<ide> html: '<ol><li>fish</li><li><p>fish</p></li><li><p>Redfish</p></li>' +
<ide> '<li>Bluefish</li></ol>'
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'order_of_end_tags_5873.md'),
<add> file: fixtures.path('order_of_end_tags_5873.md'),
<ide> html: '<h3>ClassMethod: Buffer.from(array) <span> ' +
<ide> '<a class="mark" href="#foo_class_method_buffer_from_array" ' +
<ide> 'id="foo_class_method_buffer_from_array">#</a> </span> </h3><div' +
<ide> const testData = [
<ide> '</ul></div>'
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'doc_with_yaml.md'),
<add> file: fixtures.path('doc_with_yaml.md'),
<ide> html: '<h1>Sample Markdown with YAML info' +
<ide> '<span><a class="mark" href="#foo_sample_markdown_with_yaml_info" ' +
<ide> ' id="foo_sample_markdown_with_yaml_info">#</a></span></h1>' +
<ide> const testData = [
<ide> '</p>'
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'doc_with_includes.md'),
<add> file: fixtures.path('doc_with_includes.md'),
<ide> html: '<!-- [start-include:doc_inc_1.md] -->' +
<ide> '<p>Look <a href="doc_inc_2.html#doc_inc_2_foobar">here</a>!</p>' +
<ide> '<!-- [end-include:doc_inc_1.md] -->' +
<ide> const testData = [
<ide> '<!-- [end-include:doc_inc_2.md] -->'
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'sample_document.md'),
<add> file: fixtures.path('sample_document.md'),
<ide> html: '<ol><li>fish</li><li><p>fish</p></li><li><p>Redfish</p></li>' +
<ide> '<li>Bluefish</li></ol>',
<ide> analyticsId: 'UA-67020396-1'
<ide><path>test/doctool/test-doctool-json.js
<ide> try {
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide> const json = require('../../tools/doc/json.js');
<ide>
<ide> // Outputs valid json with the expected fields when given simple markdown
<ide> const json = require('../../tools/doc/json.js');
<ide> // The json property is some json which will be generated by the doctool.
<ide> const testData = [
<ide> {
<del> file: path.join(common.fixturesDir, 'sample_document.md'),
<add> file: fixtures.path('sample_document.md'),
<ide> json: {
<ide> source: 'foo',
<ide> modules: [{
<ide> const testData = [
<ide> }
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'order_of_end_tags_5873.md'),
<add> file: fixtures.path('order_of_end_tags_5873.md'),
<ide> json: {
<ide> source: 'foo',
<ide> modules: [{
<ide> const testData = [
<ide> }
<ide> },
<ide> {
<del> file: path.join(common.fixturesDir, 'doc_with_yaml.md'),
<add> file: fixtures.path('doc_with_yaml.md'),
<ide> json: {
<ide> source: 'foo',
<ide> modules: [
<ide><path>test/fixtures/module-require-symlink/symlinked.js
<ide> 'use strict';
<del>const common = require('../../common');
<ide> const assert = require('assert');
<ide> const foo = require('./foo');
<del>const path = require('path');
<add>const fixtures = require('../../common/fixtures');
<ide>
<del>const linkScriptTarget = path.join(common.fixturesDir,
<del> 'module-require-symlink', 'symlinked.js');
<add>const linkScriptTarget = fixtures.path('module-require-symlink', 'symlinked.js');
<ide>
<ide> assert.strictEqual(foo.dep1.bar.version, 'CORRECT_VERSION');
<ide> assert.strictEqual(foo.dep2.bar.version, 'CORRECT_VERSION');
<ide><path>test/fixtures/tls-connect.js
<ide> const common = require('../common');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<del>const fs = require('fs');
<del>const join = require('path').join;
<add>const fixtures = require('../common/fixtures');
<ide> const tls = require('tls');
<ide> const util = require('util');
<ide>
<ide> const keys = exports.keys = {
<ide> function load(cert, issuer) {
<ide> issuer = issuer || cert; // Assume self-signed if no issuer
<ide> const id = {
<del> key: read(cert + '-key.pem'),
<del> cert: read(cert + '-cert.pem'),
<del> ca: read(issuer + '-cert.pem'),
<add> key: fixtures.readKey(cert + '-key.pem', 'binary'),
<add> cert: fixtures.readKey(cert + '-cert.pem', 'binary'),
<add> ca: fixtures.readKey(issuer + '-cert.pem', 'binary'),
<ide> };
<ide> return id;
<ide> }
<ide>
<del>function read(file) {
<del> return fs.readFileSync(join(common.fixturesDir, 'keys', file), 'binary');
<del>}
<del>
<ide> exports.connect = function connect(options, callback) {
<ide> callback = common.mustCall(callback);
<ide>
<ide><path>test/inspector/inspector-helper.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const http = require('http');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide> const { spawn } = require('child_process');
<ide> const url = require('url');
<ide>
<del>const _MAINSCRIPT = path.join(common.fixturesDir, 'loop.js');
<add>const _MAINSCRIPT = fixtures.path('loop.js');
<ide> const DEBUG = false;
<ide> const TIMEOUT = common.platformTimeout(15 * 1000);
<ide>
<ide><path>test/internet/test-tls-add-ca-cert.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide> const tls = require('tls');
<ide>
<ide> function filenamePEM(n) {
<del> return path.join(common.fixturesDir, 'keys', `${n}.pem`);
<add> return fixtures.path('keys', `${n}.pem`);
<ide> }
<ide>
<ide> function loadPEM(n) {
<ide><path>test/known_issues/test-repl-require-context.js
<ide> // Refs: https://github.com/nodejs/node/issues/7788
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const path = require('path');
<add>const path = require('../common/fixtures').path;
<ide> const repl = require('repl');
<ide> const stream = require('stream');
<ide> const inputStream = new stream.PassThrough();
<ide> const outputStream = new stream.PassThrough();
<del>const fixture = path.join(common.fixturesDir, 'is-object.js');
<add>const fixture = path('is-object.js');
<ide> const r = repl.start({
<ide> input: inputStream,
<ide> output: outputStream,
<ide><path>test/known_issues/test-url-parse-conformance.js
<ide> 'use strict';
<ide>
<ide> // Refs: https://github.com/nodejs/node/issues/5832
<del>
<del>const common = require('../common');
<add>require('../common');
<ide> const url = require('url');
<ide> const assert = require('assert');
<del>const path = require('path');
<del>
<del>const tests = require(path.join(common.fixturesDir, 'url-tests'));
<add>const fixtures = require('../common/fixtures');
<add>const tests = require(fixtures.path('url-tests'));
<ide>
<ide> let failed = 0;
<ide> let attempted = 0;
<ide><path>test/pummel/test-https-ci-reneg-attack.js
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide> const tls = require('tls');
<ide> const https = require('https');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> // renegotiation limits to test
<ide> const LIMITS = [0, 1, 2, 3, 5, 10, 16];
<ide> const LIMITS = [0, 1, 2, 3, 5, 10, 16];
<ide>
<ide> function test(next) {
<ide> const options = {
<del> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`),
<del> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`)
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> };
<ide>
<ide> let seenError = false;
<ide><path>test/pummel/test-https-large-response.js
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const assert = require('assert');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide> const https = require('https');
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<ide> };
<ide>
<ide> process.stdout.write('build body...');
<ide><path>test/pummel/test-https-no-reader.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<del>const fs = require('fs');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> const options = {
<del> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')),
<del> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))
<add> key: fixtures.readSync('test_key.pem'),
<add> cert: fixtures.readSync('test_cert.pem')
<ide> };
<ide>
<ide> const buf = Buffer.allocUnsafe(1024 * 1024);
<ide><path>test/pummel/test-regress-GH-892.js
<ide> if (!common.hasCrypto)
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide> const https = require('https');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> const bytesExpected = 1024 * 1024 * 32;
<ide>
<ide> let started = false;
<ide>
<del>const childScript = require('path').join(common.fixturesDir,
<del> 'GH-892-request.js');
<add>const childScript = fixtures.path('GH-892-request.js');
<ide>
<ide> function makeRequest() {
<ide> if (started) return;
<ide> function makeRequest() {
<ide>
<ide>
<ide> const serverOptions = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<ide> };
<ide>
<ide> let uploadCount = 0;
<ide><path>test/pummel/test-tls-ci-reneg-attack.js
<ide> if (!common.opensslCli)
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide> const tls = require('tls');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> // renegotiation limits to test
<ide> const LIMITS = [0, 1, 2, 3, 5, 10, 16];
<ide> const LIMITS = [0, 1, 2, 3, 5, 10, 16];
<ide>
<ide> function test(next) {
<ide> const options = {
<del> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`),
<del> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`)
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> };
<ide>
<ide> let seenError = false;
<ide><path>test/pummel/test-tls-connect-memleak.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> assert.strictEqual(
<ide> typeof global.gc,
<ide> assert.strictEqual(
<ide> );
<ide>
<ide> tls.createServer({
<del> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`),
<del> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`)
<add> cert: fixtures.readSync('test_cert.pem'),
<add> key: fixtures.readSync('test_key.pem')
<ide> }).listen(common.PORT);
<ide>
<ide> {
<ide><path>test/pummel/test-tls-securepair-client.js
<ide> if (!common.opensslCli)
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<del>const join = require('path').join;
<ide> const net = require('net');
<ide> const assert = require('assert');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide> const tls = require('tls');
<ide> const spawn = require('child_process').spawn;
<ide>
<ide> function test2() {
<ide> }
<ide>
<ide> function test(keyfn, certfn, check, next) {
<del> keyfn = join(common.fixturesDir, keyfn);
<del> const key = fs.readFileSync(keyfn).toString();
<del>
<del> certfn = join(common.fixturesDir, certfn);
<del> const cert = fs.readFileSync(certfn).toString();
<add> const key = fixtures.readSync(keyfn).toString();
<add> const cert = fixtures.readSync(certfn).toString();
<ide>
<ide> const server = spawn(common.opensslCli, ['s_server',
<ide> '-accept', common.PORT,
<ide><path>test/pummel/test-tls-server-large-request.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide> const stream = require('stream');
<ide> const util = require('util');
<ide>
<ide> const request = Buffer.from('ABCD'.repeat(1024 * 256 - 1)); // 1mb
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<ide> };
<ide>
<ide> function Mediator() {
<ide><path>test/pummel/test-tls-session-timeout.js
<ide> function doTest() {
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide> const join = require('path').join;
<add> const fixtures = require('../common/fixtures');
<ide> const spawn = require('child_process').spawn;
<ide>
<ide> const SESSION_TIMEOUT = 1;
<ide>
<del> const keyFile = join(common.fixturesDir, 'agent.key');
<del> const certFile = join(common.fixturesDir, 'agent.crt');
<del> const key = fs.readFileSync(keyFile);
<del> const cert = fs.readFileSync(certFile);
<add> const key = fixtures.path('agent.key');
<add> const cert = fixtures.path('agent.crt');
<ide> const options = {
<ide> key: key,
<ide> cert: cert,
<ide> function doTest() {
<ide>
<ide> const sessionFileName = (function() {
<ide> const ticketFileName = 'tls-session-ticket.txt';
<del> const fixturesPath = join(common.fixturesDir, ticketFileName);
<ide> const tmpPath = join(common.tmpDir, ticketFileName);
<del> fs.writeFileSync(tmpPath, fs.readFileSync(fixturesPath));
<add> fs.writeFileSync(tmpPath, fixtures.readSync(ticketFileName));
<ide> return tmpPath;
<ide> }());
<ide>
<ide><path>test/pummel/test-tls-throttle.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> process.stdout.write('build body...');
<ide> const body = 'hello world\n'.repeat(1024 * 1024);
<ide> process.stdout.write('done\n');
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`)
<add> key: fixtures.readKey('agent2-key.pem'),
<add> cert: fixtures.readKey('agent2-cert.pem')
<ide> };
<ide>
<ide> const server = tls.Server(options, common.mustCall(function(socket) {
<ide><path>test/pummel/test-watch-file.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<ide>
<add>require('../common');
<add>const assert = require('assert');
<ide> const fs = require('fs');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide>
<del>const f = path.join(common.fixturesDir, 'x.txt');
<add>const f = fixtures.path('x.txt');
<ide>
<ide> let changes = 0;
<ide> function watchFile() {
<ide><path>test/sequential/test-debugger-repeat-last.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> common.skipIfInspectorDisabled();
<del>const path = require('path');
<add>const path = require('../common/fixtures').path;
<ide> const spawn = require('child_process').spawn;
<ide> const assert = require('assert');
<del>const fixture = path.join(
<del> common.fixturesDir,
<del> 'debugger-repeat-last.js'
<del>);
<add>const fixture = path('debugger-repeat-last.js');
<ide>
<ide> const args = [
<ide> 'inspect',
<ide><path>test/sequential/test-init.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const child = require('child_process');
<del>const path = require('path');
<add>const fixtures = require('../common/fixtures');
<ide>
<ide> if (process.env['TEST_INIT']) {
<ide> return process.stdout.write('Loaded successfully!');
<ide> function test(file, expected) {
<ide> // ensures that `node fs` does not mistakenly load the native 'fs' module
<ide> // instead of the desired file and that the fs module loads as
<ide> // expected in node
<del> process.chdir(path.join(common.fixturesDir, 'test-init-native'));
<add> process.chdir(fixtures.path('test-init-native'));
<ide> test('fs', 'fs loaded successfully');
<ide> } | 24 |
Ruby | Ruby | require redis 4+ in action cable | 7559957ba20570a5c561cfdd1161142d82eca6c2 | <ide><path>actioncable/lib/action_cable/subscription_adapter/redis.rb
<ide> # frozen_string_literal: true
<ide>
<del>gem "redis", ">= 3", "< 5"
<add>gem "redis", ">= 4", "< 6"
<ide> require "redis"
<ide>
<ide> require "active_support/core_ext/hash/except"
<ide> def initialize(adapter, event_loop)
<ide>
<ide> def listen(conn)
<ide> conn.without_reconnect do
<del> original_client = conn.respond_to?(:_client) ? conn._client : conn.client
<add> original_client = conn._client
<ide>
<ide> conn.subscribe("_action_cable_internal") do |on|
<ide> on.subscribe do |chan, count| | 1 |
Javascript | Javascript | update code style | 97c9defb42634425cfa5e5795b846c62f9a784c2 | <ide><path>editor/js/Menubar.Add.js
<ide> Menubar.Add = function ( editor ) {
<ide> // OrthographicCamera
<ide>
<ide> var option = new UI.Row();
<del> option.setClass('option');
<del> option.setTextContent(strings.getKey('menubar/add/orthographiccamera'));
<del> option.onClick(function(){
<add> option.setClass( 'option' );
<add> option.setTextContent( strings.getKey( 'menubar/add/orthographiccamera' ) );
<add> option.onClick( function () {
<add>
<ide> var camera = new THREE.OrthographicCamera();
<ide> camera.name = 'OrthographicCamera';
<ide>
<del> editor.execute(new AddObjectCommand(camera));
<del> });
<del> options.add(option);
<add> editor.execute( new AddObjectCommand( camera ) );
<add>
<add> } );
<add> options.add( option );
<ide>
<ide> return container;
<ide>
<ide><path>editor/js/Sidebar.Object.js
<ide> Sidebar.Object = function ( editor ) {
<ide> // left
<ide>
<ide> var objectLeftRow = new UI.Row();
<del> var objectLeft = new UI.Number().onChange(update);
<add> var objectLeft = new UI.Number().onChange( update );
<ide>
<del> objectLeftRow.add(new UI.Text(strings.getKey('sidebar/object/left')).setWidth('90px'));
<del> objectLeftRow.add(objectLeft);
<add> objectLeftRow.add( new UI.Text( strings.getKey( 'sidebar/object/left' ) ).setWidth( '90px' ) );
<add> objectLeftRow.add( objectLeft );
<ide>
<del> container.add(objectLeftRow);
<add> container.add( objectLeftRow );
<ide>
<ide> // right
<del>
<add>
<ide> var objectRightRow = new UI.Row();
<del> var objectRight = new UI.Number().onChange(update);
<add> var objectRight = new UI.Number().onChange( update );
<ide>
<del> objectRightRow.add(new UI.Text(strings.getKey('sidebar/object/right')).setWidth('90px'));
<del> objectRightRow.add(objectRight);
<add> objectRightRow.add( new UI.Text( strings.getKey( 'sidebar/object/right' ) ).setWidth( '90px' ) );
<add> objectRightRow.add( objectRight );
<ide>
<del> container.add(objectRightRow);
<add> container.add( objectRightRow );
<ide>
<ide> // top
<del>
<add>
<ide> var objectTopRow = new UI.Row();
<del> var objectTop = new UI.Number().onChange(update);
<add> var objectTop = new UI.Number().onChange( update );
<ide>
<del> objectTopRow.add(new UI.Text(strings.getKey('sidebar/object/top')).setWidth('90px'));
<del> objectTopRow.add(objectTop);
<add> objectTopRow.add( new UI.Text( strings.getKey( 'sidebar/object/top' ) ).setWidth( '90px' ) );
<add> objectTopRow.add( objectTop );
<ide>
<del> container.add(objectTopRow);
<add> container.add( objectTopRow );
<ide>
<ide> // bottom
<del>
<add>
<ide> var objectBottomRow = new UI.Row();
<del> var objectBottom = new UI.Number().onChange(update);
<add> var objectBottom = new UI.Number().onChange( update );
<ide>
<del> objectBottomRow.add(new UI.Text(strings.getKey('sidebar/object/bottom')).setWidth('90px'));
<del> objectBottomRow.add(objectBottom);
<add> objectBottomRow.add( new UI.Text( strings.getKey( 'sidebar/object/bottom' ) ).setWidth( '90px' ) );
<add> objectBottomRow.add( objectBottom );
<ide>
<del> container.add(objectBottomRow);
<add> container.add( objectBottomRow );
<ide>
<ide> // near
<ide>
<ide> Sidebar.Object = function ( editor ) {
<ide> if ( object.near !== undefined && Math.abs( object.near - objectNear.getValue() ) >= 0.01 ) {
<ide>
<ide> editor.execute( new SetValueCommand( object, 'near', objectNear.getValue() ) );
<del> if(object.isOrthographicCamera){
<add> if ( object.isOrthographicCamera ) {
<add>
<ide> object.updateProjectionMatrix();
<add>
<ide> }
<ide>
<ide> }
<ide>
<ide> if ( object.far !== undefined && Math.abs( object.far - objectFar.getValue() ) >= 0.01 ) {
<ide>
<ide> editor.execute( new SetValueCommand( object, 'far', objectFar.getValue() ) );
<del> if(object.isOrthographicCamera){
<add> if ( object.isOrthographicCamera ) {
<add>
<ide> object.updateProjectionMatrix();
<add>
<ide> }
<add>
<ide> }
<ide>
<ide> if ( object.intensity !== undefined && Math.abs( object.intensity - objectIntensity.getValue() ) >= 0.01 ) {
<ide> Sidebar.Object = function ( editor ) {
<ide> 'intensity': objectIntensityRow,
<ide> 'color': objectColorRow,
<ide> 'groundColor': objectGroundColorRow,
<del> 'distance' : objectDistanceRow,
<del> 'angle' : objectAngleRow,
<del> 'penumbra' : objectPenumbraRow,
<del> 'decay' : objectDecayRow,
<del> 'castShadow' : objectShadowRow,
<del> 'receiveShadow' : objectReceiveShadow,
<add> 'distance': objectDistanceRow,
<add> 'angle': objectAngleRow,
<add> 'penumbra': objectPenumbraRow,
<add> 'decay': objectDecayRow,
<add> 'castShadow': objectShadowRow,
<add> 'receiveShadow': objectReceiveShadow,
<ide> 'shadow': objectShadowRadius
<ide> };
<ide>
<ide><path>editor/js/Viewport.js
<ide> var Viewport = function ( editor ) {
<ide>
<ide> signals.viewportCameraChanged.add( function ( viewportCamera ) {
<ide>
<del> if(viewportCamera.isPerspectiveCamera) {
<add> if ( viewportCamera.isPerspectiveCamera ) {
<add>
<ide> viewportCamera.aspect = editor.camera.aspect;
<ide> viewportCamera.projectionMatrix.copy( editor.camera.projectionMatrix );
<del> }
<del> else if(!viewportCamera.isOrthographicCamera){
<add>
<add> } else if ( ! viewportCamera.isOrthographicCamera ) {
<add>
<ide> throw "Invalid camera set as viewport";
<add>
<ide> }
<ide>
<ide> camera = viewportCamera; | 3 |
Javascript | Javascript | fix finished typo | 21bd6679ce150e193cacd4b1b6585928224f255a | <ide><path>lib/internal/streams/end-of-stream.js
<ide> function eos(stream, opts, callback) {
<ide> };
<ide>
<ide> let writableFinished = stream.writableFinished ||
<del> (rState && rState.finished);
<add> (wState && wState.finished);
<ide> const onfinish = () => {
<ide> writable = false;
<ide> writableFinished = true;
<ide><path>test/parallel/test-stream-finished.js
<ide> testClosed((opts) => new Writable({ write() {}, ...opts }));
<ide> }));
<ide> }
<ide>
<del>
<ide> {
<ide> const r = new Readable({
<ide> autoDestroy: false
<ide> testClosed((opts) => new Writable({ write() {}, ...opts }));
<ide> finished(rs, common.mustCall());
<ide> }));
<ide> }
<add>
<add>{
<add> const d = new EE();
<add> d._writableState = {};
<add> d._writableState.finished = true;
<add> finished(d, { readable: false, writable: true }, common.mustCall((err) => {
<add> assert.strictEqual(err, undefined);
<add> }));
<add> d._writableState.errored = true;
<add> d.emit('close');
<add>} | 2 |
Text | Text | correct the command to install grunt | 1c3567e2cf31999c12279ff07adbf996c1cceb63 | <ide><path>CONTRIBUTING.md
<ide> If you are submitting a bug, please create a [jsfiddle](http://jsfiddle.net/) de
<ide> Contributing
<ide> ============
<ide>
<del>To contribute, fork the library and install grunt.
<add>To contribute, fork the library and install grunt and dependencies.
<ide>
<del> npm install grunt -g
<add> npm install -g grunt-cli
<add> npm install
<ide>
<ide> You can add tests to the files in `/test/moment` or add a new test file if you are adding a new feature.
<ide> | 1 |
Javascript | Javascript | add deprecation notice to swipeablelistview | 99471f87b944b26bbdaa0fb0881db91c1118b741 | <ide><path>Libraries/react-native/react-native-implementation.js
<ide> const invariant = require('fbjs/lib/invariant');
<ide>
<ide> let showedListViewDeprecation = false;
<add>let showedSwipeableListViewDeprecation = false;
<ide>
<ide> // Export React, plus some native additions.
<ide> module.exports = {
<ide> module.exports = {
<ide> return require('SwipeableFlatList');
<ide> },
<ide> get SwipeableListView() {
<add> if (!showedSwipeableListViewDeprecation) {
<add> console.warn(
<add> 'ListView and SwipeableListView are deprecated and will be removed in a future release. ' +
<add> 'See https://fb.me/nolistview for more information',
<add> );
<add>
<add> showedSwipeableListViewDeprecation = true;
<add> }
<ide> return require('SwipeableListView');
<ide> },
<ide> get TabBarIOS() { | 1 |
Javascript | Javascript | remove unused import | 4e6d6d206c596d96bf4335f1bb64e8e57513ea65 | <ide><path>packages/next-polyfill-nomodule/src/index.js
<ide> import 'core-js/features/array/from'
<ide> import 'core-js/features/array/includes'
<ide> import 'core-js/features/array/iterator'
<ide> import 'core-js/features/array/of'
<del>import 'core-js/features/array/species'
<ide> import 'core-js/features/function/has-instance'
<ide> import 'core-js/features/map'
<ide> import 'core-js/features/number/constructor' | 1 |
Python | Python | fix conn_type parsing from uris | 7d0a95d4b78e95eb528e51eca71baf14fe03b43c | <ide><path>airflow/models.py
<ide> def __init__(
<ide> schema=None, port=None, extra=None,
<ide> uri=None):
<ide> self.conn_id = conn_id
<del> self.conn_type = conn_type
<ide> if uri:
<ide> self.parse_from_uri(uri)
<ide> else:
<add> self.conn_type = conn_type
<ide> self.host = host
<ide> self.login = login
<ide> self.password = password
<ide> def parse_from_uri(self, uri):
<ide> hostname = temp_uri.hostname or ''
<ide> if '%2f' in hostname:
<ide> hostname = hostname.replace('%2f', '/').replace('%2F', '/')
<add> conn_type = temp_uri.scheme
<add> if conn_type == 'postgresql':
<add> conn_type = 'postgres'
<add> self.conn_type = conn_type
<ide> self.host = hostname
<ide> self.schema = temp_uri.path[1:]
<ide> self.login = temp_uri.username | 1 |
Javascript | Javascript | address flaky worker test | f93a19b428ffb80f1b5bf918744983f9a25bdced | <ide><path>test/parallel/test-worker-message-port-transfer-closed.js
<ide> testSingle(port1, port2);
<ide> port2.close(common.mustCall(testBothClosed));
<ide> testBothClosed();
<ide>
<del>setTimeout(common.mustNotCall('The communication channel is still open'),
<del> common.platformTimeout(1000)).unref();
<add>function tickUnref(n, fn) {
<add> if (n === 0) return fn();
<add> setImmediate(tickUnref, n - 1, fn).unref();
<add>}
<add>
<add>tickUnref(10, common.mustNotCall('The communication channel is still open')); | 1 |
Go | Go | remove unnescessary conversions (unconvert) | 7c40c0a9227089a7e3ee7c23c2bc0685ed133391 | <ide><path>integration-cli/daemon/daemon.go
<ide> func (d *Daemon) CheckActiveContainerCount(c *testing.T) (interface{}, string) {
<ide> if len(strings.TrimSpace(out)) == 0 {
<ide> return 0, ""
<ide> }
<del> return len(strings.Split(strings.TrimSpace(out), "\n")), fmt.Sprintf("output: %q", string(out))
<add> return len(strings.Split(strings.TrimSpace(out), "\n")), fmt.Sprintf("output: %q", out)
<ide> }
<ide>
<ide> // WaitRun waits for a container to be running for 10s
<ide><path>integration-cli/docker_api_attach_test.go
<ide> func (s *DockerSuite) TestGetContainersAttachWebsocket(c *testing.T) {
<ide> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")
<ide>
<del> rwc, err := request.SockConn(time.Duration(10*time.Second), request.DaemonHost())
<add> rwc, err := request.SockConn(10*time.Second, request.DaemonHost())
<ide> assert.NilError(c, err)
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide> func sockRequestHijack(method, endpoint string, data io.Reader, ct string, daemo
<ide> // Deprecated: Use New instead of NewRequestClient
<ide> // Deprecated: use request.Do (or Get, Delete, Post) instead
<ide> func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) {
<del> c, err := request.SockConn(time.Duration(10*time.Second), daemon)
<add> c, err := request.SockConn(10*time.Second, daemon)
<ide> if err != nil {
<ide> return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
<ide> }
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerAPIPause(c *testing.T) {
<ide> func (s *DockerSuite) TestContainerAPITop(c *testing.T) {
<ide> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> assert.NilError(c, waitRun(id))
<ide>
<ide> cli, err := client.NewClientWithOpts(client.FromEnv)
<ide> func (s *DockerSuite) TestContainerAPITop(c *testing.T) {
<ide> func (s *DockerSuite) TestContainerAPITopWindows(c *testing.T) {
<ide> testRequires(c, DaemonIsWindows)
<ide> out := runSleepingContainer(c, "-d")
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> assert.NilError(c, waitRun(id))
<ide>
<ide> cli, err := client.NewClientWithOpts(client.FromEnv)
<ide> func UtilCreateNetworkMode(c *testing.T, networkMode containertypes.NetworkMode)
<ide> containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
<ide> assert.NilError(c, err)
<ide>
<del> assert.Equal(c, containerJSON.HostConfig.NetworkMode, containertypes.NetworkMode(networkMode), "Mismatched NetworkMode")
<add> assert.Equal(c, containerJSON.HostConfig.NetworkMode, networkMode, "Mismatched NetworkMode")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) {
<ide><path>integration-cli/docker_api_images_test.go
<ide> func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *testing.T) {
<ide> assert.Equal(c, res.StatusCode, http.StatusOK)
<ide>
<ide> inspectOut := cli.InspectCmd(c, id, cli.Format(".Id")).Combined()
<del> assert.Equal(c, strings.TrimSpace(string(inspectOut)), id, "load did not work properly")
<add> assert.Equal(c, strings.TrimSpace(inspectOut), id, "load did not work properly")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIImagesDelete(c *testing.T) {
<ide><path>integration-cli/docker_api_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *testing.T) {
<ide>
<ide> func simpleTestService(s *swarm.Service) {
<ide> ureplicas := uint64(1)
<del> restartDelay := time.Duration(100 * time.Millisecond)
<add> restartDelay := 100 * time.Millisecond
<ide>
<ide> s.Spec = swarm.ServiceSpec{
<ide> TaskTemplate: swarm.TaskSpec{
<ide> func simpleTestService(s *swarm.Service) {
<ide>
<ide> func serviceForUpdate(s *swarm.Service) {
<ide> ureplicas := uint64(1)
<del> restartDelay := time.Duration(100 * time.Millisecond)
<add> restartDelay := 100 * time.Millisecond
<ide>
<ide> s.Spec = swarm.ServiceSpec{
<ide> TaskTemplate: swarm.TaskSpec{
<ide><path>integration-cli/docker_cli_build_test.go
<ide> CMD ["cat", "/foo"]`),
<ide> }).Assert(c, icmd.Success)
<ide>
<ide> res := inspectField(c, name, "Config.Cmd")
<del> assert.Equal(c, strings.TrimSpace(string(res)), `[cat /foo]`)
<add> assert.Equal(c, strings.TrimSpace(res), `[cat /foo]`)
<ide> }
<ide>
<ide> // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e)
<ide><path>integration-cli/docker_cli_create_test.go
<ide> func (s *DockerSuite) TestCreateArgs(c *testing.T) {
<ide> assert.Equal(c, len(containers), 1)
<ide>
<ide> cont := containers[0]
<del> assert.Equal(c, string(cont.Path), "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path))
<add> assert.Equal(c, cont.Path, "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path))
<ide>
<ide> b := false
<ide> expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
<ide> func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *testing.T) {
<ide> // #20972
<ide> func (s *DockerSuite) TestCreate64ByteHexID(c *testing.T) {
<ide> out := inspectField(c, "busybox", "Id")
<del> imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
<add> imageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:")
<ide>
<ide> dockerCmd(c, "create", imageID)
<ide> }
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *testing.T) {
<ide>
<ide> out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
<ide> assert.NilError(c, err)
<del> cgroupPaths := ParseCgroupPaths(string(out))
<del> assert.Assert(c, len(cgroupPaths) != 0, "unexpected output - %q", string(out))
<add> cgroupPaths := ParseCgroupPaths(out)
<add> assert.Assert(c, len(cgroupPaths) != 0, "unexpected output - %q", out)
<ide> out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
<ide> assert.NilError(c, err)
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> expectedCgroup := path.Join(cgroupParent, id)
<ide> found := false
<ide> for _, path := range cgroupPaths {
<ide><path>integration-cli/docker_cli_images_test.go
<ide> func (s *DockerSuite) TestImagesFormat(c *testing.T) {
<ide> dockerCmd(c, "tag", "busybox", tag+":v2")
<ide>
<ide> out, _ := dockerCmd(c, "images", "--format", "{{.Repository}}", tag)
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide>
<ide> expected := []string{"myimage", "myimage"}
<ide> var names []string
<ide><path>integration-cli/docker_cli_links_test.go
<ide> func (s *DockerSuite) TestLinksUpdateOnRestart(c *testing.T) {
<ide> testRequires(c, testEnv.IsLocalDaemon)
<ide> dockerCmd(c, "run", "-d", "--name", "one", "busybox", "top")
<ide> out, _ := dockerCmd(c, "run", "-d", "--name", "two", "--link", "one:onetwo", "--link", "one:one", "busybox", "top")
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide>
<ide> realIP := inspectField(c, "one", "NetworkSettings.Networks.bridge.IPAddress")
<ide> content := readContainerFileWithExec(c, id, "/etc/hosts")
<ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *
<ide> // verify first container's etc/hosts file has not changed after spawning the second named container
<ide> hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
<ide> assert.NilError(c, err)
<del> assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
<add> assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
<ide> // stop container 2 and verify first container's etc/hosts has not changed
<ide> _, err = s.d.Cmd("stop", cid2)
<ide> assert.NilError(c, err)
<ide>
<ide> hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
<ide> assert.NilError(c, err)
<del> assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
<add> assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second container creation", hostsFile))
<ide> // but discovery is on when connecting to non default bridge network
<ide> network := "anotherbridge"
<ide> out, err = s.d.Cmd("network", "create", network)
<ide> func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *
<ide>
<ide> hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
<ide> assert.NilError(c, err)
<del> assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second network connection", hostsFile))
<add> assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second network connection", hostsFile))
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *testing.T) {
<ide> func (s *DockerDaemonSuite) TestDaemonRestartRestoreBridgeNetwork(t *testing.T)
<ide> // Cleanup because these containers will not be shut down by daemon
<ide> out, err = s.d.Cmd("stop", newCon)
<ide> if err != nil {
<del> t.Fatalf("err: %v %v", err, string(out))
<add> t.Fatalf("err: %v %v", err, out)
<ide> }
<ide> _, err = s.d.Cmd("stop", strings.TrimSpace(id))
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsRightTagName(c *testing.T) {
<ide>
<ide> var id1 string
<ide> out := runSleepingContainer(c)
<del> id1 = strings.TrimSpace(string(out))
<add> id1 = strings.TrimSpace(out)
<ide>
<ide> var id2 string
<ide> out = runSleepingContainerInImage(c, tag)
<del> id2 = strings.TrimSpace(string(out))
<add> id2 = strings.TrimSpace(out)
<ide>
<ide> var imageID string
<ide> out = inspectField(c, "busybox", "Id")
<del> imageID = strings.TrimSpace(string(out))
<add> imageID = strings.TrimSpace(out)
<ide>
<ide> var id3 string
<ide> out = runSleepingContainerInImage(c, imageID)
<del> id3 = strings.TrimSpace(string(out))
<add> id3 = strings.TrimSpace(out)
<ide>
<ide> out, _ = dockerCmd(c, "ps", "--no-trunc")
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> // skip header
<ide> lines = lines[1:]
<ide> func (s *DockerSuite) TestPsImageIDAfterUpdate(c *testing.T) {
<ide> result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
<ide> result.Assert(c, icmd.Success)
<ide>
<del> lines := strings.Split(strings.TrimSpace(string(result.Combined())), "\n")
<add> lines := strings.Split(strings.TrimSpace(result.Combined()), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> // skip header
<ide> lines = lines[1:]
<ide> func (s *DockerSuite) TestPsImageIDAfterUpdate(c *testing.T) {
<ide> result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
<ide> result.Assert(c, icmd.Success)
<ide>
<del> lines = strings.Split(strings.TrimSpace(string(result.Combined())), "\n")
<add> lines = strings.Split(strings.TrimSpace(result.Combined()), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> // skip header
<ide> lines = lines[1:]
<ide> func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *testing.T) {
<ide> dockerCmd(c, "run", "--name=foo", "-d", "-p", "5000:5000", "busybox", "top")
<ide> assert.Assert(c, waitRun("foo") == nil)
<ide> out, _ := dockerCmd(c, "ps")
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> expected := "0.0.0.0:5000->5000/tcp"
<ide> fields := strings.Fields(lines[1])
<ide> assert.Equal(c, fields[len(fields)-2], expected, fmt.Sprintf("Expected: %v, got: %v", expected, fields[len(fields)-2]))
<ide>
<ide> dockerCmd(c, "kill", "foo")
<ide> dockerCmd(c, "wait", "foo")
<ide> out, _ = dockerCmd(c, "ps", "-l")
<del> lines = strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines = strings.Split(strings.TrimSpace(out), "\n")
<ide> fields = strings.Fields(lines[1])
<ide> assert.Assert(c, fields[len(fields)-2] != expected, "Should not got %v", expected)
<ide> }
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide>
<ide> out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}")
<ide>
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> assert.Equal(c, len(lines), 3)
<ide>
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide> // filter by volume name
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test")
<ide>
<del> lines = strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines = strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> assert.Equal(c, len(lines), 1)
<ide>
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide>
<ide> // empty results filtering by unknown volume
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist")
<del> assert.Equal(c, len(strings.TrimSpace(string(out))), 0)
<add> assert.Equal(c, len(strings.TrimSpace(out)), 0)
<ide>
<ide> // filter by mount destination
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp)
<ide>
<del> lines = strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines = strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> assert.Equal(c, len(lines), 2)
<ide>
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide> // filter by bind mount source
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource)
<ide>
<del> lines = strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines = strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> assert.Equal(c, len(lines), 1)
<ide>
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide> // filter by bind mount destination
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination)
<ide>
<del> lines = strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines = strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> assert.Equal(c, len(lines), 1)
<ide>
<ide> func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
<ide>
<ide> // empty results filtering by unknown mount point
<ide> out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted")
<del> assert.Equal(c, len(strings.TrimSpace(string(out))), 0)
<add> assert.Equal(c, len(strings.TrimSpace(out)), 0)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
<ide>
<ide> // Filter docker ps on non existing network
<ide> out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist")
<del> containerOut := strings.TrimSpace(string(out))
<add> containerOut := strings.TrimSpace(out)
<ide> lines := strings.Split(containerOut, "\n")
<ide>
<ide> // skip header
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
<ide>
<ide> // Filter docker ps on network bridge
<ide> out, _ = dockerCmd(c, "ps", "--filter", "network=bridge")
<del> containerOut = strings.TrimSpace(string(out))
<add> containerOut = strings.TrimSpace(out)
<ide>
<ide> lines = strings.Split(containerOut, "\n")
<ide>
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
<ide> assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on network\n")
<ide> // Filter docker ps on networks bridge and none
<ide> out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none")
<del> containerOut = strings.TrimSpace(string(out))
<add> containerOut = strings.TrimSpace(out)
<ide>
<ide> lines = strings.Split(containerOut, "\n")
<ide>
<ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
<ide>
<ide> // Filter by network ID
<ide> out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID)
<del> containerOut = strings.TrimSpace(string(out))
<add> containerOut = strings.TrimSpace(out)
<ide>
<ide> assert.Assert(c, is.Contains(containerOut, "onbridgenetwork"))
<ide>
<ide> // Filter by partial network ID
<del> partialnwID := string(nwID[0:4])
<add> partialnwID := nwID[0:4]
<ide>
<ide> out, _ = dockerCmd(c, "ps", "--filter", "network="+partialnwID)
<del> containerOut = strings.TrimSpace(string(out))
<add> containerOut = strings.TrimSpace(out)
<ide>
<ide> lines = strings.Split(containerOut, "\n")
<ide>
<ide> func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *testing.T) {
<ide> dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top")
<ide>
<ide> out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> lines = RemoveLinesForExistingElements(lines, existingContainers)
<ide> expected := []string{"bbb", "aaa,bbb/aaa"}
<ide> var names []string
<ide><path>integration-cli/docker_cli_pull_local_test.go
<ide> func (s *DockerRegistrySuite) TestPullManifestList(c *testing.T) {
<ide> err = os.MkdirAll(blobDir, 0755)
<ide> assert.NilError(c, err, "error creating blob dir")
<ide> blobPath := filepath.Join(blobDir, "data")
<del> err = ioutil.WriteFile(blobPath, []byte(manifestListJSON), 0644)
<add> err = ioutil.WriteFile(blobPath, manifestListJSON, 0644)
<ide> assert.NilError(c, err, "error writing manifest list")
<ide>
<ide> // Add to revision store
<ide><path>integration-cli/docker_cli_registry_user_agent_test.go
<ide> func unescapeBackslashSemicolonParens(s string) string {
<ide> ret := re.ReplaceAll([]byte(s), []byte(";"))
<ide>
<ide> re = regexp.MustCompile(`\\\(`)
<del> ret = re.ReplaceAll([]byte(ret), []byte("("))
<add> ret = re.ReplaceAll(ret, []byte("("))
<ide>
<ide> re = regexp.MustCompile(`\\\)`)
<del> ret = re.ReplaceAll([]byte(ret), []byte(")"))
<add> ret = re.ReplaceAll(ret, []byte(")"))
<ide>
<ide> re = regexp.MustCompile(`\\\\`)
<del> ret = re.ReplaceAll([]byte(ret), []byte(`\`))
<add> ret = re.ReplaceAll(ret, []byte(`\`))
<ide>
<ide> return string(ret)
<ide> }
<ide><path>integration-cli/docker_cli_restart_test.go
<ide> func (s *DockerSuite) TestRestartDisconnectedContainer(c *testing.T) {
<ide> func (s *DockerSuite) TestRestartPolicyNO(c *testing.T) {
<ide> out, _ := dockerCmd(c, "create", "--restart=no", "busybox")
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> name := inspectField(c, id, "HostConfig.RestartPolicy.Name")
<ide> assert.Equal(c, name, "no")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyAlways(c *testing.T) {
<ide> out, _ := dockerCmd(c, "create", "--restart=always", "busybox")
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> name := inspectField(c, id, "HostConfig.RestartPolicy.Name")
<ide> assert.Equal(c, name, "always")
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) {
<ide>
<ide> out, _ = dockerCmd(c, "create", "--restart=on-failure:1", "busybox")
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> name := inspectField(c, id, "HostConfig.RestartPolicy.Name")
<ide> maxRetry := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) {
<ide>
<ide> out, _ = dockerCmd(c, "create", "--restart=on-failure:0", "busybox")
<ide>
<del> id = strings.TrimSpace(string(out))
<add> id = strings.TrimSpace(out)
<ide> name = inspectField(c, id, "HostConfig.RestartPolicy.Name")
<ide> maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) {
<ide>
<ide> out, _ = dockerCmd(c, "create", "--restart=on-failure", "busybox")
<ide>
<del> id = strings.TrimSpace(string(out))
<add> id = strings.TrimSpace(out)
<ide> name = inspectField(c, id, "HostConfig.RestartPolicy.Name")
<ide> maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) {
<ide> func (s *DockerSuite) TestRestartContainerwithGoodContainer(c *testing.T) {
<ide> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true")
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second)
<ide> assert.NilError(c, err)
<ide>
<ide> func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *testing.T) {
<ide> out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
<ide> out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")
<ide>
<del> id1 := strings.TrimSpace(string(out1))
<del> id2 := strings.TrimSpace(string(out2))
<add> id1 := strings.TrimSpace(out1)
<add> id2 := strings.TrimSpace(out2)
<ide> waitTimeout := 15 * time.Second
<ide> if testEnv.OSType == "windows" {
<ide> waitTimeout = 150 * time.Second
<ide> func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *testing.T) {
<ide> func (s *DockerSuite) TestRestartAutoRemoveContainer(c *testing.T) {
<ide> out := runSleepingContainer(c, "--rm")
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> dockerCmd(c, "restart", id)
<ide> err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second)
<ide> assert.NilError(c, err)
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) {
<ide> var out string
<ide> out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
<ide>
<del> if actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "127.0.0.1" {
<del> c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
<add> if actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP); actualNameservers[0] != "127.0.0.1" {
<add> c.Fatalf("expected '127.0.0.1', but says: %q", actualNameservers[0])
<ide> }
<ide>
<ide> actualSearch := resolvconf.GetSearchDomains([]byte(out))
<ide> func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) {
<ide> }
<ide> }
<ide>
<del> if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
<del> c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
<add> if actualSearch = resolvconf.GetSearchDomains([]byte(out)); actualSearch[0] != "mydomain" {
<add> c.Fatalf("expected 'mydomain', but says: %q", actualSearch[0])
<ide> }
<ide>
<ide> // test with file
<ide> func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) {
<ide> hostSearch = resolvconf.GetSearchDomains(resolvConf)
<ide>
<ide> out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
<del> if actualNameservers = resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
<add> if actualNameservers = resolvconf.GetNameservers([]byte(out), types.IP); actualNameservers[0] != "12.34.56.78" || len(actualNameservers) != 1 {
<ide> c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide> containerID1 := getIDByName(c, "first")
<ide>
<ide> // replace resolv.conf with our temporary copy
<del> bytesResolvConf := []byte(tmpResolvConf)
<del> if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
<add> if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide>
<ide> // check for update in container
<ide> containerResolv := readContainerFile(c, containerID1, "resolv.conf")
<del> if !bytes.Equal(containerResolv, bytesResolvConf) {
<add> if !bytes.Equal(containerResolv, tmpResolvConf) {
<ide> c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide> runningContainerID := strings.TrimSpace(out)
<ide>
<ide> // replace resolv.conf
<del> if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
<add> if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<ide> // check for update in container
<ide> containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
<del> if bytes.Equal(containerResolv, bytesResolvConf) {
<add> if bytes.Equal(containerResolv, tmpResolvConf) {
<ide> c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide>
<ide> // check for update in container
<ide> containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
<del> if !bytes.Equal(containerResolv, bytesResolvConf) {
<del> c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
<add> if !bytes.Equal(containerResolv, tmpResolvConf) {
<add> c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv))
<ide> }
<ide>
<ide> //5. test that additions of a localhost resolver are cleaned from
<ide> // host resolv.conf before updating container's resolv.conf copies
<ide>
<ide> // replace resolv.conf with a localhost-only nameserver copy
<del> bytesResolvConf = []byte(tmpLocalhostResolvConf)
<del> if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
<add> if err = ioutil.WriteFile("/etc/resolv.conf", tmpLocalhostResolvConf, 0644); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide> containerID3 := getIDByName(c, "third")
<ide>
<ide> // Create a modified resolv.conf.aside and override resolv.conf with it
<del> bytesResolvConf = []byte(tmpResolvConf)
<del> if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
<add> if err := ioutil.WriteFile("/etc/resolv.conf.aside", tmpResolvConf, 0644); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
<ide>
<ide> // check for update in container
<ide> containerResolv = readContainerFile(c, containerID3, "resolv.conf")
<del> if !bytes.Equal(containerResolv, bytesResolvConf) {
<add> if !bytes.Equal(containerResolv, tmpResolvConf) {
<ide> c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunRestartMaxRetries(c *testing.T) {
<ide> timeout = 120 * time.Second
<ide> }
<ide>
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) {
<ide> c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
<ide> }
<ide> expected := "type devpts (rw,"
<del> if !strings.Contains(string(out), expected) {
<add> if !strings.Contains(out, expected) {
<ide> c.Fatalf("expected output to contain %s but contains %s", expected, out)
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *
<ide> dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
<ide>
<ide> out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
<del> if !strings.Contains(string(out), "testlinked") {
<add> if !strings.Contains(out, "testlinked") {
<ide> c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *testing.T
<ide> testRequires(c, DaemonIsLinux, UserNamespaceROMount)
<ide>
<ide> out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
<del> if !strings.Contains(string(out), "1.1.1.1") {
<add> if !strings.Contains(out, "1.1.1.1") {
<ide> c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *testi
<ide> testRequires(c, DaemonIsLinux, UserNamespaceROMount)
<ide>
<ide> out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
<del> if !strings.Contains(string(out), "testreadonly") {
<add> if !strings.Contains(out, "testreadonly") {
<ide> c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithCgroupParent(c *testing.T) {
<ide> func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) {
<ide> out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
<ide> if err != nil {
<del> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
<add> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
<ide> }
<del> cgroupPaths := ParseCgroupPaths(string(out))
<add> cgroupPaths := ParseCgroupPaths(out)
<ide> if len(cgroupPaths) == 0 {
<del> c.Fatalf("unexpected output - %q", string(out))
<add> c.Fatalf("unexpected output - %q", out)
<ide> }
<ide> id := getIDByName(c, name)
<ide> expectedCgroup := path.Join(cgroupParent, id)
<ide> func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, n
<ide> out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
<ide> if err != nil {
<ide> // XXX: This may include a daemon crash.
<del> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
<add> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
<ide> }
<ide>
<ide> // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
<ide> if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
<ide> c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
<ide> }
<ide>
<del> cgroupPaths := ParseCgroupPaths(string(out))
<add> cgroupPaths := ParseCgroupPaths(out)
<ide> if len(cgroupPaths) == 0 {
<del> c.Fatalf("unexpected output - %q", string(out))
<add> c.Fatalf("unexpected output - %q", out)
<ide> }
<ide> id := getIDByName(c, name)
<ide> expectedCgroup := path.Join(cleanCgroupParent, id)
<ide> func (s *DockerSuite) TestRunAttachFailedNoLeak(c *testing.T) {
<ide> assert.Assert(c, err != nil, "Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2)
<ide> // check for windows error as well
<ide> // TODO Windows Post TP5. Fix the error message string
<del> assert.Assert(c, strings.Contains(string(out), "port is already allocated") ||
<del> strings.Contains(string(out), "were not connected because a duplicate name exists") ||
<del> strings.Contains(string(out), "The specified port already exists") ||
<del> strings.Contains(string(out), "HNS failed with error : Failed to create endpoint") ||
<del> strings.Contains(string(out), "HNS failed with error : The object already exists"), fmt.Sprintf("Output: %s", out))
<add> assert.Assert(c, strings.Contains(out, "port is already allocated") ||
<add> strings.Contains(out, "were not connected because a duplicate name exists") ||
<add> strings.Contains(out, "The specified port already exists") ||
<add> strings.Contains(out, "HNS failed with error : Failed to create endpoint") ||
<add> strings.Contains(out, "HNS failed with error : The object already exists"), fmt.Sprintf("Output: %s", out))
<ide> dockerCmd(c, "rm", "-f", "test")
<ide>
<ide> // NGoroutines is not updated right away, so we need to wait before failing
<ide><path>integration-cli/docker_cli_service_logs_test.go
<ide> func countLogLines(d *daemon.Daemon, name string) func(*testing.T) (interface{},
<ide> return 0, "Empty stdout"
<ide> }
<ide> lines := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
<del> return len(lines), fmt.Sprintf("output, %q", string(result.Stdout()))
<add> return len(lines), fmt.Sprintf("output, %q", result.Stdout())
<ide> }
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmServiceNetworkUpdate(c *testing.T) {
<ide>
<ide> result := icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "foo"))
<ide> result.Assert(c, icmd.Success)
<del> fooNetwork := strings.TrimSpace(string(result.Combined()))
<add> fooNetwork := strings.TrimSpace(result.Combined())
<ide>
<ide> result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "bar"))
<ide> result.Assert(c, icmd.Success)
<del> barNetwork := strings.TrimSpace(string(result.Combined()))
<add> barNetwork := strings.TrimSpace(result.Combined())
<ide>
<ide> result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "baz"))
<ide> result.Assert(c, icmd.Success)
<del> bazNetwork := strings.TrimSpace(string(result.Combined()))
<add> bazNetwork := strings.TrimSpace(result.Combined())
<ide>
<ide> // Create a service
<ide> name := "top"
<ide><path>integration-cli/docker_cli_swarm_unix_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *testing.T) {
<ide> }
<ide>
<ide> assert.NilError(c, json.NewDecoder(strings.NewReader(out)).Decode(&mounts))
<del> assert.Equal(c, len(mounts), 1, string(out))
<add> assert.Equal(c, len(mounts), 1, out)
<ide> assert.Equal(c, mounts[0].Name, "my-volume")
<ide> assert.Equal(c, mounts[0].Driver, "customvolumedriver")
<ide> }
<ide><path>integration-cli/docker_cli_update_unix_test.go
<ide> func (s *DockerSuite) TestUpdateNotAffectMonitorRestartPolicy(c *testing.T) {
<ide> testRequires(c, DaemonIsLinux, cpuShare)
<ide>
<ide> out, _ := dockerCmd(c, "run", "-tid", "--restart=always", "busybox", "sh")
<del> id := strings.TrimSpace(string(out))
<add> id := strings.TrimSpace(out)
<ide> dockerCmd(c, "update", "--cpu-shares", "512", id)
<ide>
<ide> cpty, tty, err := pty.Open()
<ide><path>integration-cli/docker_cli_volume_test.go
<ide> func (s *DockerSuite) TestVolumeLsFormatDefaultFormat(c *testing.T) {
<ide> }
<ide>
<ide> func assertVolumesInList(c *testing.T, out string, expected []string) {
<del> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> for _, expect := range expected {
<ide> found := false
<ide> for _, v := range lines {
<ide><path>integration-cli/requirements_test.go
<ide> func UnixCli() bool {
<ide>
<ide> func Network() bool {
<ide> // Set a timeout on the GET at 15s
<del> var timeout = time.Duration(15 * time.Second)
<del> var url = "https://hub.docker.com"
<add> const timeout = 15 * time.Second
<add> const url = "https://hub.docker.com"
<ide>
<ide> client := http.Client{
<ide> Timeout: timeout, | 22 |
Python | Python | add algorithm for newton's law of gravitation | 660d2bb66c8ca03e2225090b5c638ffb0fd14a60 | <ide><path>physics/newtons_law_of_gravitation.py
<add>"""
<add>Title : Finding the value of either Gravitational Force, one of the masses or distance
<add>provided that the other three parameters are given.
<add>
<add>Description : Newton's Law of Universal Gravitation explains the presence of force of
<add>attraction between bodies having a definite mass situated at a distance. It is usually
<add>stated as that, every particle attracts every other particle in the universe with a
<add>force that is directly proportional to the product of their masses and inversely
<add>proportional to the square of the distance between their centers. The publication of the
<add>theory has become known as the "first great unification", as it marked the unification
<add>of the previously described phenomena of gravity on Earth with known astronomical
<add>behaviors.
<add>
<add>The equation for the universal gravitation is as follows:
<add>F = (G * mass_1 * mass_2) / (distance)^2
<add>
<add>Source :
<add>- https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation
<add>- Newton (1687) "Philosophiæ Naturalis Principia Mathematica"
<add>"""
<add>
<add>from __future__ import annotations
<add>
<add># Define the Gravitational Constant G and the function
<add>GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2
<add>
<add>
<add>def gravitational_law(
<add> force: float, mass_1: float, mass_2: float, distance: float
<add>) -> dict[str, float]:
<add>
<add> """
<add> Input Parameters
<add> ----------------
<add> force : magnitude in Newtons
<add>
<add> mass_1 : mass in Kilograms
<add>
<add> mass_2 : mass in Kilograms
<add>
<add> distance : distance in Meters
<add>
<add> Returns
<add> -------
<add> result : dict name, value pair of the parameter having Zero as it's value
<add>
<add> Returns the value of one of the parameters specified as 0, provided the values of
<add> other parameters are given.
<add> >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20)
<add> {'force': 8.342875e-12}
<add>
<add> >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048)
<add> {'mass_1': 1.385816317292268e+19}
<add>
<add> >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584)
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: One and only one argument must be 0
<add>
<add> >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584)
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Mass can not be negative
<add>
<add> >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374)
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Gravitational force can not be negative
<add> """
<add>
<add> product_of_mass = mass_1 * mass_2
<add>
<add> if (force, mass_1, mass_2, distance).count(0) != 1:
<add> raise ValueError("One and only one argument must be 0")
<add> if force < 0:
<add> raise ValueError("Gravitational force can not be negative")
<add> if distance < 0:
<add> raise ValueError("Distance can not be negative")
<add> if mass_1 < 0 or mass_2 < 0:
<add> raise ValueError("Mass can not be negative")
<add> if force == 0:
<add> force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2)
<add> return {"force": force}
<add> elif mass_1 == 0:
<add> mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2)
<add> return {"mass_1": mass_1}
<add> elif mass_2 == 0:
<add> mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1)
<add> return {"mass_2": mass_2}
<add> elif distance == 0:
<add> distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5
<add> return {"distance": distance}
<add> raise ValueError("One and only one argument must be 0")
<add>
<add>
<add># Run doctest
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod() | 1 |
Python | Python | fix broken test | 72c25dd9717a6c69967734a9dddf13f800e60843 | <ide><path>libcloud/test/compute/test_ec2.py
<ide> def test_list_sizes(self):
<ide> self.assertTrue('m2.4xlarge' in ids)
<ide>
<ide> if region_name == 'us-east-1':
<del> self.assertEqual(len(sizes), 29)
<add> self.assertEqual(len(sizes), 30)
<ide> self.assertTrue('cg1.4xlarge' in ids)
<ide> self.assertTrue('cc1.4xlarge' in ids)
<ide> self.assertTrue('cc2.8xlarge' in ids)
<ide> def test_list_sizes(self):
<ide> elif region_name == 'ap-southeast-2':
<ide> self.assertEqual(len(sizes), 24)
<ide> elif region_name == 'eu-west-1':
<del> self.assertEqual(len(sizes), 25)
<add> self.assertEqual(len(sizes), 27)
<ide>
<ide> self.driver.region_name = region_old
<ide> | 1 |
Python | Python | fix syntax error, add a comment | 1d0b2eeeb710ecbf3f65a34df3c38170a78a5216 | <ide><path>libcloud/dns/drivers/gandi.py
<ide> def delete_zone(self, zone):
<ide> return res.object
<ide>
<ide> def _to_record(self, record, zone):
<del> extras = {'ttl': record['ttl']}
<add> extra = {'ttl': record['ttl']}
<ide> value = record['value']
<ide> if record['type'] == 'MX':
<del> extras['priority'] = record['value'].split(' ')[0]
<add> # Record is in the following form:
<add> # <priority> <value>
<add> # e.g. 15 aspmx.l.google.com
<add> extra['priority'] = record['value'].split(' ')[0]
<ide> value = record['value'].split(' ')[1]
<ide> return Record(
<ide> id='%s:%s' % (record['type'], record['name']),
<ide> def _to_record(self, record, zone):
<ide> zone=zone,
<ide> driver=self,
<ide> ttl=record['ttl'],
<del> extra=extras
<add> extra=extra)
<ide>
<ide> def _to_records(self, records, zone):
<ide> retval = [] | 1 |
Text | Text | add tip for comment keyboard shortcut. | 91add57a9c9f6886675b34c706b161d38d510f51 | <ide><path>guide/english/html/comments-in-html/index.md
<ide> It is a good practice to add comments to your code, especially when working with
<ide>
<ide> Comments are started with `<!--` and ended with `-->`, and can span multiple lines. They can contain code or text, and won't appear on the front-end of the website when a user visits a page. You can view comments through the Inspector Console, or by viewing Page Source.
<ide>
<add>
<ide> ### Example
<ide> ```html
<ide> <!-- You can comment out a large number of lines like this.
<ide> These comments are only available in Internet Explorer and can be used up to IE9
<ide> <!--[if gt IE 9]> <p>Your browser is greater then IE9</p> <![endif]-->
<ide> ```
<ide>
<add>
<add>[About conditional comments](https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx)
<add>
<ide> IE Conditional Comments are really helpful when you wish to serve each IE version with a slightly different CSS. IE (and other browsers) can have rendering bugs, or rather, 'quirks' that render your page a little differently than what you would expect. These require some CSS tricks to workaround (or even to make use of!) quirks, and so the conditional comments are good for targeting specific versions.
<ide>
<ide> For example, this CSS would only apply on IE 7 / 8:
<ide> For example, this CSS would only apply on IE 7 / 8:
<ide> <![endif]-->
<ide> ```
<ide>
<del>More reading:
<add>#### Tip
<add>**CTRL + /** is a keyboard shortcut which works in probably all modern text editors to create the comments. It creates a single line comment, but if you want to comment more lines, just highlight all the area and press it.
<add>
<add>#### More Information
<ide> * [About conditional comments](https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx)
<ide> * [Some IE CSS bugs](https://css-tricks.com/ie-css-bugs-thatll-get-you-every-time/)
<ide> * [IE CSS bugs and fixes](https://code.tutsplus.com/tutorials/9-most-common-ie-bugs-and-how-to-fix-them--net-7764)
<add> | 1 |
PHP | PHP | fix incorrect radio selection with falsey values | 0f0b5e7668e9cf8160efea26b9f0e84b35fa3262 | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testRadio() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => '1'));
<del> $expected = array(
<del> 'fieldset' => array(),
<del> 'legend' => array(),
<del> 'Field',
<del> '/legend',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1', 'checked' => 'checked')),
<del> array('label' => array('for' => 'ModelField1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0')),
<del> array('label' => array('for' => 'ModelField0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => '0'));
<del> $expected = array(
<del> 'fieldset' => array(),
<del> 'legend' => array(),
<del> 'Field',
<del> '/legend',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<del> array('label' => array('for' => 'ModelField1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0', 'checked' => 'checked')),
<del> array('label' => array('for' => 'ModelField0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => null));
<del> $expected = array(
<del> 'fieldset' => array(),
<del> 'legend' => array(),
<del> 'Field',
<del> '/legend',
<del> 'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '', 'id' => 'ModelField_'),
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<del> array('label' => array('for' => 'ModelField1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0')),
<del> array('label' => array('for' => 'ModelField0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'));
<del> $expected = array(
<del> 'fieldset' => array(),
<del> 'legend' => array(),
<del> 'Field',
<del> '/legend',
<del> 'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '', 'id' => 'ModelField_'),
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<del> array('label' => array('for' => 'ModelField1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0')),
<del> array('label' => array('for' => 'ModelField0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<ide> $result = $this->Form->input('Newsletter.subscribe', array('legend' => 'Legend title', 'type' => 'radio', 'options' => array('0' => 'Unsubscribe', '1' => 'Subscribe')));
<ide> $expected = array(
<ide> 'div' => array('class' => 'input radio'),
<ide> public function testRadio() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * Test that radios with a 0 value are selected under the correct conditions.
<add> *
<add> * @return void
<add> */
<add> public function testRadioOptionWithZeroValue() {
<add> $expected = array(
<add> 'fieldset' => array(),
<add> 'legend' => array(),
<add> 'Field',
<add> '/legend',
<add> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<add> array('label' => array('for' => 'ModelField1')),
<add> 'Yes',
<add> '/label',
<add> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0', 'checked' => 'checked')),
<add> array('label' => array('for' => 'ModelField0')),
<add> 'No',
<add> '/label',
<add> '/fieldset'
<add> );
<add> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => '0'));
<add> $this->assertTags($result, $expected);
<add>
<add> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => 0));
<add> $this->assertTags($result, $expected);
<add>
<add> $expected = array(
<add> 'fieldset' => array(),
<add> 'legend' => array(),
<add> 'Field',
<add> '/legend',
<add> 'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '', 'id' => 'ModelField_'),
<add> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField1')),
<add> array('label' => array('for' => 'ModelField1')),
<add> 'Yes',
<add> '/label',
<add> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField0')),
<add> array('label' => array('for' => 'ModelField0')),
<add> 'No',
<add> '/label',
<add> '/fieldset'
<add> );
<add> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => null));
<add> $this->assertTags($result, $expected);
<add>
<add> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => ''));
<add> $this->assertTags($result, $expected);
<add>
<add> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'));
<add> $this->assertTags($result, $expected);
<add> }
<add>
<ide> /**
<ide> * test disabled radio options
<ide> *
<ide> public function testRadioDisabled() {
<ide> $result = $this->Form->radio(
<ide> 'Model.field',
<ide> array('option A', 'option B'),
<del> array('disabled' => array('option A'), 'value' => 'option A')
<add> array('disabled' => array('option A'), 'value' => '0')
<ide> );
<ide> $expected = array(
<ide> 'fieldset' => array(),
<ide> public function testRadioDisabled() {
<ide> $result = $this->Form->radio(
<ide> 'Model.field',
<ide> array('option A', 'option B'),
<del> array('disabled' => true, 'value' => 'option A')
<add> array('disabled' => true, 'value' => '0')
<ide> );
<ide> $expected = array(
<ide> 'fieldset' => array(),
<ide> public function testRadioDisabled() {
<ide> $result = $this->Form->radio(
<ide> 'Model.field',
<ide> array('option A', 'option B'),
<del> array('disabled' => 'disabled', 'value' => 'option A')
<add> array('disabled' => 'disabled', 'value' => '0')
<ide> );
<ide> $expected = array(
<ide> 'fieldset' => array(),
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> public function radio($fieldName, $options = array(), $attributes = array()) {
<ide> foreach ($options as $optValue => $optTitle) {
<ide> $optionsHere = array('value' => $optValue);
<ide>
<del> if (isset($value) && $optValue == $value) {
<add> if (isset($value) && strval($optValue) === strval($value)) {
<ide> $optionsHere['checked'] = 'checked';
<ide> }
<ide> if ($disabled && (!is_array($disabled) || in_array($optValue, $disabled))) { | 2 |
Ruby | Ruby | remove dead code | a8d0084c692af41b63c39fb956f3d5ce5516121f | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def _protected_ivars # :nodoc:
<ide> PROTECTED_IVARS
<ide> end
<ide>
<del> def self.protected_instance_variables
<del> PROTECTED_IVARS
<del> end
<del>
<ide> ActiveSupport.run_load_hooks(:action_controller, self)
<ide> end
<ide> end | 1 |
Ruby | Ruby | add help message for uconv | d4e3fb45cbcab862fa8fd023a9955d5be5058d75 | <ide><path>Library/Homebrew/missing_formula.rb
<ide> def blacklisted_reason(name)
<ide> cargo is part of the rust formula:
<ide> brew install rust
<ide> EOS
<add> when "uconv" then <<~EOS
<add> uconv is part of the icu4c formula:
<add> brew install icu4c
<add> EOS
<ide> end
<ide> end
<ide> alias generic_blacklisted_reason blacklisted_reason | 1 |
Ruby | Ruby | move blackbox to the boneyard | b7060ebc438acb84664cf91c5bba7e60c1961566 | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> 'denyhosts' => 'homebrew/boneyard',
<ide> 'ipopt' => 'homebrew/science',
<ide> 'qfits' => 'homebrew/boneyard',
<add> 'blackbox' => 'homebrew/boneyard',
<ide> } | 1 |
PHP | PHP | change method order | f51a59e7e18262874a4af20634da34430100876f | <ide><path>src/Illuminate/Queue/SyncQueue.php
<ide> protected function resolveJob($payload)
<ide> }
<ide>
<ide> /**
<del> * Handle the failed job.
<add> * Raise the after queue job event.
<ide> *
<ide> * @param \Illuminate\Contracts\Queue\Job $job
<del> * @return array
<add> * @return void
<ide> */
<del> protected function handleFailedJob(Job $job)
<add> protected function raiseAfterJobEvent(Job $job)
<ide> {
<del> $job->failed();
<add> $data = json_decode($job->getRawBody(), true);
<ide>
<del> $this->raiseFailedJobEvent($job);
<add> if ($this->container->bound('events')) {
<add> $this->container['events']->fire('illuminate.queue.after', ['sync', $job, $data]);
<add> }
<ide> }
<ide>
<ide> /**
<del> * Raise the failed queue job event.
<add> * Handle the failed job.
<ide> *
<ide> * @param \Illuminate\Contracts\Queue\Job $job
<del> * @return void
<add> * @return array
<ide> */
<del> protected function raiseFailedJobEvent(Job $job)
<add> protected function handleFailedJob(Job $job)
<ide> {
<del> $data = json_decode($job->getRawBody(), true);
<add> $job->failed();
<ide>
<del> if ($this->container->bound('events')) {
<del> $this->container['events']->fire('illuminate.queue.failed', ['sync', $job, $data]);
<del> }
<add> $this->raiseFailedJobEvent($job);
<ide> }
<ide>
<ide> /**
<del> * Raise the after queue job event.
<add> * Raise the failed queue job event.
<ide> *
<ide> * @param \Illuminate\Contracts\Queue\Job $job
<ide> * @return void
<ide> */
<del> protected function raiseAfterJobEvent(Job $job)
<add> protected function raiseFailedJobEvent(Job $job)
<ide> {
<ide> $data = json_decode($job->getRawBody(), true);
<ide>
<ide> if ($this->container->bound('events')) {
<del> $this->container['events']->fire('illuminate.queue.after', ['sync', $job, $data]);
<add> $this->container['events']->fire('illuminate.queue.failed', ['sync', $job, $data]);
<ide> }
<ide> }
<ide> } | 1 |
Ruby | Ruby | apply suggestions from code review | 759708fae7dd3c9e5867ae42be34631dfe535964 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide> style_results = Style.check_style_json(style_files, options) if style_files
<ide> # load licenses
<ide> spdx = HOMEBREW_LIBRARY_PATH/"data/spdx.json"
<del> spdx_data = File.open(spdx, "r") do |file|
<del> JSON.parse(file.read)
<del> end
<add> spdx_data = JSON.parse(spdx.read)
<ide> new_formula_problem_lines = []
<ide> audit_formulae.sort.each do |f|
<ide> only = only_cops ? ["style"] : args.only
<ide> def audit_license
<ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @new_formula
<ide> user ||= nil
<ide> repo ||= nil
<del> return if user.nil?
<add> return if user.blank?
<ide>
<ide> github_license = GitHub.get_repo_license(user, repo)
<ide> return if github_license && (github_license == formula.license)
<ide><path>Library/Homebrew/dev-cmd/update-license-data.rb
<ide> module Homebrew
<ide>
<ide> SPDX_FOLDER_PATH = (HOMEBREW_LIBRARY_PATH/"data").freeze
<ide> FILE_NAME = "spdx.json"
<del> SPDX_DATA_URL = "https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json"
<add> SPDX_DATA_URL = "https://raw.githubusercontent.com/spdx/license-list-data/HEAD/json/licenses.json"
<ide>
<ide> def update_license_data_args
<ide> Homebrew::CLI::Parser.new do | 2 |
Go | Go | fix error message on firewalld init | 38b5c7266a14c34624bba532cb74d8b2ae46c726 | <ide><path>daemon/networkdriver/bridge/driver.go
<ide> func InitDriver(config *Config) error {
<ide> }
<ide>
<ide> if config.EnableIptables {
<del> iptables.FirewalldInit()
<add> if err := iptables.FirewalldInit(); err != nil {
<add> logrus.Debugf("Error initializing firewalld: %v", err)
<add> }
<ide> }
<ide>
<ide> // Configure iptables for link support
<ide><path>pkg/iptables/firewalld.go
<ide> var (
<ide> onReloaded []*func() // callbacks when Firewalld has been reloaded
<ide> )
<ide>
<del>func FirewalldInit() {
<add>func FirewalldInit() error {
<ide> var err error
<ide>
<del> connection, err = newConnection()
<del>
<del> if err != nil {
<del> logrus.Errorf("Failed to connect to D-Bus system bus: %s", err)
<add> if connection, err = newConnection(); err != nil {
<add> return fmt.Errorf("Failed to connect to D-Bus system bus: %v", err)
<ide> }
<ide> if connection != nil {
<ide> go signalHandler()
<ide> }
<ide>
<ide> firewalldRunning = checkRunning()
<add> return nil
<ide> }
<ide>
<ide> // New() establishes a connection to the system bus.
<ide> func checkRunning() bool {
<ide> logrus.Infof("Firewalld running: %t", err == nil)
<ide> return err == nil
<ide> }
<del> logrus.Info("Firewalld not running")
<ide> return false
<ide> }
<ide>
<ide> // Firewalld's passthrough method simply passes args through to iptables/ip6tables
<ide> func Passthrough(ipv IPV, args ...string) ([]byte, error) {
<ide> var output string
<del>
<ide> logrus.Debugf("Firewalld passthrough: %s, %s", ipv, args)
<del> err := connection.sysobj.Call(dbusInterface+".direct.passthrough", 0, ipv, args).Store(&output)
<del> if output != "" {
<del> logrus.Debugf("passthrough output: %s", output)
<add> if err := connection.sysobj.Call(dbusInterface+".direct.passthrough", 0, ipv, args).Store(&output); err != nil {
<add> return nil, err
<ide> }
<del>
<del> return []byte(output), err
<add> return []byte(output), nil
<ide> }
<ide><path>pkg/iptables/firewalld_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestFirewalldInit(t *testing.T) {
<del> FirewalldInit()
<add> if !checkRunning() {
<add> t.Skip("firewalld is not running")
<add> }
<add> if err := FirewalldInit(); err != nil {
<add> t.Fatal(err)
<add> }
<ide> }
<ide>
<ide> func TestReloaded(t *testing.T) { | 3 |
Javascript | Javascript | update flakey unoptimized image test | 06d2380937ad7597a8d7cce2f57d444f733ae79c | <ide><path>test/integration/image-component/unoptimized/test/index.test.js
<ide> function runTests() {
<ide> await browser.elementById('eager-image').getAttribute('srcset')
<ide> ).toBeNull()
<ide>
<del> await browser.eval(
<del> `document.getElementById("internal-image").scrollIntoView({behavior: "smooth"})`
<del> )
<del> await browser.eval(
<del> `document.getElementById("static-image").scrollIntoView({behavior: "smooth"})`
<del> )
<del> await browser.eval(
<del> `document.getElementById("external-image").scrollIntoView({behavior: "smooth"})`
<del> )
<del> await browser.eval(
<del> `document.getElementById("eager-image").scrollIntoView({behavior: "smooth"})`
<del> )
<add> await check(async () => {
<add> await browser.eval(
<add> `window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()`
<add> )
<add> return browser.eval(
<add> `document.getElementById("external-image").currentSrc`
<add> )
<add> }, 'https://image-optimization-test.vercel.app/test.jpg')
<ide>
<del> await check(
<del> () =>
<del> browser.eval(`document.getElementById("external-image").currentSrc`),
<del> 'https://image-optimization-test.vercel.app/test.jpg'
<del> )
<del> await check(
<del> () => browser.elementById('internal-image').getAttribute('src'),
<del> '/test.png'
<del> )
<del> await check(
<del> () => browser.elementById('static-image').getAttribute('src'),
<del> /test(.*)jpg/
<del> )
<del> await check(
<del> () => browser.elementById('external-image').getAttribute('src'),
<del> 'https://image-optimization-test.vercel.app/test.jpg'
<del> )
<del> await check(
<del> () => browser.elementById('eager-image').getAttribute('src'),
<del> '/test.webp'
<del> )
<add> await check(async () => {
<add> await browser.eval(
<add> `window.scrollTo(0, 0); document.getElementById("internal-image").scrollIntoView()`
<add> )
<add> return browser.elementById('internal-image').getAttribute('src')
<add> }, '/test.png')
<add>
<add> await check(async () => {
<add> await browser.eval(
<add> `window.scrollTo(0, 0); document.getElementById("static-image").scrollIntoView()`
<add> )
<add> return browser.elementById('static-image').getAttribute('src')
<add> }, /test(.*)jpg/)
<add>
<add> await check(async () => {
<add> await browser.eval(
<add> `window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()`
<add> )
<add> return browser.elementById('external-image').getAttribute('src')
<add> }, 'https://image-optimization-test.vercel.app/test.jpg')
<add>
<add> await check(async () => {
<add> await browser.eval(
<add> `window.scrollTo(0, 0); document.getElementById("eager-image").scrollIntoView()`
<add> )
<add> return browser.elementById('eager-image').getAttribute('src')
<add> }, '/test.webp')
<ide>
<ide> expect(
<ide> await browser.elementById('internal-image').getAttribute('srcset') | 1 |
Java | Java | fix race when flushing messages | 28174744a74e08cc974a54041e304dc4aafa5334 | <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<del>import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.messaging.Message;
<ide> private final class RelaySession {
<ide>
<ide> private final Promise<TcpConnection<String, String>> promise;
<ide>
<del> private final AtomicBoolean isConnected = new AtomicBoolean(false);
<del>
<ide> private final BlockingQueue<M> messageQueue = new LinkedBlockingQueue<M>(50);
<ide>
<add> private final Object monitor = new Object();
<add>
<add> private boolean isConnected = false;
<ide>
<ide> public RelaySession(final M message, final StompHeaders stompHeaders) {
<ide>
<ide> private void readStompFrame(String stompFrame) {
<ide>
<ide> StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders());
<ide> if (StompCommand.CONNECTED == headers.getStompCommand()) {
<del> this.isConnected.set(true);
<del> flushMessages(promise.get());
<add> synchronized(this.monitor) {
<add> this.isConnected = true;
<add> flushMessages(promise.get());
<add> }
<ide> return;
<ide> }
<ide> if (StompCommand.ERROR == headers.getStompCommand()) {
<ide> private void sendError(String sessionId, String errorText) {
<ide>
<ide> public void forward(M message, StompHeaders headers) {
<ide>
<del> if (!this.isConnected.get()) {
<del> @SuppressWarnings("unchecked")
<del> M m = (M) MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build();
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Adding to queue message " + m + ", queue size=" + this.messageQueue.size());
<add> synchronized(this.monitor) {
<add> if (!this.isConnected) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Adding to queue message " + message + ", queue size=" + this.messageQueue.size());
<add> }
<add> this.messageQueue.add(message);
<add> return;
<ide> }
<del> this.messageQueue.add(m);
<del> return;
<ide> }
<ide>
<ide> TcpConnection<String, String> connection = this.promise.get(); | 1 |
PHP | PHP | remove the 'line indented incorrectly' phpcs error | cb42b056ac7aac9f166dd3d9e5cd35ade3e513c0 | <ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function prepareFields(Model $Model, $queryData) {
<ide> if (empty($queryData['fields'])) {
<ide> $queryData['fields'] = $this->fields($Model);
<ide>
<del> // hasMany relationships need the $Model primary key.
<ide> } elseif (!empty($Model->hasMany) && $Model->recursive > -1) {
<add> // hasMany relationships need the $Model primary key.
<ide> $assocFields = $this->fields($Model, null, "{$Model->alias}.{$Model->primaryKey}");
<ide> $passedFields = $queryData['fields'];
<ide> | 1 |
Javascript | Javascript | prevent collision in project name with hash | e0db9777ba3a571c6595da8da0210b7caa221cbe | <ide><path>src/config.js
<ide> const {
<ide> const Color = require('./color')
<ide> const ScopedPropertyStore = require('scoped-property-store')
<ide> const ScopeDescriptor = require('./scope-descriptor')
<add>const crypto = require('crypto')
<ide>
<ide> // Essential: Used to access all of Atom's configuration details.
<ide> //
<ide> const ScopeDescriptor = require('./scope-descriptor')
<ide> // * Don't depend on (or write to) configuration keys outside of your keypath.
<ide> //
<ide> const schemaEnforcers = {}
<del>const PROJECT = '__project'
<add>const PROJECT = '__project' + crypto.randomBytes(20).toString('hex')
<ide>
<ide> class Config {
<ide> static addSchemaEnforcer (typeName, enforcerFunction) { | 1 |
Javascript | Javascript | fix perf suite broken by descriptor change | 5158a022dfd83a0dc9c3148bd3ed997716940392 | <ide><path>perf/tests/todolist-add.js
<ide> exports.defer = true;
<ide> exports.setup = function(){
<ide> /*global*/_rootNode = document.createElement('div');
<ide> document.body.appendChild(_rootNode);
<del> /*global*/_app = todolist.App({ fakeDataCount: 333 });
<del> React.renderComponent(_app, _rootNode);
<add> var appDescriptor = todolist.App({ fakeDataCount: 333 });
<add> /*global*/_app = React.renderComponent(appDescriptor, _rootNode);
<ide> };
<ide> exports.fn = function(deferred){
<ide> var liCount = document.getElementsByTagName('li').length;
<ide><path>perf/tests/todolist-do-stuff.js
<ide> exports.defer = true;
<ide> exports.setup = function(){
<ide> /*global*/_rootNode = document.createElement('div');
<ide> document.body.appendChild(_rootNode);
<del> /*global*/_app = todolist.App({ fakeDataCount: 333 });
<del> React.renderComponent(_app, _rootNode);
<add> var appDescriptor = todolist.App({ fakeDataCount: 333 });
<add> /*global*/_app = React.renderComponent(appDescriptor, _rootNode);
<ide> };
<ide>
<ide> exports.fn = function(deferred){
<ide><path>perf/tests/todolist-edit.js
<ide> exports.defer = true;
<ide> exports.setup = function(){
<ide> /*global*/_rootNode = document.createElement('div');
<ide> document.body.appendChild(_rootNode);
<del> /*global*/_app = todolist.App({ fakeDataCount: 333 });
<del> React.renderComponent(_app, _rootNode);
<add> var appDescriptor = todolist.App({ fakeDataCount: 333 });
<add> /*global*/_app = React.renderComponent(appDescriptor, _rootNode);
<ide> /*global*/_todo1 = _app.addItem("Howdy 1!");
<ide> /*global*/_todo2 = _app.addItem("Howdy 2!");
<ide> /*global*/_todo3 = _app.addItem("Howdy 3!"); | 3 |
Text | Text | add a readme for benchmark tests | 329103540c87becb0d9ee07478b0704f4d90af74 | <ide><path>benchmark/README.md
<add># Node.js core benchmark tests
<add>
<add>This folder contains benchmark tests to measure the performance for certain
<add>Node.js APIs.
<add>
<add>## How to run tests
<add>
<add>There are two ways to run benchmark tests:
<add>
<add>1. Run all tests of a given type, for example, buffers
<add>
<add>```sh
<add>node benchmark/common.js buffers
<add>```
<add>
<add>The above command will find all scripts under `buffers` directory and require
<add>each of them as a module. When a test script is required, it creates an instance
<add>of `Benchmark` (a class defined in common.js). In the next tick, the `Benchmark`
<add>constructor iterates through the configuration object property values and run
<add>the test function with each of the combined arguments in spawned processes. For
<add>example, buffers/buffer-read.js has the following configuration:
<add>
<add>```js
<add>var bench = common.createBenchmark(main, {
<add> noAssert: [false, true],
<add> buffer: ['fast', 'slow'],
<add> type: ['UInt8', 'UInt16LE', 'UInt16BE',
<add> 'UInt32LE', 'UInt32BE',
<add> 'Int8', 'Int16LE', 'Int16BE',
<add> 'Int32LE', 'Int32BE',
<add> 'FloatLE', 'FloatBE',
<add> 'DoubleLE', 'DoubleBE'],
<add> millions: [1]
<add>});
<add>```
<add>The runner takes one item from each of the property array value to build a list
<add>of arguments to run the main function. The main function will receive the conf
<add>object as follows:
<add>
<add>- first run:
<add>```js
<add> { noAssert: false,
<add> buffer: 'fast',
<add> type: 'UInt8',
<add> millions: 1
<add> }
<add>```
<add>- second run:
<add>```js
<add> {
<add> noAssert: false,
<add> buffer: 'fast',
<add> type: 'UInt16LE',
<add> millions: 1
<add> }
<add>```
<add>...
<add>
<add>In this case, the main function will run 2*2*14*1 = 56 times. The console output
<add>looks like the following:
<add>
<add>```
<add>buffers//buffer-read.js
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt8 millions=1: 271.83
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt16LE millions=1: 239.43
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt16BE millions=1: 244.57
<add>...
<add>```
<add>
<add>2. Run an individual test, for example, buffer-slice.js
<add>
<add>```sh
<add>node benchmark/buffers/buffer-read.js
<add>```
<add>The output:
<add>```
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt8 millions=1: 246.79
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt16LE millions=1: 240.11
<add>buffers/buffer-read.js noAssert=false buffer=fast type=UInt16BE millions=1: 245.91
<add>...
<add>```
<add>
<add>## How to write a benchmark test
<add>
<add>The benchmark tests are grouped by types. Each type corresponds to a subdirectory,
<add>such as `arrays`, `buffers`, or `fs`.
<add>
<add>Let's add a benchmark test for Buffer.slice function. We first create a file
<add>buffers/buffer-slice.js.
<add>
<add>### The code snippet
<add>
<add>```js
<add>var common = require('../common.js'); // Load the test runner
<add>
<add>var SlowBuffer = require('buffer').SlowBuffer;
<add>
<add>// Create a benchmark test for function `main` and the configuration variants
<add>var bench = common.createBenchmark(main, {
<add> type: ['fast', 'slow'], // Two types of buffer
<add> n: [512] // Number of times (each unit is 1024) to call the slice API
<add>});
<add>
<add>function main(conf) {
<add> // Read the parameters from the configuration
<add> var n = +conf.n;
<add> var b = conf.type === 'fast' ? buf : slowBuf;
<add> bench.start(); // Start benchmarking
<add> for (var i = 0; i < n * 1024; i++) {
<add> // Add your test here
<add> b.slice(10, 256);
<add> }
<add> bench.end(n); // End benchmarking
<add>}
<add>``` | 1 |
Ruby | Ruby | fix display of build error options | c2d23838d087b06487c4735f8b4183f0ba1a05f7 | <ide><path>Library/Homebrew/utils/analytics.rb
<ide> def report_build_error(exception)
<ide> return if exception.formula.tap.private?
<ide>
<ide> action = exception.formula.full_name
<del> if (options = exception.options)
<add> if (options = exception.options&.to_a&.join(" "))
<ide> action = "#{action} #{options}".strip
<ide> end
<ide> report_event("BuildError", action) | 1 |
Javascript | Javascript | fix babel only regexp on windows | 6b1bc4ad74310558b86d57186ce28eebf705a7a8 | <ide><path>setupBabel.js
<ide> const BABEL_ENABLED_PATHS = [
<ide> */
<ide> function buildRegExps(basePath, dirPaths) {
<ide> return dirPaths.map(folderPath =>
<del> new RegExp(`^${escapeRegExp(path.resolve(basePath, folderPath))}`)
<add> // Babel `only` option works with forward slashes in the RegExp so replace
<add> // backslashes for Windows.
<add> new RegExp(`^${escapeRegExp(path.resolve(basePath, folderPath).replace(/\\/g, '/'))}`)
<ide> );
<ide> }
<ide> | 1 |
Python | Python | switch params and example | e774e3a69eeb9a811a22e73ff87267e8bf4f9027 | <ide><path>flask/helpers.py
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide> def safe_join(directory, filename):
<ide> """Safely join `directory` and `filename`.
<ide>
<del> :param directory: the base directory.
<del> :param filename: the untrusted filename relative to that directory.
<del> :raises: :class:`~werkzeug.exceptions.NotFound` if the retsulting path
<del> would fall out of `directory`.
<del>
<ide> Example usage::
<ide>
<ide> @app.route('/wiki/<path:filename>')
<ide> def wiki_page(filename):
<ide> with open(filename, 'rb') as fd:
<ide> content = fd.read() # Read and process the file content...
<ide>
<add> :param directory: the base directory.
<add> :param filename: the untrusted filename relative to that directory.
<add> :raises: :class:`~werkzeug.exceptions.NotFound` if the retsulting path
<add> would fall out of `directory`.
<ide> """
<ide> filename = posixpath.normpath(filename)
<ide> for sep in _os_alt_seps: | 1 |
Javascript | Javascript | add errorutils to global variables | 76af5f916303d7906ea522076c965292145a1370 | <ide><path>packages/eslint-config-react-native-community/index.js
<ide> module.exports = {
<ide> clearTimeout: false,
<ide> console: false,
<ide> document: false,
<add> ErrorUtils: false,
<ide> escape: false,
<ide> Event: false,
<ide> EventTarget: false, | 1 |
Ruby | Ruby | find sequences with pg schemas properly | 055c6fb010417f7e5f8596a63075fc86ff35c54a | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
<ide> end
<ide>
<ide> if pk && sequence
<del> quoted_sequence = quote_column_name(sequence)
<del>
<add> quoted_sequence = quote_table_name(sequence)
<add>
<ide> select_value <<-end_sql, 'Reset sequence'
<ide> SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
<ide> end_sql
<ide> def pk_and_sequence_for(table) #:nodoc:
<ide> # First try looking for a sequence with a dependency on the
<ide> # given table's primary key.
<ide> result = exec_query(<<-end_sql, 'SCHEMA').rows.first
<del> SELECT attr.attname, seq.relname
<add> SELECT attr.attname, ns.nspname, seq.relname
<ide> FROM pg_class seq
<ide> INNER JOIN pg_depend dep ON seq.oid = dep.objid
<ide> INNER JOIN pg_attribute attr ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
<ide> INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
<add> INNER JOIN pg_namespace ns ON seq.relnamespace = ns.oid
<ide> WHERE seq.relkind = 'S'
<ide> AND cons.contype = 'p'
<ide> AND dep.refobjid = '#{quote_table_name(table)}'::regclass
<ide> end_sql
<ide>
<ide> # [primary_key, sequence]
<del> [result.first, result.last]
<add> if result.second == 'public' then
<add> sequence = result.last
<add> else
<add> sequence = result.second+'.'+result.last
<add> end
<add>
<add> [result.first, sequence]
<ide> rescue
<ide> nil
<ide> end | 1 |
Text | Text | update verbiage on guide faq | 786e7643ff5f8e4bdb552e9bf60b8b975ba012c9 | <ide><path>docs/index.md
<ide> Read our [How to Contribute to Open Source Guide](https://github.com/freeCodeCam
<ide>
<ide> ### Where are the Guide articles (guide.freecodecamp.org)?
<ide>
<del>We have permanently sunset the general guide articles, in favour of high quality tutorials on freeCodeCamp news. The challenge hints and articles are available on the freeCodeCamp forum which we have already migrated to, in our curriclum help button links.
<add>We have permanently sunset the general guide articles, in favour of high quality tutorials on freeCodeCamp news. The challenge hints and articles are available on the freeCodeCamp forum. Our curriclum help button links have been updated to point to those instead.
<ide>
<ide> ### Can I translate freeCodeCamp's curriculum?
<ide> | 1 |
PHP | PHP | add stub class for curl adapter | a18fd54b501487253b5d3e2913df5a3c999de51e | <ide><path>src/Http/Client.php
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Http\Client\AdapterInterface;
<add>use Cake\Http\Client\Adapter\Curl;
<ide> use Cake\Http\Client\Adapter\Stream;
<ide> use Cake\Http\Client\Request;
<ide> use Cake\Http\Cookie\CookieCollection;
<ide> class Client
<ide> * @var array
<ide> */
<ide> protected $_defaultConfig = [
<del> 'adapter' => Stream::class,
<add> 'adapter' => null,
<ide> 'host' => null,
<ide> 'port' => null,
<ide> 'scheme' => 'http',
<ide> class Client
<ide> * Defaults to true.
<ide> * - redirect - Number of redirects to follow. Defaults to false.
<ide> * - adapter - The adapter class name or instance. Defaults to
<del> * \Cake\Http\Client\Adapter\Stream
<add> * \Cake\Http\Client\Adapter\Curl if `curl` extension is loaded else
<add> * \Cake\Http\Client\Adapter\Stream.
<ide> *
<ide> * @param array $config Config options for scoped clients.
<ide> */
<ide> public function __construct($config = [])
<ide> $this->setConfig($config);
<ide>
<ide> $adapter = $this->_config['adapter'];
<del> $this->setConfig('adapter', null);
<add> if ($adapter === null) {
<add> $adapter = Curl::class;
<add>
<add> if (!extension_loaded('curl')) {
<add> $adapter = Stream::class;
<add> }
<add> } else {
<add> $this->setConfig('adapter', null);
<add> }
<add>
<ide> if (is_string($adapter)) {
<ide> $adapter = new $adapter();
<ide> }
<ide><path>src/Http/Client/Adapter/Curl.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 3.7.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http\Client\Adapter;
<add>
<add>use Cake\Http\Client\AdapterInterface;
<add>use Cake\Http\Client\Request;
<add>
<add>/**
<add> * Implements sending Cake\Http\Client\Request
<add> * via CURL.
<add> */
<add>class Curl implements AdapterInterface
<add>{
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public function send(Request $request, array $options)
<add> {
<add> // Do stuff here.
<add> }
<add>} | 2 |
Text | Text | simplify worker_threads.md text | b5fdb9e65ae99732a40b09456ba1c8db18431ee6 | <ide><path>doc/api/worker_threads.md
<ide> const worker = require('worker_threads');
<ide> ```
<ide>
<ide> Workers (threads) are useful for performing CPU-intensive JavaScript operations.
<del>They will not help much with I/O-intensive work. Node.js’s built-in asynchronous
<del>I/O operations are more efficient than Workers can be.
<add>They do not help much with I/O-intensive work. The Node.js built-in
<add>asynchronous I/O operations are more efficient than Workers can be.
<ide>
<ide> Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
<ide> so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`
<ide> if (isMainThread) {
<ide> ```
<ide>
<ide> The above example spawns a Worker thread for each `parse()` call. In actual
<del>practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the
<add>practice, use a pool of Workers for these kinds of tasks. Otherwise, the
<ide> overhead of creating Workers would likely exceed their benefit.
<ide>
<ide> When implementing a worker pool, use the [`AsyncResource`][] API to inform
<del>diagnostic tools (e.g. in order to provide asynchronous stack traces) about the
<add>diagnostic tools (e.g. to provide asynchronous stack traces) about the
<ide> correlation between tasks and their outcomes. See
<ide> ["Using `AsyncResource` for a `Worker` thread pool"][async-resource-worker-pool]
<ide> in the `async_hooks` documentation for an example implementation.
<ide> added:
<ide> -->
<ide>
<ide> Mark an object as not transferable. If `object` occurs in the transfer list of
<del>a [`port.postMessage()`][] call, it will be ignored.
<add>a [`port.postMessage()`][] call, it is ignored.
<ide>
<ide> In particular, this makes sense for objects that can be cloned, rather than
<ide> transferred, and which are used by other objects on the sending side.
<ide> There is no equivalent to this API in browsers.
<ide> added: v11.13.0
<ide> -->
<ide>
<del>* `port` {MessagePort} The message port which will be transferred.
<add>* `port` {MessagePort} The message port to transfer.
<ide> * `contextifiedSandbox` {Object} A [contextified][] object as returned by the
<ide> `vm.createContext()` method.
<ide>
<ide> * Returns: {MessagePort}
<ide>
<ide> Transfer a `MessagePort` to a different [`vm`][] Context. The original `port`
<del>object will be rendered unusable, and the returned `MessagePort` instance will
<del>take its place.
<add>object is rendered unusable, and the returned `MessagePort` instance
<add>takes its place.
<ide>
<del>The returned `MessagePort` will be an object in the target context, and will
<del>inherit from its global `Object` class. Objects passed to the
<del>[`port.onmessage()`][] listener will also be created in the target context
<add>The returned `MessagePort` is an object in the target context and
<add>inherits from its global `Object` class. Objects passed to the
<add>[`port.onmessage()`][] listener are also created in the target context
<ide> and inherit from its global `Object` class.
<ide>
<del>However, the created `MessagePort` will no longer inherit from
<add>However, the created `MessagePort` no longer inherits from
<ide> [`EventTarget`][], and only [`port.onmessage()`][] can be used to receive
<ide> events using it.
<ide>
<ide> added: v10.5.0
<ide>
<ide> * {null|MessagePort}
<ide>
<del>If this thread was spawned as a [`Worker`][], this will be a [`MessagePort`][]
<add>If this thread is a [`Worker`][], this is a [`MessagePort`][]
<ide> allowing communication with the parent thread. Messages sent using
<del>`parentPort.postMessage()` will be available in the parent thread
<add>`parentPort.postMessage()` are available in the parent thread
<ide> using `worker.on('message')`, and messages sent from the parent thread
<del>using `worker.postMessage()` will be available in this thread using
<add>using `worker.postMessage()` are available in this thread using
<ide> `parentPort.on('message')`.
<ide>
<ide> ```js
<ide> console.log(receiveMessageOnPort(port2));
<ide> // Prints: undefined
<ide> ```
<ide>
<del>When this function is used, no `'message'` event will be emitted and the
<del>`onmessage` listener will not be invoked.
<add>When this function is used, no `'message'` event is emitted and the
<add>`onmessage` listener is not invoked.
<ide>
<ide> ## `worker.resourceLimits`
<ide> <!-- YAML
<ide> added: v15.4.0
<ide> -->
<ide>
<ide> Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed
<del>BroadcastChannel will *not* let the program exit if it's the only active handle
<add>BroadcastChannel does *not* let the program exit if it's the only active handle
<ide> left (the default behavior). If the port is `ref()`ed, calling `ref()` again
<del>will have no effect.
<add>has no effect.
<ide>
<ide> ### `broadcastChannel.unref()`
<ide> <!-- YAML
<ide> added: v15.4.0
<ide> -->
<ide>
<del>Calling `unref()` on a BroadcastChannel will allow the thread to exit if this
<add>Calling `unref()` on a BroadcastChannel allows the thread to exit if this
<ide> is the only active handle in the event system. If the BroadcastChannel is
<del>already `unref()`ed calling `unref()` again will have no effect.
<add>already `unref()`ed calling `unref()` again has no effect.
<ide>
<ide> ## Class: `MessageChannel`
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> The `'message'` event is emitted for any incoming message, containing the cloned
<ide> input of [`port.postMessage()`][].
<ide>
<del>Listeners on this event will receive a clone of the `value` parameter as passed
<add>Listeners on this event receive a clone of the `value` parameter as passed
<ide> to `postMessage()` and no further arguments.
<ide>
<ide> ### Event: `'messageerror'`
<ide> Disables further sending of messages on either side of the connection.
<ide> This method can be called when no further communication will happen over this
<ide> `MessagePort`.
<ide>
<del>The [`'close'` event][] will be emitted on both `MessagePort` instances that
<add>The [`'close'` event][] is emitted on both `MessagePort` instances that
<ide> are part of the channel.
<ide>
<ide> ### `port.postMessage(value[, transferList])`
<ide> changes:
<ide> * `transferList` {Object[]}
<ide>
<ide> Sends a JavaScript value to the receiving side of this channel.
<del>`value` will be transferred in a way which is compatible with
<add>`value` is transferred in a way which is compatible with
<ide> the [HTML structured clone algorithm][].
<ide>
<ide> In particular, the significant differences to `JSON` are:
<ide> port2.postMessage(circularData);
<ide>
<ide> `transferList` may be a list of [`ArrayBuffer`][], [`MessagePort`][] and
<ide> [`FileHandle`][] objects.
<del>After transferring, they will not be usable on the sending side of the channel
<add>After transferring, they are not usable on the sending side of the channel
<ide> anymore (even if they are not contained in `value`). Unlike with
<ide> [child processes][], transferring handles such as network sockets is currently
<ide> not supported.
<ide>
<del>If `value` contains [`SharedArrayBuffer`][] instances, those will be accessible
<add>If `value` contains [`SharedArrayBuffer`][] instances, those are accessible
<ide> from either thread. They cannot be listed in `transferList`.
<ide>
<ide> `value` may still contain `ArrayBuffer` instances that are not in
<ide> port2.postMessage(uint8Array);
<ide> // This does not copy data, but renders `uint8Array` unusable:
<ide> port2.postMessage(uint8Array, [ uint8Array.buffer ]);
<ide>
<del>// The memory for the `sharedUint8Array` will be accessible from both the
<add>// The memory for the `sharedUint8Array` is accessible from both the
<ide> // original and the copy received by `.on('message')`:
<ide> const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
<ide> port2.postMessage(sharedUint8Array);
<ide> port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
<ide>
<ide> Because the object cloning uses the structured clone algorithm,
<ide> non-enumerable properties, property accessors, and object prototypes are
<del>not preserved. In particular, [`Buffer`][] objects will be read as
<add>not preserved. In particular, [`Buffer`][] objects are read as
<ide> plain [`Uint8Array`][]s on the receiving side.
<ide>
<del>The message object will be cloned immediately, and can be modified after
<add>The message object is cloned immediately, and can be modified after
<ide> posting without having side effects.
<ide>
<ide> For more information on the serialization and deserialization mechanisms
<ide> the raw data while the `TypedArray` and `Buffer` objects provide a
<ide> way of viewing and manipulating the data. It is possible and common
<ide> for multiple views to be created over the same `ArrayBuffer` instance.
<ide> Great care must be taken when using a transfer list to transfer an
<del>`ArrayBuffer` as doing so will cause all `TypedArray` and `Buffer`
<add>`ArrayBuffer` as doing so causes all `TypedArray` and `Buffer`
<ide> instances that share that same `ArrayBuffer` to become unusable.
<ide>
<ide> ```js
<ide> not own its underlying `ArrayBuffer`. An `ArrayBuffer` must not
<ide> be transferred unless it is known that the `Buffer` instance
<ide> owns it. In particular, for `Buffer`s created from the internal
<ide> `Buffer` pool (using, for instance `Buffer.from()` or `Buffer.alloc()`),
<del>transferring them is not possible and they will always be cloned,
<add>transferring them is not possible and they are always cloned,
<ide> which sends a copy of the entire `Buffer` pool.
<ide> This behavior may come with unintended higher memory
<ide> usage and possible security concerns.
<ide> See [`Buffer.allocUnsafe()`][] for more details on `Buffer` pooling.
<ide>
<ide> The `ArrayBuffer`s for `Buffer` instances created using
<ide> `Buffer.alloc()` or `Buffer.allocUnsafeSlow()` can always be
<del>transferred but doing so will render all other existing views of
<add>transferred but doing so renders all other existing views of
<ide> those `ArrayBuffer`s unusable.
<ide>
<ide> ### `port.ref()`
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> -->
<ide>
<del>Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port will
<add>Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does
<ide> *not* let the program exit if it's the only active handle left (the default
<del>behavior). If the port is `ref()`ed, calling `ref()` again will have no effect.
<add>behavior). If the port is `ref()`ed, calling `ref()` again has no effect.
<ide>
<del>If listeners are attached or removed using `.on('message')`, the port will
<del>be `ref()`ed and `unref()`ed automatically depending on whether
<add>If listeners are attached or removed using `.on('message')`, the port
<add>is `ref()`ed and `unref()`ed automatically depending on whether
<ide> listeners for the event exist.
<ide>
<ide> ### `port.start()`
<ide> added: v10.5.0
<ide> -->
<ide>
<ide> Starts receiving messages on this `MessagePort`. When using this port
<del>as an event emitter, this will be called automatically once `'message'`
<add>as an event emitter, this is called automatically once `'message'`
<ide> listeners are attached.
<ide>
<ide> This method exists for parity with the Web `MessagePort` API. In Node.js,
<ide> it is only useful for ignoring messages when no event listener is present.
<del>Node.js also diverges in its handling of `.onmessage`. Setting it will
<del>automatically call `.start()`, but unsetting it will let messages queue up
<add>Node.js also diverges in its handling of `.onmessage`. Setting it
<add>automatically calls `.start()`, but unsetting it lets messages queue up
<ide> until a new handler is set or the port is discarded.
<ide>
<ide> ### `port.unref()`
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> -->
<ide>
<del>Calling `unref()` on a port will allow the thread to exit if this is the only
<add>Calling `unref()` on a port allows the thread to exit if this is the only
<ide> active handle in the event system. If the port is already `unref()`ed calling
<del>`unref()` again will have no effect.
<add>`unref()` again has no effect.
<ide>
<del>If listeners are attached or removed using `.on('message')`, the port will
<del>be `ref()`ed and `unref()`ed automatically depending on whether
<add>If listeners are attached or removed using `.on('message')`, the port is
<add>`ref()`ed and `unref()`ed automatically depending on whether
<ide> listeners for the event exist.
<ide>
<ide> ## Class: `Worker`
<ide> Notable differences inside a Worker environment are:
<ide> * [`process.chdir()`][] and `process` methods that set group or user ids
<ide> are not available.
<ide> * [`process.env`][] is a copy of the parent thread's environment variables,
<del> unless otherwise specified. Changes to one copy will not be visible in other
<del> threads, and will not be visible to native add-ons (unless
<del> [`worker.SHARE_ENV`][] has been passed as the `env` option to the
<add> unless otherwise specified. Changes to one copy are not visible in other
<add> threads, and are not visible to native add-ons (unless
<add> [`worker.SHARE_ENV`][] is passed as the `env` option to the
<ide> [`Worker`][] constructor).
<ide> * [`process.title`][] cannot be modified.
<del>* Signals will not be delivered through [`process.on('...')`][Signals events].
<add>* Signals are not delivered through [`process.on('...')`][Signals events].
<ide> * Execution may stop at any point as a result of [`worker.terminate()`][]
<ide> being invoked.
<ide> * IPC channels from parent processes are not accessible.
<ide> changes:
<ide> * `options` {Object}
<ide> * `argv` {any[]} List of arguments which would be stringified and appended to
<ide> `process.argv` in the worker. This is mostly similar to the `workerData`
<del> but the values will be available on the global `process.argv` as if they
<add> but the values are available on the global `process.argv` as if they
<ide> were passed as CLI options to the script.
<ide> * `env` {Object} If set, specifies the initial value of `process.env` inside
<ide> the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used
<ide> to specify that the parent thread and the child thread should share their
<ide> environment variables; in that case, changes to one thread’s `process.env`
<del> object will affect the other thread as well. **Default:** `process.env`.
<add> object affect the other thread as well. **Default:** `process.env`.
<ide> * `eval` {boolean} If `true` and the first argument is a `string`, interpret
<ide> the first argument to the constructor as a script that is executed once the
<ide> worker is online.
<ide> * `execArgv` {string[]} List of node CLI options passed to the worker.
<ide> V8 options (such as `--max-old-space-size`) and options that affect the
<del> process (such as `--title`) are not supported. If set, this will be provided
<del> as [`process.execArgv`][] inside the worker. By default, options will be
<add> process (such as `--title`) are not supported. If set, this is provided
<add> as [`process.execArgv`][] inside the worker. By default, options are
<ide> inherited from the parent thread.
<del> * `stdin` {boolean} If this is set to `true`, then `worker.stdin` will
<del> provide a writable stream whose contents will appear as `process.stdin`
<add> * `stdin` {boolean} If this is set to `true`, then `worker.stdin`
<add> provides a writable stream whose contents appear as `process.stdin`
<ide> inside the Worker. By default, no data is provided.
<del> * `stdout` {boolean} If this is set to `true`, then `worker.stdout` will
<del> not automatically be piped through to `process.stdout` in the parent.
<del> * `stderr` {boolean} If this is set to `true`, then `worker.stderr` will
<del> not automatically be piped through to `process.stderr` in the parent.
<del> * `workerData` {any} Any JavaScript value that will be cloned and made
<del> available as [`require('worker_threads').workerData`][]. The cloning will
<del> occur as described in the [HTML structured clone algorithm][], and an error
<del> will be thrown if the object cannot be cloned (e.g. because it contains
<add> * `stdout` {boolean} If this is set to `true`, then `worker.stdout` is
<add> not automatically piped through to `process.stdout` in the parent.
<add> * `stderr` {boolean} If this is set to `true`, then `worker.stderr` is
<add> not automatically piped through to `process.stderr` in the parent.
<add> * `workerData` {any} Any JavaScript value that is cloned and made
<add> available as [`require('worker_threads').workerData`][]. The cloning
<add> occurs as described in the [HTML structured clone algorithm][], and an error
<add> is thrown if the object cannot be cloned (e.g. because it contains
<ide> `function`s).
<del> * `trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker will
<del> track raw file descriptors managed through [`fs.open()`][] and
<del> [`fs.close()`][], and close them when the Worker exits, similar to other
<add> * `trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker
<add> tracks raw file descriptors managed through [`fs.open()`][] and
<add> [`fs.close()`][], and closes them when the Worker exits, similar to other
<ide> resources like network sockets or file descriptors managed through
<ide> the [`FileHandle`][] API. This option is automatically inherited by all
<ide> nested `Worker`s. **Default**: `true`.
<ide> * `transferList` {Object[]} If one or more `MessagePort`-like objects
<ide> are passed in `workerData`, a `transferList` is required for those
<del> items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown.
<add> items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown.
<ide> See [`port.postMessage()`][] for more information.
<ide> * `resourceLimits` {Object} An optional set of resource limits for the new
<del> JS engine instance. Reaching these limits will lead to termination of the
<add> JS engine instance. Reaching these limits leads to termination of the
<ide> `Worker` instance. These limits only affect the JS engine, and no external
<ide> data, including no `ArrayBuffer`s. Even if these limits are set, the process
<ide> may still abort if it encounters a global out-of-memory situation.
<ide> added: v10.5.0
<ide> * `err` {Error}
<ide>
<ide> The `'error'` event is emitted if the worker thread throws an uncaught
<del>exception. In that case, the worker will be terminated.
<add>exception. In that case, the worker is terminated.
<ide>
<ide> ### Event: `'exit'`
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> * `exitCode` {integer}
<ide>
<ide> The `'exit'` event is emitted once the worker has stopped. If the worker
<del>exited by calling [`process.exit()`][], the `exitCode` parameter will be the
<del>passed exit code. If the worker was terminated, the `exitCode` parameter will
<del>be `1`.
<add>exited by calling [`process.exit()`][], the `exitCode` parameter is the
<add>passed exit code. If the worker was terminated, the `exitCode` parameter is
<add>`1`.
<ide>
<ide> This is the final event emitted by any `Worker` instance.
<ide>
<ide> The `'message'` event is emitted when the worker thread has invoked
<ide> [`require('worker_threads').parentPort.postMessage()`][].
<ide> See the [`port.on('message')`][] event for more details.
<ide>
<del>All messages sent from the worker thread will be emitted before the
<add>All messages sent from the worker thread are emitted before the
<ide> [`'exit'` event][] is emitted on the `Worker` object.
<ide>
<ide> ### Event: `'messageerror'`
<ide> Returns a readable stream for a V8 snapshot of the current state of the Worker.
<ide> See [`v8.getHeapSnapshot()`][] for more details.
<ide>
<ide> If the Worker thread is no longer running, which may occur before the
<del>[`'exit'` event][] is emitted, the returned `Promise` will be rejected
<add>[`'exit'` event][] is emitted, the returned `Promise` is rejected
<ide> immediately with an [`ERR_WORKER_NOT_RUNNING`][] error.
<ide>
<ide> ### `worker.performance`
<ide> The same call as [`perf_hooks` `eventLoopUtilization()`][], except the values
<ide> of the worker instance are returned.
<ide>
<ide> One difference is that, unlike the main thread, bootstrapping within a worker
<del>is done within the event loop. So the event loop utilization will be
<add>is done within the event loop. So the event loop utilization is
<ide> immediately available once the worker's script begins execution.
<ide>
<ide> An `idle` time that does not increase does not indicate that the worker is
<ide> stuck in bootstrap. The following examples shows how the worker's entire
<del>lifetime will never accumulate any `idle` time, but is still be able to process
<add>lifetime never accumulates any `idle` time, but is still be able to process
<ide> messages.
<ide>
<ide> ```js
<ide> added: v10.5.0
<ide> * `value` {any}
<ide> * `transferList` {Object[]}
<ide>
<del>Send a message to the worker that will be received via
<add>Send a message to the worker that is received via
<ide> [`require('worker_threads').parentPort.on('message')`][].
<ide> See [`port.postMessage()`][] for more details.
<ide>
<ide> See [`port.postMessage()`][] for more details.
<ide> added: v10.5.0
<ide> -->
<ide>
<del>Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker will
<add>Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does
<ide> *not* let the program exit if it's the only active handle left (the default
<del>behavior). If the worker is `ref()`ed, calling `ref()` again will have
<add>behavior). If the worker is `ref()`ed, calling `ref()` again has
<ide> no effect.
<ide>
<ide> ### `worker.resourceLimits`
<ide> added: v10.5.0
<ide>
<ide> This is a readable stream which contains data written to [`process.stderr`][]
<ide> inside the worker thread. If `stderr: true` was not passed to the
<del>[`Worker`][] constructor, then data will be piped to the parent thread's
<add>[`Worker`][] constructor, then data is piped to the parent thread's
<ide> [`process.stderr`][] stream.
<ide>
<ide> ### `worker.stdin`
<ide> added: v10.5.0
<ide>
<ide> This is a readable stream which contains data written to [`process.stdout`][]
<ide> inside the worker thread. If `stdout: true` was not passed to the
<del>[`Worker`][] constructor, then data will be piped to the parent thread's
<add>[`Worker`][] constructor, then data is piped to the parent thread's
<ide> [`process.stdout`][] stream.
<ide>
<ide> ### `worker.terminate()`
<ide> This value is unique for each `Worker` instance inside a single process.
<ide> added: v10.5.0
<ide> -->
<ide>
<del>Calling `unref()` on a worker will allow the thread to exit if this is the only
<add>Calling `unref()` on a worker allows the thread to exit if this is the only
<ide> active handle in the event system. If the worker is already `unref()`ed calling
<del>`unref()` again will have no effect.
<add>`unref()` again has no effect.
<ide>
<ide> [Addons worker support]: addons.md#addons_worker_support
<ide> [ECMAScript module loader]: esm.md#esm_data_imports | 1 |
Go | Go | use ioctls to create bridge | 885056b2439a1a978be2b7df02c6c04c82694d94 | <ide><path>libnetwork/drivers/bridge/setup_device.go
<ide> package bridge
<ide>
<ide> import (
<del> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<del> "github.com/docker/libnetwork/netutils"
<del> "github.com/docker/libnetwork/types"
<add> bri "github.com/docker/libcontainer/netlink"
<ide> "github.com/vishvananda/netlink"
<ide> )
<ide>
<ide> // SetupDevice create a new bridge interface/
<ide> func setupDevice(config *networkConfiguration, i *bridgeInterface) error {
<add> var setMac bool
<add>
<ide> // We only attempt to create the bridge when the requested device name is
<ide> // the default one.
<ide> if config.BridgeName != DefaultBridgeName && !config.AllowNonDefaultBridge {
<ide> func setupDevice(config *networkConfiguration, i *bridgeInterface) error {
<ide> // was not supported before that.
<ide> kv, err := kernel.GetKernelVersion()
<ide> if err == nil && (kv.Kernel >= 3 && kv.Major >= 3) {
<del> i.Link.Attrs().HardwareAddr = netutils.GenerateRandomMAC()
<del> log.Debugf("Setting bridge mac address to %s", i.Link.Attrs().HardwareAddr)
<add> setMac = true
<ide> }
<ide>
<del> // Call out to netlink to create the device.
<del> if err = netlink.LinkAdd(i.Link); err != nil {
<del> return types.InternalErrorf("Failed to program bridge link: %s", err.Error())
<del> }
<del> return nil
<add> return bri.CreateBridge(config.BridgeName, setMac)
<ide> }
<ide>
<ide> // SetupDeviceUp ups the given bridge interface. | 1 |
Text | Text | add beta installation instruction | 418cc210fab3a49820ac2781c184397a4c8a02f4 | <ide><path>readme.md
<ide> Next.js is a minimalistic framework for server-rendered React applications.
<ide>
<ide> Install it:
<ide>
<add>#### Beta
<add>
<add>The beta has support for the latest version of React (v16) and is actively being developed upon.
<add>
<add>```bash
<add>npm install next@beta react react-dom
<add>```
<add>
<add>#### Stable
<add>
<add>This is the stable version of Next.js
<add>
<ide> ```bash
<del>npm install next react react-dom --save
<add>npm install next react@15 react-dom@15 --save
<ide> ```
<ide>
<ide> and add a script to your package.json like this: | 1 |
Go | Go | replace uses of deprecated iserr...notfound() | 919726b5dbf7f063f82eac2f5384966fc7271710 | <ide><path>client/checkpoint_list_test.go
<ide> func TestCheckpointListContainerNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, err := client.CheckpointList(context.Background(), "unknown", types.CheckpointListOptions{})
<del> if err == nil || !IsErrContainerNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a containerNotFound error, got %v", err)
<ide> }
<ide> }
<ide><path>client/config_inspect_test.go
<ide> func TestConfigInspectConfigNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, _, err := client.ConfigInspectWithRaw(context.Background(), "unknown")
<del> if err == nil || !IsErrConfigNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a configNotFoundError error, got %v", err)
<ide> }
<ide> }
<ide> func TestConfigInspect(t *testing.T) {
<ide> version: "1.30",
<ide> client: newMockClient(func(req *http.Request) (*http.Response, error) {
<ide> if !strings.HasPrefix(req.URL.Path, expectedURL) {
<del> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
<add> return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, req.URL)
<ide> }
<ide> content, err := json.Marshal(swarm.Config{
<ide> ID: "config_id",
<ide><path>client/container_create_test.go
<ide> func TestContainerCreateImageNotFound(t *testing.T) {
<ide> client: newMockClient(errorMock(http.StatusNotFound, "No such image")),
<ide> }
<ide> _, err := client.ContainerCreate(context.Background(), &container.Config{Image: "unknown_image"}, nil, nil, "unknown")
<del> if err == nil || !IsErrImageNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected an imageNotFound error, got %v", err)
<ide> }
<ide> }
<ide><path>client/container_inspect_test.go
<ide> func TestContainerInspectContainerNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, err := client.ContainerInspect(context.Background(), "unknown")
<del> if err == nil || !IsErrContainerNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a containerNotFound error, got %v", err)
<ide> }
<ide> }
<ide><path>client/image_inspect_test.go
<ide> func TestImageInspectImageNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, _, err := client.ImageInspectWithRaw(context.Background(), "unknown")
<del> if err == nil || !IsErrImageNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected an imageNotFound error, got %v", err)
<ide> }
<ide> }
<ide><path>client/node_inspect_test.go
<ide> func TestNodeInspectNodeNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, _, err := client.NodeInspectWithRaw(context.Background(), "unknown")
<del> if err == nil || !IsErrNodeNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a nodeNotFoundError error, got %v", err)
<ide> }
<ide> }
<ide><path>client/secret_inspect_test.go
<ide> func TestSecretInspectSecretNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, _, err := client.SecretInspectWithRaw(context.Background(), "unknown")
<del> if err == nil || !IsErrSecretNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a secretNotFoundError error, got %v", err)
<ide> }
<ide> }
<ide><path>client/service_inspect_test.go
<ide> func TestServiceInspectServiceNotFound(t *testing.T) {
<ide> }
<ide>
<ide> _, _, err := client.ServiceInspectWithRaw(context.Background(), "unknown", types.ServiceInspectOptions{})
<del> if err == nil || !IsErrServiceNotFound(err) {
<add> if err == nil || !IsErrNotFound(err) {
<ide> t.Fatalf("expected a serviceNotFoundError error, got %v", err)
<ide> }
<ide> } | 8 |
Text | Text | use json instead of coffeescript in code block | def2001eb626515c39b09d0c48ba9827a2e58ace | <ide><path>docs/your-first-package.md
<ide> Now we need to convert the selected text to ascii art. To do this we will use
<ide> the [figlet node module](https://npmjs.org/package/figlet) from NPM. Open
<ide> _package.json_ add the latest version of figlet to the dependencies:
<ide>
<del>```coffeescript
<add>```json
<ide> "dependencies": {
<ide> "figlet": "1.0.8"
<ide> } | 1 |
Text | Text | update github url for vim syntax plugin | adaed9b6f7204d00a2153323f26d747583027cc8 | <ide><path>contrib/syntax/vim/README.md
<ide> Installation
<ide> With [pathogen](https://github.com/tpope/vim-pathogen), the usual way...
<ide>
<ide> With [Vundle](https://github.com/gmarik/Vundle.vim)
<del>
<del> Plugin 'docker/docker' , {'rtp': '/contrib/syntax/vim/'}
<add>
<add> Plugin 'moby/moby' , {'rtp': '/contrib/syntax/vim/'}
<ide>
<ide> With [vim-plug](https://github.com/junegunn/vim-plug)
<del>
<del> Plug 'docker/docker' , {'rtp': '/contrib/syntax/vim/'}
<add>
<add> Plug 'moby/moby' , {'rtp': '/contrib/syntax/vim/'}
<ide>
<ide> Features
<ide> -------- | 1 |
Ruby | Ruby | run railties tests in parallel, default to 2 cores | 265f13495fb326bd2e6a5bc9cae7e297e42893d0 | <ide><path>activesupport/lib/active_support/testing/isolation.rb
<ide> def method_missing(name, *args)
<ide> end
<ide>
<ide> module Isolation
<add> require 'thread'
<add>
<add> class ParallelEach
<add> include Enumerable
<add>
<add> # default to 2 cores
<add> CORES = ENV['TEST_CORES'] || 2
<add>
<add> def initialize list
<add> @list = list
<add> @queue = SizedQueue.new CORES
<add> end
<add>
<add> def grep pattern
<add> self.class.new super
<add> end
<add>
<add> def each
<add> threads = CORES.times.map {
<add> Thread.new {
<add> while job = @queue.pop
<add> yield job
<add> end
<add> }
<add> }
<add> @list.each { |i| @queue << i }
<add> CORES.times { @queue << nil }
<add> threads.each(&:join)
<add> end
<add> end
<add>
<add> def self.included klass
<add> klass.extend(Module.new {
<add> def test_methods
<add> ParallelEach.new super
<add> end
<add> })
<add> end
<add>
<ide> def self.forking_env?
<ide> !ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
<ide> end
<ide><path>railties/test/isolation/abstract_unit.rb
<ide>
<ide> module TestHelpers
<ide> module Paths
<del> module_function
<del>
<ide> def app_template_path
<ide> File.join Dir.tmpdir, 'app_template'
<ide> end | 2 |
Ruby | Ruby | clarify example of the test [ci skip] | f54060916fbb5450cceedaf7187e8e6bed5d44a3 | <ide><path>actionpack/lib/action_dispatch/testing/test_process.rb
<ide> module TestProcess
<ide> module FixtureFile
<ide> # Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionDispatch::IntegrationTest.fixture_path, path), type)</tt>:
<ide> #
<del> # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
<add> # post :change_avatar, params: { avatar: fixture_file_upload('files/spongebob.png', 'image/png') }
<ide> #
<ide> # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
<ide> # This will not affect other platforms:
<ide> #
<del> # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary)
<add> # post :change_avatar, params: { avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary) }
<ide> def fixture_file_upload(path, mime_type = nil, binary = false)
<ide> if self.class.respond_to?(:fixture_path) && self.class.fixture_path &&
<ide> !File.exist?(path) | 1 |
Javascript | Javascript | ignore any pending data when worker is terminated | 8d15ecb14b8b5fb451907b79ad369118325a255c | <ide><path>src/display/api.js
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> }, this);
<ide>
<ide> messageHandler.on('commonobj', function transportObj(data) {
<add> if (this.destroyed) {
<add> return; // Ignore any pending requests if the worker was terminated.
<add> }
<add>
<ide> var id = data[0];
<ide> var type = data[1];
<ide> if (this.commonObjs.hasData(id)) {
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> }, this);
<ide>
<ide> messageHandler.on('obj', function transportObj(data) {
<add> if (this.destroyed) {
<add> return; // Ignore any pending requests if the worker was terminated.
<add> }
<add>
<ide> var id = data[0];
<ide> var pageIndex = data[1];
<ide> var type = data[2];
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> }, this);
<ide>
<ide> messageHandler.on('DocProgress', function transportDocProgress(data) {
<add> if (this.destroyed) {
<add> return; // Ignore any pending requests if the worker was terminated.
<add> }
<add>
<ide> var loadingTask = this.loadingTask;
<ide> if (loadingTask.onProgress) {
<ide> loadingTask.onProgress({
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> }, this);
<ide>
<ide> messageHandler.on('PageError', function transportError(data) {
<add> if (this.destroyed) {
<add> return; // Ignore any pending requests if the worker was terminated.
<add> }
<add>
<ide> var page = this.pageCache[data.pageNum - 1];
<ide> var intentState = page.intentStates[data.intent];
<ide> if (intentState.displayReadyCapability) {
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> }, this);
<ide>
<ide> messageHandler.on('JpegDecode', function(data) {
<add> if (this.destroyed) {
<add> return Promise.reject('Worker was terminated');
<add> }
<add>
<ide> var imageUrl = data[0];
<ide> var components = data[1];
<ide> if (components !== 3 && components !== 1) {
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> };
<ide> img.src = imageUrl;
<ide> });
<del> });
<add> }, this);
<ide> },
<ide>
<ide> fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) { | 1 |
PHP | PHP | remove empty comments | aaefef40a55f85296756c7348f9d42518d492015 | <ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> public function baseNameValueProvider()
<ide> ['نام فارسی.txt', null, true],
<ide> ['/نام.txt', null, true],
<ide> ['/نام فارسی.txt', null, true],
<del> //
<ide> ['folder/نام.txt', 'txt', false],
<ide> ['folder/نام فارسی.txt', 'txt', false],
<ide> ['نام.txt', 'txt', true],
<ide> ['نام فارسی.txt', 'txt', true],
<ide> ['/نام.txt', 'txt', true],
<ide> ['/نام فارسی.txt', 'txt', true],
<del> //
<ide> ['abcde.ab', 'abe', false],
<ide> ['/etc/sudoers.d', null, true],
<ide> ['/etc/.d', 'd', true], | 1 |
Javascript | Javascript | add types and fix incorrect loc type | b93225a6a120a4155c118a0c1a5f4b0823863c41 | <ide><path>lib/Dependency.js
<ide> const DependencyReference = require("./dependencies/DependencyReference");
<ide> */
<ide>
<ide> /** @typedef {Object} SourcePosition
<del> * @property {number} column
<ide> * @property {number} line
<add> * @property {number=} column
<ide> */
<ide>
<ide> /** @typedef {Object} RealDependencyLocation
<ide> * @property {SourcePosition} start
<del> * @property {SourcePosition} end
<add> * @property {SourcePosition=} end
<ide> * @property {number=} index
<ide> */
<ide>
<ide> /** @typedef {Object} SynteticDependencyLocation
<ide> * @property {string} name
<del> * @property {number} index
<add> * @property {number=} index
<ide> */
<ide>
<ide> /** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */
<ide><path>lib/SingleEntryPlugin.js
<ide> class SingleEntryPlugin {
<ide> );
<ide> }
<ide>
<add> /**
<add> * @param {string} entry entry request
<add> * @param {string} name entry name
<add> * @returns {SingleEntryDependency} the dependency
<add> */
<ide> static createDependency(entry, name) {
<ide> const dep = new SingleEntryDependency(entry);
<del> dep.loc = name;
<add> dep.loc = { name };
<ide> return dep;
<ide> }
<ide> }
<ide><path>lib/dependencies/LoaderPlugin.js
<ide> const LoaderDependency = require("./LoaderDependency");
<ide> const NormalModule = require("../NormalModule");
<ide>
<add>/** @typedef {import("../Module")} Module */
<add>
<add>/**
<add> * @callback LoadModuleCallback
<add> * @param {Error=} err error object
<add> * @param {string=} source source code
<add> * @param {object=} map source map
<add> * @param {Module=} module loaded module if successful
<add> */
<add>
<ide> class LoaderPlugin {
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap(
<ide> class LoaderPlugin {
<ide> compilation.hooks.normalModuleLoader.tap(
<ide> "LoaderPlugin",
<ide> (loaderContext, module) => {
<add> /**
<add> * @param {string} request the request string to load the module from
<add> * @param {LoadModuleCallback} callback callback returning the loaded module or error
<add> * @returns {void}
<add> */
<ide> loaderContext.loadModule = (request, callback) => {
<ide> const dep = new LoaderDependency(request);
<del> dep.loc = request;
<add> dep.loc = {
<add> name: request
<add> };
<ide> const factory = compilation.dependencyFactories.get(
<ide> dep.constructor
<ide> );
<ide><path>lib/formatLocation.js
<ide>
<ide> "use strict";
<ide>
<add>/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
<add>/** @typedef {import("./Dependency").SourcePosition} SourcePosition */
<add>
<add>// TODO webpack 5: pos must be SourcePosition
<add>/**
<add> * @param {SourcePosition|DependencyLocation|string} pos position
<add> * @returns {string} formatted position
<add> */
<ide> const formatPosition = pos => {
<ide> if (pos === null) return "";
<del> const typeOfPos = typeof pos;
<del> switch (typeOfPos) {
<del> case "string":
<del> return pos;
<del> case "number":
<del> return `${pos}`;
<del> case "object":
<del> if (typeof pos.line === "number" && typeof pos.column === "number") {
<del> return `${pos.line}:${pos.column}`;
<del> } else if (typeof pos.line === "number") {
<del> return `${pos.line}:?`;
<del> } else if (typeof pos.index === "number") {
<del> return `+${pos.index}`;
<del> } else {
<del> return "";
<del> }
<del> default:
<add> // TODO webpack 5: Simplify this
<add> if (typeof pos === "string") return pos;
<add> if (typeof pos === "number") return `${pos}`;
<add> if (typeof pos === "object") {
<add> if ("line" in pos && "column" in pos) {
<add> return `${pos.line}:${pos.column}`;
<add> } else if ("line" in pos) {
<add> return `${pos.line}:?`;
<add> } else if ("index" in pos) {
<add> // TODO webpack 5 remove this case
<add> return `+${pos.index}`;
<add> } else {
<ide> return "";
<add> }
<ide> }
<add> return "";
<ide> };
<ide>
<add>// TODO webpack 5: loc must be DependencyLocation
<add>/**
<add> * @param {DependencyLocation|SourcePosition|string} loc location
<add> * @returns {string} formatted location
<add> */
<ide> const formatLocation = loc => {
<ide> if (loc === null) return "";
<del> const typeOfLoc = typeof loc;
<del> switch (typeOfLoc) {
<del> case "string":
<del> return loc;
<del> case "number":
<del> return `${loc}`;
<del> case "object":
<del> if (loc.start && loc.end) {
<del> if (
<del> typeof loc.start.line === "number" &&
<del> typeof loc.end.line === "number" &&
<del> typeof loc.end.column === "number" &&
<del> loc.start.line === loc.end.line
<del> ) {
<del> return `${formatPosition(loc.start)}-${loc.end.column}`;
<del> } else {
<del> return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
<del> }
<del> }
<del> if (loc.start) {
<del> return formatPosition(loc.start);
<add> // TODO webpack 5: Simplify this
<add> if (typeof loc === "string") return loc;
<add> if (typeof loc === "number") return `${loc}`;
<add> if (typeof loc === "object") {
<add> if ("start" in loc && loc.start && "end" in loc && loc.end) {
<add> if (
<add> typeof loc.start === "object" &&
<add> typeof loc.start.line === "number" &&
<add> typeof loc.end === "object" &&
<add> typeof loc.end.line === "number" &&
<add> typeof loc.end.column === "number" &&
<add> loc.start.line === loc.end.line
<add> ) {
<add> return `${formatPosition(loc.start)}-${loc.end.column}`;
<add> } else {
<add> return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
<ide> }
<del> return formatPosition(loc);
<del> default:
<del> return "";
<add> }
<add> if ("start" in loc && loc.start) {
<add> return formatPosition(loc.start);
<add> }
<add> if ("name" in loc && "index" in loc) {
<add> return `${loc.name}[${loc.index}]`;
<add> }
<add> if ("name" in loc) {
<add> return loc.name;
<add> }
<add> return formatPosition(loc);
<ide> }
<add> return "";
<ide> };
<ide>
<ide> module.exports = formatLocation; | 4 |
Javascript | Javascript | add a util function for tostring'ing objects | f9b99cdc0cacbeb6d6105cdc9ff0af9395bcf873 | <ide><path>packages/ember-metal/lib/utils.js
<ide> export function tryInvoke(obj, methodName, args) {
<ide> // TYPING & ARRAY MESSAGING
<ide> //
<ide>
<del>var toString = Object.prototype.toString;
<add>var objectToString = Object.prototype.toString;
<ide>
<ide> /**
<ide> Forces the passed object to be part of an array. If the object is already
<ide> export function inspect(obj) {
<ide> return '' + obj;
<ide> }
<ide> // overridden toString
<del> if (typeof obj.toString === 'function' && obj.toString !== toString) {
<add> if (typeof obj.toString === 'function' && obj.toString !== objectToString) {
<ide> return obj.toString();
<ide> }
<ide>
<ide> export function inspect(obj) {
<ide> if (typeof v === 'function') { v = 'function() { ... }'; }
<ide>
<ide> if (v && typeof v.toString !== 'function') {
<del> ret.push(key + ': ' + toString.call(v));
<add> ret.push(key + ': ' + objectToString.call(v));
<ide> } else {
<ide> ret.push(key + ': ' + v);
<ide> }
<ide> export function lookupDescriptor(obj, keyName) {
<ide> return null;
<ide> }
<ide>
<add>// A `toString` util function that supports objects without a `toString`
<add>// method, e.g. an object created with `Object.create(null)`.
<add>export function toString(obj) {
<add> if (obj && obj.toString) {
<add> return obj.toString();
<add> } else {
<add> return objectToString.call(obj);
<add> }
<add>}
<add>
<ide> export {
<ide> GUID_KEY,
<ide> makeArray,
<ide><path>packages/ember-metal/tests/utils_test.js
<del>import { inspect, checkHasSuper } from 'ember-metal/utils';
<ide> import environment from 'ember-metal/environment';
<add>import {
<add> inspect,
<add> checkHasSuper,
<add> toString
<add>} from 'ember-metal/utils';
<ide>
<ide> QUnit.module('Ember Metal Utils');
<ide>
<ide> if (environment.isPhantom || environment.isChrome || environment.isFirefox) {
<ide> assert.notOk(checkHasSuper(function() {}), 'empty function does not have super');
<ide> });
<ide> }
<add>
<add>QUnit.test("toString uses an object's toString method when available", function() {
<add> let obj = {
<add> toString() {
<add> return "bob";
<add> }
<add> };
<add>
<add> strictEqual(toString(obj), 'bob');
<add>});
<add>
<add>
<add>QUnit.test("toString falls back to Object.prototype.toString", function() {
<add> let obj = Object.create(null);
<add>
<add> strictEqual(toString(obj), {}.toString());
<add>}); | 2 |
Python | Python | enable task run setting to be able reinitialise | 2ba2753304461c2db46a7734ef5944e9a4d1e2b5 | <ide><path>airflow/settings.py
<ide> SQL_ALCHEMY_CONN: Optional[str] = None
<ide> PLUGINS_FOLDER: Optional[str] = None
<ide> LOGGING_CLASS_PATH: Optional[str] = None
<add>DONOT_MODIFY_HANDLERS: Optional[bool] = None
<ide> DAGS_FOLDER: str = os.path.expanduser(conf.get('core', 'DAGS_FOLDER'))
<ide>
<ide> engine: Optional[Engine] = None
<ide> def configure_vars():
<ide> global SQL_ALCHEMY_CONN
<ide> global DAGS_FOLDER
<ide> global PLUGINS_FOLDER
<add> global DONOT_MODIFY_HANDLERS
<ide> SQL_ALCHEMY_CONN = conf.get('core', 'SQL_ALCHEMY_CONN')
<ide> DAGS_FOLDER = os.path.expanduser(conf.get('core', 'DAGS_FOLDER'))
<ide>
<ide> PLUGINS_FOLDER = conf.get('core', 'plugins_folder', fallback=os.path.join(AIRFLOW_HOME, 'plugins'))
<ide>
<add> # If donot_modify_handlers=True, we do not modify logging handlers in task_run command
<add> # If the flag is set to False, we remove all handlers from the root logger
<add> # and add all handlers from 'airflow.task' logger to the root Logger. This is done
<add> # to get all the logs from the print & log statements in the DAG files before a task is run
<add> # The handlers are restored after the task completes execution.
<add> DONOT_MODIFY_HANDLERS = conf.getboolean('logging', 'donot_modify_handlers', fallback=False)
<add>
<ide>
<ide> def configure_orm(disable_connection_pool=False):
<ide> """Configure ORM using SQLAlchemy"""
<ide> def initialize():
<ide> # read rate. This config controls when your DAGs are updated in the Webserver
<ide> MIN_SERIALIZED_DAG_FETCH_INTERVAL = conf.getint('core', 'min_serialized_dag_fetch_interval', fallback=10)
<ide>
<del># If donot_modify_handlers=True, we do not modify logging handlers in task_run command
<del># If the flag is set to False, we remove all handlers from the root logger
<del># and add all handlers from 'airflow.task' logger to the root Logger. This is done
<del># to get all the logs from the print & log statements in the DAG files before a task is run
<del># The handlers are restored after the task completes execution.
<del>DONOT_MODIFY_HANDLERS = conf.getboolean('logging', 'donot_modify_handlers', fallback=False)
<del>
<ide> CAN_FORK = hasattr(os, "fork")
<ide>
<ide> EXECUTE_TASKS_NEW_PYTHON_INTERPRETER = not CAN_FORK or conf.getboolean( | 1 |
Python | Python | fix md5 for windows | b190b1fa53426581ac6db9711b3fe24ddc42be63 | <ide><path>test/test.py
<ide> def verifyPDFs(manifestList):
<ide> for item in manifestList:
<ide> f = item['file']
<ide> if os.access(f, os.R_OK):
<del> fileMd5 = hashlib.md5(open(f).read()).hexdigest()
<add> fileMd5 = hashlib.md5(open(f, 'rb').read()).hexdigest()
<ide> if 'md5' not in item:
<ide> print 'ERROR: Missing md5 for file "' + f + '".',
<ide> print 'Hash for current file is "' + fileMd5 + '"' | 1 |
Javascript | Javascript | add currentview property to ember.containerview | 00b8940af1c948dd1974be184e022269a87a461d | <ide><path>packages/ember-views/lib/views/container_view.js
<ide> var childViewsProperty = Ember.computed(function() {
<ide> And the `Ember.View` instance stored in `aContainer.aView` will be removed from `aContainer`'s
<ide> `childViews` array.
<ide>
<del>
<ide> ## Templates and Layout
<ide> A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout`
<ide> property on a container view will not result in the template or layout being rendered.
<ide> The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML
<ide> of its child views.
<ide>
<add> ## Binding a View to Display
<add>
<add> If you would like to display a single view in your ContainerView, you can set its `currentView`
<add> property. When the `currentView` property is set to a view instance, it will be added to the
<add> ContainerView's `childViews` array. If the `currentView` property is later changed to a
<add> different view, the new view will replace the old view. If `currentView` is set to `null`, the
<add> last `currentView` will be removed.
<add>
<add> This functionality is useful for cases where you want to bind the display of a ContainerView to
<add> a controller or state manager. For example, you can bind the `currentView` of a container to
<add> a controller like this:
<add>
<add> // Controller
<add> App.appController = Ember.Object.create({
<add> view: Ember.View.create({
<add> templateName: 'person_template'
<add> })
<add> });
<add>
<add> // Handlebars template
<add> {{view Ember.ContainerView currentViewBinding="App.appController.view"}}
<add>
<ide> @extends Ember.View
<ide> */
<ide>
<ide> Ember.ContainerView = Ember.View.extend({
<ide> } else {
<ide> this.domManager.prepend(this, view);
<ide> }
<del> }
<add> },
<add>
<add> currentView: null,
<add>
<add> _currentViewWillChange: Ember.beforeObserver(function() {
<add> var childViews = get(this, 'childViews'),
<add> currentView = get(this, 'currentView');
<add>
<add> if (currentView) {
<add> childViews.removeObject(currentView);
<add> }
<add> }, 'currentView'),
<add>
<add> _currentViewDidChange: Ember.observer(function() {
<add> var childViews = get(this, 'childViews'),
<add> currentView = get(this, 'currentView');
<add>
<add> if (currentView) {
<add> childViews.pushObject(currentView);
<add> }
<add> }, 'currentView')
<ide> });
<ide>
<ide> // Ember.ContainerView extends the default view states to provide different
<ide><path>packages/ember-views/tests/views/container_view_test.js
<del>var get = Ember.get, getPath = Ember.getPath;
<add>var get = Ember.get, getPath = Ember.getPath, set = Ember.set;
<ide>
<ide> module("ember-views/views/container_view_test");
<ide>
<ide> test("should be able to insert views after the DOM representation is created", function() {
<ide> var container = Ember.ContainerView.create({
<ide> classNameBindings: ['name'],
<del>
<ide> name: 'foo'
<ide> });
<ide>
<ide> test("views that are removed from a ContainerView should have their child views
<ide> });
<ide> equal(getPath(view, 'childViews.length'), 0, "child views are cleared when removed from container view");
<ide> });
<add>
<add>test("if a ContainerView starts with an empy currentView, nothing is displayed", function() {
<add> var container = Ember.ContainerView.create();
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), '', "has a empty contents");
<add> equal(getPath(container, 'childViews.length'), 0, "should not have any child views");
<add>});
<add>
<add>test("if a ContainerView starts with a currentView, it is rendered as a child view", function() {
<add> var container = Ember.ContainerView.create();
<add> var mainView = Ember.View.create({
<add> template: function() {
<add> return "This is the main view.";
<add> }
<add> });
<add>
<add> set(container, 'currentView', mainView);
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), "This is the main view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), mainView, "should have the currentView as the only child view");
<add>});
<add>
<add>test("if a ContainerView starts with no currentView and then one is set, the ContainerView is updated", function() {
<add> var container = Ember.ContainerView.create();
<add> var mainView = Ember.View.create({
<add> template: function() {
<add> return "This is the main view.";
<add> }
<add> });
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), '', "has a empty contents");
<add> equal(getPath(container, 'childViews.length'), 0, "should not have any child views");
<add>
<add> Ember.run(function() {
<add> set(container, 'currentView', mainView);
<add> });
<add>
<add> equal(container.$().text(), "This is the main view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), mainView, "should have the currentView as the only child view");
<add>});
<add>
<add>test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated", function() {
<add> var container = Ember.ContainerView.create();
<add> var mainView = Ember.View.create({
<add> template: function() {
<add> return "This is the main view.";
<add> }
<add> });
<add> container.set('currentView', mainView);
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), "This is the main view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), mainView, "should have the currentView as the only child view");
<add>
<add> Ember.run(function() {
<add> set(container, 'currentView', null);
<add> });
<add>
<add> equal(container.$().text(), '', "has a empty contents");
<add> equal(getPath(container, 'childViews.length'), 0, "should not have any child views");
<add>});
<add>
<add>test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated", function() {
<add> var container = Ember.ContainerView.create();
<add> var mainView = Ember.View.create({
<add> template: function() {
<add> return "This is the main view.";
<add> }
<add> });
<add> container.set('currentView', mainView);
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), "This is the main view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), mainView, "should have the currentView as the only child view");
<add>
<add> Ember.run(function() {
<add> set(container, 'currentView', null);
<add> });
<add>
<add> equal(container.$().text(), '', "has a empty contents");
<add> equal(getPath(container, 'childViews.length'), 0, "should not have any child views");
<add>});
<add>
<add>test("if a ContainerView starts with a currentView and then a different currentView is set, the old view is removed and the new one is added", function() {
<add> var container = Ember.ContainerView.create();
<add> var mainView = Ember.View.create({
<add> template: function() {
<add> return "This is the main view.";
<add> }
<add> });
<add>
<add> var secondaryView = Ember.View.create({
<add> template: function() {
<add> return "This is the secondary view.";
<add> }
<add> });
<add>
<add> container.set('currentView', mainView);
<add>
<add> Ember.run(function() {
<add> container.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(container.$().text(), "This is the main view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), mainView, "should have the currentView as the only child view");
<add>
<add> Ember.run(function() {
<add> set(container, 'currentView', secondaryView);
<add> });
<add>
<add> equal(container.$().text(), "This is the secondary view.", "should render its child");
<add> equal(getPath(container, 'childViews.length'), 1, "should have one child view");
<add> equal(getPath(container, 'childViews').objectAt(0), secondaryView, "should have the currentView as the only child view");
<add>}); | 2 |
Python | Python | prepare tools/specialize_node_d.py for python 3 | 7468c56742a726e18b0b6583d0ce9c6b50f2bce0 | <ide><path>tools/specialize_node_d.py
<ide>
<ide> if len(sys.argv) != 5:
<ide> print("usage: specialize_node_d.py outfile src/node.d flavor arch")
<del> sys.exit(2);
<add> sys.exit(2)
<ide>
<del>outfile = file(sys.argv[1], 'w');
<del>infile = file(sys.argv[2], 'r');
<del>flavor = sys.argv[3];
<del>arch = sys.argv[4];
<add>outfile = open(sys.argv[1], 'w')
<add>infile = open(sys.argv[2], 'r')
<add>flavor = sys.argv[3]
<add>arch = sys.argv[4]
<ide>
<ide> model = r'curpsinfo->pr_dmodel == PR_MODEL_ILP32'
<ide>
<ide> for line in infile:
<ide> if flavor == 'freebsd':
<del> line = re.sub('procfs.d', 'psinfo.d', line);
<add> line = re.sub('procfs.d', 'psinfo.d', line)
<ide> if arch == 'x64':
<del> line = re.sub(model, '0', line);
<add> line = re.sub(model, '0', line)
<ide> else:
<del> line = re.sub(model, '1', line);
<del> outfile.write(line);
<add> line = re.sub(model, '1', line)
<add> outfile.write(line) | 1 |
Javascript | Javascript | handle empty cert in checkserverindentity | f1810ed1b86cbbe5560a96839f5320b4be6ec5f7 | <ide><path>lib/tls.js
<ide> exports.checkServerIdentity = function checkServerIdentity(host, cert) {
<ide> host,
<ide> ips.join(', '));
<ide> }
<del> } else {
<add> } else if (cert.subject) {
<ide> // Transform hostname to canonical form
<ide> if (!/\.$/.test(host)) host += '.';
<ide>
<ide> exports.checkServerIdentity = function checkServerIdentity(host, cert) {
<ide> cert.subject.CN);
<ide> }
<ide> }
<add> } else {
<add> reason = 'Cert is empty';
<ide> }
<ide>
<ide> if (!valid) {
<ide><path>test/parallel/test-tls-check-server-identity.js
<ide> var tests = [
<ide> 'DNS:omg.com'
<ide> },
<ide>
<add> // Empty Cert
<add> {
<add> host: 'a.com',
<add> cert: { },
<add> error: 'Cert is empty'
<add> },
<add>
<ide> // Multiple CN fields
<ide> {
<ide> host: 'foo.com', cert: { | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.