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 |
|---|---|---|---|---|---|
Python | Python | fix separated strings in test_secrets_manager.py | f383bb34163d3d5db78c66f26f2c429140f3171f | <ide><path>tests/providers/amazon/aws/secrets/test_secrets_manager.py
<ide>
<ide>
<ide> class TestSecretsManagerBackend(TestCase):
<del> @mock.patch("airflow.providers.amazon.aws.secrets.secrets_manager." "SecretsManagerBackend.get_conn_uri")
<add> @mock.patch("airflow.providers.amazon.aws.secrets.secrets_manager.SecretsManagerBackend.get_conn_uri")
<ide> def test_aws_secrets_manager_get_connections(self, mock_get_uri):
<ide> mock_get_uri.return_value = "scheme://user:pass@host:100"
<ide> conn_list = SecretsManagerBackend().get_connections("fake_conn") | 1 |
PHP | PHP | add compatibility for 2.1 | c7a9f3412f290e5fdca76b702f67b194cde1dffc | <ide><path>lib/Cake/bootstrap.php
<ide>
<ide> Configure::bootstrap(isset($boot) ? $boot : true);
<ide>
<add>/**
<add> * Compatibility with 2.1, which expects Set to always be autoloaded.
<add> */
<add>App::uses('Set', 'Utilty');
<add>
<ide> /**
<ide> * Full url prefix
<ide> */ | 1 |
Javascript | Javascript | add bone graph to skinnedmesh | 6a53e95c2257c39d8a15b76779f38175c899ed8c | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
<ide>
<add> var buildBoneGraph = function ( parentJson, parentObject, property ) {
<add>
<add> var children = parentJson[ property ];
<add>
<add> if ( children === undefined ) return;
<add>
<add> for ( var i = 0, il = children.length; i < il; i ++ ) {
<add>
<add> var nodeId = children[ i ];
<add> var bone = __nodes[ nodeId ];
<add> var boneJson = json.nodes[ nodeId ];
<add>
<add> if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
<add>
<add> parentObject.add( bone );
<add> buildBoneGraph( boneJson, bone, 'children' );
<add>
<add> }
<add>
<add> }
<add>
<add> }
<add>
<add> buildBoneGraph( node, child, 'skeletons' );
<add>
<ide> }
<ide>
<ide> _node.add( child ); | 1 |
Text | Text | make link work in github itself | eeba91e0de9e9e4df973cc51f98a5028beb04b04 | <ide><path>docs/getting-started/index.md
<ide> module.exports = {
<ide> As you can see, some of the boilerplate needed is not visible in our sample blocks, as the samples focus on the configuration options.
<ide> :::
<ide>
<del>All our examples are [available online](/samples/).
<add>All our examples are [available online](../samples/).
<ide>
<ide> To run the samples locally you first have to install all the necessary packages using the `npm ci` command, after this you can run `npm run docs:dev` to build the documentation. As soon as the build is done, you can go to [http://localhost:8080/samples/](http://localhost:8080/samples/) to see the samples. | 1 |
Text | Text | add the translation to the topic | 0957b18c004970024862b47dcd7a5904a4a13212 | <ide><path>docs/russian/how-to-work-on-guide-articles.md
<ide> </tr>
<ide> </table>
<ide>
<del># Contribution Guidelines
<add># Правила для внесения своего вклада в проекты
<ide>
<del>Hello 👋 !
<add>Привет 👋 !
<ide>
<del>These instructions have not been translated yet. Please check this issue for details: [`#18312`](https://github.com/freeCodeCamp/freeCodeCamp/issues/18312)
<ide>\ No newline at end of file
<add>Эти инструкции еще не были переведены. Чтобы узнать больше, пройдите по:[`#18312`](https://github.com/freeCodeCamp/freeCodeCamp/issues/18312) | 1 |
Javascript | Javascript | fix typo that breaks ff4 | 41f46ca3464706c5079c7934162d25b909220abe | <ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> var w = image.dict.get("Width");
<ide> var h = image.dict.get("Height");
<ide> var tmpCanvas = document.createElement("canvas");
<del> tmpCanvas.height = w;
<del> tmpCanvas.width = h;
<add> tmpCanvas.width = w;
<add> tmpCanvas.height = h;
<ide> var tmpCtx = tmpCanvas.getContext("2d");
<ide> var imgData = tmpCtx.getImageData(0, 0, w, h);
<ide> var pixels = imgData.data; | 1 |
Javascript | Javascript | remove redundant parent check | b43a3685b60b307d61f41f0c94412380ed46ab22 | <ide><path>src/attributes/prop.js
<ide> if ( !support.optSelected ) {
<ide> if ( parent ) {
<ide> parent.selectedIndex;
<ide>
<del> if ( parent && parent.parentNode ) {
<add> if ( parent.parentNode ) {
<ide> parent.parentNode.selectedIndex;
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix premature connection termination | 9777890f5d9ce95f15c64d29f1c0a55c12d24c3e | <ide><path>lib/tls.js
<ide> function pipe(pair, socket) {
<ide> // Encrypted should be unpiped from socket to prevent possible
<ide> // write after destroy.
<ide> pair.encrypted.unpipe(socket);
<del> socket.destroy();
<add> socket.destroySoon();
<ide> });
<ide> });
<ide> | 1 |
Text | Text | fix typo in mdx guide | 98227b273fbe7da12790571f70f2a334cb0c1c30 | <ide><path>docs/advanced-features/using-mdx.md
<ide> author: 'Rich Haines'
<ide>
<ide> ### Layouts
<ide>
<del>To add a layout to your MDX page, create a new component and import it into the MDX page. Then you can wrap the MDx page with your layout component:
<add>To add a layout to your MDX page, create a new component and import it into the MDX page. Then you can wrap the MDX page with your layout component:
<ide>
<ide> ```md
<ide> import { MyComponent, MyLayoutComponent } from 'my-components' | 1 |
PHP | PHP | replace schemacleaner with connectionhelper | 0d650f32d7926650f079e6611138905980e519e1 | <ide><path>src/TestSuite/ConnectionHelper.php
<ide> namespace Cake\TestSuite;
<ide>
<ide> use Cake\Database\Connection;
<add>use Cake\Database\Driver\Postgres;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Closure;
<ide>
<ide> /**
<ide> * Helper for managing test connections
<ide> public function enableQueryLogging(array $connections = []): void
<ide> }
<ide> }
<ide> }
<add>
<add> /**
<add> * Drops all tables.
<add> *
<add> * @param string $connectionName Connection name
<add> * @param array|null $tables List of tables names or null for all.
<add> * @return void
<add> */
<add> public function dropTables(string $connectionName, ?array $tables = null): void
<add> {
<add> /** @var \Cake\Database\Connection $connection */
<add> $connection = ConnectionManager::get($connectionName);
<add> $collection = $connection->getSchemaCollection();
<add>
<add> $allTables = $collection->listTables();
<add> $tables = $tables ? array_intersect($tables, $allTables) : $allTables;
<add> $schemas = array_map(function ($table) use ($collection) {
<add> return $collection->describe($table);
<add> }, $tables);
<add>
<add> $dialect = $connection->getDriver()->schemaDialect();
<add> /** @var \Cake\Database\Schema\TableSchema $schema */
<add> foreach ($schemas as $schema) {
<add> foreach ($dialect->dropConstraintSql($schema) as $statement) {
<add> $connection->execute($statement)->closeCursor();
<add> }
<add> }
<add> /** @var \Cake\Database\Schema\TableSchema $schema */
<add> foreach ($schemas as $schema) {
<add> foreach ($dialect->dropTableSql($schema) as $statement) {
<add> $connection->execute($statement)->closeCursor();
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Truncates all tables.
<add> *
<add> * @param string $connectionName Connection name
<add> * @param array|null $tables List of tables names or null for all.
<add> * @return void
<add> */
<add> public function truncateTables(string $connectionName, ?array $tables = null): void
<add> {
<add> /** @var \Cake\Database\Connection $connection */
<add> $connection = ConnectionManager::get($connectionName);
<add> $collection = $connection->getSchemaCollection();
<add>
<add> $allTables = $collection->listTables();
<add> $tables = $tables ? array_intersect($tables, $allTables) : $allTables;
<add> $schemas = array_map(function ($table) use ($collection) {
<add> return $collection->describe($table);
<add> }, $tables);
<add>
<add> $this->runWithoutConstraints($connection, function (Connection $connection) use ($schemas) {
<add> $dialect = $connection->getDriver()->schemaDialect();
<add> /** @var \Cake\Database\Schema\TableSchema $schema */
<add> foreach ($schemas as $schema) {
<add> foreach ($dialect->truncateTableSql($schema) as $statement) {
<add> $connection->execute($statement)->closeCursor();
<add> }
<add> }
<add> });
<add> }
<add>
<add> /**
<add> * Runs callback with constraints disabled correctly per-database
<add> *
<add> * @param \Cake\Database\Connection $connection Database connection
<add> * @param \Closure $callback callback
<add> * @return void
<add> */
<add> protected function runWithoutConstraints(Connection $connection, Closure $callback): void
<add> {
<add> if ($connection->getDriver() instanceof Postgres) {
<add> $connection->transactional(function (Connection $connection) use ($callback) {
<add> $connection->disableConstraints(function (Connection $connection) use ($callback) {
<add> $callback($connection);
<add> });
<add> });
<add> } else {
<add> $connection->disableConstraints(function (Connection $connection) use ($callback) {
<add> $callback($connection);
<add> });
<add> }
<add> }
<ide> }
<ide><path>src/TestSuite/Fixture/SchemaCleaner.php
<del><?php
<del>declare(strict_types=1);
<del>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @since 4.3.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\TestSuite\Fixture;
<del>
<del>use Cake\Console\ConsoleIo;
<del>use Cake\Database\Schema\BaseSchema;
<del>use Cake\Database\Schema\CollectionInterface;
<del>use Cake\Database\Schema\SqlGeneratorInterface;
<del>use Cake\Datasource\ConnectionInterface;
<del>use Cake\Datasource\ConnectionManager;
<del>
<del>/**
<del> * This class will help dropping and truncating all tables of a given connection
<del> *
<del> * @internal
<del> */
<del>class SchemaCleaner
<del>{
<del> /**
<del> * @var \Cake\Console\ConsoleIo|null
<del> */
<del> protected $io;
<del>
<del> /**
<del> * SchemaCleaner constructor.
<del> *
<del> * @param \Cake\Console\ConsoleIo|null $io Outputs if provided.
<del> */
<del> public function __construct(?ConsoleIo $io = null)
<del> {
<del> $this->io = $io;
<del> }
<del>
<del> /**
<del> * Drop all tables of the provided connection.
<del> *
<del> * @param string $connectionName Name of the connection.
<del> * @param array|null $tables Tables to truncate (all if not set).
<del> * @return void
<del> * @throws \Exception if the dropping failed.
<del> */
<del> public function dropTables(string $connectionName, $tables = null): void
<del> {
<del> $this->handle($connectionName, 'dropConstraintSql', 'dropping constraints', $tables);
<del> $this->handle($connectionName, 'dropTableSql', 'dropping', $tables);
<del> }
<del>
<del> /**
<del> * Truncate all tables of the provided connection.
<del> *
<del> * @param string $connectionName Name of the connection.
<del> * @param array|null $tables Tables to truncate (all if not set).
<del> * @return void
<del> * @throws \Exception if the truncation failed.
<del> */
<del> public function truncateTables(string $connectionName, $tables = null): void
<del> {
<del> $this->handle($connectionName, 'truncateTableSql', 'truncating', $tables);
<del> }
<del>
<del> /**
<del> * @param string $connectionName Name of the connection.
<del> * @param string $dialectMethod Method applied to the SQL dialect.
<del> * @param string $action Action displayed in the info message
<del> * @param array<string>|null $tables Tables to truncate (all if null)
<del> * @return void
<del> * @throws \Exception
<del> */
<del> protected function handle(string $connectionName, string $dialectMethod, string $action, $tables): void
<del> {
<del> $schema = $this->getSchema($connectionName);
<del> $dialect = $this->getDialect($connectionName);
<del> $allTables = $schema->listTables();
<del> if (is_null($tables)) {
<del> $tables = $allTables;
<del> } else {
<del> $tables = array_intersect($allTables, $tables);
<del> }
<del>
<del> $this->displayInfoMessage($connectionName, $tables, $action);
<del>
<del> if (empty($tables)) {
<del> return;
<del> }
<del>
<del> $stmts = [];
<del> foreach ($tables as $table) {
<del> $tableSchema = $schema->describe($table);
<del> if ($tableSchema instanceof SqlGeneratorInterface) {
<del> $stmts = array_merge($stmts, $dialect->{$dialectMethod}($tableSchema));
<del> }
<del> }
<del>
<del> $this->executeStatements(ConnectionManager::get($connectionName), $stmts);
<del> }
<del>
<del> /**
<del> * Display message in info.
<del> *
<del> * @param string $connectionName Name of the connection.
<del> * @param array $tables Table handled.
<del> * @param string $action Action performed.
<del> * @return void
<del> */
<del> protected function displayInfoMessage(string $connectionName, array $tables, string $action): void
<del> {
<del> $msg = [ucwords($action)];
<del> $msg[] = count($tables) . ' tables';
<del> $msg[] = 'for connection ' . $connectionName;
<del> $this->info(implode(' ', $msg));
<del> }
<del>
<del> /**
<del> * @param \Cake\Datasource\ConnectionInterface $connection Connection.
<del> * @param array $commands Sql commands to run
<del> * @return void
<del> * @throws \Exception
<del> */
<del> protected function executeStatements(ConnectionInterface $connection, array $commands): void
<del> {
<del> $connection->disableConstraints(function ($connection) use ($commands) {
<del> $connection->transactional(function (ConnectionInterface $connection) use ($commands) {
<del> foreach ($commands as $sql) {
<del> $connection->execute($sql);
<del> }
<del> });
<del> });
<del> }
<del>
<del> /**
<del> * @param string $msg Message to display.
<del> * @return void
<del> */
<del> protected function info(string $msg): void
<del> {
<del> if ($this->io instanceof ConsoleIo) {
<del> $this->io->info($msg);
<del> }
<del> }
<del>
<del> /**
<del> * @param string $connectionName name of the connection.
<del> * @return \Cake\Database\Schema\CollectionInterface
<del> */
<del> protected function getSchema(string $connectionName): CollectionInterface
<del> {
<del> return ConnectionManager::get($connectionName)->getSchemaCollection();
<del> }
<del>
<del> /**
<del> * @param string $connectionName Name of the connection.
<del> * @return \Cake\Database\Schema\BaseSchema
<del> */
<del> protected function getDialect(string $connectionName): BaseSchema
<del> {
<del> return ConnectionManager::get($connectionName)->getDriver()->schemaDialect();
<del> }
<del>}
<ide><path>src/TestSuite/Fixture/SchemaLoader.php
<ide> */
<ide> namespace Cake\TestSuite\Fixture;
<ide>
<del>use Cake\Console\ConsoleIo;
<del>use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Database\Schema\TableSchema;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\TestSuite\ConnectionHelper;
<ide> use InvalidArgumentException;
<ide>
<ide> /**
<ide> */
<ide> class SchemaLoader
<ide> {
<del> use InstanceConfigTrait;
<del>
<del> /**
<del> * @var \Cake\Console\ConsoleIo
<del> */
<del> protected $io;
<del>
<del> /**
<del> * @var \Cake\TestSuite\Fixture\SchemaCleaner
<del> */
<del> protected $schemaCleaner;
<del>
<ide> /**
<del> * @var array<string, mixed>
<add> * @var \Cake\TestSuite\ConnectionHelper
<ide> */
<del> protected $_defaultConfig = [
<del> 'outputLevel' => ConsoleIo::QUIET,
<del> ];
<add> protected $helper;
<ide>
<ide> /**
<ide> * Constructor.
<del> *
<del> * @param array<string, mixed> $config Config settings
<ide> */
<del> public function __construct(array $config = [])
<add> public function __construct()
<ide> {
<del> $this->setConfig($config);
<del>
<del> $this->io = new ConsoleIo();
<del> $this->io->level($this->getConfig('outputLevel'));
<del>
<del> $this->schemaCleaner = new SchemaCleaner($this->io);
<add> $this->helper = new ConnectionHelper();
<ide> }
<ide>
<ide> /**
<ide> * Load and apply schema sql file, or an array of files.
<ide> *
<del> * @param array<string>|string $files Schema files to load
<add> * @param array<string>|string $paths Schema files to load
<ide> * @param string $connectionName Connection name
<ide> * @param bool $dropTables Drop all tables prior to loading schema files
<ide> * @param bool $truncateTables Truncate all tables after loading schema files
<ide> * @return void
<ide> */
<ide> public function loadSqlFiles(
<del> $files,
<add> $paths,
<ide> string $connectionName,
<ide> bool $dropTables = true,
<ide> bool $truncateTables = true
<ide> ): void {
<del> $files = (array)$files;
<add> $files = (array)$paths;
<ide>
<ide> // Don't create schema if we are in a phpunit separate process test method.
<ide> if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
<ide> return;
<ide> }
<ide>
<ide> if ($dropTables) {
<del> $this->schemaCleaner->dropTables($connectionName);
<add> $this->helper->dropTables($connectionName);
<ide> }
<ide>
<ide> /** @var \Cake\Database\Connection $connection */
<ide> public function loadSqlFiles(
<ide> }
<ide>
<ide> if ($truncateTables) {
<del> $this->schemaCleaner->truncateTables($connectionName);
<add> $this->helper->truncateTables($connectionName);
<ide> }
<ide> }
<ide>
<ide> public function loadInternalFile(string $file, string $connectionName): void
<ide> return;
<ide> }
<ide>
<del> $this->schemaCleaner->dropTables($connectionName);
<add> $this->helper->dropTables($connectionName);
<ide>
<ide> $tables = include $file;
<ide>
<ide><path>tests/TestCase/TestSuite/Fixture/SchemaCleanerTest.php
<del><?php
<del>declare(strict_types=1);
<del>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @since 4.3.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\TestSuite\Fixture;
<del>
<del>use Cake\Database\Schema\TableSchema;
<del>use Cake\Datasource\ConnectionManager;
<del>use Cake\TestSuite\Fixture\SchemaCleaner;
<del>use Cake\TestSuite\TestCase;
<del>use Throwable;
<del>
<del>class SchemaCleanerTest extends TestCase
<del>{
<del> public function testForeignKeyConstruction(): void
<del> {
<del> $connection = ConnectionManager::get('test');
<del>
<del> [$table] = $this->createSchemas();
<del>
<del> $this->assertTestTableExistsWithCount($table, 1);
<del>
<del> $exceptionThrown = false;
<del> try {
<del> $connection->delete($table);
<del> } catch (Throwable $e) {
<del> $exceptionThrown = true;
<del> } finally {
<del> $this->assertTrue($exceptionThrown);
<del> }
<del>
<del> // Cleanup
<del> (new SchemaCleaner())->dropTables('test', ['test_table','test_table2']);
<del> }
<del>
<del> public function testDropSchema(): void
<del> {
<del> $connection = ConnectionManager::get('test');
<del> /** @var SchemaDialect $dialect */
<del> $dialect = $connection->getDriver()->schemaDialect();
<del> [$sql, $params] = $dialect->listTablesSql($connection->config());
<del> $initialNumberOfTables = $connection->execute($sql, $params)->count();
<del>
<del> [$table1, $table2] = $this->createSchemas();
<del>
<del> // Assert that the schema was created
<del> $this->assertTestTableExistsWithCount($table1, 1);
<del> $this->assertTestTableExistsWithCount($table2, 1);
<del>
<del> // Drop the schema
<del> (new SchemaCleaner())->dropTables('test', [$table1, $table2]);
<del>
<del> // Assert that the tables created were dropped
<del> [$sql, $params] = $dialect->listTablesSql($connection->config());
<del> $tables = $connection->execute($sql, $params)->count();
<del> $this->assertSame($initialNumberOfTables, $tables, 'The test tables should be dropped.');
<del> }
<del>
<del> public function testTruncateSchema(): void
<del> {
<del> [$table1, $table2] = $this->createSchemas();
<del>
<del> $this->assertTestTableExistsWithCount($table1, 1);
<del> $this->assertTestTableExistsWithCount($table2, 1);
<del>
<del> (new SchemaCleaner())->truncateTables('test');
<del>
<del> $this->assertTestTableExistsWithCount($table1, 0);
<del> $this->assertTestTableExistsWithCount($table2, 0);
<del> }
<del>
<del> private function assertTestTableExistsWithCount(string $table, int $count): void
<del> {
<del> $this->assertSame(
<del> $count,
<del> ConnectionManager::get('test')->newQuery()->select('id')->from($table)->execute()->count()
<del> );
<del> }
<del>
<del> private function createSchemas(): array
<del> {
<del> $table1 = 'test_table_' . rand();
<del> $table2 = 'test_table_' . rand();
<del>
<del> $connection = ConnectionManager::get('test');
<del>
<del> $schema = new TableSchema($table1);
<del> $schema
<del> ->addColumn('id', 'integer')
<del> ->addColumn('name', 'string')
<del> ->addConstraint($table1 . '_primary', [
<del> 'type' => TableSchema::CONSTRAINT_PRIMARY,
<del> 'columns' => ['id'],
<del> ]);
<del>
<del> $queries = $schema->createSql($connection);
<del> foreach ($queries as $sql) {
<del> $connection->execute($sql);
<del> }
<del>
<del> $schema = new TableSchema($table2);
<del> $schema
<del> ->addColumn('id', 'integer')
<del> ->addColumn('name', 'string')
<del> ->addColumn('table1_id', 'integer')
<del> ->addConstraint($table2 . '_primary', [
<del> 'type' => TableSchema::CONSTRAINT_PRIMARY,
<del> 'columns' => ['id'],
<del> ])
<del> ->addConstraint($table2 . '_foreign_key', [
<del> 'columns' => ['table1_id'],
<del> 'type' => TableSchema::CONSTRAINT_FOREIGN,
<del> 'references' => [$table1, 'id', ],
<del> ]);
<del>
<del> $queries = $schema->createSql($connection);
<del>
<del> foreach ($queries as $sql) {
<del> $connection->execute($sql);
<del> }
<del>
<del> $connection->insert($table1, ['name' => 'foo']);
<del>
<del> $id = $connection->newQuery()->select('id')->from($table1)->limit(1)->execute()->fetch()[0];
<del> $connection->insert($table2, ['name' => 'foo', 'table1_id' => $id]);
<del>
<del> $connection->execute($connection->getDriver()->enableForeignKeySQL());
<del>
<del> return [$table1, $table2];
<del> }
<del>}
<ide><path>tests/TestCase/TestSuite/Fixture/SchemaLoaderTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\TestSuite\Fixture;
<ide>
<del>use Cake\Console\ConsoleIo;
<ide> use Cake\Database\Connection;
<ide> use Cake\Database\Driver\Sqlite;
<ide> use Cake\Database\Schema\TableSchema;
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\TestSuite\Fixture\SchemaCleaner;
<add>use Cake\TestSuite\ConnectionHelper;
<ide> use Cake\TestSuite\Fixture\SchemaLoader;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide> public function setUp(): void
<ide> $this->restore = $GLOBALS['__PHPUNIT_BOOTSTRAP'];
<ide> unset($GLOBALS['__PHPUNIT_BOOTSTRAP']);
<ide>
<del> $this->loader = new SchemaLoader(['outputLevel' => ConsoleIo::QUIET]);
<add> $this->loader = new SchemaLoader();
<ide> }
<ide>
<ide> public function tearDown(): void
<ide> {
<ide> parent::tearDown();
<ide> $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $this->restore;
<ide>
<del> (new SchemaCleaner())->dropTables('test', ['schema_loader_test_one', 'schema_loader_test_two']);
<add> (new ConnectionHelper())->dropTables('test', ['schema_loader_test_one', 'schema_loader_test_two']);
<ide> ConnectionManager::drop('test_schema_loader');
<ide>
<ide> if (file_exists($this->truncateDbFile)) { | 5 |
Javascript | Javascript | remove unused context param from `countchildren` | 1047980dca0830cd55e1622f3fbefc38aeaadb91 | <ide><path>packages/react/src/ReactChildren.js
<ide> function mapChildren(children, func, context) {
<ide> * @param {?*} children Children tree container.
<ide> * @return {number} The number of children.
<ide> */
<del>function countChildren(children, context) {
<add>function countChildren(children) {
<ide> return traverseAllChildren(children, emptyFunction.thatReturnsNull, null);
<ide> }
<ide> | 1 |
Go | Go | add tests for pkg/pools | 07a75c48fd9c081219fdef4a4d46554237467fad | <ide><path>pkg/pools/pools_test.go
<add>package pools
<add>
<add>import (
<add> "bufio"
<add> "bytes"
<add> "io"
<add> "strings"
<add> "testing"
<add>)
<add>
<add>func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) {
<add> reader := BufioReader32KPool.Get(nil)
<add> if reader == nil {
<add> t.Fatalf("BufioReaderPool should have create a bufio.Reader but did not.")
<add> }
<add>}
<add>
<add>func TestBufioReaderPoolPutAndGet(t *testing.T) {
<add> sr := bufio.NewReader(strings.NewReader("foobar"))
<add> reader := BufioReader32KPool.Get(sr)
<add> if reader == nil {
<add> t.Fatalf("BufioReaderPool should not return a nil reader.")
<add> }
<add> // verify the first 3 byte
<add> buf1 := make([]byte, 3)
<add> _, err := reader.Read(buf1)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if actual := string(buf1); actual != "foo" {
<add> t.Fatalf("The first letter should have been 'foo' but was %v", actual)
<add> }
<add> BufioReader32KPool.Put(reader)
<add> // Try to read the next 3 bytes
<add> _, err = sr.Read(make([]byte, 3))
<add> if err == nil || err != io.EOF {
<add> t.Fatalf("The buffer should have been empty, issue an EOF error.")
<add> }
<add>}
<add>
<add>type simpleReaderCloser struct {
<add> io.Reader
<add> closed bool
<add>}
<add>
<add>func (r *simpleReaderCloser) Close() error {
<add> r.closed = true
<add> return nil
<add>}
<add>
<add>func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) {
<add> br := bufio.NewReader(strings.NewReader(""))
<add> sr := &simpleReaderCloser{
<add> Reader: strings.NewReader("foobar"),
<add> closed: false,
<add> }
<add> reader := BufioReader32KPool.NewReadCloserWrapper(br, sr)
<add> if reader == nil {
<add> t.Fatalf("NewReadCloserWrapper should not return a nil reader.")
<add> }
<add> // Verify the content of reader
<add> buf := make([]byte, 3)
<add> _, err := reader.Read(buf)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if actual := string(buf); actual != "foo" {
<add> t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual)
<add> }
<add> reader.Close()
<add> // Read 3 more bytes "bar"
<add> _, err = reader.Read(buf)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if actual := string(buf); actual != "bar" {
<add> t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual)
<add> }
<add> if !sr.closed {
<add> t.Fatalf("The ReaderCloser should have been closed, it is not.")
<add> }
<add>}
<add>
<add>func TestBufioWriterPoolGetWithNoReaderShouldCreateOne(t *testing.T) {
<add> writer := BufioWriter32KPool.Get(nil)
<add> if writer == nil {
<add> t.Fatalf("BufioWriterPool should have create a bufio.Writer but did not.")
<add> }
<add>}
<add>
<add>func TestBufioWriterPoolPutAndGet(t *testing.T) {
<add> buf := new(bytes.Buffer)
<add> bw := bufio.NewWriter(buf)
<add> writer := BufioWriter32KPool.Get(bw)
<add> if writer == nil {
<add> t.Fatalf("BufioReaderPool should not return a nil writer.")
<add> }
<add> written, err := writer.Write([]byte("foobar"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if written != 6 {
<add> t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written)
<add> }
<add> // Make sure we Flush all the way ?
<add> writer.Flush()
<add> bw.Flush()
<add> if len(buf.Bytes()) != 6 {
<add> t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes()))
<add> }
<add> // Reset the buffer
<add> buf.Reset()
<add> BufioWriter32KPool.Put(writer)
<add> // Try to write something
<add> written, err = writer.Write([]byte("barfoo"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> // If we now try to flush it, it should panic (the writer is nil)
<add> // recover it
<add> defer func() {
<add> if r := recover(); r == nil {
<add> t.Fatal("Trying to flush the writter should have 'paniced', did not.")
<add> }
<add> }()
<add> writer.Flush()
<add>}
<add>
<add>type simpleWriterCloser struct {
<add> io.Writer
<add> closed bool
<add>}
<add>
<add>func (r *simpleWriterCloser) Close() error {
<add> r.closed = true
<add> return nil
<add>}
<add>
<add>func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) {
<add> buf := new(bytes.Buffer)
<add> bw := bufio.NewWriter(buf)
<add> sw := &simpleWriterCloser{
<add> Writer: new(bytes.Buffer),
<add> closed: false,
<add> }
<add> bw.Flush()
<add> writer := BufioWriter32KPool.NewWriteCloserWrapper(bw, sw)
<add> if writer == nil {
<add> t.Fatalf("BufioReaderPool should not return a nil writer.")
<add> }
<add> written, err := writer.Write([]byte("foobar"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if written != 6 {
<add> t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written)
<add> }
<add> writer.Close()
<add> if !sw.closed {
<add> t.Fatalf("The ReaderCloser should have been closed, it is not.")
<add> }
<add>} | 1 |
Python | Python | add missing reference to block | edbd745e7122454a69aa423fd44782e4f0c90ad1 | <ide><path>numpy/core/_add_newdocs.py
<ide> def luf(lamdaexpr, *args, **kwargs):
<ide> hstack : Stack arrays in sequence horizontally (column wise)
<ide> vstack : Stack arrays in sequence vertically (row wise)
<ide> dstack : Stack arrays in sequence depth wise (along third dimension)
<add> block : Assemble arrays from blocks.
<ide>
<ide> Notes
<ide> ----- | 1 |
Python | Python | fix backprop of padding variable | 6771780d3f78ab3463fa7255516334059ed2721d | <ide><path>spacy/_ml.py
<ide> def _add_padding(self, Yf):
<ide>
<ide> def _backprop_padding(self, dY, ids):
<ide> # (1, nF, nO, nP) += (nN, nF, nO, nP) where IDs (nN, nF) < 0
<del> d_pad = dY * (ids.reshape((ids.shape[0], self.nF, 1, 1)) < 0.)
<add> mask = ids < 0.
<add> mask = mask.sum(axis=1)
<add> d_pad = dY * mask.reshape((ids.shape[0], 1, 1))
<ide> self.d_pad += d_pad.sum(axis=0)
<ide> return dY, ids
<ide> | 1 |
Ruby | Ruby | remove unneeded base file | 35867c0beed7077139fe64eeb729fada448ed1e7 | <ide><path>railties/test/application/configuration/base_test.rb
<del>require 'isolation/abstract_unit'
<del>require 'rack/test'
<del>require 'env_helpers'
<del>
<del>module ApplicationTests
<del> module ConfigurationTests
<del> class BaseTest < ActiveSupport::TestCase
<del> def setup
<del> build_app
<del> boot_rails
<del> FileUtils.rm_rf("#{app_path}/config/environments")
<del> end
<del>
<del> def teardown
<del> teardown_app
<del> FileUtils.rm_rf(new_app) if File.directory?(new_app)
<del> end
<del>
<del> private
<del> def new_app
<del> File.expand_path("#{app_path}/../new_app")
<del> end
<del>
<del> def copy_app
<del> FileUtils.cp_r(app_path, new_app)
<del> end
<del>
<del> def app
<del> @app ||= Rails.application
<del> end
<del>
<del> def require_environment
<del> require "#{app_path}/config/environment"
<del> end
<del> end
<del> end
<del>end
<ide>\ No newline at end of file
<ide><path>railties/test/application/configuration/custom_test.rb
<del>require 'application/configuration/base_test'
<del>
<del>class ApplicationTests::ConfigurationTests::CustomTest < ApplicationTests::ConfigurationTests::BaseTest
<del> test 'access custom configuration point' do
<del> add_to_config <<-RUBY
<del> config.x.payment_processing.schedule = :daily
<del> config.x.payment_processing.retries = 3
<del> config.x.super_debugger = true
<del> config.x.hyper_debugger = false
<del> config.x.nil_debugger = nil
<del> RUBY
<del> require_environment
<del>
<del> x = Rails.configuration.x
<del> assert_equal :daily, x.payment_processing.schedule
<del> assert_equal 3, x.payment_processing.retries
<del> assert_equal true, x.super_debugger
<del> assert_equal false, x.hyper_debugger
<del> assert_equal nil, x.nil_debugger
<del> assert_nil x.i_do_not_exist.zomg
<add>require 'isolation/abstract_unit'
<add>require 'env_helpers'
<add>
<add>module ApplicationTests
<add> module ConfigurationTests
<add> class CustomTest < ActiveSupport::TestCase
<add> def setup
<add> build_app
<add> boot_rails
<add> FileUtils.rm_rf("#{app_path}/config/environments")
<add> end
<add>
<add> def teardown
<add> teardown_app
<add> FileUtils.rm_rf(new_app) if File.directory?(new_app)
<add> end
<add>
<add> test 'access custom configuration point' do
<add> add_to_config <<-RUBY
<add> config.x.payment_processing.schedule = :daily
<add> config.x.payment_processing.retries = 3
<add> config.x.super_debugger = true
<add> config.x.hyper_debugger = false
<add> config.x.nil_debugger = nil
<add> RUBY
<add> require_environment
<add>
<add> x = Rails.configuration.x
<add> assert_equal :daily, x.payment_processing.schedule
<add> assert_equal 3, x.payment_processing.retries
<add> assert_equal true, x.super_debugger
<add> assert_equal false, x.hyper_debugger
<add> assert_equal nil, x.nil_debugger
<add> assert_nil x.i_do_not_exist.zomg
<add> end
<add>
<add> private
<add> def new_app
<add> File.expand_path("#{app_path}/../new_app")
<add> end
<add>
<add> def copy_app
<add> FileUtils.cp_r(app_path, new_app)
<add> end
<add>
<add> def app
<add> @app ||= Rails.application
<add> end
<add>
<add> def require_environment
<add> require "#{app_path}/config/environment"
<add> end
<add> end
<ide> end
<ide> end | 2 |
Mixed | Ruby | add `expires_at` option to `signed_id` | 364939c2b17b219fc8c158da63a8517e57f892ab | <ide><path>activerecord/CHANGELOG.md
<add>* Add `expires_in` option to `signed_id`.
<add>
<add> *Shouichi Kamiya*
<add>
<ide> * Allow applications to set retry deadline for query retries.
<ide>
<ide> Building on the work done in #44576 and #44591, we extend the logic that automatically
<ide><path>activerecord/lib/active_record/signed_id.rb
<ide> def combine_signed_id_purposes(purpose)
<ide> #
<ide> # And you then change your +find_signed+ calls to require this new purpose. Any old signed ids that were not
<ide> # created with the purpose will no longer find the record.
<del> def signed_id(expires_in: nil, purpose: nil)
<del> self.class.signed_id_verifier.generate id, expires_in: expires_in, purpose: self.class.combine_signed_id_purposes(purpose)
<add> def signed_id(expires_in: nil, expires_at: nil, purpose: nil)
<add> self.class.signed_id_verifier.generate id, expires_in: expires_in, expires_at: expires_at, purpose: self.class.combine_signed_id_purposes(purpose)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/signed_id_test.rb
<ide> class SignedIdTest < ActiveRecord::TestCase
<ide> assert_nil Account.find_signed("this won't find anything")
<ide> end
<ide>
<del> test "find signed record within expiration date" do
<add> test "find signed record within expiration duration" do
<ide> assert_equal @account, Account.find_signed(@account.signed_id(expires_in: 1.minute))
<ide> end
<ide>
<del> test "fail to find signed record within expiration date" do
<add> test "fail to find signed record within expiration duration" do
<ide> signed_id = @account.signed_id(expires_in: 1.minute)
<ide> travel 2.minutes
<ide> assert_nil Account.find_signed(signed_id)
<ide> class SignedIdTest < ActiveRecord::TestCase
<ide> assert_nil Account.find_signed signed_id
<ide> end
<ide>
<add> test "find signed record within expiration time" do
<add> assert_equal @account, Account.find_signed(@account.signed_id(expires_at: 1.minute.from_now))
<add> end
<add>
<add> test "fail to find signed record within expiration time" do
<add> signed_id = @account.signed_id(expires_at: 1.minute.from_now)
<add> travel 2.minutes
<add> assert_nil Account.find_signed(signed_id)
<add> end
<add>
<ide> test "find signed record with purpose" do
<ide> assert_equal @account, Account.find_signed(@account.signed_id(purpose: :v1), purpose: :v1)
<ide> end
<ide> class SignedIdTest < ActiveRecord::TestCase
<ide> end
<ide> end
<ide>
<del> test "find signed record with a bang within expiration date" do
<add> test "find signed record with a bang within expiration duration" do
<ide> assert_equal @account, Account.find_signed!(@account.signed_id(expires_in: 1.minute))
<ide> end
<ide>
<del> test "finding signed record outside expiration date raises on the bang" do
<add> test "finding signed record outside expiration duration raises on the bang" do
<ide> signed_id = @account.signed_id(expires_in: 1.minute)
<ide> travel 2.minutes
<ide> | 3 |
PHP | PHP | fix coding standards | 16a1a0ee7939b929724252dbaa91b1ded4f740b8 | <ide><path>lib/Cake/Model/ModelValidator.php
<ide> public function getMethods() {
<ide> public function getField($name = null) {
<ide> if ($name !== null && !empty($this->_fields[$name])) {
<ide> return $this->_fields[$name];
<del> } elseif ($name !==null) {
<add> } elseif ($name !== null) {
<ide> return null;
<ide> }
<ide> return $this->_fields;
<ide><path>lib/Cake/Model/Validator/CakeValidationRule.php
<ide> public function skip() {
<ide> * @return boolean
<ide> */
<ide> public function isLast() {
<del> return (bool) $this->last;
<add> return (bool)$this->last;
<ide> }
<ide>
<ide> /**
<ide> public function process($field, &$data, &$methods) {
<ide> if (isset($methods[$rule])) {
<ide> $this->_ruleParams[] = array_merge($validator, $this->_passedOptions);
<ide> $this->_ruleParams[0] = array($field => $this->_ruleParams[0]);
<del> $this->_valid = call_user_func_array($methods[$rule], $this->_ruleParams);
<add> $this->_valid = call_user_func_array($methods[$rule], $this->_ruleParams);
<ide> } elseif (class_exists('Validation') && method_exists('Validation', $this->_rule)) {
<ide> $this->_valid = call_user_func_array(array('Validation', $this->_rule), $this->_ruleParams);
<ide> } elseif (is_string($validator['rule'])) {
<ide><path>lib/Cake/Test/Case/Model/ModelTest.php
<ide> class ModelTest extends PHPUnit_Framework_TestSuite {
<ide> public static function suite() {
<ide> $suite = new PHPUnit_Framework_TestSuite('All Model related class tests');
<ide>
<del> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS .'CakeValidationSetTest.php');
<del> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS .'CakeValidationRuleTest.php');
<add> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS . 'CakeValidationSetTest.php');
<add> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'Validator' . DS . 'CakeValidationRuleTest.php');
<ide> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelReadTest.php');
<ide> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelWriteTest.php');
<ide> $suite->addTestFile(CORE_TEST_CASES . DS . 'Model' . DS . 'ModelDeleteTest.php');
<ide><path>lib/Cake/Test/Case/Model/ModelValidationTest.php
<ide> public function testSaveAllDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> true,
<del> true
<add> true,
<add> true
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true));
<ide> public function testSaveAllDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> false,
<del> true
<add> false,
<add> true
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true));
<ide> public function testSaveAllDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> true,
<del> true
<add> true,
<add> true
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true));
<ide> public function testSaveAllDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> true,
<del> false
<add> true,
<add> false
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true));
<ide> public function testSaveAllNotDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> true,
<del> true
<add> true,
<add> true
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false));
<ide> public function testSaveAllNotDeepValidateOnly() {
<ide> $expected = array(
<ide> 'Article' => true,
<ide> 'Comment' => array(
<del> true,
<del> true
<add> true,
<add> true
<ide> )
<ide> );
<ide> $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false));
<ide><path>lib/Cake/Test/Case/Model/Validator/CakeValidationRuleTest.php
<ide> */
<ide> class CakeValidationRuleTest extends CakeTestCase {
<ide>
<del>/**
<del> * setUp method
<del> *
<del> * @return void
<del> */
<del> public function setUp() {
<del> parent::setUp();
<del> }
<del>
<ide> /**
<ide> * Auxiliary method to test custom validators
<ide> * | 5 |
PHP | PHP | add declare() to collection classes | b66e44107a311c7cc9e3f65f56fde8999dae5258 | <ide><path>src/Collection/Collection.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/Collection/CollectionInterface.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/Collection/CollectionTrait.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/Collection/ExtractTrait.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/Collection/Iterator/BufferedIterator.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/Collection/Iterator/ExtractIterator.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/Collection/Iterator/FilterIterator.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/Collection/Iterator/InsertIterator.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/Collection/Iterator/MapReduce.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> public function getIterator()
<ide> * of mapping a single record from the original data.
<ide> *
<ide> * @param mixed $val The record itself to store in the bucket
<del> * @param string $bucket the name of the bucket where to put the record
<add> * @param mixed $bucket the name of the bucket where to put the record
<ide> * @return void
<ide> */
<del> public function emitIntermediate($val, $bucket)
<add> public function emitIntermediate($val, $bucket): void
<ide> {
<ide> $this->_intermediate[$bucket][] = $val;
<ide> }
<ide> public function emitIntermediate($val, $bucket)
<ide> * for this record.
<ide> *
<ide> * @param mixed $val The value to be appended to the final list of results
<del> * @param string|null $key and optional key to assign to the value
<add> * @param mixed $key and optional key to assign to the value
<ide> * @return void
<ide> */
<del> public function emit($val, $key = null)
<add> public function emit($val, $key = null): void
<ide> {
<ide> $this->_result[$key === null ? $this->_counter : $key] = $val;
<ide> $this->_counter++;
<ide><path>src/Collection/Iterator/NestIterator.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> public function getChildren()
<ide> *
<ide> * @return bool
<ide> */
<del> public function hasChildren()
<add> public function hasChildren(): bool
<ide> {
<ide> $property = $this->_propertyExtractor($this->_nestKey);
<ide> $children = $property($this->current());
<ide><path>src/Collection/Iterator/NoChildrenIterator.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class NoChildrenIterator extends Collection implements RecursiveIterator
<ide> *
<ide> * @return bool
<ide> */
<del> public function hasChildren()
<add> public function hasChildren(): bool
<ide> {
<ide> return false;
<ide> }
<ide><path>src/Collection/Iterator/ReplaceIterator.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/Collection/Iterator/SortIterator.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/Collection/Iterator/StoppableIterator.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/Collection/Iterator/TreeIterator.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/Collection/Iterator/TreePrinter.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/Collection/Iterator/UnfoldIterator.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/Collection/Iterator/ZipIterator.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/Collection/functions.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> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> use Cake\Collection\Collection;
<add>use Cake\Collection\CollectionInterface;
<ide>
<ide> if (!function_exists('collection')) {
<ide> /**
<ide> * @param \Traversable|array $items The items from which the collection will be built.
<ide> * @return \Cake\Collection\Collection
<ide> */
<del> function collection($items)
<add> function collection($items): CollectionInterface
<ide> {
<ide> return new Collection($items);
<ide> }
<ide><path>tests/TestCase/Collection/Iterator/TreeIteratorTest.php
<ide> public function testPrinterWithClosure()
<ide> $result = (new TreeIterator($items))
<ide> ->printer(function ($element, $key, $iterator) {
<ide> return ($iterator->getDepth() + 1 ) . '.' . $key . ' ' . $element['name'];
<del> }, null, null)
<add> }, null, '')
<ide> ->toArray();
<ide> $expected = [
<ide> '1.0 a', | 20 |
Text | Text | add changelog entry for [ci skip] | c91a531ff384f70f72e7e0e213424d3e42a48c27 | <ide><path>actionpack/CHANGELOG.md
<add>* Add alias `ActionDispatch::Http::UploadedFile#to_io` to
<add> `ActionDispatch::Http::UploadedFile#tempfile`.
<add>
<add> *Tim Linquist*
<add>
<ide> * Returns null type format when format is not know and controller is using `any`
<ide> format block.
<ide> | 1 |
Text | Text | update lite path + fix --config option | 7a75bfceac93f15238884240f85b7eddade04021 | <ide><path>research/object_detection/g3doc/running_on_mobile_tensorflowlite.md
<ide> parameters and can be run via the TensorFlow Lite interpreter on the Android
<ide> device. For a floating point model, run this from the tensorflow/ directory:
<ide>
<ide> ```shell
<del>bazel run --config=opt tensorflow/contrib/lite/toco:toco -- \
<add>bazel run -c opt tensorflow/lite/toco:toco -- \
<ide> --input_file=$OUTPUT_DIR/tflite_graph.pb \
<ide> --output_file=$OUTPUT_DIR/detect.tflite \
<ide> --input_shapes=1,300,300,3 \ | 1 |
Javascript | Javascript | improve randombytes() performance | 59a1981a226045bce30aeb2889b29c829c285a80 | <ide><path>benchmark/crypto/randomBytes.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>const { randomBytes } = require('crypto');
<add>
<add>const bench = common.createBenchmark(main, {
<add> size: [64, 1024, 8192, 512 * 1024],
<add> n: [1e3],
<add>});
<add>
<add>function main({ n, size }) {
<add> bench.start();
<add> for (let i = 0; i < n; ++i)
<add> randomBytes(size);
<add> bench.end(n);
<add>}
<ide><path>lib/internal/crypto/random.js
<ide> const {
<ide> } = primordials;
<ide>
<ide> const { AsyncWrap, Providers } = internalBinding('async_wrap');
<del>const { Buffer, kMaxLength } = require('buffer');
<add>const { kMaxLength } = require('buffer');
<ide> const { randomBytes: _randomBytes } = internalBinding('crypto');
<ide> const {
<ide> ERR_INVALID_ARG_TYPE,
<ide> const {
<ide> } = require('internal/errors').codes;
<ide> const { validateNumber } = require('internal/validators');
<ide> const { isArrayBufferView } = require('internal/util/types');
<add>const { FastBuffer } = require('internal/buffer');
<ide>
<ide> const kMaxUint32 = 2 ** 32 - 1;
<ide> const kMaxPossibleLength = MathMin(kMaxLength, kMaxUint32);
<ide> function randomBytes(size, cb) {
<ide> if (cb !== undefined && typeof cb !== 'function')
<ide> throw new ERR_INVALID_CALLBACK(cb);
<ide>
<del> const buf = Buffer.alloc(size);
<add> const buf = new FastBuffer(size);
<ide>
<ide> if (!cb) return handleError(_randomBytes(buf, 0, size), buf);
<ide>
<ide><path>test/benchmark/test-benchmark-crypto.js
<ide> runBenchmark('crypto',
<ide> 'len=1',
<ide> 'n=1',
<ide> 'out=buffer',
<add> 'size=1',
<ide> 'type=buf',
<ide> 'v=crypto',
<ide> 'writes=1', | 3 |
Ruby | Ruby | use location rather than location header | 4887e53bf9fd9c35acd05a4cc40a014406132ac2 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def erase_redirect_results #:nodoc:
<ide> response.redirected_to = nil
<ide> response.redirected_to_method_params = nil
<ide> response.headers['Status'] = DEFAULT_RENDER_STATUS_CODE
<del> response.headers.delete('location')
<add> response.headers.delete('Location')
<ide> end
<ide>
<ide> # Erase both render and redirect results
<ide><path>actionpack/lib/action_controller/integration.rb
<ide> def host!(name)
<ide> # performed on the location header.
<ide> def follow_redirect!
<ide> raise "not a redirect! #{@status} #{@status_message}" unless redirect?
<del> get(interpret_uri(headers["location"].first))
<add> get(interpret_uri(headers['Location'].first))
<ide> status
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/test_process.rb
<ide> def error?
<ide>
<ide> # returns the redirection location or nil
<ide> def redirect_url
<del> redirect? ? headers['location'] : nil
<add> redirect? ? headers['Location'] : nil
<ide> end
<ide>
<ide> # does the redirect location match this regexp pattern? | 3 |
Javascript | Javascript | remove redundant ascii | fafbb39ec702903943cd1565a15a3c2f4802bcd3 | <ide><path>test/cases/resolving/data-uri/index.js
<ide> it("should require js module from base64 data-uri", function() {
<ide> });
<ide>
<ide> it("should require js module from ascii data-uri", function() {
<del> const mod = require("data:text/javascript;charset=utf-8;ascii,module.exports={number:42,fn:()=>\"Hello world\"}");
<add> const mod = require("data:text/javascript;charset=utf-8,module.exports={number:42,fn:()=>\"Hello world\"}");
<ide> expect(mod.number).toBe(42);
<ide> expect(mod.fn()).toBe("Hello world");
<ide> }); | 1 |
Python | Python | remove k8s dependency from serialization | e1e0485bb15b168440f2af0ff69f3a7fc72330fe | <ide><path>airflow/serialization/serialized_objects.py
<ide> import cattr
<ide> import pendulum
<ide> from dateutil import relativedelta
<del>from kubernetes.client import models as k8s
<add>
<add>try:
<add> from kubernetes.client import models as k8s
<add>except ImportError:
<add> k8s = None
<add>
<ide> from pendulum.tz.timezone import Timezone
<ide>
<ide> from airflow.exceptions import AirflowException | 1 |
Ruby | Ruby | remove workaround to a ruby 2.0.0 bug | 02a48fb83c6aff2c9fc82e962286212ba26a91c5 | <ide><path>activesupport/lib/active_support/duration.rb
<ide> def sum(sign, time = ::Time.current) #:nodoc:
<ide>
<ide> private
<ide>
<del> # We define it as a workaround to Ruby 2.0.0-p353 bug.
<del> # For more information, check rails/rails#13055.
<del> # Remove it when we drop support for 2.0.0-p353.
<del> def ===(other) #:nodoc:
<del> value === other
<del> end
<del>
<ide> def method_missing(method, *args, &block) #:nodoc:
<ide> value.send(method, *args, &block)
<ide> end | 1 |
Javascript | Javascript | remove require('buffer') on 6 fs test files | d31fe536c0a576ead9655acb140970690c4fbc78 | <ide><path>test/parallel/test-fs-mkdtemp.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<del>const Buffer = require('buffer').Buffer;
<ide>
<ide> common.refreshTmpDir();
<ide>
<ide><path>test/parallel/test-fs-read-zero-length.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<del>const Buffer = require('buffer').Buffer;
<ide> const fs = require('fs');
<ide> const filepath = path.join(common.fixturesDir, 'x.txt');
<ide> const fd = fs.openSync(filepath, 'r');
<ide><path>test/parallel/test-fs-read.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<del>const Buffer = require('buffer').Buffer;
<ide> const fs = require('fs');
<ide> const filepath = path.join(common.fixturesDir, 'x.txt');
<ide> const fd = fs.openSync(filepath, 'r');
<ide><path>test/parallel/test-fs-whatwg-url.js
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide> const os = require('os');
<ide> const URL = require('url').URL;
<del>const Buffer = require('buffer').Buffer;
<ide>
<ide> function pathToFileURL(p) {
<ide> if (!path.isAbsolute(p))
<ide><path>test/parallel/test-fs-write-string-coerce.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<del>const Buffer = require('buffer').Buffer;
<ide> const fs = require('fs');
<ide>
<ide> common.refreshTmpDir();
<ide><path>test/parallel/test-fs-write.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<del>const Buffer = require('buffer').Buffer;
<ide> const fs = require('fs');
<ide> const fn = path.join(common.tmpDir, 'write.txt');
<ide> const fn2 = path.join(common.tmpDir, 'write2.txt'); | 6 |
PHP | PHP | change trait name | fab6b0a6410158eee1d9b8939464441eea5488aa | <ide><path>src/Illuminate/Foundation/Bus/DispatchesCommands.php
<ide>
<ide> use ArrayAccess;
<ide>
<add>/**
<add> * This trait is deprecated. Use the DispatchesJobs trait.
<add> */
<ide> trait DispatchesCommands {
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Bus/DispatchesJobs.php
<add><?php namespace Illuminate\Foundation\Bus;
<add>
<add>use ArrayAccess;
<add>
<add>trait DispatchesJobs {
<add>
<add> /**
<add> * Dispatch a job to its appropriate handler.
<add> *
<add> * @param mixed $job
<add> * @return mixed
<add> */
<add> protected function dispatch($job)
<add> {
<add> return app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($job);
<add> }
<add>
<add> /**
<add> * Marshal a job and dispatch it to its appropriate handler.
<add> *
<add> * @param mixed $job
<add> * @param array $array
<add> * @return mixed
<add> */
<add> protected function dispatchFromArray($job, array $array)
<add> {
<add> return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFromArray($job, $array);
<add> }
<add>
<add> /**
<add> * Marshal a job and dispatch it to its appropriate handler.
<add> *
<add> * @param mixed $job
<add> * @param \ArrayAccess $source
<add> * @param array $extras
<add> * @return mixed
<add> */
<add> protected function dispatchFrom($job, ArrayAccess $source, $extras = [])
<add> {
<add> return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFrom($job, $source, $extras);
<add> }
<add>
<add>} | 2 |
Text | Text | fix links in errors.md | 4d1baf82ae0e3458d0038e0ca02d215740cdb77b | <ide><path>doc/api/errors.md
<ide> Creation of a [`zlib`][] object failed due to incorrect configuration.
<ide> [`dgram.createSocket()`]: dgram.html#dgram_dgram_createsocket_options_callback
<ide> [`ERR_INVALID_ARG_TYPE`]: #ERR_INVALID_ARG_TYPE
<ide> [`EventEmitter`]: events.html#events_class_eventemitter
<del>[`fs.symlink()`]: fs.html#fs_symlink
<del>[`fs.symlinkSync()`]: fs.html#fs_symlinksync
<add>[`fs.symlink()`]: fs.html#fs_fs_symlink_target_path_type_callback
<add>[`fs.symlinkSync()`]: fs.html#fs_fs_symlinksync_target_path_type
<ide> [`hash.digest()`]: crypto.html#crypto_hash_digest_encoding
<ide> [`hash.update()`]: crypto.html#crypto_hash_update_data_inputencoding
<ide> [`readable._read()`]: stream.html#stream_readable_read_size_1 | 1 |
Python | Python | add a test enabling get_next_as_optional behavior. | 92bad0d216cc46140c52da8d75d4685eb364736a | <ide><path>official/resnet/keras/keras_imagenet_benchmark.py
<ide> def benchmark_xla_8_gpu_fp16_tweaked(self):
<ide> FLAGS.data_delay_prefetch = True
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_xla_8_gpu_fp16_tweaked_optional_next(self):
<add> """Test Keras model with manual config tuning, XLA, 8 GPUs, fp16 and
<add> enabling get_next_as_optional.
<add> """
<add> self._setup()
<add>
<add> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<add> FLAGS.enable_eager = True
<add> FLAGS.enable_xla = True
<add> FLAGS.distribution_strategy = 'default'
<add> FLAGS.model_dir = self._get_model_dir(
<add> 'benchmark_xla_8_gpu_fp16_tweaked_optional_next')
<add> FLAGS.batch_size = 256 * 8 # 8 GPUs
<add> FLAGS.use_tensor_lr = True
<add> # FLAGS.tf_gpu_thread_mode = 'gpu_private'
<add> FLAGS.data_delay_prefetch = True
<add> FLAGS.enable_get_next_as_optional = True
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_xla_8_gpu_fp16_slack(self):
<ide> """Test Keras model with tf.data's experimental_slack functionality, XLA,
<ide> 8 GPUs and fp16. | 1 |
Ruby | Ruby | remove the reflection delegate | a35325e32491d566fbb58001f8e68bed86d06955 | <ide><path>activerecord/lib/active_record/associations/association_scope.rb
<ide> module Associations
<ide> class AssociationScope #:nodoc:
<ide> attr_reader :association, :alias_tracker
<ide>
<del> delegate :reflection, :to => :association
<del>
<ide> def initialize(association)
<ide> @association = association
<ide> @alias_tracker = AliasTracker.new association.klass.connection
<ide> end
<ide>
<ide> def scope
<ide> klass = association.klass
<add> reflection = association.reflection
<ide> scope = klass.unscoped
<ide> scope.extending! Array(reflection.options[:extend])
<ide>
<ide> owner = association.owner
<ide> scope_chain = reflection.scope_chain
<ide> chain = reflection.chain
<del> add_constraints(scope, owner, scope_chain, chain, klass)
<add> add_constraints(scope, owner, scope_chain, chain, klass, reflection)
<ide> end
<ide>
<ide> def join_type
<ide> def join_type
<ide>
<ide> private
<ide>
<del> def construct_tables(chain, klass)
<add> def construct_tables(chain, klass, refl)
<ide> chain.map do |reflection|
<ide> alias_tracker.aliased_table_for(
<del> table_name_for(reflection, klass),
<del> table_alias_for(reflection, reflection != self.reflection)
<add> table_name_for(reflection, klass, refl),
<add> table_alias_for(reflection, refl, reflection != refl)
<ide> )
<ide> end
<ide> end
<ide>
<del> def table_alias_for(reflection, join = false)
<del> name = "#{reflection.plural_name}_#{alias_suffix}"
<add> def table_alias_for(reflection, refl, join = false)
<add> name = "#{reflection.plural_name}_#{alias_suffix(refl)}"
<ide> name << "_join" if join
<ide> name
<ide> end
<ide> def bind(scope, table_name, column_name, value)
<ide> bind_value scope, column, value
<ide> end
<ide>
<del> def add_constraints(scope, owner, scope_chain, chain, assoc_klass)
<del> tables = construct_tables(chain, assoc_klass)
<add> def add_constraints(scope, owner, scope_chain, chain, assoc_klass, refl)
<add> tables = construct_tables(chain, assoc_klass, refl)
<ide>
<ide> chain.each_with_index do |reflection, i|
<ide> table, foreign_table = tables.shift, tables.first
<ide> def add_constraints(scope, owner, scope_chain, chain, assoc_klass)
<ide> scope_chain[i].each do |scope_chain_item|
<ide> item = eval_scope(klass, scope_chain_item, owner)
<ide>
<del> if scope_chain_item == self.reflection.scope
<add> if scope_chain_item == refl.scope
<ide> scope.merge! item.except(:where, :includes, :bind)
<ide> end
<ide>
<ide> def add_constraints(scope, owner, scope_chain, chain, assoc_klass)
<ide> scope
<ide> end
<ide>
<del> def alias_suffix
<del> reflection.name
<add> def alias_suffix(refl)
<add> refl.name
<ide> end
<ide>
<del> def table_name_for(reflection, klass)
<del> if reflection == self.reflection
<add> def table_name_for(reflection, klass, refl)
<add> if reflection == refl
<ide> # If this is a polymorphic belongs_to, we want to get the klass from the
<ide> # association because it depends on the polymorphic_type attribute of
<ide> # the owner | 1 |
Javascript | Javascript | add type support for sethelpers | 487d74d74d5282a52f7b09f6869f47fe0a7cc786 | <ide><path>lib/util/SetHelpers.js
<ide> "use strict";
<ide>
<del>exports.intersect = sets => {
<add>/**
<add> * @description intersect creates Set containing the intersection of elements between all sets
<add> * @param {Set[]} sets an array of sets being checked for shared elements
<add> * @returns {Set} returns a new Set containing the intersecting items
<add> */
<add>function intersect(sets) {
<ide> if (sets.length === 0) return new Set();
<ide> if (sets.length === 1) return new Set(sets[0]);
<ide> let minSize = Infinity;
<ide> exports.intersect = sets => {
<ide> }
<ide> }
<ide> return current;
<del>};
<add>}
<ide>
<del>exports.isSubset = (bigSet, smallSet) => {
<add>/**
<add> * @description
<add> * @param {Set} bigSet a Set which contains the original elements to compare against
<add> * @param {Set} smallSet the set whos elements might be contained inside of bigSet
<add> * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet
<add> */
<add>function isSubset(bigSet, smallSet) {
<ide> if (bigSet.size < smallSet.size) return false;
<ide> for (const item of smallSet) {
<ide> if (!bigSet.has(item)) return false;
<ide> }
<ide> return true;
<del>};
<add>}
<add>
<add>exports.intersect = intersect;
<add>exports.isSubset = isSubset; | 1 |
Javascript | Javascript | use getstartpromise() in specs | 6e6c0a5ef9d333faf4e72fd28120c45171e0dbb1 | <ide><path>spec/filesystem-manager-spec.js
<ide> describe('FileSystemManager', function () {
<ide> await stopAllWatchers(manager)
<ide> })
<ide>
<del> function waitForEvent (fn) {
<del> return new Promise(resolve => {
<del> subs.add(fn(resolve))
<del> })
<del> }
<del>
<ide> function waitForChanges (watcher, ...fileNames) {
<ide> const waiting = new Set(fileNames)
<ide> const relevantEvents = []
<ide> describe('FileSystemManager', function () {
<ide> }
<ide>
<ide> describe('getWatcher()', function () {
<del> it('broadcasts onDidStart when the watcher begins listening', async function () {
<add> it('resolves getStartPromise() when the watcher begins listening', async function () {
<ide> const rootDir = await temp.mkdir('atom-fsmanager-')
<ide>
<ide> const watcher = manager.getWatcher(rootDir)
<del> await waitForEvent(cb => watcher.onDidStart(cb))
<add> watcher.onDidChange(() => {})
<add>
<add> await watcher.getStartPromise()
<ide> })
<ide>
<del> it('reuses an existing native watcher and broadcasts onDidStart immediately if attached to an existing watcher', async function () {
<add> it('does not start actually watching until an onDidChange subscriber is registered', async function () {
<add> const rootDir = await temp.mkdir('atom-fsmanager-')
<add> const watcher = manager.getWatcher(rootDir)
<add>
<add> let started = false
<add> const startPromise = watcher.getStartPromise().then(() => {
<add> started = true
<add> })
<add>
<add> expect(watcher.native).toBe(null)
<add> expect(watcher.normalizedPath).toBe(null)
<add> expect(started).toBe(false)
<add>
<add> await watcher.getNormalizedPathPromise()
<add>
<add> expect(watcher.native).toBe(null)
<add> expect(watcher.normalizedPath).not.toBe(null)
<add> expect(started).toBe(false)
<add>
<add> watcher.onDidChange(() => {})
<add> await startPromise
<add>
<add> expect(watcher.native).not.toBe(null)
<add> expect(started).toBe(true)
<add> })
<add>
<add> it('automatically stops and removes the watcher when all onDidChange subscribers dispose')
<add>
<add> it('reuses an existing native watcher and resolves getStartPromise immediately if attached to a running watcher', async function () {
<ide> const rootDir = await temp.mkdir('atom-fsmanager-')
<ide>
<ide> const watcher0 = manager.getWatcher(rootDir)
<del> await waitForEvent(cb => watcher0.onDidStart(cb))
<add> watcher0.onDidChange(() => {})
<add> await watcher0.getStartPromise()
<ide>
<ide> const watcher1 = manager.getWatcher(rootDir)
<del> await waitForEvent(cb => watcher1.onDidStart(cb))
<add> watcher1.onDidChange(() => {})
<add> await watcher1.getStartPromise()
<ide>
<ide> expect(watcher0.native).toBe(watcher1.native)
<ide> })
<ide> describe('FileSystemManager', function () {
<ide> ])
<ide>
<ide> const rootWatcher = manager.getWatcher(rootDir)
<del> await waitForEvent(cb => rootWatcher.onDidStart(cb))
<del>
<ide> const childWatcher = manager.getWatcher(subDir)
<del> await waitForEvent(cb => childWatcher.onDidStart(cb))
<ide>
<ide> expect(rootWatcher.native).toBe(childWatcher.native)
<ide>
<ide> const firstRootChange = waitForChanges(rootWatcher, subFile)
<ide> const firstChildChange = waitForChanges(childWatcher, subFile)
<ide>
<add> await Promise.all([
<add> rootWatcher.getStartPromise(),
<add> childWatcher.getStartPromise()
<add> ])
<add>
<ide> await fs.appendFile(subFile, 'changes\n', {encoding: 'utf8'})
<add>
<ide> const firstPayloads = await Promise.all([firstRootChange, firstChildChange])
<ide>
<ide> for (const events of firstPayloads) {
<ide> describe('FileSystemManager', function () {
<ide> const subFile0 = path.join(subDir0, 'subfile1.txt')
<ide> const subDir1 = path.join(parentDir, 'subdir1')
<ide> const subFile1 = path.join(subDir1, 'subfile1.txt')
<add>
<ide> await Promise.all([
<ide> fs.writeFile(rootFile, 'rootfile\n', {encoding: 'utf8'}),
<ide> fs.mkdir(subDir0).then(
<ide> describe('FileSystemManager', function () {
<ide>
<ide> // Begin the child watchers
<ide> const subWatcher0 = manager.getWatcher(subDir0)
<add> const subWatcherChanges0 = waitForChanges(subWatcher0, subFile0)
<add>
<ide> const subWatcher1 = manager.getWatcher(subDir1)
<add> const subWatcherChanges1 = waitForChanges(subWatcher1, subFile1)
<ide>
<ide> await Promise.all(
<del> [subWatcher0, subWatcher1].map(watcher => waitForEvent(cb => watcher.onDidStart(cb)))
<add> [subWatcher0, subWatcher1].map(watcher => {
<add> return watcher.getStartPromise()
<add> })
<ide> )
<ide> expect(subWatcher0.native).not.toBe(subWatcher1.native)
<ide>
<ide> // Create the parent watcher
<ide> const parentWatcher = manager.getWatcher(parentDir)
<del> await waitForEvent(cb => parentWatcher.onDidStart(cb))
<add> const parentWatcherChanges = waitForChanges(parentWatcher, rootFile, subFile0, subFile1)
<add>
<add> await parentWatcher.getStartPromise()
<ide>
<ide> expect(subWatcher0.native).toBe(parentWatcher.native)
<ide> expect(subWatcher1.native).toBe(parentWatcher.native)
<ide> describe('FileSystemManager', function () {
<ide> ])
<ide>
<ide> await Promise.all([
<del> waitForChanges(subWatcher0, subFile0),
<del> waitForChanges(subWatcher1, subFile1),
<del> waitForChanges(parentWatcher, rootFile, subFile0, subFile1)
<add> subWatcherChanges0,
<add> subWatcherChanges1,
<add> parentWatcherChanges
<ide> ])
<ide> })
<ide> | 1 |
Python | Python | fix serialization error in maya exporter | ddd0803d8ace4fb43e1950e7b60f26a7625b6631 | <add><path>utils/exporters/maya/plug-ins/threeJsFileTranslator.py
<del><path>utils/exporters/maya/plug-ins/threeJsFileTranlator.py
<ide> def _iterencode(self, o, markers=None):
<ide> if '.' in s and len(s[s.index('.'):]) > FLOAT_PRECISION - 1:
<ide> s = '%.{0}f'.format(FLOAT_PRECISION) % o
<ide> while '.' in s and s[-1] == '0':
<del> s = s[-2]
<add> s = s[:-1] # this actually removes the last "0" from the string
<add> if s[-1] == '.': # added this test to avoid leaving "0." instead of "0.0",
<add> s += '0' # which would throw an error while loading the file
<ide> return (s for s in [s])
<ide> return super(DecimalEncoder, self)._iterencode(o, markers)
<ide> | 1 |
Javascript | Javascript | fix another traverse test | f1300f18877f0140994190bb1b3a945fa4b2fd3d | <ide><path>test/unit/traversing.js
<ide> QUnit.test( "not(Array)", function( assert ) {
<ide> QUnit.test( "not(jQuery)", function( assert ) {
<ide> assert.expect( 1 );
<ide>
<del> assert.deepEqual( jQuery( "p" ).not( jQuery( "#ap, #sndp, .result" ) ).get(), q( "firstp", "en", "sap", "first" ), "not(jQuery)" );
<add> assert.deepEqual(
<add> jQuery( "#qunit-fixture p" ).not( jQuery( "#ap, #sndp, .result" ) ).get(),
<add> q( "firstp", "en", "sap", "first" ),
<add> "not(jQuery)"
<add> );
<ide> } );
<ide>
<ide> QUnit.test( "not(Selector) excludes non-element nodes (gh-2808)", function( assert ) { | 1 |
PHP | PHP | fix typo in memory driver | da67b1bc667d98d363e49aa6830731faa393cdab | <ide><path>laravel/cache/drivers/memory.php
<ide> public function forget($key)
<ide> */
<ide> public function flush()
<ide> {
<del> $this->stroage = array();
<add> $this->storage = array();
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Text | Text | add changes to wordpress section | d275ffb7eee81a2c1d3ca40c6a16b958330aa2eb | <ide><path>guide/english/wordpress/index.md
<ide> title: WordPress
<ide>
<ide> # WordPress
<ide>
<del>WordPress is a free and open-source content management system based on PHP and MySQL. Features include a plugin architecture and a template system. It is most associated with blogging but supports other types of web content including more traditional mailing lists and forums, media galleries, and online stores.
<add>WordPress is a free and open-source content management system (CMS) based on PHP and MySQL. Features include a plugin architecture and a template system. It is most associated with blogging but supports other types of web content including more traditional mailing lists and forums, media galleries, and online stores.
<ide>
<del>WordPress powers over 30% of all websites and is by far the most used CMS on the planet. Backed by a huge community, this open source platform powers a multi-billion dollar economy with themes/plugins and custom software.
<add>As a CMS, WordPress allows you to control and manage content of your website with a very easy system such as the WordPress dashboard panel. A dashboard lets you to do work on your website without needing to program anything. You can add or delete images and edit text on your webpage fast and easily.
<add>
<add>WordPress powers over 30% of all websites and is by far the most used CMS on the planet. In fact, more than 60 million websites rely on WordPress. Since it's backed up by a huge community, this open source platform powers a multi-billion dollar economy with themes/plugins and custom software built on top WordPress's underlying technology.
<ide>
<ide> Wordpress offers an easy-to-use solution for both web developers and non-web developers alike to create a site.
<ide>
<ide> Just a few advantages of WordPress:
<ide> * Users are able to manage their Wordpress webpage from any computer
<del>* Has a blog built-in and ready to go whenever applicable.
<del>* Has plugins, which extend functionality to WordPress sites.
<add>* There's a blog built-in and ready to go whenever applicable
<add>* It has plugins, which extend functionality to WordPress sites
<ide>
<del>Whether its page transitions or a customized contact form, WordPress users are only a few clicks away from success and a beautiful website.
<add>One of the main things that appeal to people about WordPress is the abudant themes and plugins. You can make your website look however you like, and with many plugins available you can do anything from having a plugin to handle contact forms, manage SEO (Search Engine Optimization), and many more.
<ide>
<add>Whether its page transitions or a customized contact form, WordPress users are only a few clicks away from building a website.
<ide>
<ide> ### More Information
<ide>
<ide> - [WordPress Codex: the online manual](https://codex.wordpress.org/)
<ide> - [WordPress Code Reference](https://developer.wordpress.org/reference/)
<add>- [WordPress Github Repository](https://github.com/WordPress/WordPress) | 1 |
Javascript | Javascript | use fs.promises in test files | ba30381c99948c50da6997196b1455bf1beb2f1c | <ide><path>test/integration/amp-export-validation/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<del>import { promisify } from 'util'
<ide> import { validateAMP } from 'amp-test-utils'
<ide> import { File, nextBuild, nextExport, runNextCommand } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
<del>const access = promisify(fs.access)
<del>const readFile = promisify(fs.readFile)
<add>const { access, readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outDir = join(appDir, 'out')
<ide> const nextConfig = new File(join(appDir, 'next.config.js'))
<ide><path>test/integration/export-default-map-serverless/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<ide> import cheerio from 'cheerio'
<del>import { promisify } from 'util'
<ide> import { nextBuild, nextExport } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<del>const readFile = promisify(fs.readFile)
<del>const access = promisify(fs.access)
<add>const { access, readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide>
<ide><path>test/integration/export-default-map/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<ide> import cheerio from 'cheerio'
<del>import { promisify } from 'util'
<ide> import { nextBuild, nextExport } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<del>const readFile = promisify(fs.readFile)
<del>const access = promisify(fs.access)
<add>const { access, readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide>
<ide><path>test/integration/export-override-404/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<del>import { promisify } from 'util'
<ide> import { nextBuild, nextExport } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<del>const readFile = promisify(fs.readFile)
<add>const { readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide>
<ide><path>test/integration/export-serverless/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<ide> import { join } from 'path'
<add>import { promises } from 'fs'
<ide> import {
<ide> nextBuild,
<ide> nextExport,
<ide> import {
<ide> import ssr from './ssr'
<ide> import browser from './browser'
<ide> import dev from './dev'
<del>import { promisify } from 'util'
<del>import fs from 'fs'
<ide> import dynamic from './dynamic'
<ide> import apiRoutes from './api-routes'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<ide>
<del>const writeFile = promisify(fs.writeFile)
<del>const mkdir = promisify(fs.mkdir)
<del>const access = promisify(fs.access)
<add>const { access, mkdir, writeFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const context = {}
<ide> context.appDir = appDir
<ide><path>test/integration/export-subfolders-serverless/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<ide> import cheerio from 'cheerio'
<del>import { promisify } from 'util'
<ide> import { nextBuild, nextExport } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<del>const readFile = promisify(fs.readFile)
<del>const access = promisify(fs.access)
<add>const { access, readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide>
<ide><path>test/integration/export-subfolders/test/index.test.js
<ide> /* eslint-env jest */
<ide> /* global jasmine */
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<ide> import cheerio from 'cheerio'
<del>import { promisify } from 'util'
<ide> import { nextBuild, nextExport } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<del>const readFile = promisify(fs.readFile)
<del>const access = promisify(fs.access)
<add>const { access, readFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide>
<ide><path>test/integration/export/test/index.test.js
<ide> import {
<ide> import ssr from './ssr'
<ide> import browser from './browser'
<ide> import dev from './dev'
<del>import { promisify } from 'util'
<del>import fs from 'fs'
<add>import { promises } from 'fs'
<ide> import dynamic from './dynamic'
<ide> import apiRoutes from './api-routes'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<ide>
<del>const writeFile = promisify(fs.writeFile)
<del>const mkdir = promisify(fs.mkdir)
<del>const access = promisify(fs.access)
<add>const { access, mkdir, writeFile } = promises
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide> const outNoTrailSlash = join(appDir, 'outNoTrailSlash')
<ide><path>test/integration/production/test/process-env.js
<ide> /* eslint-env jest */
<ide> import webdriver from 'next-webdriver'
<del>import { readFile } from 'fs'
<del>import { promisify } from 'util'
<add>import { promises } from 'fs'
<ide> import { join } from 'path'
<ide>
<del>const readFileAsync = promisify(readFile)
<ide> const readNextBuildFile = relativePath =>
<del> readFileAsync(join(__dirname, '../.next', relativePath), 'utf8')
<add> promises.readFile(join(__dirname, '../.next', relativePath), 'utf8')
<ide>
<ide> export default context => {
<ide> describe('process.env', () => { | 9 |
Python | Python | add tqdm, clean up logging | 0b7a20c651afd014e884ba2c1a486fa971689f19 | <ide><path>modeling.py
<ide> def __init__(self, config, num_labels):
<ide>
<ide> def init_weights(m):
<ide> if isinstance(m, (nn.Linear, nn.Embedding)):
<del> print("Initializing {}".format(m))
<ide> # Slight difference here with the TF version which uses truncated_normal
<ide> # cf https://github.com/pytorch/pytorch/pull/5617
<ide> m.weight.data.normal_(config.initializer_range)
<ide> def __init__(self, config):
<ide>
<ide> def init_weights(m):
<ide> if isinstance(m, (nn.Linear, nn.Embedding)):
<del> print("Initializing {}".format(m))
<ide> # Slight difference here with the TF version which uses truncated_normal for initialization
<ide> # cf https://github.com/pytorch/pytorch/pull/5617
<ide> m.weight.data.normal_(config.initializer_range)
<ide><path>run_squad.py
<ide> def main():
<ide>
<ide> model.eval()
<ide> all_results = []
<del> logger.info("Start evaulating")
<add> logger.info("Start evaluating")
<ide> #for input_ids, input_mask, segment_ids, label_ids, example_index in eval_dataloader:
<del> for input_ids, input_mask, segment_ids, example_index in eval_dataloader:
<add> for input_ids, input_mask, segment_ids, example_index in tqdm(eval_dataloader, descr="Evaluating"):
<ide> if len(all_results) % 1000 == 0:
<ide> logger.info("Processing example: %d" % (len(all_results)))
<ide> | 2 |
PHP | PHP | ignore invalid psalm error | 3aa74c341be07ed6ac9d1a9ba4c78286a1b6e0da | <ide><path>src/Collection/CollectionTrait.php
<ide> public function cartesianProduct(?callable $operation = null, ?callable $filter
<ide> $changeIndex = $lastIndex;
<ide>
<ide> while (!($changeIndex === 0 && $currentIndexes[0] === $collectionArraysCounts[0])) {
<add> /** @psalm-suppress ArgumentTypeCoercion */
<ide> $currentCombination = array_map(function ($value, $keys, $index) {
<ide> return $value[$keys[$index]];
<ide> }, $collectionArrays, $collectionArraysKeys, $currentIndexes); | 1 |
Python | Python | add missing spaces to implicitly joined strings | 4c39c270af91ddbc213e077fc06b4bf67c7c6e99 | <ide><path>django/core/checks/compatibility/django_1_7_0.py
<ide> def _check_middleware_classes(app_configs=None, **kwargs):
<ide> return [
<ide> Warning(
<ide> "MIDDLEWARE_CLASSES is not set.",
<del> hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES."
<add> hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
<ide> "django.contrib.sessions.middleware.SessionMiddleware, "
<ide> "django.contrib.auth.middleware.AuthenticationMiddleware, and "
<del> "django.contrib.messages.middleware.MessageMiddleware were removed from the defaults."
<add> "django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. "
<ide> "If your project needs these middleware then you should configure this setting."),
<ide> obj=None,
<ide> id='1_7.W001', | 1 |
PHP | PHP | allow array of options on filesystem operations | 481f76000c861e3e2540dcdda986fb44622ccbbe | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> public function get($path)
<ide> *
<ide> * @param string $path
<ide> * @param string|resource $contents
<del> * @param string $visibility
<add> * @param array $options
<ide> * @return bool
<ide> */
<del> public function put($path, $contents, $visibility = null)
<add> public function put($path, $contents, $options = [])
<ide> {
<del> if ($contents instanceof File || $contents instanceof UploadedFile) {
<del> return $this->putFile($path, $contents, $visibility);
<add> if (is_string($options)) {
<add> $options = ['visibility' => $options];
<ide> }
<ide>
<del> if ($visibility = $this->parseVisibility($visibility)) {
<del> $config = ['visibility' => $visibility];
<del> } else {
<del> $config = [];
<add> if ($contents instanceof File || $contents instanceof UploadedFile) {
<add> return $this->putFile($path, $contents, $options);
<ide> }
<ide>
<ide> if (is_resource($contents)) {
<del> return $this->driver->putStream($path, $contents, $config);
<add> return $this->driver->putStream($path, $contents, $options);
<ide> } else {
<del> return $this->driver->put($path, $contents, $config);
<add> return $this->driver->put($path, $contents, $options);
<ide> }
<ide> }
<ide>
<ide> public function put($path, $contents, $visibility = null)
<ide> *
<ide> * @param string $path
<ide> * @param \Illuminate\Http\UploadedFile $file
<del> * @param string $visibility
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function putFile($path, $file, $visibility = null)
<add> public function putFile($path, $file, $options = [])
<ide> {
<del> return $this->putFileAs($path, $file, $file->hashName(), $visibility);
<add> return $this->putFileAs($path, $file, $file->hashName(), $options);
<ide> }
<ide>
<ide> /**
<ide> public function putFile($path, $file, $visibility = null)
<ide> * @param string $path
<ide> * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile $file
<ide> * @param string $name
<del> * @param string $visibility
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function putFileAs($path, $file, $name, $visibility = null)
<add> public function putFileAs($path, $file, $name, $options = [])
<ide> {
<ide> $stream = fopen($file->getRealPath(), 'r+');
<ide>
<del> $result = $this->put($path = trim($path.'/'.$name, '/'), $stream, $visibility);
<add> $result = $this->put($path = trim($path.'/'.$name, '/'), $stream, $options);
<ide>
<ide> if (is_resource($stream)) {
<ide> fclose($stream);
<ide><path>src/Illuminate/Http/UploadedFile.php
<ide>
<ide> namespace Illuminate\Http;
<ide>
<add>use Illuminate\Support\Arr;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory;
<ide> class UploadedFile extends SymfonyUploadedFile
<ide> * Store the uploaded file on a filesystem disk.
<ide> *
<ide> * @param string $path
<del> * @param string|null $disk
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function store($path, $disk = null)
<add> public function store($path, $options = [])
<ide> {
<del> return $this->storeAs($path, $this->hashName(), $disk);
<add> if (is_string($options)) {
<add> $options = ['disk' => $options];
<add> }
<add>
<add> return $this->storeAs($path, $this->hashName(), $options);
<ide> }
<ide>
<ide> /**
<ide> * Store the uploaded file on a filesystem disk with public visibility.
<ide> *
<ide> * @param string $path
<del> * @param string|null $disk
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function storePublicly($path, $disk = null)
<add> public function storePublicly($path, $options = [])
<ide> {
<del> return $this->storeAs($path, $this->hashName(), $disk, 'public');
<add> if (is_string($options)) {
<add> $options = ['disk' => $options];
<add> }
<add>
<add> $options['visibility'] = 'public';
<add>
<add> return $this->storeAs($path, $this->hashName(), $options);
<ide> }
<ide>
<ide> /**
<ide> * Store the uploaded file on a filesystem disk with public visibility.
<ide> *
<ide> * @param string $path
<ide> * @param string $name
<del> * @param string|null $disk
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function storePubliclyAs($path, $name, $disk = null)
<add> public function storePubliclyAs($path, $name, $options = [])
<ide> {
<del> return $this->storeAs($path, $name, $disk, 'public');
<add> if (is_string($options)) {
<add> $options = ['disk' => $options];
<add> }
<add>
<add> $options['visibility'] = 'public';
<add>
<add> return $this->storeAs($path, $name, $options);
<ide> }
<ide>
<ide> /**
<ide> * Store the uploaded file on a filesystem disk.
<ide> *
<ide> * @param string $path
<ide> * @param string $name
<del> * @param string|null $disk
<del> * @param string|null $visibility
<add> * @param array $options
<ide> * @return string|false
<ide> */
<del> public function storeAs($path, $name, $disk = null, $visibility = null)
<add> public function storeAs($path, $name, $options = [])
<ide> {
<ide> $factory = Container::getInstance()->make(FilesystemFactory::class);
<ide>
<del> return $factory->disk($disk)->putFileAs($path, $this, $name, $visibility);
<add> $disk = Arr::pull($options, 'disk');
<add>
<add> return $factory->disk($disk)->putFileAs($path, $this, $name, $options);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | use stub `object.create` for ie8 | 1b06211af6ed18c0ea4582c77902d9ad68fb62d0 | <ide><path>packages/ember-metal/lib/platform.js
<ide> var platform = Ember.platform = {};
<ide> */
<ide> Ember.create = Object.create;
<ide>
<add>// IE8 has Object.create but it couldn't treat property descripters.
<add>if (Ember.create) {
<add> if (Ember.create({a: 1}, {a: {value: 2}}).a !== 2) {
<add> Ember.create = null;
<add> }
<add>}
<add>
<ide> // STUB_OBJECT_CREATE allows us to override other libraries that stub
<ide> // Object.create different than we would prefer
<ide> if (!Ember.create || Ember.ENV.STUB_OBJECT_CREATE) { | 1 |
Javascript | Javascript | use the debug build of node-weak when necessary | 05fe70b582c1f888e09ea7d21a70fe736bd09d12 | <ide><path>test/gc/node_modules/weak/lib/weak.js
<del>var bindings = require('../build/Release/weakref.node')
<add>var bindings
<add>try {
<add> bindings = require('../build/Release/weakref.node')
<add>} catch (e) {
<add> if (e.code === 'MODULE_NOT_FOUND') {
<add> bindings = require('../build/Debug/weakref.node')
<add> } else {
<add> throw e
<add> }
<add>}
<ide> module.exports = bindings.create
<ide>
<ide> // backwards-compat with node-weakref | 1 |
Ruby | Ruby | fix details in cask command | 3fd1e914fd783388e9d59b504cd6a2cd8850c415 | <ide><path>Library/Homebrew/cask/lib/hbc/artifact/abstract_flight_block.rb
<ide> def uninstall_phase(**)
<ide> abstract_phase(self.class.uninstall_dsl_key)
<ide> end
<ide>
<del> def summarize
<del> directives.keys.map(&:to_s).join(", ")
<del> end
<del>
<ide> private
<ide>
<ide> def class_for_dsl_key(dsl_key)
<ide> def abstract_phase(dsl_key)
<ide> return if (block = directives[dsl_key]).nil?
<ide> class_for_dsl_key(dsl_key).new(cask).instance_eval(&block)
<ide> end
<add>
<add> def summarize
<add> directives.keys.map(&:to_s).join(", ")
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/cask.rb
<ide> def to_hash
<ide> "version" => version,
<ide> "sha256" => sha256,
<ide> "artifacts" => artifacts.map do |a|
<del> if a.respond_to? :to_a
<del> a.to_a
<del> elsif a.methods.include? :to_h
<add> if a.respond_to? :to_h
<ide> a.to_h
<add> elsif a.respond_to? :to_a
<add> a.to_a
<ide> else
<ide> a
<ide> end | 2 |
Text | Text | strengthen suggestion in errors.md | 0c81cadec6aa92985819a76827f28cfe8e656a8e | <ide><path>doc/api/errors.md
<ide> signal (such as [`subprocess.kill()`][]).
<ide> <a id="ERR_UNSUPPORTED_DIR_IMPORT"></a>
<ide> ### `ERR_UNSUPPORTED_DIR_IMPORT`
<ide>
<del>`import` a directory URL is unsupported. Instead, you can
<add>`import` a directory URL is unsupported. Instead,
<ide> [self-reference a package using its name][] and [define a custom subpath][] in
<ide> the `"exports"` field of the `package.json` file.
<ide> | 1 |
Javascript | Javascript | use infolog instead of console.log | 0694a2991c8f518b4df9ee2b7990210d5830c6ac | <ide><path>Libraries/AppRegistry/AppRegistry.js
<ide> var ReactNative = require('ReactNative');
<ide>
<ide> var invariant = require('fbjs/lib/invariant');
<ide> var renderApplication = require('renderApplication');
<add>const infoLog = require('infoLog');
<ide>
<ide> if (__DEV__) {
<ide> // In order to use Cmd+P to record/dump perf data, we need to make sure
<ide> var AppRegistry = {
<ide> '__DEV__ === ' + String(__DEV__) +
<ide> ', development-level warning are ' + (__DEV__ ? 'ON' : 'OFF') +
<ide> ', performance optimizations are ' + (__DEV__ ? 'OFF' : 'ON');
<del> console.log(msg);
<add> infoLog(msg);
<ide> BugReporting.init();
<ide> BugReporting.addSource('AppRegistry.runApplication' + runCount++, () => msg);
<ide> BugReporting.addFileSource('react_hierarchy.txt', () => require('dumpReactTree')());
<ide><path>Libraries/BugReporting/BugReporting.js
<ide> const BugReportingNativeModule = require('NativeModules').BugReporting;
<ide> const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<ide> const Map = require('Map');
<add>const infoLog = require('infoLog');
<ide>
<ide> import type EmitterSubscription from 'EmitterSubscription';
<ide>
<ide> class BugReporting {
<ide> for (const [key, callback] of BugReporting._fileSources) {
<ide> fileData[key] = callback();
<ide> }
<del> console.log('BugReporting extraData:', extraData);
<add> infoLog('BugReporting extraData:', extraData);
<ide> BugReportingNativeModule &&
<ide> BugReportingNativeModule.setExtraData &&
<ide> BugReportingNativeModule.setExtraData(extraData, fileData); | 2 |
Javascript | Javascript | fix code style to match eslint requirements | 08f44d3078771f13e8568ba7dd91f6debe340bad | <ide><path>src/cameras/ArrayCamera.js
<ide> ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototyp
<ide> * And that near and far planes are identical for both cameras.
<ide> */
<ide> setProjectionFromUnion: function () {
<add>
<ide> var cameraLPos = new Vector3();
<ide> var cameraRPos = new Vector3();
<ide>
<ide> return function () {
<add>
<ide> cameraLPos.setFromMatrixPosition( this.cameras[ 0 ].matrixWorld );
<ide> cameraRPos.setFromMatrixPosition( this.cameras[ 1 ].matrixWorld );
<ide>
<ide> ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototyp
<ide>
<ide> // Calculate the new camera's position offset from the
<ide> // left camera.
<del> var zOffset = ipd / (leftFovL + rightFovR);
<add> var zOffset = ipd / ( leftFovL + rightFovR );
<ide> var xOffset = zOffset * leftFovL;
<ide>
<ide> // TODO: Better way to apply this offset?
<ide> this.cameras[ 0 ].matrixWorld.decompose( this.position, this.quaternion, this.scale );
<del> this.translateX(xOffset);
<del> this.translateZ(-zOffset);
<add> this.translateX( xOffset );
<add> this.translateZ( - zOffset );
<ide> this.matrixWorld.compose( this.position, this.quaternion, this.scale );
<del> this.matrixWorldInverse.getInverse(this.matrixWorld);
<add> this.matrixWorldInverse.getInverse( this.matrixWorld );
<ide>
<ide> // Find the union of the frustum values of the cameras and scale
<ide> // the values so that the near plane's position does not change in world space,
<ide> // although must now be relative to the new union camera.
<ide> var near2 = near + zOffset;
<ide> var far2 = far + zOffset;
<ide> var left = leftL - xOffset;
<del> var right = rightR + (ipd - xOffset)
<add> var right = rightR + ( ipd - xOffset );
<ide> var top = Math.max( topL, topR );
<ide> var bottom = Math.min( bottomL, bottomR );
<ide>
<ide> this.projectionMatrix.makePerspective( left, right, top, bottom, near2, far2 );
<del> }
<add>
<add> };
<add>
<ide> }(),
<ide>
<ide> } ); | 1 |
Go | Go | use int32 instead of string for ip set | 3e3abdd770bdc23c409a9e49619a1897ffbf2354 | <ide><path>networkdriver/portallocator/ipset.go
<ide> package ipallocator
<ide>
<ide> import (
<add> "sort"
<ide> "sync"
<ide> )
<ide>
<ide> // iPSet is a thread-safe sorted set and a stack.
<ide> type iPSet struct {
<ide> sync.RWMutex
<del> set []string
<add> set []int32
<ide> }
<ide>
<ide> // Push takes a string and adds it to the set. If the elem aready exists, it has no effect.
<del>func (s *iPSet) Push(elem string) {
<add>func (s *iPSet) Push(elem int32) {
<ide> s.RLock()
<ide> for i, e := range s.set {
<ide> if e == elem {
<ide> func (s *iPSet) Push(elem string) {
<ide> s.Lock()
<ide> s.set = append(s.set, elem)
<ide> // Make sure the list is always sorted
<del> sort.Strings(s.set)
<add> sort.Ints(s.set)
<ide> s.Unlock()
<ide> }
<ide>
<ide> // Pop is an alias to PopFront()
<del>func (s *iPSet) Pop() string {
<add>func (s *iPSet) Pop() int32 {
<ide> return s.PopFront()
<ide> }
<ide>
<ide> // Pop returns the first elemen from the list and removes it.
<del>// If the list is empty, it returns an empty string
<del>func (s *iPSet) PopFront() string {
<add>// If the list is empty, it returns 0
<add>func (s *iPSet) PopFront() int32 {
<ide> s.RLock()
<ide>
<ide> for i, e := range s.set {
<ide> func (s *iPSet) PopFront() string {
<ide> // PullBack retrieve the last element of the list.
<ide> // The element is not removed.
<ide> // If the list is empty, an empty element is returned.
<del>func (s *iPSet) PullBack() string {
<add>func (s *iPSet) PullBack() int32 {
<ide> if len(s.set) == 0 {
<ide> return ""
<ide> }
<ide> return s.set[len(s.set)-1]
<ide> }
<ide>
<ide> // Exists checks if the given element present in the list.
<del>func (s *iPSet) Exists(elem string) bool {
<add>func (s *iPSet) Exists(elem int32) bool {
<ide> for _, e := range s.set {
<ide> if e == elem {
<ide> return true
<ide> func (s *iPSet) Exists(elem string) bool {
<ide>
<ide> // Remove removes an element from the list.
<ide> // If the element is not found, it has no effect.
<del>func (s *iPSet) Remove(elem string) {
<add>func (s *iPSet) Remove(elem int32) {
<ide> for i, e := range s.set {
<ide> if e == elem {
<ide> s.set = append(s.set[:i], s.set[i+1:]...) | 1 |
Python | Python | check expand_kwargs() input type before unmapping | 4e786e31bcdf81427163918e14d191e55a4ab606 | <ide><path>airflow/decorators/base.py
<ide> def _expand_mapped_kwargs(self, resolve: Optional[Tuple[Context, Session]]) -> D
<ide> assert self.expand_input is EXPAND_INPUT_EMPTY
<ide> return {"op_kwargs": super()._expand_mapped_kwargs(resolve)}
<ide>
<del> def _get_unmap_kwargs(self, mapped_kwargs: Dict[str, Any], *, strict: bool) -> Dict[str, Any]:
<add> def _get_unmap_kwargs(self, mapped_kwargs: Mapping[str, Any], *, strict: bool) -> Dict[str, Any]:
<ide> if strict:
<ide> prevent_duplicates(
<ide> self.partial_kwargs["op_kwargs"],
<ide><path>airflow/models/expandinput.py
<ide> import collections.abc
<ide> import functools
<ide> import operator
<del>from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, Sequence, Sized, Union
<add>from typing import TYPE_CHECKING, Any, Iterable, Mapping, NamedTuple, Sequence, Sized, Union
<ide>
<ide> from sqlalchemy import func
<ide> from sqlalchemy.orm import Session
<ide> def _find_index_for_this_field(index: int) -> int:
<ide> return k, v
<ide> raise IndexError(f"index {map_index} is over mapped length")
<ide>
<del> def resolve(self, context: Context, session: Session) -> dict[str, Any]:
<add> def resolve(self, context: Context, session: Session) -> Mapping[str, Any]:
<ide> return {k: self._expand_mapped_field(k, v, context, session=session) for k, v in self.value.items()}
<ide>
<ide>
<add>def _describe_type(value: Any) -> str:
<add> if value is None:
<add> return "None"
<add> return type(value).__name__
<add>
<add>
<ide> class ListOfDictsExpandInput(NamedTuple):
<ide> """Storage type of a mapped operator's mapped kwargs.
<ide>
<ide> def get_total_map_length(self, run_id: str, *, session: Session) -> int:
<ide> raise NotFullyPopulated({"expand_kwargs() argument"})
<ide> return value
<ide>
<del> def resolve(self, context: Context, session: Session) -> dict[str, Any]:
<add> def resolve(self, context: Context, session: Session) -> Mapping[str, Any]:
<ide> map_index = context["ti"].map_index
<ide> if map_index < 0:
<ide> raise RuntimeError("can't resolve task-mapping argument without expanding")
<del> # Validation should be done when the upstream returns.
<del> return self.value.resolve(context, session)[map_index]
<add> mappings = self.value.resolve(context, session)
<add> if not isinstance(mappings, collections.abc.Sequence):
<add> raise ValueError(f"expand_kwargs() expects a list[dict], not {_describe_type(mappings)}")
<add> mapping = mappings[map_index]
<add> if not isinstance(mapping, collections.abc.Mapping):
<add> raise ValueError(f"expand_kwargs() expects a list[dict], not list[{_describe_type(mapping)}]")
<add> for key in mapping:
<add> if not isinstance(key, str):
<add> raise ValueError(
<add> f"expand_kwargs() input dict keys must all be str, "
<add> f"but {key!r} is of type {_describe_type(key)}"
<add> )
<add> return mapping
<ide>
<ide>
<ide> EXPAND_INPUT_EMPTY = DictOfListsExpandInput({}) # Sentinel value.
<ide><path>airflow/models/mappedoperator.py
<ide> Iterable,
<ide> Iterator,
<ide> List,
<add> Mapping,
<ide> Optional,
<ide> Sequence,
<ide> Set,
<ide> def validate_mapping_kwargs(op: Type["BaseOperator"], func: ValidationSource, va
<ide> raise TypeError(f"{op.__name__}.{func}() got {error}")
<ide>
<ide>
<del>def prevent_duplicates(kwargs1: Dict[str, Any], kwargs2: Dict[str, Any], *, fail_reason: str) -> None:
<add>def prevent_duplicates(kwargs1: Dict[str, Any], kwargs2: Mapping[str, Any], *, fail_reason: str) -> None:
<ide> duplicated_keys = set(kwargs1).intersection(kwargs2)
<ide> if not duplicated_keys:
<ide> return
<ide> def serialize_for_task_group(self) -> Tuple[DagAttributeTypes, Any]:
<ide> """Implementing DAGNode."""
<ide> return DagAttributeTypes.OP, self.task_id
<ide>
<del> def _expand_mapped_kwargs(self, resolve: Optional[Tuple[Context, Session]]) -> Dict[str, Any]:
<add> def _expand_mapped_kwargs(self, resolve: Optional[Tuple[Context, Session]]) -> Mapping[str, Any]:
<ide> """Get the kwargs to create the unmapped operator.
<ide>
<ide> If *resolve* is not *None*, it must be a two-tuple to provide context to
<ide> def _expand_mapped_kwargs(self, resolve: Optional[Tuple[Context, Session]]) -> D
<ide> return expand_input.resolve(*resolve)
<ide> return expand_input.get_unresolved_kwargs()
<ide>
<del> def _get_unmap_kwargs(self, mapped_kwargs: Dict[str, Any], *, strict: bool) -> Dict[str, Any]:
<add> def _get_unmap_kwargs(self, mapped_kwargs: Mapping[str, Any], *, strict: bool) -> Dict[str, Any]:
<ide> """Get init kwargs to unmap the underlying operator class.
<ide>
<ide> :param mapped_kwargs: The dict returned by ``_expand_mapped_kwargs``.
<ide> def _get_unmap_kwargs(self, mapped_kwargs: Dict[str, Any], *, strict: bool) -> D
<ide> **mapped_kwargs,
<ide> }
<ide>
<del> def unmap(self, resolve: Union[None, Dict[str, Any], Tuple[Context, Session]]) -> "BaseOperator":
<add> def unmap(self, resolve: Union[None, Mapping[str, Any], Tuple[Context, Session]]) -> "BaseOperator":
<ide> """Get the "normal" Operator after applying the current mapping.
<ide>
<ide> If ``operator_class`` is not a class (i.e. this DAG has been
<ide><path>tests/models/test_taskinstance.py
<ide> from freezegun import freeze_time
<ide>
<ide> from airflow import models, settings
<add>from airflow.decorators import task
<ide> from airflow.example_dags.plugins.workday import AfterWorkdayTimetable
<ide> from airflow.exceptions import (
<ide> AirflowException,
<ide> def push():
<ide> assert ti.state == TaskInstanceState.FAILED
<ide> assert str(ctx.value) == error_message
<ide>
<add> @pytest.mark.parametrize(
<add> "create_upstream",
<add> [
<add> # The task returns an invalid expand_kwargs() input (a list[int] instead of list[dict]).
<add> pytest.param(lambda: task(task_id="push")(lambda: [0])(), id="normal"),
<add> # This task returns a list[dict] (correct), but we use map() to transform it to list[int] (wrong).
<add> pytest.param(lambda: task(task_id="push")(lambda: [{"v": ""}])().map(lambda _: 0), id="mapped"),
<add> ],
<add> )
<add> def test_expand_kwargs_error_if_received_invalid(self, dag_maker, session, create_upstream):
<add> with dag_maker(dag_id="test_expand_kwargs_error_if_received_invalid", session=session):
<add> push_task = create_upstream()
<add>
<add> @task()
<add> def pull(v):
<add> print(v)
<add>
<add> pull.expand_kwargs(push_task)
<add>
<add> dr = dag_maker.create_dagrun()
<add>
<add> # Run "push".
<add> decision = dr.task_instance_scheduling_decisions(session=session)
<add> assert decision.schedulable_tis
<add> for ti in decision.schedulable_tis:
<add> ti.run()
<add>
<add> # Run "pull".
<add> decision = dr.task_instance_scheduling_decisions(session=session)
<add> assert decision.schedulable_tis
<add> for ti in decision.schedulable_tis:
<add> with pytest.raises(ValueError) as ctx:
<add> ti.run()
<add> assert str(ctx.value) == "expand_kwargs() expects a list[dict], not list[int]"
<add>
<ide> @pytest.mark.parametrize(
<ide> "downstream, error_message",
<ide> [
<ide><path>tests/models/test_xcom_arg_map.py
<ide> def c_to_none(v):
<ide> tis[("pull", 1)].run()
<ide>
<ide> # But the third one fails because the map() result cannot be used as kwargs.
<del> with pytest.raises(TypeError) as ctx:
<add> with pytest.raises(ValueError) as ctx:
<ide> tis[("pull", 2)].run()
<del> assert str(ctx.value) == "'NoneType' object is not iterable"
<add> assert str(ctx.value) == "expand_kwargs() expects a list[dict], not list[None]"
<ide>
<ide> assert [tis[("pull", i)].state for i in range(3)] == [
<ide> TaskInstanceState.SUCCESS, | 5 |
Javascript | Javascript | fix coding style in src/core/fonts.js | 66e243f506490104abe8c31cd1c55f822751ff3e | <ide><path>src/core/fonts.js
<ide> var MacStandardGlyphOrdering = [
<ide> function getUnicodeRangeFor(value) {
<ide> for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
<ide> var range = UnicodeRanges[i];
<del> if (value >= range.begin && value < range.end)
<add> if (value >= range.begin && value < range.end) {
<ide> return i;
<add> }
<ide> }
<ide> return -1;
<ide> }
<ide>
<ide> function isRTLRangeFor(value) {
<ide> var range = UnicodeRanges[13];
<del> if (value >= range.begin && value < range.end)
<add> if (value >= range.begin && value < range.end) {
<ide> return true;
<add> }
<ide> range = UnicodeRanges[11];
<del> if (value >= range.begin && value < range.end)
<add> if (value >= range.begin && value < range.end) {
<ide> return true;
<add> }
<ide> return false;
<ide> }
<ide>
<ide> var NormalizedUnicodes = {
<ide> function reverseIfRtl(chars) {
<ide> var charsLength = chars.length;
<ide> //reverse an arabic ligature
<del> if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0)))
<add> if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
<ide> return chars;
<del>
<add> }
<ide> var s = '';
<del> for (var ii = charsLength - 1; ii >= 0; ii--)
<add> for (var ii = charsLength - 1; ii >= 0; ii--) {
<ide> s += chars[ii];
<add> }
<ide> return s;
<ide> }
<ide>
<ide> function fontCharsToUnicode(charCodes, font) {
<ide> var result = '';
<ide> for (var i = 0, ii = glyphs.length; i < ii; i++) {
<ide> var glyph = glyphs[i];
<del> if (!glyph)
<add> if (!glyph) {
<ide> continue;
<del>
<add> }
<ide> var glyphUnicode = glyph.unicode;
<del> if (glyphUnicode in NormalizedUnicodes)
<add> if (glyphUnicode in NormalizedUnicodes) {
<ide> glyphUnicode = NormalizedUnicodes[glyphUnicode];
<add> }
<ide> result += reverseIfRtl(glyphUnicode);
<ide> }
<ide> return result;
<ide> var Font = (function FontClosure() {
<ide> var type = properties.type;
<ide> this.type = type;
<ide>
<del> this.fallbackName = this.isMonospace ? 'monospace' :
<del> this.isSerifFont ? 'serif' : 'sans-serif';
<add> this.fallbackName = (this.isMonospace ? 'monospace' :
<add> (this.isSerifFont ? 'serif' : 'sans-serif'));
<ide>
<ide> this.differences = properties.differences;
<ide> this.widths = properties.widths;
<ide> var Font = (function FontClosure() {
<ide>
<ide> if (properties.type == 'Type3') {
<ide> for (var charCode = 0; charCode < 256; charCode++) {
<del> this.toFontChar[charCode] = this.differences[charCode] ||
<del> properties.defaultEncoding[charCode];
<add> this.toFontChar[charCode] = (this.differences[charCode] ||
<add> properties.defaultEncoding[charCode]);
<ide> }
<ide> return;
<ide> }
<ide> var Font = (function FontClosure() {
<ide> fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
<ide>
<ide> this.bold = (fontName.search(/bold/gi) != -1);
<del> this.italic = (fontName.search(/oblique/gi) != -1) ||
<del> (fontName.search(/italic/gi) != -1);
<add> this.italic = ((fontName.search(/oblique/gi) != -1) ||
<add> (fontName.search(/italic/gi) != -1));
<ide>
<ide> // Use 'name' instead of 'fontName' here because the original
<ide> // name ArialBlack for example will be replaced by Helvetica.
<ide> var Font = (function FontClosure() {
<ide>
<ide> // Some fonts might use wrong font types for Type1C or CIDFontType0C
<ide> var subtype = properties.subtype;
<del> if (subtype == 'Type1C' && (type != 'Type1' && type != 'MMType1'))
<add> if (subtype == 'Type1C' && (type != 'Type1' && type != 'MMType1')) {
<ide> type = 'Type1';
<del> if (subtype == 'CIDFontType0C' && type != 'CIDFontType0')
<add> }
<add> if (subtype == 'CIDFontType0C' && type != 'CIDFontType0') {
<ide> type = 'CIDFontType0';
<add> }
<ide> // XXX: Temporarily change the type for open type so we trigger a warning.
<ide> // This should be removed when we add support for open type.
<ide> if (subtype === 'OpenType') {
<ide> var Font = (function FontClosure() {
<ide>
<ide> function stringToArray(str) {
<ide> var array = [];
<del> for (var i = 0, ii = str.length; i < ii; ++i)
<add> for (var i = 0, ii = str.length; i < ii; ++i) {
<ide> array[i] = str.charCodeAt(i);
<del>
<add> }
<ide> return array;
<ide> }
<ide>
<ide> var Font = (function FontClosure() {
<ide> }
<ide>
<ide> value = 2;
<del> for (var i = 1; i < maxPower; i++)
<add> for (var i = 1; i < maxPower; i++) {
<ide> value *= 2;
<add> }
<ide> return value;
<ide> }
<ide>
<ide> function string16(value) {
<del> return String.fromCharCode((value >> 8) & 0xff) +
<del> String.fromCharCode(value & 0xff);
<add> return (String.fromCharCode((value >> 8) & 0xff) +
<add> String.fromCharCode(value & 0xff));
<ide> }
<ide>
<ide> function safeString16(value) {
<ide> // clamp value to the 16-bit int range
<del> value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value;
<del> return String.fromCharCode((value >> 8) & 0xff) +
<del> String.fromCharCode(value & 0xff);
<add> value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
<add> return (String.fromCharCode((value >> 8) & 0xff) +
<add> String.fromCharCode(value & 0xff));
<ide> }
<ide>
<ide> function string32(value) {
<del> return String.fromCharCode((value >> 24) & 0xff) +
<del> String.fromCharCode((value >> 16) & 0xff) +
<del> String.fromCharCode((value >> 8) & 0xff) +
<del> String.fromCharCode(value & 0xff);
<add> return (String.fromCharCode((value >> 24) & 0xff) +
<add> String.fromCharCode((value >> 16) & 0xff) +
<add> String.fromCharCode((value >> 8) & 0xff) +
<add> String.fromCharCode(value & 0xff));
<ide> }
<ide>
<ide> function createOpenTypeHeader(sfnt, file, numTables) {
<ide> // Windows hates the Mac TrueType sfnt version number
<del> if (sfnt == 'true')
<add> if (sfnt == 'true') {
<ide> sfnt = string32(0x00010000);
<add> }
<ide>
<ide> // sfnt version (4 bytes)
<ide> var header = sfnt;
<ide> var Font = (function FontClosure() {
<ide> var length = data.length;
<ide>
<ide> // Per spec tables must be 4-bytes align so add padding as needed
<del> while (data.length & 3)
<add> while (data.length & 3) {
<ide> data.push(0x00);
<del>
<del> while (file.virtualOffset & 3)
<add> }
<add> while (file.virtualOffset & 3) {
<ide> file.virtualOffset++;
<add> }
<ide>
<ide> // checksum
<ide> var checksum = 0, n = data.length;
<del> for (var i = 0; i < n; i += 4)
<add> for (var i = 0; i < n; i += 4) {
<ide> checksum = (checksum + int32(data[i], data[i + 1], data[i + 2],
<ide> data[i + 3])) | 0;
<add> }
<ide>
<ide> var tableEntry = (tag + string32(checksum) +
<ide> string32(offset) + string32(length));
<ide> var Font = (function FontClosure() {
<ide> codeIndices.push(codes[n].glyphId);
<ide> ++end;
<ide> ++n;
<del> if (end === 0xFFFF) { break; }
<add> if (end === 0xFFFF) {
<add> break;
<add> }
<ide> }
<ide> ranges.push([start, end, codeIndices]);
<ide> }
<ide> var Font = (function FontClosure() {
<ide> if (charstrings) {
<ide> for (var code in charstrings) {
<ide> code |= 0;
<del> if (firstCharIndex > code || !firstCharIndex)
<add> if (firstCharIndex > code || !firstCharIndex) {
<ide> firstCharIndex = code;
<del> if (lastCharIndex < code)
<add> }
<add> if (lastCharIndex < code) {
<ide> lastCharIndex = code;
<add> }
<ide>
<ide> var position = getUnicodeRangeFor(code);
<ide> if (position < 32) {
<ide> var Font = (function FontClosure() {
<ide> }
<ide>
<ide> var bbox = properties.bbox || [0, 0, 0, 0];
<del> var unitsPerEm = override.unitsPerEm ||
<del> 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
<add> var unitsPerEm = (override.unitsPerEm ||
<add> 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
<ide>
<ide> // if the font units differ to the PDF glyph space units
<ide> // then scale up the values
<del> var scale = properties.ascentScaled ? 1.0 :
<del> unitsPerEm / PDF_GLYPH_SPACE_UNITS;
<add> var scale = (properties.ascentScaled ? 1.0 :
<add> unitsPerEm / PDF_GLYPH_SPACE_UNITS);
<ide>
<del> var typoAscent = override.ascent || Math.round(scale *
<del> (properties.ascent || bbox[3]));
<del> var typoDescent = override.descent || Math.round(scale *
<del> (properties.descent || bbox[1]));
<add> var typoAscent = (override.ascent ||
<add> Math.round(scale * (properties.ascent || bbox[3])));
<add> var typoDescent = (override.descent ||
<add> Math.round(scale * (properties.descent || bbox[1])));
<ide> if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
<ide> typoDescent = -typoDescent; // fixing incorrect descent
<ide> }
<ide> var Font = (function FontClosure() {
<ide>
<ide> function createPostTable(properties) {
<ide> var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
<del> return '\x00\x03\x00\x00' + // Version number
<del> string32(angle) + // italicAngle
<del> '\x00\x00' + // underlinePosition
<del> '\x00\x00' + // underlineThickness
<del> string32(properties.fixedPitch) + // isFixedPitch
<del> '\x00\x00\x00\x00' + // minMemType42
<del> '\x00\x00\x00\x00' + // maxMemType42
<del> '\x00\x00\x00\x00' + // minMemType1
<del> '\x00\x00\x00\x00'; // maxMemType1
<add> return ('\x00\x03\x00\x00' + // Version number
<add> string32(angle) + // italicAngle
<add> '\x00\x00' + // underlinePosition
<add> '\x00\x00' + // underlineThickness
<add> string32(properties.fixedPitch) + // isFixedPitch
<add> '\x00\x00\x00\x00' + // minMemType42
<add> '\x00\x00\x00\x00' + // maxMemType42
<add> '\x00\x00\x00\x00' + // minMemType1
<add> '\x00\x00\x00\x00'); // maxMemType1
<ide> }
<ide>
<ide> function createNameTable(name, proto) {
<ide> var Font = (function FontClosure() {
<ide> exportData: function Font_exportData() {
<ide> var data = {};
<ide> for (var i in this) {
<del> if (this.hasOwnProperty(i))
<add> if (this.hasOwnProperty(i)) {
<ide> data[i] = this[i];
<add> }
<ide> }
<ide> return data;
<ide> },
<ide> var Font = (function FontClosure() {
<ide> var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
<ide> segment.offsetIndex = offsetIndex;
<ide> offsetsCount = Math.max(offsetsCount, offsetIndex +
<del> segment.end - segment.start + 1);
<add> segment.end - segment.start + 1);
<ide> }
<ide>
<ide> var offsets = [];
<ide> var Font = (function FontClosure() {
<ide> continue;
<ide> }
<ide>
<del> var glyphId = offsetIndex < 0 ? j :
<del> offsets[offsetIndex + j - start];
<add> var glyphId = (offsetIndex < 0 ?
<add> j : offsets[offsetIndex + j - start]);
<ide> glyphId = (glyphId + delta) & 0xFFFF;
<ide> if (glyphId === 0) {
<ide> continue;
<ide> var Font = (function FontClosure() {
<ide> if (numMissing > 0) {
<ide> font.pos = (font.start ? font.start : 0) + metrics.offset;
<ide> var entries = '';
<del> for (var i = 0, ii = metrics.length; i < ii; i++)
<add> for (var i = 0, ii = metrics.length; i < ii; i++) {
<ide> entries += String.fromCharCode(font.getByte());
<del> for (var i = 0; i < numMissing; i++)
<add> }
<add> for (var i = 0; i < numMissing; i++) {
<ide> entries += '\x00\x00';
<add> }
<ide> metrics.data = stringToArray(entries);
<ide> }
<ide> }
<ide> var Font = (function FontClosure() {
<ide> // to have single glyph with one point
<ide> var simpleGlyph = new Uint8Array(
<ide> [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
<del> for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize)
<add> for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
<ide> itemEncode(locaData, j, simpleGlyph.length);
<add> }
<ide> glyf.data = simpleGlyph;
<ide> return;
<ide> }
<ide> var Font = (function FontClosure() {
<ide> if (!inFDEF && !inELSE) {
<ide> var offset = stack[stack.length - 1];
<ide> // only jumping forward to prevent infinite loop
<del> if (offset > 0) { i += offset - 1; }
<add> if (offset > 0) {
<add> i += offset - 1;
<add> }
<ide> }
<ide> }
<ide> // Adjusting stack not extactly, but just enough to get function id
<ide> var Font = (function FontClosure() {
<ide> var numTables = header.numTables;
<ide>
<ide> var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
<del> hmtx: null, maxp: null, name: null, post: null};
<add> hmtx: null, maxp: null, name: null, post: null };
<ide> for (var i = 0; i < numTables; i++) {
<ide> var table = readTableEntry(font);
<ide> if (VALID_TABLES.indexOf(table.tag) < 0) {
<ide> var Font = (function FontClosure() {
<ide> var data = [];
<ide>
<ide> var tableData = table.data;
<del> for (var j = 0, jj = tableData.length; j < jj; j++)
<add> for (var j = 0, jj = tableData.length; j < jj; j++) {
<ide> data.push(tableData[j]);
<add> }
<ide> createTableEntry(ttf, table.tag, data);
<ide> }
<ide>
<ide> var Font = (function FontClosure() {
<ide> ttf.file += arrayToString(tableData);
<ide>
<ide> // 4-byte aligned data
<del> while (ttf.file.length & 3)
<add> while (ttf.file.length & 3) {
<ide> ttf.file += String.fromCharCode(0);
<add> }
<ide> }
<ide>
<ide> return stringToArray(ttf.file);
<ide> var Font = (function FontClosure() {
<ide> // Font header
<ide> 'head': (function fontFieldsHead() {
<ide> return stringToArray(
<del> '\x00\x01\x00\x00' + // Version number
<del> '\x00\x00\x10\x00' + // fontRevision
<del> '\x00\x00\x00\x00' + // checksumAdjustement
<del> '\x5F\x0F\x3C\xF5' + // magicNumber
<del> '\x00\x00' + // Flags
<del> safeString16(unitsPerEm) + // unitsPerEM
<del> '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
<del> '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
<del> '\x00\x00' + // xMin
<del> safeString16(properties.descent) + // yMin
<del> '\x0F\xFF' + // xMax
<del> safeString16(properties.ascent) + // yMax
<del> string16(properties.italicAngle ? 2 : 0) + // macStyle
<del> '\x00\x11' + // lowestRecPPEM
<del> '\x00\x00' + // fontDirectionHint
<del> '\x00\x00' + // indexToLocFormat
<del> '\x00\x00'); // glyphDataFormat
<add> '\x00\x01\x00\x00' + // Version number
<add> '\x00\x00\x10\x00' + // fontRevision
<add> '\x00\x00\x00\x00' + // checksumAdjustement
<add> '\x5F\x0F\x3C\xF5' + // magicNumber
<add> '\x00\x00' + // Flags
<add> safeString16(unitsPerEm) + // unitsPerEM
<add> '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
<add> '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
<add> '\x00\x00' + // xMin
<add> safeString16(properties.descent) + // yMin
<add> '\x0F\xFF' + // xMax
<add> safeString16(properties.ascent) + // yMax
<add> string16(properties.italicAngle ? 2 : 0) + // macStyle
<add> '\x00\x11' + // lowestRecPPEM
<add> '\x00\x00' + // fontDirectionHint
<add> '\x00\x00' + // indexToLocFormat
<add> '\x00\x00'); // glyphDataFormat
<ide> })(),
<ide>
<ide> // Horizontal header
<ide> 'hhea': (function fontFieldsHhea() {
<ide> return stringToArray(
<del> '\x00\x01\x00\x00' + // Version number
<del> safeString16(properties.ascent) + // Typographic Ascent
<del> safeString16(properties.descent) + // Typographic Descent
<del> '\x00\x00' + // Line Gap
<del> '\xFF\xFF' + // advanceWidthMax
<del> '\x00\x00' + // minLeftSidebearing
<del> '\x00\x00' + // minRightSidebearing
<del> '\x00\x00' + // xMaxExtent
<del> safeString16(properties.capHeight) + // caretSlopeRise
<del> safeString16(Math.tan(properties.italicAngle) *
<del> properties.xHeight) + // caretSlopeRun
<del> '\x00\x00' + // caretOffset
<del> '\x00\x00' + // -reserved-
<del> '\x00\x00' + // -reserved-
<del> '\x00\x00' + // -reserved-
<del> '\x00\x00' + // -reserved-
<del> '\x00\x00' + // metricDataFormat
<del> string16(numGlyphs + 1)); // Number of HMetrics
<add> '\x00\x01\x00\x00' + // Version number
<add> safeString16(properties.ascent) + // Typographic Ascent
<add> safeString16(properties.descent) + // Typographic Descent
<add> '\x00\x00' + // Line Gap
<add> '\xFF\xFF' + // advanceWidthMax
<add> '\x00\x00' + // minLeftSidebearing
<add> '\x00\x00' + // minRightSidebearing
<add> '\x00\x00' + // xMaxExtent
<add> safeString16(properties.capHeight) + // caretSlopeRise
<add> safeString16(Math.tan(properties.italicAngle) *
<add> properties.xHeight) + // caretSlopeRun
<add> '\x00\x00' + // caretOffset
<add> '\x00\x00' + // -reserved-
<add> '\x00\x00' + // -reserved-
<add> '\x00\x00' + // -reserved-
<add> '\x00\x00' + // -reserved-
<add> '\x00\x00' + // metricDataFormat
<add> string16(numGlyphs + 1)); // Number of HMetrics
<ide> })(),
<ide>
<ide> // Horizontal metrics
<ide> var Font = (function FontClosure() {
<ide> // Maximum profile
<ide> 'maxp': (function fontFieldsMaxp() {
<ide> return stringToArray(
<del> '\x00\x00\x50\x00' + // Version number
<del> string16(numGlyphs + 1)); // Num of glyphs
<add> '\x00\x00\x50\x00' + // Version number
<add> string16(numGlyphs + 1)); // Num of glyphs
<ide> })(),
<ide>
<ide> // Naming tables
<ide> var Font = (function FontClosure() {
<ide> 'post': stringToArray(createPostTable(properties))
<ide> };
<ide>
<del> for (var field in fields)
<add> for (var field in fields) {
<ide> createTableEntry(otf, field, fields[field]);
<del>
<add> }
<ide> for (var field in fields) {
<ide> var table = fields[field];
<ide> otf.file += arrayToString(table);
<ide> var Font = (function FontClosure() {
<ide> }
<ide> }
<ide> // ... via toUnicode map
<del> if (!charcode && 'toUnicode' in this)
<add> if (!charcode && 'toUnicode' in this) {
<ide> charcode = this.toUnicode.indexOf(glyphUnicode);
<add> }
<ide> // setting it to unicode if negative or undefined
<del> if (charcode <= 0)
<add> if (charcode <= 0) {
<ide> charcode = glyphUnicode;
<add> }
<ide> // trying to get width via charcode
<ide> width = this.widths[charcode];
<del> if (width)
<add> if (width) {
<ide> break; // the non-zero width found
<add> }
<ide> }
<ide> width = width || this.defaultWidth;
<ide> // Do not shadow the property here. See discussion:
<ide> var Font = (function FontClosure() {
<ide> // if we translated this string before, just grab it from the cache
<ide> if (charsCache) {
<ide> glyphs = charsCache[chars];
<del> if (glyphs)
<add> if (glyphs) {
<ide> return glyphs;
<add> }
<ide> }
<ide>
<ide> // lazily create the translation cache
<del> if (!charsCache)
<add> if (!charsCache) {
<ide> charsCache = this.charsCache = Object.create(null);
<add> }
<ide>
<ide> glyphs = [];
<ide> var charsCacheKey = chars;
<ide> var Font = (function FontClosure() {
<ide> var charcode = chars.charCodeAt(i);
<ide> var glyph = this.charToGlyph(charcode);
<ide> glyphs.push(glyph);
<del> if (charcode == 0x20)
<add> if (charcode == 0x20) {
<ide> glyphs.push(null);
<add> }
<ide> }
<ide> }
<ide>
<ide> var Type1Font = function Type1Font(name, file, properties) {
<ide> var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
<ide> var eexecBlockParser = new Type1Parser(eexecBlock, true);
<ide> var data = eexecBlockParser.extractFontProgram();
<del> for (var info in data.properties)
<add> for (var info in data.properties) {
<ide> properties[info] = data.properties[info];
<add> }
<ide>
<ide> var charstrings = data.charstrings;
<ide> var type2Charstrings = this.getType2Charstrings(charstrings);
<ide> Type1Font.prototype = {
<ide> getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
<ide> var bias = 0;
<ide> var count = type1Subrs.length;
<del> if (count < 1133)
<add> if (count < 1133) {
<ide> bias = 107;
<del> else if (count < 33769)
<add> } else if (count < 33769) {
<ide> bias = 1131;
<del> else
<add> } else {
<ide> bias = 32768;
<add> }
<ide>
<ide> // Add a bunch of empty subrs to deal with the Type2 bias
<ide> var type2Subrs = [];
<del> for (var i = 0; i < bias; i++)
<add> for (var i = 0; i < bias; i++) {
<ide> type2Subrs.push([0x0B]);
<add> }
<ide>
<ide> for (var i = 0; i < count; i++) {
<ide> type2Subrs.push(type1Subrs[i]);
<ide> Type1Font.prototype = {
<ide> // thought mapping names that aren't in the standard strings to .notdef
<ide> // was fine, however in issue818 when mapping them all to .notdef the
<ide> // adieresis glyph no longer worked.
<del> if (index == -1)
<add> if (index == -1) {
<ide> index = 0;
<del>
<add> }
<ide> charsetArray.push((index >> 8) & 0xff, index & 0xff);
<ide> }
<ide> cff.charset = new CFFCharset(false, 0, [], charsetArray);
<ide> Type1Font.prototype = {
<ide> ];
<ide> for (var i = 0, ii = fields.length; i < ii; i++) {
<ide> var field = fields[i];
<del> if (!properties.privateData.hasOwnProperty(field))
<add> if (!properties.privateData.hasOwnProperty(field)) {
<ide> continue;
<add> }
<ide> var value = properties.privateData[field];
<ide> if (isArray(value)) {
<ide> // All of the private dictionary array data in CFF must be stored as
<ide> var CFFParser = (function CFFParserClosure() {
<ide> var hdrSize = bytes[2];
<ide> var offSize = bytes[3];
<ide> var header = new CFFHeader(major, minor, hdrSize, offSize);
<del> return {obj: header, endPos: hdrSize};
<add> return { obj: header, endPos: hdrSize };
<ide> },
<ide> parseDict: function CFFParser_parseDict(dict) {
<ide> var pos = 0;
<ide> var CFFParser = (function CFFParserClosure() {
<ide> var b1 = b >> 4;
<ide> var b2 = b & 15;
<ide>
<del> if (b1 == eof)
<add> if (b1 == eof) {
<ide> break;
<add> }
<ide> str += lookup[b1];
<ide>
<del> if (b2 == eof)
<add> if (b2 == eof) {
<ide> break;
<add> }
<ide> str += lookup[b2];
<ide> }
<ide> return parseFloat(str);
<ide> var CFFParser = (function CFFParserClosure() {
<ide> while (pos < end) {
<ide> var b = dict[pos];
<ide> if (b <= 21) {
<del> if (b === 12)
<add> if (b === 12) {
<ide> b = (b << 8) | dict[++pos];
<add> }
<ide> entries.push([b, operands]);
<ide> operands = [];
<ide> ++pos;
<ide> var CFFParser = (function CFFParserClosure() {
<ide> stack[stackSize] = value - 139;
<ide> stackSize++;
<ide> } else if (value >= 247 && value <= 254) { // number (+1 bytes)
<del> stack[stackSize] = value < 251 ?
<del> ((value - 247) << 8) + data[j] + 108 :
<del> -((value - 251) << 8) - data[j] - 108;
<add> stack[stackSize] = (value < 251 ?
<add> ((value - 247) << 8) + data[j] + 108 :
<add> -((value - 251) << 8) - data[j] - 108);
<ide> j++;
<ide> stackSize++;
<ide> } else if (value == 255) { // number (32 bit)
<ide> stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
<del> (data[j + 2] << 8) | data[j + 3]) / 65536;
<add> (data[j + 2] << 8) | data[j + 3]) / 65536;
<ide> j += 4;
<ide> stackSize++;
<ide> } else if (value == 19 || value == 20) {
<ide> var CFFParser = (function CFFParserClosure() {
<ide> parentDict.privateDict = privateDict;
<ide>
<ide> // Parse the Subrs index also since it's relative to the private dict.
<del> if (!privateDict.getByName('Subrs'))
<add> if (!privateDict.getByName('Subrs')) {
<ide> return;
<add> }
<ide> var subrsOffset = privateDict.getByName('Subrs');
<ide> var relativeOffset = offset + subrsOffset;
<ide> // Validate the offset.
<ide> var CFFParser = (function CFFParserClosure() {
<ide> while (charset.length <= length) {
<ide> var id = (bytes[pos++] << 8) | bytes[pos++];
<ide> var count = bytes[pos++];
<del> for (var i = 0; i <= count; i++)
<add> for (var i = 0; i <= count; i++) {
<ide> charset.push(cid ? id++ : strings.get(id++));
<add> }
<ide> }
<ide> break;
<ide> case 2:
<ide> while (charset.length <= length) {
<ide> var id = (bytes[pos++] << 8) | bytes[pos++];
<ide> var count = (bytes[pos++] << 8) | bytes[pos++];
<del> for (var i = 0; i <= count; i++)
<add> for (var i = 0; i <= count; i++) {
<ide> charset.push(cid ? id++ : strings.get(id++));
<add> }
<ide> }
<ide> break;
<ide> default:
<ide> var CFFParser = (function CFFParserClosure() {
<ide> switch (format & 0x7f) {
<ide> case 0:
<ide> var glyphsCount = bytes[pos++];
<del> for (var i = 1; i <= glyphsCount; i++)
<add> for (var i = 1; i <= glyphsCount; i++) {
<ide> encoding[bytes[pos++]] = i;
<add> }
<ide> break;
<ide>
<ide> case 1:
<ide> var CFFParser = (function CFFParserClosure() {
<ide> for (var i = 0; i < rangesCount; i++) {
<ide> var start = bytes[pos++];
<ide> var left = bytes[pos++];
<del> for (var j = start; j <= start + left; j++)
<add> for (var j = start; j <= start + left; j++) {
<ide> encoding[j] = gid++;
<add> }
<ide> }
<ide> break;
<ide>
<ide> var CFFParser = (function CFFParserClosure() {
<ide> var first = (bytes[pos++] << 8) | bytes[pos++];
<ide> var fdIndex = bytes[pos++];
<ide> var next = (bytes[pos] << 8) | bytes[pos + 1];
<del> for (var j = first; j < next; ++j)
<add> for (var j = first; j < next; ++j) {
<ide> fdSelect.push(fdIndex);
<add> }
<ide> }
<ide> // Advance past the sentinel(next).
<ide> pos += 2;
<ide> var CFFStrings = (function CFFStringsClosure() {
<ide> }
<ide> CFFStrings.prototype = {
<ide> get: function CFFStrings_get(index) {
<del> if (index >= 0 && index <= 390)
<add> if (index >= 0 && index <= 390) {
<ide> return CFFStandardStrings[index];
<del> if (index - 391 <= this.strings.length)
<add> }
<add> if (index - 391 <= this.strings.length) {
<ide> return this.strings[index - 391];
<add> }
<ide> return CFFStandardStrings[0];
<ide> },
<ide> add: function CFFStrings_add(value) {
<ide> var CFFDict = (function CFFDictClosure() {
<ide> CFFDict.prototype = {
<ide> // value should always be an array
<ide> setByKey: function CFFDict_setByKey(key, value) {
<del> if (!(key in this.keyToNameMap))
<add> if (!(key in this.keyToNameMap)) {
<ide> return false;
<add> }
<ide> // ignore empty values
<del> if (value.length === 0)
<add> if (value.length === 0) {
<ide> return true;
<add> }
<ide> var type = this.types[key];
<ide> // remove the array wrapping these types of values
<del> if (type === 'num' || type === 'sid' || type === 'offset')
<add> if (type === 'num' || type === 'sid' || type === 'offset') {
<ide> value = value[0];
<add> }
<ide> this.values[key] = value;
<ide> return true;
<ide> },
<ide> var CFFDict = (function CFFDictClosure() {
<ide> return this.nameToKeyMap[name] in this.values;
<ide> },
<ide> getByName: function CFFDict_getByName(name) {
<del> if (!(name in this.nameToKeyMap))
<add> if (!(name in this.nameToKeyMap)) {
<ide> error('Invalid dictionary name "' + name + '"');
<add> }
<ide> var key = this.nameToKeyMap[name];
<del> if (!(key in this.values))
<add> if (!(key in this.values)) {
<ide> return this.defaults[key];
<add> }
<ide> return this.values[key];
<ide> },
<ide> removeByName: function CFFDict_removeByName(name) {
<ide> var CFFTopDict = (function CFFTopDictClosure() {
<ide> ];
<ide> var tables = null;
<ide> function CFFTopDict(strings) {
<del> if (tables === null)
<add> if (tables === null) {
<ide> tables = CFFDict.createTables(layout);
<add> }
<ide> CFFDict.call(this, tables, strings);
<ide> this.privateDict = null;
<ide> }
<ide> var CFFPrivateDict = (function CFFPrivateDictClosure() {
<ide> ];
<ide> var tables = null;
<ide> function CFFPrivateDict(strings) {
<del> if (tables === null)
<add> if (tables === null) {
<ide> tables = CFFDict.createTables(layout);
<add> }
<ide> CFFDict.call(this, tables, strings);
<ide> this.subrsIndex = null;
<ide> }
<ide> var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
<ide> return key in this.offsets;
<ide> },
<ide> track: function CFFOffsetTracker_track(key, location) {
<del> if (key in this.offsets)
<add> if (key in this.offsets) {
<ide> error('Already tracking location of ' + key);
<add> }
<ide> this.offsets[key] = location;
<ide> },
<ide> offset: function CFFOffsetTracker_offset(value) {
<ide> var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
<ide> setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
<ide> values,
<ide> output) {
<del> if (!(key in this.offsets))
<add> if (!(key in this.offsets)) {
<ide> error('Not tracking location of ' + key);
<add> }
<ide> var data = output.data;
<ide> var dataOffset = this.offsets[key];
<ide> var size = 5;
<ide> var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
<ide> var offset4 = offset0 + 4;
<ide> // It's easy to screw up offsets so perform this sanity check.
<ide> if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
<del> data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0)
<add> data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
<ide> error('writing to an offset that is not empty');
<add> }
<ide> var value = values[i];
<ide> data[offset0] = 0x1d;
<ide> data[offset1] = (value >> 24) & 0xFF;
<ide> var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> function stringToArray(str) {
<ide> var array = [];
<del> for (var i = 0, ii = str.length; i < ii; ++i)
<add> for (var i = 0, ii = str.length; i < ii; ++i) {
<ide> array[i] = str.charCodeAt(i);
<del>
<add> }
<ide> return array;
<ide> }
<ide> function CFFCompiler(cff) {
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> return output.data;
<ide> },
<ide> encodeNumber: function CFFCompiler_encodeNumber(value) {
<del> if (parseFloat(value) == parseInt(value, 10) && !isNaN(value)) // isInt
<add> if (parseFloat(value) == parseInt(value, 10) && !isNaN(value)) { // isInt
<ide> return this.encodeInteger(value);
<del> else
<add> } else {
<ide> return this.encodeFloat(value);
<add> }
<ide> },
<ide> encodeFloat: function CFFCompiler_encodeFloat(num) {
<ide> var value = num.toString();
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> },
<ide> compileNameIndex: function CFFCompiler_compileNameIndex(names) {
<ide> var nameIndex = new CFFIndex();
<del> for (var i = 0, ii = names.length; i < ii; ++i)
<add> for (var i = 0, ii = names.length; i < ii; ++i) {
<ide> nameIndex.add(stringToArray(names[i]));
<add> }
<ide> return this.compileIndex(nameIndex);
<ide> },
<ide> compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> var order = dict.order;
<ide> for (var i = 0; i < order.length; ++i) {
<ide> var key = order[i];
<del> if (!(key in dict.values))
<add> if (!(key in dict.values)) {
<ide> continue;
<add> }
<ide> var values = dict.values[key];
<ide> var types = dict.types[key];
<del> if (!isArray(types)) types = [types];
<del> if (!isArray(values)) values = [values];
<add> if (!isArray(types)) {
<add> types = [types];
<add> }
<add> if (!isArray(values)) {
<add> values = [values];
<add> }
<ide>
<ide> // Remove any empty dict values.
<del> if (values.length === 0)
<add> if (values.length === 0) {
<ide> continue;
<add> }
<ide>
<ide> for (var j = 0, jj = types.length; j < jj; ++j) {
<ide> var type = types[j];
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> var name = dict.keyToNameMap[key];
<ide> // Some offsets have the offset and the length, so just record the
<ide> // position of the first one.
<del> if (!offsetTracker.isTracking(name))
<add> if (!offsetTracker.isTracking(name)) {
<ide> offsetTracker.track(name, out.length);
<add> }
<ide> out = out.concat([0x1d, 0, 0, 0, 0]);
<ide> break;
<ide> case 'array':
<ide> case 'delta':
<ide> out = out.concat(this.encodeNumber(value));
<del> for (var k = 1, kk = values.length; k < kk; ++k)
<add> for (var k = 1, kk = values.length; k < kk; ++k) {
<ide> out = out.concat(this.encodeNumber(values[k]));
<add> }
<ide> break;
<ide> default:
<ide> error('Unknown data type of ' + type);
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> },
<ide> compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
<ide> var stringIndex = new CFFIndex();
<del> for (var i = 0, ii = strings.length; i < ii; ++i)
<add> for (var i = 0, ii = strings.length; i < ii; ++i) {
<ide> stringIndex.add(stringToArray(strings[i]));
<add> }
<ide> return this.compileIndex(stringIndex);
<ide> },
<ide> compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> },
<ide> compileTypedArray: function CFFCompiler_compileTypedArray(data) {
<ide> var out = [];
<del> for (var i = 0, ii = data.length; i < ii; ++i)
<add> for (var i = 0, ii = data.length; i < ii; ++i) {
<ide> out[i] = data[i];
<add> }
<ide> return out;
<ide> },
<ide> compileIndex: function CFFCompiler_compileIndex(index, trackers) {
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide>
<ide> // If there is no object, just create an index. This technically
<ide> // should just be [0, 0] but OTS has an issue with that.
<del> if (count === 0)
<add> if (count === 0) {
<ide> return [0, 0, 0];
<add> }
<ide>
<ide> var data = [(count >> 8) & 0xFF, count & 0xff];
<ide>
<ide> var lastOffset = 1;
<del> for (var i = 0; i < count; ++i)
<add> for (var i = 0; i < count; ++i) {
<ide> lastOffset += objects[i].length;
<add> }
<ide>
<ide> var offsetSize;
<del> if (lastOffset < 0x100)
<add> if (lastOffset < 0x100) {
<ide> offsetSize = 1;
<del> else if (lastOffset < 0x10000)
<add> } else if (lastOffset < 0x10000) {
<ide> offsetSize = 2;
<del> else if (lastOffset < 0x1000000)
<add> } else if (lastOffset < 0x1000000) {
<ide> offsetSize = 3;
<del> else
<add> } else {
<ide> offsetSize = 4;
<add> }
<ide>
<ide> // Next byte contains the offset size use to reference object in the file
<ide> data.push(offsetSize);
<ide> var CFFCompiler = (function CFFCompilerClosure() {
<ide> relativeOffset & 0xFF);
<ide> }
<ide>
<del> if (objects[i])
<add> if (objects[i]) {
<ide> relativeOffset += objects[i].length;
<add> }
<ide> }
<ide> var offset = data.length;
<ide>
<ide> for (var i = 0; i < count; i++) {
<ide> // Notify the tracker where the object will be offset in the data.
<del> if (trackers[i])
<add> if (trackers[i]) {
<ide> trackers[i].offset(data.length);
<del> for (var j = 0, jj = objects[i].length; j < jj; j++)
<add> }
<add> for (var j = 0, jj = objects[i].length; j < jj; j++) {
<ide> data.push(objects[i][j]);
<add> }
<ide> }
<ide> return data;
<ide> } | 1 |
Python | Python | reconstruction the class glanceslimits | 8f4235fbc8edb60343bbcde368e126faf39f7af1 | <ide><path>glances/glances.py
<ide> # Specifics libs
<ide> import json
<ide> import collections
<add>from functools import partial
<ide>
<ide> # For client/server authentication
<ide> from base64 import b64decode
<ide> def get_option(self, section, option):
<ide> Get the value of an option, if it exist
<ide> """
<ide> try:
<del> value = self.parser.getfloat(section, option)
<add> return self.parser.getfloat(section, option)
<ide> except NoOptionError:
<ide> return
<del> else:
<del> return value
<ide>
<ide>
<ide> class glancesLimits:
<ide> def __init__(self):
<ide> # Test if the configuration file has a limits section
<ide> if config.has_section('global'):
<ide> # Read STD limits
<del> self.__setLimits('STD', 'global', 'careful')
<del> self.__setLimits('STD', 'global', 'warning')
<del> self.__setLimits('STD', 'global', 'critical')
<add> self.__setLimits('STD', 'global')
<ide> if config.has_section('cpu'):
<ide> # Read CPU limits
<del> self.__setLimits('CPU_USER', 'cpu', 'user_careful')
<del> self.__setLimits('CPU_USER', 'cpu', 'user_warning')
<del> self.__setLimits('CPU_USER', 'cpu', 'user_critical')
<del> self.__setLimits('CPU_SYSTEM', 'cpu', 'system_careful')
<del> self.__setLimits('CPU_SYSTEM', 'cpu', 'system_warning')
<del> self.__setLimits('CPU_SYSTEM', 'cpu', 'system_critical')
<del> self.__setLimits('CPU_IOWAIT', 'cpu', 'iowait_careful')
<del> self.__setLimits('CPU_IOWAIT', 'cpu', 'iowait_warning')
<del> self.__setLimits('CPU_IOWAIT', 'cpu', 'iowait_critical')
<add> self.__setLimits('CPU_USER', 'cpu', 'user')
<add> self.__setLimits('CPU_SYSTEM', 'cpu', 'system')
<add> self.__setLimits('CPU_IOWAIT', 'cpu', 'iowait')
<ide> if config.has_section('load'):
<ide> # Read LOAD limits
<del> self.__setLimits('LOAD', 'load', 'careful')
<del> self.__setLimits('LOAD', 'load', 'warning')
<del> self.__setLimits('LOAD', 'load', 'critical')
<add> self.__setLimits('LOAD', 'load')
<ide> if config.has_section('memory'):
<ide> # Read MEM limits
<del> self.__setLimits('MEM', 'memory', 'careful')
<del> self.__setLimits('MEM', 'memory', 'warning')
<del> self.__setLimits('MEM', 'memory', 'critical')
<add> self.__setLimits('MEM', 'memory')
<ide> if config.has_section('swap'):
<ide> # Read MEM limits
<del> self.__setLimits('SWAP', 'swap', 'careful')
<del> self.__setLimits('SWAP', 'swap', 'warning')
<del> self.__setLimits('SWAP', 'swap', 'critical')
<add> self.__setLimits('SWAP', 'swap')
<ide> if config.has_section('temperature'):
<ide> # Read TEMP limits
<del> self.__setLimits('TEMP', 'temperature', 'careful')
<del> self.__setLimits('TEMP', 'temperature', 'warning')
<del> self.__setLimits('TEMP', 'temperature', 'critical')
<add> self.__setLimits('TEMP', 'temperature')
<ide> if config.has_section('hddtemperature'):
<ide> # Read HDDTEMP limits
<del> self.__setLimits('HDDTEMP', 'hddtemperature', 'careful')
<del> self.__setLimits('HDDTEMP', 'hddtemperature', 'warning')
<del> self.__setLimits('HDDTEMP', 'hddtemperature', 'critical')
<add> self.__setLimits('HDDTEMP', 'hddtemperature')
<ide> if config.has_section('filesystem'):
<ide> # Read FS limits
<del> self.__setLimits('FS', 'filesystem', 'careful')
<del> self.__setLimits('FS', 'filesystem', 'warning')
<del> self.__setLimits('FS', 'filesystem', 'critical')
<add> self.__setLimits('FS', 'filesystem')
<ide> if config.has_section('process'):
<ide> # Process limits
<del> self.__setLimits('PROCESS_CPU', 'process', 'cpu_careful')
<del> self.__setLimits('PROCESS_CPU', 'process', 'cpu_warning')
<del> self.__setLimits('PROCESS_CPU', 'process', 'cpu_critical')
<del> self.__setLimits('PROCESS_MEM', 'process', 'mem_careful')
<del> self.__setLimits('PROCESS_MEM', 'process', 'mem_warning')
<del> self.__setLimits('PROCESS_MEM', 'process', 'mem_critical')
<del>
<del> def __setLimits(self, stat, section, alert):
<add> self.__setLimits('PROCESS_CPU', 'process', 'cpu')
<add> self.__setLimits('PROCESS_MEM', 'process', 'mem')
<add>
<add> def __getattr__(self, name):
<add> """
<add> According to invoke methods to obtain data
<add> """
<add> base_type = ['Careful', 'Warning', 'Critical']
<add> base_module = ['CPU', 'LOAD', 'Process', 'STD', 'MEM', 'SWAP', 'TEMP', 'HDDTEMP', 'FS']
<add> get_type = ['get'+n for n in base_type]
<add> get_module = ['get'+m+t for m in base_module\
<add> for t in base_type]
<add>
<add> if name in get_module:
<add> for index, t in enumerate(base_type):
<add> if name.endswith(t):
<add> module_name = name.replace('get', '').replace(t, '')
<add> if module_name == 'CPU':
<add> return partial(self.get_CPUStat, index)
<add> elif module_name == 'LOAD':
<add> return partial(self.get_LOADStat, index)
<add> elif module_name == 'Process':
<add> return partial(self.get_ProcessStat, index)
<add> return partial(self.get_Stat, index, module_name)
<add> elif name in get_type:
<add> return partial(self.get_Stat, get_type.index(name))
<add>
<add> def get_Stat(self, index, stat):
<add> return self.__limits_list[stat][index]
<add>
<add> def get_CPUStat(self, index, stat):
<add> return self.get_Stat(index, 'CPU_'+stat.upper())
<add>
<add> def get_LOADStat(self, index, core=1):
<add> return self.get_Stat(index, 'LOAD') * core
<add>
<add> def get_ProcessStat(self, index, stat='', core=1):
<add> if stat.upper() != 'CPU':
<add> # Use core only for CPU
<add> core = 1
<add> return self.get_Stat(index, 'PROCESS_' + stat.upper()) * core
<add>
<add> def __setLimits(self, stat, section, alert_prefix=None):
<ide> """
<ide> stat: 'CPU', 'LOAD', 'MEM', 'SWAP', 'TEMP', etc.
<ide> section: 'cpu', 'load', 'memory', 'swap', 'temperature', etc.
<ide> alert: 'careful', 'warning', 'critical'
<ide> """
<del> value = config.get_option(section, alert)
<ide>
<add> alert_type = ['careful', 'warning', 'critical']
<ide> #~ print("%s / %s = %s -> %s" % (section, alert, value, stat))
<del> if alert.endswith('careful'):
<del> self.__limits_list[stat][0] = value
<del> elif alert.endswith('warning'):
<del> self.__limits_list[stat][1] = value
<del> elif alert.endswith('critical'):
<del> self.__limits_list[stat][2] = value
<add> for index, alert in enumerate(alert_type):
<add> if alert_prefix:
<add> value = config.get_option(section, '{0}_{1}'.format(
<add> alert_prefix, alert))
<add> else:
<add> value = config.get_option(section, alert)
<add> self.__limits_list[stat][index] = value
<ide>
<ide> def setAll(self, newlimits):
<ide> self.__limits_list = newlimits
<ide> def setAll(self, newlimits):
<ide> def getAll(self):
<ide> return self.__limits_list
<ide>
<del> def getCareful(self, stat):
<del> return self.__limits_list[stat][0]
<del>
<del> def getWarning(self, stat):
<del> return self.__limits_list[stat][1]
<del>
<del> def getCritical(self, stat):
<del> return self.__limits_list[stat][2]
<del>
<del> # TO BE DELETED AFTER THE HTML output refactoring
<del> def getSTDCareful(self):
<del> return self.getCareful('STD')
<del>
<del> def getSTDWarning(self):
<del> return self.getWarning('STD')
<del>
<del> def getSTDCritical(self):
<del> return self.getCritical('STD')
<del> # /TO BE DELETED AFTER THE HTML output refactoring
<del>
<del> def getCPUCareful(self, stat):
<del> return self.getCareful('CPU_' + stat.upper())
<del>
<del> def getCPUWarning(self, stat):
<del> return self.getWarning('CPU_' + stat.upper())
<del>
<del> def getCPUCritical(self, stat):
<del> return self.getCritical('CPU_' + stat.upper())
<del>
<del> def getLOADCareful(self, core=1):
<del> return self.getCareful('LOAD') * core
<del>
<del> def getLOADWarning(self, core=1):
<del> return self.getWarning('LOAD') * core
<del>
<del> def getLOADCritical(self, core=1):
<del> return self.getCritical('LOAD') * core
<del>
<del> def getMEMCareful(self):
<del> return self.getCareful('MEM')
<del>
<del> def getMEMWarning(self):
<del> return self.getWarning('MEM')
<del>
<del> def getMEMCritical(self):
<del> return self.getCritical('MEM')
<del>
<del> def getSWAPCareful(self):
<del> return self.getCareful('SWAP')
<del>
<del> def getSWAPWarning(self):
<del> return self.getWarning('SWAP')
<del>
<del> def getSWAPCritical(self):
<del> return self.getCritical('SWAP')
<del>
<del> def getTEMPCareful(self):
<del> return self.getCareful('TEMP')
<del>
<del> def getTEMPWarning(self):
<del> return self.getWarning('TEMP')
<del>
<del> def getTEMPCritical(self):
<del> return self.getCritical('TEMP')
<del>
<del> def getHDDTEMPCareful(self):
<del> return self.getCareful('HDDTEMP')
<del>
<del> def getHDDTEMPWarning(self):
<del> return self.getWarning('HDDTEMP')
<del>
<del> def getHDDTEMPCritical(self):
<del> return self.getCritical('HDDTEMP')
<del>
<del> def getFSCareful(self):
<del> return self.getCareful('FS')
<del>
<del> def getFSWarning(self):
<del> return self.getWarning('FS')
<del>
<del> def getFSCritical(self):
<del> return self.getCritical('FS')
<del>
<del> def getProcessCareful(self, stat='', core=1):
<del> if stat.upper() != 'CPU':
<del> # Use core only for CPU
<del> core = 1
<del> return self.getCareful('PROCESS_' + stat.upper()) * core
<del>
<del> def getProcessWarning(self, stat='', core=1):
<del> if stat.upper() != 'CPU':
<del> # Use core only for CPU
<del> core = 1
<del> return self.getWarning('PROCESS_' + stat.upper()) * core
<del>
<del> def getProcessCritical(self, stat='', core=1):
<del> if stat.upper() != 'CPU':
<del> # Use core only for CPU
<del> core = 1
<del> return self.getCritical('PROCESS_' + stat.upper()) * core
<del>
<ide>
<ide> class glancesLogs:
<ide> """ | 1 |
PHP | PHP | replace tabs with spaces | 8da2c77e926b49423a30b7ccf9003d1afe0d4316 | <ide><path>src/Illuminate/Notifications/resources/views/email-plain.blade.php
<ide> <?php
<ide> if( $greeting !== null ) {
<del> echo e($greeting);
<add> echo e($greeting);
<ide> } else {
<del> echo $level == 'error' ? 'Whoops!' : 'Hello!';
<add> echo $level == 'error' ? 'Whoops!' : 'Hello!';
<ide> }
<ide>
<ide> ?> | 1 |
Python | Python | reduce verbosity of cpplint | 3eff42bbca531873905ef4478e8d6ec9a7485d3a | <ide><path>tools/cpplint.py
<ide> def ProcessFile(filename, vlevel):
<ide> 'One or more unexpected \\r (^M) found;'
<ide> 'better to use only a \\n')
<ide>
<del> if not _cpplint_state.output_format == 'tap':
<del> sys.stderr.write('Done processing %s\n' % filename)
<del>
<ide>
<ide> def PrintUsage(message):
<ide> """Prints a brief usage string and exits, optionally with an error message. | 1 |
Javascript | Javascript | change invalid.js fixture for babel transpilation | 23d5dc872654c3bc353d0a3a24d782c30659ebbc | <ide><path>spec/fixtures/babel/invalid.js
<ide> 'use 6to6';
<ide>
<del>module.exports = v => v + 1
<add>module.exports = async function hello() {} | 1 |
Python | Python | add matplotlib inventory for intersphinx | bb2865a2863492a2ea1799e1ce874607e8cf6ff9 | <ide><path>doc/source/conf.py
<ide> # -----------------------------------------------------------------------------
<ide> # Intersphinx configuration
<ide> # -----------------------------------------------------------------------------
<del>intersphinx_mapping = {'http://docs.python.org/dev': None}
<add>intersphinx_mapping = {
<add> 'python': ('https://docs.python.org/dev', None),
<add> 'matplotlib': ('http://matplotlib.org', None)
<add>}
<ide>
<ide>
<ide> # ----------------------------------------------------------------------------- | 1 |
PHP | PHP | remove remaining reference operators | 8eb56960d87bb69ba520bd936d6eb4c067a22367 | <ide><path>lib/Cake/Console/Command/Task/TestTask.php
<ide> public function isLoadableClass($package, $class) {
<ide> * @param string $class the Classname of the class the test is being generated for.
<ide> * @return object And instance of the class that is going to be tested.
<ide> */
<del> public function &buildTestSubject($type, $class) {
<add> public function buildTestSubject($type, $class) {
<ide> ClassRegistry::flush();
<ide> App::import($type, $class);
<ide> $class = $this->getRealClassName($type, $class);
<ide><path>lib/Cake/I18n/I18n.php
<ide> public function __construct() {
<ide> *
<ide> * @return I18n
<ide> */
<del> public static function &getInstance() {
<add> public static function getInstance() {
<ide> static $instance = array();
<ide> if (!$instance) {
<ide> $instance[0] = new I18n();
<ide><path>lib/Cake/Routing/Router.php
<ide> public static function normalize($url = '/') {
<ide> *
<ide> * @return CakeRoute Matching route object.
<ide> */
<del> public static function &requestRoute() {
<add> public static function requestRoute() {
<ide> return self::$_currentRoute[0];
<ide> }
<ide>
<ide> public static function &requestRoute() {
<ide> *
<ide> * @return CakeRoute Matching route object.
<ide> */
<del> public static function ¤tRoute() {
<add> public static function currentRoute() {
<ide> return self::$_currentRoute[count(self::$_currentRoute) - 1];
<ide> }
<ide>
<ide><path>lib/Cake/Utility/ClassRegistry.php
<ide> class ClassRegistry {
<ide> *
<ide> * @return ClassRegistry instance
<ide> */
<del> public static function &getInstance() {
<add> public static function getInstance() {
<ide> static $instance = array();
<ide> if (!$instance) {
<ide> $instance[0] = new ClassRegistry();
<ide> public static function keys() {
<ide> * @param string $key Key of object to look for
<ide> * @return mixed Object stored in registry or boolean false if the object does not exist.
<ide> */
<del> public static function &getObject($key) {
<add> public static function getObject($key) {
<ide> $_this = ClassRegistry::getInstance();
<ide> $key = Inflector::underscore($key);
<ide> $return = false;
<ide><path>lib/Cake/Utility/Debugger.php
<ide> public function __construct() {
<ide> * @param string $class
<ide> * @return object
<ide> */
<del> public static function &getInstance($class = null) {
<add> public static function getInstance($class = null) {
<ide> static $instance = array();
<ide> if (!empty($class)) {
<ide> if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) { | 5 |
Javascript | Javascript | fix inconsistent styling in test-url | 1684957ff5a9e5d661a07fee7de29aaa7bc3bc34 | <ide><path>test/parallel/test-url.js
<ide> var url = require('url');
<ide> // URLs to parse, and expected data
<ide> // { url : parsed }
<ide> var parseTests = {
<del> '//some_path' : {
<del> 'href': '//some_path',
<del> 'pathname': '//some_path',
<del> 'path': '//some_path'
<add> '//some_path': {
<add> href: '//some_path',
<add> pathname: '//some_path',
<add> path: '//some_path'
<ide> },
<ide>
<ide> 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h': {
<ide> var parseTests = {
<ide> href: 'http://evil-phisher/foo.html'
<ide> },
<ide>
<del> 'HTTP://www.example.com/' : {
<del> 'href': 'http://www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'HTTP://www.example.com' : {
<del> 'href': 'http://www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://www.ExAmPlE.com/' : {
<del> 'href': 'http://www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://user:pw@www.ExAmPlE.com/' : {
<del> 'href': 'http://user:pw@www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pw',
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://USER:PW@www.ExAmPlE.com/' : {
<del> 'href': 'http://USER:PW@www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'USER:PW',
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://user@www.example.com/' : {
<del> 'href': 'http://user@www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user',
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://user%3Apw@www.example.com/' : {
<del> 'href': 'http://user:pw@www.example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pw',
<del> 'host': 'www.example.com',
<del> 'hostname': 'www.example.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://x.com/path?that\'s#all, folks' : {
<del> 'href': 'http://x.com/path?that%27s#all,%20folks',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x.com',
<del> 'hostname': 'x.com',
<del> 'search': '?that%27s',
<del> 'query': 'that%27s',
<del> 'pathname': '/path',
<del> 'hash': '#all,%20folks',
<del> 'path': '/path?that%27s'
<del> },
<del>
<del> 'HTTP://X.COM/Y' : {
<del> 'href': 'http://x.com/Y',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x.com',
<del> 'hostname': 'x.com',
<del> 'pathname': '/Y',
<del> 'path': '/Y'
<add> 'HTTP://www.example.com/': {
<add> href: 'http://www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'HTTP://www.example.com': {
<add> href: 'http://www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://www.ExAmPlE.com/': {
<add> href: 'http://www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://user:pw@www.ExAmPlE.com/': {
<add> href: 'http://user:pw@www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pw',
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://USER:PW@www.ExAmPlE.com/': {
<add> href: 'http://USER:PW@www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'USER:PW',
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://user@www.example.com/': {
<add> href: 'http://user@www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user',
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://user%3Apw@www.example.com/': {
<add> href: 'http://user:pw@www.example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pw',
<add> host: 'www.example.com',
<add> hostname: 'www.example.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://x.com/path?that\'s#all, folks': {
<add> href: 'http://x.com/path?that%27s#all,%20folks',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x.com',
<add> hostname: 'x.com',
<add> search: '?that%27s',
<add> query: 'that%27s',
<add> pathname: '/path',
<add> hash: '#all,%20folks',
<add> path: '/path?that%27s'
<add> },
<add>
<add> 'HTTP://X.COM/Y': {
<add> href: 'http://x.com/Y',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x.com',
<add> hostname: 'x.com',
<add> pathname: '/Y',
<add> path: '/Y'
<ide> },
<ide>
<ide> // + not an invalid host character
<ide> // per https://url.spec.whatwg.org/#host-parsing
<del> 'http://x.y.com+a/b/c' : {
<del> 'href': 'http://x.y.com+a/b/c',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x.y.com+a',
<del> 'hostname': 'x.y.com+a',
<del> 'pathname': '/b/c',
<del> 'path': '/b/c'
<add> 'http://x.y.com+a/b/c': {
<add> href: 'http://x.y.com+a/b/c',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x.y.com+a',
<add> hostname: 'x.y.com+a',
<add> pathname: '/b/c',
<add> path: '/b/c'
<ide> },
<ide>
<ide> // an unexpected invalid char in the hostname.
<del> 'HtTp://x.y.cOm;a/b/c?d=e#f g<h>i' : {
<del> 'href': 'http://x.y.com/;a/b/c?d=e#f%20g%3Ch%3Ei',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x.y.com',
<del> 'hostname': 'x.y.com',
<del> 'pathname': ';a/b/c',
<del> 'search': '?d=e',
<del> 'query': 'd=e',
<del> 'hash': '#f%20g%3Ch%3Ei',
<del> 'path': ';a/b/c?d=e'
<add> 'HtTp://x.y.cOm;a/b/c?d=e#f g<h>i': {
<add> href: 'http://x.y.com/;a/b/c?d=e#f%20g%3Ch%3Ei',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x.y.com',
<add> hostname: 'x.y.com',
<add> pathname: ';a/b/c',
<add> search: '?d=e',
<add> query: 'd=e',
<add> hash: '#f%20g%3Ch%3Ei',
<add> path: ';a/b/c?d=e'
<ide> },
<ide>
<ide> // make sure that we don't accidentally lcast the path parts.
<del> 'HtTp://x.y.cOm;A/b/c?d=e#f g<h>i' : {
<del> 'href': 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x.y.com',
<del> 'hostname': 'x.y.com',
<del> 'pathname': ';A/b/c',
<del> 'search': '?d=e',
<del> 'query': 'd=e',
<del> 'hash': '#f%20g%3Ch%3Ei',
<del> 'path': ';A/b/c?d=e'
<add> 'HtTp://x.y.cOm;A/b/c?d=e#f g<h>i': {
<add> href: 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x.y.com',
<add> hostname: 'x.y.com',
<add> pathname: ';A/b/c',
<add> search: '?d=e',
<add> query: 'd=e',
<add> hash: '#f%20g%3Ch%3Ei',
<add> path: ';A/b/c?d=e'
<ide> },
<ide>
<ide> 'http://x...y...#p': {
<del> 'href': 'http://x...y.../#p',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x...y...',
<del> 'hostname': 'x...y...',
<del> 'hash': '#p',
<del> 'pathname': '/',
<del> 'path': '/'
<add> href: 'http://x...y.../#p',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x...y...',
<add> hostname: 'x...y...',
<add> hash: '#p',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'http://x/p/"quoted"': {
<del> 'href': 'http://x/p/%22quoted%22',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'x',
<del> 'hostname': 'x',
<del> 'pathname': '/p/%22quoted%22',
<del> 'path': '/p/%22quoted%22'
<add> href: 'http://x/p/%22quoted%22',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'x',
<add> hostname: 'x',
<add> pathname: '/p/%22quoted%22',
<add> path: '/p/%22quoted%22'
<ide> },
<ide>
<ide> '<http://goo.corn/bread> Is a URL!': {
<del> 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!',
<del> 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!',
<del> 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!'
<del> },
<del>
<del> 'http://www.narwhaljs.org/blog/categories?id=news' : {
<del> 'href': 'http://www.narwhaljs.org/blog/categories?id=news',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.narwhaljs.org',
<del> 'hostname': 'www.narwhaljs.org',
<del> 'search': '?id=news',
<del> 'query': 'id=news',
<del> 'pathname': '/blog/categories',
<del> 'path': '/blog/categories?id=news'
<del> },
<del>
<del> 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : {
<del> 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'mt0.google.com',
<del> 'hostname': 'mt0.google.com',
<del> 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s='
<del> },
<del>
<del> 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : {
<del> 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' +
<del> '&x=2&y=2&z=3&s=',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'mt0.google.com',
<del> 'hostname': 'mt0.google.com',
<del> 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'pathname': '/vt/lyrs=m@114',
<del> 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s='
<add> href: '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!',
<add> pathname: '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!',
<add> path: '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!'
<add> },
<add>
<add> 'http://www.narwhaljs.org/blog/categories?id=news': {
<add> href: 'http://www.narwhaljs.org/blog/categories?id=news',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.narwhaljs.org',
<add> hostname: 'www.narwhaljs.org',
<add> search: '?id=news',
<add> query: 'id=news',
<add> pathname: '/blog/categories',
<add> path: '/blog/categories?id=news'
<add> },
<add>
<add> 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=': {
<add> href: 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'mt0.google.com',
<add> hostname: 'mt0.google.com',
<add> pathname: '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=',
<add> path: '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s='
<add> },
<add>
<add> 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': {
<add> href: 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' +
<add> '&x=2&y=2&z=3&s=',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'mt0.google.com',
<add> hostname: 'mt0.google.com',
<add> search: '???&hl=en&src=api&x=2&y=2&z=3&s=',
<add> query: '??&hl=en&src=api&x=2&y=2&z=3&s=',
<add> pathname: '/vt/lyrs=m@114',
<add> path: '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s='
<ide> },
<ide>
<ide> 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=':
<ide> {
<del> 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' +
<del> '&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'mt0.google.com',
<del> 'auth': 'user:pass',
<del> 'hostname': 'mt0.google.com',
<del> 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=',
<del> 'pathname': '/vt/lyrs=m@114',
<del> 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s='
<add> href: 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' +
<add> '&hl=en&src=api&x=2&y=2&z=3&s=',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'mt0.google.com',
<add> auth: 'user:pass',
<add> hostname: 'mt0.google.com',
<add> search: '???&hl=en&src=api&x=2&y=2&z=3&s=',
<add> query: '??&hl=en&src=api&x=2&y=2&z=3&s=',
<add> pathname: '/vt/lyrs=m@114',
<add> path: '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s='
<ide> },
<ide>
<del> 'file:///etc/passwd' : {
<del> 'href': 'file:///etc/passwd',
<del> 'slashes': true,
<del> 'protocol': 'file:',
<del> 'pathname': '/etc/passwd',
<del> 'hostname': '',
<del> 'host': '',
<del> 'path': '/etc/passwd'
<del> },
<del>
<del> 'file://localhost/etc/passwd' : {
<del> 'href': 'file://localhost/etc/passwd',
<del> 'protocol': 'file:',
<del> 'slashes': true,
<del> 'pathname': '/etc/passwd',
<del> 'hostname': 'localhost',
<del> 'host': 'localhost',
<del> 'path': '/etc/passwd'
<del> },
<del>
<del> 'file://foo/etc/passwd' : {
<del> 'href': 'file://foo/etc/passwd',
<del> 'protocol': 'file:',
<del> 'slashes': true,
<del> 'pathname': '/etc/passwd',
<del> 'hostname': 'foo',
<del> 'host': 'foo',
<del> 'path': '/etc/passwd'
<del> },
<del>
<del> 'file:///etc/node/' : {
<del> 'href': 'file:///etc/node/',
<del> 'slashes': true,
<del> 'protocol': 'file:',
<del> 'pathname': '/etc/node/',
<del> 'hostname': '',
<del> 'host': '',
<del> 'path': '/etc/node/'
<del> },
<del>
<del> 'file://localhost/etc/node/' : {
<del> 'href': 'file://localhost/etc/node/',
<del> 'protocol': 'file:',
<del> 'slashes': true,
<del> 'pathname': '/etc/node/',
<del> 'hostname': 'localhost',
<del> 'host': 'localhost',
<del> 'path': '/etc/node/'
<del> },
<del>
<del> 'file://foo/etc/node/' : {
<del> 'href': 'file://foo/etc/node/',
<del> 'protocol': 'file:',
<del> 'slashes': true,
<del> 'pathname': '/etc/node/',
<del> 'hostname': 'foo',
<del> 'host': 'foo',
<del> 'path': '/etc/node/'
<del> },
<del>
<del> 'http:/baz/../foo/bar' : {
<del> 'href': 'http:/baz/../foo/bar',
<del> 'protocol': 'http:',
<del> 'pathname': '/baz/../foo/bar',
<del> 'path': '/baz/../foo/bar'
<del> },
<del>
<del> 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : {
<del> 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com:8000',
<del> 'auth': 'user:pass',
<del> 'port': '8000',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?baz=quux',
<del> 'query': 'baz=quux',
<del> 'pathname': '/foo/bar',
<del> 'path': '/foo/bar?baz=quux'
<del> },
<del>
<del> '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : {
<del> 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag',
<del> 'slashes': true,
<del> 'host': 'example.com:8000',
<del> 'auth': 'user:pass',
<del> 'port': '8000',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?baz=quux',
<del> 'query': 'baz=quux',
<del> 'pathname': '/foo/bar',
<del> 'path': '/foo/bar?baz=quux'
<del> },
<del>
<del> '/foo/bar?baz=quux#frag' : {
<del> 'href': '/foo/bar?baz=quux#frag',
<del> 'hash': '#frag',
<del> 'search': '?baz=quux',
<del> 'query': 'baz=quux',
<del> 'pathname': '/foo/bar',
<del> 'path': '/foo/bar?baz=quux'
<del> },
<del>
<del> 'http:/foo/bar?baz=quux#frag' : {
<del> 'href': 'http:/foo/bar?baz=quux#frag',
<del> 'protocol': 'http:',
<del> 'hash': '#frag',
<del> 'search': '?baz=quux',
<del> 'query': 'baz=quux',
<del> 'pathname': '/foo/bar',
<del> 'path': '/foo/bar?baz=quux'
<del> },
<del>
<del> 'mailto:foo@bar.com?subject=hello' : {
<del> 'href': 'mailto:foo@bar.com?subject=hello',
<del> 'protocol': 'mailto:',
<del> 'host': 'bar.com',
<del> 'auth' : 'foo',
<del> 'hostname' : 'bar.com',
<del> 'search': '?subject=hello',
<del> 'query': 'subject=hello',
<del> 'path': '?subject=hello'
<del> },
<del>
<del> 'javascript:alert(\'hello\');' : {
<del> 'href': 'javascript:alert(\'hello\');',
<del> 'protocol': 'javascript:',
<del> 'pathname': 'alert(\'hello\');',
<del> 'path': 'alert(\'hello\');'
<del> },
<del>
<del> 'xmpp:isaacschlueter@jabber.org' : {
<del> 'href': 'xmpp:isaacschlueter@jabber.org',
<del> 'protocol': 'xmpp:',
<del> 'host': 'jabber.org',
<del> 'auth': 'isaacschlueter',
<del> 'hostname': 'jabber.org'
<del> },
<del>
<del> 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : {
<del> 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar',
<del> 'protocol' : 'http:',
<del> 'slashes': true,
<del> 'host' : '127.0.0.1:8080',
<del> 'auth' : 'atpass:foo@bar',
<del> 'hostname' : '127.0.0.1',
<del> 'port' : '8080',
<del> 'pathname': '/path',
<del> 'search' : '?search=foo',
<del> 'query' : 'search=foo',
<del> 'hash' : '#bar',
<del> 'path': '/path?search=foo'
<add> 'file:///etc/passwd': {
<add> href: 'file:///etc/passwd',
<add> slashes: true,
<add> protocol: 'file:',
<add> pathname: '/etc/passwd',
<add> hostname: '',
<add> host: '',
<add> path: '/etc/passwd'
<add> },
<add>
<add> 'file://localhost/etc/passwd': {
<add> href: 'file://localhost/etc/passwd',
<add> protocol: 'file:',
<add> slashes: true,
<add> pathname: '/etc/passwd',
<add> hostname: 'localhost',
<add> host: 'localhost',
<add> path: '/etc/passwd'
<add> },
<add>
<add> 'file://foo/etc/passwd': {
<add> href: 'file://foo/etc/passwd',
<add> protocol: 'file:',
<add> slashes: true,
<add> pathname: '/etc/passwd',
<add> hostname: 'foo',
<add> host: 'foo',
<add> path: '/etc/passwd'
<add> },
<add>
<add> 'file:///etc/node/': {
<add> href: 'file:///etc/node/',
<add> slashes: true,
<add> protocol: 'file:',
<add> pathname: '/etc/node/',
<add> hostname: '',
<add> host: '',
<add> path: '/etc/node/'
<add> },
<add>
<add> 'file://localhost/etc/node/': {
<add> href: 'file://localhost/etc/node/',
<add> protocol: 'file:',
<add> slashes: true,
<add> pathname: '/etc/node/',
<add> hostname: 'localhost',
<add> host: 'localhost',
<add> path: '/etc/node/'
<add> },
<add>
<add> 'file://foo/etc/node/': {
<add> href: 'file://foo/etc/node/',
<add> protocol: 'file:',
<add> slashes: true,
<add> pathname: '/etc/node/',
<add> hostname: 'foo',
<add> host: 'foo',
<add> path: '/etc/node/'
<add> },
<add>
<add> 'http:/baz/../foo/bar': {
<add> href: 'http:/baz/../foo/bar',
<add> protocol: 'http:',
<add> pathname: '/baz/../foo/bar',
<add> path: '/baz/../foo/bar'
<add> },
<add>
<add> 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag': {
<add> href: 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com:8000',
<add> auth: 'user:pass',
<add> port: '8000',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?baz=quux',
<add> query: 'baz=quux',
<add> pathname: '/foo/bar',
<add> path: '/foo/bar?baz=quux'
<add> },
<add>
<add> '//user:pass@example.com:8000/foo/bar?baz=quux#frag': {
<add> href: '//user:pass@example.com:8000/foo/bar?baz=quux#frag',
<add> slashes: true,
<add> host: 'example.com:8000',
<add> auth: 'user:pass',
<add> port: '8000',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?baz=quux',
<add> query: 'baz=quux',
<add> pathname: '/foo/bar',
<add> path: '/foo/bar?baz=quux'
<add> },
<add>
<add> '/foo/bar?baz=quux#frag': {
<add> href: '/foo/bar?baz=quux#frag',
<add> hash: '#frag',
<add> search: '?baz=quux',
<add> query: 'baz=quux',
<add> pathname: '/foo/bar',
<add> path: '/foo/bar?baz=quux'
<add> },
<add>
<add> 'http:/foo/bar?baz=quux#frag': {
<add> href: 'http:/foo/bar?baz=quux#frag',
<add> protocol: 'http:',
<add> hash: '#frag',
<add> search: '?baz=quux',
<add> query: 'baz=quux',
<add> pathname: '/foo/bar',
<add> path: '/foo/bar?baz=quux'
<add> },
<add>
<add> 'mailto:foo@bar.com?subject=hello': {
<add> href: 'mailto:foo@bar.com?subject=hello',
<add> protocol: 'mailto:',
<add> host: 'bar.com',
<add> auth: 'foo',
<add> hostname: 'bar.com',
<add> search: '?subject=hello',
<add> query: 'subject=hello',
<add> path: '?subject=hello'
<add> },
<add>
<add> 'javascript:alert(\'hello\');': {
<add> href: 'javascript:alert(\'hello\');',
<add> protocol: 'javascript:',
<add> pathname: 'alert(\'hello\');',
<add> path: 'alert(\'hello\');'
<add> },
<add>
<add> 'xmpp:isaacschlueter@jabber.org': {
<add> href: 'xmpp:isaacschlueter@jabber.org',
<add> protocol: 'xmpp:',
<add> host: 'jabber.org',
<add> auth: 'isaacschlueter',
<add> hostname: 'jabber.org'
<add> },
<add>
<add> 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar': {
<add> href: 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: '127.0.0.1:8080',
<add> auth: 'atpass:foo@bar',
<add> hostname: '127.0.0.1',
<add> port: '8080',
<add> pathname: '/path',
<add> search: '?search=foo',
<add> query: 'search=foo',
<add> hash: '#bar',
<add> path: '/path?search=foo'
<ide> },
<ide>
<ide> 'svn+ssh://foo/bar': {
<del> 'href': 'svn+ssh://foo/bar',
<del> 'host': 'foo',
<del> 'hostname': 'foo',
<del> 'protocol': 'svn+ssh:',
<del> 'pathname': '/bar',
<del> 'path': '/bar',
<del> 'slashes': true
<add> href: 'svn+ssh://foo/bar',
<add> host: 'foo',
<add> hostname: 'foo',
<add> protocol: 'svn+ssh:',
<add> pathname: '/bar',
<add> path: '/bar',
<add> slashes: true
<ide> },
<ide>
<ide> 'dash-test://foo/bar': {
<del> 'href': 'dash-test://foo/bar',
<del> 'host': 'foo',
<del> 'hostname': 'foo',
<del> 'protocol': 'dash-test:',
<del> 'pathname': '/bar',
<del> 'path': '/bar',
<del> 'slashes': true
<add> href: 'dash-test://foo/bar',
<add> host: 'foo',
<add> hostname: 'foo',
<add> protocol: 'dash-test:',
<add> pathname: '/bar',
<add> path: '/bar',
<add> slashes: true
<ide> },
<ide>
<ide> 'dash-test:foo/bar': {
<del> 'href': 'dash-test:foo/bar',
<del> 'host': 'foo',
<del> 'hostname': 'foo',
<del> 'protocol': 'dash-test:',
<del> 'pathname': '/bar',
<del> 'path': '/bar'
<add> href: 'dash-test:foo/bar',
<add> host: 'foo',
<add> hostname: 'foo',
<add> protocol: 'dash-test:',
<add> pathname: '/bar',
<add> path: '/bar'
<ide> },
<ide>
<ide> 'dot.test://foo/bar': {
<del> 'href': 'dot.test://foo/bar',
<del> 'host': 'foo',
<del> 'hostname': 'foo',
<del> 'protocol': 'dot.test:',
<del> 'pathname': '/bar',
<del> 'path': '/bar',
<del> 'slashes': true
<add> href: 'dot.test://foo/bar',
<add> host: 'foo',
<add> hostname: 'foo',
<add> protocol: 'dot.test:',
<add> pathname: '/bar',
<add> path: '/bar',
<add> slashes: true
<ide> },
<ide>
<ide> 'dot.test:foo/bar': {
<del> 'href': 'dot.test:foo/bar',
<del> 'host': 'foo',
<del> 'hostname': 'foo',
<del> 'protocol': 'dot.test:',
<del> 'pathname': '/bar',
<del> 'path': '/bar'
<add> href: 'dot.test:foo/bar',
<add> host: 'foo',
<add> hostname: 'foo',
<add> protocol: 'dot.test:',
<add> pathname: '/bar',
<add> path: '/bar'
<ide> },
<ide>
<ide> // IDNA tests
<del> 'http://www.日本語.com/' : {
<del> 'href': 'http://www.xn--wgv71a119e.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.xn--wgv71a119e.com',
<del> 'hostname': 'www.xn--wgv71a119e.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://example.Bücher.com/' : {
<del> 'href': 'http://example.xn--bcher-kva.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.xn--bcher-kva.com',
<del> 'hostname': 'example.xn--bcher-kva.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://www.Äffchen.com/' : {
<del> 'href': 'http://www.xn--ffchen-9ta.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.xn--ffchen-9ta.com',
<del> 'hostname': 'www.xn--ffchen-9ta.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://www.Äffchen.cOm;A/b/c?d=e#f g<h>i' : {
<del> 'href': 'http://www.xn--ffchen-9ta.com/;A/b/c?d=e#f%20g%3Ch%3Ei',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'www.xn--ffchen-9ta.com',
<del> 'hostname': 'www.xn--ffchen-9ta.com',
<del> 'pathname': ';A/b/c',
<del> 'search': '?d=e',
<del> 'query': 'd=e',
<del> 'hash': '#f%20g%3Ch%3Ei',
<del> 'path': ';A/b/c?d=e'
<del> },
<del>
<del> 'http://SÉLIER.COM/' : {
<del> 'href': 'http://xn--slier-bsa.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'xn--slier-bsa.com',
<del> 'hostname': 'xn--slier-bsa.com',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://ليهمابتكلموشعربي؟.ي؟/' : {
<del> 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f',
<del> 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f',
<del> 'pathname': '/',
<del> 'path': '/'
<del> },
<del>
<del> 'http://➡.ws/➡' : {
<del> 'href': 'http://xn--hgi.ws/➡',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'xn--hgi.ws',
<del> 'hostname': 'xn--hgi.ws',
<del> 'pathname': '/➡',
<del> 'path': '/➡'
<add> 'http://www.日本語.com/': {
<add> href: 'http://www.xn--wgv71a119e.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.xn--wgv71a119e.com',
<add> hostname: 'www.xn--wgv71a119e.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://example.Bücher.com/': {
<add> href: 'http://example.xn--bcher-kva.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.xn--bcher-kva.com',
<add> hostname: 'example.xn--bcher-kva.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://www.Äffchen.com/': {
<add> href: 'http://www.xn--ffchen-9ta.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.xn--ffchen-9ta.com',
<add> hostname: 'www.xn--ffchen-9ta.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://www.Äffchen.cOm;A/b/c?d=e#f g<h>i': {
<add> href: 'http://www.xn--ffchen-9ta.com/;A/b/c?d=e#f%20g%3Ch%3Ei',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'www.xn--ffchen-9ta.com',
<add> hostname: 'www.xn--ffchen-9ta.com',
<add> pathname: ';A/b/c',
<add> search: '?d=e',
<add> query: 'd=e',
<add> hash: '#f%20g%3Ch%3Ei',
<add> path: ';A/b/c?d=e'
<add> },
<add>
<add> 'http://SÉLIER.COM/': {
<add> href: 'http://xn--slier-bsa.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'xn--slier-bsa.com',
<add> hostname: 'xn--slier-bsa.com',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://ليهمابتكلموشعربي؟.ي؟/': {
<add> href: 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f',
<add> hostname: 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f',
<add> pathname: '/',
<add> path: '/'
<add> },
<add>
<add> 'http://➡.ws/➡': {
<add> href: 'http://xn--hgi.ws/➡',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'xn--hgi.ws',
<add> hostname: 'xn--hgi.ws',
<add> pathname: '/➡',
<add> path: '/➡'
<ide> },
<ide>
<ide> 'http://bucket_name.s3.amazonaws.com/image.jpg': {
<ide> var parseTests = {
<ide> hostname: 'bucket_name.s3.amazonaws.com',
<ide> pathname: '/image.jpg',
<ide> href: 'http://bucket_name.s3.amazonaws.com/image.jpg',
<del> 'path': '/image.jpg'
<add> path: '/image.jpg'
<ide> },
<ide>
<ide> 'git+http://github.com/joyent/node.git': {
<ide> var parseTests = {
<ide> //be parse into auth@hostname, but here there is no
<ide> //way to make it work in url.parse, I add the test to be explicit
<ide> 'local1@domain1': {
<del> 'pathname': 'local1@domain1',
<del> 'path': 'local1@domain1',
<del> 'href': 'local1@domain1'
<add> pathname: 'local1@domain1',
<add> path: 'local1@domain1',
<add> href: 'local1@domain1'
<ide> },
<ide>
<ide> //While this may seem counter-intuitive, a browser will parse
<ide> //<a href='www.google.com'> as a path.
<del> 'www.example.com' : {
<del> 'href': 'www.example.com',
<del> 'pathname': 'www.example.com',
<del> 'path': 'www.example.com'
<add> 'www.example.com': {
<add> href: 'www.example.com',
<add> pathname: 'www.example.com',
<add> path: 'www.example.com'
<ide> },
<ide>
<ide> // ipv6 support
<ide> '[fe80::1]': {
<del> 'href': '[fe80::1]',
<del> 'pathname': '[fe80::1]',
<del> 'path': '[fe80::1]'
<add> href: '[fe80::1]',
<add> pathname: '[fe80::1]',
<add> path: '[fe80::1]'
<ide> },
<ide>
<ide> 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': {
<del> 'protocol': 'coap:',
<del> 'slashes': true,
<del> 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]',
<del> 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210',
<del> 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/',
<del> 'pathname': '/',
<del> 'path': '/'
<add> protocol: 'coap:',
<add> slashes: true,
<add> host: '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]',
<add> hostname: 'fedc:ba98:7654:3210:fedc:ba98:7654:3210',
<add> href: 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': {
<del> 'protocol': 'coap:',
<del> 'slashes': true,
<del> 'host': '[1080:0:0:0:8:800:200c:417a]:61616',
<del> 'port': '61616',
<del> 'hostname': '1080:0:0:0:8:800:200c:417a',
<del> 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/',
<del> 'pathname': '/',
<del> 'path': '/'
<add> protocol: 'coap:',
<add> slashes: true,
<add> host: '[1080:0:0:0:8:800:200c:417a]:61616',
<add> port: '61616',
<add> hostname: '1080:0:0:0:8:800:200c:417a',
<add> href: 'coap://[1080:0:0:0:8:800:200c:417a]:61616/',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'http://user:password@[3ffe:2a00:100:7031::1]:8080': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:password',
<del> 'host': '[3ffe:2a00:100:7031::1]:8080',
<del> 'port': '8080',
<del> 'hostname': '3ffe:2a00:100:7031::1',
<del> 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/',
<del> 'pathname': '/',
<del> 'path': '/'
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:password',
<add> host: '[3ffe:2a00:100:7031::1]:8080',
<add> port: '8080',
<add> hostname: '3ffe:2a00:100:7031::1',
<add> href: 'http://user:password@[3ffe:2a00:100:7031::1]:8080/',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': {
<del> 'protocol': 'coap:',
<del> 'slashes': true,
<del> 'auth': 'u:p',
<del> 'host': '[::192.9.5.5]:61616',
<del> 'port': '61616',
<del> 'hostname': '::192.9.5.5',
<del> 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature',
<del> 'search': '?n=Temperature',
<del> 'query': 'n=Temperature',
<del> 'pathname': '/.well-known/r',
<del> 'path': '/.well-known/r?n=Temperature'
<add> protocol: 'coap:',
<add> slashes: true,
<add> auth: 'u:p',
<add> host: '[::192.9.5.5]:61616',
<add> port: '61616',
<add> hostname: '::192.9.5.5',
<add> href: 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature',
<add> search: '?n=Temperature',
<add> query: 'n=Temperature',
<add> pathname: '/.well-known/r',
<add> path: '/.well-known/r?n=Temperature'
<ide> },
<ide>
<ide> // empty port
<ide> 'http://example.com:': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'href': 'http://example.com/',
<del> 'pathname': '/',
<del> 'path': '/'
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> href: 'http://example.com/',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'http://example.com:/a/b.html': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'href': 'http://example.com/a/b.html',
<del> 'pathname': '/a/b.html',
<del> 'path': '/a/b.html'
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> href: 'http://example.com/a/b.html',
<add> pathname: '/a/b.html',
<add> path: '/a/b.html'
<ide> },
<ide>
<ide> 'http://example.com:?a=b': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'href': 'http://example.com/?a=b',
<del> 'search': '?a=b',
<del> 'query': 'a=b',
<del> 'pathname': '/',
<del> 'path': '/?a=b'
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> href: 'http://example.com/?a=b',
<add> search: '?a=b',
<add> query: 'a=b',
<add> pathname: '/',
<add> path: '/?a=b'
<ide> },
<ide>
<ide> 'http://example.com:#abc': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'href': 'http://example.com/#abc',
<del> 'hash': '#abc',
<del> 'pathname': '/',
<del> 'path': '/'
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> href: 'http://example.com/#abc',
<add> hash: '#abc',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide>
<ide> 'http://[fe80::1]:/a/b?a=b#abc': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': '[fe80::1]',
<del> 'hostname': 'fe80::1',
<del> 'href': 'http://[fe80::1]/a/b?a=b#abc',
<del> 'search': '?a=b',
<del> 'query': 'a=b',
<del> 'hash': '#abc',
<del> 'pathname': '/a/b',
<del> 'path': '/a/b?a=b'
<add> protocol: 'http:',
<add> slashes: true,
<add> host: '[fe80::1]',
<add> hostname: 'fe80::1',
<add> href: 'http://[fe80::1]/a/b?a=b#abc',
<add> search: '?a=b',
<add> query: 'a=b',
<add> hash: '#abc',
<add> pathname: '/a/b',
<add> path: '/a/b?a=b'
<ide> },
<ide>
<ide> 'http://-lovemonsterz.tumblr.com/rss': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': '-lovemonsterz.tumblr.com',
<del> 'hostname': '-lovemonsterz.tumblr.com',
<del> 'href': 'http://-lovemonsterz.tumblr.com/rss',
<del> 'pathname': '/rss',
<del> 'path': '/rss',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: '-lovemonsterz.tumblr.com',
<add> hostname: '-lovemonsterz.tumblr.com',
<add> href: 'http://-lovemonsterz.tumblr.com/rss',
<add> pathname: '/rss',
<add> path: '/rss',
<ide> },
<ide>
<ide> 'http://-lovemonsterz.tumblr.com:80/rss': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'port': '80',
<del> 'host': '-lovemonsterz.tumblr.com:80',
<del> 'hostname': '-lovemonsterz.tumblr.com',
<del> 'href': 'http://-lovemonsterz.tumblr.com:80/rss',
<del> 'pathname': '/rss',
<del> 'path': '/rss',
<add> protocol: 'http:',
<add> slashes: true,
<add> port: '80',
<add> host: '-lovemonsterz.tumblr.com:80',
<add> hostname: '-lovemonsterz.tumblr.com',
<add> href: 'http://-lovemonsterz.tumblr.com:80/rss',
<add> pathname: '/rss',
<add> path: '/rss',
<ide> },
<ide>
<ide> 'http://user:pass@-lovemonsterz.tumblr.com/rss': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pass',
<del> 'host': '-lovemonsterz.tumblr.com',
<del> 'hostname': '-lovemonsterz.tumblr.com',
<del> 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss',
<del> 'pathname': '/rss',
<del> 'path': '/rss',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pass',
<add> host: '-lovemonsterz.tumblr.com',
<add> hostname: '-lovemonsterz.tumblr.com',
<add> href: 'http://user:pass@-lovemonsterz.tumblr.com/rss',
<add> pathname: '/rss',
<add> path: '/rss',
<ide> },
<ide>
<ide> 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pass',
<del> 'port': '80',
<del> 'host': '-lovemonsterz.tumblr.com:80',
<del> 'hostname': '-lovemonsterz.tumblr.com',
<del> 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss',
<del> 'pathname': '/rss',
<del> 'path': '/rss',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pass',
<add> port: '80',
<add> host: '-lovemonsterz.tumblr.com:80',
<add> hostname: '-lovemonsterz.tumblr.com',
<add> href: 'http://user:pass@-lovemonsterz.tumblr.com:80/rss',
<add> pathname: '/rss',
<add> path: '/rss',
<ide> },
<ide>
<ide> 'http://_jabber._tcp.google.com/test': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': '_jabber._tcp.google.com',
<del> 'hostname': '_jabber._tcp.google.com',
<del> 'href': 'http://_jabber._tcp.google.com/test',
<del> 'pathname': '/test',
<del> 'path': '/test',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: '_jabber._tcp.google.com',
<add> hostname: '_jabber._tcp.google.com',
<add> href: 'http://_jabber._tcp.google.com/test',
<add> pathname: '/test',
<add> path: '/test',
<ide> },
<ide>
<ide> 'http://user:pass@_jabber._tcp.google.com/test': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pass',
<del> 'host': '_jabber._tcp.google.com',
<del> 'hostname': '_jabber._tcp.google.com',
<del> 'href': 'http://user:pass@_jabber._tcp.google.com/test',
<del> 'pathname': '/test',
<del> 'path': '/test',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pass',
<add> host: '_jabber._tcp.google.com',
<add> hostname: '_jabber._tcp.google.com',
<add> href: 'http://user:pass@_jabber._tcp.google.com/test',
<add> pathname: '/test',
<add> path: '/test',
<ide> },
<ide>
<ide> 'http://_jabber._tcp.google.com:80/test': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'port': '80',
<del> 'host': '_jabber._tcp.google.com:80',
<del> 'hostname': '_jabber._tcp.google.com',
<del> 'href': 'http://_jabber._tcp.google.com:80/test',
<del> 'pathname': '/test',
<del> 'path': '/test',
<add> protocol: 'http:',
<add> slashes: true,
<add> port: '80',
<add> host: '_jabber._tcp.google.com:80',
<add> hostname: '_jabber._tcp.google.com',
<add> href: 'http://_jabber._tcp.google.com:80/test',
<add> pathname: '/test',
<add> path: '/test',
<ide> },
<ide>
<ide> 'http://user:pass@_jabber._tcp.google.com:80/test': {
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'auth': 'user:pass',
<del> 'port': '80',
<del> 'host': '_jabber._tcp.google.com:80',
<del> 'hostname': '_jabber._tcp.google.com',
<del> 'href': 'http://user:pass@_jabber._tcp.google.com:80/test',
<del> 'pathname': '/test',
<del> 'path': '/test',
<add> protocol: 'http:',
<add> slashes: true,
<add> auth: 'user:pass',
<add> port: '80',
<add> host: '_jabber._tcp.google.com:80',
<add> hostname: '_jabber._tcp.google.com',
<add> href: 'http://user:pass@_jabber._tcp.google.com:80/test',
<add> pathname: '/test',
<add> path: '/test',
<ide> },
<ide>
<ide> 'http://x:1/\' <>"`/{}|\\^~`/': {
<ide> for (var u in parseTests) {
<ide> }
<ide>
<ide> var parseTestsWithQueryString = {
<del> '/foo/bar?baz=quux#frag' : {
<del> 'href': '/foo/bar?baz=quux#frag',
<del> 'hash': '#frag',
<del> 'search': '?baz=quux',
<del> 'query': {
<del> 'baz': 'quux'
<add> '/foo/bar?baz=quux#frag': {
<add> href: '/foo/bar?baz=quux#frag',
<add> hash: '#frag',
<add> search: '?baz=quux',
<add> query: {
<add> baz: 'quux'
<ide> },
<del> 'pathname': '/foo/bar',
<del> 'path': '/foo/bar?baz=quux'
<del> },
<del> 'http://example.com' : {
<del> 'href': 'http://example.com/',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'query': {},
<del> 'search': '',
<del> 'pathname': '/',
<del> 'path': '/'
<add> pathname: '/foo/bar',
<add> path: '/foo/bar?baz=quux'
<add> },
<add> 'http://example.com': {
<add> href: 'http://example.com/',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> query: {},
<add> search: '',
<add> pathname: '/',
<add> path: '/'
<ide> },
<ide> '/example': {
<ide> protocol: null,
<ide> for (var u in parseTestsWithQueryString) {
<ide> // some extra formatting tests, just to verify
<ide> // that it'll format slightly wonky content to a valid url.
<ide> var formatTests = {
<del> 'http://example.com?' : {
<del> 'href': 'http://example.com/?',
<del> 'protocol': 'http:',
<del> 'slashes': true,
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'search': '?',
<del> 'query': {},
<del> 'pathname': '/'
<del> },
<del> 'http://example.com?foo=bar#frag' : {
<del> 'href': 'http://example.com/?foo=bar#frag',
<del> 'protocol': 'http:',
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?foo=bar',
<del> 'query': 'foo=bar',
<del> 'pathname': '/'
<del> },
<del> 'http://example.com?foo=@bar#frag' : {
<del> 'href': 'http://example.com/?foo=@bar#frag',
<del> 'protocol': 'http:',
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?foo=@bar',
<del> 'query': 'foo=@bar',
<del> 'pathname': '/'
<del> },
<del> 'http://example.com?foo=/bar/#frag' : {
<del> 'href': 'http://example.com/?foo=/bar/#frag',
<del> 'protocol': 'http:',
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?foo=/bar/',
<del> 'query': 'foo=/bar/',
<del> 'pathname': '/'
<del> },
<del> 'http://example.com?foo=?bar/#frag' : {
<del> 'href': 'http://example.com/?foo=?bar/#frag',
<del> 'protocol': 'http:',
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag',
<del> 'search': '?foo=?bar/',
<del> 'query': 'foo=?bar/',
<del> 'pathname': '/'
<del> },
<del> 'http://example.com#frag=?bar/#frag' : {
<del> 'href': 'http://example.com/#frag=?bar/#frag',
<del> 'protocol': 'http:',
<del> 'host': 'example.com',
<del> 'hostname': 'example.com',
<del> 'hash': '#frag=?bar/#frag',
<del> 'pathname': '/'
<del> },
<del> 'http://google.com" onload="alert(42)/' : {
<del> 'href': 'http://google.com/%22%20onload=%22alert(42)/',
<del> 'protocol': 'http:',
<del> 'host': 'google.com',
<del> 'pathname': '/%22%20onload=%22alert(42)/'
<del> },
<del> 'http://a.com/a/b/c?s#h' : {
<del> 'href': 'http://a.com/a/b/c?s#h',
<del> 'protocol': 'http',
<del> 'host': 'a.com',
<del> 'pathname': 'a/b/c',
<del> 'hash': 'h',
<del> 'search': 's'
<del> },
<del> 'xmpp:isaacschlueter@jabber.org' : {
<del> 'href': 'xmpp:isaacschlueter@jabber.org',
<del> 'protocol': 'xmpp:',
<del> 'host': 'jabber.org',
<del> 'auth': 'isaacschlueter',
<del> 'hostname': 'jabber.org'
<del> },
<del> 'http://atpass:foo%40bar@127.0.0.1/' : {
<del> 'href': 'http://atpass:foo%40bar@127.0.0.1/',
<del> 'auth': 'atpass:foo@bar',
<del> 'hostname': '127.0.0.1',
<del> 'protocol': 'http:',
<del> 'pathname': '/'
<del> },
<del> 'http://atslash%2F%40:%2F%40@foo/' : {
<del> 'href': 'http://atslash%2F%40:%2F%40@foo/',
<del> 'auth': 'atslash/@:/@',
<del> 'hostname': 'foo',
<del> 'protocol': 'http:',
<del> 'pathname': '/'
<add> 'http://example.com?': {
<add> href: 'http://example.com/?',
<add> protocol: 'http:',
<add> slashes: true,
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> search: '?',
<add> query: {},
<add> pathname: '/'
<add> },
<add> 'http://example.com?foo=bar#frag': {
<add> href: 'http://example.com/?foo=bar#frag',
<add> protocol: 'http:',
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?foo=bar',
<add> query: 'foo=bar',
<add> pathname: '/'
<add> },
<add> 'http://example.com?foo=@bar#frag': {
<add> href: 'http://example.com/?foo=@bar#frag',
<add> protocol: 'http:',
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?foo=@bar',
<add> query: 'foo=@bar',
<add> pathname: '/'
<add> },
<add> 'http://example.com?foo=/bar/#frag': {
<add> href: 'http://example.com/?foo=/bar/#frag',
<add> protocol: 'http:',
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?foo=/bar/',
<add> query: 'foo=/bar/',
<add> pathname: '/'
<add> },
<add> 'http://example.com?foo=?bar/#frag': {
<add> href: 'http://example.com/?foo=?bar/#frag',
<add> protocol: 'http:',
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> hash: '#frag',
<add> search: '?foo=?bar/',
<add> query: 'foo=?bar/',
<add> pathname: '/'
<add> },
<add> 'http://example.com#frag=?bar/#frag': {
<add> href: 'http://example.com/#frag=?bar/#frag',
<add> protocol: 'http:',
<add> host: 'example.com',
<add> hostname: 'example.com',
<add> hash: '#frag=?bar/#frag',
<add> pathname: '/'
<add> },
<add> 'http://google.com" onload="alert(42)/': {
<add> href: 'http://google.com/%22%20onload=%22alert(42)/',
<add> protocol: 'http:',
<add> host: 'google.com',
<add> pathname: '/%22%20onload=%22alert(42)/'
<add> },
<add> 'http://a.com/a/b/c?s#h': {
<add> href: 'http://a.com/a/b/c?s#h',
<add> protocol: 'http',
<add> host: 'a.com',
<add> pathname: 'a/b/c',
<add> hash: 'h',
<add> search: 's'
<add> },
<add> 'xmpp:isaacschlueter@jabber.org': {
<add> href: 'xmpp:isaacschlueter@jabber.org',
<add> protocol: 'xmpp:',
<add> host: 'jabber.org',
<add> auth: 'isaacschlueter',
<add> hostname: 'jabber.org'
<add> },
<add> 'http://atpass:foo%40bar@127.0.0.1/': {
<add> href: 'http://atpass:foo%40bar@127.0.0.1/',
<add> auth: 'atpass:foo@bar',
<add> hostname: '127.0.0.1',
<add> protocol: 'http:',
<add> pathname: '/'
<add> },
<add> 'http://atslash%2F%40:%2F%40@foo/': {
<add> href: 'http://atslash%2F%40:%2F%40@foo/',
<add> auth: 'atslash/@:/@',
<add> hostname: 'foo',
<add> protocol: 'http:',
<add> pathname: '/'
<ide> },
<ide> 'svn+ssh://foo/bar': {
<del> 'href': 'svn+ssh://foo/bar',
<del> 'hostname': 'foo',
<del> 'protocol': 'svn+ssh:',
<del> 'pathname': '/bar',
<del> 'slashes': true
<add> href: 'svn+ssh://foo/bar',
<add> hostname: 'foo',
<add> protocol: 'svn+ssh:',
<add> pathname: '/bar',
<add> slashes: true
<ide> },
<ide> 'dash-test://foo/bar': {
<del> 'href': 'dash-test://foo/bar',
<del> 'hostname': 'foo',
<del> 'protocol': 'dash-test:',
<del> 'pathname': '/bar',
<del> 'slashes': true
<add> href: 'dash-test://foo/bar',
<add> hostname: 'foo',
<add> protocol: 'dash-test:',
<add> pathname: '/bar',
<add> slashes: true
<ide> },
<ide> 'dash-test:foo/bar': {
<del> 'href': 'dash-test:foo/bar',
<del> 'hostname': 'foo',
<del> 'protocol': 'dash-test:',
<del> 'pathname': '/bar'
<add> href: 'dash-test:foo/bar',
<add> hostname: 'foo',
<add> protocol: 'dash-test:',
<add> pathname: '/bar'
<ide> },
<ide> 'dot.test://foo/bar': {
<del> 'href': 'dot.test://foo/bar',
<del> 'hostname': 'foo',
<del> 'protocol': 'dot.test:',
<del> 'pathname': '/bar',
<del> 'slashes': true
<add> href: 'dot.test://foo/bar',
<add> hostname: 'foo',
<add> protocol: 'dot.test:',
<add> pathname: '/bar',
<add> slashes: true
<ide> },
<ide> 'dot.test:foo/bar': {
<del> 'href': 'dot.test:foo/bar',
<del> 'hostname': 'foo',
<del> 'protocol': 'dot.test:',
<del> 'pathname': '/bar'
<add> href: 'dot.test:foo/bar',
<add> hostname: 'foo',
<add> protocol: 'dot.test:',
<add> pathname: '/bar'
<ide> },
<ide> // ipv6 support
<ide> 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': {
<del> 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature',
<del> 'protocol': 'coap:',
<del> 'auth': 'u:p',
<del> 'hostname': '::1',
<del> 'port': '61616',
<del> 'pathname': '/.well-known/r',
<del> 'search': 'n=Temperature'
<add> href: 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature',
<add> protocol: 'coap:',
<add> auth: 'u:p',
<add> hostname: '::1',
<add> port: '61616',
<add> pathname: '/.well-known/r',
<add> search: 'n=Temperature'
<ide> },
<ide> 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': {
<del> 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton',
<del> 'protocol': 'coap',
<del> 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616',
<del> 'pathname': '/s/stopButton'
<add> href: 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton',
<add> protocol: 'coap',
<add> host: '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616',
<add> pathname: '/s/stopButton'
<ide> },
<ide>
<ide> // encode context-specific delimiters in path and query, but do not touch
<ide> // other non-delimiter chars like `%`.
<ide> // <https://github.com/joyent/node/issues/4082>
<ide>
<ide> // `#`,`?` in path
<del> '/path/to/%%23%3F+=&.txt?foo=theA1#bar' : {
<add> '/path/to/%%23%3F+=&.txt?foo=theA1#bar': {
<ide> href : '/path/to/%%23%3F+=&.txt?foo=theA1#bar',
<ide> pathname: '/path/to/%#?+=&.txt',
<ide> query: {
<ide> var formatTests = {
<ide> },
<ide>
<ide> // `#`,`?` in path + `#` in query
<del> '/path/to/%%23%3F+=&.txt?foo=the%231#bar' : {
<add> '/path/to/%%23%3F+=&.txt?foo=the%231#bar': {
<ide> href : '/path/to/%%23%3F+=&.txt?foo=the%231#bar',
<ide> pathname: '/path/to/%#?+=&.txt',
<ide> query: { | 1 |
Javascript | Javascript | add explicit schema for hidden challenges | 64c969a9082505abe47a23f84c246ba173282847 | <ide><path>client/gatsby-node.js
<ide> exports.onCreateBabelConfig = ({ actions }) => {
<ide> }
<ide> });
<ide> };
<add>
<add>// Typically the schema can be inferred, but not when some challenges are
<add>// skipped (at time of writing the Chinese only has responsive web design), so
<add>// this makes the missing fields explicit.
<add>exports.createSchemaCustomization = ({ actions }) => {
<add> const { createTypes } = actions;
<add> const typeDefs = `
<add> type ChallengeNode implements Node {
<add> question: Question
<add> videoId: String
<add> required: ExternalFile
<add> files: ChallengeFile
<add> }
<add> type Question {
<add> text: String
<add> answers: [String]
<add> solution: Int
<add> }
<add> type ChallengeFile {
<add> indexhtml: FileContents
<add> indexjs: FileContents
<add> indexjsx: FileContents
<add> }
<add> type ExternalFile {
<add> link: String
<add> src: String
<add> }
<add> type FileContents {
<add> key: String
<add> ext: String
<add> name: String
<add> contents: String
<add> head: String
<add> tail: String
<add> }
<add> `;
<add> createTypes(typeDefs);
<add>}; | 1 |
Ruby | Ruby | add missing require | 66b55dbfea370f0c4553e7d65b468dfaa81e8b37 | <ide><path>actionmailer/lib/action_mailer/old_api.rb
<add>require 'active_support/concern'
<ide> require 'active_support/core_ext/object/try'
<ide> require 'active_support/core_ext/object/blank'
<ide> | 1 |
Javascript | Javascript | check files in src for ddescribe/iit | e9fad96c7c3c351d0e53bb7bff2244bc5ce2c5f3 | <ide><path>Gruntfile.js
<ide> module.exports = function(grunt) {
<ide>
<ide> "ddescribe-iit": {
<ide> files: [
<add> 'src/**/*.js',
<ide> 'test/**/*.js',
<del> '!test/ngScenario/DescribeSpec.js'
<add> '!test/ngScenario/DescribeSpec.js',
<add> '!src/ng/directive/booleanAttrs.js', // legitimate xit here
<add> '!src/ngScenario/**/*.js'
<ide> ]
<ide> },
<ide> | 1 |
Go | Go | handle debug mode for clients | 78b0defcf344294874202e819dcb3f8a0daedf43 | <ide><path>docker/client.go
<ide> import (
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cliconfig"
<ide> flag "github.com/docker/docker/pkg/mflag"
<add> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> var clientFlags = &cli.ClientFlags{FlagSet: new(flag.FlagSet), Common: commonFlags}
<ide> func init() {
<ide> if clientFlags.Common.TrustKey == "" {
<ide> clientFlags.Common.TrustKey = filepath.Join(cliconfig.ConfigDir(), defaultTrustKeyFile)
<ide> }
<add>
<add> if clientFlags.Common.Debug {
<add> utils.EnableDebug()
<add> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | add broken test-isolates3.js | e1b829d2a502b5181d7a9d13e79d839ba0601421 | <ide><path>test/simple/test-child-process-fork3.js
<ide> var fork = require('child_process').fork;
<ide>
<ide> var filename = common.fixturesDir + '/destroy-stdin.js';
<ide>
<add>var options = {
<add> thread: process.TEST_ISOLATE ? true : false
<add>};
<add>
<ide> // Ensure that we don't accidentally close fd 0 and
<ide> // reuse it for something else, it causes all kinds
<ide> // of obscure bugs.
<ide> process.stdin.destroy();
<del>fork(filename).stdin.on('end', process.exit);
<add>fork(filename, [], options).stdin.on('end', process.exit);
<ide><path>test/simple/test-isolates3.js
<add>// Skip this test if Node is not compiled with isolates support.
<add>if (!process.features.isolates) return;
<add>
<add>var assert = require('assert');
<add>
<add>// This is the same test as test-child-process-fork3 except it uses isolates
<add>// instead of processes. process.TEST_ISOLATE is a ghetto method of passing
<add>// some information into the other test.
<add>process.TEST_ISOLATE = true;
<add>require('./test-child-process-fork3');
<add>
<add>var numThreads = process.binding('isolates').count();
<add>assert.ok(numThreads > 1); | 2 |
Javascript | Javascript | remove extra invariant | 928519e4bd8b9f576f8b72da55ed7d6feb0883e5 | <ide><path>Libraries/Text/Text.js
<ide> import {NativeText, NativeVirtualText} from './TextNativeComponent';
<ide> import {type TextProps} from './TextProps';
<ide> import * as React from 'react';
<ide> import {useContext, useMemo, useState} from 'react';
<del>import invariant from 'invariant';
<ide>
<ide> /**
<ide> * Text is the fundamental component for displaying text. | 1 |
Javascript | Javascript | use buffer.from instead of slice | 86203ade47c17130ffabf2d44fa90b7a212ca94b | <ide><path>lib/serialization/BinaryMiddleware.js
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> };
<ide> const flush = () => {
<ide> if (currentBuffer !== null) {
<del> buffers.push(currentBuffer.slice(0, currentPosition));
<add> buffers.push(
<add> Buffer.from(
<add> currentBuffer.buffer,
<add> currentBuffer.byteOffset,
<add> currentPosition
<add> )
<add> );
<ide> if (
<ide> !leftOverBuffer ||
<ide> leftOverBuffer.length < currentBuffer.length - currentPosition
<del> )
<del> leftOverBuffer = currentBuffer.slice(currentPosition);
<add> ) {
<add> leftOverBuffer = Buffer.from(
<add> currentBuffer.buffer,
<add> currentBuffer.byteOffset + currentPosition,
<add> currentBuffer.byteLength - currentPosition
<add> );
<add> }
<ide> currentBuffer = null;
<ide> buffersTotalLength += currentPosition;
<ide> currentPosition = 0;
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> if (rem < n) {
<ide> return Buffer.concat([read(rem), read(n - rem)]);
<ide> }
<del> const res = /** @type {Buffer} */ (currentBuffer).slice(
<del> currentPosition,
<del> currentPosition + n
<del> );
<add> const b = /** @type {Buffer} */ (currentBuffer);
<add> const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
<ide> currentPosition += n;
<ide> checkOverflow();
<ide> return res;
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> if (rem < n) {
<ide> n = rem;
<ide> }
<del> const res = /** @type {Buffer} */ (currentBuffer).slice(
<del> currentPosition,
<del> currentPosition + n
<del> );
<add> const b = /** @type {Buffer} */ (currentBuffer);
<add> const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
<ide> currentPosition += n;
<ide> checkOverflow();
<ide> return res;
<ide><path>lib/serialization/FileMiddleware.js
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> contentPosition += length;
<ide> length = 0;
<ide> } else {
<add> const l = contentItemLength - contentPosition;
<ide> result.push(
<ide> Buffer.from(
<ide> contentItem.buffer,
<del> contentItem.byteOffset + contentPosition
<add> contentItem.byteOffset + contentPosition,
<add> l
<ide> )
<ide> );
<del> length -= contentItemLength - contentPosition;
<add> length -= l;
<ide> contentPosition = contentItemLength;
<ide> }
<ide> } else {
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> length -= contentItemLength;
<ide> contentPosition = contentItemLength;
<ide> } else {
<del> result.push(contentItem.slice(0, length));
<add> result.push(
<add> Buffer.from(contentItem.buffer, contentItem.byteOffset, length)
<add> );
<ide> contentPosition += length;
<ide> length = 0;
<ide> }
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> length -= contentItemLength;
<ide> contentPosition = contentItemLength;
<ide> } else {
<del> result.push(contentItem.slice(0, length));
<add> result.push(
<add> Buffer.from(contentItem.buffer, contentItem.byteOffset, length)
<add> );
<ide> contentPosition += length;
<ide> length = 0;
<ide> } | 2 |
PHP | PHP | fix broken tests | 7b169ed084db099615c3de95e64c1a4284dd60c8 | <ide><path>lib/Cake/Test/Case/Core/ObjectTest.php
<ide> public function testRequestAction() {
<ide> $this->assertEqual($expected, $result);
<ide>
<ide> $result = $this->object->requestAction('/tests_apps/index', array('return'));
<del> $expected = 'This is the TestsAppsController index view';
<add> $expected = 'This is the TestsAppsController index view ';
<ide> $this->assertEqual($expected, $result);
<ide>
<ide> $result = $this->object->requestAction('/tests_apps/some_method');
<ide> public function testRequestActionArray() {
<ide> $result = $this->object->requestAction(
<ide> array('controller' => 'tests_apps', 'action' => 'index'), array('return')
<ide> );
<del> $expected = 'This is the TestsAppsController index view';
<add> $expected = 'This is the TestsAppsController index view ';
<ide> $this->assertEqual($expected, $result);
<ide>
<ide> $result = $this->object->requestAction(array('controller' => 'tests_apps', 'action' => 'some_method')); | 1 |
Go | Go | fix the assignment to wrong variable | 4141a00921e3ae814736249ec1806d5d35c8d46c | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) poolHasFreeSpace() error {
<ide>
<ide> minFreeMetadata := (metadataTotal * uint64(devices.minFreeSpacePercent)) / 100
<ide> if minFreeMetadata < 1 {
<del> minFreeData = 1
<add> minFreeMetadata = 1
<ide> }
<ide>
<ide> metadataFree := metadataTotal - metadataUsed | 1 |
Ruby | Ruby | remove unnecessary addition of `lib` | a89a06bb10e76c8377582650007cb5b66e2f248f | <ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> def rakefile_test_tasks
<ide> require 'rake/testtask'
<ide>
<ide> Rake::TestTask.new(:test) do |t|
<del> t.libs << 'lib'
<ide> t.libs << 'test'
<ide> t.pattern = 'test/**/*_test.rb'
<ide> t.verbose = false | 1 |
Ruby | Ruby | execute less operations | 994a1c2a4747efcca3c6278c119096d93f793da1 | <ide><path>activerecord/lib/active_record/associations/association_collection.rb
<ide> def ensure_owner_is_not_new
<ide>
<ide> def fetch_first_or_last_using_find?(args)
<ide> args.first.kind_of?(Hash) || !(loaded? || !@owner.persisted? || @reflection.options[:finder_sql] ||
<del> @target.any? { |record| !record.persisted? } || args.first.kind_of?(Integer))
<del> # TODO - would prefer @target.none? { |r| r.persisted? }
<add> !@target.all? { |record| record.persisted? } || args.first.kind_of?(Integer))
<ide> end
<ide>
<ide> def include_in_memory?(record) | 1 |
Javascript | Javascript | add test for selection.map | badce35c7632aa1f909f0946a2686645f8db2066 | <ide><path>test/core/selection-map-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("selection.map");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "updates the data according to the map function": function(body) {
<add> body.data([42]).map(function(d, i) { return d + i; });
<add> assert.equal(document.body.__data__, 42);
<add> },
<add> "returns the same selection": function(body) {
<add> assert.isTrue(body.map(function() { return 1; }) === body);
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "updates the data according to the map function": function(div) {
<add> div.data([42, 43]).map(function(d, i) { return d + i; });
<add> assert.equal(div[0][0].__data__, 42);
<add> assert.equal(div[0][1].__data__, 44);
<add> },
<add> "returns the same selection": function(div) {
<add> assert.isTrue(div.map(function() { return 1; }) === div);
<add> },
<add> "ignores null nodes": function(div) {
<add> var some = d3.selectAll("div").data([42, 43]);
<add> some[0][1] = null;
<add> some.map(function() { return 1; });
<add> assert.equal(div[0][0].__data__, 1);
<add> assert.equal(div[0][1].__data__, 43);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
Javascript | Javascript | allow instantiating webgltextures from a worker | 17791a42c5af98dd981311615c87b4c2dbad8589 | <ide><path>src/renderers/webgl/WebGLTextures.js
<ide> import { _Math } from '../../math/Math.js';
<ide>
<ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, infoMemory ) {
<ide>
<del> var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof window.WebGL2RenderingContext );
<add> var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
<ide> var _videoTextures = {};
<ide>
<ide> // | 1 |
Python | Python | dbapihook consistent insert_rows logging | 76014609c07bfa307ef7598794d1c0404c5279bd | <ide><path>airflow/providers/common/sql/hooks/sql.py
<ide> def insert_rows(self, table, rows, target_fields=None, commit_every=1000, replac
<ide> self.log.info("Loaded %s rows into %s so far", i, table)
<ide>
<ide> conn.commit()
<del> self.log.info("Done loading. Loaded a total of %s rows", i)
<add> self.log.info("Done loading. Loaded a total of %s rows into %s", i, table)
<ide>
<ide> @staticmethod
<ide> def _serialize_cell(cell, conn=None): | 1 |
Javascript | Javascript | handle modifications to fs.open | 06ada03ed93d6f81caef24c6dade6e616fd843b1 | <ide><path>lib/fs.js
<ide> var WriteStream = fs.WriteStream = function(path, options) {
<ide> this._queue = [];
<ide>
<ide> if (this.fd === null) {
<del> this._queue.push([fs.open, this.path, this.flags, this.mode, undefined]);
<add> this._open = fs.open;
<add> this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
<ide> this.flush();
<ide> }
<ide> };
<ide> WriteStream.prototype.flush = function() {
<ide> cb(null, arguments[1]);
<ide> }
<ide>
<del> } else if (method === fs.open) {
<add> } else if (method === self._open) {
<ide> // save reference for file pointer
<ide> self.fd = arguments[1];
<ide> self.emit('open', self.fd);
<ide> WriteStream.prototype.flush = function() {
<ide> });
<ide>
<ide> // Inject the file pointer
<del> if (method !== fs.open) {
<add> if (method !== self._open) {
<ide> args.unshift(this.fd);
<ide> }
<ide>
<ide><path>test/simple/test-fs-write-stream-change-open.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>var path = require('path'),
<add> fs = require('fs');
<add>
<add>var file = path.join(common.tmpDir, 'write.txt');
<add>
<add>var stream = fs.WriteStream(file),
<add> _fs_close = fs.close,
<add> _fs_open = fs.open;
<add>
<add>// change the fs.open with an identical function after the WriteStream
<add>// has pushed it onto its internal action queue, but before it's
<add>// returned. This simulates AOP-style extension of the fs lib.
<add>fs.open = function() {
<add> return _fs_open.apply(fs, arguments);
<add>};
<add>
<add>fs.close = function(fd) {
<add> assert.ok(fd, 'fs.close must not be called with an undefined fd.');
<add> fs.close = _fs_close;
<add> fs.open = _fs_open;
<add>}
<add>
<add>stream.write('foo');
<add>stream.end();
<add>
<add>process.on('exit', function() {
<add> assert.equal(fs.open, _fs_open);
<add>}); | 2 |
Ruby | Ruby | pass explicit sort to handle apfs | d9074b80b7617e73084a55d8318da3fb67641bbf | <ide><path>Library/Homebrew/cmd/options.rb
<ide> module Homebrew
<ide>
<ide> def options
<ide> if ARGV.include? "--all"
<del> puts_options Formula.to_a
<add> puts_options Formula.to_a.sort
<ide> elsif ARGV.include? "--installed"
<del> puts_options Formula.installed
<add> puts_options Formula.installed.sort
<ide> else
<ide> raise FormulaUnspecifiedError if ARGV.named.empty?
<ide> puts_options ARGV.formulae | 1 |
Javascript | Javascript | change appearence example to hooks | 22576fa615f0308aab00686235295b3dc0d34852 | <ide><path>packages/rn-tester/js/examples/Appearance/AppearanceExample.js
<ide> */
<ide>
<ide> import * as React from 'react';
<add>import {useState, useEffect} from 'react';
<ide> import {Appearance, Text, useColorScheme, View} from 'react-native';
<ide> import type {AppearancePreferences} from 'react-native/Libraries/Utilities/NativeAppearance';
<del>import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter';
<ide> import {RNTesterThemeContext, themes} from '../../components/RNTesterTheme';
<ide>
<del>class ColorSchemeSubscription extends React.Component<
<del> {...},
<del> {colorScheme: ?string, ...},
<del>> {
<del> _subscription: ?EventSubscription;
<add>function ColorSchemeSubscription() {
<add> const [colorScheme, setScheme] = useState(Appearance.getColorScheme());
<ide>
<del> state: {colorScheme: ?string, ...} = {
<del> colorScheme: Appearance.getColorScheme(),
<del> };
<del>
<del> componentDidMount() {
<del> this._subscription = Appearance.addChangeListener(
<add> useEffect(() => {
<add> const subscription = Appearance.addChangeListener(
<ide> (preferences: AppearancePreferences) => {
<del> const {colorScheme} = preferences;
<del> this.setState({colorScheme});
<add> const {colorScheme: scheme} = preferences;
<add> setScheme(scheme);
<ide> },
<ide> );
<del> }
<ide>
<del> componentWillUnmount() {
<del> this._subscription?.remove();
<del> }
<add> return () => subscription?.remove();
<add> }, [setScheme]);
<ide>
<del> render(): React.Node {
<del> return (
<del> <RNTesterThemeContext.Consumer>
<del> {theme => {
<del> return (
<del> <ThemedContainer>
<del> <ThemedText>{this.state.colorScheme}</ThemedText>
<del> </ThemedContainer>
<del> );
<del> }}
<del> </RNTesterThemeContext.Consumer>
<del> );
<del> }
<add> return (
<add> <RNTesterThemeContext.Consumer>
<add> {theme => {
<add> return (
<add> <ThemedContainer>
<add> <ThemedText>{colorScheme}</ThemedText>
<add> </ThemedContainer>
<add> );
<add> }}
<add> </RNTesterThemeContext.Consumer>
<add> );
<ide> }
<ide>
<ide> const ThemedContainer = (props: {children: React.Node}) => (
<ide> const ThemedContainer = (props: {children: React.Node}) => (
<ide> </RNTesterThemeContext.Consumer>
<ide> );
<ide>
<del>const ThemedText = (props: {children: React.Node}) => (
<add>const ThemedText = (props: {children: React.Node | string}) => (
<ide> <RNTesterThemeContext.Consumer>
<ide> {theme => {
<ide> return <Text style={{color: theme.LabelColor}}>{props.children}</Text>; | 1 |
Javascript | Javascript | remove a broken hook | 18d7396835c8e2fb496a501c53504ab46d92b19b | <ide><path>lib/node/NodeSourcePlugin.js
<ide> module.exports = class NodeSourcePlugin {
<ide> normalModuleFactory.hooks.parser
<ide> .for("javascript/dynamic")
<ide> .tap("NodeSourcePlugin", handler);
<del> normalModuleFactory.hooks.parser
<del> .for("javascript/esm")
<del> .tap("NodeSourcePlugin", handler);
<ide> }
<ide> );
<ide> compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { | 1 |
Text | Text | clarify usage of util.promisify.custom | cc258af0e4898338b6be49ac79b49dc28169d0c9 | <ide><path>doc/api/util.md
<ide> console.log(promisified === doSomething[util.promisify.custom]);
<ide> This can be useful for cases where the original function does not follow the
<ide> standard format of taking an error-first callback as the last argument.
<ide>
<add>For example, with a function that takes in `(foo, onSuccessCallback, onErrorCallback)`:
<add>
<add>```js
<add>doSomething[util.promisify.custom] = function(foo) {
<add> return new Promise(function(resolve, reject) {
<add> doSomething(foo, resolve, reject);
<add> });
<add>};
<add>```
<add>
<ide> ### util.promisify.custom
<ide> <!-- YAML
<ide> added: v8.0.0 | 1 |
Ruby | Ruby | reword documentation for `uncountable` [ci skip] | 6c75a111995a9aab09e19c2b6a8a42162f689bc6 | <ide><path>activesupport/lib/active_support/inflector/inflections.rb
<ide> def irregular(singular, plural)
<ide> end
<ide> end
<ide>
<del> # Add uncountable words that shouldn't be attempted inflected.
<add> # Specifies words that are uncountable and should not be inflected.
<ide> #
<ide> # uncountable 'money'
<ide> # uncountable 'money', 'information' | 1 |
Text | Text | add another link to "more information" | 88da0d48cf5e251e7e41c0799ff4b44984ef2aab | <ide><path>guide/english/computer-science/index.md
<ide> Computer science is categorized into several fields. The following are among the
<ide> * [Khan Academy](https://www.khanacademy.org/computing/computer-science) : A deep dive into algorithms, cryptography, introductory computing, and much more.
<ide> * [CS50](https://cs50.harvard.edu) : A free, introduction to computer science course, taught by David J. Malan and staff at Harvard & Yale Universities.
<ide> * [Visualization of Data Structures](http://www.cs.usfca.edu/~galles/JavascriptVisual/Algorithms.html)
<del>
<add>* [Data Structure](https://en.wikipedia.org/wiki/Data_structure) | 1 |
Text | Text | fix inconsistent heading level in guides [ci-skip] | e469025ef5f6879fd7ec2f8733140789d872abd2 | <ide><path>guides/source/3_2_release_notes.md
<ide> Railties
<ide>
<ide> * Remove old `config.paths.app.controller` API in favor of `config.paths["app/controller"]`.
<ide>
<del>#### Deprecations
<add>### Deprecations
<ide>
<ide> * `Rails::Plugin` is deprecated and will be removed in Rails 4.0. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.
<ide>
<ide><path>guides/source/action_cable_overview.md
<ide> consumer.subscriptions.create("AppearanceChannel", {
<ide> })
<ide> ```
<ide>
<del>##### Client-Server Interaction
<add>#### Client-Server Interaction
<ide>
<ide> 1. **Client** connects to the **Server** via `App.cable =
<ide> ActionCable.createConsumer("ws://cable.example.com")`. (`cable.js`). The
<ide><path>guides/source/action_mailer_basics.md
<ide> What is Action Mailer?
<ide> Action Mailer allows you to send emails from your application using mailer classes
<ide> and views.
<ide>
<del>#### Mailers are similar to controllers
<add>### Mailers are similar to controllers
<ide>
<ide> They inherit from [`ActionMailer::Base`][] and live in `app/mailers`. Mailers also work
<ide> very similarly to controllers. Some examples of similarities are enumerated below.
<ide><path>guides/source/testing.md
<ide> end
<ide>
<ide> This assertion is quite powerful. For more advanced usage, refer to its [documentation](https://github.com/rails/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb).
<ide>
<del>#### Additional View-Based Assertions
<add>### Additional View-Based Assertions
<ide>
<ide> There are more assertions that are primarily used in testing views:
<ide> | 4 |
Javascript | Javascript | add test case | 03c7f0c54afb00901f8d887efb01048a3cea749c | <ide><path>test/ConfigTestCases.test.js
<ide> describe("ConfigTestCases", () => {
<ide> let runInNewContext = false;
<ide> const moduleScope = {
<ide> require: _require.bind(null, path.dirname(p)),
<add> importScripts: _require.bind(null, path.dirname(p)),
<ide> module: m,
<ide> exports: m.exports,
<ide> __dirname: path.dirname(p),
<ide> describe("ConfigTestCases", () => {
<ide> options.target === "webworker"
<ide> ) {
<ide> moduleScope.window = globalContext;
<add> moduleScope.self = globalContext;
<ide> runInNewContext = true;
<ide> }
<ide> if (testConfig.moduleScope) {
<ide><path>test/configCases/target/webworker/index.js
<ide> it("should provide a zlib shim", function () {
<ide> it("should provide a shim for a path in a build-in module", function () {
<ide> expect(require("process/in.js")).toBe("in process");
<ide> });
<add>
<add>it("should allow to load a chunk", () => {
<add> __webpack_public_path__ = "./";
<add> return import("./module").then(module => {
<add> expect(module.default).toBe("ok");
<add> });
<add>});
<ide><path>test/configCases/target/webworker/module.js
<add>export default "ok"; | 3 |
Java | Java | add new reactmarkers for bridgeless init start/end | e125f12c01262c11d70c1015139d5f72c5576042 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java
<ide> public enum ReactMarkerConstants {
<ide> FABRIC_BATCH_EXECUTION_START,
<ide> FABRIC_BATCH_EXECUTION_END,
<ide> FABRIC_UPDATE_UI_MAIN_THREAD_START,
<del> FABRIC_UPDATE_UI_MAIN_THREAD_END
<add> FABRIC_UPDATE_UI_MAIN_THREAD_END,
<add> // New markers used by bridgeless RN below this line
<add> REACT_INSTANCE_INIT_START,
<add> REACT_INSTANCE_INIT_END
<ide> } | 1 |
Python | Python | remove unused variable | 8211f882bd973d3a418fc4752cc22af73a67819e | <ide><path>celery/contrib/coroutine.py
<ide> class Aggregate(CoroutineTask):
<ide> def body(self):
<ide> waiting = deque()
<ide>
<del> timesince = time.time()
<ide> while True:
<ide> argtuple = (yield)
<ide> waiting.append(argtuple) | 1 |
Ruby | Ruby | remove useless assertions | 327c6023cdf17cd1ac557d5db5bccf92dd681292 | <ide><path>railties/test/generators/argv_scrubber_test.rb
<ide> def self.default_rc_file
<ide> end
<ide> }.new ['new']
<ide> args = scrubber.prepare!
<del> assert_nil args.first
<ide> assert_equal [], args
<ide> end
<ide>
<ide> def test_new_homedir_rc
<ide> define_method(:puts) { |msg| message = msg }
<ide> }.new ['new']
<ide> args = scrubber.prepare!
<del> assert_nil args.first
<ide> assert_equal [nil, '--hello-world'], args
<ide> assert_match 'hello-world', message
<ide> assert_match file.path, message | 1 |
Python | Python | add test for filter_renderers | 076ca6e7651fa810a3d0bbd9d923adf10845080f | <ide><path>tests/test_negotiation.py
<ide> from __future__ import unicode_literals
<ide>
<add>import pytest
<add>from django.http import Http404
<ide> from django.test import TestCase
<ide>
<ide> from rest_framework.negotiation import DefaultContentNegotiation
<ide> def test_mediatype_string_representation(self):
<ide> params_str += '; %s=%s' % (key, val)
<ide> expected = 'test/*' + params_str
<ide> assert str(mediatype) == expected
<add>
<add> def test_raise_error_if_no_suitable_renderers_found(self):
<add> class MockRenderer(object):
<add> format = 'xml'
<add> renderers = [MockRenderer()]
<add> with pytest.raises(Http404):
<add> self.negotiator.filter_renderers(renderers, format='json') | 1 |
Javascript | Javascript | skip unneeded steps on app_shutdown | 7c902eb612dec7e256c13080d92da935781aa4b9 | <ide><path>extensions/firefox/bootstrap.js
<ide> function startup(aData, aReason) {
<ide> function shutdown(aData, aReason) {
<ide> if (Services.prefs.getBoolPref('extensions.pdf.js.active'))
<ide> Services.prefs.setBoolPref('extensions.pdf.js.active', false);
<add> if (aReason == APP_SHUTDOWN)
<add> return;
<ide> var ioService = Services.io;
<ide> var resProt = ioService.getProtocolHandler('resource')
<ide> .QueryInterface(Ci.nsIResProtocolHandler); | 1 |
Text | Text | move note about next export and i18n | ad8999356d8c246619cace4e777acc0a7222c834 | <ide><path>docs/advanced-features/i18n-routing.md
<ide> Next.js doesn't know about variants of a page so it's up to you to add the `href
<ide>
<ide> ## How does this work with Static Generation?
<ide>
<add>> Note that Internationalized Routing does not integrate with [`next export`](/docs/advanced-features/static-html-export.md) as `next export` does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use `next export` are fully supported.
<add>
<ide> ### Automatically Statically Optimized Pages
<ide>
<ide> For pages that are [automatically statically optimized](/docs/advanced-features/automatic-static-optimization.md), a version of the page will be generated for each locale.
<ide> export const getStaticPaths = ({ locales }) => {
<ide> }
<ide> }
<ide> ```
<del>
<del>## Caveats
<del>
<del>Internationalized Routing does not currently support [Static HTML Export (`next export`)](/docs/advanced-features/static-html-export.md) as you are no longer leveraging Next.js' server-side routing in that case. | 1 |
Text | Text | add discord link | 9694c34193e33851eb5643182739d6d5a6724cd8 | <ide><path>README.md
<ide> If you’re new to the NPM ecosystem and have troubles getting a project up and
<ide>
<ide> ### Discussion
<ide>
<del>Join the **#redux** channel of the [Reactiflux](http://reactiflux.com) Slack community.
<add>Join the [#redux](https://discord.gg/0ZcbPKXt5bZ6au5t) channel of the [Reactiflux](http://reactiflux.com) Discord community.
<ide>
<ide> ### Thanks
<ide> | 1 |
Ruby | Ruby | add support for single-package casks | ef1ea75c08f34ae7153db4244207edfda4c3c558 | <ide><path>Library/Homebrew/cask/artifact/pkg.rb
<ide> module Artifact
<ide> #
<ide> # @api private
<ide> class Pkg < AbstractArtifact
<del> attr_reader :pkg_relative_path, :path, :stanza_options
<add> attr_reader :path, :stanza_options
<ide>
<ide> def self.from_args(cask, path, **stanza_options)
<ide> stanza_options.assert_valid_keys!(:allow_untrusted, :choices)
<ide><path>Library/Homebrew/dev-cmd/bump-unversioned-casks.rb
<ide> def self.bump_unversioned_casks
<ide>
<ide> ohai "Checking #{cask.full_name}"
<ide>
<del> unless single_app_cask?(cask)
<del> opoo "Skipping, not a single-app cask."
<del> next
<del> end
<del>
<ide> last_state = state.fetch(cask.full_name, {})
<ide> last_check_time = last_state["check_time"]&.yield_self { |t| Time.parse(t) }
<ide>
<ide> def self.bump_unversioned_casks
<ide> sig { params(cask: Cask::Cask, installer: Cask::Installer).returns(T.nilable(String)) }
<ide> def self.guess_cask_version(cask, installer)
<ide> apps = cask.artifacts.select { |a| a.is_a?(Cask::Artifact::App) }
<del> return if apps.count != 1
<add> pkgs = cask.artifacts.select { |a| a.is_a?(Cask::Artifact::Pkg) }
<add>
<add> if apps.empty? && pkgs.empty?
<add> opoo "Cask #{cask} does not contain any apps or PKG installers."
<add> return
<add> end
<ide>
<ide> Dir.mktmpdir do |dir|
<ide> dir = Pathname(dir)
<ide> def self.guess_cask_version(cask, installer)
<ide> next
<ide> end
<ide>
<del> plists = apps.flat_map do |app|
<add> info_plist_paths = apps.flat_map do |app|
<ide> Pathname.glob(dir/"**"/app.source.basename/"Contents"/"Info.plist")
<ide> end
<del> next if plists.empty?
<ide>
<del> plist = plists.first
<add> info_plist_paths.each do |info_plist_path|
<add> if (version = version_from_info_plist(cask, info_plist_path))
<add> return version
<add> end
<add> end
<add>
<add> pkg_paths = pkgs.flat_map do |pkg|
<add> Pathname.glob(dir/"**"/pkg.path.basename)
<add> end
<add>
<add> pkg_paths.each do |pkg_path|
<add> packages =
<add> system_command!("installer", args: ["-plist", "-pkginfo", "-pkg", pkg_path])
<add> .plist
<add> .map { |package| package.fetch("Package") }
<add> .uniq
<add>
<add> if packages.count == 1
<add> extract_dir = dir/pkg_path.stem
<add> system_command! "pkgutil", args: ["--expand-full", pkg_path, extract_dir]
<add>
<add> package_info_path = extract_dir/"PackageInfo"
<add> if package_info_path.exist?
<add> if (version = version_from_package_info(cask, package_info_path))
<add> return version
<add> end
<add> else
<add> onoe "#{pkg_path.basename} does not contain a `PackageInfo` file."
<add> next
<add> end
<add>
<add> else
<add> opoo "Skipping, #{pkg_path.basename} contains multiple packages."
<add> next
<add> end
<add> end
<add>
<add> nil
<add> end
<add> end
<add>
<add> sig { params(cask: Cask::Cask, info_plist_path: Pathname).returns(T.nilable(String)) }
<add> def self.version_from_info_plist(cask, info_plist_path)
<add> plist = system_command!("plutil", args: ["-convert", "xml1", "-o", "-", info_plist_path]).plist
<ide>
<del> system_command! "plutil", args: ["-convert", "xml1", plist]
<del> plist = Plist.parse_xml(plist.read)
<add> short_version = plist["CFBundleShortVersionString"]
<add> version = plist["CFBundleVersion"]
<ide>
<del> short_version = plist["CFBundleShortVersionString"]
<del> version = plist["CFBundleVersion"]
<add> return decide_between_versions(cask, short_version, version) if short_version && version
<add> end
<ide>
<del> return "#{short_version},#{version}" if cask.version.include?(",")
<add> sig { params(cask: Cask::Cask, package_info_path: Pathname).returns(T.nilable(String)) }
<add> def self.version_from_package_info(cask, package_info_path)
<add> contents = package_info_path.read
<ide>
<del> return cask.version.to_s if [short_version, version].include?(cask.version.to_s)
<add> short_version = contents[/CFBundleShortVersionString="([^"]*)"/, 1]
<add> version = contents[/CFBundleVersion="([^"]*)"/, 1]
<ide>
<del> return short_version if short_version&.match(/\A\d+(\.\d+)+\Z/)
<del> return version if version&.match(/\A\d+(\.\d+)+\Z/)
<add> return decide_between_versions(cask, short_version, version) if short_version && version
<add> end
<ide>
<del> short_version || version
<del> end
<add> sig do
<add> params(cask: Cask::Cask, short_version: T.nilable(String), version: T.nilable(String))
<add> .returns(T.nilable(String))
<add> end
<add> def self.decide_between_versions(cask, short_version, version)
<add> return "#{short_version},#{version}" if short_version && version && cask.version.include?(",")
<add>
<add> return cask.version.to_s if [short_version, version].include?(cask.version.to_s)
<add>
<add> return short_version if short_version&.match(/\A\d+(\.\d+)+\Z/)
<add> return version if version&.match(/\A\d+(\.\d+)+\Z/)
<add>
<add> short_version || version
<ide> end
<ide>
<ide> def self.single_app_cask?(cask) | 2 |
Python | Python | move xcom tests to tests/models/test_xcom.py | 7a5441836bbc8bbcb0b02bf68dbd93d63fe4ec6a | <ide><path>tests/models/test_cleartasks.py
<ide> # under the License.
<ide>
<ide> import datetime
<del>import os
<ide> import unittest
<ide>
<ide> from airflow import settings
<del>from airflow.models import DAG, TaskInstance as TI, XCom, clear_task_instances
<add>from airflow.models import DAG, TaskInstance as TI, clear_task_instances
<ide> from airflow.operators.dummy_operator import DummyOperator
<del>from airflow.utils import timezone
<ide> from airflow.utils.session import create_session
<ide> from airflow.utils.state import State
<ide> from tests.models import DEFAULT_DATE
<del>from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> class TestClearTasks(unittest.TestCase):
<ide> def test_operator_clear(self):
<ide> self.assertEqual(ti2.try_number, 2)
<ide> # try_number (0) + retries(1)
<ide> self.assertEqual(ti2.max_tries, 1)
<del>
<del> @conf_vars({("core", "enable_xcom_pickling"): "False"})
<del> def test_xcom_disable_pickle_type(self):
<del> json_obj = {"key": "value"}
<del> execution_date = timezone.utcnow()
<del> key = "xcom_test1"
<del> dag_id = "test_dag1"
<del> task_id = "test_task1"
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> ret_value = XCom.get_many(key=key,
<del> dag_ids=dag_id,
<del> task_ids=task_id,
<del> execution_date=execution_date).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> session = settings.Session()
<del> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<del> XCom.task_id == task_id,
<del> XCom.execution_date == execution_date
<del> ).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> @conf_vars({("core", "enable_xcom_pickling"): "False"})
<del> def test_xcom_get_one_disable_pickle_type(self):
<del> json_obj = {"key": "value"}
<del> execution_date = timezone.utcnow()
<del> key = "xcom_test1"
<del> dag_id = "test_dag1"
<del> task_id = "test_task1"
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> ret_value = XCom.get_one(key=key,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> session = settings.Session()
<del> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<del> XCom.task_id == task_id,
<del> XCom.execution_date == execution_date
<del> ).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<del> def test_xcom_enable_pickle_type(self):
<del> json_obj = {"key": "value"}
<del> execution_date = timezone.utcnow()
<del> key = "xcom_test2"
<del> dag_id = "test_dag2"
<del> task_id = "test_task2"
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> ret_value = XCom.get_many(key=key,
<del> dag_ids=dag_id,
<del> task_ids=task_id,
<del> execution_date=execution_date).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> session = settings.Session()
<del> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<del> XCom.task_id == task_id,
<del> XCom.execution_date == execution_date
<del> ).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<del> def test_xcom_get_one_enable_pickle_type(self):
<del> json_obj = {"key": "value"}
<del> execution_date = timezone.utcnow()
<del> key = "xcom_test3"
<del> dag_id = "test_dag"
<del> task_id = "test_task3"
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> ret_value = XCom.get_one(key=key,
<del> dag_id=dag_id,
<del> task_id=task_id,
<del> execution_date=execution_date)
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> session = settings.Session()
<del> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<del> XCom.task_id == task_id,
<del> XCom.execution_date == execution_date
<del> ).first().value
<del>
<del> self.assertEqual(ret_value, json_obj)
<del>
<del> @conf_vars({("core", "xcom_enable_pickling"): "False"})
<del> def test_xcom_disable_pickle_type_fail_on_non_json(self):
<del> class PickleRce:
<del> def __reduce__(self):
<del> return os.system, ("ls -alt",)
<del>
<del> self.assertRaises(TypeError, XCom.set,
<del> key="xcom_test3",
<del> value=PickleRce(),
<del> dag_id="test_dag3",
<del> task_id="test_task3",
<del> execution_date=timezone.utcnow())
<del>
<del> @conf_vars({("core", "xcom_enable_pickling"): "True"})
<del> def test_xcom_get_many(self):
<del> json_obj = {"key": "value"}
<del> execution_date = timezone.utcnow()
<del> key = "xcom_test4"
<del> dag_id1 = "test_dag4"
<del> task_id1 = "test_task4"
<del> dag_id2 = "test_dag5"
<del> task_id2 = "test_task5"
<del>
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id1,
<del> task_id=task_id1,
<del> execution_date=execution_date)
<del>
<del> XCom.set(key=key,
<del> value=json_obj,
<del> dag_id=dag_id2,
<del> task_id=task_id2,
<del> execution_date=execution_date)
<del>
<del> results = XCom.get_many(key=key, execution_date=execution_date)
<del>
<del> for result in results:
<del> self.assertEqual(result.value, json_obj)
<ide><path>tests/models/test_xcom.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>import os
<add>import unittest
<add>
<add>from airflow import settings
<ide> from airflow.configuration import conf
<del>from airflow.models.xcom import BaseXCom, resolve_xcom_backend
<add>from airflow.models.xcom import BaseXCom, XCom, resolve_xcom_backend
<add>from airflow.utils import timezone
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> def serialize_value(_):
<ide> return "custom_value"
<ide>
<ide>
<del>class TestXCom:
<add>class TestXCom(unittest.TestCase):
<ide> @conf_vars({("core", "xcom_backend"): "tests.models.test_xcom.CustomXCom"})
<ide> def test_resolve_xcom_class(self):
<ide> cls = resolve_xcom_backend()
<ide> def test_resolve_xcom_class_fallback_to_basexcom_no_config(self):
<ide> cls = resolve_xcom_backend()
<ide> assert issubclass(cls, BaseXCom)
<ide> assert cls().serialize_value([1]) == b"[1]"
<add>
<add> @conf_vars({("core", "enable_xcom_pickling"): "False"})
<add> def test_xcom_disable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test1"
<add> dag_id = "test_dag1"
<add> task_id = "test_task1"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_many(key=key,
<add> dag_ids=dag_id,
<add> task_ids=task_id,
<add> execution_date=execution_date).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> @conf_vars({("core", "enable_xcom_pickling"): "False"})
<add> def test_xcom_get_one_disable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test1"
<add> dag_id = "test_dag1"
<add> task_id = "test_task1"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_one(key=key,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<add> def test_xcom_enable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test2"
<add> dag_id = "test_dag2"
<add> task_id = "test_task2"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_many(key=key,
<add> dag_ids=dag_id,
<add> task_ids=task_id,
<add> execution_date=execution_date).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<add> def test_xcom_get_one_enable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test3"
<add> dag_id = "test_dag"
<add> task_id = "test_task3"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_one(key=key,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> @conf_vars({("core", "xcom_enable_pickling"): "False"})
<add> def test_xcom_disable_pickle_type_fail_on_non_json(self):
<add> class PickleRce:
<add> def __reduce__(self):
<add> return os.system, ("ls -alt",)
<add>
<add> self.assertRaises(TypeError, XCom.set,
<add> key="xcom_test3",
<add> value=PickleRce(),
<add> dag_id="test_dag3",
<add> task_id="test_task3",
<add> execution_date=timezone.utcnow())
<add>
<add> @conf_vars({("core", "xcom_enable_pickling"): "True"})
<add> def test_xcom_get_many(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test4"
<add> dag_id1 = "test_dag4"
<add> task_id1 = "test_task4"
<add> dag_id2 = "test_dag5"
<add> task_id2 = "test_task5"
<add>
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id1,
<add> task_id=task_id1,
<add> execution_date=execution_date)
<add>
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id2,
<add> task_id=task_id2,
<add> execution_date=execution_date)
<add>
<add> results = XCom.get_many(key=key, execution_date=execution_date)
<add>
<add> for result in results:
<add> self.assertEqual(result.value, json_obj) | 2 |
Javascript | Javascript | remove global state | 365c1bfcf9e7b62b9e294a23270b02a1eebc3fb8 | <ide><path>local-cli/bundle/buildBundle.js
<ide>
<ide> const log = require('../util/log').out('bundle');
<ide> const Server = require('../../packager/src/Server');
<add>const Terminal = require('../../packager/src/lib/TerminalClass');
<ide> const TerminalReporter = require('../../packager/src/lib/TerminalReporter');
<ide> const TransformCaching = require('../../packager/src/lib/TransformCaching');
<ide>
<ide> function buildBundle(
<ide> : config.getTransformModulePath();
<ide>
<ide> const providesModuleNodeModules =
<del> typeof config.getProvidesModuleNodeModules === 'function' ? config.getProvidesModuleNodeModules() :
<del> defaultProvidesModuleNodeModules;
<add> typeof config.getProvidesModuleNodeModules === 'function'
<add> ? config.getProvidesModuleNodeModules()
<add> : defaultProvidesModuleNodeModules;
<ide>
<add> /* $FlowFixMe: Flow is wrong, Node.js docs specify that process.stdout is an
<add> * instance of a net.Socket (a local socket, not network). */
<add> const terminal = new Terminal(process.stdout);
<ide> const options = {
<ide> assetExts: defaultAssetExts.concat(assetExts),
<ide> blacklistRE: config.getBlacklistRE(),
<ide> function buildBundle(
<ide> projectRoots: config.getProjectRoots(),
<ide> providesModuleNodeModules: providesModuleNodeModules,
<ide> resetCache: args.resetCache,
<del> reporter: new TerminalReporter(),
<add> reporter: new TerminalReporter(terminal),
<ide> sourceExts: defaultSourceExts.concat(sourceExts),
<ide> transformCache: TransformCaching.useTempDir(),
<ide> transformModulePath: transformModulePath,
<ide><path>local-cli/server/runServer.js
<ide> require('../../setupBabel')();
<ide> const InspectorProxy = require('./util/inspectorProxy.js');
<ide> const ReactPackager = require('../../packager');
<add>const Terminal = require('../../packager/src/lib/TerminalClass');
<ide>
<ide> const attachHMRServer = require('./util/attachHMRServer');
<ide> const connect = require('connect');
<ide> function getPackagerServer(args, config) {
<ide> LogReporter = require('../../packager/src/lib/TerminalReporter');
<ide> }
<ide>
<add> /* $FlowFixMe: Flow is wrong, Node.js docs specify that process.stdout is an
<add> * instance of a net.Socket (a local socket, not network). */
<add> const terminal = new Terminal(process.stdout);
<ide> return ReactPackager.createServer({
<ide> assetExts: defaultAssetExts.concat(args.assetExts),
<ide> blacklistRE: config.getBlacklistRE(),
<ide> function getPackagerServer(args, config) {
<ide> postMinifyProcess: config.postMinifyProcess,
<ide> projectRoots: args.projectRoots,
<ide> providesModuleNodeModules: providesModuleNodeModules,
<del> reporter: new LogReporter(),
<add> reporter: new LogReporter(terminal),
<ide> resetCache: args.resetCache,
<ide> sourceExts: defaultSourceExts.concat(args.sourceExts),
<ide> transformModulePath: transformModulePath,
<ide><path>packager/src/Server/index.js
<ide> const mime = require('mime-types');
<ide> const parsePlatformFilePath = require('../node-haste/lib/parsePlatformFilePath');
<ide> const path = require('path');
<ide> const symbolicate = require('./symbolicate');
<del>const terminal = require('../lib/terminal');
<ide> const url = require('url');
<ide>
<ide> const debug = require('debug')('RNP:Server');
<ide> class Server {
<ide> e => {
<ide> res.writeHead(500);
<ide> res.end('Internal Error');
<del> terminal.log(e.stack); // eslint-disable-line no-console-disallow
<add> // FIXME: $FlowFixMe: that's a hack, doesn't work with JSON-mode output
<add> this._reporter.terminal && this._reporter.terminal.log(e.stack);
<ide> }
<ide> );
<ide> } else {
<add><path>packager/src/lib/TerminalClass.js
<del><path>packager/src/lib/terminal.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @flow
<add> * @format
<ide> */
<ide>
<ide> 'use strict';
<ide> function getTTYStream(stream: net$Socket): ?tty.WriteStream {
<ide> * single responsibility of handling status messages.
<ide> */
<ide> class Terminal {
<del>
<ide> _logLines: Array<string>;
<ide> _nextStatusStr: string;
<ide> _scheduleUpdate: () => void;
<ide> class Terminal {
<ide> });
<ide> this._logLines = [];
<ide> if (ttyStream != null) {
<del> this._nextStatusStr = chunkString(this._nextStatusStr, ttyStream.columns).join('\n');
<add> this._nextStatusStr = chunkString(
<add> this._nextStatusStr,
<add> ttyStream.columns,
<add> ).join('\n');
<ide> _stream.write(this._nextStatusStr);
<ide> }
<ide> this._statusStr = this._nextStatusStr;
<ide> class Terminal {
<ide> this.log(this._nextStatusStr);
<ide> this._nextStatusStr = '';
<ide> }
<del>
<del>}
<del>
<del>/**
<del> * On the same pattern as node.js `console` module, we export the stdout-based
<del> * terminal at the top-level, but provide access to the Terminal class as a
<del> * field (so it can be used, for instance, with stderr).
<del> */
<del>class GlobalTerminal extends Terminal {
<del>
<del> Terminal: Class<Terminal>;
<del>
<del> constructor() {
<del> /* $FlowFixMe: Flow is wrong, Node.js docs specify that process.stdout is an
<del> * instance of a net.Socket (a local socket, not network). */
<del> super(process.stdout);
<del> this.Terminal = Terminal;
<del> }
<del>
<ide> }
<ide>
<del>module.exports = new GlobalTerminal();
<add>module.exports = Terminal;
<ide><path>packager/src/lib/TerminalReporter.js
<ide> const chalk = require('chalk');
<ide> const formatBanner = require('./formatBanner');
<ide> const path = require('path');
<ide> const reporting = require('./reporting');
<del>const terminal = require('./terminal');
<ide> const throttle = require('lodash/throttle');
<ide> const util = require('util');
<ide>
<add>import type Terminal from './TerminalClass';
<ide> import type {ReportableEvent, GlobalCacheDisabledReason} from './reporting';
<ide>
<ide> const DEP_GRAPH_MESSAGE = 'Loading dependency graph';
<ide> class TerminalReporter {
<ide> totalFileCount: number,
<ide> }) => void;
<ide>
<del> constructor() {
<add> +terminal: Terminal;
<add>
<add> constructor(terminal: Terminal) {
<ide> this._dependencyGraphHasLoaded = false;
<ide> this._activeBundles = new Map();
<ide> this._scheduleUpdateBundleProgress = throttle(data => {
<ide> this.update({...data, type: 'bundle_transform_progressed_throttled'});
<ide> }, 100);
<add> (this: any).terminal = terminal;
<ide> }
<ide>
<ide> /**
<ide> class TerminalReporter {
<ide> const format = GLOBAL_CACHE_DISABLED_MESSAGE_FORMAT;
<ide> switch (reason) {
<ide> case 'too_many_errors':
<del> reporting.logWarning(terminal, format, 'it has been failing too many times.');
<add> reporting.logWarning(
<add> this.terminal,
<add> format,
<add> 'it has been failing too many times.',
<add> );
<ide> break;
<ide> case 'too_many_misses':
<del> reporting.logWarning(terminal, format, 'it has been missing too many consecutive keys.');
<add> reporting.logWarning(
<add> this.terminal,
<add> format,
<add> 'it has been missing too many consecutive keys.',
<add> );
<ide> break;
<ide> }
<ide> }
<ide> class TerminalReporter {
<ide> ratio: 1,
<ide> transformedFileCount: progress.totalFileCount,
<ide> }, 'done');
<del> terminal.log(msg);
<add> this.terminal.log(msg);
<ide> }
<ide> }
<ide>
<ide> _logBundleBuildFailed(buildID: string) {
<ide> const progress = this._activeBundles.get(buildID);
<ide> if (progress != null) {
<ide> const msg = this._getBundleStatusMessage(progress, 'failed');
<del> terminal.log(msg);
<add> this.terminal.log(msg);
<ide> }
<ide> }
<ide>
<ide> _logPackagerInitializing(port: number, projectRoots: $ReadOnlyArray<string>) {
<del> terminal.log(
<add> this.terminal.log(
<ide> formatBanner(
<ide> 'Running packager on port ' +
<ide> port +
<ide> class TerminalReporter {
<ide> )
<ide> );
<ide>
<del> terminal.log(
<add> this.terminal.log(
<ide> 'Looking for JS files in\n ',
<ide> chalk.dim(projectRoots.join('\n ')),
<ide> '\n'
<ide> class TerminalReporter {
<ide>
<ide> _logPackagerInitializingFailed(port: number, error: Error) {
<ide> if (error.code === 'EADDRINUSE') {
<del> terminal.log(
<add> this.terminal.log(
<ide> chalk.bgRed.bold(' ERROR '),
<ide> chalk.red("Packager can't listen on port", chalk.bold(port))
<ide> );
<del> terminal.log('Most likely another process is already using this port');
<del> terminal.log('Run the following command to find out which process:');
<del> terminal.log('\n ', chalk.bold('lsof -i :' + port), '\n');
<del> terminal.log('Then, you can either shut down the other process:');
<del> terminal.log('\n ', chalk.bold('kill -9 <PID>'), '\n');
<del> terminal.log('or run packager on different port.');
<add> this.terminal.log('Most likely another process is already using this port');
<add> this.terminal.log('Run the following command to find out which process:');
<add> this.terminal.log('\n ', chalk.bold('lsof -i :' + port), '\n');
<add> this.terminal.log('Then, you can either shut down the other process:');
<add> this.terminal.log('\n ', chalk.bold('kill -9 <PID>'), '\n');
<add> this.terminal.log('or run packager on different port.');
<ide> } else {
<del> terminal.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
<add> this.terminal.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
<ide> const errorAttributes = JSON.stringify(error);
<ide> if (errorAttributes !== '{}') {
<del> terminal.log(chalk.red(errorAttributes));
<add> this.terminal.log(chalk.red(errorAttributes));
<ide> }
<del> terminal.log(chalk.red(error.stack));
<add> this.terminal.log(chalk.red(error.stack));
<ide> }
<ide> }
<ide>
<ide> class TerminalReporter {
<ide> this._logPackagerInitializing(event.port, event.projectRoots);
<ide> break;
<ide> case 'initialize_packager_done':
<del> terminal.log('\nReact packager ready.\n');
<add> this.terminal.log('\nReact packager ready.\n');
<ide> break;
<ide> case 'initialize_packager_failed':
<ide> this._logPackagerInitializingFailed(event.port, event.error);
<ide> class TerminalReporter {
<ide> this._logBundlingError(event.error);
<ide> break;
<ide> case 'dep_graph_loaded':
<del> terminal.log(`${DEP_GRAPH_MESSAGE}, done.`);
<add> this.terminal.log(`${DEP_GRAPH_MESSAGE}, done.`);
<ide> break;
<ide> case 'global_cache_disabled':
<ide> this._logCacheDisabled(event.reason);
<ide> break;
<ide> case 'transform_cache_reset':
<del> reporting.logWarning(terminal, 'the transform cache was reset.');
<add> reporting.logWarning(this.terminal, 'the transform cache was reset.');
<ide> break;
<ide> case 'worker_stdout_chunk':
<ide> this._logWorkerChunk('stdout', event.chunk);
<ide> class TerminalReporter {
<ide> */
<ide> _logBundlingError(error: Error) {
<ide> const str = JSON.stringify(error.message);
<del> reporting.logError(terminal, 'bundling failed: %s', str);
<add> reporting.logError(this.terminal, 'bundling failed: %s', str);
<ide> }
<ide>
<ide> _logWorkerChunk(origin: 'stdout' | 'stderr', chunk: string) {
<ide> class TerminalReporter {
<ide> lines.splice(lines.length - 1, 1);
<ide> }
<ide> lines.forEach(line => {
<del> terminal.log(`transform[${origin}]: ${line}`);
<add> this.terminal.log(`transform[${origin}]: ${line}`);
<ide> });
<ide> }
<ide>
<ide> class TerminalReporter {
<ide> update(event: TerminalReportableEvent) {
<ide> this._log(event);
<ide> this._updateState(event);
<del> terminal.status(this._getStatusMessage());
<add> this.terminal.status(this._getStatusMessage());
<ide> }
<ide>
<ide> }
<ide><path>packager/src/lib/TransformCaching.js
<ide> const invariant = require('fbjs/lib/invariant');
<ide> const mkdirp = require('mkdirp');
<ide> const path = require('path');
<ide> const rimraf = require('rimraf');
<del>const terminal = require('../lib/terminal');
<ide> const writeFileAtomicSync = require('write-file-atomic').sync;
<ide>
<ide> import type {Options as WorkerOptions} from '../JSTransformer/worker';
<ide> class FileBasedCache {
<ide> lastCollected == null ||
<ide> Date.now() - lastCollected > GARBAGE_COLLECTION_PERIOD
<ide> ) {
<del> this._collectSyncNoThrow();
<add> this._collectSyncNoThrow(options.reporter);
<ide> }
<ide> }
<ide>
<ide> class FileBasedCache {
<ide> * We want to avoid preventing tool use if the cleanup fails for some reason,
<ide> * but still provide some chance for people to report/fix things.
<ide> */
<del> _collectSyncNoThrow() {
<add> _collectSyncNoThrow(reporter: Reporter) {
<ide> try {
<ide> this._collectCacheIfOldSync();
<ide> } catch (error) {
<del> terminal.log(error.stack);
<del> terminal.log(
<del> 'Error: Cleaning up the cache folder failed. Continuing anyway.',
<del> );
<del> terminal.log('The cache folder is: %s', this._rootPath);
<add> // FIXME: $FlowFixMe: this is a hack, only works for TerminalReporter
<add> const {terminal} = reporter;
<add> if (terminal != null) {
<add> terminal.log(error.stack);
<add> terminal.log(
<add> 'Error: Cleaning up the cache folder failed. Continuing anyway.',
<add> );
<add> terminal.log('The cache folder is: %s', this._rootPath);
<add> }
<ide> }
<ide> this._lastCollected = Date.now();
<ide> }
<add><path>packager/src/lib/__tests__/TerminalClass-test.js
<del><path>packager/src/lib/__tests__/terminal-test.js
<ide>
<ide> 'use strict';
<ide>
<del>jest.dontMock('../terminal').dontMock('lodash/throttle');
<add>jest.dontMock('../TerminalClass').dontMock('lodash/throttle');
<ide>
<ide> jest.mock('readline', () => ({
<ide> moveCursor: (stream, dx, dy) => {
<ide> jest.mock('readline', () => ({
<ide> },
<ide> }));
<ide>
<del>describe('terminal', () => {
<add>describe('Terminal', () => {
<ide>
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> });
<ide>
<ide> function prepare(isTTY) {
<del> const {Terminal} = require('../terminal');
<add> const Terminal = require('../TerminalClass');
<ide> const lines = 10;
<ide> const columns = 10;
<ide> const stream = Object.create(
<ide><path>packager/src/lib/__tests__/TransformCaching-test.js
<ide> describe('TransformCaching.FileBasedCache', () => {
<ide> const {result} = args;
<ide> const cachedResult = transformCache.readSync({
<ide> ...args,
<del> cacheOptions: {resetCache: false},
<add> cacheOptions: {reporter: {}, resetCache: false},
<ide> });
<ide> expect(cachedResult.result).toEqual(result);
<ide> });
<ide> describe('TransformCaching.FileBasedCache', () => {
<ide> const {result} = args;
<ide> const cachedResult = transformCache.readSync({
<ide> ...args,
<del> cacheOptions: {resetCache: false},
<add> cacheOptions: {reporter: {}, resetCache: false},
<ide> });
<ide> expect(cachedResult.result).toEqual(result);
<ide> });
<ide> allCases.pop();
<ide> allCases.forEach(entry => {
<ide> const cachedResult = transformCache.readSync({
<ide> ...argsFor(entry),
<del> cacheOptions: {resetCache: false},
<add> cacheOptions: {reporter: {}, resetCache: false},
<ide> });
<ide> expect(cachedResult.result).toBeNull();
<ide> expect(cachedResult.outdatedDependencies).toEqual(['foo', 'bar']);
<ide><path>packager/src/lib/reporting.js
<ide> const chalk = require('chalk');
<ide> const util = require('util');
<ide>
<del>import type {Terminal} from './terminal';
<add>import type Terminal from './TerminalClass';
<ide>
<ide> export type GlobalCacheDisabledReason = 'too_many_errors' | 'too_many_misses';
<ide> | 9 |
PHP | PHP | fix phpunit mocks | b204289a99eb29dc10ac8d75dd2bc33f3b6ae051 | <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Controller\Component;
<ide>
<add>use Cake\Auth\BaseAuthorize;
<add>use Cake\Auth\FormAuthenticate;
<ide> use Cake\Controller\Component\AuthComponent;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\Event;
<ide> public function testIsErrorOrTests()
<ide> */
<ide> public function testIdentify()
<ide> {
<del> $AuthLoginFormAuthenticate = $this->getMockBuilder('Cake\Controller\Component\Auth\FormAuthenticate')
<add> $AuthLoginFormAuthenticate = $this->getMockBuilder(FormAuthenticate::class)
<ide> ->setMethods(['authenticate'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> public function testIdentify()
<ide> */
<ide> public function testIdentifyArrayAccess()
<ide> {
<del> $AuthLoginFormAuthenticate = $this->getMockBuilder('Cake\Controller\Component\Auth\FormAuthenticate')
<add> $AuthLoginFormAuthenticate = $this->getMockBuilder(FormAuthenticate::class)
<ide> ->setMethods(['authenticate'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> public function testIsAuthorizedMissingFile()
<ide> */
<ide> public function testIsAuthorizedDelegation()
<ide> {
<del> $AuthMockOneAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $AuthMockOneAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<del> $AuthMockTwoAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $AuthMockTwoAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<del> $AuthMockThreeAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $AuthMockThreeAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> public function testIsAuthorizedDelegation()
<ide> */
<ide> public function testIsAuthorizedWithArrayObject()
<ide> {
<del> $AuthMockOneAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $AuthMockOneAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> public function testIsAuthorizedWithArrayObject()
<ide> */
<ide> public function testIsAuthorizedUsingUserInSession()
<ide> {
<del> $AuthMockFourAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $AuthMockFourAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> public function testNoLoginRedirectForAuthenticatedUser()
<ide>
<ide> $this->Auth->session->write('Auth.User.id', '1');
<ide> $this->Auth->config('authenticate', ['Form']);
<del> $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize')
<add> $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->setMockClassName('NoLoginRedirectMockAuthorize')
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Database\Connection;
<add>use Cake\Database\Driver\Mysql;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testMissingDriver()
<ide> */
<ide> public function testDisabledDriver()
<ide> {
<del> $mock = $this->getMockBuilder('\Cake\Database\Connection\Driver')
<add> $mock = $this->getMockBuilder(Mysql::class)
<ide> ->setMethods(['enabled'])
<ide> ->setMockClassName('DriverMock')
<ide> ->getMock();
<ide><path>tests/TestCase/Database/Driver/SqliteTest.php
<ide> public static function schemaValueProvider()
<ide> public function testSchemaValue($input, $expected)
<ide> {
<ide> $driver = new Sqlite();
<del> $mock = $this->getMockBuilder('FakePdo')
<add> $mock = $this->getMockBuilder(\PDO::class)
<ide> ->setMethods(['quote', 'quoteIdentifier'])
<add> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('quote')
<ide><path>tests/TestCase/Database/DriverTest.php
<ide> namespace Cake\Test\TestCase\Database;
<ide>
<ide> use Cake\Database\Driver;
<del>use Cake\Database\Mysql;
<add>use Cake\Database\Driver\Mysql;
<ide> use Cake\Database\Query;
<ide> use Cake\Database\QueryCompiler;
<ide> use Cake\Database\ValueBinder;
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testDescribeJson()
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new \Cake\Database\Driver\Mysql();
<del> $mock = $this->getMockBuilder('FakePdo')
<add> $mock = $this->getMockBuilder(\PDO::class)
<ide> ->setMethods(['quote', 'quoteIdentifier', 'getAttribute'])
<add> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('quote')
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public function testTruncateSql()
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new \Cake\Database\Driver\Postgres();
<del> $mock = $this->getMockBuilder('FakePdo')
<add> $mock = $this->getMockBuilder(\PDO::class)
<ide> ->setMethods(['quote'])
<add> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('quote')
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testTruncateSqlNoSequences()
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new \Cake\Database\Driver\Sqlite();
<del> $mock = $this->getMockBuilder('FakePdo')
<add> $mock = $this->getMockBuilder(\PDO::class)
<ide> ->setMethods(['quote', 'prepare'])
<add> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('quote')
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public function testTruncateSql()
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new \Cake\Database\Driver\Sqlserver();
<del> $mock = $this->getMockBuilder('FakePdo')
<add> $mock = $this->getMockBuilder(\PDO::class)
<ide> ->setMethods(['quote'])
<add> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('quote') | 8 |
Python | Python | add pagination. thanks @devioustree! | 5db422c9d38277789bb6d2cf214f46ed7642d395 | <ide><path>djangorestframework/mixins.py
<ide> """
<del>The :mod:`mixins` module provides a set of reusable `mixin`
<add>The :mod:`mixins` module provides a set of reusable `mixin`
<ide> classes that can be added to a `View`.
<ide> """
<ide>
<ide> from django.contrib.auth.models import AnonymousUser
<del>from django.db.models.query import QuerySet
<add>from django.core.paginator import Paginator
<ide> from django.db.models.fields.related import ForeignKey
<ide> from django.http import HttpResponse
<ide>
<ide> from djangorestframework import status
<del>from djangorestframework.parsers import FormParser, MultiPartParser
<ide> from djangorestframework.renderers import BaseRenderer
<ide> from djangorestframework.resources import Resource, FormResource, ModelResource
<ide> from djangorestframework.response import Response, ErrorResponse
<ide> from djangorestframework.utils import as_tuple, MSIE_USER_AGENT_REGEX
<ide> from djangorestframework.utils.mediatypes import is_form_media_type, order_by_precedence
<ide>
<del>from decimal import Decimal
<del>import re
<ide> from StringIO import StringIO
<ide>
<ide>
<ide> class RequestMixin(object):
<ide>
<ide> """
<ide> The set of request parsers that the view can handle.
<del>
<add>
<ide> Should be a tuple/list of classes as described in the :mod:`parsers` module.
<ide> """
<ide> parsers = ()
<ide> def _perform_form_overloading(self):
<ide> # We only need to use form overloading on form POST requests.
<ide> if not self._USE_FORM_OVERLOADING or self._method != 'POST' or not is_form_media_type(self._content_type):
<ide> return
<del>
<add>
<ide> # At this point we're committed to parsing the request as form data.
<ide> self._data = data = self.request.POST.copy()
<ide> self._files = self.request.FILES
<ide> def _parsed_media_types(self):
<ide> """
<ide> return [parser.media_type for parser in self.parsers]
<ide>
<del>
<add>
<ide> @property
<ide> def _default_parser(self):
<ide> """
<ide> Return the view's default parser class.
<del> """
<add> """
<ide> return self.parsers[0]
<ide>
<ide>
<ide> def _default_parser(self):
<ide> class ResponseMixin(object):
<ide> """
<ide> Adds behavior for pluggable `Renderers` to a :class:`views.View` class.
<del>
<add>
<ide> Default behavior is to use standard HTTP Accept header content negotiation.
<ide> Also supports overriding the content type by specifying an ``_accept=`` parameter in the URL.
<ide> Ignores Accept headers from Internet Explorer user agents and uses a sensible browser Accept header instead.
<ide> class ResponseMixin(object):
<ide>
<ide> """
<ide> The set of response renderers that the view can handle.
<del>
<del> Should be a tuple/list of classes as described in the :mod:`renderers` module.
<add>
<add> Should be a tuple/list of classes as described in the :mod:`renderers` module.
<ide> """
<ide> renderers = ()
<ide>
<ide> def render(self, response):
<ide> # Set the media type of the response
<ide> # Note that the renderer *could* override it in .render() if required.
<ide> response.media_type = renderer.media_type
<del>
<add>
<ide> # Serialize the response content
<ide> if response.has_content_body:
<ide> content = renderer.render(response.cleaned_content, media_type)
<ide> def _rendered_media_types(self):
<ide> Return an list of all the media types that this view can render.
<ide> """
<ide> return [renderer.media_type for renderer in self.renderers]
<del>
<add>
<ide> @property
<ide> def _rendered_formats(self):
<ide> """
<ide> class AuthMixin(object):
<ide> """
<ide> Simple :class:`mixin` class to add authentication and permission checking to a :class:`View` class.
<ide> """
<del>
<add>
<ide> """
<ide> The set of authentication types that this view can handle.
<del>
<del> Should be a tuple/list of classes as described in the :mod:`authentication` module.
<add>
<add> Should be a tuple/list of classes as described in the :mod:`authentication` module.
<ide> """
<ide> authentication = ()
<ide>
<ide> """
<ide> The set of permissions that will be enforced on this view.
<del>
<del> Should be a tuple/list of classes as described in the :mod:`permissions` module.
<add>
<add> Should be a tuple/list of classes as described in the :mod:`permissions` module.
<ide> """
<ide> permissions = ()
<ide>
<ide> class AuthMixin(object):
<ide> def user(self):
<ide> """
<ide> Returns the :obj:`user` for the current request, as determined by the set of
<del> :class:`authentication` classes applied to the :class:`View`.
<add> :class:`authentication` classes applied to the :class:`View`.
<ide> """
<ide> if not hasattr(self, '_user'):
<ide> self._user = self._authenticate()
<ide> def post(self, request, *args, **kwargs):
<ide>
<ide> for fieldname in m2m_data:
<ide> manager = getattr(instance, fieldname)
<del>
<add>
<ide> if hasattr(manager, 'add'):
<ide> manager.add(*m2m_data[fieldname][1])
<ide> else:
<ide> data = {}
<ide> data[manager.source_field_name] = instance
<del>
<add>
<ide> for related_item in m2m_data[fieldname][1]:
<ide> data[m2m_data[fieldname][0]] = related_item
<ide> manager.through(**data).save()
<ide> class UpdateModelMixin(object):
<ide> """
<ide> def put(self, request, *args, **kwargs):
<ide> model = self.resource.model
<del>
<del> # TODO: update on the url of a non-existing resource url doesn't work correctly at the moment - will end up with a new url
<add>
<add> # TODO: update on the url of a non-existing resource url doesn't work correctly at the moment - will end up with a new url
<ide> try:
<ide> if args:
<ide> # If we have any none kwargs then assume the last represents the primary key
<ide> def get(self, request, *args, **kwargs):
<ide> return queryset.filter(**kwargs)
<ide>
<ide>
<add>########## Pagination Mixins ##########
<add>
<add>class PaginatorMixin(object):
<add> """
<add> Adds pagination support to GET requests
<add> Obviously should only be used on lists :)
<add>
<add> A default limit can be set by setting `limit` on the object. This will also
<add> be used as the maximum if the client sets the `limit` GET param
<add> """
<add> limit = 20
<add>
<add> def get_limit(self):
<add> """ Helper method to determine what the `limit` should be """
<add> try:
<add> limit = int(self.request.GET.get('limit', self.limit))
<add> return min(limit, self.limit)
<add> except ValueError:
<add> return self.limit
<add>
<add> def url_with_page_number(self, page_number):
<add> """ Constructs a url used for getting the next/previous urls """
<add> url = "%s?page=%d" % (self.request.path, page_number)
<add>
<add> limit = self.get_limit()
<add> if limit != self.limit:
<add> url = "%s&limit=%d" % (url, limit)
<add>
<add> return url
<add>
<add> def next(self, page):
<add> """ Returns a url to the next page of results (if any) """
<add> if not page.has_next():
<add> return None
<add>
<add> return self.url_with_page_number(page.next_page_number())
<add>
<add> def previous(self, page):
<add> """ Returns a url to the previous page of results (if any) """
<add> if not page.has_previous():
<add> return None
<add>
<add> return self.url_with_page_number(page.previous_page_number())
<add>
<add> def serialize_page_info(self, page):
<add> """ This is some useful information that is added to the response """
<add> return {
<add> 'next': self.next(page),
<add> 'page': page.number,
<add> 'pages': page.paginator.num_pages,
<add> 'per_page': self.get_limit(),
<add> 'previous': self.previous(page),
<add> 'total': page.paginator.count,
<add> }
<add>
<add> def filter_response(self, obj):
<add> """
<add> Given the response content, paginate and then serialize.
<add>
<add> The response is modified to include to useful data relating to the number
<add> of objects, number of pages, next/previous urls etc. etc.
<add>
<add> The serialised objects are put into `results` on this new, modified
<add> response
<add> """
<add>
<add> # We don't want to paginate responses for anything other than GET requests
<add> if self.method.upper() != 'GET':
<add> return self._resource.filter_response(obj)
<add>
<add> paginator = Paginator(obj, self.get_limit())
<add>
<add> try:
<add> page_num = int(self.request.GET.get('page', '1'))
<add> except ValueError:
<add> raise ErrorResponse(status.HTTP_404_NOT_FOUND,
<add> {'detail': 'That page contains no results'})
<add>
<add> if page_num not in paginator.page_range:
<add> raise ErrorResponse(status.HTTP_404_NOT_FOUND,
<add> {'detail': 'That page contains no results'})
<add>
<add> page = paginator.page(page_num)
<add>
<add> serialized_object_list = self._resource.filter_response(page.object_list)
<add> serialized_page_info = self.serialize_page_info(page)
<add>
<add> serialized_page_info['results'] = serialized_object_list
<add>
<add> return serialized_page_info
<ide><path>djangorestframework/tests/mixins.py
<del>"""Tests for the status module"""
<add>"""Tests for the mixin module"""
<ide> from django.test import TestCase
<add>from django.utils import simplejson as json
<ide> from djangorestframework import status
<ide> from djangorestframework.compat import RequestFactory
<ide> from django.contrib.auth.models import Group, User
<del>from djangorestframework.mixins import CreateModelMixin
<add>from djangorestframework.mixins import CreateModelMixin, PaginatorMixin
<ide> from djangorestframework.resources import ModelResource
<add>from djangorestframework.response import Response
<ide> from djangorestframework.tests.models import CustomUser
<add>from djangorestframework.views import View
<ide>
<ide>
<del>class TestModelCreation(TestCase):
<add>class TestModelCreation(TestCase):
<ide> """Tests on CreateModelMixin"""
<ide>
<ide> def setUp(self):
<ide> class GroupResource(ModelResource):
<ide> mixin = CreateModelMixin()
<ide> mixin.resource = GroupResource
<ide> mixin.CONTENT = form_data
<del>
<add>
<ide> response = mixin.post(request)
<ide> self.assertEquals(1, Group.objects.count())
<ide> self.assertEquals('foo', response.cleaned_content.name)
<del>
<ide>
<ide> def test_creation_with_m2m_relation(self):
<ide> class UserResource(ModelResource):
<ide> model = User
<del>
<add>
<ide> def url(self, instance):
<ide> return "/users/%i" % instance.id
<ide>
<ide> group = Group(name='foo')
<ide> group.save()
<ide>
<del> form_data = {'username': 'bar', 'password': 'baz', 'groups': [group.id]}
<add> form_data = {
<add> 'username': 'bar',
<add> 'password': 'baz',
<add> 'groups': [group.id]
<add> }
<ide> request = self.req.post('/groups', data=form_data)
<ide> cleaned_data = dict(form_data)
<ide> cleaned_data['groups'] = [group]
<ide> def url(self, instance):
<ide> self.assertEquals(1, User.objects.count())
<ide> self.assertEquals(1, response.cleaned_content.groups.count())
<ide> self.assertEquals('foo', response.cleaned_content.groups.all()[0].name)
<del>
<add>
<ide> def test_creation_with_m2m_relation_through(self):
<ide> """
<ide> Tests creation where the m2m relation uses a through table
<ide> """
<ide> class UserResource(ModelResource):
<ide> model = CustomUser
<del>
<add>
<ide> def url(self, instance):
<ide> return "/customusers/%i" % instance.id
<del>
<del> form_data = {'username': 'bar0', 'groups': []}
<add>
<add> form_data = {'username': 'bar0', 'groups': []}
<ide> request = self.req.post('/groups', data=form_data)
<ide> cleaned_data = dict(form_data)
<ide> cleaned_data['groups'] = []
<ide> def url(self, instance):
<ide>
<ide> response = mixin.post(request)
<ide> self.assertEquals(1, CustomUser.objects.count())
<del> self.assertEquals(0, response.cleaned_content.groups.count())
<add> self.assertEquals(0, response.cleaned_content.groups.count())
<ide>
<ide> group = Group(name='foo1')
<ide> group.save()
<ide>
<del> form_data = {'username': 'bar1', 'groups': [group.id]}
<add> form_data = {'username': 'bar1', 'groups': [group.id]}
<ide> request = self.req.post('/groups', data=form_data)
<ide> cleaned_data = dict(form_data)
<ide> cleaned_data['groups'] = [group]
<ide> def url(self, instance):
<ide> self.assertEquals(2, CustomUser.objects.count())
<ide> self.assertEquals(1, response.cleaned_content.groups.count())
<ide> self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name)
<del>
<del>
<add>
<ide> group2 = Group(name='foo2')
<del> group2.save()
<del>
<del> form_data = {'username': 'bar2', 'groups': [group.id, group2.id]}
<add> group2.save()
<add>
<add> form_data = {'username': 'bar2', 'groups': [group.id, group2.id]}
<ide> request = self.req.post('/groups', data=form_data)
<ide> cleaned_data = dict(form_data)
<ide> cleaned_data['groups'] = [group, group2]
<ide> def url(self, instance):
<ide> self.assertEquals(2, response.cleaned_content.groups.count())
<ide> self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name)
<ide> self.assertEquals('foo2', response.cleaned_content.groups.all()[1].name)
<del>
<ide>
<add>
<add>class MockPaginatorView(PaginatorMixin, View):
<add> total = 60
<add>
<add> def get(self, request):
<add> return range(0, self.total)
<add>
<add> def post(self, request):
<add> return Response(status.CREATED, {'status': 'OK'})
<add>
<add>
<add>class TestPagination(TestCase):
<add> def setUp(self):
<add> self.req = RequestFactory()
<add>
<add> def test_default_limit(self):
<add> """ Tests if pagination works without overwriting the limit """
<add> request = self.req.get('/paginator')
<add> response = MockPaginatorView.as_view()(request)
<add>
<add> content = json.loads(response.content)
<add>
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(MockPaginatorView.total, content['total'])
<add> self.assertEqual(MockPaginatorView.limit, content['per_page'])
<add>
<add> self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
<add>
<add> def test_overwriting_limit(self):
<add> """ Tests if the limit can be overwritten """
<add> limit = 10
<add>
<add> request = self.req.get('/paginator')
<add> response = MockPaginatorView.as_view(limit=limit)(request)
<add>
<add> content = json.loads(response.content)
<add>
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(content['per_page'], limit)
<add>
<add> self.assertEqual(range(0, limit), content['results'])
<add>
<add> def test_limit_param(self):
<add> """ Tests if the client can set the limit """
<add> from math import ceil
<add>
<add> limit = 5
<add> num_pages = int(ceil(MockPaginatorView.total / float(limit)))
<add>
<add> request = self.req.get('/paginator/?limit=%d' % limit)
<add> response = MockPaginatorView.as_view()(request)
<add>
<add> content = json.loads(response.content)
<add>
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(MockPaginatorView.total, content['total'])
<add> self.assertEqual(limit, content['per_page'])
<add> self.assertEqual(num_pages, content['pages'])
<add>
<add> def test_exceeding_limit(self):
<add> """ Makes sure the client cannot exceed the default limit """
<add> from math import ceil
<add>
<add> limit = MockPaginatorView.limit + 10
<add> num_pages = int(ceil(MockPaginatorView.total / float(limit)))
<add>
<add> request = self.req.get('/paginator/?limit=%d' % limit)
<add> response = MockPaginatorView.as_view()(request)
<add>
<add> content = json.loads(response.content)
<add>
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(MockPaginatorView.total, content['total'])
<add> self.assertNotEqual(limit, content['per_page'])
<add> self.assertNotEqual(num_pages, content['pages'])
<add> self.assertEqual(MockPaginatorView.limit, content['per_page'])
<add>
<add> def test_only_works_for_get(self):
<add> """ Pagination should only work for GET requests """
<add> request = self.req.post('/paginator', data={'content': 'spam'})
<add> response = MockPaginatorView.as_view()(request)
<add>
<add> content = json.loads(response.content)
<add>
<add> self.assertEqual(response.status_code, status.CREATED)
<add> self.assertEqual(None, content.get('per_page'))
<add> self.assertEqual('OK', content['status'])
<add>
<add> def test_non_int_page(self):
<add> """ Tests that it can handle invalid values """
<add> request = self.req.get('/paginator/?page=spam')
<add> response = MockPaginatorView.as_view()(request)
<add>
<add> self.assertEqual(response.status_code, status.NOT_FOUND)
<add>
<add> def test_page_range(self):
<add> """ Tests that the page range is handle correctly """
<add> request = self.req.get('/paginator/?page=0')
<add> response = MockPaginatorView.as_view()(request)
<add> content = json.loads(response.content)
<add> self.assertEqual(response.status_code, status.NOT_FOUND)
<add>
<add> request = self.req.get('/paginator/')
<add> response = MockPaginatorView.as_view()(request)
<add> content = json.loads(response.content)
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
<add>
<add> num_pages = content['pages']
<add>
<add> request = self.req.get('/paginator/?page=%d' % num_pages)
<add> response = MockPaginatorView.as_view()(request)
<add> content = json.loads(response.content)
<add> self.assertEqual(response.status_code, status.OK)
<add> self.assertEqual(range(MockPaginatorView.limit*(num_pages-1), MockPaginatorView.total), content['results'])
<add>
<add> request = self.req.get('/paginator/?page=%d' % (num_pages + 1,))
<add> response = MockPaginatorView.as_view()(request)
<add> content = json.loads(response.content)
<add> self.assertEqual(response.status_code, status.NOT_FOUND) | 2 |
PHP | PHP | add dispatchtoqueue to busfake | 14b4a4331a547dc21608e3f3e18006bfb0317add | <ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php
<ide> namespace Illuminate\Support\Testing\Fakes;
<ide>
<ide> use Closure;
<del>use Illuminate\Contracts\Bus\Dispatcher;
<add>use Illuminate\Contracts\Bus\QueueingDispatcher;
<ide> use Illuminate\Support\Arr;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<ide>
<del>class BusFake implements Dispatcher
<add>class BusFake implements QueueingDispatcher
<ide> {
<ide> /**
<ide> * The original Bus dispatcher implementation.
<ide> *
<del> * @var \Illuminate\Contracts\Bus\Dispatcher
<add> * @var \Illuminate\Contracts\Bus\QueueingDispatcher
<ide> */
<ide> protected $dispatcher;
<ide>
<ide> class BusFake implements Dispatcher
<ide> /**
<ide> * Create a new bus fake instance.
<ide> *
<del> * @param \Illuminate\Contracts\Bus\Dispatcher $dispatcher
<add> * @param \Illuminate\Contracts\Bus\QueueingDispatcher $dispatcher
<ide> * @param array|string $jobsToFake
<ide> * @return void
<ide> */
<del> public function __construct(Dispatcher $dispatcher, $jobsToFake = [])
<add> public function __construct(QueueingDispatcher $dispatcher, $jobsToFake = [])
<ide> {
<ide> $this->dispatcher = $dispatcher;
<ide>
<ide> public function dispatchNow($command, $handler = null)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Dispatch a command to its appropriate handler behind a queue.
<add> *
<add> * @param mixed $command
<add> * @return mixed
<add> */
<add> public function dispatchToQueue($command)
<add> {
<add> if ($this->shouldFakeJob($command)) {
<add> $this->commands[get_class($command)][] = $command;
<add> } else {
<add> return $this->dispatcher->dispatchToQueue($command);
<add> }
<add> }
<add>
<ide> /**
<ide> * Dispatch a command to its appropriate handler.
<ide> *
<ide><path>tests/Support/SupportTestingBusFakeTest.php
<ide>
<ide> namespace Illuminate\Tests\Support;
<ide>
<del>use Illuminate\Contracts\Bus\Dispatcher;
<add>use Illuminate\Contracts\Bus\QueueingDispatcher;
<ide> use Illuminate\Support\Testing\Fakes\BusFake;
<ide> use Mockery as m;
<ide> use PHPUnit\Framework\Constraint\ExceptionMessage;
<ide> class SupportTestingBusFakeTest extends TestCase
<ide> protected function setUp(): void
<ide> {
<ide> parent::setUp();
<del> $this->fake = new BusFake(m::mock(Dispatcher::class));
<add> $this->fake = new BusFake(m::mock(QueueingDispatcher::class));
<ide> }
<ide>
<ide> protected function tearDown(): void
<ide> public function testAssertNotDispatchedAfterResponse()
<ide>
<ide> public function testAssertDispatchedWithIgnoreClass()
<ide> {
<del> $dispatcher = m::mock(Dispatcher::class);
<add> $dispatcher = m::mock(QueueingDispatcher::class);
<ide>
<ide> $job = new BusJobStub;
<ide> $dispatcher->shouldReceive('dispatch')->once()->with($job);
<ide> public function testAssertDispatchedWithIgnoreClass()
<ide>
<ide> public function testAssertDispatchedWithIgnoreCallback()
<ide> {
<del> $dispatcher = m::mock(Dispatcher::class);
<add> $dispatcher = m::mock(QueueingDispatcher::class);
<ide>
<ide> $job = new BusJobStub;
<ide> $dispatcher->shouldReceive('dispatch')->once()->with($job); | 2 |
Text | Text | add french translation | 5b618ac3f9f83c03eb9996e3bacf54c7933e5015 | <ide><path>threejs/lessons/fr/threejs-lights.md
<add>Title: Lumières en Three.js
<add>Description: Configuration des mulières
<add>TOC: Lights
<add>
<add>Cet article fait partie d'une série consacrée à Three.js.
<add>Le premier article s'intitule [Principes de base](threejs-fundamentals.html). Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là ou aussi voir l'article sur [la configuartion de votre environnement](threejs-setup.html). L'
<add>[article précédent](threejs-textures.html) parlait des textures.
<add>
<add>Voyons comment utiliser les différents types de lumières.
<add>
<add>En commençant par l'un de nos exemples précédents, mettons à jour la caméra. Nous allons régler le champ de vision à 45 degrés, le plan éloigné à 100 unités, et nous déplacerons la caméra de 10 unités vers le haut et 20 unités en arrière de l'origine.
<add>
<add>```js
<add>*const fov = 45;
<add>const aspect = 2; // the canvas default
<add>const near = 0.1;
<add>*const far = 100;
<add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add>+camera.position.set(0, 10, 20);
<add>```
<add>
<add>Ajoutons ensuite `OrbitControls`. `OrbitControls` permet à l'utilisateur de tourner ou de mettre la caméra en *orbite* autour d'un certain point. Il s'agit d'une fonctionnalité facultative de Three.js, nous devons donc d'abord l'importer
<add>
<add>```js
<add>import * as THREE from './resources/three/r127/build/three.module.js';
<add>+import {OrbitControls} from './resources/threejs/r127/examples/jsm/controls/OrbitControls.js';
<add>```
<add>
<add>Ensuite, nous pouvons l'utiliser. Nous passons à `OrbitControls` une caméra à contrôler et l'élément DOM à utiliser.
<add>
<add>```js
<add>const controls = new OrbitControls(camera, canvas);
<add>controls.target.set(0, 5, 0);
<add>controls.update();
<add>```
<add>
<add>Nous plaçons également la cible en orbite, 5 unités au-dessus de l'origine
<add>et appelons `controls.update` afin que les contrôles utilisent la nouvelle cible.
<add>
<add>Ensuite, créons des choses à éclairer. Nous allons d'abord faire un plan au sol. Nous allons appliquer une petite texture en damier de 2x2 pixels qui ressemble à ceci
<add>
<add><div class="threejs_center">
<add> <img src="../resources/images/checker.png" class="border" style="
<add> image-rendering: pixelated;
<add> width: 128px;
<add> ">
<add></div>
<add>
<add>Tout d'abord, chargeons la texture, définissons-la sur répétition, définissons le filtrage au plus proche et définissons le nombre de fois que nous voulons qu'elle se répète. Étant donné que la texture est un damier de 2x2 pixels, en répétant et en définissant la répétition à la moitié de la taille du plan, chaque case sur le damier aura exactement 1 unité de large ;
<add>
<add>```js
<add>const planeSize = 40;
<add>
<add>const loader = new THREE.TextureLoader();
<add>const texture = loader.load('resources/images/checker.png');
<add>texture.wrapS = THREE.RepeatWrapping;
<add>texture.wrapT = THREE.RepeatWrapping;
<add>texture.magFilter = THREE.NearestFilter;
<add>const repeats = planeSize / 2;
<add>texture.repeat.set(repeats, repeats);
<add>```
<add>
<add>Nous fabriquons ensuite une géométrie 'plane', un matériau et une 'mesh' pour l'insérer dans la scène. Les plans sont par défaut dans le plan XY, mais le sol est dans le plan XZ, nous le faisons donc pivoter.
<add>
<add>```js
<add>const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
<add>const planeMat = new THREE.MeshPhongMaterial({
<add> map: texture,
<add> side: THREE.DoubleSide,
<add>});
<add>const mesh = new THREE.Mesh(planeGeo, planeMat);
<add>mesh.rotation.x = Math.PI * -.5;
<add>scene.add(mesh);
<add>```
<add>
<add>Ajoutons un cube et une sphère, ainsi nous aurons 3 choses à éclairer dont le plan
<add>
<add>```js
<add>{
<add> const cubeSize = 4;
<add> const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
<add> const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
<add> const mesh = new THREE.Mesh(cubeGeo, cubeMat);
<add> mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
<add> scene.add(mesh);
<add>}
<add>{
<add> const sphereRadius = 3;
<add> const sphereWidthDivisions = 32;
<add> const sphereHeightDivisions = 16;
<add> const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
<add> const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
<add> const mesh = new THREE.Mesh(sphereGeo, sphereMat);
<add> mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
<add> scene.add(mesh);
<add>}
<add>```
<add>
<add>Maintenant que nous avons une scène à éclairer, ajoutons des lumières !
<add>
<add>## `AmbientLight`
<add>
<add>D'abord mettons en place une `AmbientLight`
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.AmbientLight(color, intensity);
<add>scene.add(light);
<add>```
<add>
<add>Faisons aussi en sorte que nous puissions ajuster les paramètres de la lumière.
<add>Utilisons à nouveau [dat.GUI](https://github.com/dataarts/dat.gui).
<add>Pour pouvoir ajuster la couleur via dat.GUI, nous avons besoin d'un petit 'helper' qui fournit à dat.GUI une couleur en hexadécimale (eg: `#FF8844`). Notre 'helper' obtiendra la couleur d'une propriété nommée, la convertira en une chaîne hexadécimale à offrir à dat.GUI. Lorsque dat.GUI essaie de définir la propriété de l'assistant, nous attribuons le résultat à la couleur de la lumière.
<add>
<add>Voici notre 'helper':
<add>
<add>```js
<add>class ColorGUIHelper {
<add> constructor(object, prop) {
<add> this.object = object;
<add> this.prop = prop;
<add> }
<add> get value() {
<add> return `#${this.object[this.prop].getHexString()}`;
<add> }
<add> set value(hexString) {
<add> this.object[this.prop].set(hexString);
<add> }
<add>}
<add>```
<add>
<add>Et voici le code de configuartion de dat.GUI
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>```
<add>
<add>Le résultat :
<add>
<add>{{{example url="../threejs-lights-ambient.html" }}}
<add>
<add>Cliquez/glissez pour mettre la caméra en *orbite*.
<add>
<add>Remarquez qu'il n'y a pas de définition. Les formes sont plates. L'`AmbientLight` multiplie simplement la couleur du matériau par la couleur de la lumière multipliée par l'intensité.
<add>
<add> color = materialColor * light.color * light.intensity;
<add>
<add>C'est ça. Il n'a pas de direction. Ce style d'éclairage ambiant n'est en fait pas très utile en tant qu'éclairage, à part changer la couleur de toute la scène, ce n'est pas vraiment un éclairage, ça rend juste les ténèbres moins sombres.
<add>
<add>
<add>XXXXXXXXXXXXXXXXXXXXXXX
<add>
<add>## `HemisphereLight`
<add>
<add>Passons à une `HemisphereLight`. Une `HemisphereLight` prend une couleur de ciel et une couleur de sol et multiplie simplement la couleur du matériau entre ces 2 couleurs : la couleur du ciel si la surface de l'objet pointe vers le haut et la couleur du sol si la surface de l'objet pointe vers le bas.
<add>
<add>Voici le nouveau code
<add>
<add>```js
<add>-const color = 0xFFFFFF;
<add>+const skyColor = 0xB1E1FF; // light blue
<add>+const groundColor = 0xB97A20; // brownish orange
<add>const intensity = 1;
<add>-const light = new THREE.AmbientLight(color, intensity);
<add>+const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
<add>scene.add(light);
<add>```
<add>
<add>Mettons aussi à jour le dat.GUI avec ces 2 couleurs
<add>
<add>```js
<add>const gui = new GUI();
<add>-gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('skyColor');
<add>+gui.addColor(new ColorGUIHelper(light, 'groundColor'), 'value').name('groundColor');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>```
<add>
<add>Le resultat :
<add>
<add>{{{example url="../threejs-lights-hemisphere.html" }}}
<add>
<add>Remarquez encore une fois qu'il n'y a presque pas de définition, tout a l'air plutôt plat. L'`HemisphereLight` utilisée en combinaison avec une autre lumière peut aider à donner une belle sorte d'influence de la couleur du ciel et du sol. Retenez qu'il est préférable de l'utiliser en combinaison avec une autre lumière ou à la place d'une `AmbientLight`.
<add>
<add>## `DirectionalLight`
<add>
<add>Remplaçons le code par une `DirectionalLight`.
<add>Une `DirectionalLight` est souvent utiliser pour représenter la lumière du soleil.
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.DirectionalLight(color, intensity);
<add>light.position.set(0, 10, 0);
<add>light.target.position.set(-5, 0, 0);
<add>scene.add(light);
<add>scene.add(light.target);
<add>```
<add>
<add>Notez que nous avons dû ajouter une `light` et une `light.target`
<add>à la scéne. Une `DirectionalLight` doit illuminer une cible.
<add>
<add>Faisons en sorte que nous puissions déplacer la cible en l'ajoutant à dat.GUI.
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>gui.add(light.target.position, 'x', -10, 10);
<add>gui.add(light.target.position, 'z', -10, 10);
<add>gui.add(light.target.position, 'y', 0, 10);
<add>```
<add>
<add>{{{example url="../threejs-lights-directional.html" }}}
<add>
<add>C'est un peu difficile de voir ce qui se passe. Three.js a un tas de 'helper' que nous pouvons ajouter à la scène pour voir les objets invibles. Utilisons, dans ce cas,
<add>`DirectionalLightHelper` qui a représente la source de lumière en direction de sa cible. Il suffit de lui ajouter une lumière et de l'ajouter à la scène.
<add>
<add>```js
<add>const helper = new THREE.DirectionalLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>Pendant que nous y sommes, faisons en sorte que nous puissions définir à la fois la position de la lumière et la cible. Pour ce faire, nous allons créer une fonction qui, étant donné un `Vector3`, ajustera ses propriétés `x`, `y` et `z` à l'aide de `dat.GUI`.
<add>
<add>```js
<add>function makeXYZGUI(gui, vector3, name, onChangeFn) {
<add> const folder = gui.addFolder(name);
<add> folder.add(vector3, 'x', -10, 10).onChange(onChangeFn);
<add> folder.add(vector3, 'y', 0, 10).onChange(onChangeFn);
<add> folder.add(vector3, 'z', -10, 10).onChange(onChangeFn);
<add> folder.open();
<add>}
<add>```
<add>
<add>Notez que nous devons appeler la fonction `update` du 'helper' à chaque fois que nous modifions quelque chose afin que l'assistant sache se mettre à jour. En tant que tel, nous passons une fonction `onChangeFn` pour être appelée à chaque fois que dat.GUI met à jour une valeur.
<add>
<add>Ensuite, nous pouvons l'utiliser à la fois pour la position de la lumière et la position de la cible comme ceci
<add>
<add>```js
<add>+function updateLight() {
<add>+ light.target.updateMatrixWorld();
<add>+ helper.update();
<add>+}
<add>+updateLight();
<add>
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>
<add>+makeXYZGUI(gui, light.position, 'position', updateLight);
<add>+makeXYZGUI(gui, light.target.position, 'target', updateLight);
<add>```
<add>
<add>Maintenant, nous pouvons bouger la lumière, et sa cible.
<add>
<add>{{{example url="../threejs-lights-directional-w-helper.html" }}}
<add>
<add>Mettez la caméra en orbite et il devient plus facile de voir. Le plan représente une lumière directionnelle car une lumière directionnelle calcule la lumière venant dans une direction. Il n'y a aucun point d'où vient la lumière, c'est un plan de lumière infini qui projette des rayons de lumière parallèles.
<add>
<add>## `PointLight`
<add>
<add>Un `PointLight` est une lumière qui se trouve en un point et projette de la lumière dans toutes les directions à partir de ce point. Changeons le code.
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>-const light = new THREE.DirectionalLight(color, intensity);
<add>+const light = new THREE.PointLight(color, intensity);
<add>light.position.set(0, 10, 0);
<add>-light.target.position.set(-5, 0, 0);
<add>scene.add(light);
<add>-scene.add(light.target);
<add>```
<add>
<add>Passons également à un `PointLightHelper`
<add>
<add>```js
<add>-const helper = new THREE.DirectionalLightHelper(light);
<add>+const helper = new THREE.PointLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>et comme il n'y a pas de cible la fonction `onChange` peut être simplifiée.
<add>
<add>```js
<add>function updateLight() {
<add>- light.target.updateMatrixWorld();
<add> helper.update();
<add>}
<add>-updateLight();
<add>```
<add>
<add>Notez qu'à un certain niveau, un `PointLightHelper` n'a pas de point. Il dessine juste un petit diamant filaire. Ou n'importe quelle autre forme que vous voulez, ajoutez simplement un maillage à la lumière elle-même.
<add>
<add>Une `PointLight` a une propriété supplémentaire, [`distance`](PointLight.distance).
<add>Si la `distance` est de 0, le `PointLight` brille à l'infini. Si la `distance` est supérieure à 0, la lumière brille de toute son intensité vers la lumière et s'estompe jusqu'à n'avoir aucune influence à des unités de `distance` de la lumière.
<add>
<add>Mettons à jour dat.GUI pour pouvoir modifier la distance.
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>+gui.add(light, 'distance', 0, 40).onChange(updateLight);
<add>
<add>makeXYZGUI(gui, light.position, 'position', updateLight);
<add>-makeXYZGUI(gui, light.target.position, 'target', updateLight);
<add>```
<add>
<add>Et maintennat, testons.
<add>
<add>{{{example url="../threejs-lights-point.html" }}}
<add>
<add>Remarquez comment la lumière s'éteint lorsque la `distance` est > 0.
<add>
<add>## `SpotLight`
<add>
<add>La `SpotLight` (projecteur), c'est une lumière ponctuelle avec un cône attaché où la lumière ne brille qu'à l'intérieur du cône. Il y a en fait 2 cônes. Un cône extérieur et un cône intérieur. Entre le cône intérieur et le cône extérieur, la lumière passe de la pleine intensité à zéro.
<add>
<add>Pour utiliser une `SpotLight`, nous avons besoin d'une cible tout comme la lumière directionnelle. Le cône de lumière s'ouvrira vers la cible.
<add>
<add>Modifions notre `DirectionalLight` avec le 'helper' vu plus haut
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>-const light = new THREE.DirectionalLight(color, intensity);
<add>+const light = new THREE.SpotLight(color, intensity);
<add>scene.add(light);
<add>scene.add(light.target);
<add>
<add>-const helper = new THREE.DirectionalLightHelper(light);
<add>+const helper = new THREE.SpotLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>L'angle du cône de la `Spotlight` est défini avec la propriété [`angle`](SpotLight.angle)
<add>en radians. Utilisons notre `DegRadHelper` vu dans
<add>[l'article sur les textures](threejs-textures.html) pour modifier l'angle avec dat.GUI.
<add>
<add>```js
<add>gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight);
<add>```
<add>
<add>Le cône intérieur est défini en paramétrant la propriété [`penumbra`](SpotLight.penumbra) en pourcentage du cône extérieur. En d'autres termes, lorsque la pénombre est de 0, le cône intérieur a la même taille (0 = aucune différence) que le cône extérieur. Lorsque la pénombre est de 1, la lumière s'estompe en partant du centre du cône jusqu'au cône extérieur. Lorsque la pénombre est de 0,5, la lumière s'estompe à partir de 50 % entre le centre du cône extérieur.
<add>
<add>```js
<add>gui.add(light, 'penumbra', 0, 1, 0.01);
<add>```
<add>
<add>{{{example url="../threejs-lights-spot-w-helper.html" }}}
<add>
<add>Remarquez qu'avec la `penumbra` par défaut à 0, le projecteur a un bord très net alors que lorsque vous l'ajustez à 1, le bord devient flou.
<add>
<add>Il peut être difficile de voir le *cône* des spotlight. C'est parce qu'il se trouve sous le sol. Raccourcissez la distance à environ 5 et vous verrez l'extrémité ouverte du cône.
<add>
<add>## `RectAreaLight`
<add>
<add>Il existe un autre type de lumière, la [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight), qui ressemble à une zone de lumière rectangulaire comme une longue lampe fluorescente ou peut-être une lucarne dépolie dans un plafond.
<add>
<add>Le [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) ne fonctionne qu'avec les [`MeshStandardMaterial`](https://threejs.org/docs/#api/en/materials/MeshStandardMaterial) et [`MeshPhysicalMaterial`](https://threejs.org/docs/#api/en/materials/MeshPhysicalMaterial) donc changeons tous nos matériaux en `MeshStandardMaterial`
<add>
<add>```js
<add> ...
<add>
<add> const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
<add>- const planeMat = new THREE.MeshPhongMaterial({
<add>+ const planeMat = new THREE.MeshStandardMaterial({
<add> map: texture,
<add> side: THREE.DoubleSide,
<add> });
<add> const mesh = new THREE.Mesh(planeGeo, planeMat);
<add> mesh.rotation.x = Math.PI * -.5;
<add> scene.add(mesh);
<add>}
<add>{
<add> const cubeSize = 4;
<add> const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
<add>- const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
<add>+ const cubeMat = new THREE.MeshStandardMaterial({color: '#8AC'});
<add> const mesh = new THREE.Mesh(cubeGeo, cubeMat);
<add> mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
<add> scene.add(mesh);
<add>}
<add>{
<add> const sphereRadius = 3;
<add> const sphereWidthDivisions = 32;
<add> const sphereHeightDivisions = 16;
<add> const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
<add>- const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
<add>+ const sphereMat = new THREE.MeshStandardMaterial({color: '#CA8'});
<add> const mesh = new THREE.Mesh(sphereGeo, sphereMat);
<add> mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
<add> scene.add(mesh);
<add>}
<add>```
<add>
<add>Pour utiliser [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) nous devons importer [`RectAreaLightHelper`](https://threejs.org/docs/#api/en/helpers/RectAreaLightHelper) pour nous aider à voir la lumière.
<add>
<add>```js
<add>import * as THREE from './resources/three/r127/build/three.module.js';
<add>+import {RectAreaLightUniformsLib} from './resources/threejs/r127/examples/jsm/lights/RectAreaLightUniformsLib.js';
<add>+import {RectAreaLightHelper} from './resources/threejs/r127/examples/jsm/helpers/RectAreaLightHelper.js';
<add>```
<add>
<add>et nous devons appeler `RectAreaLightUniformsLib.init`
<add>
<add>```js
<add>function main() {
<add> const canvas = document.querySelector('#c');
<add> const renderer = new THREE.WebGLRenderer({canvas});
<add>+ RectAreaLightUniformsLib.init();
<add>```
<add>
<add>Si vous oubliez les données, la lumière fonctionnera toujours, mais ça pourrait paraître bizarre, alors n'oubliez pas d'inclure les données supplémentaires.
<add>
<add>Maintenant, nous pouvons créer la lumière
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>*const intensity = 5;
<add>+const width = 12;
<add>+const height = 4;
<add>*const light = new THREE.RectAreaLight(color, intensity, width, height);
<add>light.position.set(0, 10, 0);
<add>+light.rotation.x = THREE.MathUtils.degToRad(-90);
<add>scene.add(light);
<add>
<add>*const helper = new RectAreaLightHelper(light);
<add>*light.add(helper);
<add>```
<add>
<add>Une chose à noter est que contrairement au [`DirectionalLight`](https://threejs.org/docs/#api/en/lights/DirectionalLight) et à la [`SpotLight`](https://threejs.org/docs/#api/en/lights/SpotLight), la [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) n'utilise pas de cible. Elle utilise juste sa rotation. Une autre chose à noter est que le 'helper' doit être un enfant de la lumière. Ce n'est pas un enfant de la scène comme les autres 'helpers'.
<add>
<add>Ajustons-la également à dat.GUI. Nous allons le faire pour que nous puissions faire pivoter la lumière et ajuster sa `width` et sa `height`
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 10, 0.01);
<add>gui.add(light, 'width', 0, 20);
<add>gui.add(light, 'height', 0, 20);
<add>gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
<add>gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
<add>gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
<add>
<add>makeXYZGUI(gui, light.position, 'position');
<add>```
<add>
<add>Et voici ce que ça donne.
<add>
<add>{{{example url="../threejs-lights-rectarea.html" }}}
<add>
<add>Une chose que nous n'avons pas vu, c'est qu'il existe un paramètre sur le [`WebGLRenderer`](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) appelé `physicalCorrectLights`. Il affecte la façon dont la lumière tombe en tant que distance de la lumière. Cela n'affecte que [`PointLight`](https://threejs.org/docs/#api/en/lights/PointLight) et [`SpotLight`](https://threejs.org/docs/#api/en/lights/SpotLight). [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) le fait automatiquement.
<add>
<add>Pour les lumières, l'idée de base est de ne pas définir de distance pour qu'elles s'éteignent, et vous ne définissez pas `intensity`. Au lieu de cela, vous définissez la [`power`](PointLight.power) de la lumière en lumens, puis three.js utilisera des calculs physiques comme de vraies lumières. Les unités de three.js dans ce cas sont des mètres et une ampoule de 60w aurait environ 800 lumens. Il y a aussi une propriété [`decay`](PointLight.decay). Elle doit être réglé sur 2 pour une apparence réaliste.
<add>
<add>Testons ça.
<add>
<add>D'abord, définissons `physicallyCorrectLights` sur true
<add>
<add>```js
<add>const renderer = new THREE.WebGLRenderer({canvas});
<add>+renderer.physicallyCorrectLights = true;
<add>```
<add>
<add>Ensuite, réglons la `power` à 800 lumens, la `decay` à 2, et
<add>la `distance` sur `Infinity`.
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.PointLight(color, intensity);
<add>light.power = 800;
<add>light.decay = 2;
<add>light.distance = Infinity;
<add>```
<add>
<add>et mettons à jour dat.GUI pour pouvoir changer `power` et `decay`
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'decay', 0, 4, 0.01);
<add>gui.add(light, 'power', 0, 2000);
<add>```
<add>
<add>{{{example url="../threejs-lights-point-physically-correct.html" }}}
<add>
<add>Il est important de noter que chaque lumière que vous ajoutez à la scène ralentit la vitesse à laquelle Three.js rend la scène, vous devez donc toujours essayer d'en utiliser le moins possible pour atteindre vos objectifs.
<add>
<add>Passons maintenant à [la gestion des caméras](threejs-cameras.html).
<add>
<add><canvas id="c"></canvas>
<add><script type="module" src="resources/threejs-lights.js"></script> | 1 |
Java | Java | add javadoc since for graphql constants | fcf64798b518149736983aa2ad1308d474a04664 | <ide><path>spring-core/src/main/java/org/springframework/util/MimeTypeUtils.java
<ide> public abstract class MimeTypeUtils {
<ide>
<ide> /**
<ide> * Public constant mime type for {@code application/graphql+json}.
<add> * @since 5.3.19
<ide> * @see <a href="https://github.com/graphql/graphql-over-http">GraphQL over HTTP spec</a>
<del> * */
<add> */
<ide> public static final MimeType APPLICATION_GRAPHQL;
<ide>
<ide> /**
<ide> * A String equivalent of {@link MimeTypeUtils#APPLICATION_GRAPHQL}.
<add> * @since 5.3.19
<ide> */
<ide> public static final String APPLICATION_GRAPHQL_VALUE = "application/graphql+json";
<ide>
<ide> /**
<ide> * Public constant mime type for {@code application/json}.
<del> * */
<add> */
<ide> public static final MimeType APPLICATION_JSON;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java
<ide> public class MediaType extends MimeType implements Serializable {
<ide>
<ide> /**
<ide> * Public constant media type for {@code application/graphql+json}.
<add> * @since 5.3.19
<ide> * @see <a href="https://github.com/graphql/graphql-over-http">GraphQL over HTTP spec</a>
<ide> */
<ide> public static final MediaType APPLICATION_GRAPHQL;
<ide>
<ide> /**
<ide> * A String equivalent of {@link MediaType#APPLICATION_GRAPHQL}.
<add> * @since 5.3.19
<ide> */
<ide> public static final String APPLICATION_GRAPHQL_VALUE = "application/graphql+json";
<ide> | 2 |
Text | Text | clarify special schemes | d71f05c03db0e94ecde8c0e92fe7696e00e32436 | <ide><path>doc/api/url.md
<ide> console.log(u.href);
<ide> // fish://example.org
<ide> ```
<ide>
<del>The protocol schemes considered to be special by the WHATWG URL Standard
<del>include: `ftp`, `file`, `gopher`, `http`, `https`, `ws`, and `wss`.
<add>According to the WHATWG URL Standard, special protocol schemes are `ftp`,
<add>`file`, `gopher`, `http`, `https`, `ws`, and `wss`.
<ide>
<ide> #### url.search
<ide> | 1 |
Javascript | Javascript | add some improvements to frustum | 01852d283b95a56e9c930c3db35fc06f346975f4 | <ide><path>build/Three.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>build/custom/ThreeCanvas.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>build/custom/ThreeDOM.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>build/custom/ThreeSVG.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>build/custom/ThreeWebGL.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>src/core/Frustum.js
<ide> THREE.Frustum.prototype.setFromMatrix = function ( m ) {
<ide> var i, plane,
<ide> planes = this.planes;
<ide> var me = m.elements;
<del>
<del> planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
<del> planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
<del> planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
<del> planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
<del> planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
<del> planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
<add> var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
<add> var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
<add> var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
<add> var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
<add>
<add> planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
<add> planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
<add> planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
<add> planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
<add> planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
<add> planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
<ide>
<ide> for ( i = 0; i < 6; i ++ ) {
<ide>
<ide><path>src/core/Matrix4.js
<ide> * @author timknip / http://www.floorplanner.com/
<ide> */
<ide>
<add>
<ide> THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
<ide>
<ide> this.elements = new Float32Array(16); | 7 |
Python | Python | use tagspecification parameter on ec2 create_node | 0d1be1d7a28699d726c1256682a4e63889f2a1ba | <ide><path>libcloud/__init__.py
<ide> '__version__',
<ide> 'enable_debug'
<ide> ]
<del>__version__ = '2.2.0'
<add>__version__ = '2.2.0.dev1'
<ide>
<ide>
<ide> def enable_debug(fo):
<ide><path>libcloud/compute/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide> if subnet_id:
<ide> params['SubnetId'] = subnet_id
<ide>
<add> # Specify tags at instance creation time
<add> tags = {'Name': kwargs['name']}
<add> if 'ex_metadata' in kwargs:
<add> tags.update(kwargs['ex_metadata'])
<add> tagspec_root = 'TagSpecification.1.'
<add> params[tagspec_root + 'ResourceType'] = 'instance'
<add> tag_nr = 1
<add> for k, v in tags.iteritems():
<add> tag_root = tagspec_root + "Tag.{}.".format(tag_nr)
<add> params[tag_root + "Key"] = k
<add> params[tag_root + "Value"] = v
<add> tag_nr += 1
<add>
<ide> object = self.connection.request(self.path, params=params).object
<ide> nodes = self._to_nodes(object, 'instancesSet/item')
<ide>
<ide> for node in nodes:
<del> tags = {'Name': kwargs['name']}
<del> if 'ex_metadata' in kwargs:
<del> tags.update(kwargs['ex_metadata'])
<del>
<del> try:
<del> self.ex_create_tags(resource=node, tags=tags)
<del> except Exception:
<del> continue
<del>
<ide> node.name = kwargs['name']
<ide> node.extra.update({'tags': tags})
<ide> | 2 |
Go | Go | add support for manifest lists ("fat manifests") | 2bb8c85bc5e59d2f5a154b58bb9a4b6e86775a40 | <ide><path>distribution/pull_v2.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/distribution/digest"
<add> "github.com/docker/distribution/manifest/manifestlist"
<ide> "github.com/docker/distribution/manifest/schema1"
<ide> "github.com/docker/distribution/manifest/schema2"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named) (tagUpdat
<ide> if err != nil {
<ide> return false, err
<ide> }
<add> case *manifestlist.DeserializedManifestList:
<add> imageID, manifestDigest, err = p.pullManifestList(ctx, ref, v)
<add> if err != nil {
<add> return false, err
<add> }
<ide> default:
<ide> return false, errors.New("unsupported manifest format")
<ide> }
<ide> func (p *v2Puller) pullSchema1(ctx context.Context, ref reference.Named, unverif
<ide> }
<ide>
<ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *schema2.DeserializedManifest) (imageID image.ID, manifestDigest digest.Digest, err error) {
<del> _, canonical, err := mfst.Payload()
<add> manifestDigest, err = schema2ManifestDigest(ref, mfst)
<ide> if err != nil {
<ide> return "", "", err
<ide> }
<ide>
<del> // If pull by digest, then verify the manifest digest.
<del> if digested, isDigested := ref.(reference.Canonical); isDigested {
<del> verifier, err := digest.NewDigestVerifier(digested.Digest())
<del> if err != nil {
<del> return "", "", err
<del> }
<del> if _, err := verifier.Write(canonical); err != nil {
<del> return "", "", err
<del> }
<del> if !verifier.Verified() {
<del> err := fmt.Errorf("manifest verification failed for digest %s", digested.Digest())
<del> logrus.Error(err)
<del> return "", "", err
<del> }
<del> manifestDigest = digested.Digest()
<del> } else {
<del> manifestDigest = digest.FromBytes(canonical)
<del> }
<del>
<ide> target := mfst.Target()
<ide> imageID = image.ID(target.Digest)
<ide> if _, err := p.config.ImageStore.Get(imageID); err == nil {
<ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s
<ide> return imageID, manifestDigest, nil
<ide> }
<ide>
<add>// pullManifestList handles "manifest lists" which point to various
<add>// platform-specifc manifests.
<add>func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mfstList *manifestlist.DeserializedManifestList) (imageID image.ID, manifestListDigest digest.Digest, err error) {
<add> manifestListDigest, err = schema2ManifestDigest(ref, mfstList)
<add> if err != nil {
<add> return "", "", err
<add> }
<add>
<add> var manifestDigest digest.Digest
<add> for _, manifestDescriptor := range mfstList.Manifests {
<add> // TODO(aaronl): The manifest list spec supports optional
<add> // "features" and "variant" fields. These are not yet used.
<add> // Once they are, their values should be interpreted here.
<add> if manifestDescriptor.Platform.Architecture == runtime.GOARCH && manifestDescriptor.Platform.OS == runtime.GOOS {
<add> manifestDigest = manifestDescriptor.Digest
<add> break
<add> }
<add> }
<add>
<add> if manifestDigest == "" {
<add> return "", "", errors.New("no supported platform found in manifest list")
<add> }
<add>
<add> manSvc, err := p.repo.Manifests(ctx)
<add> if err != nil {
<add> return "", "", err
<add> }
<add>
<add> manifest, err := manSvc.Get(ctx, manifestDigest)
<add> if err != nil {
<add> return "", "", err
<add> }
<add>
<add> manifestRef, err := reference.WithDigest(ref, manifestDigest)
<add> if err != nil {
<add> return "", "", err
<add> }
<add>
<add> switch v := manifest.(type) {
<add> case *schema1.SignedManifest:
<add> imageID, _, err = p.pullSchema1(ctx, manifestRef, v)
<add> if err != nil {
<add> return "", "", err
<add> }
<add> case *schema2.DeserializedManifest:
<add> imageID, _, err = p.pullSchema2(ctx, manifestRef, v)
<add> if err != nil {
<add> return "", "", err
<add> }
<add> default:
<add> return "", "", errors.New("unsupported manifest format")
<add> }
<add>
<add> return imageID, manifestListDigest, err
<add>}
<add>
<ide> func (p *v2Puller) pullSchema2ImageConfig(ctx context.Context, dgst digest.Digest) (configJSON []byte, err error) {
<ide> blobs := p.repo.Blobs(ctx)
<ide> configJSON, err = blobs.Get(ctx, dgst)
<ide> func (p *v2Puller) pullSchema2ImageConfig(ctx context.Context, dgst digest.Diges
<ide> return configJSON, nil
<ide> }
<ide>
<add>// schema2ManifestDigest computes the manifest digest, and, if pulling by
<add>// digest, ensures that it matches the requested digest.
<add>func schema2ManifestDigest(ref reference.Named, mfst distribution.Manifest) (digest.Digest, error) {
<add> _, canonical, err := mfst.Payload()
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> // If pull by digest, then verify the manifest digest.
<add> if digested, isDigested := ref.(reference.Canonical); isDigested {
<add> verifier, err := digest.NewDigestVerifier(digested.Digest())
<add> if err != nil {
<add> return "", err
<add> }
<add> if _, err := verifier.Write(canonical); err != nil {
<add> return "", err
<add> }
<add> if !verifier.Verified() {
<add> err := fmt.Errorf("manifest verification failed for digest %s", digested.Digest())
<add> logrus.Error(err)
<add> return "", err
<add> }
<add> return digested.Digest(), nil
<add> }
<add>
<add> return digest.FromBytes(canonical), nil
<add>}
<add>
<ide> // allowV1Fallback checks if the error is a possible reason to fallback to v1
<ide> // (even if confirmedV2 has been set already), and if so, wraps the error in
<ide> // a fallbackError with confirmedV2 set to false. Otherwise, it returns the | 1 |
Text | Text | add jsfiddle link to issue_template.md | 14717cfa40713635b27c2b62c61ce1d3d97f48e8 | <ide><path>.github/ISSUE_TEMPLATE.md
<ide>
<ide> ##### Description of the problem
<ide>
<add>Describe the problem/request in detail.
<add>Code snippet, screenshot, and small-test help us understand.
<add>
<add>You can edit for small-test.
<add>http://jsfiddle.net/akmcv7Lh/ (current revision)
<add>http://jsfiddle.net/hw9rcLL8/ (dev)
<ide>
<ide> ##### Three.js version
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.