content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | remove redundant warning information | 5242114d89652a217880c0a0f216bf46a51c1379 | <ide><path>doc/api/process.md
<ide> $ node --no-warnings
<ide> The `--trace-warnings` command-line option can be used to have the default
<ide> console output for warnings include the full stack trace of the warning.
<ide>
<del>#### Emitting custom warnings
<del>
<del>The [`process.emitWarning()`][process_emit_warning] method can be used to issue
<del>custom or application specific warnings.
<del>
<del>```js
<del>// Emit a warning using a string...
<del>process.emitWarning('Something happened!');
<del> // Prints: (node 12345) Warning: Something happened!
<del>
<del>// Emit a warning using an object...
<del>process.emitWarning('Something Happened!', 'CustomWarning');
<del> // Prints: (node 12345) CustomWarning: Something happened!
<del>
<del>// Emit a warning using a custom Error object...
<del>class CustomWarning extends Error {
<del> constructor(message) {
<del> super(message);
<del> this.name = 'CustomWarning';
<del> Error.captureStackTrace(this, CustomWarning);
<del> }
<del>}
<del>const myWarning = new CustomWarning('Something happened!');
<del>process.emitWarning(myWarning);
<del> // Prints: (node 12345) CustomWarning: Something happened!
<del>```
<del>
<del>#### Emitting custom deprecation warnings
<del>
<del>Custom deprecation warnings can be emitted by setting the `name` of a custom
<del>warning to `DeprecationWarning`. For instance:
<del>
<del>```js
<del>process.emitWarning('This API is deprecated', 'DeprecationWarning');
<del>```
<del>
<del>Or,
<del>
<del>```js
<del>const err = new Error('This API is deprecated');
<del>err.name = 'DeprecationWarning';
<del>process.emitWarning(err);
<del>```
<del>
<ide> Launching Node.js using the `--throw-deprecation` command line flag will
<ide> cause custom deprecation warnings to be thrown as exceptions.
<ide>
<ide> of the custom deprecation.
<ide> The `*-deprecation` command line flags only affect warnings that use the name
<ide> `DeprecationWarning`.
<ide>
<add>#### Emitting custom warnings
<add>
<add>See the [`process.emitWarning()`][process_emit_warning] method for issuing
<add>custom or application-specific warnings.
<add>
<ide> ### Signal Events
<ide>
<ide> <!--type=event--> | 1 |
PHP | PHP | deprecate the requireauth feature | e6493325eae490adb416cb22031f3bcd1123f2e9 | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> class SecurityComponent extends Component
<ide> * - `blackHoleCallback` - The controller method that will be called if this
<ide> * request is black-hole'd.
<ide> * - `requireSecure` - List of actions that require an SSL-secured connection.
<del> * - `requireAuth` - List of actions that require a valid authentication key.
<add> * - `requireAuth` - List of actions that require a valid authentication key. Deprecated as of 3.2.2
<ide> * - `allowedControllers` - Controllers from which actions of the current
<ide> * controller are allowed to receive requests.
<ide> * - `allowedActions` - Actions from which actions of the current controller
<ide> public function requireSecure($actions = null)
<ide> *
<ide> * @param string|array $actions Actions list
<ide> * @return void
<add> * @deprecated 3.2.2 This feature is confusing and not useful.
<ide> */
<ide> public function requireAuth($actions)
<ide> {
<ide> protected function _secureRequired(Controller $controller)
<ide> *
<ide> * @param \Cake\Controller\Controller $controller Instantiating controller
<ide> * @return bool true if authentication required
<add> * @deprecated 3.2.2 This feature is confusing and not useful.
<ide> */
<ide> protected function _authRequired(Controller $controller)
<ide> { | 1 |
PHP | PHP | reduce duplication in code | 95ed471c41f61555b2b7f642422bfef8a279cfd4 | <ide><path>lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php
<ide> public function setUp() {
<ide> array($out, $out, $in)
<ide> );
<ide> $this->Task->Test = $this->getMock('TestTask', array(), array($out, $out, $in));
<add>
<add> if (!defined('ARTICLE_MODEL_CREATED')) {
<add> $this->markTestSkipped('Could not run as an Article, Tag or Comment model was already loaded.');
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function testBakeWithPlugin() {
<ide> * @return void
<ide> */
<ide> public function testBakeActionsUsingSessions() {
<del> $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Comment & Tag Model to be undefined.');
<ide>
<ide> $result = $this->Task->bakeActions('BakeArticles', null, true);
<ide>
<ide> public function testBakeActionsUsingSessions() {
<ide> * @return void
<ide> */
<ide> public function testBakeActionsWithNoSessions() {
<del> $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Tag, Comment Models to be undefined.');
<ide>
<ide> $result = $this->Task->bakeActions('BakeArticles', null, false);
<ide>
<ide> public function testExecuteIntoAll() {
<ide> if ($count != count($this->fixtures)) {
<ide> $this->markTestSkipped('Additional tables detected.');
<ide> }
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute into all could not be run as an Article, Tag or Comment model was already loaded.');
<del> }
<ide>
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> public function testExecuteIntoAllAdmin() {
<ide> if ($count != count($this->fixtures)) {
<ide> $this->markTestSkipped('Additional tables detected.');
<ide> }
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute into all could not be run as an Article, Tag or Comment model was already loaded.');
<del> }
<ide>
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> public function testExecuteIntoAllAdmin() {
<ide> * @return void
<ide> */
<ide> public function testExecuteWithController() {
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined');
<del> }
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> $this->Task->args = array('BakeArticles');
<ide> public static function nameVariations() {
<ide> * @return void
<ide> */
<ide> public function testExecuteWithControllerNameVariations($name) {
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined.');
<del> }
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> $this->Task->args = array($name);
<ide> public function testExecuteWithControllerNameVariations($name) {
<ide> * @return void
<ide> */
<ide> public function testExecuteWithPublicParam() {
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute with public param requires no Article, Tag or Comment model to be defined.');
<del> }
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> $this->Task->args = array('BakeArticles');
<ide> public function testExecuteWithPublicParam() {
<ide> * @return void
<ide> */
<ide> public function testExecuteWithControllerAndBoth() {
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute with controller and both requires no Article, Tag or Comment model to be defined.');
<del> }
<ide> $this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> public function testExecuteWithControllerAndBoth() {
<ide> * @return void
<ide> */
<ide> public function testExecuteWithControllerAndAdmin() {
<del> if (!defined('ARTICLE_MODEL_CREATED')) {
<del> $this->markTestSkipped('Execute with controller and admin requires no Article, Tag or Comment model to be defined.');
<del> }
<ide> $this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/'; | 1 |
Javascript | Javascript | handle undefined filename in geterrmessage | a5d86f8c4ebf201092a7a155691856e13639f0cb | <ide><path>lib/assert.js
<ide> function getBuffer(fd, assertLine) {
<ide>
<ide> function getErrMessage(call) {
<ide> const filename = call.getFileName();
<add> if (!filename) {
<add> return;
<add> }
<add>
<ide> const line = call.getLineNumber() - 1;
<ide> const column = call.getColumnNumber() - 1;
<ide> const identifier = `${filename}${line}${column}`;
<ide><path>test/parallel/test-assert.js
<ide> common.expectsError(
<ide> }
<ide> );
<ide>
<add>// works in eval
<add>common.expectsError(
<add> () => new Function('assert', 'assert(1 === 2);')(assert),
<add> {
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'false == true'
<add> }
<add>);
<add>
<ide> // Do not try to check Node.js modules.
<ide> {
<ide> const e = new EventEmitter(); | 2 |
PHP | PHP | apply fixes from styleci | 66b42379183f24c74ad4c8549a826c820b97f79d | <ide><path>src/Illuminate/Auth/SessionGuard.php
<ide> use RuntimeException;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\Response;
<del>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Auth\UserProvider;
<add>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Auth\StatefulGuard;
<ide> use Symfony\Component\HttpFoundation\Request;
<ide> use Illuminate\Contracts\Auth\SupportsBasicAuth;
<ide><path>src/Illuminate/Cache/FileStore.php
<ide>
<ide> use Exception;
<ide> use Illuminate\Support\Arr;
<del>use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Contracts\Cache\Store;
<add>use Illuminate\Filesystem\Filesystem;
<ide>
<ide> class FileStore implements Store
<ide> {
<ide><path>src/Illuminate/Database/Connection.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<del>use Illuminate\Database\Query\Processors\Processor;
<ide> use Doctrine\DBAL\Connection as DoctrineConnection;
<add>use Illuminate\Database\Query\Processors\Processor;
<ide> use Illuminate\Database\Query\Builder as QueryBuilder;
<ide> use Illuminate\Database\Schema\Builder as SchemaBuilder;
<ide> use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
<ide><path>src/Illuminate/Database/DatabaseServiceProvider.php
<ide> use Faker\Generator as FakerGenerator;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Support\ServiceProvider;
<del>use Illuminate\Database\Eloquent\QueueEntityResolver;
<ide> use Illuminate\Database\Connectors\ConnectionFactory;
<add>use Illuminate\Database\Eloquent\QueueEntityResolver;
<ide> use Illuminate\Database\Eloquent\Factory as EloquentFactory;
<ide>
<ide> class DatabaseServiceProvider extends ServiceProvider
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> use Illuminate\Database\Eloquent\Relations\HasOne;
<ide> use Illuminate\Database\Eloquent\Relations\HasMany;
<ide> use Illuminate\Database\Eloquent\Relations\MorphTo;
<del>use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Database\Eloquent\Relations\MorphOne;
<add>use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Support\Collection as BaseCollection;
<del>use Illuminate\Database\Eloquent\Relations\MorphMany;
<ide> use Illuminate\Database\Eloquent\Relations\BelongsTo;
<add>use Illuminate\Database\Eloquent\Relations\MorphMany;
<ide> use Illuminate\Database\Query\Builder as QueryBuilder;
<ide> use Illuminate\Database\Eloquent\Relations\MorphToMany;
<ide> use Illuminate\Database\Eloquent\Relations\BelongsToMany;
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> use League\Flysystem\AwsS3v3\AwsS3Adapter;
<ide> use League\Flysystem\FileNotFoundException;
<ide> use League\Flysystem\Adapter\Local as LocalAdapter;
<del>use Illuminate\Contracts\Filesystem\Filesystem as FilesystemContract;
<ide> use Illuminate\Contracts\Filesystem\Cloud as CloudFilesystemContract;
<add>use Illuminate\Contracts\Filesystem\Filesystem as FilesystemContract;
<ide> use Illuminate\Contracts\Filesystem\FileNotFoundException as ContractFileNotFoundException;
<ide>
<ide> class FilesystemAdapter implements FilesystemContract, CloudFilesystemContract
<ide><path>src/Illuminate/Foundation/Bootstrap/RegisterFacades.php
<ide>
<ide> namespace Illuminate\Foundation\Bootstrap;
<ide>
<del>use Illuminate\Support\Facades\Facade;
<ide> use Illuminate\Foundation\AliasLoader;
<add>use Illuminate\Support\Facades\Facade;
<ide> use Illuminate\Contracts\Foundation\Application;
<ide>
<ide> class RegisterFacades
<ide><path>src/Illuminate/Foundation/Console/Kernel.php
<ide>
<ide> use Exception;
<ide> use Throwable;
<del>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Console\Scheduling\Schedule;
<add>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Console\Application as Artisan;
<ide> use Illuminate\Contracts\Foundation\Application;
<ide> use Illuminate\Contracts\Console\Kernel as KernelContract;
<ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> use Illuminate\Routing\Router;
<ide> use Illuminate\Routing\Pipeline;
<ide> use Illuminate\Support\Facades\Facade;
<del>use Illuminate\Contracts\Foundation\Application;
<ide> use Illuminate\Contracts\Debug\ExceptionHandler;
<add>use Illuminate\Contracts\Foundation\Application;
<ide> use Illuminate\Contracts\Http\Kernel as KernelContract;
<ide> use Symfony\Component\Debug\Exception\FatalThrowableError;
<ide>
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Foundation\Console\UpCommand;
<ide> use Illuminate\Foundation\Console\DownCommand;
<ide> use Illuminate\Auth\Console\ClearResetsCommand;
<del>use Illuminate\Foundation\Console\ServeCommand;
<ide> use Illuminate\Cache\Console\CacheTableCommand;
<del>use Illuminate\Queue\Console\FailedTableCommand;
<add>use Illuminate\Foundation\Console\ServeCommand;
<ide> use Illuminate\Foundation\Console\TinkerCommand;
<del>use Illuminate\Foundation\Console\JobMakeCommand;
<add>use Illuminate\Queue\Console\FailedTableCommand;
<ide> use Illuminate\Foundation\Console\AppNameCommand;
<add>use Illuminate\Foundation\Console\JobMakeCommand;
<ide> use Illuminate\Foundation\Console\OptimizeCommand;
<ide> use Illuminate\Foundation\Console\TestMakeCommand;
<del>use Illuminate\Foundation\Console\RouteListCommand;
<ide> use Illuminate\Foundation\Console\EventMakeCommand;
<ide> use Illuminate\Foundation\Console\ModelMakeCommand;
<add>use Illuminate\Foundation\Console\RouteListCommand;
<ide> use Illuminate\Foundation\Console\ViewClearCommand;
<ide> use Illuminate\Session\Console\SessionTableCommand;
<ide> use Illuminate\Foundation\Console\PolicyMakeCommand;
<ide> use Illuminate\Foundation\Console\RouteCacheCommand;
<ide> use Illuminate\Foundation\Console\RouteClearCommand;
<del>use Illuminate\Routing\Console\ControllerMakeCommand;
<del>use Illuminate\Routing\Console\MiddlewareMakeCommand;
<ide> use Illuminate\Foundation\Console\ConfigCacheCommand;
<ide> use Illuminate\Foundation\Console\ConfigClearCommand;
<ide> use Illuminate\Foundation\Console\ConsoleMakeCommand;
<ide> use Illuminate\Foundation\Console\EnvironmentCommand;
<ide> use Illuminate\Foundation\Console\KeyGenerateCommand;
<ide> use Illuminate\Foundation\Console\RequestMakeCommand;
<add>use Illuminate\Routing\Console\ControllerMakeCommand;
<add>use Illuminate\Routing\Console\MiddlewareMakeCommand;
<ide> use Illuminate\Foundation\Console\ListenerMakeCommand;
<ide> use Illuminate\Foundation\Console\ProviderMakeCommand;
<ide> use Illuminate\Foundation\Console\ClearCompiledCommand;
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php
<ide> use Symfony\Component\DomCrawler\Form;
<ide> use Symfony\Component\DomCrawler\Crawler;
<ide> use Illuminate\Foundation\Testing\HttpException;
<del>use Illuminate\Foundation\Testing\Constraints\HasText;
<ide> use Illuminate\Foundation\Testing\Constraints\HasLink;
<add>use Illuminate\Foundation\Testing\Constraints\HasText;
<ide> use Illuminate\Foundation\Testing\Constraints\HasValue;
<ide> use Illuminate\Foundation\Testing\Constraints\HasSource;
<ide> use Illuminate\Foundation\Testing\Constraints\IsChecked;
<ide><path>src/Illuminate/Log/Writer.php
<ide> use Closure;
<ide> use RuntimeException;
<ide> use InvalidArgumentException;
<del>use Monolog\Handler\SyslogHandler;
<ide> use Monolog\Handler\StreamHandler;
<del>use Monolog\Logger as MonologLogger;
<add>use Monolog\Handler\SyslogHandler;
<ide> use Monolog\Formatter\LineFormatter;
<ide> use Monolog\Handler\ErrorLogHandler;
<add>use Monolog\Logger as MonologLogger;
<ide> use Monolog\Handler\RotatingFileHandler;
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide><path>src/Illuminate/Mail/TransportManager.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Manager;
<ide> use GuzzleHttp\Client as HttpClient;
<del>use Swift_SmtpTransport as SmtpTransport;
<ide> use Swift_MailTransport as MailTransport;
<add>use Swift_SmtpTransport as SmtpTransport;
<ide> use Illuminate\Mail\Transport\LogTransport;
<ide> use Illuminate\Mail\Transport\SesTransport;
<ide> use Illuminate\Mail\Transport\MailgunTransport;
<ide><path>src/Illuminate/Queue/Jobs/DatabaseJob.php
<ide>
<ide> namespace Illuminate\Queue\Jobs;
<ide>
<del>use Illuminate\Queue\DatabaseQueue;
<ide> use Illuminate\Container\Container;
<add>use Illuminate\Queue\DatabaseQueue;
<ide> use Illuminate\Contracts\Queue\Job as JobContract;
<ide>
<ide> class DatabaseJob extends Job implements JobContract
<ide><path>src/Illuminate/Queue/QueueServiceProvider.php
<ide> use Illuminate\Queue\Connectors\NullConnector;
<ide> use Illuminate\Queue\Connectors\SyncConnector;
<ide> use Illuminate\Queue\Connectors\RedisConnector;
<del>use Illuminate\Queue\Failed\NullFailedJobProvider;
<ide> use Illuminate\Queue\Connectors\DatabaseConnector;
<add>use Illuminate\Queue\Failed\NullFailedJobProvider;
<ide> use Illuminate\Queue\Connectors\BeanstalkdConnector;
<ide> use Illuminate\Queue\Failed\DatabaseFailedJobProvider;
<ide>
<ide><path>src/Illuminate/Routing/Pipeline.php
<ide> namespace Illuminate\Routing;
<ide>
<ide> use Closure;
<del>use Throwable;
<ide> use Exception;
<add>use Throwable;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Contracts\Debug\ExceptionHandler;
<ide> use Illuminate\Pipeline\Pipeline as BasePipeline;
<ide><path>src/Illuminate/Routing/Route.php
<ide> use Illuminate\Routing\Matching\HostValidator;
<ide> use Illuminate\Routing\Matching\MethodValidator;
<ide> use Illuminate\Routing\Matching\SchemeValidator;
<del>use Symfony\Component\Routing\Route as SymfonyRoute;
<ide> use Illuminate\Http\Exception\HttpResponseException;
<add>use Symfony\Component\Routing\Route as SymfonyRoute;
<ide>
<ide> class Route
<ide> {
<ide><path>src/Illuminate/Routing/Router.php
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
<del>use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
<ide> use Illuminate\Contracts\Routing\Registrar as RegistrarContract;
<add>use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
<ide> use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
<ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
<ide>
<ide><path>src/Illuminate/Session/Middleware/StartSession.php
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Session\SessionManager;
<ide> use Illuminate\Session\SessionInterface;
<del>use Symfony\Component\HttpFoundation\Cookie;
<ide> use Illuminate\Session\CookieSessionHandler;
<add>use Symfony\Component\HttpFoundation\Cookie;
<ide> use Symfony\Component\HttpFoundation\Response;
<ide>
<ide> class StartSession
<ide><path>src/Illuminate/Support/Debug/Dumper.php
<ide>
<ide> namespace Illuminate\Support\Debug;
<ide>
<del>use Symfony\Component\VarDumper\Dumper\CliDumper;
<ide> use Symfony\Component\VarDumper\Cloner\VarCloner;
<add>use Symfony\Component\VarDumper\Dumper\CliDumper;
<ide>
<ide> class Dumper
<ide> {
<ide><path>src/Illuminate/Validation/Validator.php
<ide> use DateTimeZone;
<ide> use RuntimeException;
<ide> use DateTimeInterface;
<add>use BadMethodCallException;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<del>use BadMethodCallException;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Support\Fluent;
<ide> use Illuminate\Support\MessageBag;
<ide><path>src/Illuminate/View/Factory.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<add>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\View\Engines\EngineResolver;
<del>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Container\Container;
<ide> use Illuminate\Contracts\View\Factory as FactoryContract;
<ide>
<ide><path>src/Illuminate/View/View.php
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Support\MessageBag;
<ide> use Illuminate\Contracts\Support\Arrayable;
<del>use Illuminate\View\Engines\EngineInterface;
<ide> use Illuminate\Contracts\Support\Renderable;
<add>use Illuminate\View\Engines\EngineInterface;
<ide> use Illuminate\Contracts\Support\MessageProvider;
<ide> use Illuminate\Contracts\View\View as ViewContract;
<ide>
<ide><path>tests/Cookie/Middleware/EncryptCookiesTest.php
<ide> <?php
<ide>
<del>use Illuminate\Http\Response;
<ide> use Illuminate\Http\Request;
<add>use Illuminate\Http\Response;
<ide> use Illuminate\Routing\Router;
<ide> use Illuminate\Cookie\CookieJar;
<ide> use Illuminate\Events\Dispatcher;
<ide><path>tests/Database/DatabaseEloquentHasManyThroughTest.php
<ide>
<ide> use Mockery as m;
<ide> use Illuminate\Database\Eloquent\Collection;
<del>use Illuminate\Database\Eloquent\Relations\HasManyThrough;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<add>use Illuminate\Database\Eloquent\Relations\HasManyThrough;
<ide>
<ide> class DatabaseEloquentHasManyThroughTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
<ide> use Illuminate\Database\Query\Builder;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide> use Illuminate\Database\Capsule\Manager as DB;
<del>use Illuminate\Database\Eloquent\SoftDeletingScope;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<add>use Illuminate\Database\Eloquent\SoftDeletingScope;
<ide>
<ide> class DatabaseEloquentSoftDeletesIntegrationTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> <?php
<ide>
<del>use Illuminate\Pagination\LengthAwarePaginator;
<ide> use Mockery as m;
<ide> use Illuminate\Database\Query\Builder;
<add>use Illuminate\Pagination\LengthAwarePaginator;
<ide> use Illuminate\Database\Query\Expression as Raw;
<ide> use Illuminate\Pagination\AbstractPaginator as Paginator;
<ide>
<ide><path>tests/Mail/MailSesTransportTest.php
<ide> <?php
<ide>
<ide> use Aws\Ses\SesClient;
<del>use Illuminate\Foundation\Application;
<add>use Illuminate\Support\Collection;
<ide> use Illuminate\Mail\TransportManager;
<add>use Illuminate\Foundation\Application;
<ide> use Illuminate\Mail\Transport\SesTransport;
<del>use Illuminate\Support\Collection;
<ide>
<ide> class MailSesTransportTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Queue/QueueDatabaseQueueIntegrationTest.php
<ide> <?php
<ide>
<del>use Illuminate\Database\Capsule\Manager as DB;
<del>use Illuminate\Database\Schema\Blueprint;
<del>use Illuminate\Database\Eloquent\Model as Eloquent;
<del>use \Illuminate\Queue\DatabaseQueue;
<ide> use Carbon\Carbon;
<ide> use Illuminate\Container\Container;
<add>use \Illuminate\Queue\DatabaseQueue;
<add>use Illuminate\Database\Schema\Blueprint;
<add>use Illuminate\Database\Capsule\Manager as DB;
<add>use Illuminate\Database\Eloquent\Model as Eloquent;
<ide>
<ide> class QueueDatabaseQueueIntegrationTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Session/SessionTableCommandTest.php
<ide> <?php
<ide>
<del>use Illuminate\Session\Console\SessionTableCommand;
<del>use Illuminate\Foundation\Application;
<ide> use Mockery as m;
<add>use Illuminate\Foundation\Application;
<add>use Illuminate\Session\Console\SessionTableCommand;
<ide>
<ide> class SessionTableCommandTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Support/SupportMessageBagTest.php
<ide> <?php
<ide>
<del>use Illuminate\Support\MessageBag;
<ide> use Mockery as m;
<add>use Illuminate\Support\MessageBag;
<ide>
<ide> class SupportMessageBagTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Support/SupportServiceProviderTest.php
<ide> <?php
<ide>
<del>use Illuminate\Support\ServiceProvider;
<ide> use Mockery as m;
<add>use Illuminate\Support\ServiceProvider;
<ide>
<ide> class SupportServiceProviderTest extends PHPUnit_Framework_TestCase
<ide> { | 32 |
Java | Java | remove old android apis code from reactviewgroup | f829722b54b34f145c41a95edfa5b522c837f9fc | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java
<ide> * Backing for a React View. Has support for borders, but since borders aren't common, lazy
<ide> * initializes most of the storage needed for them.
<ide> */
<add>@TargetApi(Build.VERSION_CODES.KITKAT)
<ide> public class ReactViewGroup extends ViewGroup
<ide> implements ReactInterceptingViewGroup,
<ide> ReactClippingViewGroup,
<ide> protected void onLayout(boolean changed, int left, int top, int right, int botto
<ide>
<ide> @Override
<ide> public void onRtlPropertiesChanged(int layoutDirection) {
<del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
<del> if (mReactBackgroundDrawable != null) {
<del> mReactBackgroundDrawable.setResolvedLayoutDirection(mLayoutDirection);
<del> }
<add> if (mReactBackgroundDrawable != null) {
<add> mReactBackgroundDrawable.setResolvedLayoutDirection(mLayoutDirection);
<ide> }
<ide> }
<ide>
<ide> public void setBorderColor(int position, float rgb, float alpha) {
<ide> public void setBorderRadius(float borderRadius) {
<ide> ReactViewBackgroundDrawable backgroundDrawable = getOrCreateReactViewBackground();
<ide> backgroundDrawable.setRadius(borderRadius);
<del>
<del> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
<del> final int UPDATED_LAYER_TYPE =
<del> backgroundDrawable.hasRoundedBorders()
<del> ? View.LAYER_TYPE_SOFTWARE
<del> : View.LAYER_TYPE_HARDWARE;
<del>
<del> if (UPDATED_LAYER_TYPE != getLayerType()) {
<del> setLayerType(UPDATED_LAYER_TYPE, null);
<del> }
<del> }
<ide> }
<ide>
<ide> public void setBorderRadius(float borderRadius, int position) {
<ide> ReactViewBackgroundDrawable backgroundDrawable = getOrCreateReactViewBackground();
<ide> backgroundDrawable.setRadius(borderRadius, position);
<del>
<del> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
<del> final int UPDATED_LAYER_TYPE =
<del> backgroundDrawable.hasRoundedBorders()
<del> ? View.LAYER_TYPE_SOFTWARE
<del> : View.LAYER_TYPE_HARDWARE;
<del>
<del> if (UPDATED_LAYER_TYPE != getLayerType()) {
<del> setLayerType(UPDATED_LAYER_TYPE, null);
<del> }
<del> }
<ide> }
<ide>
<ide> public void setBorderStyle(@Nullable String style) {
<ide> private ReactViewBackgroundDrawable getOrCreateReactViewBackground() {
<ide> updateBackgroundDrawable(layerDrawable);
<ide> }
<ide>
<del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
<del> mLayoutDirection =
<del> I18nUtil.getInstance().isRTL(getContext())
<del> ? LAYOUT_DIRECTION_RTL
<del> : LAYOUT_DIRECTION_LTR;
<del> mReactBackgroundDrawable.setResolvedLayoutDirection(mLayoutDirection);
<del> }
<add> mLayoutDirection =
<add> I18nUtil.getInstance().isRTL(getContext()) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
<add> mReactBackgroundDrawable.setResolvedLayoutDirection(mLayoutDirection);
<ide> }
<ide> return mReactBackgroundDrawable;
<ide> }
<ide> private void dispatchOverflowDraw(Canvas canvas) {
<ide> mReactBackgroundDrawable.getBorderRadiusOrDefaultTo(
<ide> borderRadius, ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_RIGHT);
<ide>
<del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
<del> final boolean isRTL = mLayoutDirection == View.LAYOUT_DIRECTION_RTL;
<del> float topStartBorderRadius =
<del> mReactBackgroundDrawable.getBorderRadius(
<del> ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_START);
<del> float topEndBorderRadius =
<del> mReactBackgroundDrawable.getBorderRadius(
<del> ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_END);
<del> float bottomStartBorderRadius =
<del> mReactBackgroundDrawable.getBorderRadius(
<del> ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_START);
<del> float bottomEndBorderRadius =
<del> mReactBackgroundDrawable.getBorderRadius(
<del> ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_END);
<del>
<del> if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(getContext())) {
<del> if (YogaConstants.isUndefined(topStartBorderRadius)) {
<del> topStartBorderRadius = topLeftBorderRadius;
<del> }
<del>
<del> if (YogaConstants.isUndefined(topEndBorderRadius)) {
<del> topEndBorderRadius = topRightBorderRadius;
<del> }
<del>
<del> if (YogaConstants.isUndefined(bottomStartBorderRadius)) {
<del> bottomStartBorderRadius = bottomLeftBorderRadius;
<del> }
<del>
<del> if (YogaConstants.isUndefined(bottomEndBorderRadius)) {
<del> bottomEndBorderRadius = bottomRightBorderRadius;
<del> }
<del>
<del> final float directionAwareTopLeftRadius =
<del> isRTL ? topEndBorderRadius : topStartBorderRadius;
<del> final float directionAwareTopRightRadius =
<del> isRTL ? topStartBorderRadius : topEndBorderRadius;
<del> final float directionAwareBottomLeftRadius =
<del> isRTL ? bottomEndBorderRadius : bottomStartBorderRadius;
<del> final float directionAwareBottomRightRadius =
<del> isRTL ? bottomStartBorderRadius : bottomEndBorderRadius;
<add> final boolean isRTL = mLayoutDirection == View.LAYOUT_DIRECTION_RTL;
<add> float topStartBorderRadius =
<add> mReactBackgroundDrawable.getBorderRadius(
<add> ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_START);
<add> float topEndBorderRadius =
<add> mReactBackgroundDrawable.getBorderRadius(
<add> ReactViewBackgroundDrawable.BorderRadiusLocation.TOP_END);
<add> float bottomStartBorderRadius =
<add> mReactBackgroundDrawable.getBorderRadius(
<add> ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_START);
<add> float bottomEndBorderRadius =
<add> mReactBackgroundDrawable.getBorderRadius(
<add> ReactViewBackgroundDrawable.BorderRadiusLocation.BOTTOM_END);
<add>
<add> if (I18nUtil.getInstance().doLeftAndRightSwapInRTL(getContext())) {
<add> if (YogaConstants.isUndefined(topStartBorderRadius)) {
<add> topStartBorderRadius = topLeftBorderRadius;
<add> }
<ide>
<add> if (YogaConstants.isUndefined(topEndBorderRadius)) {
<add> topEndBorderRadius = topRightBorderRadius;
<add> }
<add>
<add> if (YogaConstants.isUndefined(bottomStartBorderRadius)) {
<add> bottomStartBorderRadius = bottomLeftBorderRadius;
<add> }
<add>
<add> if (YogaConstants.isUndefined(bottomEndBorderRadius)) {
<add> bottomEndBorderRadius = bottomRightBorderRadius;
<add> }
<add>
<add> final float directionAwareTopLeftRadius =
<add> isRTL ? topEndBorderRadius : topStartBorderRadius;
<add> final float directionAwareTopRightRadius =
<add> isRTL ? topStartBorderRadius : topEndBorderRadius;
<add> final float directionAwareBottomLeftRadius =
<add> isRTL ? bottomEndBorderRadius : bottomStartBorderRadius;
<add> final float directionAwareBottomRightRadius =
<add> isRTL ? bottomStartBorderRadius : bottomEndBorderRadius;
<add>
<add> topLeftBorderRadius = directionAwareTopLeftRadius;
<add> topRightBorderRadius = directionAwareTopRightRadius;
<add> bottomLeftBorderRadius = directionAwareBottomLeftRadius;
<add> bottomRightBorderRadius = directionAwareBottomRightRadius;
<add> } else {
<add> final float directionAwareTopLeftRadius =
<add> isRTL ? topEndBorderRadius : topStartBorderRadius;
<add> final float directionAwareTopRightRadius =
<add> isRTL ? topStartBorderRadius : topEndBorderRadius;
<add> final float directionAwareBottomLeftRadius =
<add> isRTL ? bottomEndBorderRadius : bottomStartBorderRadius;
<add> final float directionAwareBottomRightRadius =
<add> isRTL ? bottomStartBorderRadius : bottomEndBorderRadius;
<add>
<add> if (!YogaConstants.isUndefined(directionAwareTopLeftRadius)) {
<ide> topLeftBorderRadius = directionAwareTopLeftRadius;
<add> }
<add>
<add> if (!YogaConstants.isUndefined(directionAwareTopRightRadius)) {
<ide> topRightBorderRadius = directionAwareTopRightRadius;
<add> }
<add>
<add> if (!YogaConstants.isUndefined(directionAwareBottomLeftRadius)) {
<ide> bottomLeftBorderRadius = directionAwareBottomLeftRadius;
<add> }
<add>
<add> if (!YogaConstants.isUndefined(directionAwareBottomRightRadius)) {
<ide> bottomRightBorderRadius = directionAwareBottomRightRadius;
<del> } else {
<del> final float directionAwareTopLeftRadius =
<del> isRTL ? topEndBorderRadius : topStartBorderRadius;
<del> final float directionAwareTopRightRadius =
<del> isRTL ? topStartBorderRadius : topEndBorderRadius;
<del> final float directionAwareBottomLeftRadius =
<del> isRTL ? bottomEndBorderRadius : bottomStartBorderRadius;
<del> final float directionAwareBottomRightRadius =
<del> isRTL ? bottomStartBorderRadius : bottomEndBorderRadius;
<del>
<del> if (!YogaConstants.isUndefined(directionAwareTopLeftRadius)) {
<del> topLeftBorderRadius = directionAwareTopLeftRadius;
<del> }
<del>
<del> if (!YogaConstants.isUndefined(directionAwareTopRightRadius)) {
<del> topRightBorderRadius = directionAwareTopRightRadius;
<del> }
<del>
<del> if (!YogaConstants.isUndefined(directionAwareBottomLeftRadius)) {
<del> bottomLeftBorderRadius = directionAwareBottomLeftRadius;
<del> }
<del>
<del> if (!YogaConstants.isUndefined(directionAwareBottomRightRadius)) {
<del> bottomRightBorderRadius = directionAwareBottomRightRadius;
<del> }
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | apply fixes from styleci | f0448d4df91dcec7c49b580d3fb96c21523c3b74 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function applyScopes()
<ide> continue;
<ide> }
<ide>
<del> $builder->callScope(function (Builder $builder) use ($scope) {
<add> $builder->callScope(function (self $builder) use ($scope) {
<ide> // If the scope is a Closure we will just go ahead and call the scope with the
<ide> // builder instance. The "callScope" method will properly group the clauses
<ide> // that are added to this query so "where" clauses maintain proper logic.
<ide><path>src/Illuminate/Foundation/Application.php
<ide> public function isLocale($locale)
<ide> public function registerCoreContainerAliases()
<ide> {
<ide> foreach ([
<del> 'app' => [\Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class],
<add> 'app' => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class],
<ide> 'auth' => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],
<ide> 'auth.driver' => [\Illuminate\Contracts\Auth\Guard::class],
<ide> 'blade.compiler' => [\Illuminate\View\Compilers\BladeCompiler::class], | 2 |
Python | Python | fix typo syntax err (sorry, c/p from my repo) | 472857c47f3b6a142a7aaa53836e33cd8543088d | <ide><path>pytorch_pretrained_bert/modeling_gpt2.py
<ide> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_labels=N
<ide> # in pytorch, it's [batch, num_classes, d_0, d_1, ..., d_{r-1}]
<ide> # We just flatten the tokens out this way.
<ide> loss_fct = CrossEntropyLoss(ignore_index=-1)
<del> loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1))
<add> loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)),
<ide> shift_labels.view(-1))
<ide> return loss
<ide> return lm_logits, presents
<ide><path>pytorch_pretrained_bert/modeling_openai.py
<ide> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_labels=N
<ide> # in pytorch, it's [batch, num_classes, d_0, d_1, ..., d_{r-1}]
<ide> # We just flatten the tokens out this way.
<ide> loss_fct = CrossEntropyLoss(ignore_index=-1)
<del> loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1))
<add> loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)),
<ide> shift_labels.view(-1))
<ide> return loss
<ide> return lm_logits | 2 |
Text | Text | fix typo in 'installing with breeze' doc | 90384b10f25307282a1a39062316af622583b5e4 | <ide><path>dev/README.md
<ide> First copy all the provider packages .whl files to the `dist` folder.
<ide>
<ide> ```shell script
<ide> ./breeze start-airflow --install-airflow-version <VERSION>rc<X> \
<del> --python 3.7 --backend postgres --instal-wheels
<add> --python 3.7 --backend postgres --install-wheels
<ide> ```
<ide>
<ide> For 1.10 releases you can also use `--no-rbac-ui` flag disable RBAC UI of Airflow: | 1 |
Javascript | Javascript | add documentation stub for ember.router | 8bd4aa3358616b3ff19b5a93da7e4c3f850831ca | <ide><path>packages/ember-routing/lib/system/router.js
<ide> function setupLocation(router) {
<ide> }
<ide> }
<ide>
<add>/**
<add> The `Ember.Router` class manages the application state and URLs. Refer to
<add> the [routing guide](http://emberjs.com/guides/routing/) for documentation.
<add>
<add> @class Router
<add> @namespace Ember
<add> @extends Ember.Object
<add>*/
<ide> Ember.Router = Ember.Object.extend({
<ide> location: 'hash',
<ide> | 1 |
PHP | PHP | add remove() to cookiecollection | 1b61694dd7f93f3fce305f5b43961992e41ea7ac | <ide><path>src/Http/Cookie/CookieCollection.php
<ide> public function has($name)
<ide> return isset($this->cookies[$key]);
<ide> }
<ide>
<add> /**
<add> * Remove a cookie from the collection
<add> *
<add> * If the cookie is not in the collection, this method will do nothing.
<add> *
<add> * @param string $name The name of the cookie to remove.
<add> * @return void
<add> */
<add> public function remove($name)
<add> {
<add> $key = mb_strtolower($name);
<add> unset($this->cookies[$key]);
<add> }
<add>
<ide> /**
<ide> * Checks if only valid cookie objects are in the array
<ide> *
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> public function testHas()
<ide> $this->assertTrue($collection->has('REMEMBER_me'), 'case insensitive cookie names');
<ide> }
<ide>
<add>
<add> /**
<add> * Test removing cookies
<add> *
<add> * @return void
<add> */
<add> public function testRemove()
<add> {
<add> $cookies = [
<add> new Cookie('remember_me', 'a'),
<add> new Cookie('gtm', 'b')
<add> ];
<add>
<add> $collection = new CookieCollection($cookies);
<add> $this->assertInstanceOf(Cookie::class, $collection->get('REMEMBER_me'), 'case insensitive cookie names');
<add> $this->assertNull($collection->remove('remember_me'));
<add> $this->assertFalse($collection->has('remember_me'));
<add> $this->assertNull($collection->get('remember_me'));
<add> }
<add>
<ide> /**
<ide> * Test getting cookies by name
<ide> * | 2 |
Ruby | Ruby | simplify nosuchkegerror condition | dce7b04ea572fdd4e19b8d611625a979b48a74ce | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def kegs
<ide> rack = HOMEBREW_CELLAR/canonical_name
<ide> dirs = rack.directory? ? rack.subdirs : []
<ide>
<del> raise NoSuchKegError.new(rack.basename.to_s) if not rack.directory? or dirs.empty?
<add> raise NoSuchKegError.new(rack.basename.to_s) if dirs.empty?
<ide>
<ide> linked_keg_ref = HOMEBREW_REPOSITORY/"Library/LinkedKegs"/name
<ide> opt_prefix = HOMEBREW_PREFIX/"opt"/name | 1 |
Ruby | Ruby | fix app boot for ruby 2.4 | 555c1a3a5400dc257cee2ae5e209354f2dc4df8a | <ide><path>railties/lib/rails/all.rb
<ide> # frozen_string_literal: true
<ide>
<add># rubocop:disable Style/RedundantBegin
<add>
<ide> require "rails"
<ide>
<ide> %w(
<ide> rails/test_unit/railtie
<ide> sprockets/railtie
<ide> ).each do |railtie|
<del> require railtie
<del>rescue LoadError
<add> begin
<add> require railtie
<add> rescue LoadError
<add> end
<ide> end | 1 |
PHP | PHP | remove some bindings | 3928c224e16b85b49a7fa68b9d2e77c049a8fe1b | <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> public function register()
<ide> }
<ide>
<ide> $this->commands(
<del> 'command.changes', 'command.environment', 'command.event.cache',
<add> 'command.changes', 'command.environment',
<ide> 'command.route.cache', 'command.route.clear', 'command.route.list',
<ide> 'command.request.make', 'command.tinker', 'command.console.make',
<ide> 'command.key.generate', 'command.down', 'command.up', 'command.clear-compiled',
<ide> public function provides()
<ide> {
<ide> return [
<ide> 'artisan', 'command.changes', 'command.environment',
<del> 'command.event.cache', 'command.route.cache', 'command.route.clear',
<add> 'command.route.cache', 'command.route.clear',
<ide> 'command.route.list', 'command.request.make', 'command.tinker',
<ide> 'command.console.make', 'command.key.generate', 'command.down',
<ide> 'command.up', 'command.clear-compiled', 'command.optimize', | 1 |
Javascript | Javascript | use querycache in image | 76ab5062e973dd70d52ee5e9b0ed2a0cc1def323 | <ide><path>Libraries/Image/Image.ios.js
<ide> function prefetch(url: string): any {
<ide> async function queryCache(
<ide> urls: Array<string>,
<ide> ): Promise<{[string]: 'memory' | 'disk' | 'disk/memory'}> {
<del> return await ImageViewManager.queryCache(urls);
<add> return await NativeImageLoader.queryCache(urls);
<ide> }
<ide>
<ide> type ImageComponentStatics = $ReadOnly<{| | 1 |
Ruby | Ruby | add a `required` option to singular associations | 00f55516509770f58f9ce462d45afb80d8f649ca | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def has_many(name, scope = nil, options = {}, &extension)
<ide> # that is the inverse of this <tt>has_one</tt> association. Does not work in combination
<ide> # with <tt>:through</tt> or <tt>:as</tt> options.
<ide> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
<add> # [:required]
<add> # When set to +true+, the association will also have its presence validated.
<add> # This will validate the association itself, not the id. You can use
<add> # +:inverse_of+ to avoid an extra query during validation.
<ide> #
<ide> # Option examples:
<ide> # has_one :credit_card, dependent: :destroy # destroys the associated credit card
<ide> def has_many(name, scope = nil, options = {}, &extension)
<ide> # has_one :boss, readonly: :true
<ide> # has_one :club, through: :membership
<ide> # has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
<add> # has_one :credit_card, required: true
<ide> def has_one(name, scope = nil, options = {})
<ide> reflection = Builder::HasOne.build(self, name, scope, options)
<ide> Reflection.add_reflection self, name, reflection
<ide> def has_one(name, scope = nil, options = {})
<ide> # object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
<ide> # combination with the <tt>:polymorphic</tt> options.
<ide> # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
<add> # [:required]
<add> # When set to +true+, the association will also have its presence validated.
<add> # This will validate the association itself, not the id. You can use
<add> # +:inverse_of+ to avoid an extra query during validation.
<ide> #
<ide> # Option examples:
<ide> # belongs_to :firm, foreign_key: "client_of"
<ide> def has_one(name, scope = nil, options = {})
<ide> # belongs_to :post, counter_cache: true
<ide> # belongs_to :company, touch: true
<ide> # belongs_to :company, touch: :employees_last_updated_at
<add> # belongs_to :company, required: true
<ide> def belongs_to(name, scope = nil, options = {})
<ide> reflection = Builder::BelongsTo.build(self, name, scope, options)
<ide> Reflection.add_reflection self, name, reflection
<ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def self.build(model, name, scope, options, &block)
<ide> reflection = builder.build(model)
<ide> define_accessors model, reflection
<ide> define_callbacks model, reflection
<add> define_validations model, reflection
<ide> builder.define_extensions model
<ide> reflection
<ide> end
<ide> def #{name}=(value)
<ide> CODE
<ide> end
<ide>
<add> def self.define_validations(model, reflection)
<add> # noop
<add> end
<add>
<ide> def self.valid_dependent_options
<ide> raise NotImplementedError
<ide> end
<ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb
<ide> module ActiveRecord::Associations::Builder
<ide> class SingularAssociation < Association #:nodoc:
<ide> def valid_options
<del> super + [:remote, :dependent, :primary_key, :inverse_of]
<add> super + [:remote, :dependent, :primary_key, :inverse_of, :required]
<ide> end
<ide>
<ide> def self.define_accessors(model, reflection)
<ide> def create_#{name}!(*args, &block)
<ide> end
<ide> CODE
<ide> end
<add>
<add> def self.define_validations(model, reflection)
<add> super
<add> if reflection.options[:required]
<add> model.validates_presence_of reflection.name
<add> end
<add> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/associations/required_test.rb
<add>require "cases/helper"
<add>
<add>class RequiredAssociationsTest < ActiveRecord::TestCase
<add> self.use_transactional_fixtures = false
<add>
<add> class Parent < ActiveRecord::Base
<add> end
<add>
<add> class Child < ActiveRecord::Base
<add> end
<add>
<add> setup do
<add> @connection = ActiveRecord::Base.connection
<add> @connection.create_table :parents, force: true
<add> @connection.create_table :children, force: true do |t|
<add> t.belongs_to :parent
<add> end
<add> end
<add>
<add> teardown do
<add> @connection.execute("DROP TABLE IF EXISTS parents")
<add> @connection.execute("DROP TABLE IF EXISTS children")
<add> end
<add>
<add> test "belongs_to associations are not required by default" do
<add> model = subclass_of(Child) do
<add> belongs_to :parent, inverse_of: false,
<add> class_name: "RequiredAssociationsTest::Parent"
<add> end
<add>
<add> assert model.new.save
<add> assert model.new(parent: Parent.new).save
<add> end
<add>
<add> test "required belongs_to associations have presence validated" do
<add> model = subclass_of(Child) do
<add> belongs_to :parent, required: true, inverse_of: false,
<add> class_name: "RequiredAssociationsTest::Parent"
<add> end
<add>
<add> record = model.new
<add> assert_not record.save
<add> assert_equal ["Parent can't be blank"], record.errors.full_messages
<add>
<add> record.parent = Parent.new
<add> assert record.save
<add> end
<add>
<add> test "has_one associations are not required by default" do
<add> model = subclass_of(Parent) do
<add> has_one :child, inverse_of: false,
<add> class_name: "RequiredAssociationsTest::Child"
<add> end
<add>
<add> assert model.new.save
<add> assert model.new(child: Child.new).save
<add> end
<add>
<add> test "required has_one associations have presence validated" do
<add> model = subclass_of(Parent) do
<add> has_one :child, required: true, inverse_of: false,
<add> class_name: "RequiredAssociationsTest::Child"
<add> end
<add>
<add> record = model.new
<add> assert_not record.save
<add> assert_equal ["Child can't be blank"], record.errors.full_messages
<add>
<add> record.child = Child.new
<add> assert record.save
<add> end
<add>
<add> private
<add>
<add> def subclass_of(klass, &block)
<add> subclass = Class.new(klass, &block)
<add> def subclass.name
<add> superclass.name
<add> end
<add> subclass
<add> end
<add>end | 4 |
PHP | PHP | turn the count into an expression | aafa11b45636841c4eb175e070450ae3a68aa544 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> protected function addHasWhere(Builder $hasQuery, Relation $relation, $operator,
<ide> {
<ide> $this->mergeWheresToHas($hasQuery, $relation);
<ide>
<add> $count = new Expression((int) $count);
<add>
<ide> return $this->where(new Expression('('.$hasQuery->toSql().')'), $operator, $count, $boolean);
<ide> }
<ide> | 1 |
Javascript | Javascript | fix a typo with ie warning | 59c29e320a2c764e59f990e2064689b0b4fc33c7 | <ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide>
<ide> if (restrict.match(/E/)) {
<ide> dom.html('<p>');
<del> dom.text('This directive can be used as custom element, but we aware of ');
<add> dom.text('This directive can be used as custom element, but be aware of ');
<ide> dom.tag('a', {href:'guide/ie'}, 'IE restrictions');
<ide> dom.text('.');
<ide> dom.html('</p>'); | 1 |
Text | Text | specify the correct version for 3.2 | e8a577cc85653fb134cf507e946bcd986e74d95a | <ide><path>README.md
<ide> recommend using the [app skeleton](https://github.com/cakephp/app) as
<ide> a starting point. For existing applications you can run the following:
<ide>
<ide> ``` bash
<del>$ composer require cakephp/cakephp:"~3.1"
<add>$ composer require cakephp/cakephp:"~3.2"
<ide> ```
<ide>
<ide> ## Running Tests | 1 |
Javascript | Javascript | do some logging of the outputted text | f0f16a6a4da1376575a26af4d6603cb76cf93ae5 | <ide><path>web/viewer.js
<ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
<ide> textDiv.style.top = (text.geom.y - fontHeight) + 'px';
<ide>
<ide> // The content of the div is set in the `setTextContent` function.
<add> // For debug reasons, do the bidi thing here to compare it later once the
<add> // text from the getTextContent function comes in.
<add> var bidiText = PDFJS.bidi(text.str, -1);
<add> textDiv.textContent = bidiText.content;
<add> textDiv.dir = bidiText.direction;
<ide>
<del> this.textDivs.push(textDiv);
<add> var idx = this.textDivs.push(textDiv) - 1;
<ide> };
<ide>
<ide> this.setTextContent = function textLayerBuilderSetTextContent(textContent) {
<ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
<ide> var textDiv = textDivs[i];
<ide> var bidiText = PDFJS.bidi(textContent[i], -1);
<ide>
<add> console.log("divL #%d: text=%s, bidi=%s, dir=%s", i, textContent[i], textDiv.textContent, textDiv.dir);
<add>
<ide> textDiv.textContent = bidiText.content;
<ide> textDiv.dir = bidiText.direction;
<add> console.log("divC #%d: text=%s, bidi=%s, dir=%s", i, textContent[i], bidiText.content, bidiText.direction);
<ide> }
<ide>
<ide> this.setupRenderLayoutTimer(); | 1 |
Ruby | Ruby | prefer file.write for bulk writes | be9a32b65ff5e72f54365e79338516d46063e069 | <ide><path>railties/test/generators/actions_test.rb
<ide> def test_route_should_add_data_with_an_new_line
<ide> content.gsub!(/^ \#.*\n/, "")
<ide> content.gsub!(/^\n/, "")
<ide>
<del> File.open(route_path, "wb") { |file| file.write(content) }
<add> File.write(route_path, content)
<ide>
<ide> routes = <<-F
<ide> Rails.application.routes.draw do
<ide><path>railties/test/generators/scaffold_generator_test.rb
<ide> def test_scaffold_generator_on_revoke_does_not_mutilate_legacy_map_parameter
<ide> content = File.read(route_path).gsub(/\.routes\.draw do/) do |match|
<ide> "#{match} |map|"
<ide> end
<del> File.open(route_path, "wb") { |file| file.write(content) }
<add> File.write(route_path, content)
<ide>
<ide> run_generator ["product_line"], behavior: :revoke
<ide>
<ide> def test_scaffold_generator_on_revoke_does_not_mutilate_routes
<ide> content.gsub!(/^ \#.*\n/, "")
<ide> content.gsub!(/^\n/, "")
<ide>
<del> File.open(route_path, "wb") { |file| file.write(content) }
<add> File.write(route_path, content)
<ide> assert_file "config/routes.rb", /\.routes\.draw do\n resources :product_lines\nend\n\z/
<ide>
<ide> run_generator ["product_line"], behavior: :revoke
<ide><path>tasks/release.rb
<ide> header = "## Rails #{version} (#{Date.today.strftime('%B %d, %Y')}) ##\n\n"
<ide> header += "* No changes.\n\n\n" if current_contents =~ /\A##/
<ide> contents = header + current_contents
<del> File.open(fname, "wb") { |f| f.write contents }
<add> File.write(fname, contents)
<ide> end
<ide> end
<ide>
<ide> fname = File.join fw, "CHANGELOG.md"
<ide>
<ide> contents = File.read(fname).sub(/^(## Rails .*)\n/, replace)
<del> File.open(fname, "wb") { |f| f.write contents }
<add> File.write(fname, contents)
<ide> end
<ide> end
<ide> | 3 |
PHP | PHP | apply fixes from styleci | 648bdae04bd15f4b32f76c5dfee0294e067e90b1 | <ide><path>src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php
<ide> protected function inExceptArray($request)
<ide>
<ide> return false;
<ide> }
<del>
<ide> } | 1 |
Javascript | Javascript | remove unnatural indent in doc | 214f544e373597685adfc3ef6f30a72f774b925a | <ide><path>website/layout/AutodocsLayout.js
<ide> var APIDoc = React.createClass({
<ide> <Header level={2} toSlug={cls.name}>
<ide> class {cls.name}
<ide> </Header>
<del> <ul>
<add> <div>
<ide> {cls.docblock && <Marked>
<ide> {removeCommentsFromDocblock(cls.docblock)}
<ide> </Marked>}
<ide> {this.renderMethods(cls.methods, namedTypes)}
<ide> {this.renderProperties(cls.properties)}
<del> </ul>
<add> </div>
<ide> </span>
<ide> );
<ide> })} | 1 |
Javascript | Javascript | add raindrop.io to showcase | 10cc72bb880da7ca5058df6ce877010be393d904 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/posyt-anonymously-meet-right/id1037842845?mt=8',
<ide> author: 'Posyt.com',
<ide> },
<add> {
<add> name: 'Raindrop.io',
<add> icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/f0/a4/57/f0a4574e-4a59-033f-05ff-5c421f0a0b00/icon175x175.png',
<add> link: 'https://itunes.apple.com/us/app/raindrop.io-keep-your-favorites/id1021913807',
<add> author: 'Mussabekov Rustem',
<add> },
<ide> {
<ide> name: 'ReactTo36',
<ide> icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png', | 1 |
Javascript | Javascript | verify expectations after flush() | 4aaa2f7f6b37f0ad8255e6a320e9136a89e329de | <ide><path>src/angular-mocks.js
<ide> angular.module.ngMock.$HttpBackendProvider = function() {
<ide> while (responses.length)
<ide> responses.shift()();
<ide> }
<add> $httpBackend.verifyNoOutstandingExpectation();
<ide> };
<ide>
<ide> $httpBackend.verifyNoOutstandingExpectation = function() {
<ide><path>test/ResourceSpec.js
<ide> describe("resource", function() {
<ide>
<ide> it("should read partial resource", inject(function($httpBackend) {
<ide> $httpBackend.expect('GET', '/CreditCard').respond([{id:{key:123}}]);
<del> $httpBackend.expect('GET', '/CreditCard/123').respond({id: {key: 123}, number: '9876'});
<del>
<ide> var ccs = CreditCard.query();
<ide>
<ide> $httpBackend.flush();
<ide> describe("resource", function() {
<ide> expect(cc instanceof CreditCard).toBe(true);
<ide> expect(cc.number).toBeUndefined();
<ide>
<add> $httpBackend.expect('GET', '/CreditCard/123').respond({id: {key: 123}, number: '9876'});
<ide> cc.$get(callback);
<ide> $httpBackend.flush();
<ide> expect(callback).toHaveBeenCalledWith(cc);
<ide> describe("resource", function() {
<ide>
<ide> it('should delete resource and call callback', inject(function($httpBackend) {
<ide> $httpBackend.expect('DELETE', '/CreditCard/123').respond({});
<del> $httpBackend.expect('DELETE', '/CreditCard/333').respond(204, null);
<del>
<ide> CreditCard.remove({id:123}, callback);
<ide> expect(callback).not.toHaveBeenCalled();
<ide>
<ide> $httpBackend.flush();
<ide> nakedExpect(callback.mostRecentCall.args).toEqual([{}]);
<ide>
<ide> callback.reset();
<add> $httpBackend.expect('DELETE', '/CreditCard/333').respond(204, null);
<ide> CreditCard.remove({id:333}, callback);
<ide> expect(callback).not.toHaveBeenCalled();
<ide>
<ide> describe("resource", function() {
<ide> it('should not mutate the resource object if response contains no body', inject(function($httpBackend) {
<ide> var data = {id:{key:123}, number:'9876'};
<ide> $httpBackend.expect('GET', '/CreditCard/123').respond(data);
<del> $httpBackend.expect('POST', '/CreditCard/123', toJson(data)).respond('');
<ide>
<ide> var cc = CreditCard.get({id:123});
<ide> $httpBackend.flush();
<ide> expect(cc instanceof CreditCard).toBe(true);
<ide>
<add> $httpBackend.expect('POST', '/CreditCard/123', toJson(data)).respond('');
<ide> var idBefore = cc.id;
<add>
<ide> cc.$save();
<ide> $httpBackend.flush();
<ide> expect(idBefore).toEqual(cc.id);
<ide><path>test/angular-mocksSpec.js
<ide> describe('mocks', function() {
<ide> });
<ide>
<ide>
<add> it('(flush) should throw exception if not all expectations satasfied', function() {
<add> hb.expect('GET', '/url1').respond();
<add> hb.expect('GET', '/url2').respond();
<add>
<add> hb('GET', '/url1', null, angular.noop);
<add> expect(function() {hb.flush();}).toThrow('Unsatisfied requests: GET /url2');
<add> });
<add>
<add>
<ide> it('respond() should set default status 200 if not defined', function() {
<ide> callback.andCallFake(function(status, response) {
<ide> expect(status).toBe(200); | 3 |
Javascript | Javascript | replace var with let | 3000c2528cd901c205b2276b09b77662e6c91000 | <ide><path>lib/internal/util/comparisons.js
<ide> function areSimilarFloatArrays(a, b) {
<ide> if (a.byteLength !== b.byteLength) {
<ide> return false;
<ide> }
<del> for (var offset = 0; offset < a.byteLength; offset++) {
<add> for (let offset = 0; offset < a.byteLength; offset++) {
<ide> if (a[offset] !== b[offset]) {
<ide> return false;
<ide> } | 1 |
Text | Text | add the text 'my changes' to article | 425cb4d56da67fec29a8b130bb609d77e6482bb0 | <ide><path>guide/english/book-recommendations/index.md
<ide> title: Books to Read for Programmers
<ide> This list was compiled from multiple suggestion threads on Reddit and Stackoverflow.
<ide>
<ide> Please feel free to add more that you have found useful!
<add>
<add>## Programming Books for kids to get coding
<add>
<add>*Python for Kids: A Playful Introduction to Programming by Jason Briggs (For Ages 10+)*
<add>- [Amazon Smile](https://smile.amazon.com/Python-Kids-Playful-Introduction-Programming-ebook/dp/B00ADX21Z6)
<add>- ISBN-13: 978-1593274078
<add>
<add>*Trapped in a Video Game by Dustin Brady (For Ages 8 - 12)*
<add>- [Amazon Smile](https://smile.amazon.com/Trapped-Video-Game-Book-1/dp/1449494862)
<add>- ISBN: 978-1449494865
<add>
<add>*Super Scratch Programming Adventure! by The Lead Project (For Ages 5+)*
<add>- [Amazon Smile](https://www.amazon.com/gp/product/1593274092/)
<add>- ISBN: 978-9881840820
<add>
<add>*3D Game Programming for Kids: Create Interactive Worlds with JavaScript by Chris Strom (For Ages 10+)*
<add>- [Amazon Smile](https://smile.amazon.com/gp/product/1937785440/)
<add>- ISBN-13: 978-1937785444
<add>
<add>*Hello Ruby: Adventures in Coding by Linda Liukas*
<add>- [Amazon Smile](https://smile.amazon.com/Hello-Ruby-Adventures-Linda-Liukas/dp/1250065003)
<add>- ISBN: 978-1250065001 | 1 |
Java | Java | fix ci build | a1980264691917813037c7015d9a886b938893b0 | <ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotatedJCacheableService.java
<ide> public void earlyRemoveAllWithException(boolean matchFilter) {
<ide> public void noAnnotation() {
<ide> }
<ide>
<del> @CacheRemove
<del> @CacheRemoveAll
<del> public void multiAnnotations() {
<del>
<del> }
<del>
<ide> @Override
<ide> public long exceptionInvocations() {
<ide> return exceptionCounter.get();
<ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java
<ide>
<ide> import javax.cache.annotation.CacheDefaults;
<ide> import javax.cache.annotation.CacheKeyGenerator;
<add>import javax.cache.annotation.CacheRemove;
<add>import javax.cache.annotation.CacheRemoveAll;
<ide> import javax.cache.annotation.CacheResult;
<ide>
<ide> import org.junit.Before;
<ide> public void noAnnotation() {
<ide> @Test
<ide> public void multiAnnotations() {
<ide> thrown.expect(IllegalStateException.class);
<del> getCacheOperation(AnnotatedJCacheableService.class, name.getMethodName());
<add> getCacheOperation(InvalidCases.class, name.getMethodName());
<ide> }
<ide>
<ide> @Test
<ide> public Object customKeyGeneratorAndCacheResolverWithExceptionName(Long id) {
<ide> }
<ide> }
<ide>
<add> static class InvalidCases {
<add>
<add> @CacheRemove
<add> @CacheRemoveAll
<add> public void multiAnnotations() {
<add> }
<add> }
<add>
<ide> } | 2 |
PHP | PHP | refactor the view class | 3bf85e03a58e8d2bf3fe1d9d00575a0f17627bd7 | <ide><path>system/view.php
<ide> public function get()
<ide> // evaluate any sub-views or responses that are present.
<ide> foreach ($this->data as &$data)
<ide> {
<del> if ($data instanceof View or $data instanceof Response) $data = (string) $data;
<add> if ($data instanceof View or $data instanceof Response)
<add> {
<add> $data = (string) $data;
<add> }
<ide> }
<ide>
<ide> ob_start() and extract($this->data, EXTR_SKIP); | 1 |
Javascript | Javascript | throw invalid arg type from end of stream | fe7ca085a7332524738658b3368b3c23994c006e | <ide><path>lib/internal/streams/end-of-stream.js
<ide> const {
<ide> codes,
<ide> } = require('internal/errors');
<ide> const {
<add> ERR_INVALID_ARG_TYPE,
<ide> ERR_STREAM_PREMATURE_CLOSE
<ide> } = codes;
<ide> const { once } = require('internal/util');
<ide> function eos(stream, options, callback) {
<ide>
<ide> if (!isNodeStream(stream)) {
<ide> // TODO: Webstreams.
<del> // TODO: Throw INVALID_ARG_TYPE.
<add> throw new ERR_INVALID_ARG_TYPE('stream', 'Stream', stream);
<ide> }
<ide>
<ide> const wState = stream._writableState;
<ide><path>test/parallel/test-stream-end-of-streams.js
<add>'use strict';
<add>require('../common');
<add>const assert = require('assert');
<add>
<add>const { Duplex, finished } = require('stream');
<add>
<add>assert.throws(
<add> () => {
<add> // Passing empty object to mock invalid stream
<add> // should throw error
<add> finished({}, () => {});
<add> },
<add> { code: 'ERR_INVALID_ARG_TYPE' }
<add>);
<add>
<add>const streamObj = new Duplex();
<add>streamObj.end();
<add>// Below code should not throw any errors as the
<add>// streamObj is `Stream`
<add>finished(streamObj, () => {});
<ide><path>test/parallel/test-stream-finished.js
<ide> const http = require('http');
<ide> const streamLike = new EE();
<ide> streamLike.readableEnded = true;
<ide> streamLike.readable = true;
<del> finished(streamLike, common.mustCall());
<add> assert.throws(
<add> () => {
<add> finished(streamLike, () => {});
<add> },
<add> { code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<ide> streamLike.emit('close');
<ide> }
<ide> | 3 |
Go | Go | remove engine usage from attach | c44f513248a8b40b1b2221726c7441881383e919 | <ide><path>api/server/server.go
<ide> func postContainersAttach(eng *engine.Engine, version version.Version, w http.Re
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> var (
<del> job = eng.Job("container_inspect", vars["name"])
<del> c, err = job.Stdout.AddEnv()
<del> )
<add> d := getDaemon(eng)
<add>
<add> cont, err := d.Get(vars["name"])
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err = job.Run(); err != nil {
<del> return err
<del> }
<ide>
<ide> inStream, outStream, err := hijackServer(w)
<ide> if err != nil {
<ide> func postContainersAttach(eng *engine.Engine, version version.Version, w http.Re
<ide> fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
<ide> }
<ide>
<del> if c.GetSubEnv("Config") != nil && !c.GetSubEnv("Config").GetBool("Tty") && version.GreaterThanOrEqualTo("1.6") {
<add> if !cont.Config.Tty && version.GreaterThanOrEqualTo("1.6") {
<ide> errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<ide> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<ide> } else {
<ide> errStream = outStream
<ide> }
<add> logs := r.Form.Get("logs") != ""
<add> stream := r.Form.Get("stream") != ""
<ide>
<del> job = eng.Job("attach", vars["name"])
<del> job.Setenv("logs", r.Form.Get("logs"))
<del> job.Setenv("stream", r.Form.Get("stream"))
<del> job.Setenv("stdin", r.Form.Get("stdin"))
<del> job.Setenv("stdout", r.Form.Get("stdout"))
<del> job.Setenv("stderr", r.Form.Get("stderr"))
<del> job.Stdin.Add(inStream)
<del> job.Stdout.Add(outStream)
<del> job.Stderr.Set(errStream)
<del> if err := job.Run(); err != nil {
<add> if err := cont.AttachWithLogs(inStream, outStream, errStream, logs, stream); err != nil {
<ide> fmt.Fprintf(outStream, "Error attaching: %s\n", err)
<del>
<ide> }
<ide> return nil
<ide> }
<ide> func wsContainersAttach(eng *engine.Engine, version version.Version, w http.Resp
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<add> d := getDaemon(eng)
<ide>
<del> if err := eng.Job("container_inspect", vars["name"]).Run(); err != nil {
<add> cont, err := d.Get(vars["name"])
<add> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> h := websocket.Handler(func(ws *websocket.Conn) {
<ide> defer ws.Close()
<del> job := eng.Job("attach", vars["name"])
<del> job.Setenv("logs", r.Form.Get("logs"))
<del> job.Setenv("stream", r.Form.Get("stream"))
<del> job.Setenv("stdin", r.Form.Get("stdin"))
<del> job.Setenv("stdout", r.Form.Get("stdout"))
<del> job.Setenv("stderr", r.Form.Get("stderr"))
<del> job.Stdin.Add(ws)
<del> job.Stdout.Add(ws)
<del> job.Stderr.Set(ws)
<del> if err := job.Run(); err != nil {
<add> logs := r.Form.Get("logs") != ""
<add> stream := r.Form.Get("stream") != ""
<add>
<add> if err := cont.AttachWithLogs(ws, ws, ws, logs, stream); err != nil {
<ide> logrus.Errorf("Error attaching websocket: %s", err)
<ide> }
<ide> })
<ide><path>builder/internals.go
<ide> func (b *Builder) create() (*daemon.Container, error) {
<ide> func (b *Builder) run(c *daemon.Container) error {
<ide> var errCh chan error
<ide> if b.Verbose {
<del> errCh = b.Daemon.Attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, nil, b.OutStream, b.ErrStream)
<add> errCh = c.Attach(nil, b.OutStream, b.ErrStream)
<ide> }
<ide>
<ide> //start the container
<ide><path>daemon/attach.go
<ide> package daemon
<ide>
<ide> import (
<ide> "encoding/json"
<del> "fmt"
<ide> "io"
<ide> "os"
<ide> "sync"
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/jsonlog"
<ide> "github.com/docker/docker/pkg/promise"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerAttach(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("Usage: %s CONTAINER\n", job.Name)
<del> }
<del>
<del> var (
<del> name = job.Args[0]
<del> logs = job.GetenvBool("logs")
<del> stream = job.GetenvBool("stream")
<del> stdin = job.GetenvBool("stdin")
<del> stdout = job.GetenvBool("stdout")
<del> stderr = job.GetenvBool("stderr")
<del> )
<del>
<del> container, err := daemon.Get(name)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> //logs
<add>func (c *Container) AttachWithLogs(stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error {
<ide> if logs {
<del> cLog, err := container.ReadLog("json")
<add> cLog, err := c.ReadLog("json")
<ide> if err != nil && os.IsNotExist(err) {
<ide> // Legacy logs
<ide> logrus.Debugf("Old logs format")
<del> if stdout {
<del> cLog, err := container.ReadLog("stdout")
<add> if stdout != nil {
<add> cLog, err := c.ReadLog("stdout")
<ide> if err != nil {
<ide> logrus.Errorf("Error reading logs (stdout): %s", err)
<del> } else if _, err := io.Copy(job.Stdout, cLog); err != nil {
<add> } else if _, err := io.Copy(stdout, cLog); err != nil {
<ide> logrus.Errorf("Error streaming logs (stdout): %s", err)
<ide> }
<ide> }
<del> if stderr {
<del> cLog, err := container.ReadLog("stderr")
<add> if stderr != nil {
<add> cLog, err := c.ReadLog("stderr")
<ide> if err != nil {
<ide> logrus.Errorf("Error reading logs (stderr): %s", err)
<del> } else if _, err := io.Copy(job.Stderr, cLog); err != nil {
<add> } else if _, err := io.Copy(stderr, cLog); err != nil {
<ide> logrus.Errorf("Error streaming logs (stderr): %s", err)
<ide> }
<ide> }
<ide> func (daemon *Daemon) ContainerAttach(job *engine.Job) error {
<ide> logrus.Errorf("Error streaming logs: %s", err)
<ide> break
<ide> }
<del> if l.Stream == "stdout" && stdout {
<del> io.WriteString(job.Stdout, l.Log)
<add> if l.Stream == "stdout" && stdout != nil {
<add> io.WriteString(stdout, l.Log)
<ide> }
<del> if l.Stream == "stderr" && stderr {
<del> io.WriteString(job.Stderr, l.Log)
<add> if l.Stream == "stderr" && stderr != nil {
<add> io.WriteString(stderr, l.Log)
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<ide> //stream
<ide> if stream {
<del> var (
<del> cStdin io.ReadCloser
<del> cStdout, cStderr io.Writer
<del> )
<del>
<del> if stdin {
<del> r, w := io.Pipe()
<del> go func() {
<del> defer w.Close()
<del> defer logrus.Debugf("Closing buffered stdin pipe")
<del> io.Copy(w, job.Stdin)
<del> }()
<del> cStdin = r
<del> }
<del> if stdout {
<del> cStdout = job.Stdout
<del> }
<del> if stderr {
<del> cStderr = job.Stderr
<del> }
<del>
<del> <-daemon.Attach(&container.StreamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, cStdin, cStdout, cStderr)
<add> var stdinPipe io.ReadCloser
<add> r, w := io.Pipe()
<add> go func() {
<add> defer w.Close()
<add> defer logrus.Debugf("Closing buffered stdin pipe")
<add> io.Copy(w, stdin)
<add> }()
<add> stdinPipe = r
<add> <-c.Attach(stdinPipe, stdout, stderr)
<ide> // If we are in stdinonce mode, wait for the process to end
<ide> // otherwise, simply return
<del> if container.Config.StdinOnce && !container.Config.Tty {
<del> container.WaitStop(-1 * time.Second)
<add> if c.Config.StdinOnce && !c.Config.Tty {
<add> c.WaitStop(-1 * time.Second)
<ide> }
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func (daemon *Daemon) Attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
<add>func (c *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
<add> return attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, stdin, stdout, stderr)
<add>}
<add>
<add>func attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
<ide> var (
<ide> cStdout, cStderr io.ReadCloser
<ide> cStdin io.WriteCloser
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> // FIXME: remove ImageDelete's dependency on Daemon, then move to graph/
<ide> for name, method := range map[string]engine.Handler{
<del> "attach": daemon.ContainerAttach,
<ide> "commit": daemon.ContainerCommit,
<ide> "container_changes": daemon.ContainerChanges,
<ide> "container_copy": daemon.ContainerCopy,
<ide><path>daemon/exec.go
<ide> func (d *Daemon) ContainerExecStart(job *engine.Job) error {
<ide> execConfig.StreamConfig.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
<ide> }
<ide>
<del> attachErr := d.Attach(&execConfig.StreamConfig, execConfig.OpenStdin, true, execConfig.ProcessConfig.Tty, cStdin, cStdout, cStderr)
<add> attachErr := attach(&execConfig.StreamConfig, execConfig.OpenStdin, true, execConfig.ProcessConfig.Tty, cStdin, cStdout, cStderr)
<ide>
<ide> execErr := make(chan error)
<ide> | 5 |
Go | Go | make testlogsapistdout a bit less racey | 960b8d9294356b5651938244a62e0d485da72211 | <ide><path>integration-cli/docker_api_logs_test.go
<ide> func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) {
<ide>
<ide> type logOut struct {
<ide> out string
<del> res *http.Response
<ide> err error
<ide> }
<add>
<ide> chLog := make(chan logOut)
<add> res, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id))
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> go func() {
<del> res, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id))
<del> if err != nil {
<del> chLog <- logOut{"", nil, err}
<del> return
<del> }
<ide> defer body.Close()
<ide> out, err := bufio.NewReader(body).ReadString('\n')
<ide> if err != nil {
<del> chLog <- logOut{"", nil, err}
<add> chLog <- logOut{"", err}
<ide> return
<ide> }
<del> chLog <- logOut{strings.TrimSpace(out), res, err}
<add> chLog <- logOut{strings.TrimSpace(out), err}
<ide> }()
<ide>
<ide> select {
<ide> case l := <-chLog:
<ide> c.Assert(l.err, checker.IsNil)
<del> c.Assert(l.res.StatusCode, checker.Equals, http.StatusOK)
<ide> if !strings.HasSuffix(l.out, "hello") {
<ide> c.Fatalf("expected log output to container 'hello', but it does not")
<ide> }
<del> case <-time.After(20 * time.Second):
<add> case <-time.After(30 * time.Second):
<ide> c.Fatal("timeout waiting for logs to exit")
<ide> }
<ide> } | 1 |
Text | Text | add headless js guide | d91a5c4ffb20224e19e13424068098ea05438640 | <ide><path>docs/HeadlessJSAndroid.md
<add>---
<add>id: headless-js-android
<add>title: Headless JS
<add>layout: docs
<add>category: Guides (Android)
<add>permalink: docs/headless-js-android.html
<add>next: running-on-device-android
<add>previous: native-components-android
<add>---
<add>
<add>Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
<add>
<add>## The JS API
<add>
<add>A task is a simple async function that you register on `AppRegistry`, similar to registering React applications:
<add>
<add>```js
<add>AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName'));
<add>```
<add>
<add>Then, in `SomeTaskName.js`:
<add>
<add>```js
<add>module.exports = async (taskData) => {
<add> // do stuff
<add>}
<add>```
<add>
<add>You can do anything in your task as long as it doesn't touch UI: network requests, timers and so on. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).
<add>
<add>## The Java API
<add>
<add>Yes, this does still require some native code, but it's pretty thin. You need to extend `HeadlessJsTaskService` and override `getTaskConfig`, e.g.:
<add>
<add>```java
<add>public class MyTaskService extends FbHeadlessJsTaskService {
<add>
<add> @Override
<add> protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
<add> Bundle extras = intent.getExtras();
<add> if (extras != null) {
<add> return new HeadlessJsTaskConfig(
<add> "SomeTaskName",
<add> Arguments.fromBundle(extras),
<add> 5000);
<add> }
<add> return null;
<add> }
<add>}
<add>```
<add>
<add>Now, whenever you [start your service](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)), e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.
<add>
<add>## Caveats
<add>
<add>* By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. There is a way around this.
<add>* If you start your service from a BroadcastReceiver, make sure to call `HeadlessJsTaskService.acquireWakelockNow()` before returning from `onReceive()`.
<ide>\ No newline at end of file
<ide><path>docs/NativeComponentsAndroid.md
<ide> title: Native UI Components
<ide> layout: docs
<ide> category: Guides (Android)
<ide> permalink: docs/native-components-android.html
<del>next: running-on-device-android
<add>next: headless-js-android
<ide> previous: native-modules-android
<ide> ---
<ide>
<ide><path>docs/RunningOnDeviceAndroid.md
<ide> layout: docs
<ide> category: Guides (Android)
<ide> permalink: docs/running-on-device-android.html
<ide> next: signed-apk-android
<del>props: native-components-android
<add>previous: headless-js-android
<ide> ---
<ide>
<ide> ## Prerequisite: USB Debugging | 3 |
Java | Java | update copyright year of changed file | b81c62d064f7b78fcca5deb973b10f6e49dc9af4 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 1 |
Text | Text | add pr template | 8124f9b8fafb6bd5e7c834c789709c01fedd39f5 | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<add><!--
<add>Pull Requests without a descriptive title, thorough description or tests will be closed.
<add>
<add>Please include the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.
<add>--> | 1 |
PHP | PHP | remove nested conditionals | 7402eea9ebc230a20223bf324a212bd513340838 | <ide><path>lib/Cake/View/Helper.php
<ide> public function webroot($file) {
<ide> */
<ide> public function assetUrl($path, $options = array()) {
<ide> if (is_array($path)) {
<del> $path = $this->url($path, !empty($options['fullBase']));
<del> } elseif (strpos($path, '://') === false) {
<del> if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
<del> list($plugin, $path) = $this->_View->pluginSplit($path, false);
<del> }
<del> if (!empty($options['pathPrefix']) && $path[0] !== '/') {
<del> $path = $options['pathPrefix'] . $path;
<del> }
<del> if (
<del> !empty($options['ext']) &&
<del> strpos($path, '?') === false &&
<del> substr($path, -strlen($options['ext'])) !== $options['ext']
<del> ) {
<del> $path .= $options['ext'];
<del> }
<del> if (isset($plugin)) {
<del> $path = Inflector::underscore($plugin) . '/' . $path;
<del> }
<del> $path = h($this->assetTimestamp($this->webroot($path)));
<add> return $this->url($path, !empty($options['fullBase']));
<add> }
<add> if (strpos($path, '://') !== false) {
<add> return $path;
<add> }
<add> if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
<add> list($plugin, $path) = $this->_View->pluginSplit($path, false);
<add> }
<add> if (!empty($options['pathPrefix']) && $path[0] !== '/') {
<add> $path = $options['pathPrefix'] . $path;
<add> }
<add> if (
<add> !empty($options['ext']) &&
<add> strpos($path, '?') === false &&
<add> substr($path, -strlen($options['ext'])) !== $options['ext']
<add> ) {
<add> $path .= $options['ext'];
<add> }
<add> if (isset($plugin)) {
<add> $path = Inflector::underscore($plugin) . '/' . $path;
<add> }
<add> $path = h($this->assetTimestamp($this->webroot($path)));
<ide>
<del> if (!empty($options['fullBase'])) {
<del> $base = $this->url('/', true);
<del> $len = strlen($this->request->webroot);
<del> if ($len) {
<del> $base = substr($base, 0, -$len);
<del> }
<del> $path = $base . $path;
<add> if (!empty($options['fullBase'])) {
<add> $base = $this->url('/', true);
<add> $len = strlen($this->request->webroot);
<add> if ($len) {
<add> $base = substr($base, 0, -$len);
<ide> }
<add> $path = $base . $path;
<ide> }
<del>
<ide> return $path;
<ide> }
<ide> | 1 |
Text | Text | fix structure and typo in updating.md | 72983287a1bded61e5a664b354156a90da3de99a | <ide><path>UPDATING.md
<ide> assists users migrating to a new version.
<ide>
<ide> ## Master
<ide>
<add><!--
<add>
<add>I'm glad you want to write a new note. Remember that this note is intended for users.
<add>Make sure it contains the following information:
<add>
<add>- [ ] Previous behaviors
<add>- [ ] New behaviors
<add>- [ ] If possible, a simple example of how to migrate. This may include a simple code example.
<add>- [ ] If possible, the benefit for the user after migration e.g. "we want to make these changes to unify class names."
<add>- [ ] If possible, the reason for the change, which adds more context to that interested, e.g. reference for Airflow Improvement Proposal.
<add>
<add>More tips can be found in the guide:
<add>https://developers.google.com/style/inclusive-documentation
<add>
<add>-->
<add>
<ide> ### Default `[celery] worker_concurrency` is changed to `16`
<ide>
<ide> The default value for `[celery] worker_concurrency` was `16` for Airflow <2.0.0.
<ide> DagFileProcessor to Scheduler, so we can keep the default a bit higher: `30`.
<ide>
<ide> ## Airflow 2.0.0
<ide>
<add>The 2.0 release of the Airflow is a significant upgrade, and includes substantial major changes,
<add>and some of them may be breaking. Existing code written for earlier versions of this project will may require updates
<add>to use this version. Sometimes necessary configuration changes are also required.
<add>This document describes the changes that have been made, and what you need to do to update your usage.
<add>
<add>If you experience issues or have questions, please file [an issue](https://github.com/apache/airflow/issues/new/choose).
<add>
<add>### Major changes
<add>
<add>This section describes the major changes that have been made in this release.
<add>
<ide> ### The experimental REST API is disabled by default
<ide>
<ide> The experimental REST API is disabled by default. To restore these APIs while migrating to
<ide> def execution_date_fn(execution_date, ds_nodash, dag):
<ide> ### The default value for `[webserver] cookie_samesite` has been changed to `Lax`
<ide>
<ide> As [recommended](https://flask.palletsprojects.com/en/1.1.x/config/#SESSION_COOKIE_SAMESITE) by Flask, the
<del>`[webserver] cookie_samesite` has bee changed to `Lax` from `None`.
<del>
<del>The 2.0 release of the Airflow is a significant upgrade, and includes substantial major changes,
<del>and some of them may be breaking. Existing code written for earlier versions of this project will may require updates
<del>to use this version. Sometimes necessary configuration changes are also required.
<del>This document describes the changes that have been made, and what you need to do to update your usage.
<del>
<del>If you experience issues or have questions, please file [an issue](https://github.com/apache/airflow/issues/new/choose).
<del>
<del><!--
<del>
<del>I'm glad you want to write a new note. Remember that this note is intended for users.
<del>Make sure it contains the following information:
<del>
<del>- [ ] Previous behaviors
<del>- [ ] New behaviors
<del>- [ ] If possible, a simple example of how to migrate. This may include a simple code example.
<del>- [ ] If possible, the benefit for the user after migration e.g. "we want to make these changes to unify class names."
<del>- [ ] If possible, the reason for the change, which adds more context to that interested, e.g. reference for Airflow Improvement Proposal.
<del>
<del>More tips can be found in the guide:
<del>https://developers.google.com/style/inclusive-documentation
<del>
<del>-->
<del>
<del>### Major changes
<del>
<del>This section describes the major changes that have been made in this release.
<del>
<del>
<add>`[webserver] cookie_samesite` has been changed to `Lax` from `None`.
<ide>
<ide> #### Changes to import paths
<ide> | 1 |
Python | Python | preserve spaces in gpt-2 tokenizers | f1e8a51f08eeecacf0cde33d40702d70c737003b | <ide><path>src/transformers/pipelines.py
<ide> def pipeline(
<ide> config: Optional[Union[str, PretrainedConfig]] = None,
<ide> tokenizer: Optional[Union[str, PreTrainedTokenizer]] = None,
<ide> modelcard: Optional[Union[str, ModelCard]] = None,
<add> framework: Optional[str] = None,
<ide> **kwargs
<ide> ) -> Pipeline:
<ide> """
<ide> def pipeline(
<ide> if task not in SUPPORTED_TASKS:
<ide> raise KeyError("Unknown task {}, available tasks are {}".format(task, list(SUPPORTED_TASKS.keys())))
<ide>
<del> framework = get_framework(model)
<add> framework = framework or get_framework(model)
<ide>
<ide> targeted_task = SUPPORTED_TASKS[task]
<ide> task, model_class = targeted_task["impl"], targeted_task[framework]
<ide><path>src/transformers/tokenization_gpt2.py
<ide> def bpe(self, token):
<ide> self.cache[token] = word
<ide> return word
<ide>
<del> def _tokenize(self, text, add_prefix_space=False):
<del> """ Tokenize a string.
<del> Args:
<del> - add_prefix_space (boolean, default False):
<del> Begin the sentence with at least one space to get invariance to word order in GPT-2 (and RoBERTa) tokenizers.
<del> """
<del> if add_prefix_space:
<del> text = " " + text
<del>
<add> def _tokenize(self, text):
<add> """ Tokenize a string. """
<ide> bpe_tokens = []
<ide> for token in re.findall(self.pat, text):
<ide> token = "".join(
<ide> def save_vocabulary(self, save_directory):
<ide>
<ide> return vocab_file, merge_file
<ide>
<add> def prepare_for_tokenization(self, text, **kwargs):
<add> if "add_prefix_space" in kwargs and kwargs["add_prefix_space"]:
<add> return " " + text
<add> return text
<add>
<ide>
<ide> class GPT2TokenizerFast(PreTrainedTokenizerFast):
<ide> vocab_files_names = VOCAB_FILES_NAMES
<ide><path>src/transformers/tokenization_roberta.py
<ide> def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
<ide> if token_ids_1 is None:
<ide> return len(cls + token_ids_0 + sep) * [0]
<ide> return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
<add>
<add> def prepare_for_tokenization(self, text, add_special_tokens=False, **kwargs):
<add> if "add_prefix_space" in kwargs:
<add> add_prefix_space = kwargs["add_prefix_space"]
<add> else:
<add> add_prefix_space = add_special_tokens
<add> if add_prefix_space and not text[0].isspace():
<add> text = " " + text
<add> return text
<ide><path>src/transformers/tokenization_utils.py
<ide> def tokenize(self, text, **kwargs):
<ide> Take care of added tokens.
<ide>
<ide> text: The sequence to be encoded.
<del> **kwargs: passed to the child `self.tokenize()` method
<add> add_prefix_space: Only applies to GPT-2 and RoBERTa tokenizers. When `True`, this ensures that the sequence
<add> begins with an empty space. False by default except for when using RoBERTa with `add_special_tokens=True`.
<add> **kwargs: passed to the `prepare_for_tokenization` preprocessing method.
<ide> """
<ide> all_special_tokens = self.all_special_tokens
<add> text = self.prepare_for_tokenization(text, **kwargs)
<ide>
<ide> def lowercase_text(t):
<ide> # convert non-special tokens to lowercase
<ide> def split_on_token(tok, text):
<ide> result = []
<ide> split_text = text.split(tok)
<ide> for i, sub_text in enumerate(split_text):
<del> sub_text = sub_text.strip()
<add> sub_text = sub_text.rstrip()
<ide> if i == 0 and not sub_text:
<ide> result += [tok]
<ide> elif i == len(split_text) - 1:
<ide> def split_on_tokens(tok_list, text):
<ide> if not text.strip():
<ide> return []
<ide> if not tok_list:
<del> return self._tokenize(text, **kwargs)
<add> return self._tokenize(text)
<ide>
<ide> tokenized_text = []
<ide> text_list = [text]
<ide> def split_on_tokens(tok_list, text):
<ide> return list(
<ide> itertools.chain.from_iterable(
<ide> (
<del> self._tokenize(token, **kwargs) if token not in self.unique_added_tokens_encoder else [token]
<add> self._tokenize(token) if token not in self.unique_added_tokens_encoder else [token]
<ide> for token in tokenized_text
<ide> )
<ide> )
<ide> def encode(
<ide> Defaults to False: no padding.
<ide> return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
<ide> or PyTorch torch.Tensor instead of a list of python integers.
<add> add_prefix_space: Only applies to GPT-2 and RoBERTa tokenizers. When `True`, this ensures that the sequence
<add> begins with an empty space. False by default except for when using RoBERTa with `add_special_tokens=True`.
<ide> **kwargs: passed to the `self.tokenize()` method
<ide> """
<ide> encoded_inputs = self.encode_plus(
<ide> def encode_plus(
<ide> Defaults to False: no padding.
<ide> return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
<ide> or PyTorch torch.Tensor instead of a list of python integers.
<add> add_prefix_space: Only applies to GPT-2 and RoBERTa tokenizers. When `True`, this ensures that the sequence
<add> begins with an empty space. False by default except for when using RoBERTa with `add_special_tokens=True`.
<ide> return_token_type_ids: (optional) Set to False to avoid returning token_type_ids (default True).
<ide> return_attention_mask: (optional) Set to False to avoid returning attention mask (default True)
<ide> return_overflowing_tokens: (optional) Set to True to return overflowing token information (default False).
<ide> def encode_plus(
<ide>
<ide> def get_input_ids(text):
<ide> if isinstance(text, str):
<del> return self.convert_tokens_to_ids(self.tokenize(text, **kwargs))
<add> tokens = self.tokenize(text, add_special_tokens=add_special_tokens, **kwargs)
<add> return self.convert_tokens_to_ids(tokens)
<ide> elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
<ide> return self.convert_tokens_to_ids(text)
<ide> elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
<ide> def prepare_for_model(
<ide>
<ide> return encoded_inputs
<ide>
<add> def prepare_for_tokenization(self, text, **kwargs):
<add> """ Performs any necessary transformations before tokenization """
<add> return text
<add>
<ide> def truncate_sequences(
<ide> self, ids, pair_ids=None, num_tokens_to_remove=0, truncation_strategy="longest_first", stride=0
<ide> ):
<ide><path>tests/test_pipelines.py
<ide> def _test_mono_column_pipeline(
<ide> for key in output_keys:
<ide> self.assertIn(key, mono_result[0])
<ide>
<del> multi_result = nlp(valid_inputs)
<add> multi_result = [nlp(input) for input in valid_inputs]
<ide> self.assertIsInstance(multi_result, list)
<ide> self.assertIsInstance(multi_result[0], (dict, list))
<ide>
<ide> def test_tf_ner(self):
<ide> valid_inputs = ["HuggingFace is solving NLP one commit at a time.", "HuggingFace is based in New-York & Paris"]
<ide> invalid_inputs = [None]
<ide> for tokenizer, model, config in TF_NER_FINETUNED_MODELS:
<del> nlp = pipeline(task="ner", model=model, config=config, tokenizer=tokenizer)
<add> nlp = pipeline(task="ner", model=model, config=config, tokenizer=tokenizer, framework="tf")
<ide> self._test_mono_column_pipeline(nlp, valid_inputs, invalid_inputs, mandatory_keys)
<ide>
<ide> @require_torch
<ide> def test_tf_sentiment_analysis(self):
<ide> valid_inputs = ["HuggingFace is solving NLP one commit at a time.", "HuggingFace is based in New-York & Paris"]
<ide> invalid_inputs = [None]
<ide> for tokenizer, model, config in TF_TEXT_CLASSIF_FINETUNED_MODELS:
<del> nlp = pipeline(task="sentiment-analysis", model=model, config=config, tokenizer=tokenizer)
<add> nlp = pipeline(task="sentiment-analysis", model=model, config=config, tokenizer=tokenizer, framework="tf")
<ide> self._test_mono_column_pipeline(nlp, valid_inputs, invalid_inputs, mandatory_keys)
<ide>
<ide> @require_torch
<ide> def test_tf_feature_extraction(self):
<ide> valid_inputs = ["HuggingFace is solving NLP one commit at a time.", "HuggingFace is based in New-York & Paris"]
<ide> invalid_inputs = [None]
<ide> for tokenizer, model, config in TF_FEATURE_EXTRACT_FINETUNED_MODELS:
<del> nlp = pipeline(task="feature-extraction", model=model, config=config, tokenizer=tokenizer)
<add> nlp = pipeline(task="feature-extraction", model=model, config=config, tokenizer=tokenizer, framework="tf")
<ide> self._test_mono_column_pipeline(nlp, valid_inputs, invalid_inputs, {})
<ide>
<ide> @require_torch
<ide> def test_fill_mask(self):
<ide> invalid_inputs = [None]
<ide> expected_multi_result = [
<ide> [
<del> {"score": 0.008698059245944023, "sequence": "<s>My name is John</s>", "token": 610},
<del> {"score": 0.007750614080578089, "sequence": "<s>My name is Chris</s>", "token": 1573},
<add> {"sequence": "<s> My name is:</s>", "score": 0.009954338893294334, "token": 35},
<add> {"sequence": "<s> My name is John</s>", "score": 0.0080940006300807, "token": 610},
<ide> ],
<ide> [
<del> {"score": 0.2721288502216339, "sequence": "<s>The largest city in France is Paris</s>", "token": 2201},
<ide> {
<del> "score": 0.19764970242977142,
<del> "sequence": "<s>The largest city in France is Lyon</s>",
<add> "sequence": "<s> The largest city in France is Paris</s>",
<add> "score": 0.3185044229030609,
<add> "token": 2201,
<add> },
<add> {
<add> "sequence": "<s> The largest city in France is Lyon</s>",
<add> "score": 0.21112334728240967,
<ide> "token": 12790,
<ide> },
<ide> ],
<ide> def test_tf_fill_mask(self):
<ide> invalid_inputs = [None]
<ide> expected_multi_result = [
<ide> [
<del> {"score": 0.008698059245944023, "sequence": "<s>My name is John</s>", "token": 610},
<del> {"score": 0.007750614080578089, "sequence": "<s>My name is Chris</s>", "token": 1573},
<add> {"sequence": "<s> My name is:</s>", "score": 0.009954338893294334, "token": 35},
<add> {"sequence": "<s> My name is John</s>", "score": 0.0080940006300807, "token": 610},
<ide> ],
<ide> [
<del> {"score": 0.2721288502216339, "sequence": "<s>The largest city in France is Paris</s>", "token": 2201},
<ide> {
<del> "score": 0.19764970242977142,
<del> "sequence": "<s>The largest city in France is Lyon</s>",
<add> "sequence": "<s> The largest city in France is Paris</s>",
<add> "score": 0.3185044229030609,
<add> "token": 2201,
<add> },
<add> {
<add> "sequence": "<s> The largest city in France is Lyon</s>",
<add> "score": 0.21112334728240967,
<ide> "token": 12790,
<ide> },
<ide> ],
<ide> ]
<ide> for tokenizer, model, config in TF_FILL_MASK_FINETUNED_MODELS:
<del> nlp = pipeline(task="fill-mask", model=model, config=config, tokenizer=tokenizer, topk=2)
<add> nlp = pipeline(task="fill-mask", model=model, config=config, tokenizer=tokenizer, framework="tf", topk=2)
<ide> self._test_mono_column_pipeline(
<ide> nlp,
<ide> valid_inputs,
<ide> def test_tf_question_answering(self):
<ide> ]
<ide>
<ide> for tokenizer, model, config in TF_QA_FINETUNED_MODELS:
<del> nlp = pipeline(task="question-answering", model=model, config=config, tokenizer=tokenizer)
<add> nlp = pipeline(task="question-answering", model=model, config=config, tokenizer=tokenizer, framework="tf")
<ide> self._test_multicolumn_pipeline(nlp, valid_samples, invalid_samples, mandatory_output_keys)
<ide><path>tests/test_tokenization_common.py
<ide> def test_add_special_tokens(self):
<ide> encoded = tokenizer.encode(text, add_special_tokens=False)
<ide>
<ide> input_encoded = tokenizer.encode(input_text, add_special_tokens=False)
<del> output_encoded = tokenizer.encode(output_text, add_special_tokens=False)
<add> output_encoded = tokenizer.encode(" " + output_text, add_special_tokens=False)
<ide> special_token_id = tokenizer.encode(special_token, add_special_tokens=False)
<ide> assert encoded == input_encoded + special_token_id + output_encoded
<ide>
<ide> def test_number_of_added_tokens(self):
<ide> seq_1 = "With these inputs."
<ide>
<ide> sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=False)
<del> attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True)
<add> attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True, add_prefix_space=False)
<ide>
<ide> # Method is implemented (e.g. not GPT-2)
<ide> if len(attached_sequences) != 2:
<ide> def test_maximum_encoding_length_single_input(self):
<ide> num_added_tokens = tokenizer.num_added_tokens()
<ide> total_length = len(sequence) + num_added_tokens
<ide> information = tokenizer.encode_plus(
<del> seq_0, max_length=total_length - 2, add_special_tokens=True, stride=stride, return_overflowing_tokens=True,
<add> seq_0,
<add> max_length=total_length - 2,
<add> add_special_tokens=True,
<add> stride=stride,
<add> return_overflowing_tokens=True,
<add> add_prefix_space=False,
<ide> )
<ide>
<ide> truncated_sequence = information["input_ids"]
<ide> def test_maximum_encoding_length_pair_input(self):
<ide> sequence_0_no_special_tokens = tokenizer.encode(seq_0, add_special_tokens=False)
<ide> sequence_1_no_special_tokens = tokenizer.encode(seq_1, add_special_tokens=False)
<ide>
<del> sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=True)
<add> sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=True, add_prefix_space=False)
<ide> truncated_second_sequence = tokenizer.build_inputs_with_special_tokens(
<ide> tokenizer.encode(seq_0, add_special_tokens=False), tokenizer.encode(seq_1, add_special_tokens=False)[:-2],
<ide> )
<ide> def test_maximum_encoding_length_pair_input(self):
<ide> stride=stride,
<ide> truncation_strategy="only_second",
<ide> return_overflowing_tokens=True,
<add> add_prefix_space=False,
<ide> )
<ide> information_first_truncated = tokenizer.encode_plus(
<ide> seq_0,
<ide> def test_maximum_encoding_length_pair_input(self):
<ide> stride=stride,
<ide> truncation_strategy="only_first",
<ide> return_overflowing_tokens=True,
<add> add_prefix_space=False,
<ide> )
<ide>
<ide> truncated_sequence = information["input_ids"]
<ide> def test_encode_input_type(self):
<ide>
<ide> tokens = tokenizer.tokenize(sequence)
<ide> input_ids = tokenizer.convert_tokens_to_ids(tokens)
<del> formatted_input = tokenizer.encode(sequence, add_special_tokens=True)
<add> formatted_input = tokenizer.encode(sequence, add_special_tokens=True, add_prefix_space=False)
<ide>
<ide> self.assertEqual(tokenizer.encode(tokens, add_special_tokens=True), formatted_input)
<ide> self.assertEqual(tokenizer.encode(input_ids, add_special_tokens=True), formatted_input)
<ide>
<add> def test_swap_special_token(self):
<add> tokenizer = self.get_tokenizer()
<add>
<add> mask = "<mask>"
<add> sequence = "Encode this sequence"
<add> sequence_masked_0 = "Encode <mask> sequence"
<add> sequence_masked_1 = "<mask> this sequence"
<add>
<add> # Add tokens so that masked token isn't split
<add> tokenizer.add_tokens(sequence.split())
<add> tokenizer.add_special_tokens({"mask_token": mask})
<add> mask_ind = tokenizer.convert_tokens_to_ids(mask)
<add> encoded = tokenizer.encode(sequence, add_special_tokens=False)
<add>
<add> # Test first masked sequence
<add> encoded_masked = tokenizer.encode(sequence_masked_0, add_special_tokens=False)
<add> mask_loc = encoded_masked.index(mask_ind)
<add> encoded_masked[mask_loc] = encoded[mask_loc]
<add>
<add> self.assertEqual(encoded_masked, encoded)
<add>
<add> # Test second masked sequence
<add> encoded_masked = tokenizer.encode(sequence_masked_1, add_special_tokens=False)
<add> mask_loc = encoded_masked.index(mask_ind)
<add> encoded_masked[mask_loc] = encoded[mask_loc]
<add>
<add> self.assertEqual(encoded_masked, encoded)
<add>
<ide> def test_special_tokens_mask(self):
<ide> tokenizer = self.get_tokenizer()
<ide>
<ide> def test_special_tokens_mask(self):
<ide> # Testing single inputs
<ide> encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)
<ide> encoded_sequence_dict = tokenizer.encode_plus(
<del> sequence_0, add_special_tokens=True, return_special_tokens_mask=True
<add> sequence_0, add_special_tokens=True, return_special_tokens_mask=True, add_prefix_space=False
<ide> )
<ide> encoded_sequence_w_special = encoded_sequence_dict["input_ids"]
<ide> special_tokens_mask = encoded_sequence_dict["special_tokens_mask"]
<ide> def test_special_tokens_mask(self):
<ide> self.assertEqual(encoded_sequence, filtered_sequence)
<ide>
<ide> # Testing inputs pairs
<del> encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) + tokenizer.encode(
<del> sequence_1, add_special_tokens=False
<del> )
<add> encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)
<add> encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False)
<ide> encoded_sequence_dict = tokenizer.encode_plus(
<del> sequence_0, sequence_1, add_special_tokens=True, return_special_tokens_mask=True
<add> sequence_0, sequence_1, add_special_tokens=True, return_special_tokens_mask=True, add_prefix_space=False
<ide> )
<ide> encoded_sequence_w_special = encoded_sequence_dict["input_ids"]
<ide> special_tokens_mask = encoded_sequence_dict["special_tokens_mask"]
<ide><path>tests/test_tokenization_roberta.py
<ide> def test_sequence_builders(self):
<ide>
<ide> assert encoded_sentence == encoded_text_from_decode
<ide> assert encoded_pair == encoded_pair_from_decode
<add>
<add> def test_space_encoding(self):
<add> tokenizer = self.get_tokenizer()
<add>
<add> sequence = "Encode this sequence."
<add> space_encoding = tokenizer.byte_encoder[" ".encode("utf-8")[0]]
<add>
<add> # Testing encoder arguments
<add> encoded = tokenizer.encode(sequence, add_special_tokens=False)
<add> first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
<add> self.assertNotEqual(first_char, space_encoding)
<add>
<add> encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True)
<add> first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
<add> self.assertEqual(first_char, space_encoding)
<add>
<add> tokenizer.add_special_tokens({"bos_token": "<s>"})
<add> encoded = tokenizer.encode(sequence, add_special_tokens=True)
<add> first_char = tokenizer.convert_ids_to_tokens(encoded[1])[0]
<add> self.assertEqual(first_char, space_encoding)
<add>
<add> # Testing spaces after special tokenss
<add> mask = "<mask>"
<add> tokenizer.add_special_tokens({"mask_token": mask})
<add> mask_ind = tokenizer.convert_tokens_to_ids(mask)
<add>
<add> sequence = "Encode <mask> sequence"
<add> sequence_nospace = "Encode <mask>sequence"
<add>
<add> encoded = tokenizer.encode(sequence)
<add> mask_loc = encoded.index(mask_ind)
<add> first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
<add> self.assertEqual(first_char, space_encoding)
<add>
<add> encoded = tokenizer.encode(sequence_nospace)
<add> mask_loc = encoded.index(mask_ind)
<add> first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
<add> self.assertNotEqual(first_char, space_encoding) | 7 |
Python | Python | add type hints for gptneox models | ef28a402a931a6fcbbb81c444a94470becc1299b | <ide><path>src/transformers/models/gpt_neox/modeling_gpt_neox.py
<ide> # limitations under the License.
<ide> """ PyTorch GPTNeoX model."""
<ide>
<add>from typing import Optional, Tuple, Union
<add>
<ide> import torch
<ide> import torch.utils.checkpoint
<ide> from torch import nn
<ide> def set_input_embeddings(self, value):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> past_key_values=None,
<del> use_cache=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
<add> use_cache: Optional[bool] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPast]:
<ide> r"""
<ide> past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
<ide> Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
<ide> def set_output_embeddings(self, new_embeddings):
<ide> @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> inputs_embeds=None,
<del> head_mask=None,
<del> past_key_values=None,
<del> labels=None,
<del> use_cache=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> use_cache: Optional[bool] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, CausalLMOutputWithPast]:
<ide> r"""
<ide> past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
<ide> Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape | 1 |
Javascript | Javascript | add a safe computedstyle to videojs. | 9702618c0238461ec4a7444f52618fc0c29ae4bb | <ide><path>src/js/control-bar/progress-control/mouse-time-display.js
<ide> /**
<ide> * @file mouse-time-display.js
<ide> */
<del>import window from 'global/window';
<ide> import Component from '../../component.js';
<ide> import * as Dom from '../../utils/dom.js';
<ide> import * as Fn from '../../utils/fn.js';
<ide> import formatTime from '../../utils/format-time.js';
<ide> import throttle from 'lodash-compat/function/throttle';
<add>import computedStyle from '../../utils/computed-style.js';
<ide>
<ide> /**
<ide> * The Mouse Time Display component shows the time you will seek to
<ide> class MouseTimeDisplay extends Component {
<ide> if (this.keepTooltipsInside) {
<ide> const clampedPosition = this.clampPosition_(position);
<ide> const difference = position - clampedPosition + 1;
<del> const tooltipWidth = parseFloat(window.getComputedStyle(this.tooltip).width);
<add> const tooltipWidth = parseFloat(computedStyle(this.tooltip, 'width'));
<ide> const tooltipWidthHalf = tooltipWidth / 2;
<ide>
<ide> this.tooltip.innerHTML = time;
<ide> class MouseTimeDisplay extends Component {
<ide> return position;
<ide> }
<ide>
<del> const playerWidth = parseFloat(window.getComputedStyle(this.player().el()).width);
<del> const tooltipWidth = parseFloat(window.getComputedStyle(this.tooltip).width);
<add> const playerWidth = parseFloat(computedStyle(this.player().el(), 'width'));
<add> const tooltipWidth = parseFloat(computedStyle(this.tooltip, 'width'));
<ide> const tooltipWidthHalf = tooltipWidth / 2;
<ide> let actualPosition = position;
<ide>
<ide><path>src/js/control-bar/progress-control/seek-bar.js
<ide> /**
<ide> * @file seek-bar.js
<ide> */
<del>import window from 'global/window';
<ide> import Slider from '../../slider/slider.js';
<ide> import Component from '../../component.js';
<ide> import * as Fn from '../../utils/fn.js';
<ide> import formatTime from '../../utils/format-time.js';
<add>import computedStyle from '../../utils/computed-style.js';
<ide>
<ide> import './load-progress-bar.js';
<ide> import './play-progress-bar.js';
<ide> class SeekBar extends Slider {
<ide> this.updateAriaAttributes(this.tooltipProgressBar.el_);
<ide> this.tooltipProgressBar.el_.style.width = this.bar.el_.style.width;
<ide>
<del> const playerWidth = parseFloat(window.getComputedStyle(this.player().el()).width);
<del> const tooltipWidth = parseFloat(window.getComputedStyle(this.tooltipProgressBar.tooltip).width);
<add> const playerWidth = parseFloat(computedStyle(this.player().el(), 'width'));
<add> const tooltipWidth = parseFloat(computedStyle(this.tooltipProgressBar.tooltip, 'width'));
<ide> const tooltipStyle = this.tooltipProgressBar.el().style;
<ide>
<ide> tooltipStyle.maxWidth = Math.floor(playerWidth - (tooltipWidth / 2)) + 'px';
<ide><path>src/js/utils/computed-style.js
<add>import window from 'global/window';
<add>
<add>/**
<add> * A safe getComputedStyle with an IE8 fallback.
<add> *
<add> * This is because in Firefox, if the player is loaded in an iframe with `display:none`,
<add> * then `getComputedStyle` returns `null`, so, we do a null-check to make sure
<add> * that the player doesn't break in these cases.
<add> * See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details.
<add> *
<add> * @function computedStyle
<add> * @param el the element you want the computed style of
<add> * @param prop the property name you want
<add> */
<add>export default function computedStyle(el, prop) {
<add> if (!el || !prop) {
<add> return '';
<add> }
<add>
<add> if (typeof window.getComputedStyle === 'function') {
<add> const cs = window.getComputedStyle(el);
<add>
<add> return cs ? cs[prop] : '';
<add> }
<add>
<add> return el.currentStyle[prop] || '';
<add>}
<ide><path>src/js/video.js
<ide> import log from './utils/log.js';
<ide> import * as Dom from './utils/dom.js';
<ide> import * as browser from './utils/browser.js';
<ide> import * as Url from './utils/url.js';
<add>import computedStyle from './utils/computed-style.js';
<ide> import extendFn from './extend.js';
<ide> import merge from 'lodash-compat/object/merge';
<ide> import xhr from 'xhr';
<ide> videojs.appendContent = Dom.appendContent;
<ide> */
<ide> videojs.insertContent = Dom.insertContent;
<ide>
<add>/**
<add> * A safe getComputedStyle with an IE8 fallback.
<add> *
<add> * This is because in Firefox, if the player is loaded in an iframe with `display:none`,
<add> * then `getComputedStyle` returns `null`, so, we do a null-check to make sure
<add> * that the player doesn't break in these cases.
<add> * See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details.
<add> *
<add> * @function computedStyle
<add> * @param el the element you want the computed style of
<add> * @param prop the property name you want
<add> */
<add>videojs.computedStyle = computedStyle;
<add>
<ide> /*
<ide> * Custom Universal Module Definition (UMD)
<ide> * | 4 |
Javascript | Javascript | improve perf of object model affecting view | 1520369d998c4cdeea95e2fe74b92fd6bc9c41c9 | <ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide>
<ide> // Extract item view class if provided else default to the standard class
<ide> var itemViewClass, itemViewPath = hash.itemViewClass;
<del> var collectionPrototype = get(collectionClass, 'proto');
<add> var collectionPrototype = collectionClass.proto();
<ide> delete hash.itemViewClass;
<ide> itemViewClass = itemViewPath ? getPath(collectionPrototype, itemViewPath) : collectionPrototype.itemViewClass;
<ide> ember_assert(fmt("%@ #collection: Could not find %@", data.view, itemViewPath), !!itemViewClass);
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> function makeCtor() {
<ide> // method a lot faster. This is glue code so we want it to be as fast as
<ide> // possible.
<ide>
<del> var isPrepared = false, initMixins, init = false, hasChains = false;
<add> var wasApplied = false, initMixins, init = false, hasChains = false;
<ide>
<ide> var Class = function() {
<del> if (!isPrepared) { get(Class, 'proto'); } // prepare prototype...
<add> if (!wasApplied) { Class.proto(); } // prepare prototype...
<ide> if (initMixins) {
<ide> this.reopen.apply(this, initMixins);
<ide> initMixins = null;
<ide> function makeCtor() {
<ide> };
<ide>
<ide> Class.toString = classToString;
<del> Class._prototypeMixinDidChange = function() {
<del> ember_assert("Reopening already instantiated classes is not supported. We plan to support this in the future.", isPrepared === false);
<del> isPrepared = false;
<add> Class.willReopen = function() {
<add> if (wasApplied) {
<add> Class.PrototypeMixin = Ember.Mixin.create(Class.PrototypeMixin);
<add> }
<add>
<add> wasApplied = false;
<ide> };
<ide> Class._initMixins = function(args) { initMixins = args; };
<ide>
<del> Ember.defineProperty(Class, 'proto', Ember.computed(function() {
<del> if (!isPrepared) {
<del> isPrepared = true;
<add> Class.proto = function() {
<add> var superclass = Class.superclass;
<add> if (superclass) { superclass.proto(); }
<add>
<add> if (!wasApplied) {
<add> wasApplied = true;
<ide> Class.PrototypeMixin.applyPartial(Class.prototype);
<ide> hasChains = !!meta(Class.prototype, false).chains; // avoid rewatch
<ide> }
<add>
<ide> return this.prototype;
<del> }));
<add> };
<ide>
<ide> return Class;
<ide>
<ide> var ClassMixin = Ember.Mixin.create({
<ide> },
<ide>
<ide> reopen: function() {
<add> this.willReopen();
<ide> var PrototypeMixin = this.PrototypeMixin;
<ide> PrototypeMixin.reopen.apply(PrototypeMixin, arguments);
<del> this._prototypeMixinDidChange();
<ide> return this;
<ide> },
<ide>
<ide> var ClassMixin = Ember.Mixin.create({
<ide> },
<ide>
<ide> detectInstance: function(obj) {
<del> return this.PrototypeMixin.detect(obj);
<add> return obj instanceof this;
<ide> },
<ide>
<ide> /**
<ide> var ClassMixin = Ember.Mixin.create({
<ide> This will return the original hash that was passed to `meta()`.
<ide> */
<ide> metaForProperty: function(key) {
<del> var desc = meta(get(this, 'proto'), false).descs[key];
<add> var desc = meta(this.proto(), false).descs[key];
<ide>
<ide> ember_assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty);
<ide> return desc._meta || {};
<ide> var ClassMixin = Ember.Mixin.create({
<ide> and any associated metadata (see `metaForProperty`) to the callback.
<ide> */
<ide> eachComputedProperty: function(callback, binding) {
<del> var proto = get(this, 'proto'),
<add> var proto = this.proto(),
<ide> descs = meta(proto).descs,
<ide> empty = {},
<ide> property; | 2 |
PHP | PHP | remove unused use statement | 0dbad225481a0fbdf1585f4660ccfe82ec5e24d8 | <ide><path>src/View/Helper/FormHelper.php
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Form\Form;
<del>use Cake\ORM\Entity;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector; | 1 |
Javascript | Javascript | fix change events for custom elements | 05a55a4b09b7b7c8f63778fb8252a001ca66f8d7 | <ide><path>packages/react-dom/src/__tests__/DOMPropertyOperations-test.js
<ide> describe('DOMPropertyOperations', () => {
<ide> ReactDOM = require('react-dom');
<ide> });
<ide>
<add> // Sets a value in a way that React doesn't see,
<add> // so that a subsequent "change" event will trigger the event handler.
<add> const setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'value',
<add> ).set;
<add> const setUntrackedChecked = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'checked',
<add> ).set;
<add>
<ide> describe('setValueForProperty', () => {
<ide> it('should set values as properties by default', () => {
<ide> const container = document.createElement('div');
<ide> describe('DOMPropertyOperations', () => {
<ide> expect(syntheticClickEvent.nativeEvent).toBe(nativeClickEvent);
<ide> });
<ide>
<add> // @gate enableCustomElementPropertySupport
<add> it('custom elements should have working onChange event listeners', () => {
<add> let reactChangeEvent = null;
<add> const eventHandler = jest.fn(event => (reactChangeEvent = event));
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> ReactDOM.render(<my-custom-element onChange={eventHandler} />, container);
<add> const customElement = container.querySelector('my-custom-element');
<add> let expectedHandlerCallCount = 0;
<add>
<add> const changeEvent = new Event('change', {bubbles: true});
<add> customElement.dispatchEvent(changeEvent);
<add> expectedHandlerCallCount++;
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> expect(reactChangeEvent.nativeEvent).toBe(changeEvent);
<add>
<add> // Also make sure that removing and re-adding the event listener works
<add> ReactDOM.render(<my-custom-element />, container);
<add> customElement.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> ReactDOM.render(<my-custom-element onChange={eventHandler} />, container);
<add> customElement.dispatchEvent(new Event('change', {bubbles: true}));
<add> expectedHandlerCallCount++;
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> });
<add>
<add> it('custom elements should have working onInput event listeners', () => {
<add> let reactInputEvent = null;
<add> const eventHandler = jest.fn(event => (reactInputEvent = event));
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> ReactDOM.render(<my-custom-element onInput={eventHandler} />, container);
<add> const customElement = container.querySelector('my-custom-element');
<add> let expectedHandlerCallCount = 0;
<add>
<add> const inputEvent = new Event('input', {bubbles: true});
<add> customElement.dispatchEvent(inputEvent);
<add> expectedHandlerCallCount++;
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> expect(reactInputEvent.nativeEvent).toBe(inputEvent);
<add>
<add> // Also make sure that removing and re-adding the event listener works
<add> ReactDOM.render(<my-custom-element />, container);
<add> customElement.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> ReactDOM.render(<my-custom-element onInput={eventHandler} />, container);
<add> customElement.dispatchEvent(new Event('input', {bubbles: true}));
<add> expectedHandlerCallCount++;
<add> expect(eventHandler).toHaveBeenCalledTimes(expectedHandlerCallCount);
<add> });
<add>
<add> // @gate enableCustomElementPropertySupport
<add> it('custom elements should have separate onInput and onChange handling', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const inputEventHandler = jest.fn();
<add> const changeEventHandler = jest.fn();
<add> ReactDOM.render(
<add> <my-custom-element
<add> onInput={inputEventHandler}
<add> onChange={changeEventHandler}
<add> />,
<add> container,
<add> );
<add> const customElement = container.querySelector('my-custom-element');
<add>
<add> customElement.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(inputEventHandler).toHaveBeenCalledTimes(1);
<add> expect(changeEventHandler).toHaveBeenCalledTimes(0);
<add>
<add> customElement.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(inputEventHandler).toHaveBeenCalledTimes(1);
<add> expect(changeEventHandler).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> // @gate enableCustomElementPropertySupport
<add> it('custom elements should be able to remove and re-add custom event listeners', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const eventHandler = jest.fn();
<add> ReactDOM.render(
<add> <my-custom-element oncustomevent={eventHandler} />,
<add> container,
<add> );
<add>
<add> const customElement = container.querySelector('my-custom-element');
<add> customElement.dispatchEvent(new Event('customevent'));
<add> expect(eventHandler).toHaveBeenCalledTimes(1);
<add>
<add> ReactDOM.render(<my-custom-element />, container);
<add> customElement.dispatchEvent(new Event('customevent'));
<add> expect(eventHandler).toHaveBeenCalledTimes(1);
<add>
<add> ReactDOM.render(
<add> <my-custom-element oncustomevent={eventHandler} />,
<add> container,
<add> );
<add> customElement.dispatchEvent(new Event('customevent'));
<add> expect(eventHandler).toHaveBeenCalledTimes(2);
<add> });
<add>
<add> it('<input is=...> should have the same onChange/onInput/onClick behavior as <input>', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const regularOnInputHandler = jest.fn();
<add> const regularOnChangeHandler = jest.fn();
<add> const regularOnClickHandler = jest.fn();
<add> const customOnInputHandler = jest.fn();
<add> const customOnChangeHandler = jest.fn();
<add> const customOnClickHandler = jest.fn();
<add> function clearMocks() {
<add> regularOnInputHandler.mockClear();
<add> regularOnChangeHandler.mockClear();
<add> regularOnClickHandler.mockClear();
<add> customOnInputHandler.mockClear();
<add> customOnChangeHandler.mockClear();
<add> customOnClickHandler.mockClear();
<add> }
<add> ReactDOM.render(
<add> <div>
<add> <input
<add> onInput={regularOnInputHandler}
<add> onChange={regularOnChangeHandler}
<add> onClick={regularOnClickHandler}
<add> />
<add> <input
<add> is="my-custom-element"
<add> onInput={customOnInputHandler}
<add> onChange={customOnChangeHandler}
<add> onClick={customOnClickHandler}
<add> />
<add> </div>,
<add> container,
<add> );
<add>
<add> const regularInput = container.querySelector(
<add> 'input:not([is=my-custom-element])',
<add> );
<add> const customInput = container.querySelector(
<add> 'input[is=my-custom-element]',
<add> );
<add> expect(regularInput).not.toBe(customInput);
<add>
<add> // Typing should trigger onInput and onChange for both kinds of inputs.
<add> clearMocks();
<add> setUntrackedValue.call(regularInput, 'hello');
<add> regularInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> setUntrackedValue.call(customInput, 'hello');
<add> customInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add>
<add> // The native change event itself does not produce extra React events.
<add> clearMocks();
<add> regularInput.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> customInput.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add>
<add> // The click event is handled by both inputs.
<add> clearMocks();
<add> regularInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(1);
<add> customInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(1);
<add>
<add> // Typing again should trigger onInput and onChange for both kinds of inputs.
<add> clearMocks();
<add> setUntrackedValue.call(regularInput, 'goodbye');
<add> regularInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> setUntrackedValue.call(customInput, 'goodbye');
<add> customInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add> });
<add>
<add> it('<input type=radio is=...> should have the same onChange/onInput/onClick behavior as <input type=radio>', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const regularOnInputHandler = jest.fn();
<add> const regularOnChangeHandler = jest.fn();
<add> const regularOnClickHandler = jest.fn();
<add> const customOnInputHandler = jest.fn();
<add> const customOnChangeHandler = jest.fn();
<add> const customOnClickHandler = jest.fn();
<add> function clearMocks() {
<add> regularOnInputHandler.mockClear();
<add> regularOnChangeHandler.mockClear();
<add> regularOnClickHandler.mockClear();
<add> customOnInputHandler.mockClear();
<add> customOnChangeHandler.mockClear();
<add> customOnClickHandler.mockClear();
<add> }
<add> ReactDOM.render(
<add> <div>
<add> <input
<add> type="radio"
<add> onInput={regularOnInputHandler}
<add> onChange={regularOnChangeHandler}
<add> onClick={regularOnClickHandler}
<add> />
<add> <input
<add> is="my-custom-element"
<add> type="radio"
<add> onInput={customOnInputHandler}
<add> onChange={customOnChangeHandler}
<add> onClick={customOnClickHandler}
<add> />
<add> </div>,
<add> container,
<add> );
<add>
<add> const regularInput = container.querySelector(
<add> 'input:not([is=my-custom-element])',
<add> );
<add> const customInput = container.querySelector(
<add> 'input[is=my-custom-element]',
<add> );
<add> expect(regularInput).not.toBe(customInput);
<add>
<add> // Clicking should trigger onClick and onChange on both inputs.
<add> clearMocks();
<add> setUntrackedChecked.call(regularInput, true);
<add> regularInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(1);
<add> setUntrackedChecked.call(customInput, true);
<add> customInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(1);
<add>
<add> // The native input event only produces a React onInput event.
<add> clearMocks();
<add> regularInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> customInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add>
<add> // Clicking again should trigger onClick and onChange on both inputs.
<add> clearMocks();
<add> setUntrackedChecked.call(regularInput, false);
<add> regularInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(1);
<add> setUntrackedChecked.call(customInput, false);
<add> customInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(1);
<add> });
<add>
<add> it('<select is=...> should have the same onChange/onInput/onClick behavior as <select>', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const regularOnInputHandler = jest.fn();
<add> const regularOnChangeHandler = jest.fn();
<add> const regularOnClickHandler = jest.fn();
<add> const customOnInputHandler = jest.fn();
<add> const customOnChangeHandler = jest.fn();
<add> const customOnClickHandler = jest.fn();
<add> function clearMocks() {
<add> regularOnInputHandler.mockClear();
<add> regularOnChangeHandler.mockClear();
<add> regularOnClickHandler.mockClear();
<add> customOnInputHandler.mockClear();
<add> customOnChangeHandler.mockClear();
<add> customOnClickHandler.mockClear();
<add> }
<add> ReactDOM.render(
<add> <div>
<add> <select
<add> onInput={regularOnInputHandler}
<add> onChange={regularOnChangeHandler}
<add> onClick={regularOnClickHandler}
<add> />
<add> <select
<add> is="my-custom-element"
<add> onInput={customOnInputHandler}
<add> onChange={customOnChangeHandler}
<add> onClick={customOnClickHandler}
<add> />
<add> </div>,
<add> container,
<add> );
<add>
<add> const regularSelect = container.querySelector(
<add> 'select:not([is=my-custom-element])',
<add> );
<add> const customSelect = container.querySelector(
<add> 'select[is=my-custom-element]',
<add> );
<add> expect(regularSelect).not.toBe(customSelect);
<add>
<add> // Clicking should only trigger onClick on both inputs.
<add> clearMocks();
<add> regularSelect.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(1);
<add> customSelect.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(1);
<add>
<add> // Native input event should only trigger onInput on both inputs.
<add> clearMocks();
<add> regularSelect.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> customSelect.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add>
<add> // Native change event should trigger onChange.
<add> clearMocks();
<add> regularSelect.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(regularOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(regularOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(regularOnClickHandler).toHaveBeenCalledTimes(0);
<add> customSelect.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(customOnInputHandler).toHaveBeenCalledTimes(0);
<add> expect(customOnChangeHandler).toHaveBeenCalledTimes(1);
<add> expect(customOnClickHandler).toHaveBeenCalledTimes(0);
<add> });
<add>
<add> // @gate enableCustomElementPropertySupport
<add> it('onChange/onInput/onClick on div with various types of children', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const onChangeHandler = jest.fn();
<add> const onInputHandler = jest.fn();
<add> const onClickHandler = jest.fn();
<add> function clearMocks() {
<add> onChangeHandler.mockClear();
<add> onInputHandler.mockClear();
<add> onClickHandler.mockClear();
<add> }
<add> ReactDOM.render(
<add> <div
<add> onChange={onChangeHandler}
<add> onInput={onInputHandler}
<add> onClick={onClickHandler}>
<add> <my-custom-element />
<add> <input />
<add> <input is="my-custom-element" />
<add> </div>,
<add> container,
<add> );
<add> const customElement = container.querySelector('my-custom-element');
<add> const regularInput = container.querySelector(
<add> 'input:not([is="my-custom-element"])',
<add> );
<add> const customInput = container.querySelector(
<add> 'input[is="my-custom-element"]',
<add> );
<add> expect(regularInput).not.toBe(customInput);
<add>
<add> // Custom element has no special logic for input/change.
<add> clearMocks();
<add> customElement.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> customElement.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> customElement.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add>
<add> // Regular input treats browser input as onChange.
<add> clearMocks();
<add> setUntrackedValue.call(regularInput, 'hello');
<add> regularInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> regularInput.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> regularInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add>
<add> // Custom input treats browser input as onChange.
<add> clearMocks();
<add> setUntrackedValue.call(customInput, 'hello');
<add> customInput.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> customInput.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> customInput.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add> });
<add>
<add> it('custom element onChange/onInput/onClick with event target input child', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const onChangeHandler = jest.fn();
<add> const onInputHandler = jest.fn();
<add> const onClickHandler = jest.fn();
<add> ReactDOM.render(
<add> <my-custom-element
<add> onChange={onChangeHandler}
<add> onInput={onInputHandler}
<add> onClick={onClickHandler}>
<add> <input />
<add> </my-custom-element>,
<add> container,
<add> );
<add>
<add> const input = container.querySelector('input');
<add> setUntrackedValue.call(input, 'hello');
<add> input.dispatchEvent(new Event('input', {bubbles: true}));
<add> // Simulated onChange from the child's input event
<add> // bubbles to the parent custom element.
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> // Consequently, the native change event is ignored.
<add> input.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> input.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add> });
<add>
<add> it('custom element onChange/onInput/onClick with event target div child', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const onChangeHandler = jest.fn();
<add> const onInputHandler = jest.fn();
<add> const onClickHandler = jest.fn();
<add> ReactDOM.render(
<add> <my-custom-element
<add> onChange={onChangeHandler}
<add> onInput={onInputHandler}
<add> onClick={onClickHandler}>
<add> <div />
<add> </my-custom-element>,
<add> container,
<add> );
<add>
<add> const div = container.querySelector('div');
<add> div.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add>
<add> div.dispatchEvent(new Event('change', {bubbles: true}));
<add> // React always ignores change event invoked on non-custom and non-input targets.
<add> // So change event emitted on a div does not propagate upwards.
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add>
<add> div.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add> });
<add>
<add> it('div onChange/onInput/onClick with event target div child', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const onChangeHandler = jest.fn();
<add> const onInputHandler = jest.fn();
<add> const onClickHandler = jest.fn();
<add> ReactDOM.render(
<add> <div
<add> onChange={onChangeHandler}
<add> onInput={onInputHandler}
<add> onClick={onClickHandler}>
<add> <div />
<add> </div>,
<add> container,
<add> );
<add>
<add> const div = container.querySelector('div > div');
<add> div.dispatchEvent(new Event('input', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add>
<add> div.dispatchEvent(new Event('change', {bubbles: true}));
<add> // React always ignores change event invoked on non-custom and non-input targets.
<add> // So change event emitted on a div does not propagate upwards.
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add>
<add> div.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add> });
<add>
<add> // @gate enableCustomElementPropertySupport
<add> it('custom element onChange/onInput/onClick with event target custom element child', () => {
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add> const onChangeHandler = jest.fn();
<add> const onInputHandler = jest.fn();
<add> const onClickHandler = jest.fn();
<add> ReactDOM.render(
<add> <my-custom-element
<add> onChange={onChangeHandler}
<add> onInput={onInputHandler}
<add> onClick={onClickHandler}>
<add> <other-custom-element />
<add> </my-custom-element>,
<add> container,
<add> );
<add>
<add> const customChild = container.querySelector('other-custom-element');
<add> customChild.dispatchEvent(new Event('input', {bubbles: true}));
<add> // There is no simulated onChange, only raw onInput is dispatched.
<add> expect(onChangeHandler).toBeCalledTimes(0);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> // The native change event propagates to the parent as onChange.
<add> customChild.dispatchEvent(new Event('change', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(0);
<add> customChild.dispatchEvent(new Event('click', {bubbles: true}));
<add> expect(onChangeHandler).toBeCalledTimes(1);
<add> expect(onInputHandler).toBeCalledTimes(1);
<add> expect(onClickHandler).toBeCalledTimes(1);
<add> });
<add>
<ide> // @gate enableCustomElementPropertySupport
<ide> it('custom elements should allow custom events with capture event listeners', () => {
<ide> const oncustomeventCapture = jest.fn();
<ide><path>packages/react-dom/src/events/plugins/ChangeEventPlugin.js
<ide> import {updateValueIfChanged} from '../../client/inputValueTracking';
<ide> import {setDefaultValue} from '../../client/ReactDOMInput';
<ide> import {enqueueStateRestore} from '../ReactDOMControlledComponent';
<ide>
<del>import {disableInputAttributeSyncing} from 'shared/ReactFeatureFlags';
<add>import {
<add> disableInputAttributeSyncing,
<add> enableCustomElementPropertySupport,
<add>} from 'shared/ReactFeatureFlags';
<ide> import {batchedUpdates} from '../ReactDOMUpdateBatching';
<ide> import {
<ide> processDispatchQueue,
<ide> accumulateTwoPhaseListeners,
<ide> } from '../DOMPluginEventSystem';
<add>import isCustomComponent from '../../shared/isCustomComponent';
<ide>
<ide> function registerEvents() {
<ide> registerTwoPhaseEvent('onChange', [
<ide> function extractEvents(
<ide> }
<ide> } else if (shouldUseClickEvent(targetNode)) {
<ide> getTargetInstFunc = getTargetInstForClickEvent;
<add> } else if (
<add> enableCustomElementPropertySupport &&
<add> targetInst &&
<add> isCustomComponent(targetInst.elementType, targetInst.memoizedProps)
<add> ) {
<add> getTargetInstFunc = getTargetInstForChangeEvent;
<ide> }
<ide>
<ide> if (getTargetInstFunc) { | 2 |
Ruby | Ruby | fix route recognition encoding test | 43b406bdb0a747392f30d3da404da3aa6fb29776 | <ide><path>actionpack/test/controller/routing_test.rb
<add># encoding: utf-8
<ide> require 'abstract_unit'
<ide> require 'controller/fake_controllers'
<ide> require 'active_support/dependencies'
<ide> def test_route_with_text_default
<ide> assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
<ide>
<ide> token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
<del> token.force_encoding("UTF-8") if token.respond_to?(:force_encoding)
<ide> escaped_token = CGI::escape(token)
<ide>
<ide> assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token) | 1 |
Java | Java | add debug logs to fabricuimanager | c49afb174f76b74e390f531ee67d43997d76f71b | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public class FabricUIManager implements UIManager {
<ide>
<ide> private static final String TAG = FabricUIManager.class.getSimpleName();
<ide> private static final boolean DEBUG = true;
<add>
<ide> private final RootShadowNodeRegistry mRootShadowNodeRegistry = new RootShadowNodeRegistry();
<ide> private final ReactApplicationContext mReactApplicationContext;
<ide> private final ViewManagerRegistry mViewManagerRegistry;
<ide> public FabricUIManager(
<ide> @Nullable
<ide> public ReactShadowNode createNode(
<ide> int reactTag, String viewName, int rootTag, ReadableNativeMap props) {
<add> if (DEBUG) {
<add> Log.d(TAG, "createNode \n\ttag: " + reactTag +
<add> "\n\tviewName: " + viewName +
<add> "\n\trootTag: " + rootTag +
<add> "\n\tprops: " + props);
<add> }
<ide> try {
<ide> ViewManager viewManager = mViewManagerRegistry.get(viewName);
<ide> ReactShadowNode node = viewManager.createShadowNodeInstance(mReactApplicationContext);
<ide> private ReactStylesDiffMap updateProps(ReactShadowNode node, @Nullable ReadableN
<ide> */
<ide> @Nullable
<ide> public ReactShadowNode cloneNode(ReactShadowNode node) {
<add> if (DEBUG) {
<add> Log.d(TAG, "cloneNode \n\tnode: " + node);
<add> }
<ide> try {
<ide> ReactShadowNode clone = node.mutableCopy();
<ide> assertReactShadowNodeCopy(node, clone);
<ide> public ReactShadowNode cloneNode(ReactShadowNode node) {
<ide> */
<ide> @Nullable
<ide> public ReactShadowNode cloneNodeWithNewChildren(ReactShadowNode node) {
<add> if (DEBUG) {
<add> Log.d(TAG, "cloneNodeWithNewChildren \n\tnode: " + node);
<add> }
<ide> try {
<ide> ReactShadowNode clone = node.mutableCopyWithNewChildren();
<ide> assertReactShadowNodeCopy(node, clone);
<ide> public ReactShadowNode cloneNodeWithNewChildren(ReactShadowNode node) {
<ide> @Nullable
<ide> public ReactShadowNode cloneNodeWithNewProps(
<ide> ReactShadowNode node, @Nullable ReadableNativeMap newProps) {
<add> if (DEBUG) {
<add> Log.d(TAG, "cloneNodeWithNewProps \n\tnode: " + node + "\n\tprops: " + newProps);
<add> }
<ide> try {
<ide> ReactShadowNode clone =
<ide> node.mutableCopyWithNewProps(newProps == null ? null : new ReactStylesDiffMap(newProps));
<ide> public ReactShadowNode cloneNodeWithNewProps(
<ide> @Nullable
<ide> public ReactShadowNode cloneNodeWithNewChildrenAndProps(
<ide> ReactShadowNode node, ReadableNativeMap newProps) {
<add> if (DEBUG) {
<add> Log.d(TAG, "cloneNodeWithNewChildrenAndProps \n\tnode: " + node + "\n\tnewProps: " + newProps);
<add> }
<ide> try {
<ide> ReactShadowNode clone =
<ide> node.mutableCopyWithNewChildrenAndProps(
<ide> private void assertReactShadowNodeCopy(ReactShadowNode source, ReactShadowNode t
<ide> */
<ide> @Nullable
<ide> public void appendChild(ReactShadowNode parent, ReactShadowNode child) {
<add> if (DEBUG) {
<add> Log.d(TAG, "appendChild \n\tparent: " + parent + "\n\tchild: " + child);
<add> }
<ide> try {
<ide> parent.addChildAt(child, parent.getChildCount());
<ide> } catch (Throwable t) {
<ide> public void appendChild(ReactShadowNode parent, ReactShadowNode child) {
<ide> * ReactShadowNode} elements of the root. Typically this List will contain one element.
<ide> */
<ide> public List<ReactShadowNode> createChildSet(int rootTag) {
<add> if (DEBUG) {
<add> Log.d(TAG, "createChildSet rootTag: " + rootTag);
<add> }
<ide> return new ArrayList<>(1);
<ide> }
<ide>
<ide> public void appendChildToSet(List<ReactShadowNode> childList, ReactShadowNode ch
<ide> }
<ide>
<ide> public synchronized void completeRoot(int rootTag, List<ReactShadowNode> childList) {
<add> if (DEBUG) {
<add> Log.d(TAG, "completeRoot rootTag: " + rootTag + ", childList: " + childList);
<add> }
<ide> try {
<ide> ReactShadowNode rootNode = getRootNode(rootTag);
<ide> Assertions.assertNotNull(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java
<ide> public boolean isDescendantOf(ReactShadowNodeImpl ancestorNode) {
<ide>
<ide> @Override
<ide> public String toString() {
<del> return mViewClassName;
<add> return "[" + mViewClassName + " " + getReactTag() + "]";
<ide> }
<ide>
<ide> /* | 2 |
Ruby | Ruby | remove unnecessary else statement | 7554e5cdf49bbc337ebd7cc68c5dd459c6b296af | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def setup_subscriptions
<ide> path = payload[:virtual_path]
<ide> next unless path
<ide> partial = path =~ /^.*\/_[^\/]*$/
<add>
<ide> if partial
<ide> @partials[path] += 1
<ide> @partials[path.split("/").last] += 1
<del> @templates[path] += 1
<del> else
<del> @templates[path] += 1
<ide> end
<add>
<add> @templates[path] += 1
<ide> end
<ide> end
<ide> | 1 |
Mixed | Javascript | add array.prototype.includes polyfill | ed47efe4a17a6fa3f0a2a8a36600efdcd1c65b86 | <ide><path>docs/JavaScriptEnvironment.md
<ide> ES6
<ide> * [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
<ide> * String.prototype.{[startsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith), [endsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith), [repeat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeats), [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)}
<ide> * [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
<del>* Array.prototype.{[find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find), [findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)}
<add>* Array.prototype.{[find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find), [findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex), [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)}
<ide>
<ide> ES7
<ide>
<ide><path>packager/react-packager/src/Resolver/polyfills/Array.prototype.es6.js
<ide> if (!Array.prototype.find) {
<ide> }
<ide> });
<ide> }
<add>
<add>// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
<add>if (!Array.prototype.includes) {
<add> Object.defineProperty(Array.prototype, 'includes', {
<add> enumerable: false,
<add> writable: true,
<add> configurable: true,
<add> value: function (searchElement) {
<add> var O = Object(this);
<add> var len = parseInt(O.length) || 0;
<add> if (len === 0) {
<add> return false;
<add> }
<add> var n = parseInt(arguments[1]) || 0;
<add> var k;
<add> if (n >= 0) {
<add> k = n;
<add> } else {
<add> k = len + n;
<add> if (k < 0) {
<add> k = 0;
<add> }
<add> }
<add> var currentElement;
<add> while (k < len) {
<add> currentElement = O[k];
<add> if (searchElement === currentElement ||
<add> (searchElement !== searchElement && currentElement !== currentElement)) {
<add> return true;
<add> }
<add> k++;
<add> }
<add> return false;
<add> }
<add> });
<add>} | 2 |
Go | Go | ensure clean engine shutdown on startup errors | 0e3f2f2ac07c69922bd837f864219a088d243248 | <ide><path>daemon/daemon.go
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> trustStore: t,
<ide> statsCollector: newStatsCollector(1 * time.Second),
<ide> }
<del> if err := daemon.restore(); err != nil {
<del> return nil, err
<del> }
<del>
<del> // set up filesystem watch on resolv.conf for network changes
<del> if err := daemon.setupResolvconfWatcher(); err != nil {
<del> return nil, err
<del> }
<ide>
<ide> // Setup shutdown handlers
<ide> // FIXME: can these shutdown handlers be registered closer to their source?
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> }
<ide> })
<ide>
<add> if err := daemon.restore(); err != nil {
<add> return nil, err
<add> }
<add>
<add> // set up filesystem watch on resolv.conf for network changes
<add> if err := daemon.setupResolvconfWatcher(); err != nil {
<add> return nil, err
<add> }
<add>
<ide> return daemon, nil
<ide> }
<ide>
<ide><path>docker/daemon.go
<ide> func mainDaemon() {
<ide> // load the daemon in the background so we can immediately start
<ide> // the http api so that connections don't fail while the daemon
<ide> // is booting
<add> daemonWait := make(chan struct{})
<ide> go func() {
<add> defer func() {
<add> close(daemonWait)
<add> }()
<ide> d, err := daemon.NewDaemon(daemonCfg, eng)
<ide> if err != nil {
<del> log.Fatal(err)
<add> log.Error(err)
<add> return
<ide> }
<add>
<ide> log.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
<ide> dockerversion.VERSION,
<ide> dockerversion.GITCOMMIT,
<ide> func mainDaemon() {
<ide> )
<ide>
<ide> if err := d.Install(eng); err != nil {
<del> log.Fatal(err)
<add> log.Error(err)
<add> return
<ide> }
<ide>
<ide> b := &builder.BuilderJob{eng, d}
<ide> func mainDaemon() {
<ide> // after the daemon is done setting up we can tell the api to start
<ide> // accepting connections
<ide> if err := eng.Job("acceptconnections").Run(); err != nil {
<del> log.Fatal(err)
<add> log.Error(err)
<add> return
<ide> }
<add>
<add> log.Debugf("daemon finished")
<ide> }()
<ide>
<ide> // Serve api
<ide> func mainDaemon() {
<ide> job.Setenv("TlsCert", *flCert)
<ide> job.Setenv("TlsKey", *flKey)
<ide> job.SetenvBool("BufferRequests", true)
<del> if err := job.Run(); err != nil {
<del> log.Fatal(err)
<add> err := job.Run()
<add>
<add> // Wait for the daemon startup goroutine to finish
<add> // This makes sure we can actually cleanly shutdown the daemon
<add> log.Infof("waiting for daemon to initialize")
<add> <-daemonWait
<add> eng.Shutdown()
<add> if err != nil {
<add> // log errors here so the log output looks more consistent
<add> log.Fatalf("shutting down daemon due to errors: %v", err)
<ide> }
<add>
<ide> } | 2 |
PHP | PHP | fix action reference | 3d74b25c9f5c9c340d9d7a776ad878ce333bca5c | <ide><path>src/Illuminate/Notifications/Messages/SimpleMessage.php
<ide>
<ide> namespace Illuminate\Notifications\Messages;
<ide>
<add>use Illuminate\Notifications\Action;
<add>
<ide> class SimpleMessage
<ide> {
<ide> /** | 1 |
Python | Python | change depth_radius from 5 to 2 | 11733fcafdb148878052c47dda0e4b9e76736700 | <ide><path>tutorials/image/alexnet/alexnet_benchmark.py
<ide> def inference(images):
<ide> lrn1 = tf.nn.local_response_normalization(conv1,
<ide> alpha=1e-4,
<ide> beta=0.75,
<del> depth_radius=5,
<add> depth_radius=2,
<ide> bias=2.0)
<ide>
<ide> # pool1
<ide> def inference(images):
<ide> lrn2 = tf.nn.local_response_normalization(conv2,
<ide> alpha=1e-4,
<ide> beta=0.75,
<del> depth_radius=5,
<add> depth_radius=2,
<ide> bias=2.0)
<ide>
<ide> # pool2 | 1 |
Ruby | Ruby | fix precedence error in failsafe rescue. closes | c5f00580d376a226956401e8802ab7f0ffced563 | <ide><path>railties/lib/dispatcher.rb
<ide> def dispatch(cgi = nil, session_options = ActionController::CgiRequest::DEFAULT_
<ide> end
<ide> rescue Exception => exception # errors from CGI dispatch
<ide> failsafe_response(cgi, output, '500 Internal Server Error', exception) do
<del> controller ||= ApplicationController rescue ActionController::Base
<add> controller ||= (ApplicationController rescue ActionController::Base)
<ide> controller.process_with_exception(request, response, exception).out(output)
<ide> end
<ide> ensure | 1 |
Ruby | Ruby | fix inflection regexes for mouse, mice | 6f253fb440d4979632ab7763e8cf353f9519cc35 | <ide><path>activesupport/lib/active_support/inflections.rb
<ide> module ActiveSupport
<ide> inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
<ide> inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
<ide> inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
<del> inflect.plural(/([m|l])ouse$/i, '\1ice')
<del> inflect.plural(/([m|l])ice$/i, '\1ice')
<add> inflect.plural(/(m|l)ouse$/i, '\1ice')
<add> inflect.plural(/(m|l)ice$/i, '\1ice')
<ide> inflect.plural(/^(ox)$/i, '\1en')
<ide> inflect.plural(/^(oxen)$/i, '\1')
<ide> inflect.plural(/(quiz)$/i, '\1zes')
<ide> module ActiveSupport
<ide> inflect.singular(/(s)eries$/i, '\1eries')
<ide> inflect.singular(/(m)ovies$/i, '\1ovie')
<ide> inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
<del> inflect.singular(/([m|l])ice$/i, '\1ouse')
<add> inflect.singular(/(m|l)ice$/i, '\1ouse')
<ide> inflect.singular(/(bus)es$/i, '\1')
<ide> inflect.singular(/(o)es$/i, '\1')
<ide> inflect.singular(/(shoe)s$/i, '\1')
<ide><path>activesupport/test/inflector_test_cases.rb
<ide> module InflectorTestCases
<ide> "edge" => "edges",
<ide>
<ide> "cow" => "kine",
<del> "database" => "databases"
<add> "database" => "databases",
<add>
<add> # regression tests against improper inflection regexes
<add> "|ice" => "|ices",
<add> "|ouse" => "|ouses"
<ide> }
<ide>
<ide> CamelToUnderscore = { | 2 |
PHP | PHP | add appview as a starting default | 8c922926034ef6104cf5094f3daa53f83f3e4abb | <ide><path>src/View/ViewBuilder.php
<ide> use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<del>use Cake\View\View;
<ide> use Cake\View\Exception\MissingViewException;
<add>use Cake\View\View;
<ide>
<ide>
<ide> /**
<ide> public function className($name = null)
<ide> /**
<ide> * Using the data in the builder, create a view instance.
<ide> *
<add> * If className() is null, App\View\AppView will be used.
<add> * If that class does not exist, then Cake\View\View will be used.
<add> *
<ide> * @param array $vars The view variables/context to use.
<ide> * @param \Cake\Network\Request $request The request to use.
<ide> * @param \Cake\Network\Response $response The response to use.
<ide> public function className($name = null)
<ide> */
<ide> public function build($vars = [], Request $request = null, Response $response = null, EventManager $events = null)
<ide> {
<del> if ($this->_className === 'View') {
<del> $className = App::className($this->_className, 'View');
<add> $className = $this->_className;
<add> if ($className === null) {
<add> $className = App::className('App', 'View', 'View') ?: 'Cake\View\View';
<add> }
<add> if ($className === 'View') {
<add> $className = App::className($className, 'View');
<ide> } else {
<del> $className = App::className($this->_className, 'View', 'View');
<add> $className = App::className($className, 'View', 'View');
<ide> }
<ide> if (!$className) {
<ide> throw new MissingViewException([$this->_className]);
<ide> }
<add>
<ide> $data = [
<ide> 'name' => $this->_name,
<ide> 'viewPath' => $this->_templatePath,
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View;
<ide>
<add>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\ViewBuilder;
<ide>
<ide> public function testBuildComplete()
<ide> $this->assertInstanceOf('Cake\View\Helper\FormHelper', $view->Form);
<ide> }
<ide>
<add> /**
<add> * Test that the default is AppView.
<add> *
<add> * @return void
<add> */
<add> public function testBuildAppViewMissing()
<add> {
<add> Configure::write('App.namespace', 'Nope');
<add> $builder = new ViewBuilder();
<add> $view = $builder->build();
<add> $this->assertInstanceOf('Cake\View\View', $view);
<add> }
<add>
<add> /**
<add> * Test that the default is AppView.
<add> *
<add> * @return void
<add> */
<add> public function testBuildAppViewPresent()
<add> {
<add> Configure::write('App.namespace', 'TestApp');
<add> $builder = new ViewBuilder();
<add> $view = $builder->build();
<add> $this->assertInstanceOf('TestApp\View\AppView', $view);
<add> }
<add>
<ide> /**
<ide> * test missing view class
<ide> * | 2 |
PHP | PHP | use strict assertions | 03f2df5732a663c8eadb33fdd0a3ead84b34b1d9 | <ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> public function testSelectLimitOldServer()
<ide> ])
<ide> ->offset(10);
<ide>
<del> $this->assertEquals(
<add> $this->assertSame(
<ide> 'SELECT * FROM (' .
<ide> 'SELECT id, ' .
<ide> '(SELECT count(*) FROM articles a WHERE (a.id = articles.id AND a.published = :c0)) AS computedA, ' .
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testOrderBySubquery()
<ide> ->select(['id'])
<ide> ->from('articles')
<ide> ->orderDesc($subquery)
<del> ->orderAsc('id');
<add> ->orderAsc('id')
<add> ->setSelectTypeMap(new TypeMap([
<add> 'id' => 'integer',
<add> ]));
<ide>
<ide> $this->assertQuotedQuery(
<ide> 'SELECT <id> FROM <articles> ORDER BY \(' .
<ide> public function testOrderBySubquery()
<ide> $this->assertEquals(
<ide> [
<ide> [
<del> 'id' => '3',
<add> 'id' => 3,
<ide> ],
<ide> [
<del> 'id' => '1',
<add> 'id' => 1,
<ide> ],
<ide> [
<del> 'id' => '2',
<add> 'id' => 2,
<ide> ],
<ide> ],
<ide> $query->execute()->fetchAll('assoc')
<ide> public function testReusingExpressions()
<ide> ])
<ide> ->from('articles')
<ide> ->orderDesc($subqueryB)
<del> ->orderAsc('id');
<add> ->orderAsc('id')
<add> ->setSelectTypeMap(new TypeMap([
<add> 'id' => 'integer',
<add> 'computedA' => 'integer',
<add> 'computedB' => 'integer',
<add> ]));
<ide>
<ide> $this->assertQuotedQuery(
<ide> 'SELECT <id>, ' .
<ide> public function testReusingExpressions()
<ide> !$this->autoQuote
<ide> );
<ide>
<del> $this->assertEquals(
<add> $this->assertSame(
<ide> [
<ide> [
<del> 'id' => '3',
<del> 'computedA' => '0',
<del> 'computedB' => '1',
<add> 'id' => 3,
<add> 'computedA' => 0,
<add> 'computedB' => 1,
<ide> ],
<ide> [
<del> 'id' => '1',
<del> 'computedA' => '1',
<del> 'computedB' => '0',
<add> 'id' => 1,
<add> 'computedA' => 1,
<add> 'computedB' => 0,
<ide> ],
<ide> [
<del> 'id' => '2',
<del> 'computedA' => '1',
<del> 'computedB' => '0',
<add> 'id' => 2,
<add> 'computedA' => 1,
<add> 'computedB' => 0,
<ide> ],
<ide> ],
<ide> $query->execute()->fetchAll('assoc')
<ide> );
<ide>
<del> $this->assertEquals(
<add> $this->assertSame(
<ide> [
<ide> ':c0' => [
<ide> 'value' => 'Y', | 2 |
Python | Python | fix failing dependencies for fab and celery | f76ab1f88236b3732fa402dbbf4ee7df671bb1cd | <ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'celery~=4.4.2',
<ide> 'flower>=0.7.3, <1.0',
<ide> 'tornado>=4.2.0, <6.0', # Dep of flower. Pin to a version that works on Py3.5.2
<add> 'vine~=1.3', # https://stackoverflow.com/questions/32757259/celery-no-module-named-five
<ide> ]
<ide> cgroups = [
<ide> 'cgroupspy>=0.1.4',
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'facebook-business>=6.0.2',
<ide> ]
<ide> flask_oauth = [
<del> 'Flask-OAuthlib>=0.9.1',
<add> 'Flask-OAuthlib>=0.9.1,<0.9.6', # Flask OAuthLib 0.9.6 requires Flask-Login 0.5.0 - breaks FAB
<ide> 'oauthlib!=2.0.3,!=2.0.4,!=2.0.5,<3.0.0,>=1.1.2',
<ide> 'requests-oauthlib==1.1.0',
<ide> ]
<ide> def is_package_excluded(package: str, exclusion_list: List[str]):
<ide> 'flask>=1.1.0, <2.0',
<ide> 'flask-appbuilder>2.3.4,~=3.0',
<ide> 'flask-caching>=1.3.3, <2.0.0',
<del> 'flask-login>=0.3, <1.0',
<add> 'flask-login>=0.3, <0.5',
<ide> 'flask-swagger==0.2.13',
<ide> 'flask-wtf>=0.14.2, <0.15',
<ide> 'funcsigs>=1.0.0, <2.0.0', | 1 |
Java | Java | use shared eventloopgroup in reactor2tcpclient | 5538863dc94364ef4fdbd10537ab0e2aba3f173d | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractPromiseToListenableFutureAdapter.java
<ide> public T get() throws InterruptedException {
<ide> @Override
<ide> public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
<ide> S result = this.promise.await(timeout, unit);
<del> if (result == null) {
<add> if (!this.promise.isComplete()) {
<ide> throw new TimeoutException();
<ide> }
<ide> return adapt(result);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/Reactor2TcpClient.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.Properties;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import io.netty.channel.nio.NioEventLoopGroup;
<add>import io.netty.util.concurrent.Future;
<add>import io.netty.util.concurrent.FutureListener;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.Environment;
<ide> import reactor.core.config.ConfigurationReader;
<ide> private final List<TcpClient<Message<P>, Message<P>>> tcpClients =
<ide> new ArrayList<TcpClient<Message<P>, Message<P>>>();
<ide>
<add> private final NioEventLoopGroup eventLoopGroup;
<add>
<add> private boolean stopping;
<add>
<ide>
<ide> /**
<ide> * A constructor that creates a {@link TcpClientSpec TcpClientSpec} factory
<ide> */
<ide> public Reactor2TcpClient(final String host, final int port, final Codec<Buffer, Message<P>, Message<P>> codec) {
<ide>
<del> final NioEventLoopGroup eventLoopGroup = initEventLoopGroup();
<add> this.eventLoopGroup = initEventLoopGroup();
<ide>
<ide> this.tcpClientSpecFactory = new TcpClientFactory<Message<P>, Message<P>>() {
<ide>
<ide> public TcpClientSpec<Message<P>, Message<P>> apply(TcpClientSpec<Message<P>, Mes
<ide> };
<ide> }
<ide>
<del> private NioEventLoopGroup initEventLoopGroup() {
<add> private static NioEventLoopGroup initEventLoopGroup() {
<ide> int ioThreadCount;
<ide> try {
<ide> ioThreadCount = Integer.parseInt(System.getProperty("reactor.tcp.ioThreadCount"));
<ide> private NioEventLoopGroup initEventLoopGroup() {
<ide> public Reactor2TcpClient(TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory) {
<ide> Assert.notNull(tcpClientSpecFactory, "'tcpClientClientFactory' must not be null");
<ide> this.tcpClientSpecFactory = tcpClientSpecFactory;
<add> this.eventLoopGroup = null;
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public ListenableFuture<Void> connect(final TcpConnectionHandler<P> connectionHandler) {
<ide> Assert.notNull(connectionHandler, "'connectionHandler' must not be null");
<del> Promise<Void> promise = createTcpClient().start(new MessageChannelStreamHandler<P>(connectionHandler));
<add>
<add> TcpClient<Message<P>, Message<P>> tcpClient;
<add> synchronized (this.tcpClients) {
<add> if (this.stopping) {
<add> IllegalStateException ex = new IllegalStateException("Shutting down.");
<add> connectionHandler.afterConnectFailure(ex);
<add> return new PassThroughPromiseToListenableFutureAdapter<Void>(Promises.<Void>error(ex));
<add> }
<add> tcpClient = NetStreams.tcpClient(REACTOR_TCP_CLIENT_TYPE, this.tcpClientSpecFactory);
<add> this.tcpClients.add(tcpClient);
<add> }
<add>
<add> Promise<Void> promise = tcpClient.start(new MessageChannelStreamHandler<P>(connectionHandler));
<add>
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(
<ide> promise.onError(new Consumer<Throwable>() {
<ide> @Override
<ide> public ListenableFuture<Void> connect(TcpConnectionHandler<P> connectionHandler,
<ide> Assert.notNull(connectionHandler, "'connectionHandler' must not be null");
<ide> Assert.notNull(strategy, "'reconnectStrategy' must not be null");
<ide>
<del> Stream<Tuple2<InetSocketAddress, Integer>> stream = createTcpClient().start(
<add> TcpClient<Message<P>, Message<P>> tcpClient;
<add> synchronized (this.tcpClients) {
<add> if (this.stopping) {
<add> IllegalStateException ex = new IllegalStateException("Shutting down.");
<add> connectionHandler.afterConnectFailure(ex);
<add> return new PassThroughPromiseToListenableFutureAdapter<Void>(Promises.<Void>error(ex));
<add> }
<add> tcpClient = NetStreams.tcpClient(REACTOR_TCP_CLIENT_TYPE, this.tcpClientSpecFactory);
<add> this.tcpClients.add(tcpClient);
<add> }
<add>
<add> Stream<Tuple2<InetSocketAddress, Integer>> stream = tcpClient.start(
<ide> new MessageChannelStreamHandler<P>(connectionHandler),
<ide> new ReactorReconnectAdapter(strategy));
<ide>
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(stream.next().after());
<ide> }
<ide>
<del> private TcpClient<Message<P>, Message<P>> createTcpClient() {
<del> Class<NettyTcpClient> type = REACTOR_TCP_CLIENT_TYPE;
<del> TcpClient<Message<P>, Message<P>> tcpClient = NetStreams.tcpClient(type, this.tcpClientSpecFactory);
<del> synchronized (this.tcpClients) {
<del> this.tcpClients.add(tcpClient);
<del> }
<del> return tcpClient;
<del> }
<del>
<ide> @Override
<ide> public ListenableFuture<Void> shutdown() {
<del> final List<TcpClient<Message<P>, Message<P>>> readOnlyClients;
<ide> synchronized (this.tcpClients) {
<del> readOnlyClients = new ArrayList<TcpClient<Message<P>, Message<P>>>(this.tcpClients);
<add> this.stopping = true;
<ide> }
<del> Promise<Void> promise = Streams.from(readOnlyClients)
<add> Promise<Void> promise = Streams.from(this.tcpClients)
<ide> .flatMap(new Function<TcpClient<Message<P>, Message<P>>, Promise<Void>>() {
<ide> @Override
<ide> public Promise<Void> apply(final TcpClient<Message<P>, Message<P>> client) {
<ide> return client.shutdown().onComplete(new Consumer<Promise<Void>>() {
<ide> @Override
<ide> public void accept(Promise<Void> voidPromise) {
<del> synchronized (tcpClients) {
<del> tcpClients.remove(client);
<del> }
<add> tcpClients.remove(client);
<ide> }
<ide> });
<ide> }
<ide> })
<ide> .next();
<add> if (this.eventLoopGroup != null) {
<add> final Promise<Void> eventLoopPromise = Promises.prepare();
<add> promise.onComplete(new Consumer<Promise<Void>>() {
<add> @Override
<add> public void accept(Promise<Void> voidPromise) {
<add> eventLoopGroup.shutdownGracefully().addListener(new FutureListener<Object>() {
<add> @Override
<add> public void operationComplete(Future<Object> future) throws Exception {
<add> if (future.isSuccess()) {
<add> eventLoopPromise.onComplete();
<add> }
<add> else {
<add> eventLoopPromise.onError(future.cause());
<add> }
<add> }
<add> });
<add> }
<add> });
<add> promise = eventLoopPromise;
<add> }
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(promise);
<ide> }
<ide> | 2 |
PHP | PHP | add median function | e011ca3761653d8de194441d4f5e6f6a68f9fc08 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function average($key = null)
<ide> return $this->avg($key);
<ide> }
<ide>
<add> /**
<add> * Get the median of a given key.
<add> *
<add> * @param null $key
<add> * @return mixed|null
<add> */
<add> public function median($key = null)
<add> {
<add> $count = $this->count();
<add> if ($count == 0) {
<add> return;
<add> }
<add>
<add> $collection = isset($key) ? $this->map(function ($value) use ($key) {
<add> return $value->{$key};
<add> }) : $this;
<add>
<add> $values = $collection->values()->sort();
<add> $middlePosition = (int) floor($count / 2);
<add> $hasAnOddQuantity = $count % 2;
<add>
<add> if ($hasAnOddQuantity) {
<add> return $values->get($middlePosition);
<add> }
<add>
<add> $start = $values->get($middlePosition - 1);
<add> $end = $values->get($middlePosition);
<add>
<add> return (new static([$start, $end]))->average();
<add> }
<add>
<ide> /**
<ide> * Collapse the collection of items into a single array.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testPipe()
<ide> return $collection->sum();
<ide> }));
<ide> }
<add>
<add> public function testMedianValueWithArrayCollection()
<add> {
<add> $collection = new Collection([1, 2, 2, 4]);
<add>
<add> $this->assertEquals(2, $collection->median());
<add> }
<add>
<add> public function testMedianValueByKey()
<add> {
<add> $collection = new Collection([
<add> (object) ['foo' => 1],
<add> (object) ['foo' => 2],
<add> (object) ['foo' => 2],
<add> (object) ['foo' => 4],
<add> ]);
<add> $this->assertEquals(2, $collection->median('foo'));
<add> }
<add>
<add> public function testEvenMedianCollection()
<add> {
<add> $collection = new Collection([
<add> (object) ['foo' => 0],
<add> (object) ['foo' => 3],
<add> ]);
<add> $this->assertEquals(1.5, $collection->median('foo'));
<add> }
<add>
<add> public function testMedianOnEmptyCollectionReturnsNull()
<add> {
<add> $collection = new Collection();
<add> $this->assertNull($collection->median());
<add> }
<ide> }
<ide>
<ide> class TestAccessorEloquentTestStub | 2 |
Ruby | Ruby | teach fetch to download patches | 86cdd812a2517e6dddfe9628220e5806ca6557fb | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> fetch_formula(f.bottle)
<ide> else
<ide> fetch_formula(f)
<del> f.resources.each do |r|
<del> fetch_resource(r)
<del> end
<add> f.resources.each { |r| fetch_resource(r) }
<add> f.patchlist.select(&:external?).each { |p| fetch_patch(p) }
<ide> end
<ide> end
<ide> end
<ide> def fetch_formula f
<ide> opoo "Formula reports different #{e.hash_type}: #{e.expected}"
<ide> end
<ide>
<add> def fetch_patch p
<add> fetch_fetchable p
<add> rescue ChecksumMismatchError => e
<add> Homebrew.failed = true
<add> opoo "Patch reports different #{e.hash_type}: #{e.expected}"
<add> end
<add>
<ide> private
<ide>
<ide> def retry_fetch? f
<ide><path>Library/Homebrew/formula.rb
<ide> def clear_cache
<ide> active_spec.clear_cache
<ide> end
<ide>
<add> def patchlist
<add> active_spec.patches
<add> end
<add>
<ide> # if the dir is there, but it's empty we consider it not installed
<ide> def installed?
<ide> (dir = installed_prefix).directory? && dir.children.length > 0
<ide><path>Library/Homebrew/patch.rb
<ide> require 'resource'
<ide> require 'stringio'
<ide> require 'erb'
<add>require 'forwardable'
<ide>
<ide> class Patch
<ide> def self.create(strip, io=nil, &block)
<ide> def apply
<ide> end
<ide>
<ide> class ExternalPatch < Patch
<add> extend Forwardable
<add>
<ide> attr_reader :resource, :strip
<ide>
<add> def_delegators :@resource, :fetch, :verify_download_integrity,
<add> :cached_download, :clear_cache
<add>
<ide> def initialize(strip, &block)
<ide> @strip = strip
<ide> @resource = Resource.new(&block) | 3 |
Go | Go | pass containerrmconfig as parameter | f3bce92a24300366c1f14e2a71361bceefd90e59 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide> }
<ide> defer func() {
<ide> if retErr != nil {
<del> if err := daemon.cleanupContainer(ctr, true, true); err != nil {
<del> logrus.Errorf("failed to cleanup container on create error: %v", err)
<add> err = daemon.cleanupContainer(ctr, types.ContainerRmConfig{
<add> ForceRemove: true,
<add> RemoveVolume: true,
<add> })
<add> if err != nil {
<add> logrus.WithError(err).Error("failed to cleanup container on create error")
<ide> }
<ide> }
<ide> }()
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) ContainerRm(name string, config *types.ContainerRmConfig)
<ide> return daemon.rmLink(ctr, name)
<ide> }
<ide>
<del> err = daemon.cleanupContainer(ctr, config.ForceRemove, config.RemoveVolume)
<add> err = daemon.cleanupContainer(ctr, *config)
<ide> containerActions.WithValues("delete").UpdateSince(start)
<ide>
<ide> return err
<ide> func (daemon *Daemon) rmLink(container *container.Container, name string) error
<ide>
<ide> // cleanupContainer unregisters a container from the daemon, stops stats
<ide> // collection and cleanly removes contents and metadata from the filesystem.
<del>func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemove, removeVolume bool) error {
<add>func (daemon *Daemon) cleanupContainer(container *container.Container, config types.ContainerRmConfig) error {
<ide> if container.IsRunning() {
<del> if !forceRemove {
<add> if !config.ForceRemove {
<ide> state := container.StateString()
<ide> procedure := "Stop the container before attempting removal or force remove"
<ide> if state == "paused" {
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide> daemon.idIndex.Delete(container.ID)
<ide> daemon.containers.Delete(container.ID)
<ide> daemon.containersReplica.Delete(container)
<del> if err := daemon.removeMountPoints(container, removeVolume); err != nil {
<add> if err := daemon.removeMountPoints(container, config.RemoveVolume); err != nil {
<ide> logrus.Error(err)
<ide> }
<ide> for _, name := range linkNames { | 2 |
Javascript | Javascript | add resizing support to afterimagepass | 9e402e577be661179043699e3295f2b1def50042 | <ide><path>examples/js/postprocessing/AfterimagePass.js
<ide> THREE.AfterimagePass.prototype = Object.assign( Object.create( THREE.Pass.protot
<ide>
<ide> }
<ide>
<add> },
<add>
<add> setSize: function ( width, height ) {
<add>
<add> this.textureComp.setSize( width, height );
<add> this.textureOld.setSize( width, height );
<add>
<ide> }
<ide>
<ide> } ); | 1 |
Javascript | Javascript | remove artificial isenabled tests | 29a1fc2114b28b8fa25ba4dd88e807ead1f581d9 | <ide><path>packages/ember-metal/tests/features_test.js
<del>import { ENV } from 'ember-environment';
<del>import isEnabled, { FEATURES } from 'ember-metal/features';
<del>import assign from 'ember-metal/assign';
<del>
<del>var origFeatures, origEnableOptional;
<del>
<del>QUnit.module('isEnabled', {
<del> setup() {
<del> origFeatures = assign({}, FEATURES);
<del> origEnableOptional = ENV.ENABLE_OPTIONAL_FEATURES;
<del> },
<del>
<del> teardown() {
<del> for (var feature in FEATURES) {
<del> delete FEATURES[feature];
<del> }
<del> assign(FEATURES, origFeatures);
<del>
<del> ENV.ENABLE_OPTIONAL_FEATURES = origEnableOptional;
<del> }
<del>});
<del>
<del>QUnit.test('ENV.ENABLE_OPTIONAL_FEATURES', function() {
<del> ENV.ENABLE_OPTIONAL_FEATURES = true;
<del> FEATURES['fred'] = false;
<del> FEATURES['barney'] = true;
<del> FEATURES['wilma'] = null;
<del>
<del> equal(isEnabled('fred'), false, 'returns flag value if false');
<del> equal(isEnabled('barney'), true, 'returns flag value if true');
<del> equal(isEnabled('wilma'), true, 'returns true if flag is not true|false|undefined');
<del> equal(isEnabled('betty'), undefined, 'returns flag value if undefined');
<del>});
<del>
<del>QUnit.test('isEnabled without ENV options', function() {
<del> ENV.ENABLE_OPTIONAL_FEATURES = false;
<del>
<del> FEATURES['fred'] = false;
<del> FEATURES['barney'] = true;
<del> FEATURES['wilma'] = null;
<del>
<del> equal(isEnabled('fred'), false, 'returns flag value if false');
<del> equal(isEnabled('barney'), true, 'returns flag value if true');
<del> equal(isEnabled('wilma'), false, 'returns false if flag is not set');
<del> equal(isEnabled('betty'), undefined, 'returns flag value if undefined');
<del>}); | 1 |
Javascript | Javascript | add news to the env file | 0369dfbf37caaf523b7d8c87a17cf72df2d08a25 | <ide><path>config/env.js
<ide> const {
<ide> HOME_LOCATION: home,
<ide> API_LOCATION: api,
<ide> FORUM_LOCATION: forum,
<add> NEWS_LOCATION: news,
<ide> LOCALE: locale,
<ide> } = process.env;
<ide>
<ide> const locations = {
<ide> homeLocation: home,
<ide> apiLocation: api,
<del> forumLocation: forum
<add> forumLocation: forum,
<add> newsLocation: news
<ide> };
<ide>
<ide> module.exports = Object.assign(locations, { locale }); | 1 |
Javascript | Javascript | remove unused jquerydisabled flag | d26676cab6a1e60ae5cd7985675f8314c89cb2f4 | <ide><path>packages/ember-glimmer/tests/integration/event-dispatcher-test.js
<ide> import {
<ide> run
<ide> } from 'ember-metal';
<ide> import { EMBER_IMPROVED_INSTRUMENTATION } from 'ember/features';
<del>import { jQueryDisabled } from 'ember-views';
<ide>
<ide> let canDataTransfer = !!document.createEvent('HTMLEvents').dataTransfer;
<ide> | 1 |
Text | Text | fix typo in cli.md | 472a8a7f8dc09dc0c0b2643d2449e3aa5ca58c71 | <ide><path>doc/api/cli.md
<ide> If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's directory
<ide> containing trusted certificates.
<ide>
<ide> *Note*: Be aware that unless the child environment is explicitly set, this
<del>evironment variable will be inherited by any child processes, and if they use
<add>environment variable will be inherited by any child processes, and if they use
<ide> OpenSSL, it may cause them to trust the same CAs as node.
<ide>
<ide> ### `SSL_CERT_FILE=file`
<ide> If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's file
<ide> containing trusted certificates.
<ide>
<ide> *Note*: Be aware that unless the child environment is explicitly set, this
<del>evironment variable will be inherited by any child processes, and if they use
<add>environment variable will be inherited by any child processes, and if they use
<ide> OpenSSL, it may cause them to trust the same CAs as node.
<ide>
<ide> ### `NODE_REDIRECT_WARNINGS=file` | 1 |
Javascript | Javascript | cover vm with negative tests | ee14a645379e4eff58ab106f1eae7abc70a01d9e | <ide><path>test/parallel/test-vm-module-basic.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const { SourceTextModule, SyntheticModule, createContext } = require('vm');
<add>const {
<add> Module,
<add> SourceTextModule,
<add> SyntheticModule,
<add> createContext
<add>} = require('vm');
<ide> const util = require('util');
<ide>
<ide> (async function test1() {
<ide> const util = require('util');
<ide> assert.notStrictEqual(dep, undefined);
<ide> assert.strictEqual(dep, m.dependencySpecifiers);
<ide> }
<add>
<add>// Check the impossibility of creating an abstract instance of the Module.
<add>{
<add> common.expectsError(() => new Module(), {
<add> message: 'Module is not a constructor',
<add> type: TypeError
<add> });
<add>}
<add>
<add>// Check to throws invalid exportNames
<add>{
<add> common.expectsError(() => new SyntheticModule(undefined, () => {}, {}), {
<add> message: 'The "exportNames" argument must be an Array of strings.' +
<add> ' Received undefined',
<add> type: TypeError
<add> });
<add>}
<add>
<add>// Check to throws invalid evaluateCallback
<add>{
<add> common.expectsError(() => new SyntheticModule([], undefined, {}), {
<add> message: 'The "evaluateCallback" argument must be of type function.' +
<add> ' Received undefined',
<add> type: TypeError
<add> });
<add>}
<add>
<add>// Check to throws invalid options
<add>{
<add> common.expectsError(() => new SyntheticModule([], () => {}, null), {
<add> message: 'The "options" argument must be of type object.' +
<add> ' Received null',
<add> type: TypeError
<add> });
<add>} | 1 |
Java | Java | add finally0 to observable.java | e517f55833c7ec02676bd850e9cd8f302a8a713f | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public static <T> Observable<T> concat(Observable<T>... source) {
<ide> return _create(OperationConcat.concat(source));
<ide> }
<ide>
<add> /**
<add> * Emits the same objects as the given Observable, calling the given action
<add> * when it calls <code>onComplete</code> or <code>onError</code>.
<add> * @param source an observable
<add> * @param action an action to be called when the source completes or errors.
<add> * @return an Observable that emits the same objects, then calls the action.
<add> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN: Observable.Finally Method</a>
<add> */
<add> public static <T> Observable<T> finally0(Observable source, Action0 action) {
<add> return _create(OperationFinally.finally0(source, action));
<add> }
<add>
<ide> /**
<ide> * Groups the elements of an observable and selects the resulting elements by using a specified function.
<ide> *
<ide><path>rxjava-core/src/main/java/rx/operators/OperationFinally.java
<ide> /**
<ide> * Copyright 2013 Netflix, Inc.
<del> *
<add> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<del> *
<add> *
<ide> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<add> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> import java.util.List;
<ide> import java.util.concurrent.CountDownLatch;
<ide>
<del>import org.junit.Assert;
<del>import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> import rx.Observable;
<ide> import rx.Observer;
<ide> import rx.Subscription;
<ide> import rx.util.AtomicObservableSubscription;
<del>import rx.util.AtomicObserver;
<ide> import rx.util.functions.Action0;
<ide> import rx.util.functions.Func1;
<ide>
<ide> public final class OperationFinally {
<ide> * exception). The returned observable is exactly as threadsafe as the
<ide> * source observable; in particular, any situation allowing the source to
<ide> * call onComplete or onError multiple times allows the returned observable
<del> * to call the action multiple times.
<add> * to call the final action multiple times.
<ide> * <p/>
<ide> * Note that "finally" is a Java reserved word and cannot be an identifier,
<ide> * so we use "finally0".
<del> *
<add> *
<ide> * @param sequence An observable sequence of elements
<ide> * @param action An action to be taken when the sequence is complete or throws an exception
<ide> * @return An observable sequence with the same elements as the input.
<ide> * After the last element is consumed (just before {@link Observer#onComplete} is called),
<del> * or when an exception is thrown (just before {@link Observer#onError}), the action will be taken.
<add> * or when an exception is thrown (just before {@link Observer#onError}), the action will be called.
<ide> * @see http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx
<ide> */
<ide> public static <T> Func1<Observer<T>, Subscription> finally0(final Observable<T> sequence, final Action0 action) {
<ide> private static class TestAction implements Action0 {
<ide> called++;
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void testFinally() {
<ide> final String[] n = {"1", "2", "3"};
<ide> final Observable<String> nums = Observable.toObservable(n);
<ide> TestAction action = new TestAction();
<ide> action.called = 0;
<del> @SuppressWarnings("unchecked")
<ide> Observable<String> fin = Observable.create(finally0(nums, action));
<ide> @SuppressWarnings("unchecked")
<ide> Observer<String> aObserver = mock(Observer.class);
<ide> fin.subscribe(aObserver);
<del> Assert.assertEquals(1, action.called);
<add> assertEquals(1, action.called);
<ide>
<ide> action.called = 0;
<ide> Observable<String> error = Observable.<String>error(new RuntimeException("expected"));
<ide> fin = Observable.create(finally0(error, action));
<ide> fin.subscribe(aObserver);
<del> Assert.assertEquals(1, action.called);
<add> assertEquals(1, action.called);
<ide> }
<ide> }
<del>}
<ide>\ No newline at end of file
<add>} | 2 |
Ruby | Ruby | fix bogus line that was raising warning | 2044294a865a85c4c3144a3000bd9a48427e12c6 | <ide><path>Library/Homebrew/cmd/pull.rb
<ide> def verify_bintray_published(formulae_names)
<ide> # We're in the cache; make sure to force re-download
<ide> while true do
<ide> begin
<del> retry_count = retry_count
<ide> curl url, "-o", filename
<ide> break
<ide> rescue | 1 |
Javascript | Javascript | memorize the keyframetrack.setresult() | e9cd1a28124456ee10d080ac1e311e047cdb61de | <ide><path>src/animation/KeyframeTrack.js
<ide> THREE.KeyframeTrack = function ( name, keys ) {
<ide> this.result = THREE.AnimationUtils.clone( this.keys[0].value );
<ide> //console.log( 'constructor result', this.result )
<ide>
<add> // the index of the last result, used as a starting point for local search.
<add> // TODO: this is okay in the keyframetrack, but it would be better stored in AnimationAction eventually.
<ide> this.lastIndex = 0;
<ide>
<ide> this.sort();
<ide> THREE.KeyframeTrack.prototype = {
<ide> var prevKey = this.keys[ this.lastIndex - 1 ];
<ide> this.setResult( prevKey.value );
<ide>
<add> // if true, means that prev/current keys are identical, thus no interpolation required.
<ide> if( prevKey.constantToNext ) {
<del>
<add>
<ide> return this.result;
<ide>
<ide> }
<ide> THREE.KeyframeTrack.prototype = {
<ide> var currentKey = this.keys[ this.lastIndex ];
<ide> var alpha = ( time - prevKey.time ) / ( currentKey.time - prevKey.time );
<ide> this.result = this.lerp( this.result, currentKey.value, alpha );
<add>
<ide> //console.log( 'lerp result', this.result )
<ide> /*if( /morph/i.test( this.name ) ) {
<ide> console.log( ' interpolated: ', {
<ide> THREE.KeyframeTrack.prototype = {
<ide> },
<ide>
<ide> setResult: function( value ) {
<add>
<ide> if( this.result.copy ) {
<del> this.result.copy( value );
<add>
<add> setResult = function( value ) {
<add> this.result.copy( value );
<add> }
<add>
<ide> }
<ide> else {
<del> this.result = value;
<add>
<add> setResult = function( value ) {
<add> this.result = value;
<add> }
<add>
<ide> }
<add>
<add> this.setResult( value );
<add>
<ide> },
<ide>
<ide> // memoization of the lerp function for speed. | 1 |
Javascript | Javascript | use branchpattern where we are replacing * | 1a7e9de8d8efcb1b2453b5553fa4aad36521750f | <ide><path>lib/versions/version-info.js
<ide> var getTaggedVersion = function() {
<ide> if ( version && semver.satisfies(version, currentPackage.branchVersion)) {
<ide> version.codeName = getCodeName(tag);
<ide> version.full = version.version;
<del> version.branch = 'v' + currentPackage.branchVersion.replace('*', 'x');
<add> version.branch = 'v' + currentPackage.branchPattern.replace('*', 'x');
<ide> return version;
<ide> }
<ide> }
<ide> var getCdnVersion = function() {
<ide> return semver.satisfies(tag, currentPackage.branchVersion);
<ide> })
<ide> .reverse()
<add> .tap(function(versions) {
<add> console.log(versions);
<add> })
<ide> .reduce(function(cdnVersion, version) {
<ide> if (!cdnVersion) {
<ide> // Note: need to use shell.exec and curl here
<ide> // as version-infos returns its result synchronously...
<ide> var cdnResult = shell.exec('curl http://ajax.googleapis.com/ajax/libs/angularjs/'+version+'/angular.min.js '+
<ide> '--head --write-out "%{http_code}" -o /dev/null -silent',
<del> {silent: true});
<add> {silent: false});
<add> console.log('http://ajax.googleapis.com/ajax/libs/angularjs/'+version+'/angular.min.js');
<ide> if ( cdnResult.code === 0 ) {
<ide> var statusCode = cdnResult.output.trim();
<ide> if (statusCode === '200') {
<ide> var getSnapshotVersion = function() {
<ide>
<ide> if ( !version ) {
<ide> // a snapshot version before the first tag on the branch
<del> version = semver(currentPackage.branchVersion.replace('*','0-beta.1'));
<add> version = semver(currentPackage.branchPattern.replace('*','0-beta.1'));
<ide> }
<ide>
<ide> // We need to clone to ensure that we are not modifying another version | 1 |
Python | Python | fix regression in intersect1d | fc2df52313c6db5ba4ccbd10b233cee6b4acec2c | <ide><path>numpy/lib/arraysetops.py
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> If True, the input arrays are both assumed to be unique, which
<ide> can speed up the calculation. Default is False.
<ide> return_indices : bool
<del> If True, the indices which correspond to the intersection of the
<del> two arrays are returned. The first instance of a value is used
<del> if there are multiple. Default is False.
<del>
<del> .. versionadded:: 1.15.0
<del>
<add> If True, the indices which correspond to the intersection of the two
<add> arrays are returned. The first instance of a value is used if there are
<add> multiple. Default is False.
<add>
<add> .. versionadded:: 1.15.0
<add>
<ide> Returns
<ide> -------
<ide> intersect1d : ndarray
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> The indices of the first occurrences of the common values in `ar1`.
<ide> Only provided if `return_indices` is True.
<ide> comm2 : ndarray
<del> The indices of the first occurrences of the common values in `ar2`.
<add> The indices of the first occurrences of the common values in `ar2`.
<ide> Only provided if `return_indices` is True.
<ide>
<ide>
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> >>> from functools import reduce
<ide> >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
<ide> array([3])
<del>
<add>
<ide> To return the indices of the values common to the input arrays
<ide> along with the intersected values:
<ide> >>> x = np.array([1, 1, 2, 3, 4])
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> (array([0, 2, 4]), array([1, 0, 2]))
<ide> >>> xy, x[x_ind], y[y_ind]
<ide> (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
<del>
<add>
<ide> """
<add> ar1 = np.asanyarray(ar1)
<add> ar2 = np.asanyarray(ar2)
<add>
<ide> if not assume_unique:
<ide> if return_indices:
<ide> ar1, ind1 = unique(ar1, return_index=True)
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> else:
<ide> ar1 = ar1.ravel()
<ide> ar2 = ar2.ravel()
<del>
<add>
<ide> aux = np.concatenate((ar1, ar2))
<ide> if return_indices:
<ide> aux_sort_indices = np.argsort(aux, kind='mergesort')
<ide> def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
<ide> else:
<ide> return int1d
<ide>
<add>
<ide> def setxor1d(ar1, ar2, assume_unique=False):
<ide> """
<ide> Find the set exclusive-or of two arrays.
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def test_intersect1d(self):
<ide> ed = np.array([1, 2, 5])
<ide> c = intersect1d(a, b)
<ide> assert_array_equal(c, ed)
<del>
<ide> assert_array_equal([], intersect1d([], []))
<del>
<add>
<add> def test_intersect1d_array_like(self):
<add> # See gh-11772
<add> class Test(object):
<add> def __array__(self):
<add> return np.arange(3)
<add>
<add> a = Test()
<add> res = intersect1d(a, a)
<add> assert_array_equal(res, a)
<add> res = intersect1d([1, 2, 3], [1, 2, 3])
<add> assert_array_equal(res, [1, 2, 3])
<add>
<ide> def test_intersect1d_indices(self):
<ide> # unique inputs
<del> a = np.array([1, 2, 3, 4])
<add> a = np.array([1, 2, 3, 4])
<ide> b = np.array([2, 1, 4, 6])
<ide> c, i1, i2 = intersect1d(a, b, assume_unique=True, return_indices=True)
<ide> ee = np.array([1, 2, 4])
<ide> assert_array_equal(c, ee)
<ide> assert_array_equal(a[i1], ee)
<ide> assert_array_equal(b[i2], ee)
<del>
<add>
<ide> # non-unique inputs
<ide> a = np.array([1, 2, 2, 3, 4, 3, 2])
<ide> b = np.array([1, 8, 4, 2, 2, 3, 2, 3])
<ide> def test_intersect1d_indices(self):
<ide> assert_array_equal(c, ef)
<ide> assert_array_equal(a[i1], ef)
<ide> assert_array_equal(b[i2], ef)
<del>
<add>
<ide> # non1d, unique inputs
<ide> a = np.array([[2, 4, 5, 6], [7, 8, 1, 15]])
<ide> b = np.array([[3, 2, 7, 6], [10, 12, 8, 9]])
<ide> def test_intersect1d_indices(self):
<ide> ea = np.array([2, 6, 7, 8])
<ide> assert_array_equal(ea, a[ui1])
<ide> assert_array_equal(ea, b[ui2])
<del>
<add>
<ide> # non1d, not assumed to be uniqueinputs
<ide> a = np.array([[2, 4, 5, 6, 6], [4, 7, 8, 7, 2]])
<ide> b = np.array([[3, 2, 7, 7], [10, 12, 8, 7]])
<ide> def test_intersect1d_indices(self):
<ide> ea = np.array([2, 7, 8])
<ide> assert_array_equal(ea, a[ui1])
<ide> assert_array_equal(ea, b[ui2])
<del>
<add>
<ide> def test_setxor1d(self):
<ide> a = np.array([5, 7, 1, 2])
<ide> b = np.array([2, 4, 3, 1, 5]) | 2 |
Javascript | Javascript | remove useless shouldverify assignments | 5dab4be53ced9907ea27e7d8624a61031b31dd13 | <ide><path>lib/crypto.js
<ide> function Credentials (method) {
<ide> this.context.init();
<ide> }
<ide>
<del> this.shouldVerify = false;
<ide> }
<ide>
<ide> exports.Credentials = Credentials;
<ide> exports.createCredentials = function (options) {
<ide> if (options.cert) c.context.setCert(options.cert);
<ide>
<ide> if (options.ca) {
<del> c.shouldVerify = true;
<ide> if (Array.isArray(options.ca)) {
<ide> for (var i = 0, len = options.ca.length; i < len; i++) {
<ide> c.context.addCACert(options.ca[i]); | 1 |
Go | Go | remove unused features | 4fb1db7f742fb34a7a06621d0698063de87a572c | <ide><path>archive/archive.go
<ide> type Compression int
<ide>
<ide> type TarOptions struct {
<ide> Includes []string
<del> Excludes []string
<del> Recursive bool
<ide> Compression Compression
<del> CreateFiles []string
<ide> }
<ide>
<ide> const (
<ide> func DetectCompression(source []byte) Compression {
<ide> func xzDecompress(archive io.Reader) (io.Reader, error) {
<ide> args := []string{"xz", "-d", "-c", "-q"}
<ide>
<del> return CmdStream(exec.Command(args[0], args[1:]...), archive, nil)
<add> return CmdStream(exec.Command(args[0], args[1:]...), archive)
<ide> }
<ide>
<ide> func DecompressStream(archive io.Reader) (io.Reader, error) {
<ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader *tar.Reader)
<ide> // Tar creates an archive from the directory at `path`, and returns it as a
<ide> // stream of bytes.
<ide> func Tar(path string, compression Compression) (io.Reader, error) {
<del> return TarFilter(path, &TarOptions{Recursive: true, Compression: compression})
<add> return TarFilter(path, &TarOptions{Compression: compression})
<ide> }
<ide>
<ide> func escapeName(name string) string {
<ide> func TarFilter(path string, options *TarOptions) (io.Reader, error) {
<ide> }
<ide> args = append(args, "-c"+options.Compression.Flag())
<ide>
<del> for _, exclude := range options.Excludes {
<del> args = append(args, fmt.Sprintf("--exclude=%s", exclude))
<del> }
<del>
<del> if !options.Recursive {
<del> args = append(args, "--no-recursion")
<del> }
<del>
<ide> files := ""
<ide> for _, f := range options.Includes {
<ide> files = files + escapeName(f) + "\n"
<ide> }
<ide>
<del> tmpDir := ""
<del>
<del> if options.CreateFiles != nil {
<del> var err error // Can't use := here or we override the outer tmpDir
<del> tmpDir, err = ioutil.TempDir("", "docker-tar")
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> files = files + "-C" + tmpDir + "\n"
<del> for _, f := range options.CreateFiles {
<del> path := filepath.Join(tmpDir, f)
<del> err := os.MkdirAll(filepath.Dir(path), 0600)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> if file, err := os.OpenFile(path, os.O_CREATE, 0600); err != nil {
<del> return nil, err
<del> } else {
<del> file.Close()
<del> }
<del> files = files + escapeName(f) + "\n"
<del> }
<del> }
<del>
<del> return CmdStream(exec.Command(args[0], args[1:]...), bytes.NewBufferString(files), func() {
<del> if tmpDir != "" {
<del> _ = os.RemoveAll(tmpDir)
<del> }
<del> })
<add> return CmdStream(exec.Command(args[0], args[1:]...), bytes.NewBufferString(files))
<ide> }
<ide>
<ide> // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> return err
<ide> }
<ide>
<del> if options != nil {
<del> excludeFile := false
<del> for _, exclude := range options.Excludes {
<del> if strings.HasPrefix(hdr.Name, exclude) {
<del> excludeFile = true
<del> break
<del> }
<del> }
<del> if excludeFile {
<del> continue
<del> }
<del> }
<del>
<ide> // Normalize name, for safety and for a simple is-root check
<ide> hdr.Name = filepath.Clean(hdr.Name)
<ide>
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> // TarUntar is a convenience function which calls Tar and Untar, with
<ide> // the output of one piped into the other. If either Tar or Untar fails,
<ide> // TarUntar aborts and returns the error.
<del>func TarUntar(src string, filter []string, dst string) error {
<del> utils.Debugf("TarUntar(%s %s %s)", src, filter, dst)
<del> archive, err := TarFilter(src, &TarOptions{Compression: Uncompressed, Includes: filter, Recursive: true})
<add>func TarUntar(src string, dst string) error {
<add> utils.Debugf("TarUntar(%s %s)", src, dst)
<add> archive, err := TarFilter(src, &TarOptions{Compression: Uncompressed})
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func CopyWithTar(src, dst string) error {
<ide> return err
<ide> }
<ide> utils.Debugf("Calling TarUntar(%s, %s)", src, dst)
<del> return TarUntar(src, nil, dst)
<add> return TarUntar(src, dst)
<ide> }
<ide>
<ide> // CopyFileWithTar emulates the behavior of the 'cp' command-line
<ide> func CopyFileWithTar(src, dst string) (err error) {
<ide> // CmdStream executes a command, and returns its stdout as a stream.
<ide> // If the command fails to run or doesn't complete successfully, an error
<ide> // will be returned, including anything written on stderr.
<del>func CmdStream(cmd *exec.Cmd, input io.Reader, atEnd func()) (io.Reader, error) {
<add>func CmdStream(cmd *exec.Cmd, input io.Reader) (io.Reader, error) {
<ide> if input != nil {
<ide> stdin, err := cmd.StdinPipe()
<ide> if err != nil {
<del> if atEnd != nil {
<del> atEnd()
<del> }
<ide> return nil, err
<ide> }
<ide> // Write stdin if any
<ide> func CmdStream(cmd *exec.Cmd, input io.Reader, atEnd func()) (io.Reader, error)
<ide> }
<ide> stdout, err := cmd.StdoutPipe()
<ide> if err != nil {
<del> if atEnd != nil {
<del> atEnd()
<del> }
<ide> return nil, err
<ide> }
<ide> stderr, err := cmd.StderrPipe()
<ide> if err != nil {
<del> if atEnd != nil {
<del> atEnd()
<del> }
<ide> return nil, err
<ide> }
<ide> pipeR, pipeW := io.Pipe()
<ide> func CmdStream(cmd *exec.Cmd, input io.Reader, atEnd func()) (io.Reader, error)
<ide> } else {
<ide> pipeW.Close()
<ide> }
<del> if atEnd != nil {
<del> atEnd()
<del> }
<ide> }()
<ide> // Run the command and return the pipe
<ide> if err := cmd.Start(); err != nil {
<ide><path>archive/archive_test.go
<ide> import (
<ide>
<ide> func TestCmdStreamLargeStderr(t *testing.T) {
<ide> cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
<del> out, err := CmdStream(cmd, nil, nil)
<add> out, err := CmdStream(cmd, nil)
<ide> if err != nil {
<ide> t.Fatalf("Failed to start command: %s", err)
<ide> }
<ide> func TestCmdStreamLargeStderr(t *testing.T) {
<ide>
<ide> func TestCmdStreamBad(t *testing.T) {
<ide> badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
<del> out, err := CmdStream(badCmd, nil, nil)
<add> out, err := CmdStream(badCmd, nil)
<ide> if err != nil {
<ide> t.Fatalf("Failed to start command: %s", err)
<ide> }
<ide> func TestCmdStreamBad(t *testing.T) {
<ide>
<ide> func TestCmdStreamGood(t *testing.T) {
<ide> cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0")
<del> out, err := CmdStream(cmd, nil, nil)
<add> out, err := CmdStream(cmd, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>container.go
<ide> func (container *Container) Copy(resource string) (archive.Archive, error) {
<ide> return archive.TarFilter(basePath, &archive.TarOptions{
<ide> Compression: archive.Uncompressed,
<ide> Includes: filter,
<del> Recursive: true,
<ide> })
<ide> }
<ide>
<ide><path>graphdriver/aufs/aufs.go
<ide> func (a *Driver) Get(id string) (string, error) {
<ide> // Returns an archive of the contents for the id
<ide> func (a *Driver) Diff(id string) (archive.Archive, error) {
<ide> return archive.TarFilter(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
<del> Recursive: true,
<ide> Compression: archive.Uncompressed,
<ide> })
<ide> } | 4 |
Go | Go | add network method to return list of endpoints | f151cc23ab8d6032ea575990ef76f64367225361 | <ide><path>libnetwork/libnetwork_test.go
<ide> func TestSimplebridge(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> epList := network.Endpoints()
<add> if len(epList) != 1 {
<add> t.Fatal(err)
<add> }
<add> if ep != epList[0] {
<add> t.Fatal(err)
<add> }
<add>
<ide> if err := ep.Delete(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>libnetwork/network.go
<ide> create network namespaces and allocate interfaces for containers to use.
<ide> // For each new container: allocate IP and interfaces. The returned network
<ide> // settings will be used for container infos (inspect and such), as well as
<ide> // iptables rules for port publishing.
<del> _, sinfo, err := network.CreateEndpoint("Endpoint1", networkNamespace.Key(), "")
<add> ep, err := network.CreateEndpoint("Endpoint1", networkNamespace.Key(), "")
<ide> if err != nil {
<ide> return
<ide> }
<ide> type Network interface {
<ide> // Labels support will be added in the near future.
<ide> CreateEndpoint(name string, sboxKey string, options interface{}) (Endpoint, *driverapi.SandboxInfo, error)
<ide>
<add> // Endpoints returns the list of Endpoint in this network.
<add> Endpoints() []Endpoint
<add>
<ide> // Delete the network.
<ide> Delete() error
<ide> }
<ide> func (n *network) CreateEndpoint(name string, sboxKey string, options interface{
<ide> return ep, sinfo, nil
<ide> }
<ide>
<add>func (n *network) Endpoints() []Endpoint {
<add> n.Lock()
<add> defer n.Unlock()
<add>
<add> list := make([]Endpoint, len(n.endpoints))
<add>
<add> idx := 0
<add> for _, e := range n.endpoints {
<add> list[idx] = e
<add> idx++
<add> }
<add>
<add> return list
<add>}
<add>
<ide> func (ep *endpoint) ID() string {
<ide> return string(ep.id)
<ide> } | 2 |
Go | Go | remove omitempty json tags from stucts | 44f4c95c0ece887023d3ad7ab9c4f147c81d9d3f | <ide><path>api/stats/stats.go
<ide> import "time"
<ide>
<ide> type ThrottlingData struct {
<ide> // Number of periods with throttling active
<del> Periods uint64 `json:"periods,omitempty"`
<add> Periods uint64 `json:"periods"`
<ide> // Number of periods when the container hit its throttling limit.
<del> ThrottledPeriods uint64 `json:"throttled_periods,omitempty"`
<add> ThrottledPeriods uint64 `json:"throttled_periods"`
<ide> // Aggregate time the container was throttled for in nanoseconds.
<del> ThrottledTime uint64 `json:"throttled_time,omitempty"`
<add> ThrottledTime uint64 `json:"throttled_time"`
<ide> }
<ide>
<ide> // All CPU stats are aggregated since container inception.
<ide> type CpuUsage struct {
<ide> // Total CPU time consumed.
<ide> // Units: nanoseconds.
<del> TotalUsage uint64 `json:"total_usage,omitempty"`
<add> TotalUsage uint64 `json:"total_usage"`
<ide> // Total CPU time consumed per core.
<ide> // Units: nanoseconds.
<del> PercpuUsage []uint64 `json:"percpu_usage,omitempty"`
<add> PercpuUsage []uint64 `json:"percpu_usage"`
<ide> // Time spent by tasks of the cgroup in kernel mode.
<ide> // Units: nanoseconds.
<ide> UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
<ide> type CpuUsage struct {
<ide> }
<ide>
<ide> type CpuStats struct {
<del> CpuUsage CpuUsage `json:"cpu_usage,omitempty"`
<add> CpuUsage CpuUsage `json:"cpu_usage"`
<ide> SystemUsage uint64 `json:"system_cpu_usage"`
<ide> ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
<ide> }
<ide>
<ide> type MemoryStats struct {
<ide> // current res_counter usage for memory
<del> Usage uint64 `json:"usage,omitempty"`
<add> Usage uint64 `json:"usage"`
<ide> // maximum usage ever recorded.
<del> MaxUsage uint64 `json:"max_usage,omitempty"`
<add> MaxUsage uint64 `json:"max_usage"`
<ide> // TODO(vishh): Export these as stronger types.
<ide> // all the stats exported via memory.stat.
<del> Stats map[string]uint64 `json:"stats,omitempty"`
<add> Stats map[string]uint64 `json:"stats"`
<ide> // number of times memory usage hits limits.
<ide> Failcnt uint64 `json:"failcnt"`
<ide> Limit uint64 `json:"limit"`
<ide> }
<ide>
<ide> type BlkioStatEntry struct {
<del> Major uint64 `json:"major,omitempty"`
<del> Minor uint64 `json:"minor,omitempty"`
<del> Op string `json:"op,omitempty"`
<del> Value uint64 `json:"value,omitempty"`
<add> Major uint64 `json:"major"`
<add> Minor uint64 `json:"minor"`
<add> Op string `json:"op"`
<add> Value uint64 `json:"value"`
<ide> }
<ide>
<ide> type BlkioStats struct {
<ide> // number of bytes tranferred to and from the block device
<del> IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive,omitempty"`
<del> IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive,omitempty"`
<del> IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive,omitempty"`
<del> IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive,omitempty"`
<del> IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive,omitempty"`
<del> IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive,omitempty"`
<del> IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive,omitempty"`
<del> SectorsRecursive []BlkioStatEntry `json:"sectors_recursive,omitempty"`
<add> IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
<add> IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"`
<add> IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"`
<add> IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"`
<add> IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"`
<add> IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"`
<add> IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"`
<add> SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"`
<ide> }
<ide>
<ide> type Network struct { | 1 |
Text | Text | add arabic translation for insertion sort | eb1c54a15e55b884db59b79d748ef9ddebeabbad | <ide><path>curriculum/challenges/arabic/08-coding-interview-prep/algorithms/implement-insertion-sort.arabic.md
<ide> localeTitle: ''
<ide> ---
<ide>
<ide> ## Description
<del>undefined
<add>طريقة الفرز التالية التي سنتعرف إليها هي فرز بالإدراج. تعمل هذه الطريقة عن طريق إنشاء مصفوفة مرتبة في بداية القائمة. تبدأ المصفوفة المرتبة مع العنصر الاول. ثم يقوم بفحص العنصر التالي ويقوم بتبديله إلى الخلف في المصفوفة التي تم فرزها حتى يكون في موضع تم فرزه. تستمر العملية بالتكرار عن طريق تبديل عناصر جديدة الى القسم المرتب من المصفوفة حتى تصل الى النهاية. هذه الخوارزمية لها تعقيد زمني من الدرجة الثانية في الحالات المتوسطة والأسوأ.
<add>
<ide>
<ide> ## Instructions
<del>undefined
<add>اكتب تابع الفرز بالادراج والذي يأخذ مجموعة من الأعداد الصحيحة كدخل ويعيد مصفوفة من هذه الأعداد الصحيحة في ترتيب مفرز من الاصغر إلى الأكبر. ملحوظة:
<add>يتم استدعاء هذا التابع من وراء الكواليس, بالاضافة الى كتابة مصفوفة التجريب في نهاية محرر النصوص. يمكمك ادراج مصفوفة جديدة للتحقق من صحة عمل التابع.
<add>
<ide>
<ide> ## Tests
<ide> <section id='tests'> | 1 |
Javascript | Javascript | cover all http methods that parser supports | 1268737e7198b77817fd0abf18edef5e76b78b33 | <ide><path>test/parallel/test-http-methods.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const http = require('http');
<del>const util = require('util');
<ide>
<del>assert(Array.isArray(http.METHODS));
<del>assert(http.METHODS.length > 0);
<del>assert(http.METHODS.includes('GET'));
<del>assert(http.METHODS.includes('HEAD'));
<del>assert(http.METHODS.includes('POST'));
<del>assert.deepStrictEqual(util._extend([], http.METHODS), http.METHODS.sort());
<add>// This test ensures all http methods from HTTP parser are exposed
<add>// to http library
<add>
<add>const methods = [
<add> 'DELETE',
<add> 'GET',
<add> 'HEAD',
<add> 'POST',
<add> 'PUT',
<add> 'CONNECT',
<add> 'OPTIONS',
<add> 'TRACE',
<add> 'COPY',
<add> 'LOCK',
<add> 'MKCOL',
<add> 'MOVE',
<add> 'PROPFIND',
<add> 'PROPPATCH',
<add> 'SEARCH',
<add> 'UNLOCK',
<add> 'BIND',
<add> 'REBIND',
<add> 'UNBIND',
<add> 'ACL',
<add> 'REPORT',
<add> 'MKACTIVITY',
<add> 'CHECKOUT',
<add> 'MERGE',
<add> 'M-SEARCH',
<add> 'NOTIFY',
<add> 'SUBSCRIBE',
<add> 'UNSUBSCRIBE',
<add> 'PATCH',
<add> 'PURGE',
<add> 'MKCALENDAR',
<add> 'LINK',
<add> 'UNLINK'
<add>];
<add>
<add>assert.deepStrictEqual(http.METHODS, methods.sort()); | 1 |
Go | Go | add notary integration to `docker build` | 578b1521df85eae8a6205118131751c631323ba5 | <ide><path>api/client/build.go
<ide> package client
<ide>
<ide> import (
<add> "archive/tar"
<ide> "bufio"
<ide> "encoding/base64"
<ide> "encoding/json"
<ide> import (
<ide> "os/exec"
<ide> "path"
<ide> "path/filepath"
<add> "regexp"
<ide> "runtime"
<ide> "strconv"
<ide> "strings"
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> contextDir = tempDir
<ide> }
<ide>
<add> // Resolve the FROM lines in the Dockerfile to trusted digest references
<add> // using Notary.
<add> newDockerfile, err := rewriteDockerfileFrom(filepath.Join(contextDir, relDockerfile), cli.trustedReference)
<add> if err != nil {
<add> return fmt.Errorf("unable to process Dockerfile: %v", err)
<add> }
<add> defer newDockerfile.Close()
<add>
<ide> // And canonicalize dockerfile name to a platform-independent one
<ide> relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
<ide> if err != nil {
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> includes = append(includes, ".dockerignore", relDockerfile)
<ide> }
<ide>
<del> if context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
<add> context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
<ide> Compression: archive.Uncompressed,
<ide> ExcludePatterns: excludes,
<ide> IncludeFiles: includes,
<del> }); err != nil {
<add> })
<add> if err != nil {
<ide> return err
<ide> }
<ide>
<add> // Wrap the tar archive to replace the Dockerfile entry with the rewritten
<add> // Dockerfile which uses trusted pulls.
<add> context = replaceDockerfileTarWrapper(context, newDockerfile, relDockerfile)
<add>
<ide> // Setup an upload progress bar
<ide> // FIXME: ProgressReader shouldn't be this annoying to use
<ide> sf := streamformatter.NewStreamFormatter()
<ide> func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, rel
<ide>
<ide> return getDockerfileRelPath(localDir, dockerfileName)
<ide> }
<add>
<add>var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
<add>
<add>type trustedDockerfile struct {
<add> *os.File
<add> size int64
<add>}
<add>
<add>func (td *trustedDockerfile) Close() error {
<add> td.File.Close()
<add> return os.Remove(td.File.Name())
<add>}
<add>
<add>// rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
<add>// "FROM <image>" instructions to a digest reference. `translator` is a
<add>// function that takes a repository name and tag reference and returns a
<add>// trusted digest reference.
<add>func rewriteDockerfileFrom(dockerfileName string, translator func(string, registry.Reference) (registry.Reference, error)) (newDockerfile *trustedDockerfile, err error) {
<add> dockerfile, err := os.Open(dockerfileName)
<add> if err != nil {
<add> return nil, fmt.Errorf("unable to open Dockerfile: %v", err)
<add> }
<add> defer dockerfile.Close()
<add>
<add> scanner := bufio.NewScanner(dockerfile)
<add>
<add> // Make a tempfile to store the rewritten Dockerfile.
<add> tempFile, err := ioutil.TempFile("", "trusted-dockerfile-")
<add> if err != nil {
<add> return nil, fmt.Errorf("unable to make temporary trusted Dockerfile: %v", err)
<add> }
<add>
<add> trustedFile := &trustedDockerfile{
<add> File: tempFile,
<add> }
<add>
<add> defer func() {
<add> if err != nil {
<add> // Close the tempfile if there was an error during Notary lookups.
<add> // Otherwise the caller should close it.
<add> trustedFile.Close()
<add> }
<add> }()
<add>
<add> // Scan the lines of the Dockerfile, looking for a "FROM" line.
<add> for scanner.Scan() {
<add> line := scanner.Text()
<add>
<add> matches := dockerfileFromLinePattern.FindStringSubmatch(line)
<add> if matches != nil && matches[1] != "scratch" {
<add> // Replace the line with a resolved "FROM repo@digest"
<add> repo, tag := parsers.ParseRepositoryTag(matches[1])
<add> if tag == "" {
<add> tag = tags.DEFAULTTAG
<add> }
<add> ref := registry.ParseReference(tag)
<add>
<add> if !ref.HasDigest() && isTrusted() {
<add> trustedRef, err := translator(repo, ref)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.ImageName(repo)))
<add> }
<add> }
<add>
<add> n, err := fmt.Fprintln(tempFile, line)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> trustedFile.size += int64(n)
<add> }
<add>
<add> tempFile.Seek(0, os.SEEK_SET)
<add>
<add> return trustedFile, scanner.Err()
<add>}
<add>
<add>// replaceDockerfileTarWrapper wraps the given input tar archive stream and
<add>// replaces the entry with the given Dockerfile name with the contents of the
<add>// new Dockerfile. Returns a new tar archive stream with the replaced
<add>// Dockerfile.
<add>func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, newDockerfile *trustedDockerfile, dockerfileName string) io.ReadCloser {
<add> pipeReader, pipeWriter := io.Pipe()
<add>
<add> go func() {
<add> tarReader := tar.NewReader(inputTarStream)
<add> tarWriter := tar.NewWriter(pipeWriter)
<add>
<add> defer inputTarStream.Close()
<add>
<add> for {
<add> hdr, err := tarReader.Next()
<add> if err == io.EOF {
<add> // Signals end of archive.
<add> tarWriter.Close()
<add> pipeWriter.Close()
<add> return
<add> }
<add> if err != nil {
<add> pipeWriter.CloseWithError(err)
<add> return
<add> }
<add>
<add> var content io.Reader = tarReader
<add>
<add> if hdr.Name == dockerfileName {
<add> // This entry is the Dockerfile. Since the tar archive was
<add> // generated from a directory on the local filesystem, the
<add> // Dockerfile will only appear once in the archive.
<add> hdr.Size = newDockerfile.size
<add> content = newDockerfile
<add> }
<add>
<add> if err := tarWriter.WriteHeader(hdr); err != nil {
<add> pipeWriter.CloseWithError(err)
<add> return
<add> }
<add>
<add> if _, err := io.Copy(tarWriter, content); err != nil {
<add> pipeWriter.CloseWithError(err)
<add> return
<add> }
<add> }
<add> }()
<add>
<add> return pipeReader
<add>} | 1 |
PHP | PHP | remove redundancy in regex | b268a4da0e349b764cf6739b2c8b0b8188395606 | <ide><path>src/Database/Driver/SqlDialectTrait.php
<ide> public function quoteIdentifier(string $identifier): string
<ide> }
<ide>
<ide> // string.string with spaces
<del> if (preg_match('/^([\w-]+\.[\w][\w\s\-]*[\w])(.*)/u', $identifier, $matches)) {
<add> if (preg_match('/^([\w-]+\.[\w][\w\s-]*[\w])(.*)/u', $identifier, $matches)) {
<ide> $items = explode('.', $matches[1]);
<ide> $field = implode($this->_endQuote . '.' . $this->_startQuote, $items);
<ide>
<ide> return $this->_startQuote . $field . $this->_endQuote . $matches[2];
<ide> }
<ide>
<del> if (preg_match('/^[\w_\s-]*[\w_-]+/u', $identifier)) {
<add> if (preg_match('/^[\w\s-]*[\w-]+/u', $identifier)) {
<ide> return $this->_startQuote . $identifier . $this->_endQuote;
<ide> }
<ide> | 1 |
Python | Python | fix mypy errors at mst_kruskal | da71184b04837d2bc934f9947b4c262da096f349 | <ide><path>graphs/minimum_spanning_tree_kruskal.py
<del>from typing import List, Tuple
<del>
<del>
<del>def kruskal(num_nodes: int, num_edges: int, edges: List[Tuple[int, int, int]]) -> int:
<add>def kruskal(
<add> num_nodes: int, edges: list[tuple[int, int, int]]
<add>) -> list[tuple[int, int, int]]:
<ide> """
<del> >>> kruskal(4, 3, [(0, 1, 3), (1, 2, 5), (2, 3, 1)])
<add> >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)])
<ide> [(2, 3, 1), (0, 1, 3), (1, 2, 5)]
<ide>
<del> >>> kruskal(4, 5, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)])
<add> >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)])
<ide> [(2, 3, 1), (0, 2, 1), (0, 1, 3)]
<ide>
<del> >>> kruskal(4, 6, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2),
<add> >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2),
<ide> ... (2, 1, 1)])
<ide> [(2, 3, 1), (0, 2, 1), (2, 1, 1)]
<ide> """
<ide> def find_parent(i):
<ide> node1, node2, cost = [int(x) for x in input().strip().split()]
<ide> edges.append((node1, node2, cost))
<ide>
<del> kruskal(num_nodes, num_edges, edges)
<add> kruskal(num_nodes, edges)
<ide><path>graphs/tests/test_min_spanning_tree_kruskal.py
<ide>
<ide>
<ide> def test_kruskal_successful_result():
<del> num_nodes, num_edges = 9, 14
<add> num_nodes = 9
<ide> edges = [
<ide> [0, 1, 4],
<ide> [0, 7, 8],
<ide> def test_kruskal_successful_result():
<ide> [1, 7, 11],
<ide> ]
<ide>
<del> result = kruskal(num_nodes, num_edges, edges)
<add> result = kruskal(num_nodes, edges)
<ide>
<ide> expected = [
<ide> [7, 6, 1], | 2 |
Javascript | Javascript | add a temporary fix for re-evaluation support" | 49ef3ae90af7433b0ff29eb8519ae3bd6c9d58dd | <ide><path>lib/fs.js
<ide> const isWindows = process.platform === 'win32';
<ide>
<ide> const DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
<ide> const errnoException = util._errnoException;
<del>
<del>var printDeprecation;
<del>try {
<del> printDeprecation = require('internal/util').printDeprecationMessage;
<del>} catch (e) {
<del> if (e.code !== 'MODULE_NOT_FOUND') throw e;
<del>
<del> // TODO(ChALkeR): remove this in master after 6.x
<del> // This code was based upon internal/util and is required to give users
<del> // a grace period before actually breaking modules that re-evaluate fs
<del> // sources from context where internal modules are not allowed, e.g.
<del> // older versions of graceful-fs module.
<del>
<del> const prefix = `(${process.release.name}:${process.pid}) `;
<del>
<del> printDeprecation = function(msg, warned) {
<del> if (process.noDeprecation)
<del> return true;
<del>
<del> if (warned)
<del> return warned;
<del>
<del> if (process.throwDeprecation)
<del> throw new Error(`${prefix}${msg}`);
<del> else if (process.traceDeprecation)
<del> console.trace(msg);
<del> else
<del> console.error(`${prefix}${msg}`);
<del>
<del> return true;
<del> };
<del> printDeprecation('fs: re-evaluating native module sources is not ' +
<del> 'supported. If you are using the graceful-fs module, ' +
<del> 'please update it to a more recent version.',
<del> false);
<del>}
<add>const printDeprecation = require('internal/util').printDeprecationMessage;
<ide>
<ide> function throwOptionsError(options) {
<ide> throw new TypeError('Expected options to be either an object or a string, ' + | 1 |
Javascript | Javascript | adjust function argument alignment | 8f5695865860ecf06868a89687923e7eb514b442 | <ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> function launchChildProcess(index) {
<ide> worker.pid, count);
<ide>
<ide> assert.strictEqual(count, messages.length,
<del> 'A worker received an invalid multicast message');
<add> 'A worker received an invalid multicast message');
<ide> });
<ide>
<ide> clearTimeout(timer);
<ide><path>test/parallel/test-assert.js
<ide> try {
<ide> } catch (e) {
<ide> assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no');
<ide> assert.equal(e.generatedMessage, false,
<del> 'Message incorrectly marked as generated');
<add> 'Message incorrectly marked as generated');
<ide> }
<ide>
<ide> // Verify that throws() and doesNotThrow() throw on non-function block
<ide><path>test/parallel/test-buffer-alloc.js
<ide> assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(),
<ide> '********************');
<ide>
<ide> // handle padding graciously, multiple-of-4 or not
<del>assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==',
<del> 'base64').length, 32);
<del>assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=',
<del> 'base64').length, 32);
<del>assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw',
<del> 'base64').length, 32);
<del>assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==',
<del> 'base64').length, 31);
<del>assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=',
<del> 'base64').length, 31);
<del>assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg',
<del> 'base64').length, 31);
<add>assert.equal(
<add> Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', 'base64').length,
<add> 31
<add>);
<add>assert.equal(
<add> Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64').length,
<add> 31
<add>);
<add>assert.equal(
<add> Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length,
<add> 31
<add>);
<ide>
<ide> // This string encodes single '.' character in UTF-16
<ide> var dot = Buffer.from('//4uAA==', 'base64');
<ide><path>test/parallel/test-buffer.js
<ide> assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(),
<ide> '********************');
<ide>
<ide> // handle padding graciously, multiple-of-4 or not
<del>assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==',
<del> 'base64').length, 32);
<del>assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=',
<del> 'base64').length, 32);
<del>assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw',
<del> 'base64').length, 32);
<del>assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==',
<del> 'base64').length, 31);
<del>assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=',
<del> 'base64').length, 31);
<del>assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg',
<del> 'base64').length, 31);
<add>assert.equal(
<add> new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', 'base64').length,
<add> 32
<add>);
<add>assert.equal(
<add> new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', 'base64').length,
<add> 31
<add>);
<add>assert.equal(
<add> new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64').length,
<add> 31
<add>);
<add>assert.equal(
<add> new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length,
<add> 31
<add>);
<ide>
<ide> // This string encodes single '.' character in UTF-16
<ide> var dot = new Buffer('//4uAA==', 'base64');
<ide><path>test/parallel/test-cluster-basic.js
<ide> var assert = require('assert');
<ide> var cluster = require('cluster');
<ide>
<ide> assert.equal('NODE_UNIQUE_ID' in process.env, false,
<del> 'NODE_UNIQUE_ID should be removed on startup');
<add> 'NODE_UNIQUE_ID should be removed on startup');
<ide>
<ide> function forEach(obj, fn) {
<ide> Object.keys(obj).forEach(function(name, index) {
<ide> else if (cluster.isMaster) {
<ide> worker = cluster.fork();
<ide> assert.equal(worker.id, 1);
<ide> assert.ok(worker instanceof cluster.Worker,
<del> 'the worker is not a instance of the Worker constructor');
<add> 'the worker is not a instance of the Worker constructor');
<ide>
<ide> //Check event
<ide> forEach(checks.worker.events, function(bool, name, index) {
<ide><path>test/parallel/test-crypto-binary-default.js
<ide> var a4 = crypto.createHash('sha1').update('Test123').digest('buffer');
<ide>
<ide> if (!common.hasFipsCrypto) {
<ide> var a0 = crypto.createHash('md5').update('Test123').digest('binary');
<del> assert.equal(a0, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' +
<del> '\u00bd\u008c', 'Test MD5 as binary');
<add> assert.equal(
<add> a0,
<add> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c',
<add> 'Test MD5 as binary'
<add> );
<ide> }
<ide>
<ide> assert.equal(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1');
<ide><path>test/parallel/test-crypto-hash.js
<ide> a8 = a8.read();
<ide>
<ide> if (!common.hasFipsCrypto) {
<ide> var a0 = crypto.createHash('md5').update('Test123').digest('binary');
<del> assert.equal(a0, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' +
<del> '\u00bd\u008c', 'Test MD5 as binary');
<add> assert.equal(
<add> a0,
<add> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c',
<add> 'Test MD5 as binary'
<add> );
<ide> }
<ide> assert.equal(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1');
<ide> assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=',
<ide><path>test/parallel/test-domain-exit-dispose-again.js
<ide> setTimeout(function firstTimer() {
<ide> d.dispose();
<ide> console.error(err);
<ide> console.error('in domain error handler',
<del> process.domain, process.domain === d);
<add> process.domain, process.domain === d);
<ide> });
<ide>
<ide> d.run(function() {
<ide><path>test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js
<ide> const d = domain.create();
<ide>
<ide> process.on('uncaughtException', common.mustCall(function onUncaught() {
<ide> assert.equal(process.domain, null,
<del> 'domains stack should be empty in uncaughtException handler');
<add> 'domains stack should be empty in uncaughtException handler');
<ide> }));
<ide>
<ide> process.on('beforeExit', common.mustCall(function onBeforeExit() {
<ide> assert.equal(process.domain, null,
<del> 'domains stack should be empty in beforeExit handler');
<add> 'domains stack should be empty in beforeExit handler');
<ide> }));
<ide>
<ide> d.run(function() {
<ide><path>test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js
<ide> function runTestWithoutAbortOnUncaughtException() {
<ide> 'include domain\'s error\'s message');
<ide>
<ide> assert.notEqual(err.code, 0,
<del> 'child process should have exited with a non-zero exit code, ' +
<del> 'but did not');
<add> 'child process should have exited with a non-zero ' +
<add> 'exit code, but did not');
<ide> });
<ide> }
<ide>
<ide> function runTestWithAbortOnUncaughtException() {
<ide> withAbortOnUncaughtException: true
<ide> }), function onTestDone(err, stdout, stderr) {
<ide> assert.notEqual(err.code, RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE,
<del> 'child process should not have run its uncaughtException event ' +
<del> 'handler');
<add> 'child process should not have run its uncaughtException ' +
<add> 'event handler');
<ide> assert(common.nodeProcessAborted(err.code, err.signal),
<ide> 'process should have aborted, but did not');
<ide> });
<ide><path>test/parallel/test-domain-timers.js
<ide> timeout = setTimeout(function() {}, 10 * 1000);
<ide>
<ide> process.on('exit', function() {
<ide> assert.equal(timeout_err.message, 'Timeout UNREFd',
<del> 'Domain should catch timer error');
<add> 'Domain should catch timer error');
<ide> assert.equal(immediate_err.message, 'Immediate Error',
<del> 'Domain should catch immediate error');
<add> 'Domain should catch immediate error');
<ide> });
<ide><path>test/parallel/test-domain-top-level-error-handler-clears-stack.js
<ide> d.on('error', common.mustCall(function() {
<ide> // call to process._fatalException, and so on recursively and
<ide> // indefinitely.
<ide> console.error('domains stack length should be 1, but instead is:',
<del> domain._stack.length);
<add> domain._stack.length);
<ide> process.exit(1);
<ide> }
<ide> });
<ide><path>test/parallel/test-file-write-stream2.js
<ide> process.on('exit', function() {
<ide> console.log(' expected: %j', cb_expected);
<ide> console.log(' occurred: %j', cb_occurred);
<ide> assert.strictEqual(cb_occurred, cb_expected,
<del> 'events missing or out of order: "' +
<del> cb_occurred + '" !== "' + cb_expected + '"');
<add> 'events missing or out of order: "' +
<add> cb_occurred + '" !== "' + cb_expected + '"');
<ide> } else {
<ide> console.log('ok');
<ide> }
<ide><path>test/parallel/test-file-write-stream3.js
<ide> process.on('exit', function() {
<ide> console.log(' expected: %j', cb_expected);
<ide> console.log(' occurred: %j', cb_occurred);
<ide> assert.strictEqual(cb_occurred, cb_expected,
<del> 'events missing or out of order: "' +
<del> cb_occurred + '" !== "' + cb_expected + '"');
<add> 'events missing or out of order: "' +
<add> cb_occurred + '" !== "' + cb_expected + '"');
<ide> }
<ide> });
<ide>
<ide><path>test/parallel/test-fs-realpath.js
<ide> function test_escape_cwd(cb) {
<ide> console.log('test_escape_cwd');
<ide> asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) {
<ide> assertEqualPath(upone, uponeActual,
<del> 'realpath("..") expected: ' + path.resolve(upone) +
<del> ' actual:' + uponeActual);
<add> 'realpath("..") expected: ' + path.resolve(upone) +
<add> ' actual:' + uponeActual);
<ide> });
<ide> }
<ide> var uponeActual = fs.realpathSync('..');
<ide> assertEqualPath(upone, uponeActual,
<del> 'realpathSync("..") expected: ' + path.resolve(upone) +
<del> ' actual:' + uponeActual);
<add> 'realpathSync("..") expected: ' + path.resolve(upone) +
<add> ' actual:' + uponeActual);
<ide>
<ide>
<ide> // going up with .. multiple times
<ide><path>test/parallel/test-http-agent-error-on-idle.js
<ide> server.listen(common.PORT, function() {
<ide>
<ide> function done() {
<ide> assert.equal(Object.keys(agent.freeSockets).length, 0,
<del> 'expect the freeSockets pool to be empty');
<add> 'expect the freeSockets pool to be empty');
<ide>
<ide> agent.destroy();
<ide> server.close();
<ide><path>test/parallel/test-http-agent-keepalive.js
<ide> function remoteClose() {
<ide> setTimeout(function() {
<ide> assert.equal(agent.sockets[name], undefined);
<ide> assert.equal(agent.freeSockets[name], undefined,
<del> 'freeSockets is not empty');
<add> 'freeSockets is not empty');
<ide> remoteError();
<ide> }, common.platformTimeout(200));
<ide> });
<ide><path>test/parallel/test-http-agent-maxsockets.js
<ide> function done() {
<ide> }
<ide> var freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]];
<ide> assert.equal(freepool.length, 2,
<del> 'expect keep 2 free sockets, but got ' + freepool.length);
<add> 'expect keep 2 free sockets, but got ' + freepool.length);
<ide> agent.destroy();
<ide> server.close();
<ide> }
<ide><path>test/parallel/test-http-destroyed-socket-write2.js
<ide> server.listen(common.PORT, function() {
<ide> break;
<ide> default:
<ide> assert.strictEqual(er.code,
<del> 'ECONNRESET',
<del> 'Writing to a torn down client should RESET or ABORT');
<add> 'ECONNRESET',
<add> 'Write to a torn down client should RESET or ABORT');
<ide> break;
<ide> }
<ide>
<ide><path>test/parallel/test-http-parser-bad-ref.js
<ide> demoBug('POST /1', '/22 HTTP/1.1\r\n' +
<ide> 'Content-Length: 4\r\n\r\n' +
<ide> 'pong');
<ide>
<add>/* eslint-disable align-function-arguments */
<ide> demoBug('POST /1/22 HTTP/1.1\r\n' +
<ide> 'Content-Type: tex', 't/plain\r\n' +
<ide> 'Content-Length: 4\r\n\r\n' +
<ide> 'pong');
<add>/* eslint-enable align-function-arguments */
<ide>
<ide> process.on('exit', function() {
<ide> assert.equal(2, headersComplete);
<ide><path>test/parallel/test-http-url.parse-post.js
<ide> function check(request) {
<ide> assert.strictEqual(request.url, '/asdf?qwer=zxcv');
<ide> //the host header should use the url.parse.hostname
<ide> assert.strictEqual(request.headers.host,
<del> testURL.hostname + ':' + testURL.port);
<add> testURL.hostname + ':' + testURL.port);
<ide> }
<ide>
<ide> var server = http.createServer(function(request, response) {
<ide><path>test/parallel/test-module-relative-lookup.js
<ide> const lookupResults = _module._resolveLookupPaths('./lodash');
<ide> const paths = lookupResults[1];
<ide>
<ide> assert.strictEqual(paths[0], '.',
<del> 'Current directory is prioritized before node_modules for local modules');
<add> 'Current directory gets highest priority for local modules');
<ide><path>test/parallel/test-require-process.js
<ide> var assert = require('assert');
<ide>
<ide> var nativeProcess = require('process');
<ide> assert.strictEqual(nativeProcess, process,
<del> 'require("process") should return a reference to global process');
<add> 'require("process") should return global process reference');
<ide><path>test/parallel/test-timers-ordering.js
<ide> var f = function(i) {
<ide> var now = Timer.now();
<ide> console.log(i, now);
<ide> assert(now >= last_ts + 1,
<del> 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1');
<add> 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1');
<ide> last_ts = now;
<ide>
<ide> // schedule next iteration
<ide><path>test/parallel/test-timers-reset-process-domain-on-throw.js
<ide> function secondTimer() {
<ide> // secondTimer was scheduled before any domain had been created, so its
<ide> // callback should not have any active domain set when it runs.
<ide> if (process.domain !== null) {
<del> console.log('process.domain should be null in this timer callback, but ' +
<del> 'instead is:', process.domain);
<add> console.log('process.domain should be null in this timer callback, but is:',
<add> process.domain);
<ide> // Do not use assert here, as it throws errors and if a domain with an error
<ide> // handler is active, then asserting wouldn't make the test fail.
<ide> process.exit(1);
<ide><path>test/parallel/test-tls-peer-certificate.js
<ide> server.listen(common.PORT, function() {
<ide> assert.equal(peerCert.fingerprint,
<ide> '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA');
<ide> assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'],
<del> [ 'http://ocsp.nodejs.org/' ]);
<add> [ 'http://ocsp.nodejs.org/' ]);
<ide>
<ide> var issuer = peerCert.issuerCertificate;
<ide> assert.ok(issuer.issuerCertificate === issuer);
<ide><path>test/parallel/test-zlib-convenience-methods.js
<ide> var opts = {
<ide> zlib[method[0]](expect, opts, function(err, result) {
<ide> zlib[method[1]](result, opts, function(err, result) {
<ide> assert.equal(result, expect,
<del> 'Should get original string after ' +
<del> method[0] + '/' + method[1] + ' with options.');
<add> 'Should get original string after ' +
<add> method[0] + '/' + method[1] + ' with options.');
<ide> hadRun++;
<ide> });
<ide> });
<ide>
<ide> zlib[method[0]](expect, function(err, result) {
<ide> zlib[method[1]](result, function(err, result) {
<ide> assert.equal(result, expect,
<del> 'Should get original string after ' +
<del> method[0] + '/' + method[1] + ' without options.');
<add> 'Should get original string after ' +
<add> method[0] + '/' + method[1] + ' without options.');
<ide> hadRun++;
<ide> });
<ide> });
<ide>
<ide> var result = zlib[method[0] + 'Sync'](expect, opts);
<ide> result = zlib[method[1] + 'Sync'](result, opts);
<ide> assert.equal(result, expect,
<del> 'Should get original string after ' +
<del> method[0] + '/' + method[1] + ' with options.');
<add> 'Should get original string after ' +
<add> method[0] + '/' + method[1] + ' with options.');
<ide> hadRun++;
<ide>
<ide> result = zlib[method[0] + 'Sync'](expect);
<ide> result = zlib[method[1] + 'Sync'](result);
<ide> assert.equal(result, expect,
<del> 'Should get original string after ' +
<del> method[0] + '/' + method[1] + ' without options.');
<add> 'Should get original string after ' +
<add> method[0] + '/' + method[1] + ' without options.');
<ide> hadRun++;
<ide>
<ide> });
<ide><path>test/parallel/test-zlib-flush-drain.js
<ide> deflater.on('drain', function() {
<ide>
<ide> process.once('exit', function() {
<ide> assert.equal(beforeFlush, true,
<del> 'before calling flush the writable stream should need to drain');
<add> 'before calling flush, writable stream should need to drain');
<ide> assert.equal(afterFlush, false,
<del> 'after calling flush the writable stream should not need to drain');
<add> 'after calling flush, writable stream should not need to drain');
<ide> assert.equal(drainCount, 1,
<del> 'the deflater should have emitted a single drain event');
<add> 'the deflater should have emitted a single drain event');
<ide> assert.equal(flushCount, 2,
<del> 'flush should be called twice');
<add> 'flush should be called twice');
<ide> });
<ide><path>tools/doc/html.js
<ide> module.exports = toHTML;
<ide> // TODO(chrisdickinson): never stop vomitting / fix this.
<ide> var gtocPath = path.resolve(path.join(
<ide> __dirname,
<del> '..',
<del> '..',
<del> 'doc',
<del> 'api',
<del> '_toc.md'
<add> '..',
<add> '..',
<add> 'doc',
<add> 'api',
<add> '_toc.md'
<ide> ));
<ide> var gtocLoading = null;
<ide> var gtocData = null; | 29 |
Ruby | Ruby | fix inflector to respect default locale | 8cf88cc75ad0289f39fc2272c372f945b3934e76 | <ide><path>activesupport/lib/active_support/core_ext/string/inflections.rb
<ide> class String
<ide> # 'apple'.pluralize(2) # => "apples"
<ide> # 'ley'.pluralize(:es) # => "leyes"
<ide> # 'ley'.pluralize(1, :es) # => "ley"
<del> def pluralize(count = nil, locale = :en)
<add> def pluralize(count = nil, locale = I18n.locale)
<ide> locale = count if count.is_a?(Symbol)
<ide> if count == 1
<ide> self
<ide> def pluralize(count = nil, locale = :en)
<ide> # 'the blue mailmen'.singularize # => "the blue mailman"
<ide> # 'CamelOctopi'.singularize # => "CamelOctopus"
<ide> # 'leyes'.singularize(:es) # => "ley"
<del> def singularize(locale = :en)
<add> def singularize(locale = I18n.locale)
<ide> ActiveSupport::Inflector.singularize(self, locale)
<ide> end
<ide>
<ide><path>activesupport/test/inflector_test.rb
<ide> def test_inflector_locality
<ide> assert !ActiveSupport::Inflector.inflections.plurals.empty?
<ide> assert !ActiveSupport::Inflector.inflections.singulars.empty?
<ide> end
<add>
<add> def test_inflector_with_default_locale
<add> old_locale = I18n.locale
<add>
<add> begin
<add> I18n.locale = :de
<add>
<add> ActiveSupport::Inflector.inflections(:de) do |inflect|
<add> inflect.irregular 'region', 'regionen'
<add> end
<add>
<add> assert_equal('regionen', 'region'.pluralize)
<add> assert_equal('region', 'regionen'.singularize)
<add> ensure
<add> I18n.locale = old_locale
<add> end
<add> end
<ide>
<ide> def test_clear_all
<ide> with_dup do | 2 |
Python | Python | return nonzero exit codes on pool import errors. | 397d9128b6abb201e4eafd4a1dd7ece9db5661c5 | <ide><path>airflow/cli/commands/pool_command.py
<ide> """Pools sub-commands"""
<ide> import json
<ide> import os
<add>import sys
<ide> from json import JSONDecodeError
<ide>
<ide> from tabulate import tabulate
<ide> def pool_delete(args):
<ide> @cli_utils.action_logging
<ide> def pool_import(args):
<ide> """Imports pools from the file"""
<del> api_client = get_current_api_client()
<del> if os.path.exists(args.file):
<del> pools = pool_import_helper(args.file)
<del> else:
<del> print("Missing pools file.")
<del> pools = api_client.get_pools()
<add> if not os.path.exists(args.file):
<add> sys.exit("Missing pools file.")
<add> pools, failed = pool_import_helper(args.file)
<ide> print(_tabulate_pools(pools=pools, tablefmt=args.output))
<add> if len(failed) > 0:
<add> sys.exit("Failed to update pool(s): {}".format(", ".join(failed)))
<ide>
<ide>
<ide> def pool_export(args):
<ide> def pool_import_helper(filepath):
<ide> try: # pylint: disable=too-many-nested-blocks
<ide> pools_json = json.loads(data)
<ide> except JSONDecodeError as e:
<del> print("Please check the validity of the json file: " + str(e))
<del> else:
<del> try:
<del> pools = []
<del> counter = 0
<del> for k, v in pools_json.items():
<del> if isinstance(v, dict) and len(v) == 2:
<del> pools.append(
<del> api_client.create_pool(name=k, slots=v["slots"], description=v["description"])
<del> )
<del> counter += 1
<del> else:
<del> pass
<del> except Exception: # pylint: disable=broad-except
<del> pass
<del> finally:
<del> print("{} of {} pool(s) successfully updated.".format(counter, len(pools_json)))
<del> return pools # pylint: disable=lost-exception
<add> sys.exit("Invalid json file: " + str(e))
<add> pools = []
<add> failed = []
<add> for k, v in pools_json.items():
<add> if isinstance(v, dict) and len(v) == 2:
<add> pools.append(api_client.create_pool(name=k, slots=v["slots"], description=v["description"]))
<add> else:
<add> failed.append(k)
<add> print(f"{len(pools)} of {len(pools_json)} pool(s) successfully updated.")
<add> return pools, failed
<ide>
<ide>
<ide> def pool_export_helper(filepath):
<ide><path>tests/cli/commands/test_pool_command.py
<ide> def test_pool_delete(self):
<ide> pool_command.pool_delete(self.parser.parse_args(['pools', 'delete', 'foo']))
<ide> self.assertEqual(self.session.query(Pool).count(), 1)
<ide>
<add> def test_pool_import_nonexistent(self):
<add> with self.assertRaises(SystemExit):
<add> pool_command.pool_import(self.parser.parse_args(['pools', 'import', 'nonexistent.json']))
<add>
<add> def test_pool_import_invalid_json(self):
<add> with open('pools_import_invalid.json', mode='w') as file:
<add> file.write("not valid json")
<add>
<add> with self.assertRaises(SystemExit):
<add> pool_command.pool_import(self.parser.parse_args(['pools', 'import', 'pools_import_invalid.json']))
<add>
<add> def test_pool_import_invalid_pools(self):
<add> pool_config_input = {"foo": {"description": "foo_test"}}
<add> with open('pools_import_invalid.json', mode='w') as file:
<add> json.dump(pool_config_input, file)
<add>
<add> with self.assertRaises(SystemExit):
<add> pool_command.pool_import(self.parser.parse_args(['pools', 'import', 'pools_import_invalid.json']))
<add>
<ide> def test_pool_import_export(self):
<ide> # Create two pools first
<ide> pool_config_input = { | 2 |
PHP | PHP | fix trace/context for errors wrapped by debug kit | 0228bc73b6d6b3ce279b4313b01019faa551a109 | <ide><path>src/Error/BaseErrorHandler.php
<ide> public function handleError(
<ide>
<ide> $debug = Configure::read('debug');
<ide> if ($debug) {
<add> // By default trim 3 frames off for the public and protected methods
<add> // used by ErrorHandler instances.
<add> $start = 3;
<add>
<add> // Can be used by error handlers that wrap other error handlers
<add> // to coerce the generated stack trace to the correct point.
<add> if (isset($context['_trace_frame_offset'])) {
<add> $start += $context['_trace_frame_offset'];
<add> unset($context['_trace_frame_offset']);
<add> }
<ide> $data += [
<ide> 'context' => $context,
<del> 'start' => 3,
<add> 'start' => $start,
<ide> 'path' => Debugger::trimPath((string)$file),
<ide> ];
<ide> }
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> public function testHandleErrorDebugOn()
<ide> $this->assertRegExp('/<pre class="cake-error">/', $result);
<ide> $this->assertRegExp('/<b>Notice<\/b>/', $result);
<ide> $this->assertRegExp('/variable:\s+wrong/', $result);
<add> $this->assertStringContainsString(
<add> 'ErrorHandlerTest.php, line ' . (__LINE__ - 7),
<add> $result,
<add> 'Should contain file and line reference'
<add> );
<add> }
<add>
<add> /**
<add> * test error handling with the _trace_offset context variable
<add> *
<add> * @return void
<add> */
<add> public function testHandleErrorTraceOffset()
<add> {
<add> $this->_restoreError = true;
<add>
<add> set_error_handler(function ($code, $message, $file, $line, $context = null) {
<add> $errorHandler = new ErrorHandler();
<add> $context['_trace_frame_offset'] = 3;
<add> $errorHandler->handleError($code, $message, $file, $line, $context);
<add> });
<add>
<add> ob_start();
<add> $wrong = $wrong + 1;
<add> $result = ob_get_clean();
<add>
<add> $this->assertStringNotContainsString(
<add> 'ErrorHandlerTest.php, line ' . (__LINE__ - 4),
<add> $result,
<add> 'Should not contain file and line reference'
<add> );
<add> $this->assertStringNotContainsString('_trace_frame_offset', $result);
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | remove unneeded headings | f93f0850fa12ae7fd9cb5bab5fc2034eae112d95 | <ide><path>.github/ISSUE_TEMPLATE.md
<del>#### Preamble
<ide> This is a (multiple allowed):
<ide> * [x] bug
<ide> * [ ] enhancement
<ide> * [ ] feature-discussion (RFC)
<ide>
<del>## DESCRIPTIVE TITLE HERE
<ide> * CakePHP Version: EXACT RELEASE VERSION OR COMMIT HASH, HERE.
<ide> * Platform and Target: YOUR WEB-SERVER, DATABASE AND OTHER RELEVANT INFO AND HOW THE REQUEST IS BEING MADE, HERE.
<ide> | 1 |
Javascript | Javascript | use types from schema | d48975c948320d7983a928c4eeede93e8540c503 | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> yoda: "error",
<ide> eqeqeq: "error",
<ide> "global-require": "off",
<del> "brace-style": "error",
<add> "brace-style": "off",
<ide> "eol-last": "error",
<ide> "no-extra-bind": "warn",
<ide> "no-process-exit": "warn",
<ide><path>lib/AmdMainTemplatePlugin.js
<ide> const Template = require("./Template");
<ide>
<ide> class AmdMainTemplatePlugin {
<ide> /**
<del> * @param {string} name the library name
<add> * @param {string=} name the library name
<ide> */
<ide> constructor(name) {
<del> /** @type {string} */
<add> /** @type {string=} */
<ide> this.name = name;
<ide> }
<ide>
<ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> this.inputFileSystem = compiler.inputFileSystem;
<ide> this.requestShortener = compiler.requestShortener;
<ide>
<del> const options = (this.options = compiler.options);
<add> const options = compiler.options;
<add> this.options = options;
<ide> this.outputOptions = options && options.output;
<ide> /** @type {boolean=} */
<ide> this.bail = options && options.bail;
<ide><path>lib/Compiler.js
<ide> const RequestShortener = require("./RequestShortener");
<ide> const { makePathsRelative } = require("./util/identifier");
<ide> const ConcurrentCompilationError = require("./ConcurrentCompilationError");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */
<add>/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
<add>
<ide> /**
<ide> * @typedef {Object} CompilationParams
<ide> * @property {NormalModuleFactory} normalModuleFactory
<ide> * @property {ContextModuleFactory} contextModuleFactory
<ide> * @property {Set<string>} compilationDependencies
<ide> */
<ide>
<del>/** @typedef {string|string[]} EntryValues */
<del>/** @typedef {Record<string, EntryValues>} EntryOptionValues */
<del>
<del>/**
<del> * @callback EntryOptionValuesFunction
<del> * @returns {EntryOptionValues | EntryValues} the computed value
<del> */
<del>
<del>/** @typedef {EntryOptionValuesFunction | EntryOptionValues | EntryValues} EntryOptions */
<del>
<ide> class Compiler extends Tapable {
<ide> constructor(context) {
<ide> super();
<ide> class Compiler extends Tapable {
<ide> afterPlugins: new SyncHook(["compiler"]),
<ide> /** @type {SyncHook<Compiler>} */
<ide> afterResolvers: new SyncHook(["compiler"]),
<del> /** @type {SyncBailHook<string, EntryOptions>} */
<add> /** @type {SyncBailHook<string, Entry>} */
<ide> entryOption: new SyncBailHook(["context", "entry"])
<ide> };
<ide>
<ide> class Compiler extends Tapable {
<ide> }
<ide> };
<ide>
<del> this.options = {};
<add> /** @type {WebpackOptions} */
<add> this.options = /** @type {WebpackOptions} */ ({});
<ide>
<ide> this.context = context;
<ide>
<ide><path>lib/DynamicEntryPlugin.js
<ide> const MultiModuleFactory = require("./MultiModuleFactory");
<ide> const MultiEntryPlugin = require("./MultiEntryPlugin");
<ide> const SingleEntryPlugin = require("./SingleEntryPlugin");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */
<add>/** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */
<ide> /** @typedef {import("./Compiler")} Compiler */
<del>/** @typedef {import("./Compiler").EntryOptionValuesFunction} EntryOptionValuesFunction */
<ide>
<ide> class DynamicEntryPlugin {
<ide> /**
<ide> * @param {string} context the context path
<del> * @param {EntryOptionValuesFunction} entry the entry value
<add> * @param {EntryDynamic} entry the entry value
<ide> */
<ide> constructor(context, entry) {
<ide> this.context = context;
<ide> class DynamicEntryPlugin {
<ide> /**
<ide> * @param {string|string[]} entry entry value or array of entry values
<ide> * @param {string} name name of entry
<del> * @returns {Promise<any>} returns the promise resolving the Compilation#addEntry function
<add> * @returns {Promise<EntryStatic>} returns the promise resolving the Compilation#addEntry function
<ide> */
<ide> const addEntry = (entry, name) => {
<ide> const dep = DynamicEntryPlugin.createDependency(entry, name);
<ide><path>lib/EntryOptionPlugin.js
<ide> const SingleEntryPlugin = require("./SingleEntryPlugin");
<ide> const MultiEntryPlugin = require("./MultiEntryPlugin");
<ide> const DynamicEntryPlugin = require("./DynamicEntryPlugin");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */
<ide> /** @typedef {import("./Compiler")} Compiler */
<ide>
<ide> /**
<ide> * @param {string} context context path
<del> * @param {string | string[]} item entry array or single path
<add> * @param {EntryItem} item entry array or single path
<ide> * @param {string} name entry key name
<ide> * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin
<ide> */
<ide><path>lib/LibraryTemplatePlugin.js
<ide>
<ide> const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */
<ide> /** @typedef {import("./Compiler")} Compiler */
<ide>
<ide> /**
<ide> const accessorToObjectAccess = accessor => {
<ide>
<ide> /**
<ide> * @param {string=} base the path prefix
<del> * @param {string|string[]} accessor the accessor
<add> * @param {string|string[]|LibraryCustomUmdObject} accessor the accessor
<add> * @param {"amd" | "commonjs" | "root"} umdProperty property used when a custom umd object is provided
<ide> * @param {string=} joinWith the element separator
<ide> * @returns {string} the path
<ide> */
<del>const accessorAccess = (base, accessor, joinWith = "; ") => {
<del> const accessors = Array.isArray(accessor) ? accessor : [accessor];
<add>const accessorAccess = (base, accessor, umdProperty, joinWith = "; ") => {
<add> const normalizedAccessor =
<add> typeof accessor === "object" ? accessor[umdProperty] : accessor;
<add> const accessors = Array.isArray(normalizedAccessor)
<add> ? normalizedAccessor
<add> : [normalizedAccessor];
<ide> return accessors
<ide> .map((_, idx) => {
<ide> const a = base
<ide> const accessorAccess = (base, accessor, joinWith = "; ") => {
<ide>
<ide> class LibraryTemplatePlugin {
<ide> /**
<del> * @param {string} name name of library
<add> * @param {string|string[]|LibraryCustomUmdObject} name name of library
<ide> * @param {string} target type of library
<ide> * @param {boolean} umdNamedDefine setting this to true will name the UMD module
<ide> * @param {string|TODO} auxiliaryComment comment in the UMD wrapper
<ide> class LibraryTemplatePlugin {
<ide> }
<ide> switch (this.target) {
<ide> case "var":
<add> if (
<add> !this.name ||
<add> (typeof this.name === "object" && !Array.isArray(this.name))
<add> ) {
<add> throw new Error(
<add> "library name must be set and not an UMD custom object for non-UMD target"
<add> );
<add> }
<ide> new SetVarMainTemplatePlugin(
<del> `var ${accessorAccess(undefined, this.name)}`,
<add> `var ${accessorAccess(undefined, this.name, "root")}`,
<ide> false
<ide> ).apply(compilation);
<ide> break;
<ide> case "assign":
<ide> new SetVarMainTemplatePlugin(
<del> accessorAccess(undefined, this.name),
<add> accessorAccess(undefined, this.name, "root"),
<ide> false
<ide> ).apply(compilation);
<ide> break;
<ide> class LibraryTemplatePlugin {
<ide> case "window":
<ide> if (this.name) {
<ide> new SetVarMainTemplatePlugin(
<del> accessorAccess(this.target, this.name),
<add> accessorAccess(this.target, this.name, "root"),
<ide> false
<ide> ).apply(compilation);
<ide> } else {
<ide> class LibraryTemplatePlugin {
<ide> new SetVarMainTemplatePlugin(
<ide> accessorAccess(
<ide> compilation.runtimeTemplate.outputOptions.globalObject,
<del> this.name
<add> this.name,
<add> "root"
<ide> ),
<ide> false
<ide> ).apply(compilation);
<ide> class LibraryTemplatePlugin {
<ide> case "commonjs":
<ide> if (this.name) {
<ide> new SetVarMainTemplatePlugin(
<del> accessorAccess("exports", this.name),
<add> accessorAccess("exports", this.name, "commonjs"),
<ide> false
<ide> ).apply(compilation);
<ide> } else {
<ide> class LibraryTemplatePlugin {
<ide> break;
<ide> case "amd": {
<ide> const AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin");
<del> new AmdMainTemplatePlugin(this.name).apply(compilation);
<add> if (this.name) {
<add> if (typeof this.name !== "string")
<add> throw new Error("library name must be a string for amd target");
<add> new AmdMainTemplatePlugin(this.name).apply(compilation);
<add> } else {
<add> new AmdMainTemplatePlugin().apply(compilation);
<add> }
<ide> break;
<ide> }
<ide> case "umd":
<ide> class LibraryTemplatePlugin {
<ide> }
<ide> case "jsonp": {
<ide> const JsonpExportMainTemplatePlugin = require("./web/JsonpExportMainTemplatePlugin");
<add> if (typeof this.name !== "string")
<add> throw new Error("library name must be a string for jsonp target");
<ide> new JsonpExportMainTemplatePlugin(this.name).apply(compilation);
<ide> break;
<ide> }
<ide><path>lib/UmdMainTemplatePlugin.js
<ide> const { ConcatSource, OriginalSource } = require("webpack-sources");
<ide> const Template = require("./Template");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */
<ide> /** @typedef {import("./Compilation")} Compilation */
<ide>
<ide> /**
<ide> const accessorAccess = (base, accessor, joinWith = ", ") => {
<ide> .join(joinWith);
<ide> };
<ide>
<del>/** @typedef {string | string[] | Record<string, string | string[]>} UmdMainTemplatePluginName */
<add>/** @typedef {string | string[] | LibraryCustomUmdObject} UmdMainTemplatePluginName */
<ide>
<ide> /**
<ide> * @typedef {Object} AuxiliaryCommentObject
<ide><path>lib/WebpackOptionsApply.js
<ide> const DefinePlugin = require("./DefinePlugin");
<ide> const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin");
<ide> const WasmFinalizeExportsPlugin = require("./wasm/WasmFinalizeExportsPlugin");
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
<add>/** @typedef {import("./Compiler")} Compiler */
<add>
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> constructor() {
<ide> super();
<ide> }
<ide>
<add> /**
<add> * @param {WebpackOptions} options options object
<add> * @param {Compiler} compiler compiler object
<add> * @returns {WebpackOptions} options object
<add> */
<ide> process(options, compiler) {
<ide> let ExternalsPlugin;
<ide> compiler.outputPath = options.output.path;
<ide> compiler.recordsInputPath = options.recordsInputPath || options.recordsPath;
<ide> compiler.recordsOutputPath =
<ide> options.recordsOutputPath || options.recordsPath;
<ide> compiler.name = options.name;
<add> // TODO webpack 5 refactor this to MultiCompiler.setDependencies() with a WeakMap
<add> // @ts-ignore TODO
<ide> compiler.dependencies = options.dependencies;
<ide> if (typeof options.target === "string") {
<ide> let JsonpTemplatePlugin;
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> default:
<ide> throw new Error("Unsupported target '" + options.target + "'.");
<ide> }
<del> } else if (options.target !== false) {
<add> }
<add> // @ts-ignore This is always true, which is good this way
<add> else if (options.target !== false) {
<ide> options.target(compiler);
<ide> } else {
<ide> throw new Error("Unsupported target '" + options.target + "'.");
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> }
<ide> if (options.optimization.minimize) {
<ide> for (const minimizer of options.optimization.minimizer) {
<del> minimizer.apply(compiler);
<add> if (typeof minimizer === "function") {
<add> minimizer.apply(compiler);
<add> } else {
<add> minimizer.apply(compiler);
<add> }
<ide> }
<ide> }
<ide>
<ide><path>lib/web/JsonpExportMainTemplatePlugin.js
<ide> const { ConcatSource } = require("webpack-sources");
<ide>
<ide> class JsonpExportMainTemplatePlugin {
<add> /**
<add> * @param {string} name jsonp function name
<add> */
<ide> constructor(name) {
<ide> this.name = name;
<ide> }
<ide><path>lib/webpack.js
<ide> const webpackOptionsSchema = require("../schemas/WebpackOptions.json");
<ide> const RemovedPluginError = require("./RemovedPluginError");
<ide> const version = require("../package.json").version;
<ide>
<add>/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
<add>
<add>/**
<add> * @param {WebpackOptions} options options object
<add> * @param {function(Error=, Stats=): void=} callback callback
<add> * @returns {Compiler | MultiCompiler} the compiler object
<add> */
<ide> const webpack = (options, callback) => {
<ide> const webpackOptionsValidationErrors = validateSchema(
<ide> webpackOptionsSchema,
<ide> const webpack = (options, callback) => {
<ide> new NodeEnvironmentPlugin().apply(compiler);
<ide> if (options.plugins && Array.isArray(options.plugins)) {
<ide> for (const plugin of options.plugins) {
<del> plugin.apply(compiler);
<add> if (typeof plugin === "function") {
<add> plugin.apply(compiler);
<add> } else {
<add> plugin.apply(compiler);
<add> }
<ide> }
<ide> }
<ide> compiler.hooks.environment.call(); | 11 |
Ruby | Ruby | fix eager load of serializers on active model | 486db21f919c39cef76b487be45290b7561307e8 | <ide><path>activemodel/lib/active_model.rb
<ide> module Serializers
<ide> end
<ide> end
<ide>
<del> def eager_load!
<add> def self.eager_load!
<ide> super
<del> ActiveModel::Serializer.eager_load!
<add> ActiveModel::Serializers.eager_load!
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | add requested changes from pr comments | 57c6c4323c0655a19fea1d2dc350d7fba5ffe7a5 | <ide><path>lib/WebpackOptionsDefaulter.js
<ide> class WebpackOptionsDefaulter extends OptionsDefaulter {
<ide> });
<ide> this.set("output.devtoolNamespace", "make", options => {
<ide> if (Array.isArray(options.output.library))
<del> return [].concat(options.output.library).join(".");
<add> return options.output.library.join(".");
<ide> return options.output.library || "";
<ide> });
<ide> this.set("output.libraryTarget", "var");
<ide><path>test/configCases/source-map/array-as-output-library/index.js
<add>it("should compile successfully when output.library is an array of strings", function() {});
<ide><path>test/configCases/source-map/array-as-output-library/webpack.config.js
<add>module.exports = {
<add> devtool: "source-map",
<add> output: {
<add> filename: "MyLibrary.[name].js",
<add> library: ["Foo", "[name]"]
<add> }
<add>}; | 3 |
Python | Python | fix half of the tests that are failing in v1 | 1e859f75070ea2c145850bddc61a0de82f69db61 | <ide><path>keras/applications/imagenet_utils_test.py
<ide> def test_preprocess_input_symbolic(self, mode):
<ide> },
<ide> ])
<ide> def test_preprocess_input_symbolic_mixed_precision(self, mode):
<add> if not tf.__internal__.tf2.enabled():
<add> self.skipTest('The global policy can only be tested in TensorFlow 2')
<ide> set_global_policy('mixed_float16')
<ide> shape = (20, 20, 3)
<ide> inputs = keras.layers.Input(shape=shape)
<ide><path>keras/distribute/keras_premade_models_test.py
<ide> def test_linear_model(self, distribution, use_dataset_creator, data_fn):
<ide> self.skipTest(
<ide> 'Parameter Server strategy requires dataset creator to be used in '
<ide> 'model.fit.')
<add> if (not tf.__internal__.tf2.enabled() and use_dataset_creator
<add> and isinstance(distribution,
<add> tf.distribute.experimental.ParameterServerStrategy)):
<add> self.skipTest(
<add> 'Parameter Server strategy with dataset creator needs to be run when '
<add> 'eager execution is enabled.')
<ide> with distribution.scope():
<ide> model = linear.LinearModel()
<ide> opt = gradient_descent.SGD(learning_rate=0.1)
<ide> def test_wide_deep_model(self, distribution, use_dataset_creator, data_fn):
<ide> self.skipTest(
<ide> 'Parameter Server strategy requires dataset creator to be used in '
<ide> 'model.fit.')
<add> if (not tf.__internal__.tf2.enabled() and use_dataset_creator
<add> and isinstance(distribution,
<add> tf.distribute.experimental.ParameterServerStrategy)):
<add> self.skipTest(
<add> 'Parameter Server strategy with dataset creator needs to be run when '
<add> 'eager execution is enabled.')
<ide> with distribution.scope():
<ide> linear_model = linear.LinearModel(units=1)
<ide> dnn_model = sequential.Sequential([core.Dense(units=1)])
<ide><path>keras/engine/functional_utils_test.py
<ide> import tensorflow.compat.v2 as tf
<ide>
<ide>
<add>@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> class FunctionalModelSlideTest(keras_parameterized.TestCase):
<ide>
<ide> def test_find_nodes_by_inputs_and_outputs(self):
<ide><path>keras/engine/training_test.py
<ide> def test_model_make_function(self):
<ide>
<ide> class TestExceptionsAndWarnings(keras_parameterized.TestCase):
<ide>
<del> @keras_parameterized.run_all_keras_modes
<add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> @keras_parameterized.run_with_all_model_types
<ide> def test_fit_on_no_output(self):
<ide> inputs = layers_module.Input((3,))
<ide> def test_fit_on_no_output(self):
<ide> with self.assertRaisesRegex(TypeError, 'Target data is missing..*'):
<ide> model.fit(x)
<ide>
<del> @keras_parameterized.run_all_keras_modes
<add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> @keras_parameterized.run_with_all_model_types
<ide> def test_fit_on_wrong_output_type(self):
<ide> inputs1 = layers_module.Input((3,), name='a')
<ide> def call(self, inputs):
<ide>
<ide> class ScalarDataModelTest(keras_parameterized.TestCase):
<ide>
<add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> def test_scalar_loss_reduction(self):
<ide>
<ide> class MyModel(training_module.Model):
<ide>
<ide> def __init__(self):
<ide> super().__init__()
<del> self.w = self.add_weight((), initializer='ones')
<del> self.b = self.add_weight((), initializer='zeros')
<add> self.w = self.add_weight(initializer='ones', name='kernel')
<add> self.b = self.add_weight(initializer='zeros', name='bias')
<ide>
<ide> def call(self, inputs):
<ide> return inputs * self.w + self.b
<ide><path>keras/integration_test/distributed_training_test.py
<ide> class DistributedTrainingTest(tf.test.TestCase):
<ide> """Test to demonstrate basic Keras training with a variety of strategies."""
<ide>
<ide> def testKerasTrainingAPI(self, strategy):
<add> if (not tf.__internal__.tf2.enabled()
<add> and isinstance(strategy,
<add> tf.distribute.experimental.ParameterServerStrategy)):
<add> self.skipTest(
<add> "Parameter Server strategy with dataset creator need to be run when "
<add> "eager execution is enabled.")
<ide>
<ide> # A `dataset_fn` is required for `Model.fit` to work across all strategies.
<ide> def dataset_fn(input_context):
<ide><path>keras/integration_test/forwardprop_test.py
<ide> def _loss(*unused_args):
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> tf.test.main()
<add> if tf.__internal__.tf2.enabled():
<add> tf.test.main()
<ide><path>keras/integration_test/function_test.py
<ide> def fn(x):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> tf.test.main()
<add> if tf.__internal__.tf2.enabled():
<add> tf.test.main()
<ide><path>keras/integration_test/gradients_test.py
<ide> def _run(x):
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> tf.test.main()
<add> if tf.__internal__.tf2.enabled():
<add> tf.test.main()
<ide><path>keras/integration_test/parameter_server_custom_training_loop_test.py
<ide> def replica_fn(inputs):
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> tf.__internal__.distribute.multi_process_runner.test_main()
<add> if tf.__internal__.tf2.enabled():
<add> tf.__internal__.distribute.multi_process_runner.test_main()
<ide><path>keras/integration_test/preprocessing_test_utils.py
<ide> def make_dataset():
<ide> The dataset.
<ide> """
<ide> tf.random.set_seed(197011)
<del> floats = tf.random.uniform((DS_SIZE, 1), maxval=10, dtype="float64")
<add> floats = tf.random.uniform((DS_SIZE, 1), maxval=10, dtype="float32")
<ide> # Generate a 100 unique integer values, but over a wide range to showcase a
<ide> # common use case for IntegerLookup.
<ide> ints = tf.random.uniform((DS_SIZE, 1), maxval=VOCAB_SIZE, dtype="int64")
<ide> def make_dataset():
<ide> def make_preprocessing_model(file_dir):
<ide> """Make a standalone preprocessing model."""
<ide> # The name of our keras.Input should match the column name in the dataset.
<del> float_in = tf.keras.Input(shape=(1,), dtype="float64", name="float_col")
<add> float_in = tf.keras.Input(shape=(1,), dtype="float32", name="float_col")
<ide> int_in = tf.keras.Input(shape=(1,), dtype="int64", name="int_col")
<ide> string_in = tf.keras.Input(shape=(1,), dtype="string", name="string_col")
<ide>
<ide> def make_preprocessing_model(file_dir):
<ide>
<ide> def make_training_model():
<ide> """Make a trainable model for the preprocessed inputs."""
<del> float_in = tf.keras.Input(shape=(1,), dtype="float64", name="float_col")
<add> float_in = tf.keras.Input(shape=(1,), dtype="float32", name="float_col")
<ide> # After preprocessing, both the string and int column are integer ready for
<ide> # embedding.
<ide> int_in = tf.keras.Input(shape=(1,), dtype="int64", name="int_col")
<ide><path>keras/integration_test/saved_model_test.py
<ide> def test_functional_model_with_conv(self, cycles):
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> tf.test.main()
<add> if tf.__internal__.tf2.enabled():
<add> tf.test.main()
<ide><path>keras/integration_test/tpu_strategy_test.py
<ide> def define_inverse_lookup_layer(self):
<ide> return label_inverse_lookup_layer
<ide>
<ide> def test_keras_metric_outside_strategy_scope_per_replica(self):
<add> if not tf.compat.v1.executing_eagerly():
<add> self.skipTest("connect_to_cluster() can only be called in eager mode")
<ide> strategy = get_tpu_strategy()
<ide> metric = tf.keras.metrics.Mean("test_metric", dtype=tf.float32)
<ide>
<ide> def step_fn(i):
<ide>
<ide> @test_util.disable_mlir_bridge("TODO(b/168036682): Support dynamic padder")
<ide> def test_train_and_serve(self):
<add> if not tf.compat.v1.executing_eagerly():
<add> self.skipTest("connect_to_cluster() can only be called in eager mode")
<ide> strategy = get_tpu_strategy()
<ide> use_adapt = False
<ide> | 12 |
Go | Go | normalize comment formatting | 0fb563078469c76fbd16535d7a2bf10772cbec3a | <ide><path>pkg/system/chtimes_unix.go
<ide> import (
<ide> "time"
<ide> )
<ide>
<del>//setCTime will set the create time on a file. On Unix, the create
<del>//time is updated as a side effect of setting the modified time, so
<del>//no action is required.
<add>// setCTime will set the create time on a file. On Unix, the create
<add>// time is updated as a side effect of setting the modified time, so
<add>// no action is required.
<ide> func setCTime(path string, ctime time.Time) error {
<ide> return nil
<ide> }
<ide><path>pkg/system/chtimes_windows.go
<ide> import (
<ide> "golang.org/x/sys/windows"
<ide> )
<ide>
<del>//setCTime will set the create time on a file. On Windows, this requires
<del>//calling SetFileTime and explicitly including the create time.
<add>// setCTime will set the create time on a file. On Windows, this requires
<add>// calling SetFileTime and explicitly including the create time.
<ide> func setCTime(path string, ctime time.Time) error {
<ide> ctimespec := windows.NsecToTimespec(ctime.UnixNano())
<ide> pathp, e := windows.UTF16PtrFromString(path)
<ide><path>pkg/system/filesys_windows.go
<ide> func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle,
<ide> createmode = windows.OPEN_EXISTING
<ide> }
<ide> // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang.
<del> //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
<add> // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
<ide> const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN
<ide> h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0)
<ide> return h, e | 3 |
PHP | PHP | remove unneeded trait | 749528db0c85c69349f8e8af564378cf9457a1d8 | <ide><path>app/Http/Controllers/Controller.php
<ide> use Illuminate\Routing\Controller as BaseController;
<ide> use Illuminate\Foundation\Validation\ValidatesRequests;
<ide> use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
<del>use Illuminate\Foundation\Auth\Access\AuthorizesResources;
<ide>
<ide> class Controller extends BaseController
<ide> {
<del> use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
<add> use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
<ide> } | 1 |
Python | Python | implement like_num getter for dutch (via ) | adda08fe14479e465668bcf39dcedd238a4be20e | <ide><path>spacy/lang/nl/__init__.py
<ide> from __future__ import unicode_literals
<ide>
<ide> from .stop_words import STOP_WORDS
<add>from .lex_attrs import LEX_ATTRS
<ide>
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide>
<ide> class DutchDefaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<add> lex_attr_getters.update(LEX_ATTRS)
<ide> lex_attr_getters[LANG] = lambda text: 'nl'
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<ide>
<ide><path>spacy/lang/nl/lex_attrs.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...attrs import LIKE_NUM
<add>
<add>
<add>_num_words = set("""
<add>nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien
<add>veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd
<add>duizend miljoen miljard biljoen biljard triljoen triljard
<add>""".split())
<add>
<add>_ordinal_words = set("""
<add>eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde
<add>twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste
<add>zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste
<add>miljardste biljoenste biljardste triljoenste triljardste
<add>""".split())
<add>
<add>
<add>def like_num(text):
<add> text = text.replace(',', '').replace('.', '')
<add> if text.isdigit():
<add> return True
<add> if text.count('/') == 1:
<add> num, denom = text.split('/')
<add> if num.isdigit() and denom.isdigit():
<add> return True
<add> if text in _num_words:
<add> return True
<add> return False
<add>
<add>
<add>LEX_ATTRS = {
<add> LIKE_NUM: like_num
<add>} | 2 |
Ruby | Ruby | add failing test case for parameters with periods | 3d8200318aab7458e019e2e434901cccc2532979 | <ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def self.matches?(request)
<ide> get "profile" => "customers#profile", :as => :profile, :on => :member
<ide> post "preview" => "customers#preview", :as => :preview, :on => :new
<ide> end
<add> scope(':version', :version => /.+/) do
<add> resources :users, :id => /.+?/, :format => /json|xml/
<add> end
<ide> end
<ide>
<ide> match 'sprockets.js' => ::TestRoutingMapper::SprocketsApp
<ide> def test_shallow_nested_routes_ignore_module
<ide> end
<ide> end
<ide>
<add> def test_non_greedy_regexp
<add> with_test_routes do
<add> get '/api/1.0/users'
<add> assert_equal 'api/users#index', @response.body
<add> assert_equal '/api/1.0/users', api_users_path(:version => '1.0')
<add>
<add> get '/api/1.0/users.json'
<add> assert_equal 'api/users#index', @response.body
<add> assert_equal true, @request.format.json?
<add> assert_equal '/api/1.0/users.json', api_users_path(:version => '1.0', :format => :json)
<add>
<add> get '/api/1.0/users/first.last'
<add> assert_equal 'api/users#show', @response.body
<add> assert_equal 'first.last', @request.params[:id]
<add> assert_equal '/api/1.0/users/first.last', api_user_path(:version => '1.0', :id => 'first.last')
<add>
<add> get '/api/1.0/users/first.last.xml'
<add> assert_equal 'api/users#show', @response.body
<add> assert_equal 'first.last', @request.params[:id]
<add> assert_equal true, @request.format.xml?
<add> assert_equal '/api/1.0/users/first.last.xml', api_user_path(:version => '1.0', :id => 'first.last', :format => :xml)
<add> end
<add> end
<add>
<ide> private
<ide> def with_test_routes
<ide> yield | 1 |
PHP | PHP | add strict_types to testsuite/constraint | 5a5b7b62b725fca79aa491b9eedbee1dd8106ff8 | <ide><path>src/TestSuite/Constraint/Console/ContentsBase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ContentsContain.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ContentsContainRow.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ContentsEmpty.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ContentsNotContain.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ContentsRegExp.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Console/ExitCode.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailConstraintBase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailContains.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailContainsHtml.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailContainsText.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailCount.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailSentFrom.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailSentTo.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/MailSentWith.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Email/NoMailSent.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/EventFired.php
<ide> <?php
<add>declare(strict_types=1);
<ide> namespace Cake\TestSuite\Constraint;
<ide>
<ide> use PHPUnit\Framework\AssertionFailedError;
<ide><path>src/TestSuite/Constraint/EventFiredWith.php
<ide> <?php
<add>declare(strict_types=1);
<ide> namespace Cake\TestSuite\Constraint;
<ide>
<ide> use Cake\Event\EventInterface;
<ide><path>src/TestSuite/Constraint/Response/BodyContains.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyEmpty.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyNotContains.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyNotEmpty.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyNotEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyNotRegExp.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/BodyRegExp.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/ContentType.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/CookieEncryptedEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/CookieEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/CookieNotSet.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/CookieSet.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/FileSent.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/FileSentAs.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/HeaderContains.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/HeaderEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/HeaderNotSet.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/HeaderSet.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/ResponseBase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusCode.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusCodeBase.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusError.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusFailure.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusOk.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Response/StatusSuccess.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Session/FlashParamEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/Session/SessionEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/View/LayoutFileEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/TestSuite/Constraint/View/TemplateFileEquals.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) | 48 |
Javascript | Javascript | move built flag into compilation | eb63cf80d6f2102270c2babfb620cfd78a2a33cb | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> this.compilationDependencies = undefined;
<ide> /** @type {boolean} */
<ide> this.needAdditionalPass = false;
<add> /** @type {WeakSet<Module>} */
<add> this.builtModules = new WeakSet();
<ide> /** @private @type {Map<Module, Callback[]>} */
<ide> this._buildingModules = new Map();
<ide> /** @private @type {Map<Module, Callback[]>} */
<ide> class Compilation {
<ide> };
<ide>
<ide> this.hooks.buildModule.call(module);
<add> this.builtModules.add(module);
<ide> module.build(
<ide> this.options,
<ide> this,
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> * @returns {void}
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<del> this.built = true;
<ide> this.buildMeta = {};
<ide> this.buildInfo = {
<ide> builtTime: Date.now(),
<ide><path>lib/DelegatedModule.js
<ide> class DelegatedModule extends Module {
<ide> * @returns {void}
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<del> this.built = true;
<ide> this.buildMeta = Object.assign({}, this.delegateData.buildMeta);
<ide> this.buildInfo = {};
<ide> this.delegatedSourceDependency = new DelegatedSourceDependency(
<ide><path>lib/DllModule.js
<ide> class DllModule extends Module {
<ide> * @returns {void}
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<del> this.built = true;
<ide> this.buildMeta = {};
<ide> this.buildInfo = {};
<ide> return callback();
<ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> * @returns {void}
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<del> this.built = true;
<ide> this.buildMeta = {};
<ide> this.buildInfo = {};
<ide> callback();
<ide><path>lib/Module.js
<ide> class Module extends DependenciesBlock {
<ide> // Info from Compilation (per Compilation)
<ide> /** @type {number|string} */
<ide> this.id = null;
<del> /** @type {boolean} */
<del> this.built = false;
<ide>
<ide> /** @type {boolean} */
<ide> this.useSourceMap = false;
<ide> class Module extends DependenciesBlock {
<ide> this.renderedHash = undefined;
<ide>
<ide> this.id = null;
<del> this.built = false;
<ide>
<ide> super.disconnect();
<ide> }
<ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<ide> this.buildTimestamp = Date.now();
<del> this.built = true;
<ide> this._source = null;
<ide> this._ast = null;
<ide> this._buildHash = "";
<ide><path>lib/RawModule.js
<ide> module.exports = class RawModule extends Module {
<ide> this.sourceStr = source;
<ide> this.identifierStr = identifier || this.sourceStr;
<ide> this.readableIdentifierStr = readableIdentifier || this.identifierStr;
<del> this.built = false;
<ide> }
<ide>
<ide> /**
<ide> module.exports = class RawModule extends Module {
<ide> * @returns {void}
<ide> */
<ide> build(options, compilation, resolver, fs, callback) {
<del> this.built = true;
<ide> this.buildMeta = {};
<ide> this.buildInfo = {
<ide> cacheable: true
<ide><path>lib/Stats.js
<ide> class Stats {
<ide> }
<ide>
<ide> if (!showCachedModules) {
<del> excludeModules.push((ident, module) => !module.built);
<add> excludeModules.push(
<add> (ident, module) => !compilation.builtModules.has(module)
<add> );
<ide> }
<ide>
<ide> const createModuleFilter = type => {
<ide> class Stats {
<ide> postOrderIndex: moduleGraph.getPostOrderIndex(module),
<ide> size: module.size(),
<ide> cacheable: module.buildInfo.cacheable,
<del> built: !!module.built,
<add> built: compilation.builtModules.has(module),
<ide> optional: module.isOptional(moduleGraph),
<ide> chunks: Array.from(
<ide> chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById),
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> contextDependencies: new Set(),
<ide> assets: undefined
<ide> };
<del> this.built = modulesArray.some(m => m.built);
<ide> this.buildMeta = rootModule.buildMeta;
<ide>
<ide> // Caching
<ide><path>lib/optimize/ModuleConcatenationPlugin.js
<ide> class ModuleConcatenationPlugin {
<ide> moduleGraph.moveModuleAttributes(rootModule, newModule);
<ide> for (const m of modules) {
<ide> usedModules.add(m);
<add> // add to builtModules when one of the included modules was built
<add> if (compilation.builtModules.has(m)) {
<add> compilation.builtModules.add(newModule);
<add> }
<ide> // remove attributes from module
<ide> moduleGraph.removeModuleAttributes(m);
<ide> // remove module from chunk | 11 |
Ruby | Ruby | add parentheses to hide ruby warning | 6d8ec0bc93d29ae16e74aa2baf9d361e558e7d12 | <ide><path>railties/test/queueing/threaded_consumer_test.rb
<ide> def teardown
<ide> sleep 0.1
<ide>
<ide> assert_equal 1, logger.logged(:error).size
<del> assert_match /Job Error: RuntimeError: Error!/, logger.logged(:error).last
<add> assert_match(/Job Error: RuntimeError: Error!/, logger.logged(:error).last)
<ide> end
<ide> end | 1 |
Text | Text | improve russian translation in challenge | c88b622ab9ad7a90fdf9cce061c02e8bb5ef68e5 | <ide><path>curriculum/challenges/russian/08-coding-interview-prep/algorithms/find-the-symmetric-difference.russian.md
<ide> localeTitle: Найти симметричную разницу
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Создайте функцию, которая принимает два или более массива и возвращает массив <dfn>симметричной разности</dfn> ( <code>△</code> или <code>⊕</code> ) предоставленных массивов. Для двух наборов (например, множества <code>A = {1, 2, 3}</code> и множества <code>B = {2, 3, 4}</code> ) математический термин «симметричная разность» двух множеств представляет собой набор элементов, которые находятся в любом из два набора, но не в обоих ( <code>A △ B = C = {1, 4}</code> ). Для каждой дополнительной симметричной разности, которую вы принимаете (скажем, на множестве <code>D = {2, 3}</code> ), вы должны получить набор с элементами, которые находятся в любом из двух наборов, но не оба ( <code>C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}</code> ). Результирующий массив должен содержать только уникальные значения ( <em>без дубликатов</em> ). Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код. </section>
<add><section id="description"> Создайте функцию, которая принимает два или более массива и возвращает массив <dfn>симметричной разности</dfn> ( <code>△</code> или <code>⊕</code> ) предоставленных массивов. Для двух множеств (например, для множества <code>A = {1, 2, 3}</code> и множества <code>B = {2, 3, 4}</code> ) математический термин «симметричная разность» двух множеств представляет собой включающее все элементы исходных множеств, не принадлежащие одновременно обоим исходным множествам ( <code>A △ B = C = {1, 4}</code> ). Для каждой дополнительной симметричной разности, которую вы принимаете (допустим, множество <code>D = {2, 3}</code> ), вы должны получить набор с элементами, которые находятся в любом из двух наборов, но не в обоих одновременно ( <code>C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}</code> ). Результирующий массив должен содержать только уникальные значения ( <em>без дубликатов</em> ). Не забудьте использовать <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте парное программирование. Напишите свой собственный код. </section>
<ide>
<ide> ## Instructions
<ide> undefined
<ide> undefined
<ide>
<ide> ```yml
<ide> tests:
<del> - text: ''
<add> - text: '<code>sym([1, 2, 3], [5, 2, 1, 4])</code> должнен возвращать <code>[3, 4, 5]</code>.'
<ide> testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5], "<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.");'
<del> - text: ''
<add> - text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен содержать только три элемента.'
<ide> testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3, "<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should contain only three elements.");'
<del> - text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен вернуться <code>[3, 4, 5]</code> .'
<add> - text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен возвращать <code>[3, 4, 5]</code> .'
<ide> testString: 'assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5], "<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.");'
<ide> - text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> должен содержать только три элемента.'
<ide> testString: 'assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3, "<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should contain only three elements.");'
<del> - text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> должен вернуться <code>[3, 4, 5]</code> .'
<add> - text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> должен возвращать <code>[3, 4, 5]</code> .'
<ide> testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5], "<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should return <code>[3, 4, 5]</code>.");'
<del> - text: ''
<add> - text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> должен содержать только три элемента.'
<ide> testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3, "<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should contain only three elements.");'
<del> - text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> должны возвращать <code>[1, 4, 5]</code>'
<add> - text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> должен возвращать <code>[1, 4, 5]</code>'
<ide> testString: 'assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5], "<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should return <code>[1, 4, 5]</code>");'
<del> - text: ''
<add> - text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> должен содержать только три элемента.'
<ide> testString: 'assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3, "<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should contain only three elements.");'
<del> - text: ''
<add> - text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> должен возвращать <code>[1, 4, 5]</code>'
<ide> testString: 'assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5], "<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should return <code>[1, 4, 5]</code>.");'
<del> - text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> должны содержать только три элемента.'
<add> - text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> должен содержать только три элемента.'
<ide> testString: 'assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3, "<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should contain only three elements.");'
<del> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должны возвращать <code>[2, 3, 4, 6, 7]</code> .'
<add> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должен возвращать <code>[2, 3, 4, 6, 7]</code> .'
<ide> testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]), [2, 3, 4, 6, 7], "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should return <code>[2, 3, 4, 6, 7]</code>.");'
<del> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должны содержать только пять элементов.'
<add> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> должен содержать только пять элементов.'
<ide> testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]).length, 5, "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should contain only five elements.");'
<del> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должны возвращать <code>[1, 2, 4, 5, 6, 7, 8, 9]</code> .'
<add> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должен возвращать <code>[1, 2, 4, 5, 6, 7, 8, 9]</code> .'
<ide> testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]), [1, 2, 4, 5, 6, 7, 8, 9], "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should return <code>[1, 2, 4, 5, 6, 7, 8, 9]</code>.");'
<del> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должны содержать только восемь элементов.'
<add> - text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> должен содержать только восемь элементов.'
<ide> testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]).length, 8, "<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should contain only eight elements.");'
<ide>
<ide> ``` | 1 |
Javascript | Javascript | fix an incorrect comment in the attributes module | 5430c540dfedf1a64558d5f55f668904ee787817 | <ide><path>src/attributes/attr.js
<ide> jQuery.extend( {
<ide> return jQuery.prop( elem, name, value );
<ide> }
<ide>
<del> // All attributes are lowercase
<add> // Attribute hooks are determined by the lowercase version
<ide> // Grab necessary hook if one is defined
<ide> if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
<ide> hooks = jQuery.attrHooks[ name.toLowerCase() ] || | 1 |
Go | Go | set appropriate cflags on solaris | 4683f588ce893f3156ecfa63bfd16ebda1d09157 | <ide><path>pkg/system/meminfo_solaris.go
<ide> import (
<ide> "unsafe"
<ide> )
<ide>
<add>// #cgo CFLAGS: -std=c99
<ide> // #cgo LDFLAGS: -lkstat
<ide> // #include <unistd.h>
<ide> // #include <stdlib.h> | 1 |
Javascript | Javascript | add tests for false positives | eab6a1a38954efe09f6825289b6bc0beecebe43c | <ide><path>type-definitions/tests/immutable-flow.js
<ide> stringToNumber = Map({'a': 1}).mergeDeepIn([], [])
<ide>
<ide> anyMap = Map({'a': {}}).mergeIn(['a'], { b: 2 })
<ide> anyMap = Map({'a': {}}).mergeDeepIn(['a'], { b: 2 })
<add>// $ExpectError
<add>anyMap = Map({'a': {}}).mergeIn(['a'], 1)
<add>// $ExpectError
<add>anyMap = Map({'a': {}}).mergeDeepIn(['a'], 1)
<ide>
<ide> stringToNumber = Map({'a': 1}).withMutations(mutable => mutable)
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.