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
remove initargs support for taskpool
2321a319e042540681559db2b4cba4c80a89f1ca
<ide><path>celery/worker/pool.py <ide> class TaskPool(object): <ide> <ide> """ <ide> <del> def __init__(self, limit, logger=None, initializer=None, initargs=None): <add> def __init__(self, limit, logger=None, initializer=None): <ide> self.limit = limit <ide> self.logger = logger or log.get_default_logger() <ide> self.initializer = initializer <del> self.initargs = initargs <ide> self._pool = None <ide> <ide> def start(self): <ide> def start(self): <ide> <ide> """ <ide> self._pool = DynamicPool(processes=self.limit, <del> initializer=self.initializer, <del> initargs=self.initargs) <add> initializer=self.initializer) <ide> <ide> def stop(self): <ide> """Terminate the pool."""
1
PHP
PHP
fix migrations $connection property
03e3a807fd8d5c2524800dcd8f7a57753330be67
<ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> protected function runMigration($migration, $method) <ide> $migration->getConnection() <ide> ); <ide> <del> $callback = function () use ($migration, $method) { <add> $callback = function () use ($connection, $migration, $method) { <ide> if (method_exists($migration, $method)) { <ide> $this->fireMigrationEvent(new MigrationStarted($migration, $method)); <ide> <del> $migration->{$method}(); <add> $this->runMethod($connection, $migration, $method); <ide> <ide> $this->fireMigrationEvent(new MigrationEnded($migration, $method)); <ide> } <ide> protected function getQueries($migration, $method) <ide> $migration->getConnection() <ide> ); <ide> <del> return $db->pretend(function () use ($migration, $method) { <add> return $db->pretend(function () use ($db, $migration, $method) { <ide> if (method_exists($migration, $method)) { <del> $migration->{$method}(); <add> $this->runMethod($db, $migration, $method); <ide> } <ide> }); <ide> } <ide> <add> /** <add> * Run a migration method on the given connection. <add> * <add> * @param \Illuminate\Database\Connection $connection <add> * @param object $migration <add> * @param string $method <add> * @return void <add> */ <add> protected function runMethod($connection, $migration, $method) <add> { <add> $previousConnection = $this->resolver->getDefaultConnection(); <add> <add> try { <add> $this->resolver->setDefaultConnection($connection->getName()); <add> <add> $migration->{$method}(); <add> } finally { <add> $this->resolver->setDefaultConnection($previousConnection); <add> } <add> } <add> <ide> /** <ide> * Resolve a migration instance from a file. <ide> * <ide><path>tests/Database/DatabaseMigratorIntegrationTest.php <ide> protected function setUp(): void <ide> 'database' => ':memory:', <ide> ], 'sqlite2'); <ide> <add> $db->addConnection([ <add> 'driver' => 'sqlite', <add> 'database' => ':memory:', <add> ], 'sqlite3'); <add> <ide> $db->setAsGlobal(); <ide> <ide> $container = new Container; <ide> public function testBasicMigrationOfSingleFolder() <ide> $this->assertTrue(Str::contains($ran[1], 'password_resets')); <ide> } <ide> <add> public function testMigrationsDefaultConnectionCanBeChanged() <add> { <add> $ran = $this->migrator->usingConnection('sqlite2', function () { <add> return $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqllite3']); <add> }); <add> <add> $this->assertFalse($this->db->schema()->hasTable('users')); <add> $this->assertFalse($this->db->schema()->hasTable('password_resets')); <add> $this->assertTrue($this->db->schema('sqlite2')->hasTable('users')); <add> $this->assertTrue($this->db->schema('sqlite2')->hasTable('password_resets')); <add> $this->assertFalse($this->db->schema('sqlite3')->hasTable('users')); <add> $this->assertFalse($this->db->schema('sqlite3')->hasTable('password_resets')); <add> <add> $this->assertTrue(Str::contains($ran[0], 'users')); <add> $this->assertTrue(Str::contains($ran[1], 'password_resets')); <add> } <add> <add> public function testMigrationsCanEachDefineConnection() <add> { <add> $ran = $this->migrator->run([__DIR__.'/migrations/connection_configured']); <add> <add> $this->assertFalse($this->db->schema()->hasTable('failed_jobs')); <add> $this->assertFalse($this->db->schema()->hasTable('jobs')); <add> $this->assertFalse($this->db->schema('sqlite2')->hasTable('failed_jobs')); <add> $this->assertFalse($this->db->schema('sqlite2')->hasTable('jobs')); <add> $this->assertTrue($this->db->schema('sqlite3')->hasTable('failed_jobs')); <add> $this->assertTrue($this->db->schema('sqlite3')->hasTable('jobs')); <add> <add> $this->assertTrue(Str::contains($ran[0], 'failed_jobs')); <add> $this->assertTrue(Str::contains($ran[1], 'jobs')); <add> } <add> <add> public function testMigratorCannotChangeDefinedMigrationConnection() <add> { <add> $ran = $this->migrator->usingConnection('sqlite2', function () { <add> return $this->migrator->run([__DIR__.'/migrations/connection_configured']); <add> }); <add> <add> $this->assertFalse($this->db->schema()->hasTable('failed_jobs')); <add> $this->assertFalse($this->db->schema()->hasTable('jobs')); <add> $this->assertFalse($this->db->schema('sqlite2')->hasTable('failed_jobs')); <add> $this->assertFalse($this->db->schema('sqlite2')->hasTable('jobs')); <add> $this->assertTrue($this->db->schema('sqlite3')->hasTable('failed_jobs')); <add> $this->assertTrue($this->db->schema('sqlite3')->hasTable('jobs')); <add> <add> $this->assertTrue(Str::contains($ran[0], 'failed_jobs')); <add> $this->assertTrue(Str::contains($ran[1], 'jobs')); <add> } <add> <ide> public function testMigrationsCanBeRolledBack() <ide> { <ide> $this->migrator->run([__DIR__.'/migrations/one']); <ide><path>tests/Database/migrations/connection_configured/2022_02_21_000000_create_failed_jobs_table.php <add><?php <add> <add>use Illuminate\Database\Migrations\Migration; <add>use Illuminate\Database\Schema\Blueprint; <add>use Illuminate\Support\Facades\Schema; <add> <add>return new class extends Migration <add>{ <add> /** <add> * The database connection that should be used by the migration. <add> * <add> * @var string <add> */ <add> protected $connection = 'sqlite3'; <add> <add> /** <add> * Run the migrations. <add> * <add> * @return void <add> */ <add> public function up() <add> { <add> Schema::create('failed_jobs', function (Blueprint $table) { <add> $table->id(); <add> $table->text('connection'); <add> $table->text('queue'); <add> $table->longText('payload'); <add> $table->longText('exception'); <add> $table->timestamp('failed_at')->useCurrent(); <add> }); <add> } <add> <add> /** <add> * Reverse the migrations. <add> * <add> * @return void <add> */ <add> public function down() <add> { <add> Schema::dropIfExists('failed_jobs'); <add> } <add>}; <ide><path>tests/Database/migrations/connection_configured/2022_02_21_120000_create_jobs_table.php <add><?php <add> <add>use Illuminate\Database\Migrations\Migration; <add>use Illuminate\Database\Schema\Blueprint; <add>use Illuminate\Support\Facades\Schema; <add> <add>return new class extends Migration <add>{ <add> /** <add> * Run the migrations. <add> * <add> * @return void <add> */ <add> public function up() <add> { <add> Schema::connection('sqlite3')->create('jobs', function (Blueprint $table) { <add> $table->bigIncrements('id'); <add> $table->string('queue')->index(); <add> $table->longText('payload'); <add> $table->unsignedTinyInteger('attempts'); <add> $table->unsignedInteger('reserved_at')->nullable(); <add> $table->unsignedInteger('available_at'); <add> $table->unsignedInteger('created_at'); <add> }); <add> } <add> <add> /** <add> * Reverse the migrations. <add> * <add> * @return void <add> */ <add> public function down() <add> { <add> Schema::connection('sqlite3')->dropIfExists('jobs'); <add> } <add>};
4
Javascript
Javascript
add removal warning
fe0e7957e3102b96213409408aa8b04b32fa9f33
<ide><path>src/materials/Material.js <ide> function Material() { <ide> this.stencilZPass = KeepStencilOp; <ide> this.stencilWrite = false; <ide> <add> Object.defineProperty( this, 'stencilMask', { <add> <add> set: function( value ) { <add> <add> console.warn( 'Material.stencilMask has been removed. Use Material.stencilFuncMask instead.' ); <add> this.stencilFuncMask = value; <add> <add> }, <add> <add> get: function() { <add> <add> console.warn( 'Material.stencilMask has been removed. Use Material.stencilFuncMask instead.' ); <add> return this.stencilFuncMask; <add> <add> } <add> <add> } ); <add> <ide> this.clippingPlanes = null; <ide> this.clipIntersection = false; <ide> this.clipShadows = false;
1
Text
Text
remove style instruction that is not followed
120442a00b349d52dee48d7ee7b179ae7c69d8fa
<ide><path>doc/STYLE_GUIDE.md <ide> clause — a subject, verb, and an object. <ide> * Outside of the wrapping element if the wrapping element contains only a <ide> fragment of a clause. <del>* Place end-of-sentence punctuation inside wrapping elements — periods go <del> inside parentheses and quotes, not after. <ide> * Documents must start with a level-one heading. <ide> * Prefer affixing links to inlining links — prefer `[a link][]` to <ide> `[a link](http://example.com)`.
1
Mixed
Javascript
make tcp nodelay enabled by default
eacd45656a6bf18be4a3215bb3fcbd54f5f0b17f
<ide><path>doc/api/http.md <ide> Found'`. <ide> <!-- YAML <ide> added: v0.1.13 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/42163 <add> description: The `noDelay` option now defaults to `true`. <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41310 <add> description: The `noDelay`, `keepAlive` and `keepAliveInitialDelay` <add> options are supported now. <ide> - version: <ide> - v13.8.0 <ide> - v12.15.0 <ide> changes: <ide> **Default:** 16384 (16 KB). <ide> * `noDelay` {boolean} If set to `true`, it disables the use of Nagle's <ide> algorithm immediately after a new incoming connection is received. <del> **Default:** `false`. <add> **Default:** `true`. <ide> * `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality <ide> on the socket immediately after a new incoming connection is received, <ide> similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`]. <ide><path>doc/api/net.md <ide> behavior. <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/41310 <add> description: The `noDelay`, `keepAlive` and `keepAliveInitialDelay` <add> options are supported now. <ide> - version: v12.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/25436 <ide> description: Added `onread` option. <ide><path>lib/_http_agent.js <ide> function Agent(options) { <ide> <ide> this.options = { __proto__: null, ...options }; <ide> <add> if (this.options.noDelay === undefined) <add> this.options.noDelay = true; <add> <ide> // Don't confuse net and make it think that we're connecting to a pipe <ide> this.options.path = null; <ide> this.requests = ObjectCreate(null); <ide><path>lib/_http_server.js <ide> function storeHTTPOptions(options) { <ide> if (insecureHTTPParser !== undefined) <ide> validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); <ide> this.insecureHTTPParser = insecureHTTPParser; <add> <add> if (options.noDelay === undefined) <add> options.noDelay = true; <ide> } <ide> <ide> function Server(options, requestListener) { <ide><path>test/parallel/test-http-nodelay.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add>const net = require('net'); <add> <add>const originalConnect = net.Socket.prototype.connect; <add> <add>net.Socket.prototype.connect = common.mustCall(function(args) { <add> assert.strictEqual(args[0].noDelay, true); <add> return originalConnect.call(this, args); <add>}); <add> <add>const server = http.createServer(common.mustCall((req, res) => { <add> res.writeHead(200); <add> res.end(); <add> server.close(); <add>})); <add> <add>server.listen(0, common.mustCall(() => { <add> assert.strictEqual(server.noDelay, true); <add> <add> const req = http.request({ <add> method: 'GET', <add> port: server.address().port <add> }, common.mustCall((res) => { <add> res.on('end', () => { <add> server.close(); <add> res.req.socket.end(); <add> }); <add> <add> res.resume(); <add> })); <add> <add> req.end(); <add>}));
5
Ruby
Ruby
change config implementation in av slightly
e1490d4e4c60211173d51e7b21c16dbe4c2d942a
<ide><path>actionmailer/test/abstract_unit.rb <ide> ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!".inspect } <ide> ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup".inspect } <ide> <del>ActionView::Base.config = { :assets_dir => '/nowhere' } <add>ActionView::Base::DEFAULT_CONFIG = { :assets_dir => '/nowhere' } <ide> <ide> $:.unshift "#{File.dirname(__FILE__)}/fixtures/helpers" <ide> <ide><path>actionpack/lib/action_view/base.rb <ide> class Base <ide> module Subclasses <ide> end <ide> <del> include Helpers, Rendering, Partials, ::ERB::Util, ActiveSupport::Configurable <add> include Helpers, Rendering, Partials, ::ERB::Util <add> <add> def config <add> self.config = DEFAULT_CONFIG unless @config <add> @config <add> end <add> <add> def config=(config) <add> @config = ActiveSupport::OrderedOptions.new.merge(config) <add> end <ide> <ide> extend ActiveSupport::Memoizable <ide>
2
Python
Python
add test for buffered maskna iteration
1a58505bd5bd63961ee0b177d234a6c03aabb0c0
<ide><path>numpy/core/tests/test_nditer.py <ide> def test_iter_writemasked(): <ide> assert_equal(a, [3,3,2.5]) <ide> <ide> def test_iter_maskna(): <del> a = np.zeros((3,), dtype='f8', maskna=True) <del> b = np.zeros((3,), dtype='f4') <add> a_orig = np.zeros((3,), dtype='f8') <add> b_orig = np.zeros((3,), dtype='f4') <add> a = a_orig.view(maskna=True) <add> b = b_orig.view(maskna=True) <ide> <ide> # Default iteration with NA mask <ide> a[...] = np.NA <ide> def test_iter_maskna(): <ide> <ide> # Assigning NAs and values in an iteration <ide> a[...] = [0,1,2] <del> b[...] = [1,2,2] <del> it = np.nditer([a,b], [], [['writeonly','use_maskna'], ['readonly']]) <add> b_orig[...] = [1,2,2] <add> it = np.nditer([a,b_orig], [], [['writeonly','use_maskna'], ['readonly']]) <ide> for x, y in it: <ide> if y == 2: <ide> x[...] = np.NA <ide> def test_iter_maskna(): <ide> assert_equal(a[1], 0) <ide> assert_equal(np.isna(a), [1,0,1]) <ide> <add> # Copying values with buffering <add> a_orig[...] = [1,2,3] <add> b_orig[...] = [4,5,6] <add> a[...] = [np.NA, np.NA, 5] <add> b[...] = [np.NA, 3, np.NA] <add> it = np.nditer([a,b], ['buffered'], [['writeonly','use_maskna'], <add> ['readonly','use_maskna']], <add> op_dtypes=['i4','i4'], <add> casting='unsafe') <add> for x, y in it: <add> x[...] = y <add> assert_equal(a[1], 3) <add> assert_equal(np.isna(a), [1,0,1]) <add> assert_equal(a_orig, [1,3,3]) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Javascript
Javascript
move usedexports into exportsinfo
739fef4fda591b2d01b8863b83c881e076e26c1a
<ide><path>lib/Compilation.js <ide> const StatsFactory = require("./stats/StatsFactory"); <ide> const StatsPrinter = require("./stats/StatsPrinter"); <ide> const AsyncQueue = require("./util/AsyncQueue"); <ide> const Queue = require("./util/Queue"); <del>const SortableSet = require("./util/SortableSet"); <ide> const { <ide> compareLocations, <ide> concatComparators, <ide> class Compilation { <ide> this.chunkGraph.connectChunkAndRuntimeModule(chunk, module); <ide> <ide> // Setup internals <del> this.moduleGraph.setUsedExports(module, new SortableSet()); <add> this.moduleGraph.getExportsInfo(module).setUsedForSideEffectsOnly(); <ide> this.chunkGraph.addModuleRuntimeRequirements(module, [ <ide> RuntimeGlobals.require <ide> ]); <ide><path>lib/FlagDependencyUsagePlugin.js <ide> "use strict"; <ide> <ide> const { STAGE_DEFAULT } = require("./OptimizationStages"); <del>const SortableSet = require("./util/SortableSet"); <add>const Queue = require("./util/Queue"); <ide> <ide> /** @typedef {import("./Compiler")} Compiler */ <ide> /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ <ide> /** @typedef {import("./Dependency")} Dependency */ <ide> /** @typedef {import("./Module")} Module */ <ide> <del>/** @typedef {false | true | SortableSet<string>} UsedExports */ <del> <del>/** <del> * @param {UsedExports} moduleUsedExports the current used exports of the module <del> * @param {false | true | string[]} newUsedExports the new used exports <del> * @returns {boolean} true, if the newUsedExports is part of the moduleUsedExports <del> */ <del>const isContained = (moduleUsedExports, newUsedExports) => { <del> if (moduleUsedExports === null) return false; <del> if (moduleUsedExports === true) return true; <del> if (newUsedExports === true) return false; <del> if (newUsedExports === false) return true; <del> if (moduleUsedExports === false) return false; <del> if (newUsedExports.length > moduleUsedExports.size) return false; <del> return newUsedExports.every(item => moduleUsedExports.has(item)); <del>}; <del> <ide> class FlagDependencyUsagePlugin { <ide> /** <ide> * @param {Compiler} compiler the compiler instance <ide> class FlagDependencyUsagePlugin { <ide> * @returns {void} <ide> */ <ide> const processModule = (module, usedExports) => { <del> let ue = moduleGraph.getUsedExports(module); <del> if (ue === true) return; <add> const exportsInfo = moduleGraph.getExportsInfo(module); <add> let changed = false; <ide> if (usedExports === true) { <del> moduleGraph.setUsedExports(module, (ue = true)); <del> } else if (Array.isArray(usedExports)) { <del> if (!ue) { <del> moduleGraph.setUsedExports( <del> module, <del> (ue = new SortableSet(usedExports)) <del> ); <del> } else { <del> const old = ue ? ue.size : -1; <del> for (const exportName of usedExports) { <del> ue.add(exportName); <del> } <del> if (ue.size === old) { <del> return; <add> changed = exportsInfo.setUsedInUnknownWay(); <add> } else if (usedExports) { <add> for (const exportName of usedExports) { <add> const exportInfo = exportsInfo.getExportInfo(exportName); <add> if (exportInfo.used !== true) { <add> exportInfo.used = true; <add> changed = true; <ide> } <ide> } <ide> } else { <del> if (ue !== false) return; <del> moduleGraph.setUsedExports(module, (ue = new SortableSet())); <add> // for a module without side effects we stop tracking usage here when no export is used <add> // This module won't be evaluated in this case <add> if (module.factoryMeta.sideEffectFree) return; <add> changed = exportsInfo.setUsedForSideEffectsOnly(); <ide> } <ide> <del> // for a module without side effects we stop tracking usage here when no export is used <del> // This module won't be evaluated in this case <del> if (module.factoryMeta.sideEffectFree) { <del> if (ue !== true && ue.size === 0) return; <add> if (changed) { <add> queue.enqueue(module); <ide> } <del> <del> queue.push([module, module, ue]); <ide> }; <ide> <ide> /** <del> * @param {Module} module the module <ide> * @param {DependenciesBlock} depBlock the dependencies block <del> * @param {UsedExports} usedExports the used exports <ide> * @returns {void} <ide> */ <del> const processDependenciesBlock = (module, depBlock, usedExports) => { <add> const processDependenciesBlock = depBlock => { <ide> for (const dep of depBlock.dependencies) { <del> processDependency(module, dep); <add> processDependency(dep); <ide> } <ide> for (const block of depBlock.blocks) { <del> queue.push([module, block, usedExports]); <add> queue.enqueue(block); <ide> } <ide> }; <ide> <ide> /** <del> * @param {Module} module the module <ide> * @param {Dependency} dep the dependency <ide> * @returns {void} <ide> */ <del> const processDependency = (module, dep) => { <add> const processDependency = dep => { <ide> const reference = compilation.getDependencyReference(dep); <ide> if (!reference) return; <ide> const referenceModule = reference.module; <ide> const importedNames = reference.importedNames; <del> const oldUsedExports = moduleGraph.getUsedExports(referenceModule); <del> if ( <del> !oldUsedExports || <del> !isContained(oldUsedExports, importedNames) <del> ) { <del> processModule(referenceModule, importedNames); <del> } <add> processModule(referenceModule, importedNames); <ide> }; <ide> <ide> for (const module of modules) { <del> moduleGraph.setUsedExports(module, false); <add> moduleGraph.getExportsInfo(module).setHasUseInfo(); <ide> } <ide> <del> /** @type {[Module, DependenciesBlock, UsedExports][]} */ <del> const queue = []; <add> /** @type {Queue<DependenciesBlock>} */ <add> const queue = new Queue(); <add> <ide> for (const deps of compilation.entryDependencies.values()) { <ide> for (const dep of deps) { <ide> const module = moduleGraph.getModule(dep); <ide> class FlagDependencyUsagePlugin { <ide> } <ide> <ide> while (queue.length) { <del> const queueItem = queue.pop(); <del> processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); <add> const depBlock = queue.dequeue(); <add> processDependenciesBlock(depBlock); <ide> } <ide> } <ide> ); <ide><path>lib/FlagInitialModulesAsUsedPlugin.js <ide> class FlagInitialModulesAsUsedPlugin { <ide> return; <ide> } <ide> for (const module of chunkGraph.getChunkModulesIterable(chunk)) { <del> moduleGraph.setUsedExports(module, true); <add> moduleGraph.getExportsInfo(module).setUsedInUnknownWay(); <ide> moduleGraph.addExtraReason(module, this.explanation); <ide> } <ide> } <ide><path>lib/Module.js <ide> class Module extends DependenciesBlock { <ide> ).getUsedExports(this); <ide> } <ide> <del> set usedExports(value) { <del> ModuleGraph.getModuleGraphForModule( <del> this, <del> "Module.usedExports" <del> ).setUsedExports(this, value); <del> } <del> <ide> get optimizationBailout() { <ide> return ModuleGraph.getModuleGraphForModule( <ide> this, <ide> class Module extends DependenciesBlock { <ide> * @returns {boolean} true, if the module is used <ide> */ <ide> isModuleUsed(moduleGraph) { <del> return moduleGraph.getUsedExports(this) !== false; <add> return moduleGraph.getExportsInfo(this).isUsed() !== false; <ide> } <ide> <ide> /** <ide> class Module extends DependenciesBlock { <ide> * @returns {boolean} true, if the export is used <ide> */ <ide> isExportUsed(moduleGraph, exportName) { <del> const usedExports = moduleGraph.getUsedExports(this); <del> if (usedExports === null || usedExports === true) return true; <del> if (usedExports === false) return false; <del> return usedExports.has(exportName); <add> const exportInfo = moduleGraph.getExportInfo(this, exportName); <add> return exportInfo.used !== false; <ide> } <ide> <ide> // TODO move to ModuleGraph <ide><path>lib/ModuleGraph.js <ide> <ide> const util = require("util"); <ide> const ModuleGraphConnection = require("./ModuleGraphConnection"); <add>const SortableSet = require("./util/SortableSet"); <ide> <ide> /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ <ide> /** @typedef {import("./Dependency")} Dependency */ <ide> /** @typedef {import("./Module")} Module */ <ide> /** @typedef {import("./ModuleProfile")} ModuleProfile */ <ide> /** @typedef {import("./RequestShortener")} RequestShortener */ <del>/** @template T @typedef {import("./util/SortableSet")<T>} SortableSet<T> */ <ide> <ide> /** <ide> * @callback OptimizationBailoutFunction <ide> class ExportsInfo { <ide> /** @type {Map<string, ExportInfo>} */ <ide> this._exports = new Map(); <ide> this._otherExportsInfo = new ExportInfo(null); <add> this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); <ide> this._exportsIsOrdered = false; <ide> } <ide> <ide> class ExportsInfo { <ide> } <ide> } <ide> <add> setHasUseInfo() { <add> for (const exportInfo of this._exports.values()) { <add> if (exportInfo.used === undefined) { <add> exportInfo.used = false; <add> } <add> } <add> if (this._otherExportsInfo.used === undefined) { <add> this._otherExportsInfo.used = false; <add> } <add> if (this._sideEffectsOnlyInfo.used === undefined) { <add> this._sideEffectsOnlyInfo.used = false; <add> } <add> } <add> <ide> getExportInfo(name) { <ide> const info = this._exports.get(name); <ide> if (info !== undefined) return info; <ide> class ExportsInfo { <ide> return changed; <ide> } <ide> <add> setUsedInUnknownWay() { <add> let changed = false; <add> if (this._isUsed === false) { <add> this._isUsed = true; <add> changed = true; <add> } <add> for (const exportInfo of this._exports.values()) { <add> if (exportInfo.used !== true && exportInfo.used !== null) { <add> exportInfo.used = null; <add> changed = true; <add> } <add> if (exportInfo.canMangle !== false) { <add> exportInfo.canMangle = false; <add> changed = true; <add> } <add> } <add> if ( <add> this._otherExportsInfo.used !== true && <add> this._otherExportsInfo.used !== null <add> ) { <add> this._otherExportsInfo.used = null; <add> changed = true; <add> } <add> if (this._otherExportsInfo.canMangle !== false) { <add> this._otherExportsInfo.canMangle = false; <add> changed = true; <add> } <add> return changed; <add> } <add> <add> setUsedForSideEffectsOnly() { <add> if (this._sideEffectsOnlyInfo.used === false) { <add> this._sideEffectsOnlyInfo.used = true; <add> return true; <add> } <add> return false; <add> } <add> <add> isUsed() { <add> if (this._otherExportsInfo.used !== false) { <add> return true; <add> } <add> if (this._sideEffectsOnlyInfo.used !== false) { <add> return true; <add> } <add> for (const exportInfo of this._exports.values()) { <add> if (exportInfo.used !== false) { <add> return true; <add> } <add> } <add> } <add> <add> getUsedExports() { <add> switch (this._otherExportsInfo.used) { <add> case undefined: <add> return null; <add> case null: <add> return true; <add> case true: <add> return true; <add> } <add> const array = []; <add> if (!this._exportsIsOrdered) this._sortExports(); <add> for (const exportInfo of this._exports.values()) { <add> switch (exportInfo.used) { <add> case undefined: <add> return null; <add> case null: <add> return true; <add> case true: <add> array.push(exportInfo.name); <add> } <add> } <add> if (array.length === 0) { <add> switch (this._sideEffectsOnlyInfo.used) { <add> case undefined: <add> return null; <add> case false: <add> return false; <add> } <add> } <add> return new SortableSet(array); <add> } <add> <ide> getProvidedExports() { <ide> switch (this._otherExportsInfo.provided) { <ide> case undefined: <ide> class ExportInfo { <ide> constructor(name, initFrom) { <ide> /** @type {string} */ <ide> this.name = name; <add> /** <add> * true: it is used <add> * false: it is not used <add> * null: only the runtime knows if it is used <add> * undefined: it was not determined if it is used <add> * @type {boolean | null | undefined} <add> */ <add> this.used = initFrom ? initFrom.used : undefined; <ide> /** <ide> * true: it is provided <ide> * false: it is not provided <ide> class ExportInfo { <ide> } <ide> <ide> getUsedInfo() { <del> return "no usage info"; <add> switch (this.used) { <add> case undefined: <add> return "no usage info"; <add> case null: <add> return "maybe used (runtime-defined)"; <add> case true: <add> return "used"; <add> case false: <add> return "unused"; <add> } <ide> } <ide> <ide> getProvidedInfo() { <ide> class ModuleGraphModule { <ide> this.optimizationBailout = []; <ide> /** @type {ExportsInfo} */ <ide> this.exports = new ExportsInfo(); <del> /** @type {false | true | SortableSet<string> | null} */ <del> this.usedExports = null; <ide> /** @type {number} */ <ide> this.preOrderIndex = null; <ide> /** @type {number} */ <ide> class ModuleGraph { <ide> newMgm.postOrderIndex = oldMgm.postOrderIndex; <ide> newMgm.preOrderIndex = oldMgm.preOrderIndex; <ide> newMgm.depth = oldMgm.depth; <del> newMgm.usedExports = oldMgm.usedExports; <ide> // TODO optimize this <ide> newMgm.exports.restoreProvided(oldMgm.exports.getRestoreProvidedData()); <ide> } <ide> class ModuleGraph { <ide> */ <ide> getUsedExports(module) { <ide> const mgm = this._getModuleGraphModule(module); <del> return mgm.usedExports; <del> } <del> <del> /** <del> * @param {Module} module the module <del> * @param {false | true | SortableSet<string>} usedExports the used exports <del> * @returns {void} <del> */ <del> setUsedExports(module, usedExports) { <del> const mgm = this._getModuleGraphModule(module); <del> mgm.usedExports = usedExports; <add> return mgm.exports.getUsedExports(); <ide> } <ide> <ide> /** <ide><path>lib/dependencies/RequireIncludeDependency.js <ide> class RequireIncludeDependency extends ModuleDependency { <ide> // This doesn't use any export <ide> return new DependencyReference( <ide> () => moduleGraph.getModule(this), <del> [], <add> false, <ide> false <ide> ); <ide> } <ide><path>lib/optimize/ConcatenatedModule.js <ide> class ConcatenatedModule extends Module { <ide> const result = new ConcatSource(); <ide> <ide> // add harmony compatibility flag (must be first because of possible circular dependencies) <del> const usedExports = moduleGraph.getUsedExports(this.rootModule); <del> if (usedExports === true) { <add> if (moduleGraph.getExportsInfo(this).otherExportsInfo.used !== false) { <ide> result.add( <ide> runtimeTemplate.defineEsModuleFlagStatement({ <ide> exportsArgument: this.exportsArgument, <ide><path>test/configCases/deep-scope-analysis/remove-export-scope-hoisting/webpack.config.js <ide> module.exports = { <ide> Array.isArray(ref.importedNames) && <ide> ref.importedNames.includes("unused") <ide> ) { <add> const newExports = ref.importedNames.filter(item => item !== "unused"); <ide> return new DependencyReference( <ide> () => ref.module, <del> ref.importedNames.filter(item => item !== "unused"), <add> newExports.length > 0 ? newExports : false, <ide> ref.weak, <ide> ref.order <ide> ); <ide><path>test/configCases/deep-scope-analysis/remove-export/webpack.config.js <ide> module.exports = { <ide> Array.isArray(ref.importedNames) && <ide> ref.importedNames.includes("unused") <ide> ) { <add> const newExports = ref.importedNames.filter(item => item !== "unused"); <ide> return new DependencyReference( <ide> () => ref.module, <del> ref.importedNames.filter(item => item !== "unused"), <add> newExports.length > 0 ? newExports : false, <ide> ref.weak, <ide> ref.order <ide> );
9
Go
Go
normalize comment formatting
92ad849327d8ed5640bc7d0fbcba3fcf56f8a962
<ide><path>integration/service/update_test.go <ide> func TestServiceUpdateNetwork(t *testing.T) { <ide> assert.NilError(t, err) <ide> assert.Assert(t, len(netInfo.Containers) == 2, "Expected 2 endpoints, one for container and one for LB Sandbox") <ide> <del> //Remove network from service <add> // Remove network from service <ide> service.Spec.TaskTemplate.Networks = []swarmtypes.NetworkAttachmentConfig{} <ide> _, err = cli.ServiceUpdate(ctx, serviceID, service.Version, service.Spec, types.ServiceUpdateOptions{}) <ide> assert.NilError(t, err)
1
Go
Go
fix typo in error message
d19e1f22cbbb7f4911f95f6b537d3eac65ea0bfe
<ide><path>libnetwork/drivers/overlay/peerdb.go <ide> func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, <ide> <ide> // Add neighbor entry for the peer IP <ide> if err := sbox.AddNeighbor(peerIP, peerMac, sbox.NeighborOptions().LinkName(s.vxlanName)); err != nil { <del> return fmt.Errorf("could not add neigbor entry into the sandbox: %v", err) <add> return fmt.Errorf("could not add neighbor entry into the sandbox: %v", err) <ide> } <ide> <ide> // Add fdb entry to the bridge for the peer mac <ide> func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMas <ide> <ide> // Delete neighbor entry for the peer IP <ide> if err := sbox.DeleteNeighbor(peerIP, peerMac); err != nil { <del> return fmt.Errorf("could not delete neigbor entry into the sandbox: %v", err) <add> return fmt.Errorf("could not delete neighbor entry into the sandbox: %v", err) <ide> } <ide> <ide> if err := d.checkEncryption(nid, vtep, 0, false, false); err != nil {
1
Ruby
Ruby
fix cleanup for head-only formulae
037acb81c82e852aa037b3f8ef70d5f480b34bd5
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_cache <ide> next <ide> end <ide> <del> v = f.stable.version || f.devel.version || f.head.version <del> if v > version || ARGV.switch?('s') && !f.installed? || bottle_file_outdated?(f, file) <add> spec = f.stable || f.devel || f.head <add> if spec.version > version || ARGV.switch?('s') && !f.installed? || bottle_file_outdated?(f, file) <ide> cleanup_cached_file(file) <ide> end <ide> end
1
Javascript
Javascript
add examples for some methods
3be6835e0f0ae4c0e8a191b146662cfe7c762670
<ide><path>src/ng/location.js <ide> var locationPrototype = { <ide> * Return full url representation with all segments encoded according to rules specified in <ide> * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var absUrl = $location.absUrl(); <add> * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" <add> * ``` <add> * <ide> * @return {string} full url <ide> */ <ide> absUrl: locationGetter('$$absUrl'), <ide> var locationPrototype = { <ide> * <ide> * Change path, search and hash, when called with parameter and return `$location`. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var url = $location.url(); <add> * // => "/some/path?foo=bar&baz=xoxo" <add> * ``` <add> * <ide> * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) <ide> * @return {string} url <ide> */ <ide> var locationPrototype = { <ide> * <ide> * Return protocol of current url. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var protocol = $location.protocol(); <add> * // => "http" <add> * ``` <add> * <ide> * @return {string} protocol of current url <ide> */ <ide> protocol: locationGetter('$$protocol'), <ide> var locationPrototype = { <ide> * <ide> * Return host of current url. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var host = $location.host(); <add> * // => "example.com" <add> * ``` <add> * <ide> * @return {string} host of current url. <ide> */ <ide> host: locationGetter('$$host'), <ide> var locationPrototype = { <ide> * <ide> * Return port of current url. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var port = $location.port(); <add> * // => 80 <add> * ``` <add> * <ide> * @return {Number} port <ide> */ <ide> port: locationGetter('$$port'), <ide> var locationPrototype = { <ide> * Note: Path should always begin with forward slash (/), this method will add the forward slash <ide> * if it is missing. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo <add> * var path = $location.path(); <add> * // => "/some/path" <add> * ``` <add> * <ide> * @param {(string|number)=} path New path <ide> * @return {string} path <ide> */ <ide> var locationPrototype = { <ide> * var searchObject = $location.search(); <ide> * // => {foo: 'bar', baz: 'xoxo'} <ide> * <del> * <ide> * // set foo to 'yipee' <ide> * $location.search('foo', 'yipee'); <del> * // => $location <add> * // $location.search() => {foo: 'yipee', baz: 'xoxo'} <ide> * ``` <ide> * <ide> * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or <ide> var locationPrototype = { <ide> * <ide> * Change hash fragment when called with parameter and return `$location`. <ide> * <add> * <add> * ```js <add> * // given url http://example.com/some/path?foo=bar&baz=xoxo#hashValue <add> * var hash = $location.hash(); <add> * // => "hashValue" <add> * ``` <add> * <ide> * @param {(string|number)=} hash New hash fragment <ide> * @return {string} hash <ide> */
1
PHP
PHP
fix scopes with actions not working
1585d0eb4bb9bb4a39441eb6f69bb8ba41308d2b
<ide><path>src/Routing/RouteBuilder.php <ide> public function loadPlugin($name, $file = 'routes.php') <ide> public function connect($route, $defaults = [], array $options = []) <ide> { <ide> $defaults = $this->parseDefaults($defaults); <del> if (!isset($options['action']) && !isset($defaults['action'])) { <del> $defaults['action'] = 'index'; <del> } <del> <ide> if (empty($options['_ext'])) { <ide> $options['_ext'] = $this->_extensions; <ide> } <del> <ide> if (empty($options['routeClass'])) { <ide> $options['routeClass'] = $this->_routeClass; <ide> } <ide> protected function _makeRoute($route, $defaults, $options) <ide> } <ide> } <ide> $defaults += $this->_params + ['plugin' => null]; <add> if (!isset($defaults['action']) && !isset($options['action'])) { <add> $defaults['action'] = 'index'; <add> } <ide> <ide> $route = new $routeClass($route, $defaults, $options); <ide> } <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function testScope() <ide> }); <ide> } <ide> <add> /** <add> * Test adding a scope with action in the scope <add> * <add> * @return void <add> */ <add> public function testScopeWithAction() <add> { <add> $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']); <add> $routes->scope('/prices', ['controller' => 'Prices', 'action' => 'view'], function ($routes) { <add> $routes->connect('/shared', ['shared' => true]); <add> $routes->get('/exclusive', ['exclusive' => true]); <add> }); <add> $all = $this->collection->routes(); <add> $this->assertCount(2, $all); <add> $this->assertSame('view', $all[0]->defaults['action']); <add> $this->assertArrayHasKey('shared', $all[0]->defaults); <add> <add> $this->assertSame('view', $all[1]->defaults['action']); <add> $this->assertArrayHasKey('exclusive', $all[1]->defaults); <add> } <add> <ide> /** <ide> * Test that nested scopes inherit middleware. <ide> *
2
Python
Python
fix arg names for our models
68187c4642568daaca0512393922e8cd1fddf61d
<ide><path>src/transformers/models/esm/modeling_esmfold.py <ide> def bert_mask(self, aa, esmaa, mask, pattern): <ide> def infer( <ide> self, <ide> seqs: Union[str, List[str]], <del> residx=None, <del> with_mask: Optional[torch.Tensor] = None, <add> position_ids=None, <ide> ): <ide> if type(seqs) is str: <ide> lst = [seqs] <ide> def infer( <ide> ] <ide> ) # B=1 x L <ide> mask = collate_dense_tensors([aatype.new_ones(len(seq)) for seq in lst]) <del> residx = ( <del> torch.arange(aatype.shape[1], device=device).expand(len(lst), -1) if residx is None else residx.to(device) <add> position_ids = ( <add> torch.arange(aatype.shape[1], device=device).expand(len(lst), -1) <add> if position_ids is None <add> else position_ids.to(device) <ide> ) <del> if residx.ndim == 1: <del> residx = residx.unsqueeze(0) <add> if position_ids.ndim == 1: <add> position_ids = position_ids.unsqueeze(0) <ide> return self.forward( <ide> aatype, <ide> mask, <del> mask_aa=with_mask is not None, <del> masking_pattern=with_mask, <del> residx=residx, <add> position_ids=position_ids, <ide> ) <ide> <ide> @staticmethod
1
PHP
PHP
fix failing test
0e7947e460a5d3716a5ae38e7784ab67d5e0f84d
<ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> public function testUndefinedValidViewOptions() <ide> public function testDisableAutoLayout() <ide> { <ide> $builder = new ViewBuilder(); <del> $this->assertNull($builder->isAutoLayoutEnabled()); <add> $this->assertTrue($builder->isAutoLayoutEnabled()); <ide> <ide> $builder->disableAutoLayout(); <ide> $this->assertFalse($builder->isAutoLayoutEnabled());
1
Ruby
Ruby
remove circular require
ae9060fc54faa1ec273b090a3791a5a1cab174dd
<ide><path>Library/Homebrew/formula_pin.rb <del>require 'formula' <ide> require 'fileutils' <ide> <ide> class FormulaPin
1
Javascript
Javascript
remove unused $browser dependency
950d02b4d4b1d574dfbb9bbdd56b8dc430db0a93
<ide><path>docs/src/templates/docs.js <del>DocsController.$inject = ['$location', '$browser', '$window', '$cookies']; <del>function DocsController($location, $browser, $window, $cookies) { <add>DocsController.$inject = ['$location', '$window', '$cookies']; <add>function DocsController($location, $window, $cookies) { <ide> window.$root = this.$root; <ide> <ide> var scope = this,
1
Javascript
Javascript
remove usages of isoldie in tests
33747ee8fb349a59368f62c9415664d53c84baf4
<ide><path>test/specs/requests.spec.js <ide> describe('requests', function () { <ide> }); <ide> <ide> it('should support binary data as array buffer', function (done) { <del> // Int8Array doesn't exist in IE8/9 <del> if (isOldIE && typeof Int8Array === 'undefined') { <del> done(); <del> return; <del> } <del> <ide> var input = new Int8Array(2); <ide> input[0] = 1; <ide> input[1] = 2; <ide> describe('requests', function () { <ide> }); <ide> <ide> it('should support binary data as array buffer view', function (done) { <del> // Int8Array doesn't exist in IE8/9 <del> if (isOldIE && typeof Int8Array === 'undefined') { <del> done(); <del> return; <del> } <del> <ide> var input = new Int8Array(2); <ide> input[0] = 1; <ide> input[1] = 2; <ide> describe('requests', function () { <ide> }); <ide> <ide> it('should support array buffer response', function (done) { <del> // ArrayBuffer doesn't exist in IE8/9 <del> if (isOldIE && typeof ArrayBuffer === 'undefined') { <del> done(); <del> return; <del> } <del> <ide> var response; <ide> <ide> function str2ab(str) { <ide><path>test/specs/utils/isX.spec.js <ide> describe('utils::isX', function () { <ide> }); <ide> <ide> it('should validate ArrayBuffer', function () { <del> // ArrayBuffer doesn't exist in IE8/9 <del> if (isOldIE && typeof ArrayBuffer === 'undefined') { <del> return; <del> } <del> <ide> expect(utils.isArrayBuffer(new ArrayBuffer(2))).toEqual(true); <ide> expect(utils.isArrayBuffer({})).toEqual(false); <ide> }); <ide> <ide> it('should validate ArrayBufferView', function () { <del> // ArrayBuffer doesn't exist in IE8/9 <del> if (isOldIE && typeof ArrayBuffer === 'undefined') { <del> return; <del> } <del> <ide> expect(utils.isArrayBufferView(new DataView(new ArrayBuffer(2)))).toEqual(true); <ide> }); <ide> <ide> it('should validate FormData', function () { <del> // FormData doesn't exist in IE8/9 <del> if (isOldIE && typeof FormData === 'undefined') { <del> return; <del> } <del> <ide> expect(utils.isFormData(new FormData())).toEqual(true); <ide> }); <ide> <ide> it('should validate Blob', function () { <del> // Blob doesn't exist in IE8/9 <del> if (isOldIE && typeof Blob === 'undefined') { <del> return; <del> } <del> <ide> expect(utils.isBlob(new Blob())).toEqual(true); <ide> }); <ide>
2
Javascript
Javascript
remove incorrect casts, improve error handling
603d4026ed6133ac5ca3c9120f4d33f5643dc2e0
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> const usedHash = fileManifest.hash; <ide> <ide> this.cache.get(cacheName, usedHash, (err, sourceFromCache) => { <del> let filenameTemplate, file; <add> /** @type {string | function(PathData): string} */ <add> let filenameTemplate; <add> /** @type {string} */ <add> let file; <add> <add> let inTry = true; <add> const errorAndCallback = err => { <add> const filename = <add> file || <add> (typeof filenameTemplate === "string" <add> ? filenameTemplate <add> : ""); <add> <add> this.errors.push(new ChunkRenderError(chunk, filename, err)); <add> inTry = false; <add> return callback(); <add> }; <add> <ide> try { <ide> filenameTemplate = fileManifest.filenameTemplate; <ide> file = this.getPath(filenameTemplate, fileManifest.pathOptions); <ide> <del> const filename = <del> file || /** @type {string} */ (filenameTemplate); <del> <ide> if (err) { <del> this.errors.push(new ChunkRenderError(chunk, filename, err)); <del> return callback(); <add> return errorAndCallback(err); <ide> } <ide> <ide> let source = sourceFromCache; <ide> class Compilation { <ide> const alreadyWritten = alreadyWrittenFiles.get(file); <ide> if (alreadyWritten !== undefined) { <ide> if (alreadyWritten.hash !== usedHash) { <add> inTry = false; <ide> return callback( <ide> new WebpackError( <ide> `Conflict: Multiple chunks emit assets to the same filename ${file}` + <ide> class Compilation { <ide> } <ide> } <ide> if (this.assets[file] && this.assets[file] !== source) { <add> inTry = false; <ide> return callback( <ide> new WebpackError( <ide> `Conflict: Rendering chunk ${chunk.id} ` + <ide> class Compilation { <ide> chunk <ide> }); <ide> if (source !== sourceFromCache) { <del> this.cache.store(cacheName, usedHash, source, callback); <add> this.cache.store(cacheName, usedHash, source, err => { <add> if (err) return errorAndCallback(err); <add> return callback(); <add> }); <ide> } else { <add> inTry = false; <ide> callback(); <ide> } <ide> } catch (err) { <del> const filename = <del> file || /** @type {string} */ (filenameTemplate); <del> <del> this.errors.push( <del> new ChunkRenderError(chunk, file || filename, err) <del> ); <del> return callback(); <add> if (!inTry) throw err; <add> errorAndCallback(err); <ide> } <ide> }); <ide> },
1
Ruby
Ruby
rename the method to match what it is doing
b24ed15baa988a37b436bc9636bd0ecdb3ae0a4a
<ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> def allow_only_integer?(record) <ide> end <ide> end <ide> <del> def read_attribute_for_validation(record, attr_name, value) <add> def prepare_value_for_validation(value, record, attr_name) <ide> return value if record_attribute_changed_in_place?(record, attr_name) <ide> <ide> came_from_user = :"#{attr_name}_came_from_user?" <ide><path>activemodel/lib/active_model/validator.rb <ide> def validate(record) <ide> attributes.each do |attribute| <ide> value = record.read_attribute_for_validation(attribute) <ide> next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) <del> value = read_attribute_for_validation(record, attribute, value) <add> value = prepare_value_for_validation(value, record, attribute) <ide> validate_each(record, attribute, value) <ide> end <ide> end <ide> def check_validity! <ide> end <ide> <ide> private <del> def read_attribute_for_validation(record, attr_name, value) <add> def prepare_value_for_validation(value, record, attr_name) <ide> value <ide> end <ide> end
2
Python
Python
fix default fallback in genfromtxt
8bc4701bbfbcfafb2be634d41a2611bd0182d344
<ide><path>numpy/lib/_iotools.py <ide> class StringConverter: <ide> _mapper.extend([(nx.float64, float, nx.nan), <ide> (nx.complex128, complex, nx.nan + 0j), <ide> (nx.longdouble, nx.longdouble, nx.nan), <del> (nx.unicode_, asunicode, '???'), <del> (nx.string_, asbytes, '???'), <ide> # If a non-default dtype is passed, fall back to generic <ide> # ones (should only be used for the converter) <ide> (nx.integer, int, -1), <ide> (nx.floating, float, nx.nan), <del> (nx.complexfloating, complex, nx.nan + 0j),]) <add> (nx.complexfloating, complex, nx.nan + 0j), <add> # Last, try with the string types (must be last, because <add> # `_mapper[-1]` is used as default in some cases) <add> (nx.unicode_, asunicode, '???'), <add> (nx.string_, asbytes, '???'),]) <ide> <ide> @classmethod <ide> def _getdtype(cls, val): <ide><path>numpy/lib/tests/test__iotools.py <ide> def test_upgrade(self): <ide> # test str <ide> # note that the longdouble type has been skipped, so the <ide> # _status increases by 2. Everything should succeed with <del> # unicode conversion (5). <add> # unicode conversion (8). <ide> for s in ['a', b'a']: <ide> res = converter.upgrade(s) <ide> assert_(type(res) is str) <ide> assert_equal(res, 'a') <del> assert_equal(converter._status, 5 + status_offset) <add> assert_equal(converter._status, 8 + status_offset) <ide> <ide> def test_missing(self): <ide> "Tests the use of missing values." <ide><path>numpy/lib/tests/test_io.py <ide> def test_dtype_with_object(self): <ide> test = np.genfromtxt(TextIO(data), delimiter=";", <ide> dtype=ndtype, converters=converters) <ide> <add> def test_dtype_with_object_no_converter(self): <add> # Object without a converter uses bytes: <add> parsed = np.genfromtxt(TextIO("1"), dtype=object) <add> assert parsed[()] == b"1" <add> parsed = np.genfromtxt(TextIO("string"), dtype=object) <add> assert parsed[()] == b"string" <add> <ide> def test_userconverters_with_explicit_dtype(self): <ide> # Test user_converters w/ explicit (standard) dtype <ide> data = TextIO('skip,skip,2001-01-01,1.0,skip')
3
Javascript
Javascript
add array<object> props to schema
bc1c7b1096b7155742325cd66761303c919d860a
<ide><path>packages/react-native-codegen/src/CodegenSchema.js <ide> type PropTypeTypeAnnotation = <ide> name: string, <ide> |}>, <ide> |}> <add> | $ReadOnly<{| <add> type: 'ObjectTypeAnnotation', <add> properties: $ReadOnlyArray<PropTypeShape>, <add> |}> <ide> | $ReadOnly<{| <ide> type: 'NativePrimitiveTypeAnnotation', <ide> name: 'ColorPrimitive' | 'ImageSourcePrimitive' | 'PointPrimitive',
1
Python
Python
add the reference to 'printoptions'
112ce58723a37bb6ebca34cae42476e96bb8eede
<ide><path>numpy/core/arrayprint.py <ide> def set_printoptions(precision=None, threshold=None, edgeitems=None, <ide> <ide> See Also <ide> -------- <del> get_printoptions, set_string_function, array2string <add> get_printoptions, printoptions, set_string_function, array2string <ide> <ide> Notes <ide> ----- <ide> def get_printoptions(): <ide> <ide> See Also <ide> -------- <del> set_printoptions, set_string_function <add> set_printoptions, printoptions, set_string_function <ide> <ide> """ <ide> return _format_options.copy()
1
Go
Go
add test w/ "" stream only
f26f405b00a2d9d1c6ebc11bffb810c54ac510ce
<ide><path>pkg/broadcastwriter/broadcastwriter_test.go <ide> func BenchmarkBroadcastWriter(b *testing.B) { <ide> b.StartTimer() <ide> } <ide> } <add> <add>func BenchmarkBroadcastWriterWithoutStdoutStderr(b *testing.B) { <add> writer := New() <add> setUpWriter := func() { <add> for i := 0; i < 100; i++ { <add> writer.AddWriter(devNullCloser(0), "") <add> } <add> } <add> testLine := "Line that thinks that it is log line from docker" <add> var buf bytes.Buffer <add> for i := 0; i < 100; i++ { <add> buf.Write([]byte(testLine + "\n")) <add> } <add> // line without eol <add> buf.Write([]byte(testLine)) <add> testText := buf.Bytes() <add> b.SetBytes(int64(5 * len(testText))) <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> setUpWriter() <add> <add> for j := 0; j < 5; j++ { <add> if _, err := writer.Write(testText); err != nil { <add> b.Fatal(err) <add> } <add> } <add> <add> writer.Clean() <add> } <add>}
1
Javascript
Javascript
expose clipboard docs
f6b0c13fd6196ba8599badfb3c3e52ab004f4fd5
<ide><path>website/server/extractDocs.js <ide> var apis = [ <ide> '../Libraries/Storage/AsyncStorage.js', <ide> '../Libraries/Utilities/BackAndroid.android.js', <ide> '../Libraries/CameraRoll/CameraRoll.js', <add> '../Libraries/Components/Clipboard/Clipboard.js', <ide> '../Libraries/Components/DatePickerAndroid/DatePickerAndroid.android.js', <ide> '../Libraries/Utilities/Dimensions.js', <ide> '../Libraries/Components/Intent/IntentAndroid.android.js',
1
Text
Text
fix yaml lint error on master
1103b15af65dec07363288ce101bc11a6d9aa16b
<ide><path>doc/api/process.md <ide> added: v11.12.0 <ide> changes: <ide> - version: <ide> - REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/35654 <ide> description: This API is no longer experimental. <ide> --> <ide>
1
Javascript
Javascript
provide better error when writing after fin
2106ef000c7d891385d5480a61d95327caf8e277
<ide><path>lib/_stream_writable.js <ide> Writable.prototype.write = function(chunk, encoding, cb) { <ide> } <ide> <ide> if (state.ended) { <add> var self = this; <ide> var er = new Error('write after end'); <del> if (typeof cb === 'function') <del> cb(er); <del> this.emit('error', er); <add> // TODO: defer error events consistently everywhere, not just the cb <add> self.emit('error', er); <add> if (typeof cb === 'function') { <add> process.nextTick(function() { <add> cb(er); <add> }); <add> } <ide> return; <ide> } <ide> <ide><path>lib/net.js <ide> function onSocketEnd() { <ide> this.read(0); <ide> } <ide> <del> if (!this.allowHalfOpen) <add> if (!this.allowHalfOpen) { <add> this.write = writeAfterFIN; <ide> this.destroySoon(); <add> } <add>} <add> <add>// Provide a better error message when we call end() as a result <add>// of the other side sending a FIN. The standard 'write after end' <add>// is overly vague, and makes it seem like the user's code is to blame. <add>function writeAfterFIN(chunk, encoding, cb) { <add> if (typeof encoding === 'function') { <add> cb = encoding; <add> encoding = null; <add> } <add> <add> var er = new Error('This socket has been closed by the other party'); <add> er.code = 'EPIPE'; <add> var self = this; <add> // TODO: defer error events consistently everywhere, not just the cb <add> self.emit('error', er); <add> if (typeof cb === 'function') { <add> process.nextTick(function() { <add> cb(er); <add> }); <add> } <ide> } <ide> <ide> exports.Socket = Socket; <ide> function connect(self, address, port, addressType, localAddress) { <ide> <ide> <ide> Socket.prototype.connect = function(options, cb) { <add> if (this.write !== Socket.prototype.write) <add> this.write = Socket.prototype.write; <add> <ide> if (typeof options !== 'object') { <ide> // Old API: <ide> // connect(port, [host], [cb]) <ide><path>test/simple/test-socket-write-after-fin-error.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>// This is similar to simple/test-socket-write-after-fin, except that <add>// we don't set allowHalfOpen. Then we write after the client has sent <add>// a FIN, and this is an error. However, the standard "write after end" <add>// message is too vague, and doesn't actually tell you what happens. <add> <add>var net = require('net'); <add>var serverData = ''; <add>var gotServerEnd = false; <add>var clientData = ''; <add>var gotClientEnd = false; <add>var gotServerError = false; <add> <add>var server = net.createServer(function(sock) { <add> sock.setEncoding('utf8'); <add> sock.on('error', function(er) { <add> console.error(er.code + ': ' + er.message); <add> gotServerError = er; <add> }); <add> <add> sock.on('data', function(c) { <add> serverData += c; <add> }); <add> sock.on('end', function() { <add> gotServerEnd = true <add> sock.write(serverData); <add> sock.end(); <add> }); <add> server.close(); <add>}); <add>server.listen(common.PORT); <add> <add>var sock = net.connect(common.PORT); <add>sock.setEncoding('utf8'); <add>sock.on('data', function(c) { <add> clientData += c; <add>}); <add> <add>sock.on('end', function() { <add> gotClientEnd = true; <add>}); <add> <add>process.on('exit', function() { <add> assert.equal(clientData, ''); <add> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <add> assert(gotClientEnd); <add> assert(gotServerEnd); <add> assert(gotServerError); <add> assert.equal(gotServerError.code, 'EPIPE'); <add> assert.notEqual(gotServerError.message, 'write after end'); <add> console.log('ok'); <add>}); <add> <add>sock.write('hello1'); <add>sock.write('hello2'); <add>sock.write('hello3\n'); <add>sock.end('THUNDERMUSCLE!'); <ide><path>test/simple/test-socket-write-after-fin.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>var net = require('net'); <add>var serverData = ''; <add>var gotServerEnd = false; <add>var clientData = ''; <add>var gotClientEnd = false; <add> <add>var server = net.createServer({ allowHalfOpen: true }, function(sock) { <add> sock.setEncoding('utf8'); <add> sock.on('data', function(c) { <add> serverData += c; <add> }); <add> sock.on('end', function() { <add> gotServerEnd = true <add> sock.end(serverData); <add> server.close(); <add> }); <add>}); <add>server.listen(common.PORT); <add> <add>var sock = net.connect(common.PORT); <add>sock.setEncoding('utf8'); <add>sock.on('data', function(c) { <add> clientData += c; <add>}); <add> <add>sock.on('end', function() { <add> gotClientEnd = true; <add>}); <add> <add>process.on('exit', function() { <add> assert.equal(serverData, clientData); <add> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <add> assert(gotClientEnd); <add> assert(gotServerEnd); <add> console.log('ok'); <add>}); <add> <add>sock.write('hello1'); <add>sock.write('hello2'); <add>sock.write('hello3\n'); <add>sock.end('THUNDERMUSCLE!');
4
Javascript
Javascript
display error message when loading directory
aad6b9f0ebf79cb4f80a9b4be7c05e27a5d9489d
<ide><path>lib/repl.js <ide> function defineDefaultCommands(repl) { <ide> self.write(line + '\n'); <ide> } <ide> }); <add> } else { <add> this.outputStream.write('Failed to load:' + file + <add> ' is not a valid file\n'); <ide> } <ide> } catch (e) { <ide> this.outputStream.write('Failed to load:' + file + '\n'); <ide><path>test/parallel/test-repl-.save.load.js <ide> putIn.write = function(data) { <ide> }; <ide> putIn.run(['.load ' + loadFile]); <ide> <add>// throw error on loading directory <add>loadFile = common.tmpDir; <add>putIn.write = function(data) { <add> assert.equal(data, 'Failed to load:' + loadFile + ' is not a valid file\n'); <add> putIn.write = function() {}; <add>}; <add>putIn.run(['.load ' + loadFile]); <add> <ide> // clear the REPL <ide> putIn.run(['.clear']); <ide>
2
PHP
PHP
remove debug code
ba68e8dde78b708357ddc0a5a28e62870ddbbbd4
<ide><path>src/Core/functions.php <ide> function deprecationWarning(string $message, int $stackFrame = 1): void <ide> <ide> $patterns = (array)Configure::read('Error.disableDeprecations'); <ide> $relative = substr($frame['file'], strlen(ROOT) + 1); <del> debug($relative); <ide> foreach ($patterns as $pattern) { <ide> $pattern = str_replace('/', DIRECTORY_SEPARATOR, $pattern); <ide> if (fnmatch($pattern, $relative)) {
1
Javascript
Javascript
implement anchor scroll when content added
eb51b024c9b77527420014cdf7dbb292b5b9dd6b
<ide><path>docs/src/templates/js/docs.js <ide> docsApp.directive.sourceEdit = function(getEmbeddedTemplate) { <ide> } <ide> }; <ide> <del>docsApp.directive.docModuleComponents = ['sections', function(sections) { <add>docsApp.directive.docModuleComponents = function() { <ide> return { <ide> template: ' <div class="component-breakdown">' + <ide> ' <h2>Module Components</h2>' + <del> ' <div ng-repeat="(key, section) in components">' + <del> ' <h3 class="component-heading" id="{{ section.type }}">{{ section.title }}</h3>' + <del> ' <table class="definition-table">' + <del> ' <tr>' + <del> ' <th>Name</th>' + <del> ' <th>Description</th>' + <del> ' </tr>' + <del> ' <tr ng-repeat="component in section.components">' + <del> ' <td><a ng-href="{{ component.url }}">{{ component.shortName }}</a></td>' + <del> ' <td>{{ component.shortDescription }}</td>' + <del> ' </tr>' + <del> ' </table>' + <add> ' <div ng-repeat="(key, section) in components">' + <add> ' <h3 class="component-heading" id="{{ section.type }}">{{ section.title }}</h3>' + <add> ' <table class="definition-table">' + <add> ' <tr>' + <add> ' <th>Name</th>' + <add> ' <th>Description</th>' + <add> ' </tr>' + <add> ' <tr ng-repeat="component in section.components">' + <add> ' <td><a ng-href="{{ component.url }}">{{ component.shortName }}</a></td>' + <add> ' <td>{{ component.shortDescription }}</td>' + <add> ' </tr>' + <add> ' </table>' + <ide> ' </div>' + <ide> ' </div>', <ide> scope : { <ide> module : '@docModuleComponents' <ide> }, <del> controller : ['$scope', function($scope) { <add> controller : ['$scope', '$anchorScroll', '$timeout', 'sections', <add> function($scope, $anchorScroll, $timeout, sections) { <ide> var validTypes = ['property','function','directive','service','object','filter']; <ide> var components = {}; <ide> angular.forEach(sections.api, function(item) { <ide> docsApp.directive.docModuleComponents = ['sections', function(sections) { <ide> components[type] = components[type] || { <ide> title : type, <ide> type : type, <del> components : [] <add> components : [] <ide> }; <ide> components[type].components.push(item); <ide> } <ide> } <ide> }); <ide> $scope.components = components; <add> $timeout($anchorScroll, 0, false); <ide> }] <ide> }; <del>}] <add>}; <ide> <ide> docsApp.directive.docTutorialNav = function(templateMerge) { <ide> var pages = [ <ide> docsApp.serviceFactory.prepareDefaultAppModule = function() { <ide> var moduleName = 'App'; <ide> return { <ide> module : moduleName, <del> script : "angular.module('" + moduleName + "', [" + <add> script : "angular.module('" + moduleName + "', [" + <ide> (deps.length ? "'" + deps.join("','") + "'" : "") + "]);\n\n" <ide> }; <ide> }; <ide> docsApp.controller.DocsController = function($scope, $location, $window, $cookie <ide> error: 'Error Reference' <ide> }; <ide> <del> populateComponentsList(); <add> populateComponentsList(); <ide> <ide> $scope.$watch(function docsPathWatch() {return $location.path(); }, function docsPathWatchAction(path) { <ide> // ignore non-doc links which are used in examples
1
Ruby
Ruby
remove tests for hash_for_* methods
ce5c2b88fead992db51476c14cc2d7c323f5cd0c
<ide><path>actionpack/test/controller/routing_test.rb <ide> def setup_named_route_test <ide> MockController.build(set.url_helpers).new <ide> end <ide> <del> def test_named_route_hash_access_method <del> controller = setup_named_route_test <del> <del> assert_equal( <del> { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => false }, <del> controller.send(:hash_for_show_url, :id => 5)) <del> <del> assert_equal( <del> { :controller => 'people', :action => 'index', :use_route => "index", :only_path => false }, <del> controller.send(:hash_for_index_url)) <del> <del> assert_equal( <del> { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => true }, <del> controller.send(:hash_for_show_path, :id => 5) <del> ) <del> end <del> <ide> def test_named_route_url_method <ide> controller = setup_named_route_test <ide> <ide> def test_named_route_url_method <ide> <ide> assert_equal "http://test.host/admin/users", controller.send(:users_url) <ide> assert_equal '/admin/users', controller.send(:users_path) <del> assert_equal '/admin/users', url_for(set, controller.send(:hash_for_users_url), { :controller => 'users', :action => 'index' }) <ide> end <ide> <ide> def test_named_route_url_method_with_anchor
1
Python
Python
use frozen list with custom errors
34146750d4284b542078255f1c8dfaf4c0652a23
<ide><path>spacy/__init__.py <ide> <ide> def load( <ide> name: Union[str, Path], <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = util.SimpleFrozenList(), <add> exclude: Iterable[str] = util.SimpleFrozenList(), <ide> config: Union[Dict[str, Any], Config] = util.SimpleFrozenDict(), <ide> ) -> Language: <ide> """Load a spaCy model from an installed package or a local path. <ide><path>spacy/cli/project/dvc.py <ide> """This module contains helpers and subcommands for integrating spaCy projects <ide> with Data Version Controk (DVC). https://dvc.org""" <del>from typing import Dict, Any, List, Optional <add>from typing import Dict, Any, List, Optional, Iterable <ide> import subprocess <ide> from pathlib import Path <ide> from wasabi import msg <ide> <ide> from .._util import PROJECT_FILE, load_project_config, get_hash, project_cli <ide> from .._util import Arg, Opt, NAME, COMMAND <ide> from ...util import working_dir, split_command, join_command, run_command <add>from ...util import SimpleFrozenList <ide> <ide> <ide> DVC_CONFIG = "dvc.yaml" <ide> def update_dvc_config( <ide> <ide> <ide> def run_dvc_commands( <del> commands: List[str] = tuple(), flags: Dict[str, bool] = {}, <add> commands: Iterable[str] = SimpleFrozenList(), flags: Dict[str, bool] = {}, <ide> ) -> None: <ide> """Run a sequence of DVC commands in a subprocess, in order. <ide> <ide><path>spacy/cli/project/run.py <del>from typing import Optional, List, Dict, Sequence, Any <add>from typing import Optional, List, Dict, Sequence, Any, Iterable <ide> from pathlib import Path <ide> from wasabi import msg <ide> import sys <ide> import srsly <ide> <ide> from ...util import working_dir, run_command, split_command, is_cwd, join_command <add>from ...util import SimpleFrozenList <ide> from .._util import PROJECT_FILE, PROJECT_LOCK, load_project_config, get_hash <ide> from .._util import get_checksum, project_cli, Arg, Opt, COMMAND <ide> <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <ide> <ide> <ide> def run_commands( <del> commands: List[str] = tuple(), silent: bool = False, dry: bool = False, <add> commands: Iterable[str] = SimpleFrozenList(), <add> silent: bool = False, <add> dry: bool = False, <ide> ) -> None: <ide> """Run a sequence of commands in a subprocess, in order. <ide> <ide><path>spacy/errors.py <ide> class Errors: <ide> E199 = ("Unable to merge 0-length span at doc[{start}:{end}].") <ide> <ide> # TODO: fix numbering after merging develop into master <add> E926 = ("It looks like you're trying to modify nlp.{attr} directly. This " <add> "doesn't work because it's an immutable computed property. If you " <add> "need to modify the pipeline, use the built-in methods like " <add> "nlp.add_pipe, nlp.remove_pipe, nlp.disable_pipe or nlp.enable_pipe " <add> "instead.") <add> E927 = ("Can't write to frozen list Maybe you're trying to modify a computed " <add> "property or default function argument?") <ide> E928 = ("A 'KnowledgeBase' should be written to / read from a file, but the " <ide> "provided argument {loc} is an existing directory.") <ide> E929 = ("A 'KnowledgeBase' could not be read from {loc} - the path does " <ide><path>spacy/language.py <ide> from .pipe_analysis import validate_attrs, analyze_pipes, print_pipe_analysis <ide> from .gold import Example, validate_examples <ide> from .scorer import Scorer <del>from .util import create_default_optimizer, registry <add>from .util import create_default_optimizer, registry, SimpleFrozenList <ide> from .util import SimpleFrozenDict, combine_score_weights, CONFIG_SECTION_ORDER <ide> from .lang.tokenizer_exceptions import URL_MATCH, BASE_EXCEPTIONS <ide> from .lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES <ide> def __init__( <ide> self.vocab: Vocab = vocab <ide> if self.lang is None: <ide> self.lang = self.vocab.lang <del> self.components = [] <add> self._components = [] <ide> self._disabled = set() <ide> self.max_length = max_length <ide> self.resolved = {} <ide> def meta(self) -> Dict[str, Any]: <ide> "keys": self.vocab.vectors.n_keys, <ide> "name": self.vocab.vectors.name, <ide> } <del> self._meta["labels"] = self.pipe_labels <add> self._meta["labels"] = dict(self.pipe_labels) <ide> # TODO: Adding this back to prevent breaking people's code etc., but <ide> # we should consider removing it <del> self._meta["pipeline"] = self.pipe_names <del> self._meta["disabled"] = self.disabled <add> self._meta["pipeline"] = list(self.pipe_names) <add> self._meta["disabled"] = list(self.disabled) <ide> return self._meta <ide> <ide> @meta.setter <ide> def config(self) -> Config: <ide> pipeline[pipe_name] = {"factory": pipe_meta.factory, **pipe_config} <ide> if pipe_meta.default_score_weights: <ide> score_weights.append(pipe_meta.default_score_weights) <del> self._config["nlp"]["pipeline"] = self.component_names <del> self._config["nlp"]["disabled"] = self.disabled <add> self._config["nlp"]["pipeline"] = list(self.component_names) <add> self._config["nlp"]["disabled"] = list(self.disabled) <ide> self._config["components"] = pipeline <ide> self._config["training"]["score_weights"] = combine_score_weights(score_weights) <ide> if not srsly.is_json_serializable(self._config): <ide> def disabled(self) -> List[str]: <ide> """ <ide> # Make sure the disabled components are returned in the order they <ide> # appear in the pipeline (which isn't guaranteed by the set) <del> return [name for name, _ in self.components if name in self._disabled] <add> names = [name for name, _ in self._components if name in self._disabled] <add> return SimpleFrozenList(names, error=Errors.E926.format(attr="disabled")) <ide> <ide> @property <ide> def factory_names(self) -> List[str]: <ide> """Get names of all available factories. <ide> <ide> RETURNS (List[str]): The factory names. <ide> """ <del> return list(self.factories.keys()) <add> names = list(self.factories.keys()) <add> return SimpleFrozenList(names) <add> <add> @property <add> def components(self) -> List[Tuple[str, Callable[[Doc], Doc]]]: <add> """Get all (name, component) tuples in the pipeline, including the <add> currently disabled components. <add> """ <add> return SimpleFrozenList( <add> self._components, error=Errors.E926.format(attr="components") <add> ) <ide> <ide> @property <ide> def component_names(self) -> List[str]: <ide> def component_names(self) -> List[str]: <ide> <ide> RETURNS (List[str]): List of component name strings, in order. <ide> """ <del> return [pipe_name for pipe_name, _ in self.components] <add> names = [pipe_name for pipe_name, _ in self._components] <add> return SimpleFrozenList(names, error=Errors.E926.format(attr="component_names")) <ide> <ide> @property <ide> def pipeline(self) -> List[Tuple[str, Callable[[Doc], Doc]]]: <ide> def pipeline(self) -> List[Tuple[str, Callable[[Doc], Doc]]]: <ide> <ide> RETURNS (List[Tuple[str, Callable[[Doc], Doc]]]): The pipeline. <ide> """ <del> return [(name, p) for name, p in self.components if name not in self._disabled] <add> pipes = [(n, p) for n, p in self._components if n not in self._disabled] <add> return SimpleFrozenList(pipes, error=Errors.E926.format(attr="pipeline")) <ide> <ide> @property <ide> def pipe_names(self) -> List[str]: <ide> """Get names of available active pipeline components. <ide> <ide> RETURNS (List[str]): List of component name strings, in order. <ide> """ <del> return [pipe_name for pipe_name, _ in self.pipeline] <add> names = [pipe_name for pipe_name, _ in self.pipeline] <add> return SimpleFrozenList(names, error=Errors.E926.format(attr="pipe_names")) <ide> <ide> @property <ide> def pipe_factories(self) -> Dict[str, str]: <ide> def pipe_factories(self) -> Dict[str, str]: <ide> RETURNS (Dict[str, str]): Factory names, keyed by component names. <ide> """ <ide> factories = {} <del> for pipe_name, pipe in self.components: <add> for pipe_name, pipe in self._components: <ide> factories[pipe_name] = self.get_pipe_meta(pipe_name).factory <del> return factories <add> return SimpleFrozenDict(factories) <ide> <ide> @property <ide> def pipe_labels(self) -> Dict[str, List[str]]: <ide> def pipe_labels(self) -> Dict[str, List[str]]: <ide> RETURNS (Dict[str, List[str]]): Labels keyed by component name. <ide> """ <ide> labels = {} <del> for name, pipe in self.components: <add> for name, pipe in self._components: <ide> if hasattr(pipe, "labels"): <ide> labels[name] = list(pipe.labels) <del> return labels <add> return SimpleFrozenDict(labels) <ide> <ide> @classmethod <ide> def has_factory(cls, name: str) -> bool: <ide> def factory( <ide> name: str, <ide> *, <ide> default_config: Dict[str, Any] = SimpleFrozenDict(), <del> assigns: Iterable[str] = tuple(), <del> requires: Iterable[str] = tuple(), <add> assigns: Iterable[str] = SimpleFrozenList(), <add> requires: Iterable[str] = SimpleFrozenList(), <ide> retokenizes: bool = False, <del> scores: Iterable[str] = tuple(), <add> scores: Iterable[str] = SimpleFrozenList(), <ide> default_score_weights: Dict[str, float] = SimpleFrozenDict(), <ide> func: Optional[Callable] = None, <ide> ) -> Callable: <ide> def component( <ide> cls, <ide> name: Optional[str] = None, <ide> *, <del> assigns: Iterable[str] = tuple(), <del> requires: Iterable[str] = tuple(), <add> assigns: Iterable[str] = SimpleFrozenList(), <add> requires: Iterable[str] = SimpleFrozenList(), <ide> retokenizes: bool = False, <ide> func: Optional[Callable[[Doc], Doc]] = None, <ide> ) -> Callable: <ide> def get_pipe(self, name: str) -> Callable[[Doc], Doc]: <ide> <ide> DOCS: https://spacy.io/api/language#get_pipe <ide> """ <del> for pipe_name, component in self.components: <add> for pipe_name, component in self._components: <ide> if pipe_name == name: <ide> return component <ide> raise KeyError(Errors.E001.format(name=name, opts=self.component_names)) <ide> def add_pipe( <ide> ) <ide> pipe_index = self._get_pipe_index(before, after, first, last) <ide> self._pipe_meta[name] = self.get_factory_meta(factory_name) <del> self.components.insert(pipe_index, (name, pipe_component)) <add> self._components.insert(pipe_index, (name, pipe_component)) <ide> return pipe_component <ide> <ide> def _get_pipe_index( <ide> def _get_pipe_index( <ide> Errors.E006.format(args=all_args, opts=self.component_names) <ide> ) <ide> if last or not any(value is not None for value in [first, before, after]): <del> return len(self.components) <add> return len(self._components) <ide> elif first: <ide> return 0 <ide> elif isinstance(before, str): <ide> def _get_pipe_index( <ide> # We're only accepting indices referring to components that exist <ide> # (can't just do isinstance here because bools are instance of int, too) <ide> elif type(before) == int: <del> if before >= len(self.components) or before < 0: <add> if before >= len(self._components) or before < 0: <ide> err = Errors.E959.format( <ide> dir="before", idx=before, opts=self.component_names <ide> ) <ide> raise ValueError(err) <ide> return before <ide> elif type(after) == int: <del> if after >= len(self.components) or after < 0: <add> if after >= len(self._components) or after < 0: <ide> err = Errors.E959.format( <ide> dir="after", idx=after, opts=self.component_names <ide> ) <ide> def replace_pipe( <ide> # to Language.pipeline to make sure the configs are handled correctly <ide> pipe_index = self.pipe_names.index(name) <ide> self.remove_pipe(name) <del> if not len(self.components) or pipe_index == len(self.components): <add> if not len(self._components) or pipe_index == len(self._components): <ide> # we have no components to insert before/after, or we're replacing the last component <ide> self.add_pipe(factory_name, name=name, config=config, validate=validate) <ide> else: <ide> def rename_pipe(self, old_name: str, new_name: str) -> None: <ide> Errors.E007.format(name=new_name, opts=self.component_names) <ide> ) <ide> i = self.component_names.index(old_name) <del> self.components[i] = (new_name, self.components[i][1]) <add> self._components[i] = (new_name, self._components[i][1]) <ide> self._pipe_meta[new_name] = self._pipe_meta.pop(old_name) <ide> self._pipe_configs[new_name] = self._pipe_configs.pop(old_name) <ide> <ide> def remove_pipe(self, name: str) -> Tuple[str, Callable[[Doc], Doc]]: <ide> """ <ide> if name not in self.component_names: <ide> raise ValueError(Errors.E001.format(name=name, opts=self.component_names)) <del> removed = self.components.pop(self.component_names.index(name)) <add> removed = self._components.pop(self.component_names.index(name)) <ide> # We're only removing the component itself from the metas/configs here <ide> # because factory may be used for something else <ide> self._pipe_meta.pop(name) <ide> def __call__( <ide> self, <ide> text: str, <ide> *, <del> disable: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <ide> component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, <ide> ) -> Doc: <ide> """Apply the pipeline to some text. The text can span multiple sentences, <ide> def update( <ide> sgd: Optional[Optimizer] = None, <ide> losses: Optional[Dict[str, float]] = None, <ide> component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, <del> exclude: Iterable[str] = tuple(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> ): <ide> """Update the models in the pipeline. <ide> <ide> def rehearse( <ide> sgd: Optional[Optimizer] = None, <ide> losses: Optional[Dict[str, float]] = None, <ide> component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, <del> exclude: Iterable[str] = tuple(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> ) -> Dict[str, float]: <ide> """Make a "rehearsal" update to the models in the pipeline, to prevent <ide> forgetting. Rehearsal updates run an initial copy of the model over some <ide> def pipe( <ide> *, <ide> as_tuples: bool = False, <ide> batch_size: int = 1000, <del> disable: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <ide> cleanup: bool = False, <ide> component_cfg: Optional[Dict[str, Dict[str, Any]]] = None, <ide> n_process: int = 1, <ide> def from_config( <ide> config: Union[Dict[str, Any], Config] = {}, <ide> *, <ide> vocab: Union[Vocab, bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> auto_fill: bool = True, <ide> validate: bool = True, <ide> ) -> "Language": <ide> def from_config( <ide> return nlp <ide> <ide> def to_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> None: <ide> """Save the current state to a directory. If a model is loaded, this <ide> will include the model. <ide> def to_disk( <ide> ) <ide> serializers["meta.json"] = lambda p: srsly.write_json(p, self.meta) <ide> serializers["config.cfg"] = lambda p: self.config.to_disk(p) <del> for name, proc in self.components: <add> for name, proc in self._components: <ide> if name in exclude: <ide> continue <ide> if not hasattr(proc, "to_disk"): <ide> def to_disk( <ide> util.to_disk(path, serializers, exclude) <ide> <ide> def from_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> "Language": <ide> """Loads state from a directory. Modifies the object in place and <ide> returns it. If the saved `Language` object contains a model, the <ide> def deserialize_vocab(path: Path) -> None: <ide> deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk( <ide> p, exclude=["vocab"] <ide> ) <del> for name, proc in self.components: <add> for name, proc in self._components: <ide> if name in exclude: <ide> continue <ide> if not hasattr(proc, "from_disk"): <ide> def deserialize_vocab(path: Path) -> None: <ide> self._link_components() <ide> return self <ide> <del> def to_bytes(self, *, exclude: Iterable[str] = tuple()) -> bytes: <add> def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes: <ide> """Serialize the current state to a binary string. <ide> <ide> exclude (list): Names of components or serialization fields to exclude. <ide> def to_bytes(self, *, exclude: Iterable[str] = tuple()) -> bytes: <ide> serializers["tokenizer"] = lambda: self.tokenizer.to_bytes(exclude=["vocab"]) <ide> serializers["meta.json"] = lambda: srsly.json_dumps(self.meta) <ide> serializers["config.cfg"] = lambda: self.config.to_bytes() <del> for name, proc in self.components: <add> for name, proc in self._components: <ide> if name in exclude: <ide> continue <ide> if not hasattr(proc, "to_bytes"): <ide> def to_bytes(self, *, exclude: Iterable[str] = tuple()) -> bytes: <ide> return util.to_bytes(serializers, exclude) <ide> <ide> def from_bytes( <del> self, bytes_data: bytes, *, exclude: Iterable[str] = tuple() <add> self, bytes_data: bytes, *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> "Language": <ide> """Load state from a binary string. <ide> <ide> def deserialize_meta(b): <ide> deserializers["tokenizer"] = lambda b: self.tokenizer.from_bytes( <ide> b, exclude=["vocab"] <ide> ) <del> for name, proc in self.components: <add> for name, proc in self._components: <ide> if name in exclude: <ide> continue <ide> if not hasattr(proc, "from_bytes"): <ide><path>spacy/pipeline/attributeruler.py <ide> from ..tokens import Doc, Span <ide> from ..tokens._retokenize import normalize_token_attrs, set_token_attrs <ide> from ..vocab import Vocab <add>from ..util import SimpleFrozenList <ide> from .. import util <ide> <ide> <ide> def score(self, examples, **kwargs): <ide> results.update(Scorer.score_token_attr(examples, "lemma", **kwargs)) <ide> return results <ide> <del> def to_bytes(self, exclude: Iterable[str] = tuple()) -> bytes: <add> def to_bytes(self, exclude: Iterable[str] = SimpleFrozenList()) -> bytes: <ide> """Serialize the AttributeRuler to a bytestring. <ide> <ide> exclude (Iterable[str]): String names of serialization fields to exclude. <ide> def to_bytes(self, exclude: Iterable[str] = tuple()) -> bytes: <ide> serialize["indices"] = lambda: srsly.msgpack_dumps(self.indices) <ide> return util.to_bytes(serialize, exclude) <ide> <del> def from_bytes(self, bytes_data: bytes, exclude: Iterable[str] = tuple()): <add> def from_bytes( <add> self, bytes_data: bytes, exclude: Iterable[str] = SimpleFrozenList() <add> ): <ide> """Load the AttributeRuler from a bytestring. <ide> <ide> bytes_data (bytes): The data to load. <ide> def load_indices(b): <ide> <ide> return self <ide> <del> def to_disk(self, path: Union[Path, str], exclude: Iterable[str] = tuple()) -> None: <add> def to_disk( <add> self, path: Union[Path, str], exclude: Iterable[str] = SimpleFrozenList() <add> ) -> None: <ide> """Serialize the AttributeRuler to disk. <ide> <ide> path (Union[Path, str]): A path to a directory. <ide> def to_disk(self, path: Union[Path, str], exclude: Iterable[str] = tuple()) -> N <ide> util.to_disk(path, serialize, exclude) <ide> <ide> def from_disk( <del> self, path: Union[Path, str], exclude: Iterable[str] = tuple() <add> self, path: Union[Path, str], exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> None: <ide> """Load the AttributeRuler from disk. <ide> <ide><path>spacy/pipeline/entity_linker.py <ide> from ..vocab import Vocab <ide> from ..gold import Example, validate_examples <ide> from ..errors import Errors, Warnings <add>from ..util import SimpleFrozenList <ide> from .. import util <ide> <ide> <ide> def set_annotations(self, docs: Iterable[Doc], kb_ids: List[str]) -> None: <ide> token.ent_kb_id_ = kb_id <ide> <ide> def to_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList(), <ide> ) -> None: <ide> """Serialize the pipe to disk. <ide> <ide> def to_disk( <ide> util.to_disk(path, serialize, exclude) <ide> <ide> def from_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList(), <ide> ) -> "EntityLinker": <ide> """Load the pipe from disk. Modifies the object in place and returns it. <ide> <ide><path>spacy/pipeline/entityruler.py <ide> <ide> from ..language import Language <ide> from ..errors import Errors <del>from ..util import ensure_path, to_disk, from_disk <add>from ..util import ensure_path, to_disk, from_disk, SimpleFrozenList <ide> from ..tokens import Doc, Span <ide> from ..matcher import Matcher, PhraseMatcher <ide> from ..scorer import Scorer <ide> def score(self, examples, **kwargs): <ide> return Scorer.score_spans(examples, "ents", **kwargs) <ide> <ide> def from_bytes( <del> self, patterns_bytes: bytes, *, exclude: Iterable[str] = tuple() <add> self, patterns_bytes: bytes, *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> "EntityRuler": <ide> """Load the entity ruler from a bytestring. <ide> <ide> def from_bytes( <ide> self.add_patterns(cfg) <ide> return self <ide> <del> def to_bytes(self, *, exclude: Iterable[str] = tuple()) -> bytes: <add> def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes: <ide> """Serialize the entity ruler patterns to a bytestring. <ide> <ide> RETURNS (bytes): The serialized patterns. <ide> def to_bytes(self, *, exclude: Iterable[str] = tuple()) -> bytes: <ide> return srsly.msgpack_dumps(serial) <ide> <ide> def from_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> "EntityRuler": <ide> """Load the entity ruler from a file. Expects a file containing <ide> newline-delimited JSON (JSONL) with one entry per line. <ide> def from_disk( <ide> return self <ide> <ide> def to_disk( <del> self, path: Union[str, Path], *, exclude: Iterable[str] = tuple() <add> self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList() <ide> ) -> None: <ide> """Save the entity ruler patterns to a directory. The patterns will be <ide> saved as newline-delimited JSON (JSONL). <ide><path>spacy/scorer.py <del>from typing import Optional, Iterable, Dict, Any, Callable, Tuple, TYPE_CHECKING <add>from typing import Optional, Iterable, Dict, Any, Callable, TYPE_CHECKING <ide> import numpy as np <ide> <ide> from .gold import Example <ide> from .tokens import Token, Doc, Span <ide> from .errors import Errors <del>from .util import get_lang_class <add>from .util import get_lang_class, SimpleFrozenList <ide> from .morphology import Morphology <ide> <ide> if TYPE_CHECKING: <ide> def score_cats( <ide> attr: str, <ide> *, <ide> getter: Callable[[Doc, str], Any] = getattr, <del> labels: Iterable[str] = tuple(), <add> labels: Iterable[str] = SimpleFrozenList(), <ide> multi_label: bool = True, <ide> positive_label: Optional[str] = None, <ide> threshold: Optional[float] = None, <ide> def score_deps( <ide> getter: Callable[[Token, str], Any] = getattr, <ide> head_attr: str = "head", <ide> head_getter: Callable[[Token, str], Token] = getattr, <del> ignore_labels: Tuple[str] = tuple(), <add> ignore_labels: Iterable[str] = SimpleFrozenList(), <ide> **cfg, <ide> ) -> Dict[str, Any]: <ide> """Returns the UAS, LAS, and LAS per type scores for dependency <ide><path>spacy/tests/pipeline/test_pipe_methods.py <ide> import pytest <ide> from spacy.language import Language <add>from spacy.util import SimpleFrozenList <ide> <ide> <ide> @pytest.fixture <ide> def component(doc): <ide> assert nlp.config["nlp"]["disabled"] == [name] <ide> nlp("?") <ide> assert results[f"{name}1"] == "!" <add> <add> <add>def test_pipe_methods_frozen(): <add> """Test that spaCy raises custom error messages if "frozen" properties are <add> accessed. We still want to use a list here to not break backwards <add> compatibility, but users should see an error if they're trying to append <add> to nlp.pipeline etc.""" <add> nlp = Language() <add> ner = nlp.add_pipe("ner") <add> assert nlp.pipe_names == ["ner"] <add> for prop in [ <add> nlp.pipeline, <add> nlp.pipe_names, <add> nlp.components, <add> nlp.component_names, <add> nlp.disabled, <add> nlp.factory_names, <add> ]: <add> assert isinstance(prop, list) <add> assert isinstance(prop, SimpleFrozenList) <add> with pytest.raises(NotImplementedError): <add> nlp.pipeline.append(("ner2", ner)) <add> with pytest.raises(NotImplementedError): <add> nlp.pipe_names.pop() <add> with pytest.raises(NotImplementedError): <add> nlp.components.sort() <add> with pytest.raises(NotImplementedError): <add> nlp.component_names.clear() <ide><path>spacy/tests/test_util.py <ide> from .util import get_random_doc <ide> <ide> from spacy import util <del>from spacy.util import dot_to_object <add>from spacy.util import dot_to_object, SimpleFrozenList <ide> from thinc.api import Config, Optimizer <ide> from spacy.gold.batchers import minibatch_by_words <del> <ide> from ..lang.en import English <ide> from ..lang.nl import Dutch <ide> from ..language import DEFAULT_CONFIG_PATH <ide> def test_util_dot_section(): <ide> assert not dot_to_object(en_config, "nlp.load_vocab_data") <ide> assert dot_to_object(nl_config, "nlp.load_vocab_data") <ide> assert isinstance(dot_to_object(nl_config, "training.optimizer"), Optimizer) <add> <add> <add>def test_simple_frozen_list(): <add> t = SimpleFrozenList(["foo", "bar"]) <add> assert t == ["foo", "bar"] <add> assert t.index("bar") == 1 # okay method <add> with pytest.raises(NotImplementedError): <add> t.append("baz") <add> with pytest.raises(NotImplementedError): <add> t.sort() <add> with pytest.raises(NotImplementedError): <add> t.extend(["baz"]) <add> with pytest.raises(NotImplementedError): <add> t.pop() <add> t = SimpleFrozenList(["foo", "bar"], error="Error!") <add> with pytest.raises(NotImplementedError): <add> t.append("baz") <ide><path>spacy/tokens/_serialize.py <ide> from ..compat import copy_reg <ide> from ..attrs import SPACY, ORTH, intify_attr <ide> from ..errors import Errors <del>from ..util import ensure_path <add>from ..util import ensure_path, SimpleFrozenList <ide> <ide> # fmt: off <ide> ALL_ATTRS = ("ORTH", "TAG", "HEAD", "DEP", "ENT_IOB", "ENT_TYPE", "ENT_KB_ID", "LEMMA", "MORPH", "POS") <ide> def __init__( <ide> self, <ide> attrs: Iterable[str] = ALL_ATTRS, <ide> store_user_data: bool = False, <del> docs: Iterable[Doc] = tuple(), <add> docs: Iterable[Doc] = SimpleFrozenList(), <ide> ) -> None: <ide> """Create a DocBin object to hold serialized annotations. <ide> <ide><path>spacy/util.py <ide> def update(self, other): <ide> raise NotImplementedError(self.error) <ide> <ide> <add>class SimpleFrozenList(list): <add> """Wrapper class around a list that lets us raise custom errors if certain <add> attributes/methods are accessed. Mostly used for properties like <add> Language.pipeline that return an immutable list (and that we don't want to <add> convert to a tuple to not break too much backwards compatibility). If a user <add> accidentally calls nlp.pipeline.append(), we can raise a more helpful error. <add> """ <add> <add> def __init__(self, *args, error: str = Errors.E927) -> None: <add> """Initialize the frozen list. <add> <add> error (str): The error message when user tries to mutate the list. <add> """ <add> self.error = error <add> super().__init__(*args) <add> <add> def append(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def clear(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def extend(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def insert(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def pop(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def remove(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def reverse(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> def sort(self, *args, **kwargs): <add> raise NotImplementedError(self.error) <add> <add> <ide> def lang_class_is_loaded(lang: str) -> bool: <ide> """Check whether a Language class is already loaded. Language classes are <ide> loaded lazily, to avoid expensive setup code associated with the language <ide> def load_model( <ide> name: Union[str, Path], <ide> *, <ide> vocab: Union["Vocab", bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(), <ide> ) -> "Language": <ide> """Load a model from a package or data path. <ide> def load_model_from_package( <ide> name: str, <ide> *, <ide> vocab: Union["Vocab", bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(), <ide> ) -> "Language": <ide> """Load a model from an installed package. <ide> def load_model_from_path( <ide> *, <ide> meta: Optional[Dict[str, Any]] = None, <ide> vocab: Union["Vocab", bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(), <ide> ) -> "Language": <ide> """Load a model from a data directory path. Creates Language class with <ide> def load_model_from_config( <ide> config: Union[Dict[str, Any], Config], <ide> *, <ide> vocab: Union["Vocab", bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> auto_fill: bool = False, <ide> validate: bool = True, <ide> ) -> Tuple["Language", Config]: <ide> def load_model_from_init_py( <ide> init_file: Union[Path, str], <ide> *, <ide> vocab: Union["Vocab", bool] = True, <del> disable: Iterable[str] = tuple(), <del> exclude: Iterable[str] = tuple(), <add> disable: Iterable[str] = SimpleFrozenList(), <add> exclude: Iterable[str] = SimpleFrozenList(), <ide> config: Union[Dict[str, Any], Config] = SimpleFrozenDict(), <ide> ) -> "Language": <ide> """Helper function to use in the `load()` method of a model package's
13
Python
Python
add __wrapped__ for python 2 support
1b8996e9477f38c8ced522c85df9ab9d73fcd339
<ide><path>numpy/core/overrides.py <ide> def public_api(*args, **kwargs): <ide> relevant_args = dispatcher(*args, **kwargs) <ide> return array_function_implementation_or_override( <ide> implementation, public_api, relevant_args, args, kwargs) <add> <add> # TODO: remove this when we drop Python 2 support (functools.wraps <add> # adds __wrapped__ automatically in later versions) <add> public_api.__wrapped__ = implementation <add> <ide> return public_api <ide> <ide> return decorator
1
Ruby
Ruby
restore deprecation require in dbconsole command
bcb63fcaa89a17c3f8c65680b4e21134cebaf843
<ide><path>railties/lib/rails/commands/dbconsole/dbconsole_command.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/string/filters" <add>require "active_support/deprecation" <ide> require "rails/command/environment_argument" <ide> <ide> module Rails
1
Javascript
Javascript
improve implementation accordingly to pr reviews
233aa3edf3e0991aafe5dbc2b548993b4bf407ea
<ide><path>examples/js/loaders/GLTFLoader.js <ide> THREE.GLTFLoader = ( function () { <ide> <ide> function createMultiPassGeometryKey( geometry, primitives ) { <ide> <del> var key = createPrimitiveKey( geometry ); <add> var key = geometry.uuid; <ide> <ide> for ( var i = 0, il = primitives.length; i < il; i ++ ) { <ide> <del> key += i + primitives[ i ].uuid; <add> key += i + createPrimitiveKey( primitives[ i ].uuid ); <ide> <ide> } <ide>
1
Ruby
Ruby
skip some flaky tests for now."
5baf16f50e71cd8224dad58350e67fceb56942a1
<ide><path>Library/Homebrew/test/uninstall_test.rb <ide> def handle_unsatisfied_dependents <ide> end <ide> <ide> def test_check_for_testball_f2s_when_developer <del> skip "Flaky test" <ide> assert_match "Warning", handle_unsatisfied_dependents <ide> refute_predicate Homebrew, :failed? <ide> end <ide> <ide> def test_check_for_dependents_when_not_developer <del> skip "Flaky test" <ide> run_as_not_developer do <ide> assert_match "Error", handle_unsatisfied_dependents <ide> assert_predicate Homebrew, :failed?
1
Ruby
Ruby
write untapped setting only on manual untap
ecfad29347d9e58b9499144cab0a539d9e863ce9
<ide><path>Library/Homebrew/cmd/untap.rb <ide> def untap <ide> end <ide> end <ide> <del> tap.uninstall <add> tap.uninstall manual: true <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/tap.rb <ide> def link_completions_and_manpages <ide> end <ide> <ide> # Uninstall this {Tap}. <del> def uninstall <add> def uninstall(manual: false) <ide> require "descriptions" <ide> raise TapUnavailableError, name unless installed? <ide> <ide> def uninstall <ide> Commands.rebuild_commands_completion_list <ide> clear_cache <ide> <del> return unless official? <add> return if !manual || !official? <ide> <ide> untapped = self.class.untapped_official_taps <ide> return if untapped.include? name
2
Java
Java
fix failing tests
aea3a750189977ca231172db87408f03979bace6
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java <ide> public int getBufferSize() { <ide> @Override <ide> public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException { <ide> <add> // Start async before Read/WriteListener registration <add> AsyncContext asyncContext = servletRequest.startAsync(); <add> <ide> ServletServerHttpRequest request = new ServletServerHttpRequest( <ide> ((HttpServletRequest) servletRequest), getDataBufferFactory(), getBufferSize()); <ide> ServletServerHttpResponse response = new ServletServerHttpResponse( <ide> ((HttpServletResponse) servletResponse), getDataBufferFactory(), getBufferSize()); <ide> <del> AsyncContext asyncContext = servletRequest.startAsync(); <ide> asyncContext.addListener(new EventHandlingAsyncListener(request, response)); <ide> <ide> HandlerResultSubscriber resultSubscriber = new HandlerResultSubscriber(asyncContext);
1
Text
Text
correct the wrong added meta data
667f8c642d35da18493ab7cd397070c7bd0fbf84
<ide><path>doc/api/async_hooks.md <ide> function promiseResolve(asyncId) { } <ide> #### `async_hooks.createHook(callbacks)` <ide> <ide> <!-- YAML <del>added: v9.0.0 <add>added: v8.1.0 <ide> --> <ide> <ide> * `callbacks` {Object} The [Hook Callbacks][] to register <ide><path>doc/api/fs.md <ide> argument to `fs.createReadStream()`. If `path` is passed as a string, then <ide> <!-- YAML <ide> added: v0.1.21 <ide> changes: <del> - version: v9.0.0 <add> - version: v8.1.0 <ide> pr-url: https://github.com/nodejs/node/pull/13173 <ide> description: Added times as numbers. <ide> --> <ide><path>doc/api/http.md <ide> socket/stream from this function, or by passing the socket/stream to `callback`. <ide> <ide> ### agent.keepSocketAlive(socket) <ide> <!-- YAML <del>added: v9.0.0 <add>added: v8.1.0 <ide> --> <ide> <ide> * `socket` {net.Socket} <ide> it for use with the next request. <ide> <ide> ### agent.reuseSocket(socket, request) <ide> <!-- YAML <del>added: v9.0.0 <add>added: v8.1.0 <ide> --> <ide> <ide> * `socket` {net.Socket} <ide><path>doc/api/zlib.md <ide> class of the compressor/decompressor classes. <ide> <ide> ### zlib.bytesRead <ide> <!-- YAML <del>added: v9.0.0 <add>added: v8.1.0 <ide> --> <ide> <ide> * {number}
4
Javascript
Javascript
return correct contents when no config present
9282f07d070aa8cc68a76c523bf59c0220a4ff34
<ide><path>src/main-process/parse-command-line.js <ide> function readProjectSpecificationSync (filepath, executedFrom) { <ide> if (contents.paths == null) { <ide> contents.paths = [path.dirname(filepath)] <ide> } <del> return (contents.config == null) ? {} : contents <add> contents.config = (contents.config == null) ? {} : contents.config <add> return contents <ide> } <ide> <ide> function normalizeDriveLetterName (filePath) {
1
Javascript
Javascript
use full url for typedocs
5cf054ef257ce28407ae5c13bcc0b5f8c0199c80
<ide><path>docs/docusaurus.config.js <add>/* eslint-disable import/no-commonjs */ <ide> // VERSION replaced by deploy script <ide> module.exports = { <del> title: 'Chart.js', <del> tagline: 'Open source HTML5 Charts for your website', <del> url: 'https://chartjs.org', <del> baseUrl: '/docs/VERSION/', <del> favicon: 'img/favicon.ico', <del> organizationName: 'chartjs', // Usually your GitHub org/user name. <del> projectName: 'chartjs.github.io', // Usually your repo name. <del> plugins: ['@docusaurus/plugin-google-analytics'], <del> scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'], <del> themes: ['@docusaurus/theme-live-codeblock'], <del> themeConfig: { <del> algolia: { <del> apiKey: 'd7ee00a3cbaaf3c33e28ad1c274e7ba6', <del> indexName: 'chartjs', <del> algoliaOptions: { <del> facetFilters: [`version:VERSION`], <del> } <del> }, <del> googleAnalytics: { <del> trackingID: 'UA-28909194-3', <del> // Optional fields. <del> anonymizeIP: true, // Should IPs be anonymized? <del> }, <del> disableDarkMode: true, // Would need to implement for Charts embedded in docs <del> navbar: { <del> title: 'Chart.js', <del> logo: { <del> alt: 'Chart.js Logo', <del> src: 'img/logo.svg', <del> }, <del> }, <del> footer: { <del> style: 'dark', <del> links: [ <del> { <del> title: 'Other Docs', <del> items: [ <del> { <del> label: 'Samples', <del> href: 'https://www.chartjs.org/samples/VERSION/', <del> }, <del> { <del> label: 'v2 Docs', <del> href: 'https://www.chartjs.org/docs/2.9.3/', <del> }, <del> ], <del> }, <del> { <del> title: 'Community', <del> items: [ <del> { <del> label: 'Slack', <del> href: 'https://chartjs-slack.herokuapp.com/', <del> }, <del> { <del> label: 'Stack Overflow', <del> href: 'https://stackoverflow.com/questions/tagged/chart.js', <del> }, <del> ], <del> }, <del> { <del> title: 'Developers', <del> items: [ <del> { <del> label: 'GitHub', <del> href: 'https://github.com/chartjs/Chart.js', <del> }, <del> { <del> label: 'Contributing', <del> to: 'developers/contributing', <del> }, <del> ], <del> }, <del> ], <del> copyright: `Copyright © ${new Date().getFullYear()} Chart.js contributors.`, <del> }, <del> }, <del> presets: [ <del> [ <del> '@docusaurus/preset-classic', <del> { <del> docs: { <del> sidebarPath: require.resolve('./sidebars.js'), <del> routeBasePath: '', <del> editUrl: <del> 'https://github.com/chartjs/Chart.js/edit/master/docs/', <del> }, <del> theme: { <del> customCss: require.resolve('./src/css/custom.css'), <del> }, <del> }, <del> ], <del> ], <add> title: 'Chart.js', <add> tagline: 'Open source HTML5 Charts for your website', <add> url: 'https://chartjs.org', <add> baseUrl: '/docs/VERSION/', <add> favicon: 'img/favicon.ico', <add> organizationName: 'chartjs', // Usually your GitHub org/user name. <add> projectName: 'chartjs.github.io', // Usually your repo name. <add> plugins: ['@docusaurus/plugin-google-analytics'], <add> scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'], <add> themes: ['@docusaurus/theme-live-codeblock'], <add> themeConfig: { <add> algolia: { <add> apiKey: 'd7ee00a3cbaaf3c33e28ad1c274e7ba6', <add> indexName: 'chartjs', <add> algoliaOptions: { <add> facetFilters: ['version:VERSION'], <add> } <add> }, <add> googleAnalytics: { <add> trackingID: 'UA-28909194-3', <add> // Optional fields. <add> anonymizeIP: true, // Should IPs be anonymized? <add> }, <add> disableDarkMode: true, // Would need to implement for Charts embedded in docs <add> navbar: { <add> title: 'Chart.js', <add> logo: { <add> alt: 'Chart.js Logo', <add> src: 'img/logo.svg', <add> }, <add> }, <add> footer: { <add> style: 'dark', <add> links: [ <add> { <add> title: 'Other Docs', <add> items: [ <add> { <add> label: 'Samples', <add> href: 'https://www.chartjs.org/samples/VERSION/', <add> }, <add> { <add> label: 'v2 Docs', <add> href: 'https://www.chartjs.org/docs/2.9.3/', <add> }, <add> ], <add> }, <add> { <add> title: 'Community', <add> items: [ <add> { <add> label: 'Slack', <add> href: 'https://chartjs-slack.herokuapp.com/', <add> }, <add> { <add> label: 'Stack Overflow', <add> href: 'https://stackoverflow.com/questions/tagged/chart.js', <add> }, <add> ], <add> }, <add> { <add> title: 'Developers', <add> items: [ <add> { <add> label: 'GitHub', <add> href: 'https://github.com/chartjs/Chart.js', <add> }, <add> { <add> label: 'Contributing', <add> to: 'developers/contributing', <add> }, <add> ], <add> }, <add> ], <add> copyright: `Copyright © ${new Date().getFullYear()} Chart.js contributors.`, <add> }, <add> }, <add> presets: [ <add> [ <add> '@docusaurus/preset-classic', <add> { <add> docs: { <add> sidebarPath: require.resolve('./sidebars.js'), <add> routeBasePath: '', <add> editUrl: 'https://github.com/chartjs/Chart.js/edit/master/docs/', <add> }, <add> theme: { <add> customCss: require.resolve('./src/css/custom.css'), <add> }, <add> }, <add> ], <add> ], <ide> }; <ide><path>docs/sidebars.js <add>const pkg = require('../package.json'); <add>const docsVersion = pkg.version.indexOf('-') > -1 ? 'next' : 'latest'; <add> <ide> module.exports = { <del> someSidebar: { <del> Introduction: ['index'], <del> 'Getting Started': [ <del> 'getting-started/index', <del> 'getting-started/installation', <del> 'getting-started/integration', <del> 'getting-started/usage', <del> 'getting-started/v3-migration' <del> ], <del> General: [ <del> 'general/data-structures', <del> 'general/accessibility', <del> 'general/responsive', <del> 'general/device-pixel-ratio', <del> {Interactions: ['general/interactions/index', 'general/interactions/events', 'general/interactions/modes']}, <del> 'general/options', <del> 'general/colors', <del> 'general/fonts', <del> 'general/performance' <del> ], <del> Configuration: [ <del> 'configuration/index', <del> 'configuration/animations', <del> 'configuration/layout', <del> 'configuration/legend', <del> 'configuration/title', <del> 'configuration/tooltip', <del> 'configuration/elements' <del> ], <del> 'Chart Types': [ <del> 'charts/line', <del> 'charts/bar', <del> 'charts/radar', <del> 'charts/doughnut', <del> 'charts/polar', <del> 'charts/bubble', <del> 'charts/scatter', <del> 'charts/area', <del> 'charts/mixed' <del> ], <del> Axes:[ <del> 'axes/index', <del> { Cartesian: [ <del> 'axes/cartesian/index', <del> 'axes/cartesian/category', <del> 'axes/cartesian/linear', <del> 'axes/cartesian/logarithmic', <del> 'axes/cartesian/time' <del> ]}, <del> { Radial: [ <del> 'axes/radial/index', <del> 'axes/radial/linear' <del> ]}, <del> 'axes/labelling', <del> 'axes/styling' <del> ], <del> Developers: [ <del> 'developers/index', <del> 'developers/api', <del> { <del> type: 'link', <del> label: 'TypeDoc', <del> href: 'typedoc/index.html' <del> }, <del> 'developers/updates', <del> 'developers/plugins', <del> 'developers/charts', <del> 'developers/axes', <del> 'developers/contributing' <del> ], <del> 'Additional Notes':[ <del> 'notes/comparison', <del> { <del> type: 'link', <del> label: 'Extensions', <del> href: 'https://github.com/chartjs/awesome' <del> }, <del> 'notes/license' <del> ] <del> }, <add> someSidebar: { <add> Introduction: ['index'], <add> 'Getting Started': [ <add> 'getting-started/index', <add> 'getting-started/installation', <add> 'getting-started/integration', <add> 'getting-started/usage', <add> 'getting-started/v3-migration' <add> ], <add> General: [ <add> 'general/data-structures', <add> 'general/accessibility', <add> 'general/responsive', <add> 'general/device-pixel-ratio', <add> {Interactions: ['general/interactions/index', 'general/interactions/events', 'general/interactions/modes']}, <add> 'general/options', <add> 'general/colors', <add> 'general/fonts', <add> 'general/performance' <add> ], <add> Configuration: [ <add> 'configuration/index', <add> 'configuration/animations', <add> 'configuration/layout', <add> 'configuration/legend', <add> 'configuration/title', <add> 'configuration/tooltip', <add> 'configuration/elements' <add> ], <add> 'Chart Types': [ <add> 'charts/line', <add> 'charts/bar', <add> 'charts/radar', <add> 'charts/doughnut', <add> 'charts/polar', <add> 'charts/bubble', <add> 'charts/scatter', <add> 'charts/area', <add> 'charts/mixed' <add> ], <add> Axes: [ <add> 'axes/index', <add> {Cartesian: [ <add> 'axes/cartesian/index', <add> 'axes/cartesian/category', <add> 'axes/cartesian/linear', <add> 'axes/cartesian/logarithmic', <add> 'axes/cartesian/time' <add> ]}, <add> {Radial: [ <add> 'axes/radial/index', <add> 'axes/radial/linear' <add> ]}, <add> 'axes/labelling', <add> 'axes/styling' <add> ], <add> Developers: [ <add> 'developers/index', <add> 'developers/api', <add> { <add> type: 'link', <add> label: 'TypeDoc', <add> href: 'https://chartjs.org/docs/' + docsVersion + '/typedoc/' <add> }, <add> 'developers/updates', <add> 'developers/plugins', <add> 'developers/charts', <add> 'developers/axes', <add> 'developers/contributing' <add> ], <add> 'Additional Notes': [ <add> 'notes/comparison', <add> { <add> type: 'link', <add> label: 'Extensions', <add> href: 'https://github.com/chartjs/awesome' <add> }, <add> 'notes/license' <add> ] <add> }, <ide> };
2
Python
Python
fix precomputed layer
b10173655589b038ba1e69e937eddf03819dc94d
<ide><path>spacy/_ml.py <ide> def _preprocess_doc(docs, drop=0.): <ide> nF=Dimension("Number of features"), <ide> nO=Dimension("Output size"), <ide> W=Synapses("Weights matrix", <del> lambda obj: (obj.nI, obj.nF, obj.nO)), <add> lambda obj: (obj.nF, obj.nO, obj.nI)), <ide> b=Biases("Bias vector", <ide> lambda obj: (obj.nO,)), <ide> d_W=Gradient("W"), <ide> def __init__(self, nO=None, nI=None, nF=None, **kwargs): <ide> self.nI = nI <ide> self.nF = nF <ide> <del> @property <del> def nFI(self): <del> return self.nI * self.nF <add> def begin_update(self, X, drop=0.): <add> tensordot = self.ops.xp.tensordot <add> ascontiguous = self.ops.xp.ascontiguousarray <ide> <del> @property <del> def nFO(self): <del> return self.nF * self.nO <add> Yf = tensordot(X, self.W, axes=[[1], [2]]) <ide> <del> def begin_update(self, X, drop=0.): <del> nN = X.shape[0] <del> # X: (b, i) <del> # Xf: (b, f, i) <del> # Yf: (b, f, o) <del> # dY: (b, o) <del> # dYf: (b, f, o) <del> # W: (i, f, o) <del> W = self.W.reshape((self.nI, self.nFO)) <del> Yf = self.ops.xp.dot(X, W) <del> Yf = Yf.reshape((Yf.shape[0], self.nF, self.nO)) <del> #Yf = einsum('ab,bc->ac', X, W) <ide> def backward(dY_ids, sgd=None): <ide> dY, ids = dY_ids <ide> Xf = X[ids] <del> # bo,fi_o->b_if -> b_fi <del> W_o_fi = self._transpose(self.W, shape=(self.nO, self.nFI)) <del> dXf = self.ops.xp.dot(dY, W_o_fi).reshape((Xf.shape[0], self.nF, self.nI)) <del> # bo,b_fi->o_fi <del> dW = Xf.reshape((Xf.shape[0], self.nFI)) <del> dW = self.ops.xp.dot(Xf.T, dY) <del> dW = dW.reshape((self.nO, self.nF, self.nI)) <del> self.d_W += dW.transpose((2, 1, 0)) <add> <add> dXf = tensordot(dY, self.W, axes=[[1], [1]]) <add> dW = tensordot(dY, Xf, axes=[[0], [0]]) <add> <add> self.d_W += dW.transpose((1, 0, 2)) <ide> self.d_b += dY.sum(axis=0) <ide> <ide> if sgd is not None: <ide> sgd(self._mem.weights, self._mem.gradient, key=self.id) <ide> return dXf <ide> return Yf, backward <ide> <del> def _transpose(self, weights, shape): <del> weights = weights.transpose((2, 1, 0)) <del> weights = self.ops.xp.ascontiguousarray(weights) <del> return weights.reshape(shape) <del> <ide> @staticmethod <ide> def init_weights(model): <ide> '''This is like the 'layer sequential unit variance', but instead <ide> def init_weights(model): <ide> ''' <ide> if (model.W**2).sum() != 0.: <ide> return <del> model.ops.normal_init(model.W, model.nFI, inplace=True) <add> model.ops.normal_init(model.W, model.nF * model.nI, inplace=True) <ide> <ide> ids = numpy.zeros((5000, model.nF), dtype='i') <ide> ids += numpy.asarray(numpy.random.uniform(0, 1000, ids.shape), dtype='i')
1
Ruby
Ruby
use map! instead of replace + map
808592bae2b83ced018f16d576d41a0059ed302a
<ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb <ide> def convert_value(value) <ide> value.nested_under_indifferent_access <ide> elsif value.is_a?(Array) <ide> value = value.dup if value.frozen? <del> value.replace(value.map { |e| convert_value(e) }) <add> value.map! { |e| convert_value(e) } <ide> else <ide> value <ide> end
1
Javascript
Javascript
adjust verbiage and time contibuted
21b09b53cbfd475cfb31f50b3cb0cecc7519b79a
<ide><path>client/src/components/Donation/components/DonateForm.js <ide> class DonateForm extends Component { <ide> : this.amounts[durationSelected][0]; <ide> } <ide> <del> convertToTimeContributed(amount) { <del> return `${numToCommas((amount / 100) * 50 * 60)} minutes`; <add> convertToTimeContributed(amount, duration) { <add> const timeContributed = <add> duration === 'month' <add> ? Math.round(((amount / 100) * 50) / 12) <add> : (amount / 100) * 50; <add> return `${numToCommas(timeContributed)} hours`; <ide> } <ide> <ide> getFormatedAmountLabel(amount) { <ide> class DonateForm extends Component { <ide> {`Your `} <ide> {this.getFormatedAmountLabel(donationAmount)} <ide> {` donation will provide `} <del> {this.convertToTimeContributed(donationAmount)} <del> {` of learning to people around the world `} <del> {duration === 'one-time' ? `for one ` : `each `} <del> {duration === 'monthly' ? `month.` : `year.`} <add> {this.convertToTimeContributed(donationAmount, duration)} <add> {` of learning to people around the world`} <add> {duration === 'onetime' ? `.` : ` each ${duration}.`} <ide> </p> <ide> </div> <ide> </Tab> <ide><path>client/src/components/Donation/components/DonateText.js <ide> const DonateText = () => { <ide> <Col sm={10} smOffset={1} xs={12}> <ide> <p>freeCodeCamp is a highly efficient education nonprofit.</p> <ide> <p> <del> In 2019 alone, we provided 1,100,000,000 minutes of free education to <add> In 2019 alone, we provided 18 million hours of free education to <ide> people around the world. <ide> </p> <ide> <p>
2
Text
Text
use markdown syntax instead of html on exercises
49992889124b2585f0e4ae1178cc2b5147a0e800
<ide><path>client/src/pages/learn/coding-interview-prep/algorithms/index.md <ide> In most of the coding interviews, foundation mostly means a clear understanding <ide> This course presents you with the most frequently asked questions during interviews to prepare you with a basic understanding of algorithms. <ide> It will provide clear and concise explanations and implementations of different algorithms. <ide> <del># Prerequisite: All of the algorithmic questions require the solutions are written in JavaScript. It is a good idea to complete the JavaScript course first. <add>**Prerequisite: All of the algorithmic questions require the solutions are written in JavaScript. It is a good idea to complete the JavaScript course first** <ide> <ide> It is good practice to use a whiteboard or notepad to implement and practice interview questions, since most coding interviews may limit you to these tools when writing the code. So forget your nice IDEs and debuggers and start getting your hands dirty! <ide> <del># Best of Luck !! <add>**Best of Luck !!** <ide><path>client/src/pages/learn/front-end-libraries/bootstrap/index.md <ide> superBlock: Front End Libraries <ide> ## Introduction to the Bootstrap Challenges <ide> <ide> Bootstrap is a front-end framework used to design responsive web pages and web applications. It takes a mobile-first approach to web development. Bootstrap includes pre-built CSS styles and classes, plus some JavaScript functionality. <del>Bootstrap uses a responsive 12 column grid layout and has design templates for:<br><br><ul><li>buttons</li><li>images</li><li>tables</li><li>forms</li><li>navigation</li></ul><br>To know more about it and how to include Bootstrap in your projects visit [Bootstrap](https://getbootstrap.com/docs/4.1/getting-started/introduction/)<br>This section introduces some of the ways to use Bootstrap in your web projects. <add>Bootstrap uses a responsive 12 column grid layout and has design templates for: <ide> <add>- buttons <add>- images <add>- tables <add>- forms <add>- navigation <add> <add>To know more about it and how to include Bootstrap in your projects visit [Bootstrap](https://getbootstrap.com/docs/4.1/getting-started/introduction/) <add> <add>This section introduces some of the ways to use Bootstrap in your web projects. <ide><path>client/src/pages/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/index.md <ide> superBlock: JavaScript Algorithms and Data Structures <ide> --- <ide> ## Introduction to Basic Algorithm Scripting <ide> <del>A computer algorithm is a sequence of steps that is followed to achieve a particular outcome. To write an algorithm, you must first understand a problem, and then solve it with coding. <add>A computer algorithm is a sequence of steps that is followed to achieve a particular outcome. To write an algorithm, you must first understand a problem, and then solve it with coding. <ide> <ide> To make solving problems easier, it can be helpful to break them down into many chunks. Then, each chunk can be solved one by one. For example, if you are building a calculator, don't try to solve the problem as a whole. First, consider how to get inputs. Then, determine each arithmetic operation one by one. Finally, display the results. <ide> <del>In this section we will learn to solve basic algorithm problems using JavaScript. This will help you improve your problem solving skills and prepare you to later solve more complex problems. <add>In this section we will learn to solve basic algorithm problems using JavaScript. This will help you improve your problem solving skills and prepare you to later solve more complex problems. <ide> <del>#### Hint <del>If you get stuck, try using `console.log()` to log variable values to the console. This will help to debug problems. <add>**Hint**: If you get stuck, try using `console.log()` to log variable values to the console. This will help to debug problems. <ide><path>client/src/pages/learn/javascript-algorithms-and-data-structures/es6/index.md <ide> superBlock: JavaScript Algorithms and Data Structures <ide> --- <ide> ## Introduction to the ES6 Challenges <ide> <del>ECMAScript is a standardized version of JavaScript with the goal of unifying the language's specifications and features. As all major browsers and JavaScript-runtimes follow this specification, the term <i>ECMAScript</i> is interchangeable with the term <i>JavaScript</i>.<br><br>Most of the challenges on freeCodeCamp use the ECMAScript 5 (ES5) specification of the language, finalized in 2009. But JavaScript is an evolving programming language. As features are added and revisions are made, new versions of the language are released for use by developers.<br><br>The most recent standardized version is called ECMAScript 6 (ES6), released in 2015. This new version of the language adds some powerful features that will be covered in this section of challenges, including:<br><br><ul><li>Arrow functions</li><li>Classes</li><li>Modules</li><li>Promises</li><li>Generators</li><li><code>let</code> and <code>const</code></li></ul><br><br><strong>Note</strong><br>Not all browsers support ES6 features. If you use ES6 in your own projects, you may need to use a program (transpiler) to convert your ES6 code into ES5 until browsers support ES6. <add>ECMAScript is a standardized version of JavaScript with the goal of unifying the language's specifications and features. As all major browsers and JavaScript-runtimes follow this specification, the term _ECMAScript_ is interchangeable with the term _JavaScript_. <ide> <add>Most of the challenges on freeCodeCamp use the ECMAScript 5 (ES5) specification of the language, finalized in 2009. But JavaScript is an evolving programming language. As features are added and revisions are made, new versions of the language are released for use by developers. <add> <add>The most recent standardized version is called ECMAScript 6 (ES6), released in 2015. This new version of the language adds some powerful features that will be covered in this section of challenges, including: <add> <add>- Arrow functions <add>- Classes <add>- Modules <add>- Promises <add>- Generators <add>- `let` and `const` <add> <add>**Note**: Not all browsers support ES6 features. If you use ES6 in your own projects, you may need to use a program (transpiler) to convert your ES6 code into ES5 until browsers support ES6. <ide><path>client/src/pages/learn/javascript-algorithms-and-data-structures/functional-programming/index.md <ide> superBlock: JavaScript Algorithms and Data Structures <ide> --- <ide> ## Introduction to the Functional Programming Challenges <ide> <del>Functional programming is an approach to software development based around the evaluation of functions. Like mathematics, functions in programming map input to output to produce a result. You can combine basic functions in many ways to build more and more complex programs.<br><br>Functional programming follows a few core principles:<br><br><ul><li>Functions are independent from the state of the program or global variables. They only depend on the arguments passed into them to make a calculation</li><br><li>Functions try to limit any changes to the state of the program and avoid changes to the global objects holding data</li><br><li>Functions have minimal side effects in the program</li></ul><br><br>The functional programming software development approach breaks a program into small, testable parts. This section covers basic functional programming principles in JavaScript. <add>Functional programming is an approach to software development based around the evaluation of functions. Like mathematics, functions in programming map input to output to produce a result. You can combine basic functions in many ways to build more and more complex programs. <ide> <add>Functional programming follows a few core principles: <add> <add>- Functions are independent from the state of the program or global variables. They only depend on the arguments passed into them to make a calculation <add>- Functions try to limit any changes to the state of the program and avoid changes to the global objects holding data <add>- Functions have minimal side effects in the program <add> <add>The functional programming software development approach breaks a program into small, testable parts. This section covers basic functional programming principles in JavaScript. <ide><path>client/src/pages/learn/javascript-algorithms-and-data-structures/index.md <ide> superBlock: JavaScript Algorithms and Data Structures <ide> --- <ide> ## Introduction to JavaScript Algorithms and Data Structures <ide> <del>JavaScript Algorithms and Data Structures will teach you basic JavaScript in a series of challenges. It will teach you how to assign variables, arrays, create functions, and some of the various loop types used in JavaScript.Then it will teach you to apply what you’ve learned in multiple algorithm creation challenges. Once you have completed all the challenges and the required projects you will receive the JavaScript Algorithms and Data Structures certificate. <add>JavaScript Algorithms and Data Structures will teach you basic JavaScript in a series of challenges. It will teach you how to assign variables, arrays, create functions, and some of the various loop types used in JavaScript. Then it will teach you to apply what you’ve learned in multiple algorithm creation challenges. Once you have completed all the challenges and the required projects you will receive the JavaScript Algorithms and Data Structures certificate. <ide><path>client/src/pages/learn/responsive-web-design/applied-accessibility/index.md <ide> superBlock: Responsive Web Design <ide> ## Introduction to the Applied Accessibility Challenges <ide> <ide> "Accessibility" generally means having web content and a user interface that can be understood, navigated, and interacted with by a broad audience. This includes people with visual, auditory, mobility, or cognitive disabilities. <add> <ide> Websites should be open and accessible to everyone, regardless of a user's abilities or resources. Some users rely on assistive technology such as a screen reader or voice recognition software. Other users may be able to navigate through a site only using a keyboard. Keeping the needs of various users in mind when developing your project can go a long way towards creating an open web. <del>Here are three general concepts this section will explore throughout the following challenges:<br><br><ol><br><li>have well-organized code that uses appropriate markup</li><br><li>ensure text alternatives exist for non-text and visual content</li><br><li>create an easily-navigated page that's keyboard-friendly</li><br></ol><br><br>Having accessible web content is an ongoing challenge. A great resource for your projects going forward is the W3 Consortium's Web Content Accessibility Guidelines (WCAG). They set the international standard for accessibility and provide a number of criteria you can use to check your work. <ide> <add>Here are three general concepts this section will explore throughout the following challenges: <add> <add>1. have well-organized code that uses appropriate markup <add>2. ensure text alternatives exist for non-text and visual content <add>3. create an easily-navigated page that's keyboard-friendly <add> <add>Having accessible web content is an ongoing challenge. A great resource for your projects going forward is the W3 Consortium's Web Content Accessibility Guidelines (WCAG). They set the international standard for accessibility and provide a number of criteria you can use to check your work. <ide><path>client/src/pages/learn/responsive-web-design/basic-css/index.md <ide> superBlock: Responsive Web Design <ide> --- <ide> ## Introduction to Basic CSS <ide> <del>Cascading Style Sheets (CSS) tell the browser how to display the text and other content that you write in HTML.<br><br>Note that CSS is case-sensitive so be careful with your capitalization. <del>CSS has been adopted by all major browsers and allows you to control:<br><ul><li>color</li><li>fonts</li><li>positioning</li><li>spacing</li><li>sizing</li><li>decorations</li><li>transitions</li></ul> <del>There are three main ways to apply CSS styling. You can apply inline styles directly to HTML elements with the <code>style</code> attribute. Alternatively, you can place CSS rules within <code>style</code> tags in an HTML document. Finally, you can write CSS rules in an external style sheet, then reference that file in the HTML document. Even though the first two options have their use cases, most developers prefer external style sheets because they keep the styles separate from the HTML elements. This improves the readability and reusability of your code. <del>The idea behind CSS is that you can use a selector to target an HTML element in the DOM (Document Object Model) and then apply a variety of attributes to that element to change the way it is displayed on the page.<br><br>In this section, you'll see how adding CSS styles to the elements of your CatPhotoApp can change it from simple text to something more. <add>Cascading Style Sheets (CSS) tell the browser how to display the text and other content that you write in HTML. <ide> <add>Note that CSS is case-sensitive so be careful with your capitalization. <add> <add>CSS has been adopted by all major browsers and allows you to control: <add> <add>- color <add>- fonts <add>- positioning <add>- spacing <add>- sizing <add>- decorations <add>- transitions <add> <add>There are three main ways to apply CSS styling. You can apply inline styles directly to HTML elements with the `style` attribute. Alternatively, you can place CSS rules within `style` tags in an HTML document. Finally, you can write CSS rules in an external style sheet, then reference that file in the HTML document. Even though the first two options have their use cases, most developers prefer external style sheets because they keep the styles separate from the HTML elements. This improves the readability and reusability of your code. <add> <add>The idea behind CSS is that you can use a selector to target an HTML element in the DOM (Document Object Model) and then apply a variety of attributes to that element to change the way it is displayed on the page. <add> <add>In this section, you'll see how adding CSS styles to the elements of your CatPhotoApp can change it from simple text to something more.
8
PHP
PHP
fix more uses of set -> hash
a76a926ac13039bb5b5a846c2bc56d9f83a545b6
<ide><path>lib/Cake/Model/Model.php <ide> App::uses('ClassRegistry', 'Utility'); <ide> App::uses('Validation', 'Utility'); <ide> App::uses('String', 'Utility'); <del>App::uses('Set', 'Utility'); <add>App::uses('Hash', 'Utility'); <ide> App::uses('BehaviorCollection', 'Model'); <ide> App::uses('ModelBehavior', 'Model'); <ide> App::uses('ConnectionManager', 'Model'); <ide> protected function _findNeighbors($state, $query, $results = array()) { <ide> unset($query['conditions'][$field . ' <']); <ide> $return = array(); <ide> if (isset($results[0])) { <del> $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]); <add> $prevVal = Hash::get($results[0], $field); <ide> $query['conditions'][$field . ' >='] = $prevVal[0]; <ide> $query['conditions'][$field . ' !='] = $value; <ide> $query['limit'] = 2; <ide><path>lib/Cake/View/Helper/FormHelper.php <ide> */ <ide> <ide> App::uses('AppHelper', 'View/Helper'); <add>App::uses('Hash', 'Utility'); <ide> <ide> /** <ide> * Form helper library. <ide> public function inputs($fields = null, $blacklist = null) { <ide> public function input($fieldName, $options = array()) { <ide> $this->setEntity($fieldName); <ide> <del> $options = Set::merge( <add> $options = Hash::merge( <ide> array('before' => null, 'between' => null, 'after' => null, 'format' => null), <ide> $this->_inputDefaults, <ide> $options
2
Javascript
Javascript
improve error message
8a014cdfb3f33a7b49a68205e72c609c9ff3bb62
<ide><path>Libraries/TurboModule/TurboModuleRegistry.js <ide> export function get<T: TurboModule>(name: string): ?T { <ide> <ide> export function getEnforcing<T: TurboModule>(name: string): T { <ide> const module = get(name); <del> invariant(module != null, `${name} is not available in this app.`); <add> invariant( <add> module != null, <add> `TurboModuleRegistry.getEnforcing(...): '${name}' could not be found. ` + <add> 'Verify that a module by this name is registered in the native binary.', <add> ); <ide> return module; <ide> }
1
Go
Go
fix raw terminal
ec6b35240ed19aa68e4295c9211aa13a7e37efad
<ide><path>commands.go <ide> func (cli *DockerCli) CmdLogin(args ...string) error { <ide> flUsername := cmd.String("u", "", "username") <ide> flPassword := cmd.String("p", "", "password") <ide> flEmail := cmd.String("e", "", "email") <del> if err := cmd.Parse(args); err != nil { <add> err := cmd.Parse(args) <add> if err != nil { <ide> return nil <ide> } <ide> var oldState *term.State <del> if *flUsername != "" && *flPassword != "" && *flEmail != "" { <del> oldState, err := term.SetRawTerminal() <add> if *flUsername == "" || *flPassword == "" || *flEmail == "" { <add> oldState, err = term.SetRawTerminal() <ide> if err != nil { <ide> return err <ide> }
1
PHP
PHP
improve comments in routes.php
84f05fd3ee4d28e378eae8a684a74a65efc99a84
<ide><path>application/routes.php <ide> | Here is the public API of your application. To add functionality to your <ide> | application, you just add to the array located in this file. <ide> | <del> | It's a breeze. Simply tell Laravel the request URIs it should respond to. <add> | It's a breeze. Simply tell Laravel the HTTP verbs and request URIs it <add> | should respond to. The GET, POST, PUT, and DELETE verbs are all <add> | recognized by the Laravel routing system. <ide> | <del> | Need more breathing room? Organize your routes in their own directory. <del> | Here's how: http://laravel.com/docs/start/routes#organize <add> | Here is how to respond to a simple GET request to http://example.com/hello: <add> | <add> | 'GET /hello' => function() <add> | { <add> | return 'Hello World!'; <add> | } <add> | <add> | You can even respond to more than one URI: <add> | <add> | 'GET /hello, GET /world' => function() <add> | { <add> | return 'Hello World!'; <add> | } <add> | <add> | Allow URI wildcards using the (:num) or (:any) place-holders: <add> | <add> | 'GET /hello/(:any)' => function($name) <add> | { <add> | return "Welcome, $name."; <add> | } <add> | <add> | Ready to learn more? Check out: http://laravel.com/docs/start/routes <ide> | <ide> */ <ide>
1
PHP
PHP
improve mode function in collection
61b260556da4e75bff9b721b0085dd8848b9ea31
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function avg($callback = null) <ide> public function median($key = null) <ide> { <ide> $values = (isset($key) ? $this->pluck($key) : $this) <del> ->filter(function ($item) { <del> return ! is_null($item); <del> })->sort()->values(); <add> ->filter(fn ($item) => ! is_null($item)) <add> ->sort()->values(); <ide> <ide> $count = $values->count(); <ide> <ide> public function mode($key = null) <ide> <ide> $counts = new static; <ide> <del> $collection->each(function ($value) use ($counts) { <del> $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1; <del> }); <add> $collection->each(fn ($value) => $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1); <ide> <ide> $sorted = $counts->sort(); <ide> <ide> $highestValue = $sorted->last(); <ide> <del> return $sorted->filter(function ($value) use ($highestValue) { <del> return $value == $highestValue; <del> })->sort()->keys()->all(); <add> return $sorted->filter(fn ($value) => $value == $highestValue) <add> ->sort()->keys()->all(); <ide> } <ide> <ide> /** <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testGettingAvgItemsFromCollection($collection) <ide> <ide> $c = new $collection; <ide> $this->assertNull($c->avg()); <add> <add> $c = new $collection([['foo' => "4"], ['foo' => "2"]]); <add> $this->assertIsInt($c->avg('foo')); <add> $this->assertEquals(3, $c->avg('foo')); <add> <add> $c = new $collection([['foo' => 1], ['foo' => 2]]); <add> $this->assertIsFloat($c->avg('foo')); <add> $this->assertEquals(1.5, $c->avg('foo')); <add> <add> $c = new $collection([ <add> ['foo' => 1], ['foo' => 2], <add> (object)['foo' => 6] <add> ]); <add> $this->assertEquals(3,$c->avg('foo')); <ide> } <ide> <ide> /** <ide> public function testModeOnNullCollection($collection) <ide> public function testMode($collection) <ide> { <ide> $data = new $collection([1, 2, 3, 4, 4, 5]); <add> $this->assertIsArray($data->mode()); <ide> $this->assertEquals([4], $data->mode()); <ide> } <ide> <ide> public function testModeValueByKey($collection) <ide> (object) ['foo' => 2], <ide> (object) ['foo' => 4], <ide> ]); <add> $data2 = new Collection([ <add> ['foo' => 1], <add> ['foo' => 1], <add> ['foo' => 2], <add> ['foo' => 4], <add> ]); <ide> $this->assertEquals([1], $data->mode('foo')); <add> $this->assertEquals($data2->mode('foo'), $data->mode('foo')); <ide> } <ide> <ide> /**
2
Javascript
Javascript
add missing ondidaddtexteditor method to dock
92d0f60e6c408b65ac4d6b22a63256c93eae6c3f
<ide><path>spec/dock-spec.js <ide> /** @babel */ <ide> <add>const TextEditor = require('../src/text-editor') <add> <ide> import {it, fit, ffit, fffit, beforeEach, afterEach} from './async-spec-helpers' <ide> <ide> describe('Dock', () => { <ide> describe('Dock', () => { <ide> expect(() => atom.workspace.getElement().handleDragStart(dragEvent)).not.toThrow() <ide> }) <ide> }) <add> <add> describe('.observeTextEditors()', () => { <add> it('invokes the observer with current and future text editors', () => { <add> const dock = atom.workspace.getLeftDock() <add> const dockPane = dock.getActivePane() <add> const observed = [] <add> <add> const editorAddedBeforeRegisteringObserver = new TextEditor() <add> const nonEditorItemAddedBeforeRegisteringObserver = document.createElement('div') <add> dockPane.activateItem(editorAddedBeforeRegisteringObserver) <add> dockPane.activateItem(nonEditorItemAddedBeforeRegisteringObserver) <add> <add> dock.observeTextEditors(editor => observed.push(editor)) <add> <add> const editorAddedAfterRegisteringObserver = new TextEditor() <add> const nonEditorItemAddedAfterRegisteringObserver = document.createElement('div') <add> dockPane.activateItem(editorAddedAfterRegisteringObserver) <add> dockPane.activateItem(nonEditorItemAddedAfterRegisteringObserver) <add> <add> expect(observed).toEqual( <add> [editorAddedBeforeRegisteringObserver, editorAddedAfterRegisteringObserver] <add> ) <add> }) <add> }) <ide> }) <ide><path>src/dock.js <ide> module.exports = class Dock { <ide> return this.paneContainer.onDidDestroyPaneItem(callback) <ide> } <ide> <add> // Extended: Invoke the given callback when a text editor is added to the <add> // dock. <add> // <add> // * `callback` {Function} to be called when panes are added. <add> // * `event` {Object} with the following keys: <add> // * `textEditor` {TextEditor} that was added. <add> // * `pane` {Pane} containing the added text editor. <add> // * `index` {Number} indicating the index of the added text editor in its <add> // pane. <add> // <add> // Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. <add> onDidAddTextEditor (callback) { <add> return this.onDidAddPaneItem(({item, pane, index}) => { <add> if (item instanceof TextEditor) { <add> callback({textEditor: item, pane, index}) <add> } <add> }) <add> } <add> <ide> /* <ide> Section: Pane Items <ide> */ <ide> module.exports = class Dock { <ide> // <ide> // Returns an {Array} of {TextEditor}s. <ide> getTextEditors () { <del> return this.paneContainer.getTextEditors() <add> return this.getPaneItems().filter(item => item instanceof TextEditor) <ide> } <ide> <ide> // Essential: Get the active item if it is an {TextEditor}.
2
Javascript
Javascript
remove unused flow suppressions
70dcba99946a43b13776f33f3b9432c5d66055c1
<ide><path>Libraries/Components/Touchable/Touchable.js <ide> const TouchableMixin = { <ide> * @param {SyntheticEvent} e Synthetic event from event system. <ide> * <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleResponderGrant: function(e: PressEvent) { <ide> const dispatchID = e.currentTarget; <ide> // Since e is used in a callback invoked on another event loop <ide> const TouchableMixin = { <ide> /** <ide> * Place as callback for a DOM element's `onResponderRelease` event. <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleResponderRelease: function(e: PressEvent) { <ide> this.pressInLocation = null; <ide> this._receiveSignal(Signals.RESPONDER_RELEASE, e); <ide> const TouchableMixin = { <ide> /** <ide> * Place as callback for a DOM element's `onResponderTerminate` event. <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleResponderTerminate: function(e: PressEvent) { <ide> this.pressInLocation = null; <ide> this._receiveSignal(Signals.RESPONDER_TERMINATED, e); <ide> const TouchableMixin = { <ide> /** <ide> * Place as callback for a DOM element's `onResponderMove` event. <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleResponderMove: function(e: PressEvent) { <ide> // Measurement may not have returned yet. <ide> if (!this.state.touchable.positionOnActivate) { <ide> const TouchableMixin = { <ide> * element that was blurred just prior to this. This can be overridden when <ide> * using `Touchable.Mixin.withoutDefaultFocusAndBlur`. <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleFocus: function(e: Event) { <ide> this.props.onFocus && this.props.onFocus(e); <ide> }, <ide> const TouchableMixin = { <ide> * This can be overridden when using <ide> * `Touchable.Mixin.withoutDefaultFocusAndBlur`. <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> touchableHandleBlur: function(e: Event) { <ide> this.props.onBlur && this.props.onBlur(e); <ide> }, <ide> const TouchableMixin = { <ide> } <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _handleQueryLayout: function( <ide> l: number, <ide> t: number, <ide> const TouchableMixin = { <ide> ); <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _handleDelay: function(e: PressEvent) { <ide> this.touchableDelayTimeout = null; <ide> this._receiveSignal(Signals.DELAY, e); <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _handleLongDelay: function(e: PressEvent) { <ide> this.longPressDelayTimeout = null; <ide> const curState = this.state.touchable.touchState; <ide> const TouchableMixin = { <ide> * @throws Error if invalid state transition or unrecognized signal. <ide> * @sideeffects <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> _receiveSignal: function(signal: Signal, e: PressEvent) { <ide> const responderID = this.state.touchable.responderID; <ide> const curState = this.state.touchable.touchState; <ide> const TouchableMixin = { <ide> ); <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _savePressInLocation: function(e: PressEvent) { <ide> const touch = extractSingleTouch(e.nativeEvent); <ide> const pageX = touch && touch.pageX; <ide> const TouchableMixin = { <ide> * @param {Event} e Native event. <ide> * @sideeffects <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> _performSideEffectsForTransition: function( <ide> curState: State, <ide> nextState: State, <ide> const TouchableMixin = { <ide> this.touchableDelayTimeout = null; <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _startHighlight: function(e: PressEvent) { <ide> this._savePressInLocation(e); <ide> this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); <ide> }, <ide> <del> // $FlowFixMe[signature-verification-failure] <ide> _endHighlight: function(e: PressEvent) { <ide> if (this.touchableHandleActivePressOut) { <ide> if ( <ide><path>Libraries/DeprecatedPropTypes/DeprecatedTextInputPropTypes.js <ide> module.exports = { <ide> * <ide> * [Styles](docs/style.html) <ide> */ <del> // $FlowFixMe[incompatible-use] <ide> style: DeprecatedTextPropTypes.style, <ide> /** <ide> * The color of the `TextInput` underline. <ide><path>Libraries/Image/Image.ios.js <ide> let Image = (props: ImagePropsType, forwardedRef) => { <ide> } <ide> } <ide> <del> // $FlowFixMe[incompatible-use] <del> // $FlowFixMe[incompatible-type] <ide> const resizeMode = props.resizeMode || style.resizeMode || 'cover'; <del> // $FlowFixMe[prop-missing] <del> // $FlowFixMe[incompatible-use] <ide> const tintColor = style.tintColor; <ide> <ide> if (props.src != null) { <ide> let Image = (props: ImagePropsType, forwardedRef) => { <ide> {...props} <ide> ref={forwardedRef} <ide> style={style} <del> // $FlowFixMe[incompatible-type] <ide> resizeMode={resizeMode} <ide> tintColor={tintColor} <ide> source={sources} <ide><path>Libraries/Lists/VirtualizedList.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> } <ide> } <ide> if (someChildHasMore) { <del> // $FlowFixMe[incompatible-use] <ide> newState.last = ii; <ide> break; <ide> } <ide><path>Libraries/Storage/AsyncStorage.js <ide> const AsyncStorage = { <ide> * <ide> * See https://reactnative.dev/docs/asyncstorage.html#multiget <ide> */ <del> // $FlowFixMe[signature-verification-failure] <ide> multiGet: function( <ide> keys: Array<string>, <ide> callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void, <ide><path>Libraries/Text/TextNativeComponent.js <ide> type NativeTextProps = $ReadOnly<{ <ide> export const NativeText: HostComponent<NativeTextProps> = (createReactNativeComponentClass( <ide> 'RCTText', <ide> () => ({ <del> // $FlowFixMe[incompatible-call] <ide> validAttributes: { <ide> ...ReactNativeViewAttributes.UIView, <ide> isHighlighted: true, <ide> export const NativeVirtualText: HostComponent<NativeTextProps> = <ide> !global.RN$Bridgeless && !UIManager.hasViewManagerConfig('RCTVirtualText') <ide> ? NativeText <ide> : (createReactNativeComponentClass('RCTVirtualText', () => ({ <del> // $FlowFixMe[incompatible-call] <ide> validAttributes: { <ide> ...ReactNativeViewAttributes.UIView, <ide> isHighlighted: true, <ide><path>Libraries/Utilities/ReactNativeTestTools.js <ide> const shallowRenderer = new ShallowRenderer(); <ide> <ide> import type {ReactTestRenderer as ReactTestRendererType} from 'react-test-renderer'; <ide> <del>// $FlowFixMe[value-as-type] <ide> export type ReactTestInstance = $PropertyType<ReactTestRendererType, 'root'>; <ide> <ide> export type Predicate = (node: ReactTestInstance) => boolean; <ide> function enter(instance: ReactTestInstance, text: string) { <ide> <ide> // Returns null if there is no error, otherwise returns an error message string. <ide> function maximumDepthError( <del> // $FlowFixMe[value-as-type] <ide> tree: ReactTestRendererType, <ide> maxDepthLimit: number, <ide> ): ?string { <ide> function renderAndEnforceStrictMode(element: React.Node): any { <ide> return renderWithStrictMode(element); <ide> } <ide> <del>// $FlowFixMe[value-as-type] <ide> function renderWithStrictMode(element: React.Node): ReactTestRendererType { <ide> const WorkAroundBugWithStrictModeInTestRenderer = prps => prps.children; <ide> const StrictMode = (React: $FlowFixMe).StrictMode; <ide><path>packages/rn-tester/js/examples/Animated/EasingExample.js <ide> const easingSections = [ <ide> { <ide> title: 'Predefined animations', <ide> data: [ <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Bounce', easing: Easing.bounce}, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Ease', easing: Easing.ease}, <ide> {title: 'Elastic', easing: Easing.elastic(4)}, <ide> ], <ide> }, <ide> { <ide> title: 'Standard functions', <ide> data: [ <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Linear', easing: Easing.linear}, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Quad', easing: Easing.quad}, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Cubic', easing: Easing.cubic}, <ide> ], <ide> }, <ide> const easingSections = [ <ide> title: 'Bezier', <ide> easing: Easing.bezier(0, 2, 1, -1), <ide> }, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Circle', easing: Easing.circle}, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Sin', easing: Easing.sin}, <del> // $FlowFixMe[method-unbinding] <ide> {title: 'Exp', easing: Easing.exp}, <ide> ], <ide> }, <ide><path>packages/rn-tester/js/examples/PanResponder/PanResponderExample.js <ide> class PanResponderExample extends React.Component<Props, State> { <ide> }} <ide> style={[ <ide> styles.circle, <del> // $FlowFixMe[incompatible-type] <ide> { <ide> transform: [ <ide> {translateX: this.state.left}, <ide><path>packages/rn-tester/js/examples/PointerEvents/PointerEventsExample.js <ide> class ExampleBox extends React.Component<ExampleBoxProps, ExampleBoxState> { <ide> <View <ide> onTouchEndCapture={this.handleTouchCapture} <ide> onTouchStart={this.flushReactChanges}> <del> {/* $FlowFixMe[type-as-value] (>=0.53.0 site=react_native_fb,react_ <del> * native_oss) This comment suppresses an error when upgrading <del> * Flow's support for React. To see the error delete this comment <del> * and run Flow. */} <ide> <Component onLog={this.handleLog} /> <ide> </View> <ide> <View style={styles.logBox}> <ide><path>packages/rn-tester/js/examples/RTL/RTLExample.js <ide> exports.examples = [ <ide> description: ('In iOS, it depends on active language. ' + <ide> 'In Android, it depends on the text content.': string), <ide> render: function(): React.Element<any> { <del> // $FlowFixMe[speculation-ambiguous] <ide> return <TextAlignmentExample style={styles.fontSizeSmall} />; <ide> }, <ide> }, <ide> exports.examples = [ <ide> 'languages or text content.': string), <ide> render: function(): React.Element<any> { <ide> return ( <del> // $FlowFixMe[speculation-ambiguous] <ide> <TextAlignmentExample <ide> style={[styles.fontSizeSmall, styles.textAlignLeft]} <ide> /> <ide> exports.examples = [ <ide> 'languages or text content.': string), <ide> render: function(): React.Element<any> { <ide> return ( <del> // $FlowFixMe[speculation-ambiguous] <ide> <TextAlignmentExample <ide> style={[styles.fontSizeSmall, styles.textAlignRight]} <ide> /> <ide> exports.examples = [ <ide> title: "Using textAlign: 'right' for TextInput", <ide> description: ('Flip TextInput direction to RTL': string), <ide> render: function(): React.Element<any> { <del> // $FlowFixMe[speculation-ambiguous] <ide> return <TextInputExample style={[styles.textAlignRight]} />; <ide> }, <ide> }, <ide><path>packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js <ide> class TokenizedTextExample extends React.Component< <ide> index = 1; <ide> } <ide> parts.push(_text.substr(0, index)); <del> // $FlowFixMe[incompatible-use] <ide> parts.push(token[0]); <del> // $FlowFixMe[incompatible-use] <ide> index = index + token[0].length; <ide> _text = _text.slice(index); <ide> } <ide><path>packages/rn-tester/js/utils/RNTesterStatePersister.js <ide> function createContainer<Props: Object, State>( <ide> _passSetState = (stateLamda: (state: State) => State): void => { <ide> this.setState(state => { <ide> const value = stateLamda(state.value); <del> AsyncStorage.setItem( <del> this._cacheKey, <del> // $FlowFixMe[incompatible-call] Error surfaced when typing AsyncStorage <del> JSON.stringify(value), <del> ); <add> AsyncStorage.setItem(this._cacheKey, JSON.stringify(value)); <ide> return {value}; <ide> }); <ide> };
13
Javascript
Javascript
fix floor logic
49b9c7cc0c5fa25826be65d290258a638c27ad06
<ide><path>server/boot/about.js <ide> export default function about(app) { <ide> globalCompletedCount: numberWithCommas( <ide> 5612952 + (Math.floor((Date.now() - 1446268581061) / 1800)) <ide> ), <del> globalPledgedAmount: numberWithCommas( <del> 28000.00 + <del> ( <del> Math.floor((Date.now() - 1456207176902) / (2629746 / 2000)) * <del> 8.30 <del> ) <del> ) <add> globalPledgedAmount: numberWithCommas(Math.floor( <add> 28000 + <add> ((Date.now() - 1456207176902) / (2629746000 / 2000) * 8.30) <add> )) <ide> }); <ide> }) <ide> .subscribe(() => {}, next);
1
Mixed
Ruby
keep executions for each specific exception
95d9c3b3d6828b8ce37591e68d4239ce8c18460b
<ide><path>activejob/CHANGELOG.md <add>* Keep executions for each specific declaration <add> <add> Each `retry_on` declaration has now its own specific executions counter. Before it was <add> shared between all executions of a job. <add> <add> *Alberto Almagro* <add> <ide> * Allow all assertion helpers that have a `only` and `except` keyword to accept <ide> Procs. <ide> <ide><path>activejob/lib/active_job/core.rb <ide> module Core <ide> # Number of times this job has been executed (which increments on every retry, like after an exception). <ide> attr_accessor :executions <ide> <add> # Hash that contains the number of times this job handled errors for each specific retry_on declaration. <add> # Keys are the string representation of the exceptions listed in the retry_on declaration, <add> # while its associated value holds the number of executions where the corresponding retry_on <add> # declaration handled one of its listed exceptions. <add> attr_accessor :exception_executions <add> <ide> # I18n.locale to be used during the job. <ide> attr_accessor :locale <ide> <ide> def initialize(*arguments) <ide> @queue_name = self.class.queue_name <ide> @priority = self.class.priority <ide> @executions = 0 <add> @exception_executions = Hash.new(0) <ide> end <ide> <ide> # Returns a hash with the job data that can safely be passed to the <ide> def serialize <ide> "priority" => priority, <ide> "arguments" => serialize_arguments_if_needed(arguments), <ide> "executions" => executions, <add> "exception_executions" => exception_executions, <ide> "locale" => I18n.locale.to_s, <ide> "timezone" => Time.zone.try(:name) <ide> } <ide> def deserialize(job_data) <ide> self.priority = job_data["priority"] <ide> self.serialized_arguments = job_data["arguments"] <ide> self.executions = job_data["executions"] <add> self.exception_executions = job_data["exception_executions"] <ide> self.locale = job_data["locale"] || I18n.locale.to_s <ide> self.timezone = job_data["timezone"] || Time.zone.try(:name) <ide> end <ide><path>activejob/lib/active_job/exceptions.rb <ide> module Exceptions <ide> <ide> module ClassMethods <ide> # Catch the exception and reschedule job for re-execution after so many seconds, for a specific number of attempts. <del> # The number of attempts includes the total executions of a job, not just the retried executions. <ide> # If the exception keeps getting raised beyond the specified number of attempts, the exception is allowed to <ide> # bubble up to the underlying queuing system, which may have its own retry mechanism or place it in a <ide> # holding queue for inspection. <ide> module ClassMethods <ide> # as a computing proc that the number of executions so far as an argument, or as a symbol reference of <ide> # <tt>:exponentially_longer</tt>, which applies the wait algorithm of <tt>(executions ** 4) + 2</tt> <ide> # (first wait 3s, then 18s, then 83s, etc) <del> # * <tt>:attempts</tt> - Re-enqueues the job the specified number of times (default: 5 attempts), <del> # attempts here refers to the total number of times the job is executed, not just retried executions <add> # * <tt>:attempts</tt> - Re-enqueues the job the specified number of times (default: 5 attempts) <ide> # * <tt>:queue</tt> - Re-enqueues the job on a different queue <ide> # * <tt>:priority</tt> - Re-enqueues the job with a different priority <ide> # <ide> module ClassMethods <ide> # end <ide> def retry_on(*exceptions, wait: 3.seconds, attempts: 5, queue: nil, priority: nil) <ide> rescue_from(*exceptions) do |error| <del> if executions < attempts <add> exception_executions[exceptions.to_s] += 1 <add> <add> if exception_executions[exceptions.to_s] < attempts <ide> retry_job wait: determine_delay(wait), queue: queue, priority: priority, error: error <ide> else <ide> if block_given? <ide><path>activejob/test/cases/exceptions_test.rb <ide> class ExceptionsTest < ActiveJob::TestCase <ide> end <ide> end <ide> <add> test "keeps the same attempts counter when several exceptions are listed in the same declaration" do <add> exceptions_to_raise = %w(FirstRetryableErrorOfTwo FirstRetryableErrorOfTwo FirstRetryableErrorOfTwo <add> SecondRetryableErrorOfTwo SecondRetryableErrorOfTwo) <add> <add> assert_raises SecondRetryableErrorOfTwo do <add> perform_enqueued_jobs do <add> ExceptionRetryJob.perform_later(exceptions_to_raise) <add> end <add> end <add> end <add> <add> test "keeps a separate attempts counter for each individual declaration" do <add> exceptions_to_raise = %w(FirstRetryableErrorOfTwo FirstRetryableErrorOfTwo FirstRetryableErrorOfTwo <add> DefaultsError DefaultsError) <add> <add> assert_nothing_raised do <add> perform_enqueued_jobs do <add> ExceptionRetryJob.perform_later(exceptions_to_raise) <add> end <add> end <add> end <add> <ide> test "failed retry job when exception kept occurring against defaults" do <ide> perform_enqueued_jobs do <ide> begin <ide><path>activejob/test/jobs/retry_job.rb <ide> def perform(raising, attempts) <ide> end <ide> end <ide> end <add> <add>class ExceptionRetryJob < ActiveJob::Base <add> retry_on FirstRetryableErrorOfTwo, SecondRetryableErrorOfTwo, attempts: 4 <add> retry_on DefaultsError <add> <add> def perform(exceptions) <add> raise exceptions.shift.constantize.new unless exceptions.empty? <add> end <add>end
5
Text
Text
remove bullet point referring to node.js 12
ed7631dae984c9b5a7ef722119dc9363af7472a5
<ide><path>doc/contributing/maintaining-openssl.md <ide> currently need to generate four PRs as follows: <ide> of this guide. <ide> * a PR for 14.x following the instructions in the v14.x-staging version <ide> of this guide. <del>* a PR which uses the same commit from the third PR to apply the <del> updates to the openssl source code, with a new commit generated <del> by following steps 2 onwards on the 12.x line. This is <del> necessary because the configuration files have embedded timestamps <del> which lead to merge conflicts if cherry-picked from the second PR. <ide> <ide> ## Use of the quictls/openssl fork <ide>
1
Javascript
Javascript
fix incorrect test description
70dbb158469541a6f712ebe03b970a4a4d1abe57
<ide><path>test/ngSanitize/sanitizeSpec.js <ide> describe('HTML', function() { <ide> .toEqual('<p>text1text2</p>'); <ide> }); <ide> <del> it('should remove clobbered elements', function() { <add> it('should throw on clobbered elements', function() { <ide> inject(function($sanitize) { <ide> expect(function() { <ide> $sanitize('<form><input name="parentNode" /></form>');
1
Javascript
Javascript
add validation for fd and path
d4693ff4308de3517f064a2c930718a6f37229fe
<ide><path>lib/internal/fs/streams.js <ide> const { Buffer } = require('buffer'); <ide> const { <ide> copyObject, <ide> getOptions, <add> getValidatedFd, <add> validatePath, <ide> } = require('internal/fs/utils'); <ide> const { Readable, Writable, finished } = require('stream'); <ide> const { toPathIfFileURL } = require('internal/url'); <ide> function close(stream, err, cb) { <ide> <ide> function importFd(stream, options) { <ide> stream.fd = null; <del> if (options.fd) { <add> if (options.fd != null) { <ide> if (typeof options.fd === 'number') { <ide> // When fd is a raw descriptor, we must keep our fingers crossed <ide> // that the descriptor won't get closed, or worse, replaced with <ide> function ReadStream(path, options) { <ide> this.pos = this.start; <ide> } <ide> <add> // If fd has been set, validate, otherwise validate path. <add> if (this.fd != null) { <add> this.fd = getValidatedFd(this.fd); <add> } else { <add> validatePath(this.path); <add> } <add> <ide> if (this.end === undefined) { <ide> this.end = Infinity; <ide> } else if (this.end !== Infinity) { <ide> function WriteStream(path, options) { <ide> this.closed = false; <ide> this[kIsPerformingIO] = false; <ide> <add> // If fd has been set, validate, otherwise validate path. <add> if (this.fd != null) { <add> this.fd = getValidatedFd(this.fd); <add> } else { <add> validatePath(this.path); <add> } <add> <ide> if (this.start !== undefined) { <ide> validateInteger(this.start, 'start', 0); <ide> <ide><path>test/parallel/test-fs-stream-options.js <add>'use strict'; <add>require('../common'); <add> <add>const assert = require('assert'); <add>const fs = require('fs'); <add> <add>{ <add> const fd = 'k'; <add> <add> assert.throws( <add> () => { <add> fs.createReadStream(null, { fd }); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError', <add> }); <add> <add> assert.throws( <add> () => { <add> fs.createWriteStream(null, { fd }); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError', <add> }); <add>} <add> <add>{ <add> const path = 46; <add> <add> assert.throws( <add> () => { <add> fs.createReadStream(path); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError', <add> }); <add> <add> assert.throws( <add> () => { <add> fs.createWriteStream(path); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError', <add> }); <add>}
2
PHP
PHP
use value helper when applicable
6116d5106525a05d885408ed0a63a752732ba253
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HidesAttributes.php <ide> public function makeVisible($attributes) <ide> */ <ide> public function makeVisibleIf($condition, $attributes) <ide> { <del> $condition = $condition instanceof Closure ? $condition($this) : $condition; <del> <del> return $condition ? $this->makeVisible($attributes) : $this; <add> return value($condition, $this) ? $this->makeVisible($attributes) : $this; <ide> } <ide> <ide> /** <ide> public function makeHidden($attributes) <ide> */ <ide> public function makeHiddenIf($condition, $attributes) <ide> { <del> $condition = $condition instanceof Closure ? $condition($this) : $condition; <del> <del> return value($condition) ? $this->makeHidden($attributes) : $this; <add> return value($condition, $this) ? $this->makeHidden($attributes) : $this; <ide> } <ide> } <ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithViews.php <ide> <ide> namespace Illuminate\Foundation\Testing\Concerns; <ide> <del>use Closure; <ide> use Illuminate\Support\Facades\View as ViewFacade; <ide> use Illuminate\Support\MessageBag; <ide> use Illuminate\Support\Str; <ide> protected function component(string $componentClass, array $data = []) <ide> { <ide> $component = $this->app->make($componentClass, $data); <ide> <del> $view = $component->resolveView(); <del> <del> if ($view instanceof Closure) { <del> $view = $view($data); <del> } <add> $view = value($component->resolveView(), $data); <ide> <ide> return $view instanceof View <ide> ? new TestView($view->with($component->data())) <ide><path>src/Illuminate/Foundation/helpers.php <ide> function rescue(callable $callback, $rescue = null, $report = true) <ide> report($e); <ide> } <ide> <del> return $rescue instanceof Closure ? $rescue($e) : $rescue; <add> return value($rescue, $e); <ide> } <ide> } <ide> } <ide><path>src/Illuminate/View/Concerns/ManagesComponents.php <ide> <ide> namespace Illuminate\View\Concerns; <ide> <del>use Closure; <ide> use Illuminate\Contracts\Support\Htmlable; <ide> use Illuminate\Contracts\View\View; <ide> use Illuminate\Support\Arr; <ide> public function renderComponent() <ide> <ide> $data = $this->componentData(); <ide> <del> if ($view instanceof Closure) { <del> $view = $view($data); <del> } <add> $view = value($view, $data); <ide> <ide> if ($view instanceof View) { <ide> return $view->with($data)->render(); <ide> public function endSlot() <ide> $this->slotStack[$this->currentComponent()] <ide> ); <ide> <del> $this->slots[$this->currentComponent()] <del> [$currentSlot] = new HtmlString(trim(ob_get_clean())); <add> $this->slots[$this->currentComponent()][$currentSlot] = new HtmlString(trim(ob_get_clean())); <ide> } <ide> <ide> /**
4
Text
Text
add tellnes as collaborator
865ee313cff5470e831d8c09003f03eb52f3ca41
<ide><path>README.md <ide> information about the governance of the io.js project, see <ide> * **Sam Roberts** ([@sam-github](https://github.com/sam-github)) &lt;vieuxtech@gmail.com&gt; <ide> * **Wyatt Preul** ([@geek](https://github.com/geek)) &lt;wpreul@gmail.com&gt; <ide> * **Brian White** ([@mscdex](https://github.com/mscdex)) &lt;mscdex@mscdex.net&gt; <add>* **Christian Vaagland Tellnes** ([@tellnes](https://github.com/tellnes)) &lt;christian@tellnes.com&gt; <ide> <ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in <ide> maintaining the io.js project.
1
Ruby
Ruby
remove a relic of #request being in rackdelegation
f368b21cb6e45268359c0f0b8beda175e3b40eae
<ide><path>actionpack/lib/action_controller/metal.rb <ide> def build(action, app=nil, &block) <ide> class Metal < AbstractController::Base <ide> abstract! <ide> <del> # :api: public <del> attr_internal :params, :env <add> attr_internal :env <ide> <ide> # Returns the last part of the controller's name, underscored, without the ending <ide> # "Controller". For instance, MyApp::MyPostsController would return "my_posts" for <ide> def initialize(*) <ide> super <ide> end <ide> <add> def params <add> @_params ||= request.parameters <add> end <add> <add> def params=(val) <add> @_params = val <add> end <add> <ide> # Basic implementations for content_type=, location=, and headers are <ide> # provided to reduce the dependency on the RackDelegation module <ide> # in Renderer and Redirector. <ide><path>actionpack/lib/action_controller/metal/rack_delegation.rb <ide> def dispatch(action, request, response = ActionDispatch::Response.new) <ide> super(action, request) <ide> end <ide> <del> def params <del> @_params ||= @_request.parameters <del> end <del> <ide> def response_body=(body) <ide> response.body = body if response <ide> super
2
PHP
PHP
fix minor cs issue
6e0b7995c657e8c15fce8bd6d26ff923c0320a2b
<ide><path>src/Network/Request.php <ide> protected function _headerDetector($detect) <ide> { <ide> foreach ($detect['header'] as $header => $value) { <ide> $header = $this->env('http_' . $header); <del> if (!is_null($header)) { <add> if ($header !== null) { <ide> if (!is_string($value) && !is_bool($value) && is_callable($value)) { <ide> return call_user_func($value, $header); <ide> }
1
Ruby
Ruby
use the predicate method
6e24d501d3a84a59feb8ed37ed71759ed8a96995
<ide><path>activerecord/lib/active_record/reflection.rb <ide> def source_macro <ide> <ide> # A through association is nested if there would be more than one join table <ide> def nested? <del> chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many <add> chain.length > 2 || through_reflection.has_and_belongs_to_many? <ide> end <ide> <ide> # We want to use the klass from this reflection, rather than just delegate straight to
1
Mixed
Javascript
add timeout to spawn and fork
d8fb5c2f1c907f09e2763046c436a236b70cdea5
<ide><path>doc/api/child_process.md <ide> controller.abort(); <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37256 <add> description: timeout was added. <ide> - version: v15.11.0 <ide> pr-url: https://github.com/nodejs/node/pull/37325 <ide> description: killSignal for AbortSignal was added. <ide> changes: <ide> See [Advanced serialization][] for more details. **Default:** `'json'`. <ide> * `signal` {AbortSignal} Allows closing the child process using an <ide> AbortSignal. <del> * `killSignal` {string} The signal value to be used when the spawned <del> process will be killed by the abort signal. **Default:** `'SIGTERM'`. <add> * `killSignal` {string|integer} The signal value to be used when the spawned <add> process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`. <ide> * `silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be <ide> piped to the parent, otherwise they will be inherited from the parent, see <ide> the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s <ide> changes: <ide> * `uid` {number} Sets the user identity of the process (see setuid(2)). <ide> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is <ide> done on Windows. Ignored on Unix. **Default:** `false`. <add> * `timeout` {number} In milliseconds the maximum amount of time the process <add> is allowed to run. **Default:** `undefined`. <ide> * Returns: {ChildProcess} <ide> <ide> The `child_process.fork()` method is a special case of <ide> if (process.argv[2] === 'child') { <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37256 <add> description: timeout was added. <ide> - version: v15.11.0 <ide> pr-url: https://github.com/nodejs/node/pull/37325 <ide> description: killSignal for AbortSignal was added. <ide> changes: <ide> normally be created on Windows systems. **Default:** `false`. <ide> * `signal` {AbortSignal} allows aborting the child process using an <ide> AbortSignal. <del> * `killSignal` {string} The signal value to be used when the spawned <del> process will be killed by the abort signal. **Default:** `'SIGTERM'`. <add> * `timeout` {number} In milliseconds the maximum amount of time the process <add> is allowed to run. **Default:** `undefined`. <add> * `killSignal` {string|integer} The signal value to be used when the spawned <add> process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`. <ide> <ide> * Returns: {ChildProcess} <ide> <ide><path>lib/child_process.js <ide> function abortChildProcess(child, killSignal) { <ide> <ide> <ide> function spawn(file, args, options) { <del> const child = new ChildProcess(); <ide> options = normalizeSpawnArguments(file, args, options); <add> validateTimeout(options.timeout, 'options.timeout'); <add> validateAbortSignal(options.signal, 'options.signal'); <add> const killSignal = sanitizeKillSignal(options.killSignal); <add> const child = new ChildProcess(); <ide> <ide> if (options.signal) { <ide> const signal = options.signal; <del> // Validate signal, if present <del> validateAbortSignal(signal, 'options.signal'); <del> const killSignal = sanitizeKillSignal(options.killSignal); <del> // Do nothing and throw if already aborted <ide> if (signal.aborted) { <ide> onAbortListener(); <ide> } else { <ide> function spawn(file, args, options) { <ide> debug('spawn', options); <ide> child.spawn(options); <ide> <add> if (options.timeout > 0) { <add> let timeoutId = setTimeout(() => { <add> if (timeoutId) { <add> try { <add> child.kill(killSignal); <add> } catch (err) { <add> child.emit('error', err); <add> } <add> timeoutId = null; <add> } <add> }, options.timeout); <add> <add> child.once('exit', () => { <add> if (timeoutId) { <add> clearTimeout(timeoutId); <add> timeoutId = null; <add> } <add> }); <add> } <add> <ide> return child; <ide> } <ide> <ide><path>test/parallel/test-child-process-fork-timeout-kill-signal.js <add>'use strict'; <add> <add>const { mustCall } = require('../common'); <add>const { strictEqual, throws } = require('assert'); <add>const fixtures = require('../common/fixtures'); <add>const { fork } = require('child_process'); <add>const { getEventListeners } = require('events'); <add> <add>{ <add> // Verify default signal <add> const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> timeout: 5, <add> }); <add> cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGTERM'))); <add>} <add> <add>{ <add> // Verify correct signal + closes after at least 4 ms. <add> const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> timeout: 5, <add> killSignal: 'SIGKILL', <add> }); <add> cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGKILL'))); <add>} <add> <add>{ <add> // Verify timeout verification <add> throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> timeout: 'badValue', <add> }), /ERR_OUT_OF_RANGE/); <add> <add> throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> timeout: {}, <add> }), /ERR_OUT_OF_RANGE/); <add>} <add> <add>{ <add> // Verify abort signal gets unregistered <add> const signal = new EventTarget(); <add> signal.aborted = false; <add> <add> const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> timeout: 6, <add> signal, <add> }); <add> strictEqual(getEventListeners(signal, 'abort').length, 1); <add> cp.on('exit', mustCall(() => { <add> strictEqual(getEventListeners(signal, 'abort').length, 0); <add> })); <add>} <ide><path>test/parallel/test-child-process-spawn-timeout-kill-signal.js <add>'use strict'; <add> <add>const { mustCall } = require('../common'); <add>const { strictEqual, throws } = require('assert'); <add>const fixtures = require('../common/fixtures'); <add>const { spawn } = require('child_process'); <add>const { getEventListeners } = require('events'); <add> <add>const aliveForeverFile = 'child-process-stay-alive-forever.js'; <add>{ <add> // Verify default signal + closes <add> const cp = spawn(process.execPath, [fixtures.path(aliveForeverFile)], { <add> timeout: 5, <add> }); <add> cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGTERM'))); <add>} <add> <add>{ <add> // Verify SIGKILL signal + closes <add> const cp = spawn(process.execPath, [fixtures.path(aliveForeverFile)], { <add> timeout: 6, <add> killSignal: 'SIGKILL', <add> }); <add> cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGKILL'))); <add>} <add> <add>{ <add> // Verify timeout verification <add> throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], { <add> timeout: 'badValue', <add> }), /ERR_OUT_OF_RANGE/); <add> <add> throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], { <add> timeout: {}, <add> }), /ERR_OUT_OF_RANGE/); <add>} <add> <add>{ <add> // Verify abort signal gets unregistered <add> const controller = new AbortController(); <add> const { signal } = controller; <add> const cp = spawn(process.execPath, [fixtures.path(aliveForeverFile)], { <add> timeout: 6, <add> signal, <add> }); <add> strictEqual(getEventListeners(signal, 'abort').length, 1); <add> cp.on('exit', mustCall(() => { <add> strictEqual(getEventListeners(signal, 'abort').length, 0); <add> })); <add>}
4
Ruby
Ruby
use a || b
6e616b29c5c47d49e94f2fe2345564cf381b0e0f
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def fflags; self['FFLAGS']; end <ide> def fcflags; self['FCFLAGS']; end <ide> <ide> def compiler <del> @compiler ||= if (cc = [ARGV.cc, homebrew_cc].compact.first) <add> @compiler ||= if (cc = ARGV.cc || homebrew_cc) <ide> COMPILER_SYMBOL_MAP.fetch(cc) do |other| <ide> case other <ide> when GNU_GCC_REGEXP
1
Javascript
Javascript
remove redundant backtick in comment
6abd2cb7dbe5f4cd4fe6364b28c92dcdbd81c47b
<ide><path>packages/@ember/application/lib/application.js <ide> const Application = Engine.extend({ <ide> // Start the app at the special demo URL <ide> App.visit('/demo', options); <ide> }); <del> ```` <add> ``` <ide> <ide> Or perhaps you might want to boot two instances of your app on the same <ide> page for a split-screen multiplayer experience:
1
PHP
PHP
use single logs by default
3516f4f6771bd1817d08b529549c4f4a449e672f
<ide><path>config/app.php <ide> | <ide> */ <ide> <del> 'log' => 'daily', <add> 'log' => 'single', <ide> <ide> /* <ide> |--------------------------------------------------------------------------
1
Python
Python
add unit tests for limits and resources
1dcd3d0b67402f68db3e53357c83a944b4d76c63
<ide><path>chart/tests/test_flower.py <ide> def test_should_create_valid_affinity_tolerations_and_node_selector(self): <ide> "spec.template.spec.tolerations[0].key", <ide> docs[0], <ide> ) <add> <add> def test_flower_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "flower": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/flower/flower-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_flower_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/flower/flower-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_kerberos.py <ide> def test_kerberos_sidecar_resources(self): <ide> ) <ide> assert jmespath.search("spec.template.spec.containers[2].resources.limits.cpu", docs[0]) == "201m" <ide> assert jmespath.search("spec.template.spec.containers[2].resources.limits.memory", docs[0]) == "201Mi" <add> <add> def test_keberos_sidecar_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/workers/worker-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_limit_ranges.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import unittest <add> <add>import jmespath <add> <add>from chart.tests.helm_template_generator import render_chart <add> <add> <add>class LimitRangesTest(unittest.TestCase): <add> def test_limit_ranges_template(self): <add> docs = render_chart( <add> values={"limits": [{"max": {"cpu": "500m"}, "min": {"min": "200m"}, "type": "Container"}]}, <add> show_only=["templates/limitrange.yaml"], <add> ) <add> assert "LimitRange" == jmespath.search("kind", docs[0]) <add> assert "500m" == jmespath.search("spec.limits[0].max.cpu", docs[0]) <add> <add> def test_limit_ranges_are_not_added_by_default(self): <add> docs = render_chart(show_only=["templates/limitrange.yaml"]) <add> assert docs == [] <ide><path>chart/tests/test_pgbouncer.py <ide> def test_existing_secret(self): <ide> "name": "pgbouncer-config", <ide> "secret": {"secretName": "pgbouncer-config-secret"}, <ide> } == jmespath.search("spec.template.spec.volumes[0]", docs[0]) <add> <add> def test_pgbouncer_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "pgbouncer": { <add> "enabled": True, <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> }, <add> }, <add> }, <add> show_only=["templates/pgbouncer/pgbouncer-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_pgbouncer_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> values={ <add> "pgbouncer": {"enabled": True}, <add> }, <add> show_only=["templates/pgbouncer/pgbouncer-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_redis.py <ide> def test_should_create_valid_affinity_tolerations_and_node_selector(self): <ide> "spec.template.spec.tolerations[0].key", <ide> docs[0], <ide> ) <add> <add> def test_redis_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "redis": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/redis/redis-statefulset.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_redis_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/redis/redis-statefulset.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_resource_quota.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import unittest <add> <add>import jmespath <add> <add>from chart.tests.helm_template_generator import render_chart <add> <add> <add>class ResourceQuotaTest(unittest.TestCase): <add> def test_resource_quota_template(self): <add> docs = render_chart( <add> values={ <add> "quotas": { <add> "configmaps": "10", <add> "persistentvolumeclaims": "4", <add> "pods": "4", <add> "replicationcontrollers": "20", <add> "secrets": "10", <add> "services": "10", <add> } <add> }, <add> show_only=["templates/resourcequota.yaml"], <add> ) <add> assert "ResourceQuota" == jmespath.search("kind", docs[0]) <add> assert "20" == jmespath.search("spec.hard.replicationcontrollers", docs[0]) <add> <add> def test_resource_quota_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/resourcequota.yaml"], <add> ) <add> assert docs == [] <ide><path>chart/tests/test_scheduler.py <ide> def test_logs_persistence_changes_volume(self, log_persistence_values, expected_ <ide> assert {"name": "logs", **expected_volume} == jmespath.search( <ide> "spec.template.spec.volumes[1]", docs[0] <ide> ) <add> <add> def test_scheduler_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "scheduler": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/scheduler/scheduler-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_scheduler_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/scheduler/scheduler-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_statsd.py <ide> def test_should_create_valid_affinity_tolerations_and_node_selector(self): <ide> "spec.template.spec.tolerations[0].key", <ide> docs[0], <ide> ) <add> <add> def test_stastd_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "statsd": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/statsd/statsd-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_statsd_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/statsd/statsd-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_webserver_deployment.py <ide> def test_logs_persistence_adds_volume_and_mount(self, log_persistence_values, ex <ide> assert "logs" not in [ <ide> v["name"] for v in jmespath.search("spec.template.spec.containers[0].volumeMounts", docs[0]) <ide> ] <add> <add> def test_webserver_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "webserver": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/webserver/webserver-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_webserver_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/webserver/webserver-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} <ide><path>chart/tests/test_worker.py <ide> def test_logs_persistence_changes_volume(self, log_persistence_values, expected_ <ide> assert {"name": "logs", **expected_volume} == jmespath.search( <ide> "spec.template.spec.volumes[1]", docs[0] <ide> ) <add> <add> def test_worker_resources_are_configurable(self): <add> docs = render_chart( <add> values={ <add> "workers": { <add> "resources": { <add> "limits": {"cpu": "200m", 'memory': "128Mi"}, <add> "requests": {"cpu": "300m", 'memory': "169Mi"}, <add> } <add> }, <add> }, <add> show_only=["templates/workers/worker-deployment.yaml"], <add> ) <add> assert "128Mi" == jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) <add> assert "169Mi" == jmespath.search( <add> "spec.template.spec.containers[0].resources.requests.memory", docs[0] <add> ) <add> assert "300m" == jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) <add> <add> def test_worker_resources_are_not_added_by_default(self): <add> docs = render_chart( <add> show_only=["templates/workers/worker-deployment.yaml"], <add> ) <add> assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {}
10
Javascript
Javascript
fix typo in inspector-helper.js
0ed9961f1239a3d9f79334dc8b7f0a3ba6c6fee2
<ide><path>test/common/inspector-helper.js <ide> class InspectorSession { <ide> <ide> waitForNotification(methodOrPredicate, description) { <ide> const desc = description || methodOrPredicate; <del> const message = `Timed out waiting for matching notification (${desc}))`; <add> const message = `Timed out waiting for matching notification (${desc})`; <ide> return fires( <ide> this._asyncWaitForNotification(methodOrPredicate), message, TIMEOUT); <ide> }
1
Java
Java
remove componentregistry class
c629cdc39a2d64b65e40ba550b7b6c8d22bc7065
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/ComponentRegistry.java <del>// Copyright 2004-present Facebook. All Rights Reserved. <del> <del>package com.facebook.react.fabric; <del> <del>import com.facebook.jni.HybridData; <del>import com.facebook.proguard.annotations.DoNotStrip; <del>import com.facebook.soloader.SoLoader; <del> <del>@DoNotStrip <del>public class ComponentRegistry { <del> <del> static { <del> FabricSoLoader.staticInit(); <del> } <del> <del> private final HybridData mHybridData; <del> <del> @DoNotStrip <del> private static native HybridData initHybrid(); <del> <del> public ComponentRegistry() { <del> mHybridData = initHybrid(); <del> } <del> <del>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java <ide> private static void loadClasses() { <ide> ViewPool.class.getClass(); <ide> Binding.class.getClass(); <ide> ComponentFactoryDelegate.class.getClass(); <del> ComponentRegistry.class.getClass(); <ide> EventBeatManager.class.getClass(); <ide> EventEmitterWrapper.class.getClass(); <ide> StateWrapperImpl.class.getClass();
2
Python
Python
call ping to set connection for avoiding error
bc13e2fdc7fd0a82eaa7e0b89869e4d4ef5051bb
<ide><path>celery/backends/redis.py <ide> def _reconnect_pubsub(self): <ide> ) <ide> if self.subscribed_to: <ide> self._pubsub.subscribe(*self.subscribed_to) <add> else: <add> self._pubsub.ping() <ide> <ide> @contextmanager <ide> def reconnect_on_error(self):
1
Javascript
Javascript
fix @each for changes in defineproperty
eb7a1ac16015c73cf152b61aad825e473aea1c00
<ide><path>packages/ember-runtime/lib/system/each_proxy.js <ide> Ember.EachProxy = Ember.Object.extend({ <ide> unknownProperty: function(keyName, value) { <ide> var ret; <ide> ret = new EachArray(this._content, keyName, this); <del> new Ember.Descriptor().setup(this, keyName, ret); <add> Ember.defineProperty(this, keyName, null, ret); <ide> this.beginObservingContentKey(keyName); <ide> return ret; <ide> },
1
Javascript
Javascript
use safe computedstyle in currentdimension
20cae21ff7222fd6b1efa6b4e48578fd405ba126
<ide><path>src/js/component.js <ide> import * as Fn from './utils/fn.js'; <ide> import * as Guid from './utils/guid.js'; <ide> import toTitleCase from './utils/to-title-case.js'; <ide> import mergeOptions from './utils/merge-options.js'; <add>import computedStyle from './utils/computed-style'; <ide> <ide> /** <ide> * Base class for all UI Components. <ide> class Component { <ide> throw new Error('currentDimension only accepts width or height value'); <ide> } <ide> <del> if (typeof window.getComputedStyle === 'function') { <del> const computedStyle = window.getComputedStyle(this.el_); <del> <del> computedWidthOrHeight = computedStyle.getPropertyValue(widthOrHeight) || computedStyle[widthOrHeight]; <del> } <add> computedWidthOrHeight = computedStyle(this.el_, widthOrHeight); <ide> <ide> // remove 'px' from variable and parse as integer <ide> computedWidthOrHeight = parseFloat(computedWidthOrHeight); <ide> <ide> // if the computed value is still 0, it's possible that the browser is lying <ide> // and we want to check the offset values. <ide> // This code also runs wherever getComputedStyle doesn't exist. <del> if (computedWidthOrHeight === 0) { <add> if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) { <ide> const rule = `offset${toTitleCase(widthOrHeight)}`; <ide> <ide> computedWidthOrHeight = this.el_[rule]; <ide><path>src/js/utils/computed-style.js <ide> function computedStyle(el, prop) { <ide> } <ide> <ide> if (typeof window.getComputedStyle === 'function') { <del> const cs = window.getComputedStyle(el); <add> const computedStyleValue = window.getComputedStyle(el); <ide> <del> return cs ? cs[prop] : ''; <add> return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : ''; <ide> } <ide> <ide> return '';
2
Javascript
Javascript
make safe primordials safe to construct
40fc395d7d4aee0db61a64cca5dd96718b75d307
<ide><path>lib/internal/per_context/primordials.js <ide> primordials.makeSafe = makeSafe; <ide> <ide> // Subclass the constructors because we need to use their prototype <ide> // methods later. <add>// Defining the `constructor` is necessary here to avoid the default <add>// constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`. <ide> primordials.SafeMap = makeSafe( <ide> Map, <del> class SafeMap extends Map {} <add> class SafeMap extends Map { <add> constructor(i) { super(i); } // eslint-disable-line no-useless-constructor <add> } <ide> ); <ide> primordials.SafeWeakMap = makeSafe( <ide> WeakMap, <del> class SafeWeakMap extends WeakMap {} <add> class SafeWeakMap extends WeakMap { <add> constructor(i) { super(i); } // eslint-disable-line no-useless-constructor <add> } <ide> ); <ide> primordials.SafeSet = makeSafe( <ide> Set, <del> class SafeSet extends Set {} <add> class SafeSet extends Set { <add> constructor(i) { super(i); } // eslint-disable-line no-useless-constructor <add> } <ide> ); <ide> primordials.SafeWeakSet = makeSafe( <ide> WeakSet, <del> class SafeWeakSet extends WeakSet {} <add> class SafeWeakSet extends WeakSet { <add> constructor(i) { super(i); } // eslint-disable-line no-useless-constructor <add> } <ide> ); <ide> <ide> // Create copies of the namespace objects
1
Python
Python
specify ram size in gib
d09f9b5d941e838601cafb9dbb95be82f634693d
<ide><path>libcloud/compute/drivers/ec2.py <ide> Sizes must be hardcoded, because Amazon doesn't provide an API to fetch them. <ide> From http://aws.amazon.com/ec2/instance-types/ <ide> """ <add> <add> <add>def GiB(value): <add> return int(value * 1024) <add> <add> <ide> INSTANCE_TYPES = { <ide> 't1.micro': { <ide> 'id': 't1.micro', <ide> 'name': 'Micro Instance', <del> 'ram': 613, <add> 'ram': GiB(0.613), <ide> 'disk': 15, <ide> 'bandwidth': None <ide> }, <ide> 'm1.small': { <ide> 'id': 'm1.small', <ide> 'name': 'Small Instance', <del> 'ram': 1740, <add> 'ram': GiB(1.7), <ide> 'disk': 160, <ide> 'bandwidth': None <ide> }, <ide> 'm1.medium': { <ide> 'id': 'm1.medium', <ide> 'name': 'Medium Instance', <del> 'ram': 3700, <add> 'ram': GiB(3.75), <ide> 'disk': 410, <ide> 'bandwidth': None <ide> }, <ide> 'm1.large': { <ide> 'id': 'm1.large', <ide> 'name': 'Large Instance', <del> 'ram': 7680, <add> 'ram': GiB(7.5), <ide> 'disk': 850, <ide> 'bandwidth': None <ide> }, <ide> 'm1.xlarge': { <ide> 'id': 'm1.xlarge', <ide> 'name': 'Extra Large Instance', <del> 'ram': 15360, <add> 'ram': GiB(15), <ide> 'disk': 1690, <ide> 'bandwidth': None <ide> }, <ide> 'c1.medium': { <ide> 'id': 'c1.medium', <ide> 'name': 'High-CPU Medium Instance', <del> 'ram': 1740, <add> 'ram': GiB(1.7), <ide> 'disk': 350, <ide> 'bandwidth': None <ide> }, <ide> 'c1.xlarge': { <ide> 'id': 'c1.xlarge', <ide> 'name': 'High-CPU Extra Large Instance', <del> 'ram': 7680, <add> 'ram': GiB(7), <ide> 'disk': 1690, <ide> 'bandwidth': None <ide> }, <ide> 'm2.xlarge': { <ide> 'id': 'm2.xlarge', <ide> 'name': 'High-Memory Extra Large Instance', <del> 'ram': 17510, <add> 'ram': GiB(17.1), <ide> 'disk': 420, <ide> 'bandwidth': None <ide> }, <ide> 'm2.2xlarge': { <ide> 'id': 'm2.2xlarge', <ide> 'name': 'High-Memory Double Extra Large Instance', <del> 'ram': 35021, <add> 'ram': GiB(34.2), <ide> 'disk': 850, <ide> 'bandwidth': None <ide> }, <ide> 'm2.4xlarge': { <ide> 'id': 'm2.4xlarge', <ide> 'name': 'High-Memory Quadruple Extra Large Instance', <del> 'ram': 70042, <add> 'ram': GiB(68.4), <ide> 'disk': 1690, <ide> 'bandwidth': None <ide> }, <ide> 'm3.medium': { <ide> 'id': 'm3.medium', <ide> 'name': 'Medium Instance', <del> 'ram': 3840, <add> 'ram': GiB(3.75), <ide> 'disk': 4000, <ide> 'bandwidth': None <ide> }, <ide> 'm3.large': { <ide> 'id': 'm3.large', <ide> 'name': 'Large Instance', <del> 'ram': 7168, <add> 'ram': GiB(7.5), <ide> 'disk': 32000, <ide> 'bandwidth': None <ide> }, <ide> 'm3.xlarge': { <ide> 'id': 'm3.xlarge', <ide> 'name': 'Extra Large Instance', <del> 'ram': 15360, <add> 'ram': GiB(15), <ide> 'disk': 80000, <ide> 'bandwidth': None <ide> }, <ide> 'm3.2xlarge': { <ide> 'id': 'm3.2xlarge', <ide> 'name': 'Double Extra Large Instance', <del> 'ram': 30720, <add> 'ram': GiB(30), <ide> 'disk': 160000, <ide> 'bandwidth': None <ide> }, <ide> 'm4.large': { <ide> 'id': 'm4.large', <ide> 'name': 'Large Instance', <del> 'ram': 8192, <add> 'ram': GiB(8), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'm4.xlarge': { <ide> 'id': 'm4.xlarge', <ide> 'name': 'Extra Large Instance', <del> 'ram': 16384, <add> 'ram': GiB(16), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'm4.2xlarge': { <ide> 'id': 'm4.2xlarge', <ide> 'name': 'Double Extra Large Instance', <del> 'ram': 32768, <add> 'ram': GiB(32), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'm4.4xlarge': { <ide> 'id': 'm4.4xlarge', <ide> 'name': 'Quadruple Extra Large Instance', <del> 'ram': 65536, <add> 'ram': GiB(64), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'm4.10xlarge': { <ide> 'id': 'm4.10xlarge', <ide> 'name': '10 Extra Large Instance', <del> 'ram': 163840, <add> 'ram': GiB(160), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'cg1.4xlarge': { <ide> 'id': 'cg1.4xlarge', <ide> 'name': 'Cluster GPU Quadruple Extra Large Instance', <del> 'ram': 22528, <add> 'ram': GiB(22.5), <ide> 'disk': 1690, <ide> 'bandwidth': None <ide> }, <ide> 'g2.2xlarge': { <ide> 'id': 'g2.2xlarge', <ide> 'name': 'Cluster GPU G2 Double Extra Large Instance', <del> 'ram': 15000, <add> 'ram': GiB(15), <ide> 'disk': 60, <ide> 'bandwidth': None, <ide> }, <ide> 'cc2.8xlarge': { <ide> 'id': 'cc2.8xlarge', <ide> 'name': 'Cluster Compute Eight Extra Large Instance', <del> 'ram': 63488, <add> 'ram': GiB(60.5), <ide> 'disk': 3370, <ide> 'bandwidth': None <ide> }, <ide> # c3 instances have 2 SSDs of the specified disk size <ide> 'c3.large': { <ide> 'id': 'c3.large', <ide> 'name': 'Compute Optimized Large Instance', <del> 'ram': 3750, <add> 'ram': GiB(3.75), <ide> 'disk': 32, # x2 <ide> 'bandwidth': None <ide> }, <ide> 'c3.xlarge': { <ide> 'id': 'c3.xlarge', <ide> 'name': 'Compute Optimized Extra Large Instance', <del> 'ram': 7500, <add> 'ram': GiB(7.5), <ide> 'disk': 80, # x2 <ide> 'bandwidth': None <ide> }, <ide> 'c3.2xlarge': { <ide> 'id': 'c3.2xlarge', <ide> 'name': 'Compute Optimized Double Extra Large Instance', <del> 'ram': 15000, <add> 'ram': GiB(15), <ide> 'disk': 160, # x2 <ide> 'bandwidth': None <ide> }, <ide> 'c3.4xlarge': { <ide> 'id': 'c3.4xlarge', <ide> 'name': 'Compute Optimized Quadruple Extra Large Instance', <del> 'ram': 30000, <add> 'ram': GiB(30), <ide> 'disk': 320, # x2 <ide> 'bandwidth': None <ide> }, <ide> 'c3.8xlarge': { <ide> 'id': 'c3.8xlarge', <ide> 'name': 'Compute Optimized Eight Extra Large Instance', <del> 'ram': 60000, <add> 'ram': GiB(60), <ide> 'disk': 640, # x2 <ide> 'bandwidth': None <ide> }, <ide> 'c4.large': { <ide> 'id': 'c4.large', <ide> 'name': 'Compute Optimized Large Instance', <del> 'ram': 3750, <add> 'ram': GiB(3.75), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'c4.xlarge': { <ide> 'id': 'c4.xlarge', <ide> 'name': 'Compute Optimized Extra Large Instance', <del> 'ram': 7500, <add> 'ram': GiB(7.5), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'c4.2xlarge': { <ide> 'id': 'c4.2xlarge', <ide> 'name': 'Compute Optimized Double Large Instance', <del> 'ram': 15000, <add> 'ram': GiB(15), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'c4.4xlarge': { <ide> 'id': 'c4.4xlarge', <ide> 'name': 'Compute Optimized Quadruple Extra Large Instance', <del> 'ram': 30000, <add> 'ram': GiB(30), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'c4.8xlarge': { <ide> 'id': 'c4.8xlarge', <ide> 'name': 'Compute Optimized Eight Extra Large Instance', <del> 'ram': 60000, <add> 'ram': GiB(60), <ide> 'disk': 0, <ide> 'bandwidth': None <ide> }, <ide> 'cr1.8xlarge': { <ide> 'id': 'cr1.8xlarge', <ide> 'name': 'High Memory Cluster Eight Extra Large', <del> 'ram': 244000, <add> 'ram': GiB(244), <ide> 'disk': 240, <ide> 'bandwidth': None <ide> }, <ide> 'hs1.4xlarge': { <ide> 'id': 'hs1.4xlarge', <ide> 'name': 'High Storage Quadruple Extra Large Instance', <del> 'ram': 61952, <add> 'ram': GiB(64), <ide> 'disk': 2048, <ide> 'bandwidth': None <ide> }, <ide> 'hs1.8xlarge': { <ide> 'id': 'hs1.8xlarge', <ide> 'name': 'High Storage Eight Extra Large Instance', <del> 'ram': 119808, <add> 'ram': GiB(117), <ide> 'disk': 48000, <ide> 'bandwidth': None <ide> }, <ide> # i2 instances have up to eight SSD drives <ide> 'i2.xlarge': { <ide> 'id': 'i2.xlarge', <ide> 'name': 'High Storage Optimized Extra Large Instance', <del> 'ram': 31232, <add> 'ram': GiB(30.5), <ide> 'disk': 800, <ide> 'bandwidth': None <ide> }, <ide> 'i2.2xlarge': { <ide> 'id': 'i2.2xlarge', <ide> 'name': 'High Storage Optimized Double Extra Large Instance', <del> 'ram': 62464, <add> 'ram': GiB(61), <ide> 'disk': 1600, <ide> 'bandwidth': None <ide> }, <ide> 'i2.4xlarge': { <ide> 'id': 'i2.4xlarge', <ide> 'name': 'High Storage Optimized Quadruple Large Instance', <del> 'ram': 124928, <add> 'ram': GiB(122), <ide> 'disk': 3200, <ide> 'bandwidth': None <ide> }, <ide> 'i2.8xlarge': { <ide> 'id': 'i2.8xlarge', <ide> 'name': 'High Storage Optimized Eight Extra Large Instance', <del> 'ram': 249856, <add> 'ram': GiB(244), <ide> 'disk': 6400, <ide> 'bandwidth': None <ide> }, <ide> 'd2.xlarge': { <ide> 'id': 'd2.xlarge', <ide> 'name': 'High Storage Optimized Extra Large Instance', <del> 'ram': 30050, <add> 'ram': GiB(30.5), <ide> 'disk': 6000, # 3 x 2 TB <ide> 'bandwidth': None <ide> }, <ide> 'd2.2xlarge': { <ide> 'id': 'd2.2xlarge', <ide> 'name': 'High Storage Optimized Double Extra Large Instance', <del> 'ram': 61952, <add> 'ram': GiB(61), <ide> 'disk': 12000, # 6 x 2 TB <ide> 'bandwidth': None <ide> }, <ide> 'd2.4xlarge': { <ide> 'id': 'd2.4xlarge', <ide> 'name': 'High Storage Optimized Quadruple Extra Large Instance', <del> 'ram': 122000, <add> 'ram': GiB(122), <ide> 'disk': 24000, # 12 x 2 TB <ide> 'bandwidth': None <ide> }, <ide> 'd2.8xlarge': { <ide> 'id': 'd2.8xlarge', <ide> 'name': 'High Storage Optimized Eight Extra Large Instance', <del> 'ram': 244000, <add> 'ram': GiB(244), <ide> 'disk': 48000, # 24 x 2 TB <ide> 'bandwidth': None <ide> }, <ide> # 1x SSD <ide> 'r3.large': { <ide> 'id': 'r3.large', <ide> 'name': 'Memory Optimized Large instance', <del> 'ram': 15000, <add> 'ram': GiB(15.25), <ide> 'disk': 32, <ide> 'bandwidth': None <ide> }, <ide> 'r3.xlarge': { <ide> 'id': 'r3.xlarge', <ide> 'name': 'Memory Optimized Extra Large instance', <del> 'ram': 30500, <add> 'ram': GiB(30.5), <ide> 'disk': 80, <ide> 'bandwidth': None <ide> }, <ide> 'r3.2xlarge': { <ide> 'id': 'r3.2xlarge', <ide> 'name': 'Memory Optimized Double Extra Large instance', <del> 'ram': 61000, <add> 'ram': GiB(61), <ide> 'disk': 160, <ide> 'bandwidth': None <ide> }, <ide> 'r3.4xlarge': { <ide> 'id': 'r3.4xlarge', <ide> 'name': 'Memory Optimized Quadruple Extra Large instance', <del> 'ram': 122000, <add> 'ram': GiB(122), <ide> 'disk': 320, <ide> 'bandwidth': None <ide> }, <ide> 'r3.8xlarge': { <ide> 'id': 'r3.8xlarge', <ide> 'name': 'Memory Optimized Eight Extra Large instance', <del> 'ram': 244000, <add> 'ram': GiB(244), <ide> 'disk': 320, # x2 <ide> 'bandwidth': None <ide> }, <ide> 't2.micro': { <ide> 'id': 't2.micro', <ide> 'name': 'Burstable Performance Micro Instance', <del> 'ram': 1024, <add> 'ram': GiB(1), <ide> 'disk': 0, # EBS Only <ide> 'bandwidth': None, <ide> 'extra': { <ide> 't2.small': { <ide> 'id': 't2.small', <ide> 'name': 'Burstable Performance Small Instance', <del> 'ram': 2048, <add> 'ram': GiB(2), <ide> 'disk': 0, # EBS Only <ide> 'bandwidth': None, <ide> 'extra': { <ide> 't2.medium': { <ide> 'id': 't2.medium', <ide> 'name': 'Burstable Performance Medium Instance', <del> 'ram': 4028, <add> 'ram': GiB(4), <ide> 'disk': 0, # EBS Only <ide> 'bandwidth': None, <ide> 'extra': {
1
Text
Text
remove erroneous remove_column option from example
7be279a64456b33cd745720ab3dd1c59482bc542
<ide><path>guides/source/active_record_migrations.md <ide> argument. Provide the original column options too, otherwise Rails can't <ide> recreate the column exactly when rolling back: <ide> <ide> ```ruby <del>remove_column :posts, :slug, :string, null: false, default: '', index: true <add>remove_column :posts, :slug, :string, null: false, default: '' <ide> ``` <ide> <ide> If you're going to need to use any other methods, you should use `reversible`
1
Javascript
Javascript
update jsm files
348d6267dec151f8934a73f6aa892767f184e051
<ide><path>examples/jsm/loaders/LWOLoader.js <ide> GeometryParser.prototype = { <ide> <ide> } <ide> <add> geometry.morphTargetsRelative = false; <add> <ide> }, <ide> <ide> }; <ide><path>examples/jsm/loaders/MD2Loader.js <ide> MD2Loader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> geometry.morphAttributes.position = morphPositions; <ide> geometry.morphAttributes.normal = morphNormals; <add> geometry.morphTargetsRelative = false; <ide> <ide> geometry.animations = AnimationClip.CreateClipsFromMorphTargetSequences( frames, 10 ); <ide> <ide><path>examples/jsm/loaders/MMDLoader.js <ide> var MMDLoader = ( function () { <ide> <ide> geometry.morphTargets = morphTargets; <ide> geometry.morphAttributes.position = morphPositions; <add> geometry.morphTargetsRelative = false; <ide> <ide> geometry.userData.MMD = { <ide> bones: bones,
3
Javascript
Javascript
allow enoent in test-worker-init-failure
0e1fd8d0b42340039ae4086fa23c062d1a2dee74
<ide><path>test/parallel/test-worker-init-failure.js <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> // We want to test that if there is an error in a constrained running <del> // environment, it will be one of `ENFILE`, `EMFILE`, or <add> // environment, it will be one of `ENFILE`, `EMFILE`, 'ENOENT', or <ide> // `ERR_WORKER_INIT_FAILED`. <del> const allowableCodes = ['ERR_WORKER_INIT_FAILED', 'EMFILE', 'ENFILE']; <add> const expected = ['ERR_WORKER_INIT_FAILED', 'EMFILE', 'ENFILE', 'ENOENT']; <ide> <ide> // `common.mustCall*` cannot be used here as in some environments <ide> // (i.e. single cpu) `ulimit` may not lead to such an error. <ide> worker.on('error', (e) => { <del> assert.ok(allowableCodes.includes(e.code), `${e.code} not expected`); <add> assert.ok(expected.includes(e.code), `${e.code} not expected`); <ide> }); <ide> } <ide>
1
Ruby
Ruby
fix deprecation message in test for path#children
72e6fb005fbdd211883282fc761d3ded23ef7fbb
<ide><path>railties/test/application/paths_test.rb <ide> def assert_not_in_load_path(*path) <ide> end <ide> <ide> test "deprecated children method" do <del> assert_deprecated "children is deprecated and will be removed in Rails 4.1." do <add> assert_deprecated "children is deprecated and will be removed from Rails 4.1." do <ide> @paths["app/assets"].children <ide> end <ide> end
1
Python
Python
add workaround for v8 builds
d206aa36e27e212d00857ab56d174ace5e6b6c45
<ide><path>configure.py <ide> import bz2 <ide> import io <ide> <del>from shutil import which <add># Fallback to find_executable from distutils.spawn is a stopgap for <add># supporting V8 builds, which do not yet support Python 3. <add>try: <add> from shutil import which <add>except ImportError: <add> from distutils.spawn import find_executable as which <ide> from distutils.version import StrictVersion <ide> <ide> # If not run from node/, cd to node/.
1
Mixed
Javascript
remove unneeded quicstream.aborted and fixup docs
83bf0d7e8cf39c49750cf527f331cdf6b5f4f225
<ide><path>doc/api/quic.md <ide> const { createQuicSocket } = require('net'); <ide> // Create the QUIC UDP IPv4 socket bound to local IP port 1234 <ide> const socket = createQuicSocket({ endpoint: { port: 1234 } }); <ide> <del>socket.on('session', (session) => { <add>socket.on('session', async (session) => { <ide> // A new server side session has been created! <ide> <del> session.on('secure', () => { <del> // Once the TLS handshake is completed, we can <del> // open streams... <del> const uni = session.openStream({ halfOpen: true }); <del> uni.write('hi '); <del> uni.end('from the server!'); <del> }); <del> <ide> // The peer opened a new stream! <ide> session.on('stream', (stream) => { <ide> // Let's say hello <ide> socket.on('session', (session) => { <ide> stream.on('data', console.log); <ide> stream.on('end', () => console.log('stream ended')); <ide> }); <add> <add> const uni = await session.openStream({ halfOpen: true }); <add> uni.write('hi '); <add> uni.end('from the server!'); <ide> }); <ide> <ide> // Tell the socket to operate as a server using the given <ide> The `openStream()` method is used to create a new `QuicStream`: <ide> <ide> ```js <ide> // Create a new bidirectional stream <del>const stream1 = session.openStream(); <add>const stream1 = await session.openStream(); <ide> <ide> // Create a new unidirectional stream <del>const stream2 = session.openStream({ halfOpen: true }); <add>const stream2 = await session.openStream({ halfOpen: true }); <ide> ``` <ide> <ide> As suggested by the names, a bidirectional stream allows data to be sent on <ide> added: REPLACEME <ide> * `defaultEncoding` {string} The default encoding that is used when no <ide> encoding is specified as an argument to `quicstream.write()`. Default: <ide> `'utf8'`. <del>* Returns: {QuicStream} <add>* Returns: {Promise} containing {QuicStream} <ide> <del>Returns a new `QuicStream`. <add>Returns a `Promise` that resolves a new `QuicStream`. <ide> <del>An error will be thrown if the `QuicSession` has been destroyed or is in the <del>process of a graceful shutdown. <add>The `Promise` will be rejected if the `QuicSession` has been destroyed or is in <add>the process of a graceful shutdown. <ide> <ide> #### `quicsession.ping()` <ide> <!--YAML <ide> stream('trailingHeaders', (headers) => { <ide> added: REPLACEME <ide> --> <ide> <del>#### `quicstream.aborted` <del><!-- YAML <del>added: REPLACEME <del>--> <del>* Type: {boolean} <del> <del>True if dataflow on the `QuicStream` was prematurely terminated. <del> <ide> #### `quicstream.bidirectional` <ide> <!--YAML <ide> added: REPLACEME <ide> added: REPLACEME <ide> <ide> The maximum received offset for this `QuicStream`. <ide> <del>#### `quicstream.pending` <del><!-- YAML <del>added: REPLACEME <del>--> <del> <del>* {boolean} <del> <del>This property is `true` if the underlying session is not finished yet, <del>i.e. before the `'ready'` event is emitted. <del> <ide> #### `quicstream.pushStream(headers\[, options\])` <ide> <!-- YAML <ide> added: REPLACEME <ide><path>lib/internal/quic/core.js <ide> function streamOnPause() { <ide> class QuicStream extends Duplex { <ide> [kInternalState] = { <ide> closed: false, <del> aborted: false, <ide> defaultEncoding: undefined, <ide> didRead: false, <ide> id: undefined, <ide> class QuicStream extends Duplex { <ide> <ide> state.closed = true; <ide> <del> state.aborted = this.readable || this.writable; <del> <ide> // Trigger scheduling of the RESET_STREAM and STOP_SENDING frames <ide> // as appropriate. Notify ngtcp2 that the stream is to be shutdown. <ide> // Once sent, the stream will be closed and destroyed as soon as <ide> class QuicStream extends Duplex { <ide> // TODO(@jasnell): Implement this later <ide> } <ide> <del> get aborted() { <del> return this[kInternalState].aborted; <del> } <del> <ide> get serverInitiated() { <ide> return !!(this[kInternalState].id & 0b01); <ide> } <ide><path>test/parallel/test-quic-quicstream-close-early.js <ide> const countdown = new Countdown(2, () => { <ide> server.on('session', common.mustCall(async (session) => { <ide> const uni = await session.openStream({ halfOpen: true }); <ide> uni.write('hi', common.expectsError()); <del> uni.on('error', common.mustCall(() => { <del> assert.strictEqual(uni.aborted, true); <del> })); <add> uni.on('error', common.mustCall()); <ide> uni.on('data', common.mustNotCall()); <ide> uni.on('close', common.mustCall()); <ide> uni.close(3); <ide> const countdown = new Countdown(2, () => { <ide> const stream = await req.openStream(); <ide> stream.write('hello', common.expectsError()); <ide> stream.write('there', common.expectsError()); <del> stream.on('error', common.mustCall(() => { <del> assert.strictEqual(stream.aborted, true); <del> })); <add> stream.on('error', common.mustCall()); <ide> stream.on('end', common.mustNotCall()); <ide> stream.on('close', common.mustCall(() => { <ide> countdown.dec();
3
Javascript
Javascript
add support to tag-hyphenated elements
85ffc6d973865a031ded170934e0acfc2e97cb11
<ide><path>src/manipulation.js <ide> define([ <ide> ], function( jQuery, concat, push, access, rcheckableType, support, dataPriv, dataUser ) { <ide> <ide> var <del> rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, <del> rtagName = /<([\w:]+)/, <add> rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, <add> rtagName = /<([\w:-]+)/, <ide> rhtml = /<|&#?\w+;/, <ide> rnoInnerhtml = /<(?:script|style|link)/i, <ide> // checked="checked" or checked <ide><path>test/unit/manipulation.js <ide> test( "html(String) with HTML5 (Bug #6485)", function() { <ide> equal( jQuery("#qunit-fixture").children().children().children().length, 1, "Make sure nested HTML5 elements can hold children." ); <ide> }); <ide> <add>test( "html(String) tag-hyphenated elements (Bug #1987)", function() { <add> <add> expect( 27 ); <add> <add> jQuery.each( "thead tbody tfoot colgroup caption tr th td".split(" "), function( i, name ) { <add> var j = jQuery("<" + name + "-d></" + name + "-d><" + name + "-d></" + name + "-d>"); <add> ok( j[0], "Create a tag-hyphenated element" ); <add> ok( jQuery.nodeName(j[0], name.toUpperCase() + "-D"), "Hyphenated node name" ); <add> ok( jQuery.nodeName(j[1], name.toUpperCase() + "-D"), "Hyphenated node name" ); <add> }); <add> <add> var j = jQuery("<tr-multiple-hyphens><td-with-hyphen>text</td-with-hyphen></tr-multiple-hyphens>"); <add> ok( jQuery.nodeName(j[0], "TR-MULTIPLE-HYPHENS"), "Tags with multiple hypens" ); <add> ok( jQuery.nodeName(j.children()[0], "TD-WITH-HYPHEN"), "Tags with multiple hypens" ); <add> equal( j.children().text(), "text", "Tags with multple hypens behave normally" ); <add>}); <add> <ide> test( "IE8 serialization bug", function() { <ide> <ide> expect( 2 );
2
Python
Python
handle the case where .svn/entries does not exist
03693fb5fa4343165c0f3eeef4d769932a07dc3e
<ide><path>scipy_distutils/misc_util.py <ide> def generate_svn_version_py(extension, build_dir): <ide> local_path = extension.local_path <ide> target = os.path.join(build_dir, '__svn_version__.py') <ide> entries = os.path.join(local_path,'.svn','entries') <del> if not dep_util.newer(entries, target): <add> if os.path.isfile(entries): <add> if not dep_util.newer(entries, target): <add> return target <add> elif os.path.isfile(target): <ide> return target <add> <ide> revision = get_svn_revision(local_path) <ide> f = open(target,'w') <ide> f.write('revision=%s\n' % (revision))
1
Ruby
Ruby
remove count var
34db2b7caacefac2dd808b52a7f77d58ff6a8b69
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb <ide> def delete_or_nullify_all_records(method) <ide> # Deletes the records according to the <tt>:dependent</tt> option. <ide> def delete_records(records, method) <ide> if method == :destroy <del> count = records.length <ide> records.each(&:destroy!) <del> update_counter(-count) unless inverse_updates_counter_cache? <add> update_counter(-records.length) unless inverse_updates_counter_cache? <ide> else <ide> scope = self.scope.where(reflection.klass.primary_key => records) <del> count = delete_count(method, scope) <del> update_counter(-count) <add> update_counter(-delete_count(method, scope)) <ide> end <ide> end <ide>
1
Text
Text
improve callback params for `fs.mkdir`
def4bb774f2b1adc67d06b354cc7bdd977f6e4d8
<ide><path>doc/api/fs.md <ide> changes: <ide> * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`. <ide> * `callback` {Function} <ide> * `err` {Error} <add> * `path` {string|undefined} Present only if a directory is created with <add> `recursive` set to `true`. <ide> <ide> Asynchronously creates a directory. <ide>
1
Ruby
Ruby
pass the view around instead of using an ivar
1853b0d0abf87dfdd4c3a277c3badb17ca19652e
<ide><path>actionview/lib/action_view/renderer/streaming_template_renderer.rb <ide> def log_error(exception) <ide> # For streaming, instead of rendering a given a template, we return a Body <ide> # object that responds to each. This object is initialized with a block <ide> # that knows how to render the template. <del> def render_template(template, layout_name = nil, locals = {}) #:nodoc: <add> def render_template(view, template, layout_name = nil, locals = {}) #:nodoc: <ide> return [super] unless layout_name && template.supports_streaming? <ide> <ide> locals ||= {} <ide> layout = layout_name && find_layout(layout_name, locals.keys, [formats.first]) <ide> <ide> Body.new do |buffer| <del> delayed_render(buffer, template, layout, @view, locals) <add> delayed_render(buffer, template, layout, view, locals) <ide> end <ide> end <ide> <ide><path>actionview/lib/action_view/renderer/template_renderer.rb <ide> module ActionView <ide> class TemplateRenderer < AbstractRenderer #:nodoc: <ide> def render(context, options) <del> @view = context <ide> @details = extract_details(options) <ide> template = determine_template(options) <ide> <ide> prepend_formats(template.formats) <ide> <ide> @lookup_context.rendered_format ||= (template.formats.first || formats.first) <ide> <del> render_template(template, options[:layout], options[:locals]) <add> render_template(context, template, options[:layout], options[:locals]) <ide> end <ide> <ide> private <ide> def determine_template(options) <ide> <ide> # Renders the given template. A string representing the layout can be <ide> # supplied as well. <del> def render_template(template, layout_name = nil, locals = nil) <del> view, locals = @view, locals || {} <add> def render_template(view, template, layout_name = nil, locals = nil) <add> locals ||= {} <ide> <del> render_with_layout(layout_name, locals) do |layout| <add> render_with_layout(view, layout_name, locals) do |layout| <ide> instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do <ide> template.render(view, locals) { |*name| view._layout_for(*name) } <ide> end <ide> end <ide> end <ide> <del> def render_with_layout(path, locals) <add> def render_with_layout(view, path, locals) <ide> layout = path && find_layout(path, locals.keys, [formats.first]) <ide> content = yield(layout) <ide> <ide> if layout <del> view = @view <ide> view.view_flow.set(:layout, content) <ide> layout.render(view, locals) { |*name| view._layout_for(*name) } <ide> else
2
Go
Go
add some builder getenv tests
eeeae2c235f0f075284008cced669de177dd8747
<ide><path>builder/shell_parser_test.go <ide> func TestShellParser(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestGetEnv(t *testing.T) { <add> sw := &shellWord{ <add> word: "", <add> envs: nil, <add> pos: 0, <add> } <add> <add> sw.envs = []string{} <add> if sw.getEnv("foo") != "" { <add> t.Fatalf("2 - 'foo' should map to ''") <add> } <add> <add> sw.envs = []string{"foo"} <add> if sw.getEnv("foo") != "" { <add> t.Fatalf("3 - 'foo' should map to ''") <add> } <add> <add> sw.envs = []string{"foo="} <add> if sw.getEnv("foo") != "" { <add> t.Fatalf("4 - 'foo' should map to ''") <add> } <add> <add> sw.envs = []string{"foo=bar"} <add> if sw.getEnv("foo") != "bar" { <add> t.Fatalf("5 - 'foo' should map to 'bar'") <add> } <add> <add> sw.envs = []string{"foo=bar", "car=hat"} <add> if sw.getEnv("foo") != "bar" { <add> t.Fatalf("6 - 'foo' should map to 'bar'") <add> } <add> if sw.getEnv("car") != "hat" { <add> t.Fatalf("7 - 'car' should map to 'hat'") <add> } <add> <add> // Make sure we grab the first 'car' in the list <add> sw.envs = []string{"foo=bar", "car=hat", "car=bike"} <add> if sw.getEnv("car") != "hat" { <add> t.Fatalf("8 - 'car' should map to 'hat'") <add> } <add>}
1
Text
Text
add remark about collaborators discussion page
bea2252554b6305ed1960a5d7c718e3ae08458b9
<ide><path>GOVERNANCE.md <ide> The nomination passes if no Collaborators oppose it after one week. Otherwise, <ide> the nomination fails. <ide> <ide> There are steps a nominator can take in advance to make a nomination as <del>frictionless as possible. Use the [Collaborators discussion page][] to request <del>feedback from other Collaborators in private. A nominator may also work with the <add>frictionless as possible. To request feedback from other Collaborators in <add> private, use the [Collaborators discussion page][] <add> (which only Collaborators may view). A nominator may also work with the <ide> nominee to improve their contribution profile. <ide> <ide> Collaborators might overlook someone with valuable contributions. In that case,
1
Javascript
Javascript
add referrerpolicy to htmldompropertyconfig
cccef3c68310df3bd611df2a7b98a530645c67c0
<ide><path>src/renderers/dom/shared/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> profile: 0, <ide> radioGroup: 0, <ide> readOnly: HAS_BOOLEAN_VALUE, <add> referrerPolicy: 0, <ide> rel: 0, <ide> required: HAS_BOOLEAN_VALUE, <ide> reversed: HAS_BOOLEAN_VALUE,
1
Java
Java
limit alias to take
06ba7523dd3eaa325ee77c9e91ee61f1eff7f39f
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public final Observable<T> lastOrDefault(T defaultValue, Func1<? super T, Boolea <ide> return filter(predicate).takeLast(1).singleOrDefault(defaultValue); <ide> } <ide> <add> /** <add> * Returns an Observable that emits only the first {@code num} items emitted by the source Observable. <add> * <p> <add> * Alias of {@link #take(int)} to match Java 8 Stream API naming convention. <add> * <p> <add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png"> <add> * <p> <add> * This method returns an Observable that will invoke a subscribing {@link Observer}'s {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking <add> * {@link Observer#onCompleted onCompleted}. <add> * <add> * @param num <add> * the maximum number of items to emit <add> * @return an Observable that emits only the first {@code num} items emitted by the source Observable, or <add> * all of the items from the source Observable if that Observable emits fewer than {@code num} items <add> * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-take">RxJava Wiki: take()</a> <add> */ <add> public final Observable<T> limit(int num) { <add> return take(num); <add> } <add> <ide> /** <ide> * Returns an Observable that counts the total number of items emitted by the source Observable and emits <ide> * this count as a 64-bit Long.
1
Mixed
Ruby
fix hashwithindifferentaccess#without bug
b2ea8310734b734c29b806f272c866045fc9bca7
<ide><path>activesupport/CHANGELOG.md <add>* Fix bug where `#without` for `ActiveSupport::HashWithIndifferentAccess` would fail <add> with symbol arguments <add> <add> *Abraham Chan* <add> <ide> * Treat `#delete_prefix`, `#delete_suffix` and `#unicode_normalize` results as non-`html_safe`. <ide> Ensure safety of arguments for `#insert`, `#[]=` and `#replace` calls on `html_safe` Strings. <ide> <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb <ide> def delete(key) <ide> super(convert_key(key)) <ide> end <ide> <add> alias_method :without, :except <add> <ide> def stringify_keys!; self end <ide> def deep_stringify_keys!; self end <ide> def stringify_keys; dup end <ide><path>activesupport/test/hash_with_indifferent_access_test.rb <ide> def test_indifferent_slice_access_with_symbols <ide> assert_equal "bender", slice["login"] <ide> end <ide> <add> def test_indifferent_without <add> original = { a: "x", b: "y", c: 10 }.with_indifferent_access <add> expected = { c: 10 }.with_indifferent_access <add> <add> [["a", "b"], [:a, :b]].each do |keys| <add> # Should return a new hash without the given keys. <add> assert_equal expected, original.without(*keys), keys.inspect <add> assert_not_equal expected, original <add> end <add> end <add> <ide> def test_indifferent_extract <ide> original = { :a => 1, "b" => 2, :c => 3, "d" => 4 }.with_indifferent_access <ide> expected = { a: 1, b: 2 }.with_indifferent_access
3
Javascript
Javascript
remove old unneded files
94759f4c2cab91d35a18159a00fbdaec0af79aa9
<ide><path>src/delete/Binder.js <del>function Binder(doc, widgetFactory, datastore, location, config) { <del> this.doc = doc; <del> this.location = location; <del> this.datastore = datastore; <del> this.anchor = {}; <del> this.widgetFactory = widgetFactory; <del> this.config = config || {}; <del> this.updateListeners = []; <del>} <del> <del>Binder.parseBindings = function(string) { <del> var results = []; <del> var lastIndex = 0; <del> var index; <del> while((index = string.indexOf('{{', lastIndex)) > -1) { <del> if (lastIndex < index) <del> results.push(string.substr(lastIndex, index - lastIndex)); <del> lastIndex = index; <del> <del> index = string.indexOf('}}', index); <del> index = index < 0 ? string.length : index + 2; <del> <del> results.push(string.substr(lastIndex, index - lastIndex)); <del> lastIndex = index; <del> } <del> if (lastIndex != string.length) <del> results.push(string.substr(lastIndex, string.length - lastIndex)); <del> return results.length === 0 ? [ string ] : results; <del>}; <del> <del>Binder.hasBinding = function(string) { <del> var bindings = Binder.parseBindings(string); <del> return bindings.length > 1 || Binder.binding(bindings[0]) !== null; <del>}; <del> <del>Binder.binding = function(string) { <del> var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); <del> return binding ? binding[1] : null; <del>}; <del> <del> <del>Binder.prototype = { <del> parseQueryString: function(query) { <del> var params = {}; <del> query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, <del> function (match, left, right) { <del> if (left) params[decodeURIComponent(left)] = decodeURIComponent(right); <del> }); <del> return params; <del> }, <del> <del> parseAnchor: function() { <del> var self = this, url = this.location['get']() || ""; <del> <del> var anchorIndex = url.indexOf('#'); <del> if (anchorIndex < 0) return; <del> var anchor = url.substring(anchorIndex + 1); <del> <del> var anchorQuery = this.parseQueryString(anchor); <del> foreach(self.anchor, function(newValue, key) { <del> delete self.anchor[key]; <del> }); <del> foreach(anchorQuery, function(newValue, key) { <del> self.anchor[key] = newValue; <del> }); <del> }, <del> <del> onUrlChange: function() { <del> this.parseAnchor(); <del> this.updateView(); <del> }, <del> <del> updateAnchor: function() { <del> var url = this.location['get']() || ""; <del> var anchorIndex = url.indexOf('#'); <del> if (anchorIndex > -1) <del> url = url.substring(0, anchorIndex); <del> url += "#"; <del> var sep = ''; <del> for (var key in this.anchor) { <del> var value = this.anchor[key]; <del> if (typeof value === 'undefined' || value === null) { <del> delete this.anchor[key]; <del> } else { <del> url += sep + encodeURIComponent(key); <del> if (value !== true) <del> url += "=" + encodeURIComponent(value); <del> sep = '&'; <del> } <del> } <del> this.location['set'](url); <del> return url; <del> }, <del> <del> updateView: function() { <del> var start = new Date().getTime(); <del> var scope = jQuery(this.doc).scope(); <del> scope.clearInvalid(); <del> scope.updateView(); <del> var end = new Date().getTime(); <del> this.updateAnchor(); <del> foreach(this.updateListeners, function(fn) {fn();}); <del> }, <del> <del> docFindWithSelf: function(exp){ <del> var doc = jQuery(this.doc); <del> var selection = doc.find(exp); <del> if (doc.is(exp)){ <del> selection = selection.andSelf(); <del> } <del> return selection; <del> }, <del> <del> executeInit: function() { <del> this.docFindWithSelf("[ng:init]").each(function() { <del> var jThis = jQuery(this); <del> var scope = jThis.scope(); <del> try { <del> scope.eval(jThis.attr('ng:init')); <del> } catch (e) { <del> alert("EVAL ERROR:\n" + jThis.attr('ng:init') + '\n' + toJson(e, true)); <del> } <del> }); <del> }, <del> <del> entity: function (scope) { <del> var self = this; <del> this.docFindWithSelf("[ng-entity]").attr("ng:watch", function() { <del> try { <del> var jNode = jQuery(this); <del> var decl = scope.entity(jNode.attr("ng-entity"), self.datastore); <del> return decl + (jNode.attr('ng:watch') || ""); <del> } catch (e) { <del> log(e); <del> alert(e); <del> } <del> }); <del> }, <del> <del> compile: function() { <del> var jNode = jQuery(this.doc); <del> if (this.config['autoSubmit']) { <del> var submits = this.docFindWithSelf(":submit").not("[ng-action]"); <del> submits.attr("ng-action", "$save()"); <del> submits.not(":disabled").not("ng:bind-attr").attr("ng:bind-attr", '{disabled:"{{$invalidWidgets}}"}'); <del> } <del> this.precompile(this.doc)(this.doc, jNode.scope(), ""); <del> this.docFindWithSelf("a[ng-action]").live('click', function (event) { <del> var jNode = jQuery(this); <del> var scope = jNode.scope(); <del> try { <del> scope.eval(jNode.attr('ng-action')); <del> jNode.removeAttr('ng-error'); <del> jNode.removeClass("ng-exception"); <del> } catch (e) { <del> jNode.addClass("ng-exception"); <del> jNode.attr('ng-error', toJson(e, true)); <del> } <del> scope.get('$updateView')(); <del> return false; <del> }); <del> }, <del> <del> translateBinding: function(node, parentPath, factories) { <del> var path = parentPath.concat(); <del> var offset = path.pop(); <del> var parts = Binder.parseBindings(node.nodeValue); <del> if (parts.length > 1 || Binder.binding(parts[0])) { <del> var parent = node.parentNode; <del> if (isLeafNode(parent)) { <del> parent.setAttribute('ng:bind-template', node.nodeValue); <del> factories.push({path:path, fn:function(node, scope, prefix) { <del> return new BindUpdater(node, node.getAttribute('ng:bind-template')); <del> }}); <del> } else { <del> for (var i = 0; i < parts.length; i++) { <del> var part = parts[i]; <del> var binding = Binder.binding(part); <del> var newNode; <del> if (binding) { <del> newNode = document.createElement("span"); <del> var jNewNode = jQuery(newNode); <del> jNewNode.attr("ng:bind", binding); <del> if (i === 0) { <del> factories.push({path:path.concat(offset + i), fn:this.ng_bind}); <del> } <del> } else if (msie && part.charAt(0) == ' ') { <del> newNode = document.createElement("span"); <del> newNode.innerHTML = '&nbsp;' + part.substring(1); <del> } else { <del> newNode = document.createTextNode(part); <del> } <del> parent.insertBefore(newNode, node); <del> } <del> } <del> parent.removeChild(node); <del> } <del> }, <del> <del> precompile: function(root) { <del> var factories = []; <del> this.precompileNode(root, [], factories); <del> return function (template, scope, prefix) { <del> var len = factories.length; <del> for (var i = 0; i < len; i++) { <del> var factory = factories[i]; <del> var node = template; <del> var path = factory.path; <del> for (var j = 0; j < path.length; j++) { <del> node = node.childNodes[path[j]]; <del> } <del> try { <del> scope.addWidget(factory.fn(node, scope, prefix)); <del> } catch (e) { <del> alert(e); <del> } <del> } <del> }; <del> }, <del> <del> precompileNode: function(node, path, factories) { <del> var nodeType = node.nodeType; <del> if (nodeType == Node.TEXT_NODE) { <del> this.translateBinding(node, path, factories); <del> return; <del> } else if (nodeType != Node.ELEMENT_NODE && nodeType != Node.DOCUMENT_NODE) { <del> return; <del> } <del> <del> if (!node.getAttribute) return; <del> var nonBindable = node.getAttribute('ng:non-bindable'); <del> if (nonBindable || nonBindable === "") return; <del> <del> var attributes = node.attributes; <del> if (attributes) { <del> var bindings = node.getAttribute('ng:bind-attr'); <del> node.removeAttribute('ng:bind-attr'); <del> bindings = bindings ? fromJson(bindings) : {}; <del> var attrLen = attributes.length; <del> for (var i = 0; i < attrLen; i++) { <del> var attr = attributes[i]; <del> var attrName = attr.name; <del> // http://www.glennjones.net/Post/809/getAttributehrefbug.htm <del> var attrValue = msie && attrName == 'href' ? <del> decodeURI(node.getAttribute(attrName, 2)) : attr.value; <del> if (Binder.hasBinding(attrValue)) { <del> bindings[attrName] = attrValue; <del> } <del> } <del> var json = toJson(bindings); <del> if (json.length > 2) { <del> node.setAttribute("ng:bind-attr", json); <del> } <del> } <del> <del> if (!node.getAttribute) log(node); <del> var repeaterExpression = node.getAttribute('ng:repeat'); <del> if (repeaterExpression) { <del> node.removeAttribute('ng:repeat'); <del> var precompiled = this.precompile(node); <del> var view = document.createComment("ng:repeat: " + repeaterExpression); <del> var parentNode = node.parentNode; <del> parentNode.insertBefore(view, node); <del> parentNode.removeChild(node); <del> function template(childScope, prefix, i) { <del> var clone = jQuery(node).clone(); <del> clone.css('display', ''); <del> clone.attr('ng:repeat-index', "" + i); <del> clone.data('scope', childScope); <del> precompiled(clone[0], childScope, prefix + i + ":"); <del> return clone; <del> } <del> factories.push({path:path, fn:function(node, scope, prefix) { <del> return new RepeaterUpdater(jQuery(node), repeaterExpression, template, prefix); <del> }}); <del> return; <del> } <del> <del> if (node.getAttribute('ng:eval')) factories.push({path:path, fn:this.ng_eval}); <del> if (node.getAttribute('ng:bind')) factories.push({path:path, fn:this.ng_bind}); <del> if (node.getAttribute('ng:bind-attr')) factories.push({path:path, fn:this.ng_bind_attr}); <del> if (node.getAttribute('ng:hide')) factories.push({path:path, fn:this.ng_hide}); <del> if (node.getAttribute('ng:show')) factories.push({path:path, fn:this.ng_show}); <del> if (node.getAttribute('ng:class')) factories.push({path:path, fn:this.ng_class}); <del> if (node.getAttribute('ng:class-odd')) factories.push({path:path, fn:this.ng_class_odd}); <del> if (node.getAttribute('ng:class-even')) factories.push({path:path, fn:this.ng_class_even}); <del> if (node.getAttribute('ng:style')) factories.push({path:path, fn:this.ng_style}); <del> if (node.getAttribute('ng:watch')) factories.push({path:path, fn:this.ng_watch}); <del> var nodeName = node.nodeName; <del> if ((nodeName == 'INPUT' ) || <del> nodeName == 'TEXTAREA' || <del> nodeName == 'SELECT' || <del> nodeName == 'BUTTON') { <del> var self = this; <del> factories.push({path:path, fn:function(node, scope, prefix) { <del> node.name = prefix + node.name.split(":").pop(); <del> return self.widgetFactory.createController(jQuery(node), scope); <del> }}); <del> } <del> if (nodeName == 'OPTION') { <del> var html = jQuery('<select/>').append(jQuery(node).clone()).html(); <del> if (!html.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)) { <del> if (Binder.hasBinding(node.text)) { <del> jQuery(node).attr('ng:bind-attr', angular.toJson({'value':node.text})); <del> } else { <del> node.value = node.text; <del> } <del> } <del> } <del> <del> var children = node.childNodes; <del> for (var k = 0; k < children.length; k++) { <del> this.precompileNode(children[k], path.concat(k), factories); <del> } <del> }, <del> <del> ng_eval: function(node) { <del> return new EvalUpdater(node, node.getAttribute('ng:eval')); <del> }, <del> <del> ng_bind: function(node) { <del> return new BindUpdater(node, "{{" + node.getAttribute('ng:bind') + "}}"); <del> }, <del> <del> ng_bind_attr: function(node) { <del> return new BindAttrUpdater(node, fromJson(node.getAttribute('ng:bind-attr'))); <del> }, <del> <del> ng_hide: function(node) { <del> return new HideUpdater(node, node.getAttribute('ng:hide')); <del> }, <del> <del> ng_show: function(node) { <del> return new ShowUpdater(node, node.getAttribute('ng:show')); <del> }, <del> <del> ng_class: function(node) { <del> return new ClassUpdater(node, node.getAttribute('ng:class')); <del> }, <del> <del> ng_class_even: function(node) { <del> return new ClassEvenUpdater(node, node.getAttribute('ng:class-even')); <del> }, <del> <del> ng_class_odd: function(node) { <del> return new ClassOddUpdater(node, node.getAttribute('ng:class-odd')); <del> }, <del> <del> ng_style: function(node) { <del> return new StyleUpdater(node, node.getAttribute('ng:style')); <del> }, <del> <del> ng_watch: function(node, scope) { <del> scope.watch(node.getAttribute('ng:watch')); <del> } <del>}; <ide><path>src/delete/Model.js <del>// Single $ is special and does not get searched <del>// Double $$ is special an is client only (does not get sent to server) <del> <del>function Model(entity, initial) { <del> this['$$entity'] = entity; <del> this['$loadFrom'](initial||{}); <del> this['$entity'] = entity['title']; <del> this['$migrate'](); <del>}; <del> <del>Model.copyDirectFields = function(src, dst) { <del> if (src === dst || !src || !dst) return; <del> var isDataField = function(src, dst, field) { <del> return (field.substring(0,2) !== '$$') && <del> (typeof src[field] !== 'function') && <del> (typeof dst[field] !== 'function'); <del> }; <del> for (var field in dst) { <del> if (isDataField(src, dst, field)) <del> delete dst[field]; <del> } <del> for (field in src) { <del> if (isDataField(src, dst, field)) <del> dst[field] = src[field]; <del> } <del>}; <del> <del>extend(Model.prototype, { <del> '$migrate': function() { <del> merge(this['$$entity']['defaults'], this); <del> return this; <del> }, <del> <del> '$merge': function(other) { <del> merge(other, this); <del> return this; <del> }, <del> <del> '$save': function(callback) { <del> this['$$entity'].datastore.save(this, callback === true ? undefined : callback); <del> if (callback === true) this['$$entity'].datastore.flush(); <del> return this; <del> }, <del> <del> '$delete': function(callback) { <del> this['$$entity'].datastore.remove(this, callback === true ? undefined : callback); <del> if (callback === true) this['$$entity'].datastore.flush(); <del> return this; <del> }, <del> <del> '$loadById': function(id, callback) { <del> this['$$entity'].datastore.load(this, id, callback); <del> return this; <del> }, <del> <del> '$loadFrom': function(other) { <del> Model.copyDirectFields(other, this); <del> return this; <del> }, <del> <del> '$saveTo': function(other) { <del> Model.copyDirectFields(this, other); <del> return this; <del> } <del>}); <ide>\ No newline at end of file <ide><path>src/delete/Scope.js <del>function Scope(initialState, name) { <del> var self = this; <del> self.widgets = []; <del> self.evals = []; <del> self.watchListeners = {}; <del> self.name = name; <del> initialState = initialState || {}; <del> var State = function(){}; <del> State.prototype = initialState; <del> self.state = new State(); <del> extend(self.state, { <del> '$parent': initialState, <del> '$watch': bind(self, self.addWatchListener), <del> '$eval': bind(self, self.eval), <del> '$bind': bind(self, bind, self), <del> // change name to autoEval? <del> '$addEval': bind(self, self.addEval), <del> '$updateView': bind(self, self.updateView) <del> }); <del> if (name == "ROOT") { <del> self.state['$root'] = self.state; <del> } <del>}; <del> <del>Scope.expressionCache = {}; <del>Scope.getter = function(instance, path) { <del> if (!path) return instance; <del> var element = path.split('.'); <del> var key; <del> var lastInstance = instance; <del> var len = element.length; <del> for ( var i = 0; i < len; i++) { <del> key = element[i]; <del> if (!key.match(/^[\$\w][\$\w\d]*$/)) <del> throw "Expression '" + path + "' is not a valid expression for accesing variables."; <del> if (instance) { <del> lastInstance = instance; <del> instance = instance[key]; <del> } <del> if (_.isUndefined(instance) && key.charAt(0) == '$') { <del> var type = angular['Global']['typeOf'](lastInstance); <del> type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; <del> var fn = type ? type[[key.substring(1)]] : undefined; <del> if (fn) { <del> instance = _.bind(fn, lastInstance, lastInstance); <del> return instance; <del> } <del> } <del> } <del> if (typeof instance === 'function' && !instance['$$factory']) { <del> return bind(lastInstance, instance); <del> } <del> return instance; <del>}; <del> <del>Scope.setter = function(instance, path, value){ <del> var element = path.split('.'); <del> for ( var i = 0; element.length > 1; i++) { <del> var key = element.shift(); <del> var newInstance = instance[key]; <del> if (!newInstance) { <del> newInstance = {}; <del> instance[key] = newInstance; <del> } <del> instance = newInstance; <del> } <del> instance[element.shift()] = value; <del> return value; <del>}; <del> <del>Scope.prototype = { <del> // TODO: rename to update? or eval? <del> updateView: function() { <del> var self = this; <del> this.fireWatchers(); <del> foreach(this.widgets, function(widget){ <del> self.evalWidget(widget, "", {}, function(){ <del> this.updateView(self); <del> }); <del> }); <del> foreach(this.evals, bind(this, this.apply)); <del> }, <del> <del> addWidget: function(controller) { <del> if (controller) this.widgets.push(controller); <del> }, <del> <del> addEval: function(fn, listener) { <del> // todo: this should take a function/string and a listener <del> // todo: this is a hack, which will need to be cleaned up. <del> var self = this, <del> listenFn = listener || noop, <del> expr = self.compile(fn); <del> this.evals.push(function(){ <del> self.apply(listenFn, expr()); <del> }); <del> }, <del> <del> isProperty: function(exp) { <del> for ( var i = 0; i < exp.length; i++) { <del> var ch = exp.charAt(i); <del> if (ch!='.' && !Lexer.prototype.isIdent(ch)) { <del> return false; <del> } <del> } <del> return true; <del> }, <del> <del> get: function(path) { <del>// log('SCOPE.get', path, Scope.getter(this.state, path)); <del> return Scope.getter(this.state, path); <del> }, <del> <del> set: function(path, value) { <del>// log('SCOPE.set', path, value); <del> var instance = this.state; <del> return Scope.setter(instance, path, value); <del> }, <del> <del> setEval: function(expressionText, value) { <del> this.eval(expressionText + "=" + toJson(value)); <del> }, <del> <del> compile: function(exp) { <del> if (isFunction(exp)) return bind(this.state, exp); <del> var expFn = Scope.expressionCache[exp], self = this; <del> if (!expFn) { <del> var parser = new Parser(exp); <del> expFn = parser.statements(); <del> parser.assertAllConsumed(); <del> Scope.expressionCache[exp] = expFn; <del> } <del> return function(context){ <del> context = context || {}; <del> context.self = self.state; <del> context.scope = self; <del> return expFn.call(self, context); <del> }; <del> }, <del> <del> eval: function(exp, context) { <del>// log('Scope.eval', expressionText); <del> return this.compile(exp)(context); <del> }, <del> <del> //TODO: Refactor. This function needs to be an execution closure for widgets <del> // move to widgets <del> // remove expression, just have inner closure. <del> evalWidget: function(widget, expression, context, onSuccess, onFailure) { <del> try { <del> var value = this.eval(expression, context); <del> if (widget.hasError) { <del> widget.hasError = false; <del> jQuery(widget.view). <del> removeClass('ng-exception'). <del> removeAttr('ng-error'); <del> } <del> if (onSuccess) { <del> value = onSuccess.apply(widget, [value]); <del> } <del> return true; <del> } catch (e){ <del> var jsonError = toJson(e, true); <del> error('Eval Widget Error:', jsonError); <del> widget.hasError = true; <del> jQuery(widget.view). <del> addClass('ng-exception'). <del> attr('ng-error', jsonError); <del> if (onFailure) { <del> onFailure.apply(widget, [e, jsonError]); <del> } <del> return false; <del> } <del> }, <del> <del> validate: function(expressionText, value, element) { <del> var expression = Scope.expressionCache[expressionText]; <del> if (!expression) { <del> expression = new Parser(expressionText).validator(); <del> Scope.expressionCache[expressionText] = expression; <del> } <del> var self = {scope:this, self:this.state, '$element':element}; <del> return expression(self)(self, value); <del> }, <del> <del> entity: function(entityDeclaration, datastore) { <del> var expression = new Parser(entityDeclaration).entityDeclaration(); <del> return expression({scope:this, datastore:datastore}); <del> }, <del> <del> clearInvalid: function() { <del> var invalid = this.state['$invalidWidgets']; <del> while(invalid.length > 0) {invalid.pop();} <del> }, <del> <del> markInvalid: function(widget) { <del> this.state['$invalidWidgets'].push(widget); <del> }, <del> <del> watch: function(declaration) { <del> var self = this; <del> new Parser(declaration).watch()({ <del> scope:this, <del> addListener:function(watch, exp){ <del> self.addWatchListener(watch, function(n,o){ <del> try { <del> return exp({scope:self}, n, o); <del> } catch(e) { <del> alert(e); <del> } <del> }); <del> } <del> }); <del> }, <del> <del> addWatchListener: function(watchExpression, listener) { <del> // TODO: clean me up! <del> if (!isFunction(listener)) { <del> listener = this.compile(listener); <del> } <del> var watcher = this.watchListeners[watchExpression]; <del> if (!watcher) { <del> watcher = {listeners:[], expression:watchExpression}; <del> this.watchListeners[watchExpression] = watcher; <del> } <del> watcher.listeners.push(listener); <del> }, <del> <del> fireWatchers: function() { <del> var self = this, fired = false; <del> foreach(this.watchListeners, function(watcher) { <del> var value = self.eval(watcher.expression); <del> if (value !== watcher.lastValue) { <del> foreach(watcher.listeners, function(listener){ <del> listener(value, watcher.lastValue); <del> fired = true; <del> }); <del> watcher.lastValue = value; <del> } <del> }); <del> return fired; <del> }, <del> <del> apply: function(fn) { <del> fn.apply(this.state, slice.call(arguments, 1, arguments.length)); <del> } <del>}; <del> <del>////////////////////////////// <del> <del>function getter(instance, path) { <del> if (!path) return instance; <del> var element = path.split('.'); <del> var key; <del> var lastInstance = instance; <del> var len = element.length; <del> for ( var i = 0; i < len; i++) { <del> key = element[i]; <del> if (!key.match(/^[\$\w][\$\w\d]*$/)) <del> throw "Expression '" + path + "' is not a valid expression for accesing variables."; <del> if (instance) { <del> lastInstance = instance; <del> instance = instance[key]; <del> } <del> if (_.isUndefined(instance) && key.charAt(0) == '$') { <del> var type = angular['Global']['typeOf'](lastInstance); <del> type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; <del> var fn = type ? type[[key.substring(1)]] : undefined; <del> if (fn) { <del> instance = _.bind(fn, lastInstance, lastInstance); <del> return instance; <del> } <del> } <del> } <del> if (typeof instance === 'function' && !instance['$$factory']) { <del> return bind(lastInstance, instance); <del> } <del> return instance; <del>}; <del> <del>function setter(instance, path, value){ <del> var element = path.split('.'); <del> for ( var i = 0; element.length > 1; i++) { <del> var key = element.shift(); <del> var newInstance = instance[key]; <del> if (!newInstance) { <del> newInstance = {}; <del> instance[key] = newInstance; <del> } <del> instance = newInstance; <del> } <del> instance[element.shift()] = value; <del> return value; <del>}; <del> <del>var compileCache = {}; <del>function expressionCompile(exp){ <del> if (isFunction(exp)) return exp; <del> var expFn = compileCache[exp]; <del> if (!expFn) { <del> var parser = new Parser(exp); <del> expFn = parser.statements(); <del> parser.assertAllConsumed(); <del> compileCache[exp] = expFn; <del> } <del> // return expFn <del> // TODO(remove this hack) <del> return function(){ <del> return expFn({ <del> scope: { <del> set: this.$set, <del> get: this.$get <del> } <del> }); <del> }; <del>}; <del> <del>var NON_RENDERABLE_ELEMENTS = { <del> '#text': 1, '#comment':1, 'TR':1, 'TH':1 <del>}; <del> <del>function isRenderableElement(element){ <del> return element && element[0] && !NON_RENDERABLE_ELEMENTS[element[0].nodeName]; <del>} <del> <del>function rethrow(e) { throw e; } <del>function errorHandlerFor(element) { <del> while (!isRenderableElement(element)) { <del> element = element.parent() || jqLite(document.body); <del> } <del> return function(error) { <del> element.attr('ng-error', angular.toJson(error)); <del> element.addClass('ng-exception'); <del> }; <del>} <del> <del>function createScope(parent, Class) { <del> function Parent(){} <del> function API(){} <del> function Behavior(){} <del> <del> var instance, behavior, api, watchList = [], evalList = []; <del> <del> Class = Class || noop; <del> parent = Parent.prototype = parent || {}; <del> api = API.prototype = new Parent(); <del> behavior = Behavior.prototype = extend(new API(), Class.prototype); <del> instance = new Behavior(); <del> <del> extend(api, { <del> $parent: parent, <del> $bind: bind(instance, bind, instance), <del> $get: bind(instance, getter, instance), <del> $set: bind(instance, setter, instance), <del> <del> $eval: function(exp) { <del> if (isDefined(exp)) { <del> return expressionCompile(exp).apply(instance, slice.call(arguments, 1, arguments.length)); <del> } else { <del> foreach(evalList, function(eval) { <del> instance.$tryEval(eval.fn, eval.handler); <del> }); <del> foreach(watchList, function(watch) { <del> var value = instance.$tryEval(watch.watch, watch.handler); <del> if (watch.last !== value) { <del> instance.$tryEval(watch.listener, watch.handler, value, watch.last); <del> watch.last = value; <del> } <del> }); <del> } <del> }, <del> <del> $tryEval: function (expression, exceptionHandler) { <del> try { <del> return expressionCompile(expression).apply(instance, slice.call(arguments, 2, arguments.length)); <del> } catch (e) { <del> error(e); <del> if (isFunction(exceptionHandler)) { <del> exceptionHandler(e); <del> } else if (exceptionHandler) { <del> errorHandlerFor(exceptionHandler)(e); <del> } <del> } <del> }, <del> <del> $watch: function(watchExp, listener, exceptionHandler) { <del> var watch = expressionCompile(watchExp); <del> watchList.push({ <del> watch: watch, <del> last: watch.call(instance), <del> handler: exceptionHandler, <del> listener:expressionCompile(listener) <del> }); <del> }, <del> <del> $onEval: function(expr, exceptionHandler){ <del> evalList.push({ <del> fn: expressionCompile(expr), <del> handler: exceptionHandler <del> }); <del> } <del> }); <del> <del> Class.apply(instance, slice.call(arguments, 2, arguments.length)); <del> <del> return instance; <del>} <ide><path>src/delete/Widgets.js <del>function WidgetFactory(serverUrl, database) { <del> this.nextUploadId = 0; <del> this.serverUrl = serverUrl; <del> this.database = database; <del> if (window['swfobject']) { <del> this.createSWF = window['swfobject']['createSWF']; <del> } else { <del> this.createSWF = function(){ <del> alert("ERROR: swfobject not loaded!"); <del> }; <del> } <del>}; <del> <del>WidgetFactory.prototype = { <del> createController: function(input, scope) { <del> var controller; <del> var type = input.attr('type').toLowerCase(); <del> var exp = input.attr('name'); <del> if (exp) exp = exp.split(':').pop(); <del> var event = "change"; <del> var bubbleEvent = true; <del> var formatter = angularFormatter[input.attr('ng:format')] || angularFormatter['noop']; <del> if (type == 'button' || type == 'submit' || type == 'reset' || type == 'image') { <del> controller = new ButtonController(input[0], exp, formatter); <del> event = "click"; <del> bubbleEvent = false; <del> } else if (type == 'text' || type == 'textarea' || type == 'hidden' || type == 'password') { <del> controller = new TextController(input[0], exp, formatter); <del> event = "keyup change"; <del> } else if (type == 'checkbox') { <del> controller = new CheckboxController(input[0], exp, formatter); <del> event = "click"; <del> } else if (type == 'radio') { <del> controller = new RadioController(input[0], exp, formatter); <del> event="click"; <del> } else if (type == 'select-one') { <del> controller = new SelectController(input[0], exp, formatter); <del> } else if (type == 'select-multiple') { <del> controller = new MultiSelectController(input[0], exp, formatter); <del> } else if (type == 'file') { <del> controller = this.createFileController(input, exp, formatter); <del> } else { <del> throw 'Unknown type: ' + type; <del> } <del> input.data('controller', controller); <del> var updateView = scope.get('$updateView'); <del> var action = function() { <del> if (controller.updateModel(scope)) { <del> var action = jQuery(controller.view).attr('ng-action') || ""; <del> if (scope.evalWidget(controller, action)) { <del> updateView(scope); <del> } <del> } <del> return bubbleEvent; <del> }; <del> jQuery(controller.view, ":input"). <del> bind(event, action); <del> return controller; <del> }, <del> <del> createFileController: function(fileInput) { <del> var uploadId = '__uploadWidget_' + (this.nextUploadId++); <del> var view = FileController.template(uploadId); <del> fileInput.after(view); <del> var att = { <del> 'data':this.serverUrl + "/admin/ServerAPI.swf", <del> 'width':"95", 'height':"20", 'align':"top", <del> 'wmode':"transparent"}; <del> var par = { <del> 'flashvars':"uploadWidgetId=" + uploadId, <del> 'allowScriptAccess':"always"}; <del> var swfNode = this.createSWF(att, par, uploadId); <del> fileInput.remove(); <del> var cntl = new FileController(view, fileInput[0].name, swfNode, this.serverUrl + "/data/" + this.database); <del> jQuery(swfNode).parent().data('controller', cntl); <del> return cntl; <del> } <del>}; <del>///////////////////// <del>// FileController <del>/////////////////////// <del> <del>function FileController(view, scopeName, uploader, databaseUrl) { <del> this.view = view; <del> this.uploader = uploader; <del> this.scopeName = scopeName; <del> this.attachmentsPath = databaseUrl + '/_attachments'; <del> this.value = null; <del> this.lastValue = undefined; <del>}; <del> <del>angularCallbacks['flashEvent'] = function(id, event, args) { <del> var object = document.getElementById(id); <del> var jobject = jQuery(object); <del> var controller = jobject.parent().data("controller"); <del> FileController.prototype[event].apply(controller, args); <del> _.defer(jobject.scope().get('$updateView')); <del>}; <del> <del>FileController.template = function(id) { <del> return jQuery('<span class="ng-upload-widget">' + <del> '<input type="checkbox" ng:non-bindable="true"/>' + <del> '<object id="' + id + '" />' + <del> '<a></a>' + <del> '<span/>' + <del> '</span>'); <del>}; <del> <del>extend(FileController.prototype, { <del> 'cancel': noop, <del> 'complete': noop, <del> 'httpStatus': function(status) { <del> alert("httpStatus:" + this.scopeName + " status:" + status); <del> }, <del> 'ioError': function() { <del> alert("ioError:" + this.scopeName); <del> }, <del> 'open': function() { <del> alert("open:" + this.scopeName); <del> }, <del> 'progress':noop, <del> 'securityError': function() { <del> alert("securityError:" + this.scopeName); <del> }, <del> 'uploadCompleteData': function(data) { <del> var value = fromJson(data); <del> value.url = this.attachmentsPath + '/' + value.id + '/' + value.text; <del> this.view.find("input").attr('checked', true); <del> var scope = this.view.scope(); <del> this.value = value; <del> this.updateModel(scope); <del> this.value = null; <del> }, <del> 'select': function(name, size, type) { <del> this.name = name; <del> this.view.find("a").text(name).attr('href', name); <del> this.view.find("span").text(angular['filter']['bytes'](size)); <del> this.upload(); <del> }, <del> <del> updateModel: function(scope) { <del> var isChecked = this.view.find("input").attr('checked'); <del> var value = isChecked ? this.value : null; <del> if (this.lastValue === value) { <del> return false; <del> } else { <del> scope.set(this.scopeName, value); <del> return true; <del> } <del> }, <del> <del> updateView: function(scope) { <del> var modelValue = scope.get(this.scopeName); <del> if (modelValue && this.value !== modelValue) { <del> this.value = modelValue; <del> this.view.find("a"). <del> attr("href", this.value.url). <del> text(this.value.text); <del> this.view.find("span").text(angular['filter']['bytes'](this.value.size)); <del> } <del> this.view.find("input").attr('checked', !!modelValue); <del> }, <del> <del> upload: function() { <del> if (this.name) { <del> this.uploader['uploadFile'](this.attachmentsPath); <del> } <del> } <del>}); <del> <del>/////////////////////// <del>// NullController <del>/////////////////////// <del>function NullController(view) {this.view = view;}; <del>NullController.prototype = { <del> updateModel: function() { return true; }, <del> updateView: noop <del>}; <del>NullController.instance = new NullController(); <del> <del> <del>/////////////////////// <del>// ButtonController <del>/////////////////////// <del>var ButtonController = NullController; <del> <del>/////////////////////// <del>// TextController <del>/////////////////////// <del>function TextController(view, exp, formatter) { <del> this.view = view; <del> this.formatter = formatter; <del> this.exp = exp; <del> this.validator = view.getAttribute('ng:validate'); <del> this.required = typeof view.attributes['ng:required'] != "undefined"; <del> this.lastErrorText = null; <del> this.lastValue = undefined; <del> this.initialValue = this.formatter['parse'](view.value); <del> var widget = view.getAttribute('ng-widget'); <del> if (widget === 'datepicker') { <del> jQuery(view).datepicker(); <del> } <del>}; <del> <del>TextController.prototype = { <del> updateModel: function(scope) { <del> var value = this.formatter['parse'](this.view.value); <del> if (this.lastValue === value) { <del> return false; <del> } else { <del> scope.setEval(this.exp, value); <del> this.lastValue = value; <del> return true; <del> } <del> }, <del> <del> updateView: function(scope) { <del> var view = this.view; <del> var value = scope.get(this.exp); <del> if (typeof value === "undefined") { <del> value = this.initialValue; <del> scope.setEval(this.exp, value); <del> } <del> value = value ? value : ''; <del> if (!_(this.lastValue).isEqual(value)) { <del> view.value = this.formatter['format'](value); <del> this.lastValue = value; <del> } <del> <del> var isValidationError = false; <del> view.removeAttribute('ng-error'); <del> if (this.required) { <del> isValidationError = !(value && $.trim("" + value).length > 0); <del> } <del> var errorText = isValidationError ? "Required Value" : null; <del> if (!isValidationError && this.validator && value) { <del> errorText = scope.validate(this.validator, value, view); <del> isValidationError = !!errorText; <del> } <del> if (this.lastErrorText !== errorText) { <del> this.lastErrorText = isValidationError; <del> if (errorText && isVisible(view)) { <del> view.setAttribute('ng-error', errorText); <del> scope.markInvalid(this); <del> } <del> jQuery(view).toggleClass('ng-validation-error', isValidationError); <del> } <del> } <del>}; <del> <del>/////////////////////// <del>// CheckboxController <del>/////////////////////// <del>function CheckboxController(view, exp, formatter) { <del> this.view = view; <del> this.exp = exp; <del> this.lastValue = undefined; <del> this.formatter = formatter; <del> this.initialValue = this.formatter['parse'](view.checked ? view.value : ""); <del>}; <del> <del>CheckboxController.prototype = { <del> updateModel: function(scope) { <del> var input = this.view; <del> var value = input.checked ? input.value : ''; <del> value = this.formatter['parse'](value); <del> value = this.formatter['format'](value); <del> if (this.lastValue === value) { <del> return false; <del> } else { <del> scope.setEval(this.exp, this.formatter['parse'](value)); <del> this.lastValue = value; <del> return true; <del> } <del> }, <del> <del> updateView: function(scope) { <del> var input = this.view; <del> var value = scope.eval(this.exp); <del> if (typeof value === "undefined") { <del> value = this.initialValue; <del> scope.setEval(this.exp, value); <del> } <del> input.checked = this.formatter['parse'](input.value) == value; <del> } <del>}; <del> <del>/////////////////////// <del>// SelectController <del>/////////////////////// <del>function SelectController(view, exp) { <del> this.view = view; <del> this.exp = exp; <del> this.lastValue = undefined; <del> this.initialValue = view.value; <del>}; <del> <del>SelectController.prototype = { <del> updateModel: function(scope) { <del> var input = this.view; <del> if (input.selectedIndex < 0) { <del> scope.setEval(this.exp, null); <del> } else { <del> var value = this.view.value; <del> if (this.lastValue === value) { <del> return false; <del> } else { <del> scope.setEval(this.exp, value); <del> this.lastValue = value; <del> return true; <del> } <del> } <del> }, <del> <del> updateView: function(scope) { <del> var input = this.view; <del> var value = scope.get(this.exp); <del> if (typeof value === 'undefined') { <del> value = this.initialValue; <del> scope.setEval(this.exp, value); <del> } <del> if (value !== this.lastValue) { <del> input.value = value ? value : ""; <del> this.lastValue = value; <del> } <del> } <del>}; <del> <del>/////////////////////// <del>// MultiSelectController <del>/////////////////////// <del>function MultiSelectController(view, exp) { <del> this.view = view; <del> this.exp = exp; <del> this.lastValue = undefined; <del> this.initialValue = this.selected(); <del>}; <del> <del>MultiSelectController.prototype = { <del> selected: function () { <del> var value = []; <del> var options = this.view.options; <del> for ( var i = 0; i < options.length; i++) { <del> var option = options[i]; <del> if (option.selected) { <del> value.push(option.value); <del> } <del> } <del> return value; <del> }, <del> <del> updateModel: function(scope) { <del> var value = this.selected(); <del> // TODO: This is wrong! no caching going on here as we are always comparing arrays <del> if (this.lastValue === value) { <del> return false; <del> } else { <del> scope.setEval(this.exp, value); <del> this.lastValue = value; <del> return true; <del> } <del> }, <del> <del> updateView: function(scope) { <del> var input = this.view; <del> var selected = scope.get(this.exp); <del> if (typeof selected === "undefined") { <del> selected = this.initialValue; <del> scope.setEval(this.exp, selected); <del> } <del> if (selected !== this.lastValue) { <del> var options = input.options; <del> for ( var i = 0; i < options.length; i++) { <del> var option = options[i]; <del> option.selected = _.include(selected, option.value); <del> } <del> this.lastValue = selected; <del> } <del> } <del>}; <del> <del>/////////////////////// <del>// RadioController <del>/////////////////////// <del>function RadioController(view, exp) { <del> this.view = view; <del> this.exp = exp; <del> this.lastChecked = undefined; <del> this.lastValue = undefined; <del> this.inputValue = view.value; <del> this.initialValue = view.checked ? view.value : null; <del>}; <del> <del>RadioController.prototype = { <del> updateModel: function(scope) { <del> var input = this.view; <del> if (this.lastChecked) { <del> return false; <del> } else { <del> input.checked = true; <del> this.lastValue = scope.setEval(this.exp, this.inputValue); <del> this.lastChecked = true; <del> return true; <del> } <del> }, <del> <del> updateView: function(scope) { <del> var input = this.view; <del> var value = scope.get(this.exp); <del> if (this.initialValue && typeof value === "undefined") { <del> value = this.initialValue; <del> scope.setEval(this.exp, value); <del> } <del> if (this.lastValue != value) { <del> this.lastChecked = input.checked = this.inputValue == (''+value); <del> this.lastValue = value; <del> } <del> } <del>}; <del> <del>/////////////////////// <del>//ElementController <del>/////////////////////// <del>function BindUpdater(view, exp) { <del> this.view = view; <del> this.exp = Binder.parseBindings(exp); <del> this.hasError = false; <del>}; <del> <del>BindUpdater.toText = function(obj) { <del> var e = escapeHtml; <del> switch(typeof obj) { <del> case "string": <del> case "boolean": <del> case "number": <del> return e(obj); <del> case "function": <del> return BindUpdater.toText(obj()); <del> case "object": <del> if (isNode(obj)) { <del> return outerHTML(obj); <del> } else if (obj instanceof angular.filter.Meta) { <del> switch(typeof obj.html) { <del> case "string": <del> case "number": <del> return obj.html; <del> case "function": <del> return obj.html(); <del> case "object": <del> if (isNode(obj.html)) <del> return outerHTML(obj.html); <del> default: <del> break; <del> } <del> switch(typeof obj.text) { <del> case "string": <del> case "number": <del> return e(obj.text); <del> case "function": <del> return e(obj.text()); <del> default: <del> break; <del> } <del> } <del> if (obj === null) <del> return ""; <del> return e(toJson(obj, true)); <del> default: <del> return ""; <del> } <del>}; <del> <del>BindUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> var html = []; <del> var parts = this.exp; <del> var length = parts.length; <del> for(var i=0; i<length; i++) { <del> var part = parts[i]; <del> var binding = Binder.binding(part); <del> if (binding) { <del> scope.evalWidget(this, binding, {$element:this.view}, function(value){ <del> html.push(BindUpdater.toText(value)); <del> }, function(e, text){ <del> setHtml(this.view, text); <del> }); <del> if (this.hasError) { <del> return; <del> } <del> } else { <del> html.push(escapeHtml(part)); <del> } <del> } <del> setHtml(this.view, html.join('')); <del> } <del>}; <del> <del>function BindAttrUpdater(view, attrs) { <del> this.view = view; <del> this.attrs = attrs; <del>}; <del> <del>BindAttrUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> var jNode = jQuery(this.view); <del> var attributeTemplates = this.attrs; <del> if (this.hasError) { <del> this.hasError = false; <del> jNode. <del> removeClass('ng-exception'). <del> removeAttr('ng-error'); <del> } <del> var isImage = jNode.is('img'); <del> for (var attrName in attributeTemplates) { <del> var attributeTemplate = Binder.parseBindings(attributeTemplates[attrName]); <del> var attrValues = []; <del> for ( var i = 0; i < attributeTemplate.length; i++) { <del> var binding = Binder.binding(attributeTemplate[i]); <del> if (binding) { <del> try { <del> var value = scope.eval(binding, {$element:jNode[0], attrName:attrName}); <del> if (value && (value.constructor !== array || value.length !== 0)) <del> attrValues.push(value); <del> } catch (e) { <del> this.hasError = true; <del> error('BindAttrUpdater', e); <del> var jsonError = toJson(e, true); <del> attrValues.push('[' + jsonError + ']'); <del> jNode. <del> addClass('ng-exception'). <del> attr('ng-error', jsonError); <del> } <del> } else { <del> attrValues.push(attributeTemplate[i]); <del> } <del> } <del> var attrValue = attrValues.length ? attrValues.join('') : null; <del> if(isImage && attrName == 'src' && !attrValue) <del> attrValue = scope.get('$config.blankImage'); <del> jNode.attr(attrName, attrValue); <del> } <del> } <del>}; <del> <del>function EvalUpdater(view, exp) { <del> this.view = view; <del> this.exp = exp; <del> this.hasError = false; <del>}; <del>EvalUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp); <del> } <del>}; <del> <del>function HideUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>HideUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(hideValue){ <del> var view = jQuery(this.view); <del> if (toBoolean(hideValue)) { <del> view.hide(); <del> } else { <del> view.show(); <del> } <del> }); <del> } <del>}; <del> <del>function ShowUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>ShowUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(hideValue){ <del> var view = jQuery(this.view); <del> if (toBoolean(hideValue)) { <del> view.show(); <del> } else { <del> view.hide(); <del> } <del> }); <del> } <del>}; <del> <del>function ClassUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>ClassUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(classValue){ <del> if (classValue !== null && classValue !== undefined) { <del> this.view.className = classValue; <del> } <del> }); <del> } <del>}; <del> <del>function ClassEvenUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>ClassEvenUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(classValue){ <del> var index = scope.get('$index'); <del> jQuery(this.view).toggleClass(classValue, index % 2 === 1); <del> }); <del> } <del>}; <del> <del>function ClassOddUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>ClassOddUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(classValue){ <del> var index = scope.get('$index'); <del> jQuery(this.view).toggleClass(classValue, index % 2 === 0); <del> }); <del> } <del>}; <del> <del>function StyleUpdater(view, exp) { this.view = view; this.exp = exp; }; <del>StyleUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.exp, {}, function(styleValue){ <del> jQuery(this.view).attr('style', "").css(styleValue); <del> }); <del> } <del>}; <del> <del>/////////////////////// <del>// RepeaterUpdater <del>/////////////////////// <del>function RepeaterUpdater(view, repeaterExpression, template, prefix) { <del> this.view = view; <del> this.template = template; <del> this.prefix = prefix; <del> this.children = []; <del> var match = repeaterExpression.match(/^\s*(.+)\s+in\s+(.*)\s*$/); <del> if (! match) { <del> throw "Expected ng:repeat in form of 'item in collection' but got '" + <del> repeaterExpression + "'."; <del> } <del> var keyValue = match[1]; <del> this.iteratorExp = match[2]; <del> match = keyValue.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); <del> if (!match) { <del> throw "'item' in 'item in collection' should be identifier or (key, value) but get '" + <del> keyValue + "'."; <del> } <del> this.valueExp = match[3] || match[1]; <del> this.keyExp = match[2]; <del>}; <del> <del>RepeaterUpdater.prototype = { <del> updateModel: noop, <del> updateView: function(scope) { <del> scope.evalWidget(this, this.iteratorExp, {}, function(iterator){ <del> var self = this; <del> if (!iterator) { <del> iterator = []; <del> if (scope.isProperty(this.iteratorExp)) { <del> scope.set(this.iteratorExp, iterator); <del> } <del> } <del> var childrenLength = this.children.length; <del> var cursor = this.view; <del> var time = 0; <del> var child = null; <del> var keyExp = this.keyExp; <del> var valueExp = this.valueExp; <del> var iteratorCounter = 0; <del> foreach(iterator, function(value, key){ <del> if (iteratorCounter < childrenLength) { <del> // reuse children <del> child = self.children[iteratorCounter]; <del> child.scope.set(valueExp, value); <del> } else { <del> // grow children <del> var name = self.prefix + <del> valueExp + " in " + self.iteratorExp + "[" + iteratorCounter + "]"; <del> var childScope = new Scope(scope.state, name); <del> childScope.set('$index', iteratorCounter); <del> if (keyExp) <del> childScope.set(keyExp, key); <del> childScope.set(valueExp, value); <del> child = { scope:childScope, element:self.template(childScope, self.prefix, iteratorCounter) }; <del> cursor.after(child.element); <del> self.children.push(child); <del> } <del> cursor = child.element; <del> var s = new Date().getTime(); <del> child.scope.updateView(); <del> time += new Date().getTime() - s; <del> iteratorCounter++; <del> }); <del> // shrink children <del> for ( var r = childrenLength; r > iteratorCounter; --r) { <del> this.children.pop().element.remove(); <del> } <del> // Special case for option in select <del> if (child && child.element[0].nodeName === "OPTION") { <del> var select = jQuery(child.element[0].parentNode); <del> var cntl = select.data('controller'); <del> if (cntl) { <del> cntl.lastValue = undefined; <del> cntl.updateView(scope); <del> } <del> } <del> }); <del> } <del>}; <del> <del>////////////////////////////////// <del>// PopUp <del>////////////////////////////////// <del> <del>function PopUp(doc) { <del> this.doc = doc; <del>}; <del> <del>PopUp.OUT_EVENT = "mouseleave mouseout click dblclick keypress keyup"; <del> <del>PopUp.onOver = function(e) { <del> PopUp.onOut(); <del> var jNode = jQuery(this); <del> jNode.bind(PopUp.OUT_EVENT, PopUp.onOut); <del> var position = jNode.position(); <del> var de = document.documentElement; <del> var w = self.innerWidth || (de && de.clientWidth) || document.body.clientWidth; <del> var hasArea = w - position.left; <del> var width = 300; <del> var title = jNode.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."; <del> var msg = jNode.attr("ng-error"); <del> <del> var x; <del> var arrowPos = hasArea>(width+75) ? "left" : "right"; <del> var tip = jQuery( <del> "<div id='ng-callout' style='width:"+width+"px'>" + <del> "<div class='ng-arrow-"+arrowPos+"'/>" + <del> "<div class='ng-title'>"+title+"</div>" + <del> "<div class='ng-content'>"+msg+"</div>" + <del> "</div>"); <del> jQuery("body").append(tip); <del> if(arrowPos === 'left'){ <del> x = position.left + this.offsetWidth + 11; <del> }else{ <del> x = position.left - (width + 15); <del> tip.find('.ng-arrow-right').css({left:width+1}); <del> } <del> <del> tip.css({left: x+"px", top: (position.top - 3)+"px"}); <del> return true; <del>}; <del> <del>PopUp.onOut = function() { <del> jQuery('#ng-callout'). <del> unbind(PopUp.OUT_EVENT, PopUp.onOut). <del> remove(); <del> return true; <del>}; <del> <del>PopUp.prototype = { <del> bind: function () { <del> var self = this; <del> this.doc.find('.ng-validation-error,.ng-exception'). <del> live("mouseover", PopUp.onOver); <del> } <del>}; <del> <del>////////////////////////////////// <del>// Status <del>////////////////////////////////// <del> <del>function NullStatus(body) { <del>}; <del> <del>NullStatus.prototype = { <del> beginRequest:function(){}, <del> endRequest:function(){} <del>}; <del> <del>function Status(body) { <del> this.requestCount = 0; <del> this.body = body; <del>}; <del> <del>Status.DOM ='<div id="ng-spacer"></div><div id="ng-loading">loading....</div>'; <del> <del>Status.prototype = { <del> beginRequest: function () { <del> if (this.requestCount === 0) { <del> (this.loader = this.loader || this.body.append(Status.DOM).find("#ng-loading")).show(); <del> } <del> this.requestCount++; <del> }, <del> <del> endRequest: function () { <del> this.requestCount--; <del> if (this.requestCount === 0) { <del> this.loader.hide("fold"); <del> } <del> } <del>}; <ide><path>src/moveToAngularCom/ControlBar.js <del>function ControlBar(document, serverUrl, database) { <del> this._document = document; <del> this.serverUrl = serverUrl; <del> this.database = database; <del> this._window = window; <del> this.callbacks = []; <del>}; <del> <del>ControlBar.HTML = <del> '<div>' + <del> '<div class="ui-widget-overlay"></div>' + <del> '<div id="ng-login" ng:non-bindable="true">' + <del> '<div class="ng-login-container"></div>' + <del> '</div>' + <del> '</div>'; <del> <del> <del>ControlBar.FORBIDEN = <del> '<div ng:non-bindable="true" title="Permission Error:">' + <del> 'Sorry, you do not have permission for this!'+ <del> '</div>'; <del> <del>ControlBar.prototype = { <del> bind: function () { <del> }, <del> <del> login: function (loginSubmitFn) { <del> this.callbacks.push(loginSubmitFn); <del> if (this.callbacks.length == 1) { <del> this.doTemplate("/user_session/new.mini?database="+encodeURIComponent(this.database)+"&return_url=" + encodeURIComponent(this.urlWithoutAnchor())); <del> } <del> }, <del> <del> logout: function (loginSubmitFn) { <del> this.callbacks.push(loginSubmitFn); <del> if (this.callbacks.length == 1) { <del> this.doTemplate("/user_session/do_destroy.mini"); <del> } <del> }, <del> <del> urlWithoutAnchor: function (path) { <del> return this._window['location']['href'].split("#")[0]; <del> }, <del> <del> doTemplate: function (path) { <del> var self = this; <del> var id = new Date().getTime(); <del> var url = this.urlWithoutAnchor() + "#$iframe_notify=" + id; <del> var iframeHeight = 330; <del> var loginView = jQuery('<div style="overflow:hidden; padding:2px 0 0 0;"><iframe name="'+ url +'" src="'+this.serverUrl + path + '" width="500" height="'+ iframeHeight +'"/></div>'); <del> this._document.append(loginView); <del> loginView['dialog']({ <del> 'height':iframeHeight + 33, 'width':500, <del> 'resizable': false, 'modal':true, <del> 'title': 'Authentication: <a href="http://www.getangular.com"><tt>&lt;angular/&gt;</tt></a>' <del> }); <del> angularCallbacks["_iframe_notify_" + id] = function() { <del> loginView['dialog']("destroy"); <del> loginView['remove'](); <del> foreach(self.callbacks, function(callback){ <del> callback(); <del> }); <del> self.callbacks = []; <del> }; <del> }, <del> <del> notAuthorized: function () { <del> if (this.forbidenView) return; <del> this.forbidenView = jQuery(ControlBar.FORBIDEN); <del> this.forbidenView.dialog({bgiframe:true, height:70, modal:true}); <del> } <del>}; <ide>\ No newline at end of file <ide><path>src/moveToAngularCom/DataStore.js <del>function DataStore(post, users, anchor) { <del> this.post = post; <del> this.users = users; <del> this._cache_collections = []; <del> this._cache = {'$collections':this._cache_collections}; <del> this.anchor = anchor; <del> this.bulkRequest = []; <del>}; <del> <del>DataStore.NullEntity = extend(function(){}, { <del> 'all': function(){return [];}, <del> 'query': function(){return [];}, <del> 'load': function(){return {};}, <del> 'title': undefined <del>}); <del> <del>DataStore.prototype = { <del> cache: function(document) { <del> if (! document.datastore === this) { <del> throw "Parameter must be an instance of Entity! " + toJson(document); <del> } <del> var key = document['$entity'] + '/' + document['$id']; <del> var cachedDocument = this._cache[key]; <del> if (cachedDocument) { <del> Model.copyDirectFields(document, cachedDocument); <del> } else { <del> this._cache[key] = document; <del> cachedDocument = document; <del> } <del> return cachedDocument; <del> }, <del> <del> load: function(instance, id, callback, failure) { <del> if (id && id !== '*') { <del> var self = this; <del> this._jsonRequest(["GET", instance['$entity'] + "/" + id], function(response) { <del> instance['$loadFrom'](response); <del> instance['$migrate'](); <del> var clone = instance['$$entity'](instance); <del> self.cache(clone); <del> (callback||noop)(instance); <del> }, failure); <del> } <del> return instance; <del> }, <del> <del> loadMany: function(entity, ids, callback) { <del> var self=this; <del> var list = []; <del> var callbackCount = 0; <del> foreach(ids, function(id){ <del> list.push(self.load(entity(), id, function(){ <del> callbackCount++; <del> if (callbackCount == ids.length) { <del> (callback||noop)(list); <del> } <del> })); <del> }); <del> return list; <del> }, <del> <del> loadOrCreate: function(instance, id, callback) { <del> var self=this; <del> return this.load(instance, id, callback, function(response){ <del> if (response['$status_code'] == 404) { <del> instance['$id'] = id; <del> (callback||noop)(instance); <del> } else { <del> throw response; <del> } <del> }); <del> }, <del> <del> loadAll: function(entity, callback) { <del> var self = this; <del> var list = []; <del> list['$$accept'] = function(doc){ <del> return doc['$entity'] == entity['title']; <del> }; <del> this._cache_collections.push(list); <del> this._jsonRequest(["GET", entity['title']], function(response) { <del> var rows = response; <del> for ( var i = 0; i < rows.length; i++) { <del> var document = entity(); <del> document['$loadFrom'](rows[i]); <del> list.push(self.cache(document)); <del> } <del> (callback||noop)(list); <del> }); <del> return list; <del> }, <del> <del> save: function(document, callback) { <del> var self = this; <del> var data = {}; <del> document['$saveTo'](data); <del> this._jsonRequest(["POST", "", data], function(response) { <del> document['$loadFrom'](response); <del> var cachedDoc = self.cache(document); <del> _.each(self._cache_collections, function(collection){ <del> if (collection['$$accept'](document)) { <del> angularArray['includeIf'](collection, cachedDoc, true); <del> } <del> }); <del> if (document['$$anchor']) { <del> self.anchor[document['$$anchor']] = document['$id']; <del> } <del> if (callback) <del> callback(document); <del> }); <del> }, <del> <del> remove: function(document, callback) { <del> var self = this; <del> var data = {}; <del> document['$saveTo'](data); <del> this._jsonRequest(["DELETE", "", data], function(response) { <del> delete self._cache[document['$entity'] + '/' + document['$id']]; <del> _.each(self._cache_collections, function(collection){ <del> for ( var i = 0; i < collection.length; i++) { <del> var item = collection[i]; <del> if (item['$id'] == document['$id']) { <del> collection.splice(i, 1); <del> } <del> } <del> }); <del> (callback||noop)(response); <del> }); <del> }, <del> <del> _jsonRequest: function(request, callback, failure) { <del> request['$$callback'] = callback; <del> request['$$failure'] = failure||function(response){ <del> throw response; <del> }; <del> this.bulkRequest.push(request); <del> }, <del> <del> flush: function() { <del> if (this.bulkRequest.length === 0) return; <del> var self = this; <del> var bulkRequest = this.bulkRequest; <del> this.bulkRequest = []; <del> log('REQUEST:', bulkRequest); <del> function callback(code, bulkResponse){ <del> log('RESPONSE[' + code + ']: ', bulkResponse); <del> if(bulkResponse['$status_code'] == 401) { <del> self.users['login'](function(){ <del> self.post(bulkRequest, callback); <del> }); <del> } else if(bulkResponse['$status_code']) { <del> alert(toJson(bulkResponse)); <del> } else { <del> for ( var i = 0; i < bulkResponse.length; i++) { <del> var response = bulkResponse[i]; <del> var request = bulkRequest[i]; <del> var responseCode = response['$status_code']; <del> if(responseCode) { <del> if(responseCode == 403) { <del> self.users['notAuthorized'](); <del> } else { <del> request['$$failure'](response); <del> } <del> } else { <del> request['$$callback'](response); <del> } <del> } <del> } <del> } <del> this.post(bulkRequest, callback); <del> }, <del> <del> saveScope: function(scope, callback) { <del> var saveCounter = 1; <del> function onSaveDone() { <del> saveCounter--; <del> if (saveCounter === 0 && callback) <del> callback(); <del> } <del> for(var key in scope) { <del> var item = scope[key]; <del> if (item && item['$save'] == Model.prototype['$save']) { <del> saveCounter++; <del> item['$save'](onSaveDone); <del> } <del> } <del> onSaveDone(); <del> }, <del> <del> query: function(type, query, arg, callback){ <del> var self = this; <del> var queryList = []; <del> queryList['$$accept'] = function(doc){ <del> return false; <del> }; <del> this._cache_collections.push(queryList); <del> var request = type['title'] + '/' + query + '=' + arg; <del> this._jsonRequest(["GET", request], function(response){ <del> var list = response; <del> foreach(list, function(item){ <del> var document = type()['$loadFrom'](item); <del> queryList.push(self.cache(document)); <del> }); <del> (callback||noop)(queryList); <del> }); <del> return queryList; <del> }, <del> <del> entities: function(callback) { <del> var entities = []; <del> var self = this; <del> this._jsonRequest(["GET", "$entities"], function(response) { <del> foreach(response, function(value, entityName){ <del> entities.push(self.entity(entityName)); <del> }); <del> entities.sort(function(a,b){return a.title > b.title ? 1 : -1;}); <del> (callback||noop)(entities); <del> }); <del> return entities; <del> }, <del> <del> documentCountsByUser: function(){ <del> var counts = {}; <del> var self = this; <del> self.post([["GET", "$users"]], function(code, response){ <del> extend(counts, response[0]); <del> }); <del> return counts; <del> }, <del> <del> userDocumentIdsByEntity: function(user){ <del> var ids = {}; <del> var self = this; <del> self.post([["GET", "$users/" + user]], function(code, response){ <del> extend(ids, response[0]); <del> }); <del> return ids; <del> }, <del> <del> entity: function(name, defaults){ <del> if (!name) { <del> return DataStore.NullEntity; <del> } <del> var self = this; <del> var entity = extend(function(initialState){ <del> return new Model(entity, initialState); <del> }, { <del> // entity.name does not work as name seems to be reserved for functions <del> 'title': name, <del> '$$factory': true, <del> datastore: this, //private, obfuscate <del> 'defaults': defaults || {}, <del> 'load': function(id, callback){ <del> return self.load(entity(), id, callback); <del> }, <del> 'loadMany': function(ids, callback){ <del> return self.loadMany(entity, ids, callback); <del> }, <del> 'loadOrCreate': function(id, callback){ <del> return self.loadOrCreate(entity(), id, callback); <del> }, <del> 'all': function(callback){ <del> return self.loadAll(entity, callback); <del> }, <del> 'query': function(query, queryArgs, callback){ <del> return self.query(entity, query, queryArgs, callback); <del> }, <del> 'properties': function(callback) { <del> self._jsonRequest(["GET", name + "/$properties"], callback); <del> } <del> }); <del> return entity; <del> }, <del> <del> join: function(join){ <del> function fn(){ <del> throw "Joined entities can not be instantiated into a document."; <del> }; <del> function base(name){return name ? name.substring(0, name.indexOf('.')) : undefined;} <del> function next(name){return name.substring(name.indexOf('.') + 1);} <del> var joinOrder = _(join).chain(). <del> map(function($, name){ <del> return name;}). <del> sortBy(function(name){ <del> var path = []; <del> do { <del> if (_(path).include(name)) throw "Infinite loop in join: " + path.join(" -> "); <del> path.push(name); <del> if (!join[name]) throw _("Named entity '<%=name%>' is undefined.").template({name:name}); <del> name = base(join[name].on); <del> } while(name); <del> return path.length; <del> }). <del> value(); <del> if (_(joinOrder).select(function($){return join[$].on;}).length != joinOrder.length - 1) <del> throw "Exactly one entity needs to be primary."; <del> fn['query'] = function(exp, value) { <del> var joinedResult = []; <del> var baseName = base(exp); <del> if (baseName != joinOrder[0]) throw _("Named entity '<%=name%>' is not a primary entity.").template({name:baseName}); <del> var Entity = join[baseName].join; <del> var joinIndex = 1; <del> Entity['query'](next(exp), value, function(result){ <del> var nextJoinName = joinOrder[joinIndex++]; <del> var nextJoin = join[nextJoinName]; <del> var nextJoinOn = nextJoin.on; <del> var joinIds = {}; <del> _(result).each(function(doc){ <del> var row = {}; <del> joinedResult.push(row); <del> row[baseName] = doc; <del> var id = Scope.getter(row, nextJoinOn); <del> joinIds[id] = id; <del> }); <del> nextJoin.join.loadMany(_.toArray(joinIds), function(result){ <del> var byId = {}; <del> _(result).each(function(doc){ <del> byId[doc.$id] = doc; <del> }); <del> _(joinedResult).each(function(row){ <del> var id = Scope.getter(row, nextJoinOn); <del> row[nextJoinName] = byId[id]; <del> }); <del> }); <del> }); <del> return joinedResult; <del> }; <del> return fn; <del> } <del>}; <ide><path>src/moveToAngularCom/Server.js <del>function Server(url, getScript) { <del> this.url = url; <del> this.nextId = 0; <del> this.getScript = getScript; <del> this.uuid = "_" + ("" + Math.random()).substr(2) + "_"; <del> this.maxSize = 1800; <del>}; <del> <del>Server.prototype = { <del> base64url: function(txt) { <del> return Base64.encode(txt); <del> }, <del> <del> request: function(method, url, request, callback) { <del> var requestId = this.uuid + (this.nextId++); <del> var payload = this.base64url(toJson({'u':url, 'm':method, 'p':request})); <del> var totalPockets = Math.ceil(payload.length / this.maxSize); <del> var baseUrl = this.url + "/$/" + requestId + "/" + totalPockets + "/"; <del> angularCallbacks[requestId] = function(response) { <del> delete angularCallbacks[requestId]; <del> callback(200, response); <del> }; <del> for ( var pocketNo = 0; pocketNo < totalPockets; pocketNo++) { <del> var pocket = payload.substr(pocketNo * this.maxSize, this.maxSize); <del> this.getScript(baseUrl + (pocketNo+1) + "?h=" + pocket, noop); <del> } <del> } <del>}; <del> <del>function FrameServer(frame) { <del> this.frame = frame; <del>}; <del>FrameServer.PREFIX = "$DATASET:"; <del> <del>FrameServer.prototype = { <del> read:function(){ <del> this.data = fromJson(this.frame.name.substr(FrameServer.PREFIX.length)); <del> }, <del> write:function(){ <del> this.frame.name = FrameServer.PREFIX + toJson(this.data); <del> }, <del> request: function(method, url, request, callback) { <del> //alert(method + " " + url + " " + toJson(request) + " " + toJson(callback)); <del> } <del>}; <del> <del> <del>function VisualServer(delegate, status, update) { <del> this.delegate = delegate; <del> this.update = update; <del> this.status = status; <del>}; <del> <del>VisualServer.prototype = { <del> request:function(method, url, request, callback) { <del> var self = this; <del> this.status.beginRequest(request); <del> this.delegate.request(method, url, request, function() { <del> self.status.endRequest(); <del> try { <del> callback.apply(this, arguments); <del> } catch (e) { <del> alert(toJson(e)); <del> } <del> self.update(); <del> }); <del> } <del>}; <ide><path>src/moveToAngularCom/Users.js <del>function Users(server, controlBar) { <del> this.server = server; <del> this.controlBar = controlBar; <del>}; <del> <del>extend(Users.prototype, { <del> 'fetchCurrentUser':function(callback) { <del> var self = this; <del> this.server.request("GET", "/account.json", {}, function(code, response){ <del> self['current'] = response['user']; <del> callback(response['user']); <del> }); <del> }, <del> <del> 'logout': function(callback) { <del> var self = this; <del> this.controlBar.logout(function(){ <del> delete self['current']; <del> (callback||noop)(); <del> }); <del> }, <del> <del> 'login': function(callback) { <del> var self = this; <del> this.controlBar.login(function(){ <del> self['fetchCurrentUser'](function(){ <del> (callback||noop)(); <del> }); <del> }); <del> }, <del> <del> 'notAuthorized': function(){ <del> this.controlBar.notAuthorized(); <del> } <del>}); <ide><path>src/moveToAngularCom/directivesAngularCom.js <del> <del>angular.directive("auth", function(expression, element){ <del> return function(){ <del> if(expression == "eager") { <del> this.$users.fetchCurrent(); <del> } <del> }; <del>}); <del> <del> <del>//expression = "book=Book:{year=2000}" <del>angular.directive("entity", function(expression, element){ <del> //parse expression, ignore element <del> var entityName; // "Book"; <del> var instanceName; // "book"; <del> var defaults; // {year: 2000}; <del> <del> parse(expression); <del> <del> return function(){ <del> this[entityName] = this.$datastore.entity(entityName, defaults); <del> this[instanceName] = this[entityName](); <del> this.$watch("$anchor."+instanceName, function(newAnchor){ <del> this[instanceName] = this[entityName].get(this.$anchor[instanceName]); <del> }); <del> }; <del>}); <del> <del> <ide><path>test/delete/ScopeTest.js <del>ScopeTest = TestCase('ScopeTest'); <del> <del>ScopeTest.prototype.testGetScopeRetrieval = function(){ <del> var scope = {}; <del> var form = jQuery("<a><b><c></c></b></a>"); <del> form.data('scope', scope); <del> var c = form.find('c'); <del> assertTrue(scope === c.scope()); <del>}; <del> <del>ScopeTest.prototype.testGetScopeRetrievalIntermediateNode = function(){ <del> var scope = {}; <del> var form = jQuery("<a><b><c></c></b></a>"); <del> form.find("b").data('scope', scope); <del> var b = form.find('b'); <del> assertTrue(scope === b.scope()); <del>}; <del> <del>ScopeTest.prototype.testNoScopeDoesNotCauseInfiniteRecursion = function(){ <del> var form = jQuery("<a><b><c></c></b></a>"); <del> var c = form.find('c'); <del> assertTrue(!c.scope()); <del>}; <del> <del>ScopeTest.prototype.testScopeEval = function(){ <del> var scope = new Scope({b:345}); <del> assertEquals(scope.eval('b = 123'), 123); <del> assertEquals(scope.get('b'), 123); <del>}; <del> <del>ScopeTest.prototype.testScopeFromPrototype = function(){ <del> var scope = new Scope({b:123}); <del> scope.eval('a = b'); <del> scope.eval('b = 456'); <del> assertEquals(scope.get('a'), 123); <del> assertEquals(scope.get('b'), 456); <del>}; <del> <del>ScopeTest.prototype.testSetScopeGet = function(){ <del> var scope = new Scope(); <del> assertEquals(987, scope.set('a', 987)); <del> assertEquals(scope.get('a'), 987); <del> assertEquals(scope.eval('a'), 987); <del>}; <del> <del>ScopeTest.prototype.testGetChain = function(){ <del> var scope = new Scope({a:{b:987}}); <del> assertEquals(scope.get('a.b'), 987); <del> assertEquals(scope.eval('a.b'), 987); <del>}; <del> <del>ScopeTest.prototype.testGetUndefinedChain = function(){ <del> var scope = new Scope(); <del> assertEquals(typeof scope.get('a.b'), 'undefined'); <del>}; <del> <del>ScopeTest.prototype.testSetChain = function(){ <del> var scope = new Scope({a:{}}); <del> scope.set('a.b', 987); <del> assertEquals(scope.get('a.b'), 987); <del> assertEquals(scope.eval('a.b'), 987); <del>}; <del> <del>ScopeTest.prototype.testSetGetOnChain = function(){ <del> var scope = new Scope(); <del> scope.set('a.b', 987); <del> assertEquals(scope.get('a.b'), 987); <del> assertEquals(scope.eval('a.b'), 987); <del>}; <del> <del>ScopeTest.prototype.testGlobalFunctionAccess =function(){ <del> window['scopeAddTest'] = function (a, b) {return a+b;}; <del> var scope = new Scope({window:window}); <del> assertEquals(scope.eval('window.scopeAddTest(1,2)'), 3); <del> <del> scope.set('add', function (a, b) {return a+b;}); <del> assertEquals(scope.eval('add(1,2)'), 3); <del> <del> scope.set('math.add', function (a, b) {return a+b;}); <del> assertEquals(scope.eval('math.add(1,2)'), 3); <del>}; <del> <del>ScopeTest.prototype.testValidationEval = function(){ <del> expectAsserts(4); <del> var scope = new Scope(); <del> scope.set("name", "misko"); <del> angular.validator.testValidator = function(value, expect){ <del> assertEquals("misko", this.name); <del> return value == expect ? null : "Error text"; <del> }; <del> <del> assertEquals("Error text", scope.validate("testValidator:'abc'", 'x')); <del> assertEquals(null, scope.validate("testValidator:'abc'", 'abc')); <del> <del> delete angular.validator['testValidator']; <del>}; <del> <del>ScopeTest.prototype.testCallingNonExistantMethodShouldProduceFriendlyException = function() { <del> expectAsserts(1); <del> var scope = new Scope({obj:{}}); <del> try { <del> scope.eval("obj.iDontExist()"); <del> fail(); <del> } catch (e) { <del> assertEquals("Expression 'obj.iDontExist' is not a function.", e); <del> } <del>}; <del> <del>ScopeTest.prototype.testAccessingWithInvalidPathShouldThrowError = function() { <del> var scope = new Scope(); <del> try { <del> scope.get('a.{{b}}'); <del> fail(); <del> } catch (e) { <del> assertEquals("Expression 'a.{{b}}' is not a valid expression for accesing variables.", e); <del> } <del>}; <del> <del>ScopeTest.prototype.testItShouldHave$parent = function() { <del> var parent = new Scope({}, "ROOT"); <del> var child = new Scope(parent.state); <del> assertSame("parent", child.state.$parent, parent.state); <del> assertSame("root", child.state.$root, parent.state); <del>}; <del> <del>ScopeTest.prototype.testItShouldHave$root = function() { <del> var scope = new Scope({}, "ROOT"); <del> assertSame(scope.state.$root, scope.state); <del>}; <del> <del>ScopeTest.prototype.testItShouldBuildPathOnUndefined = function(){ <del> var scope = new Scope({}, "ROOT"); <del> scope.setEval("a.$b.c", 1); <del> assertJsonEquals({$b:{c:1}}, scope.get("a")); <del>}; <del> <del>ScopeTest.prototype.testItShouldMapUnderscoreFunctions = function(){ <del> var scope = new Scope({}, "ROOT"); <del> scope.set("a", [1,2,3]); <del> assertEquals('function', typeof scope.get("a.$size")); <del> scope.eval("a.$includeIf(4,true)"); <del> assertEquals(4, scope.get("a.$size")()); <del> assertEquals(4, scope.eval("a.$size()")); <del> assertEquals('undefined', typeof scope.get("a.dontExist")); <del>}; <ide><path>test/delete/WidgetsTest.js <del>WidgetTest = TestCase('WidgetTest'); <del> <del>WidgetTest.prototype.testRequired = function () { <del> var view = $('<input name="a" ng:required>'); <del> var scope = new Scope({$invalidWidgets:[]}); <del> var cntl = new TextController(view[0], 'a', angularFormatter.noop); <del> cntl.updateView(scope); <del> assertTrue(view.hasClass('ng-validation-error')); <del> assertEquals("Required Value", view.attr('ng-error')); <del> scope.set('a', 'A'); <del> cntl.updateView(scope); <del> assertFalse(view.hasClass('ng-validation-error')); <del> assertEquals("undefined", typeof view.attr('ng-error')); <del>}; <del> <del>WidgetTest.prototype.testValidator = function () { <del> var view = $('<input name="a" ng:validate="testValidator:\'ABC\'">'); <del> var scope = new Scope({$invalidWidgets:[]}); <del> var cntl = new TextController(view[0], 'a', angularFormatter.noop); <del> angular.validator.testValidator = function(value, expect){ <del> return value == expect ? false : "Error text"; <del> }; <del> <del> scope.set('a', ''); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), false); <del> assertEquals(null, view.attr('ng-error')); <del> <del> scope.set('a', 'X'); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), true); <del> assertEquals(view.attr('ng-error'), "Error text"); <del> assertEquals("Error text", view.attr('ng-error')); <del> <del> scope.set('a', 'ABC'); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), false); <del> assertEquals(view.attr('ng-error'), null); <del> assertEquals(null, view.attr('ng-error')); <del> <del> delete angular.validator['testValidator']; <del>}; <del> <del>WidgetTest.prototype.testRequiredValidator = function () { <del> var view = $('<input name="a" ng:required ng:validate="testValidator:\'ABC\'">'); <del> var scope = new Scope({$invalidWidgets:[]}); <del> var cntl = new TextController(view[0], 'a', angularFormatter.noop); <del> angular.validator.testValidator = function(value, expect){ <del> return value == expect ? null : "Error text"; <del> }; <del> <del> scope.set('a', ''); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), true); <del> assertEquals("Required Value", view.attr('ng-error')); <del> <del> scope.set('a', 'X'); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), true); <del> assertEquals("Error text", view.attr('ng-error')); <del> <del> scope.set('a', 'ABC'); <del> cntl.updateView(scope); <del> assertEquals(view.hasClass('ng-validation-error'), false); <del> assertEquals(null, view.attr('ng-error')); <del> <del> delete angular.validator['testValidator']; <del>}; <del> <del>TextControllerTest = TestCase("TextControllerTest"); <del> <del>TextControllerTest.prototype.testDatePicker = function() { <del> var input = $('<input type="text" ng-widget="datepicker">'); <del> input.data('scope', new Scope()); <del> var body = $(document.body); <del> body.append(input); <del> var binder = new Binder(input[0], new WidgetFactory()); <del> assertTrue('before', input.data('datepicker') === undefined); <del> binder.compile(); <del> assertTrue('after', input.data('datepicker') !== null); <del> assertTrue(body.html(), input.hasClass('hasDatepicker')); <del>}; <del> <del>RepeaterUpdaterTest = TestCase("RepeaterUpdaterTest"); <del> <del>RepeaterUpdaterTest.prototype.testRemoveThenAdd = function() { <del> var view = $("<div><span/></div>"); <del> var template = function () { <del> return $("<li/>"); <del> }; <del> var repeater = new RepeaterUpdater(view.find("span"), "a in b", template, ""); <del> var scope = new Scope(); <del> scope.set('b', [1,2]); <del> <del> repeater.updateView(scope); <del> <del> scope.set('b', []); <del> repeater.updateView(scope); <del> <del> scope.set('b', [1]); <del> repeater.updateView(scope); <del> assertEquals(1, view.find("li").size()); <del>}; <del> <del>RepeaterUpdaterTest.prototype.testShouldBindWidgetOnRepeaterClone = function(){ <del> //fail(); <del>}; <del> <del>RepeaterUpdaterTest.prototype.testShouldThrowInformativeSyntaxError= function(){ <del> expectAsserts(1); <del> try { <del> var repeater = new RepeaterUpdater(null, "a=b"); <del> } catch (e) { <del> assertEquals("Expected ng:repeat in form of 'item in collection' but got 'a=b'.", e); <del> } <del>}; <del> <del>SelectControllerTest = TestCase("SelectControllerTest"); <del> <del>SelectControllerTest.prototype.testShouldUpdateModelNullOnNothingSelected = function(){ <del> var scope = new Scope(); <del> var view = {selectedIndex:-1, options:[]}; <del> var cntl = new SelectController(view, 'abc'); <del> cntl.updateModel(scope); <del> assertNull(scope.get('abc')); <del>}; <del> <del>SelectControllerTest.prototype.testShouldUpdateModelWhenNothingSelected = function(){ <del> var scope = new Scope(); <del> var view = {value:'123'}; <del> var cntl = new SelectController(view, 'abc'); <del> cntl.updateView(scope); <del> assertEquals("123", scope.get('abc')); <del>}; <del> <del>BindUpdaterTest = TestCase("BindUpdaterTest"); <del> <del>BindUpdaterTest.prototype.testShouldDisplayNothingForUndefined = function () { <del> var view = $('<span />'); <del> var controller = new BindUpdater(view[0], "{{a}}"); <del> var scope = new Scope(); <del> <del> scope.set('a', undefined); <del> controller.updateView(scope); <del> assertEquals("", view.text()); <del> <del> scope.set('a', null); <del> controller.updateView(scope); <del> assertEquals("", view.text()); <del>}; <del> <del>BindUpdaterTest.prototype.testShouldDisplayJsonForNonStrings = function () { <del> var view = $('<span />'); <del> var controller = new BindUpdater(view[0], "{{obj}}"); <del> <del> controller.updateView(new Scope({obj:[]})); <del> assertEquals("[]", view.text()); <del> <del> controller.updateView(new Scope({obj:{text:'abc'}})); <del> assertEquals('abc', fromJson(view.text()).text); <del>}; <del> <del> <del>BindUpdaterTest.prototype.testShouldInsertHtmlNode = function () { <del> var view = $('<span />'); <del> var controller = new BindUpdater(view[0], "<fake>&{{obj}}</fake>"); <del> var scope = new Scope(); <del> <del> scope.set("obj", $('<div>myDiv</div>')[0]); <del> controller.updateView(scope); <del> assertEquals("<fake>&myDiv</fake>", view.text()); <del>}; <del> <del> <del>BindUpdaterTest.prototype.testShouldDisplayTextMethod = function () { <del> var view = $('<div />'); <del> var controller = new BindUpdater(view[0], "{{obj}}"); <del> var scope = new Scope(); <del> <del> scope.set("obj", new angular.filter.Meta({text:function(){return "abc";}})); <del> controller.updateView(scope); <del> assertEquals("abc", view.text()); <del> <del> scope.set("obj", new angular.filter.Meta({text:"123"})); <del> controller.updateView(scope); <del> assertEquals("123", view.text()); <del> <del> scope.set("obj", {text:"123"}); <del> controller.updateView(scope); <del> assertEquals("123", fromJson(view.text()).text); <del>}; <del> <del>BindUpdaterTest.prototype.testShouldDisplayHtmlMethod = function () { <del> var view = $('<div />'); <del> var controller = new BindUpdater(view[0], "{{obj}}"); <del> var scope = new Scope(); <del> <del> scope.set("obj", new angular.filter.Meta({html:function(){return "a<div>b</div>c";}})); <del> controller.updateView(scope); <del> assertEquals("abc", view.text()); <del> <del> scope.set("obj", new angular.filter.Meta({html:"1<div>2</div>3"})); <del> controller.updateView(scope); <del> assertEquals("123", view.text()); <del> <del> scope.set("obj", {html:"123"}); <del> controller.updateView(scope); <del> assertEquals("123", fromJson(view.text()).html); <del>}; <del> <del>BindUpdaterTest.prototype.testUdateBoolean = function() { <del> var view = $('<div />'); <del> var controller = new BindUpdater(view[0], "{{true}}, {{false}}"); <del> controller.updateView(new Scope()); <del> assertEquals('true, false', view.text()); <del>}; <del> <del>BindAttrUpdaterTest = TestCase("BindAttrUpdaterTest"); <del> <del>BindAttrUpdaterTest.prototype.testShouldLoadBlankImageWhenBindingIsUndefined = function () { <del> var view = $('<img />'); <del> var controller = new BindAttrUpdater(view[0], {src: '{{imageUrl}}'}); <del> <del> var scope = new Scope(); <del> scope.set('imageUrl', undefined); <del> scope.set('$config.blankImage', 'http://server/blank.gif'); <del> <del> controller.updateView(scope); <del> assertEquals("http://server/blank.gif", view.attr('src')); <del>}; <del> <del>RepeaterUpdaterTest.prototype.testShouldNotDieWhenRepeatExpressionIsNull = function() { <del> var rep = new RepeaterUpdater(null, "$item in items", null, null); <del> var scope = new Scope(); <del> scope.set('items', undefined); <del> rep.updateView(scope); <del>}; <del> <del>RepeaterUpdaterTest.prototype.testShouldIterateOverKeys = function() { <del> var rep = new RepeaterUpdater(null, "($k,_v) in items", null, null); <del> assertEquals("items", rep.iteratorExp); <del> assertEquals("_v", rep.valueExp); <del> assertEquals("$k", rep.keyExp); <del>}; <del> <del>EvalUpdaterTest = TestCase("EvalUpdaterTest"); <del>EvalUpdaterTest.prototype.testEvalThrowsException = function(){ <del> var view = $('<div/>'); <del> var eval = new EvalUpdater(view[0], 'undefined()'); <del> <del> eval.updateView(new Scope()); <del> assertTrue(!!view.attr('ng-error')); <del> assertTrue(view.hasClass('ng-exception')); <del> <del> eval.exp = "1"; <del> eval.updateView(new Scope()); <del> assertFalse(!!view.attr('ng-error')); <del> assertFalse(view.hasClass('ng-exception')); <del>}; <del> <del>RadioControllerTest = TestCase("RadioController"); <del>RadioControllerTest.prototype.testItShouldTreatTrueStringAsBoolean = function () { <del> var view = $('<input type="radio" name="select" value="true"/>'); <del> var radio = new RadioController(view[0], 'select'); <del> var scope = new Scope({select:true}); <del> radio.updateView(scope); <del> assertTrue(view[0].checked); <del>}; <ide><path>test/moveToAngularCom/Base64Test.js <del>Base64Test = TestCase('Base64Test'); <del> <del>Base64Test.prototype.testEncodeDecode = function(){ <del> assertEquals(Base64.decode(Base64.encode('hello')), 'hello'); <del>}; <ide><path>test/moveToAngularCom/DataStoreTest.js <del>DataStoreTest = TestCase('DataStoreTest'); <del> <del>DataStoreTest.prototype.testSavePostsToServer = function(){ <del> expectAsserts(10); <del> var response; <del> var post = function(data, callback){ <del> var method = data[0][0]; <del> var posted = data[0][2]; <del> assertEquals("POST", method); <del> assertEquals("abc", posted.$entity); <del> assertEquals("123", posted.$id); <del> assertEquals("1", posted.$version); <del> assertFalse('function' == typeof posted.save); <del> response = fromJson(toJson(posted)); <del> response.$entity = "abc"; <del> response.$id = "123"; <del> response.$version = "2"; <del> callback(200, [response]); <del> }; <del> var datastore = new DataStore(post); <del> var model = datastore.entity('abc', {name: "value"})(); <del> model.$id = "123"; <del> model.$version = "1"; <del> <del> datastore.save(model, function(obj){ <del> assertTrue(obj === model); <del> assertEquals(obj.$entity, "abc"); <del> assertEquals(obj.$id, "123"); <del> assertEquals(obj.$version, "2"); <del> assertEquals(obj.name, "value"); <del> obj.after = true; <del> }); <del> datastore.flush(); <del>}; <del> <del>DataStoreTest.prototype.testLoadGetsFromServer = function(){ <del> expectAsserts(12); <del> var post = function(data, callback){ <del> var method = data[0][0]; <del> var path = data[0][1]; <del> assertEquals("GET", method); <del> assertEquals("abc/1", path); <del> response = [{$entity:'abc', $id:'1', $version:'2', key:"value"}]; <del> callback(200, response); <del> }; <del> var datastore = new DataStore(post); <del> <del> var model = datastore.entity("abc", {merge:true})(); <del> assertEquals(datastore.load(model, '1', function(obj){ <del> assertEquals(obj.$entity, "abc"); <del> assertEquals(obj.$id, "1"); <del> assertEquals(obj.$version, "2"); <del> assertEquals(obj.key, "value"); <del> }), model); <del> datastore.flush(); <del> assertEquals(model.$entity, "abc"); <del> assertEquals(model.$id, "1"); <del> assertEquals(model.$version, "2"); <del> assertEquals(model.key, "value"); <del> assertEquals(model.merge, true); <del>}; <del> <del>DataStoreTest.prototype.testRemove = function(){ <del> expectAsserts(8); <del> var response; <del> var post = function(data, callback){ <del> var method = data[0][0]; <del> var posted = data[0][2]; <del> assertEquals("DELETE", method); <del> assertEquals("abc", posted.$entity); <del> assertEquals("123", posted.$id); <del> assertEquals("1", posted.$version); <del> assertFalse('function' == typeof posted.save); <del> response = fromJson(toJson(posted)); <del> response.$entity = "abc"; <del> response.$id = "123"; <del> response.$version = "2"; <del> callback(200, [response]); <del> }; <del> var model; <del> var datastore = new DataStore(post); <del> model = datastore.entity('abc', {name: "value"})(); <del> model.$id = "123"; <del> model.$version = "1"; <del> <del> datastore.remove(model, function(obj){ <del> assertEquals(obj.$id, "123"); <del> assertEquals(obj.$version, "2"); <del> assertEquals(obj.name, "value"); <del> obj.after = true; <del> }); <del> datastore.flush(); <del> <del>}; <del> <del> <del>DataStoreTest.prototype.test401ResponseDoesNotCallCallback = function(){ <del> expectAsserts(1); <del> var post = function(data, callback) { <del> callback(200, {$status_code: 401}); <del> }; <del> <del> var datastore = new DataStore(post, {login:function(){ <del> assertTrue(true); <del> }}); <del> <del> var onLoadAll = function(){ <del> assertTrue(false, "onLoadAll should not be called when response is status 401"); <del> }; <del> datastore.bulkRequest.push({}); <del> datastore.flush(); <del> datastore.loadAll({type: "A"}, onLoadAll); <del>}; <del> <del>DataStoreTest.prototype.test403ResponseDoesNotCallCallback = function(){ <del> expectAsserts(1); <del> var post = function(data, callback) { <del> callback(200, [{$status_code: 403}]); <del> }; <del> <del> var datastore = new DataStore(post, {notAuthorized:function(){ <del> assertTrue(true); <del> }}); <del> <del> var onLoadAll = function(){ <del> assertTrue(false, "onLoadAll should not be called when response is status 403"); <del> }; <del> datastore.bulkRequest.push({}); <del> datastore.flush(); <del> datastore.loadAll({type: "A"}, onLoadAll); <del>}; <del> <del>DataStoreTest.prototype.testLoadCalledWithoutIdShouldBeNoop = function(){ <del> expectAsserts(2); <del> var post = function(url, callback){ <del> assertTrue(false); <del> }; <del> var datastore = new DataStore(post); <del> var model = datastore.entity("abc")(); <del> assertEquals(datastore.load(model, undefined), model); <del> assertEquals(model.$entity, "abc"); <del>}; <del> <del>DataStoreTest.prototype.testEntityFactory = function(){ <del> var ds = new DataStore(); <del> var Recipe = ds.entity("Recipe", {a:1, b:2}); <del> assertEquals(Recipe.title, "Recipe"); <del> assertEquals(Recipe.defaults.a, 1); <del> assertEquals(Recipe.defaults.b, 2); <del> <del> var recipe = Recipe(); <del> assertEquals(recipe.$entity, "Recipe"); <del> assertEquals(recipe.a, 1); <del> assertEquals(recipe.b, 2); <del> <del> recipe = new Recipe(); <del> assertEquals(recipe.$entity, "Recipe"); <del> assertEquals(recipe.a, 1); <del> assertEquals(recipe.b, 2); <del>}; <del> <del>DataStoreTest.prototype.testEntityFactoryNoDefaults = function(){ <del> var ds = new DataStore(); <del> var Recipe = ds.entity("Recipe"); <del> assertEquals(Recipe.title, "Recipe"); <del> <del> recipe = new Recipe(); <del> assertEquals(recipe.$entity, "Recipe"); <del>}; <del> <del>DataStoreTest.prototype.testEntityFactoryWithInitialValues = function(){ <del> var ds = new DataStore(); <del> var Recipe = ds.entity("Recipe"); <del> <del> var recipe = Recipe({name: "name"}); <del> assertEquals("name", recipe.name); <del>}; <del> <del>DataStoreTest.prototype.testEntityLoad = function(){ <del> var ds = new DataStore(); <del> var Recipe = ds.entity("Recipe", {a:1, b:2}); <del> ds.load = function(instance, id, callback){ <del> callback.apply(instance); <del> return instance; <del> }; <del> var instance = null; <del> var recipe2 = Recipe.load("ID", function(){ <del> instance = this; <del> }); <del> assertTrue(recipe2 === instance); <del>}; <del> <del>DataStoreTest.prototype.testSaveScope = function(){ <del> var ds = new DataStore(); <del> var log = ""; <del> var Person = ds.entity("Person"); <del> var person1 = Person({name:"A", $entity:"Person", $id:"1", $version:"1"}, ds); <del> person1.$$anchor = "A"; <del> var person2 = Person({name:"B", $entity:"Person", $id:"2", $version:"2"}, ds); <del> person2.$$anchor = "B"; <del> var anchor = {}; <del> ds.anchor = anchor; <del> ds._jsonRequest = function(request, callback){ <del> log += "save(" + request[2].$id + ");"; <del> callback({$id:request[2].$id}); <del> }; <del> ds.saveScope({person1:person1, person2:person2, <del> ignoreMe:{name: "ignore", save:function(callback){callback();}}}, function(){ <del> log += "done();"; <del> }); <del> assertEquals("save(1);save(2);done();", log); <del> assertEquals(1, anchor.A); <del> assertEquals(2, anchor.B); <del>}; <del> <del>DataStoreTest.prototype.testEntityLoadAllRows = function(){ <del> var ds = new DataStore(); <del> var Recipe = ds.entity("Recipe"); <del> var list = []; <del> ds.loadAll = function(entity, callback){ <del> assertTrue(Recipe === entity); <del> callback.apply(list); <del> return list; <del> }; <del> var items = Recipe.all(function(){ <del> assertTrue(list === this); <del> }); <del> assertTrue(items === list); <del>}; <del> <del>DataStoreTest.prototype.testLoadAll = function(){ <del> expectAsserts(8); <del> var post = function(data, callback){ <del> assertEquals("GET", data[0][0]); <del> assertEquals("A", data[0][1]); <del> callback(200, [[{$entity:'A', $id:'1'},{$entity:'A', $id:'2'}]]); <del> }; <del> var datastore = new DataStore(post); <del> var list = datastore.entity("A").all(function(){ <del> assertTrue(true); <del> }); <del> datastore.flush(); <del> assertEquals(list.length, 2); <del> assertEquals(list[0].$entity, "A"); <del> assertEquals(list[0].$id, "1"); <del> assertEquals(list[1].$entity, "A"); <del> assertEquals(list[1].$id, "2"); <del>}; <del> <del>DataStoreTest.prototype.testQuery = function(){ <del> expectAsserts(5); <del> var post = function(data, callback) { <del> assertEquals("GET", data[0][0]); <del> assertEquals("Employee/managerId=123abc", data[0][1]); <del> callback(200, [[{$entity:"Employee", $id: "456", managerId: "123ABC"}]]); <del> <del> }; <del> var datastore = new DataStore(post); <del> var Employee = datastore.entity("Employee"); <del> var list = Employee.query('managerId', "123abc", function(){ <del> assertTrue(true); <del> }); <del> datastore.flush(); <del> assertJsonEquals([[{$entity:"Employee", $id: "456", managerId: "123ABC"}]], datastore._cache.$collections); <del> assertEquals(list[0].$id, "456"); <del>}; <del> <del>DataStoreTest.prototype.testLoadingDocumentRefreshesExistingArrays = function() { <del> expectAsserts(12); <del> var post; <del> var datastore = new DataStore(function(r, c){post(r,c);}); <del> var Book = datastore.entity('Book'); <del> post = function(req, callback) { <del> callback(200, [[{$id:1, $entity:"Book", name:"Moby"}, <del> {$id:2, $entity:"Book", name:"Dick"}]]); <del> }; <del> var allBooks = Book.all(); <del> datastore.flush(); <del> var queryBooks = Book.query("a", "b"); <del> datastore.flush(); <del> assertEquals("Moby", allBooks[0].name); <del> assertEquals("Dick", allBooks[1].name); <del> assertEquals("Moby", queryBooks[0].name); <del> assertEquals("Dick", queryBooks[1].name); <del> <del> post = function(req, callback) { <del> assertEquals('[["GET","Book/1"]]', toJson(req)); <del> callback(200, [{$id:1, $entity:"Book", name:"Moby Dick"}]); <del> }; <del> var book = Book.load(1); <del> datastore.flush(); <del> assertEquals("Moby Dick", book.name); <del> assertEquals("Moby Dick", allBooks[0].name); <del> assertEquals("Moby Dick", queryBooks[0].name); <del> <del> post = function(req, callback) { <del> assertEquals('POST', req[0][0]); <del> callback(200, [{$id:1, $entity:"Book", name:"The Big Fish"}]); <del> }; <del> book.$save(); <del> datastore.flush(); <del> assertEquals("The Big Fish", book.name); <del> assertEquals("The Big Fish", allBooks[0].name); <del> assertEquals("The Big Fish", queryBooks[0].name); <del>}; <del> <del>DataStoreTest.prototype.testEntityProperties = function() { <del> expectAsserts(2); <del> var datastore = new DataStore(); <del> var callback = {}; <del> <del> datastore._jsonRequest = function(request, callbackFn) { <del> assertJsonEquals(["GET", "Cheese/$properties"], request); <del> assertEquals(callback, callbackFn); <del> }; <del> <del> var Cheese = datastore.entity("Cheese"); <del> Cheese.properties(callback); <del> <del>}; <del> <del>DataStoreTest.prototype.testLoadInstanceIsNotFromCache = function() { <del> var post; <del> var datastore = new DataStore(function(r, c){post(r,c);}); <del> var Book = datastore.entity('Book'); <del> <del> post = function(req, callback) { <del> assertEquals('[["GET","Book/1"]]', toJson(req)); <del> callback(200, [{$id:1, $entity:"Book", name:"Moby Dick"}]); <del> }; <del> var book = Book.load(1); <del> datastore.flush(); <del> assertEquals("Moby Dick", book.name); <del> assertFalse(book === datastore._cache['Book/1']); <del>}; <del> <del>DataStoreTest.prototype.testLoadStarsIsNewDocument = function() { <del> var datastore = new DataStore(); <del> var Book = datastore.entity('Book'); <del> var book = Book.load('*'); <del> assertEquals('Book', book.$entity); <del>}; <del> <del>DataStoreTest.prototype.testUndefinedEntityReturnsNullValueObject = function() { <del> var datastore = new DataStore(); <del> var Entity = datastore.entity(undefined); <del> var all = Entity.all(); <del> assertEquals(0, all.length); <del>}; <del> <del>DataStoreTest.prototype.testFetchEntities = function(){ <del> expectAsserts(6); <del> var post = function(data, callback){ <del> assertJsonEquals(["GET", "$entities"], data[0]); <del> callback(200, [{A:0, B:0}]); <del> }; <del> var datastore = new DataStore(post); <del> var entities = datastore.entities(function(){ <del> assertTrue(true); <del> }); <del> datastore.flush(); <del> assertJsonEquals([], datastore.bulkRequest); <del> assertEquals(2, entities.length); <del> assertEquals("A", entities[0].title); <del> assertEquals("B", entities[1].title); <del>}; <del> <del>DataStoreTest.prototype.testItShouldMigrateSchema = function() { <del> var datastore = new DataStore(); <del> var Entity = datastore.entity("Entity", {a:[], user:{name:"Misko", email:""}}); <del> var doc = Entity().$loadFrom({b:'abc', user:{email:"misko@hevery.com"}}); <del> assertFalse( <del> toJson({a:[], b:'abc', user:{name:"Misko", email:"misko@hevery.com"}}) == <del> toJson(doc)); <del> doc.$migrate(); <del> assertEquals( <del> toJson({a:[], b:'abc', user:{name:"Misko", email:"misko@hevery.com"}}), <del> toJson(doc)); <del>}; <del> <del>DataStoreTest.prototype.testItShouldCollectRequestsForBulk = function() { <del> var ds = new DataStore(); <del> var Book = ds.entity("Book"); <del> var Library = ds.entity("Library"); <del> Book.all(); <del> Library.load("123"); <del> assertEquals(2, ds.bulkRequest.length); <del> assertJsonEquals(["GET", "Book"], ds.bulkRequest[0]); <del> assertJsonEquals(["GET", "Library/123"], ds.bulkRequest[1]); <del>}; <del> <del>DataStoreTest.prototype.testEmptyFlushShouldDoNothing = function () { <del> var ds = new DataStore(function(){ <del> fail("expecting noop"); <del> }); <del> ds.flush(); <del>}; <del> <del>DataStoreTest.prototype.testFlushShouldCallAllCallbacks = function() { <del> var log = ""; <del> function post(request, callback){ <del> log += 'BulkRequest:' + toJson(request) + ';'; <del> callback(200, [[{$id:'ABC'}], {$id:'XYZ'}]); <del> } <del> var ds = new DataStore(post); <del> var Book = ds.entity("Book"); <del> var Library = ds.entity("Library"); <del> Book.all(function(instance){ <del> log += toJson(instance) + ';'; <del> }); <del> Library.load("123", function(instance){ <del> log += toJson(instance) + ';'; <del> }); <del> assertEquals("", log); <del> ds.flush(); <del> assertJsonEquals([], ds.bulkRequest); <del> assertEquals('BulkRequest:[["GET","Book"],["GET","Library/123"]];[{"$id":"ABC"}];{"$id":"XYZ"};', log); <del>}; <del> <del>DataStoreTest.prototype.testSaveOnNotLoggedInRetriesAfterLoggin = function(){ <del> var log = ""; <del> var book; <del> var ds = new DataStore(null, {login:function(c){c();}}); <del> ds.post = function (request, callback){ <del> assertJsonEquals([["POST", "", book]], request); <del> ds.post = function(request, callback){ <del> assertJsonEquals([["POST", "", book]], request); <del> ds.post = function(){fail("too much recursion");}; <del> callback(200, [{saved:"ok"}]); <del> }; <del> callback(200, {$status_code:401}); <del> }; <del> book = ds.entity("Book")({name:"misko"}); <del> book.$save(); <del> ds.flush(); <del> assertJsonEquals({saved:"ok"}, book); <del>}; <del> <del>DataStoreTest.prototype.testItShouldRemoveItemFromCollectionWhenDeleted = function() { <del> expectAsserts(6); <del> var ds = new DataStore(); <del> ds.post = function(request, callback){ <del> assertJsonEquals([["GET", "Book"]], request); <del> callback(200, [[{name:"Moby Dick", $id:123, $entity:'Book'}]]); <del> }; <del> var Book = ds.entity("Book"); <del> var books = Book.all(); <del> ds.flush(); <del> assertJsonEquals([[{name:"Moby Dick", $id:123, $entity:'Book'}]], ds._cache.$collections); <del> assertDefined(ds._cache['Book/123']); <del> var book = Book({$id:123}); <del> ds.post = function(request, callback){ <del> assertJsonEquals([["DELETE", "", book]], request); <del> callback(200, [book]); <del> }; <del> ds.remove(book); <del> ds.flush(); <del> assertUndefined(ds._cache['Book/123']); <del> assertJsonEquals([[]],ds._cache.$collections); <del>}; <del> <del>DataStoreTest.prototype.testItShouldAddToAll = function() { <del> expectAsserts(8); <del> var ds = new DataStore(); <del> ds.post = function(request, callback){ <del> assertJsonEquals([["GET", "Book"]], request); <del> callback(200, [[]]); <del> }; <del> var Book = ds.entity("Book"); <del> var books = Book.all(); <del> assertEquals(0, books.length); <del> ds.flush(); <del> var moby = Book({name:'moby'}); <del> moby.$save(); <del> ds.post = function(request, callback){ <del> assertJsonEquals([["POST", "", moby]], request); <del> moby.$id = '123'; <del> callback(200, [moby]); <del> }; <del> ds.flush(); <del> assertEquals(1, books.length); <del> assertEquals(moby, books[0]); <del> <del> moby.$save(); <del> ds.flush(); <del> assertEquals(1, books.length); <del> assertEquals(moby, books[0]); <del>}; <del> <del>DataStoreTest.prototype.testItShouldReturnCreatedDocumentCountByUser = function(){ <del> expectAsserts(2); <del> var datastore = new DataStore( <del> function(request, callback){ <del> assertJsonEquals([["GET", "$users"]], request); <del> callback(200, [{misko:1, adam:1}]); <del> }); <del> var users = datastore.documentCountsByUser(); <del> assertJsonEquals({misko:1, adam:1}, users); <del>}; <del> <del> <del>DataStoreTest.prototype.testItShouldReturnDocumentIdsForUeserByEntity = function(){ <del> expectAsserts(2); <del> var datastore = new DataStore( <del> function(request, callback){ <del> assertJsonEquals([["GET", "$users/misko@hevery.com"]], request); <del> callback(200, [{Book:["1"], Library:["2"]}]); <del> }); <del> var users = datastore.userDocumentIdsByEntity("misko@hevery.com"); <del> assertJsonEquals({Book:["1"], Library:["2"]}, users); <del>}; <del> <del>DataStoreTest.prototype.testItShouldReturnNewInstanceOn404 = function(){ <del> expectAsserts(7); <del> var log = ""; <del> var datastore = new DataStore( <del> function(request, callback){ <del> assertJsonEquals([["GET", "User/misko"]], request); <del> callback(200, [{$status_code:404}]); <del> }); <del> var User = datastore.entity("User", {admin:false}); <del> var user = User.loadOrCreate('misko', function(i){log+="cb "+i.$id+";";}); <del> datastore.flush(); <del> assertEquals("misko", user.$id); <del> assertEquals("User", user.$entity); <del> assertEquals(false, user.admin); <del> assertEquals("undefined", typeof user.$secret); <del> assertEquals("undefined", typeof user.$version); <del> assertEquals("cb misko;", log); <del>}; <del> <del>DataStoreTest.prototype.testItShouldReturnNewInstanceOn404 = function(){ <del> var log = ""; <del> var datastore = new DataStore( <del> function(request, callback){ <del> assertJsonEquals([["GET", "User/misko"],["GET", "User/adam"]], request); <del> callback(200, [{$id:'misko'},{$id:'adam'}]); <del> }); <del> var User = datastore.entity("User"); <del> var users = User.loadMany(['misko', 'adam'], function(i){log+="cb "+toJson(i)+";";}); <del> datastore.flush(); <del> assertEquals("misko", users[0].$id); <del> assertEquals("adam", users[1].$id); <del> assertEquals('cb [{"$id":"misko"},{"$id":"adam"}];', log); <del>}; <del> <del>DataStoreTest.prototype.testItShouldCreateJoinAndQuery = function() { <del> var datastore = new DataStore(); <del> var Invoice = datastore.entity("Invoice"); <del> var Customer = datastore.entity("Customer"); <del> var InvoiceWithCustomer = datastore.join({ <del> invoice:{join:Invoice}, <del> customer:{join:Customer, on:"invoice.customer"} <del> }); <del> var invoiceWithCustomer = InvoiceWithCustomer.query("invoice.month", 1); <del> assertEquals([], invoiceWithCustomer); <del> assertJsonEquals([["GET", "Invoice/month=1"]], datastore.bulkRequest); <del> var request = datastore.bulkRequest.shift(); <del> request.$$callback([{$id:1, customer:1},{$id:2, customer:1},{$id:3, customer:3}]); <del> assertJsonEquals([["GET","Customer/1"],["GET","Customer/3"]], datastore.bulkRequest); <del> datastore.bulkRequest.shift().$$callback({$id:1}); <del> datastore.bulkRequest.shift().$$callback({$id:3}); <del> assertJsonEquals([ <del> {invoice:{$id:1,customer:1},customer:{$id:1}}, <del> {invoice:{$id:2,customer:1},customer:{$id:1}}, <del> {invoice:{$id:3,customer:3},customer:{$id:3}}], invoiceWithCustomer); <del>}; <del> <del>DataStoreTest.prototype.testItShouldThrowIfMoreThanOneEntityIsPrimary = function() { <del> var datastore = new DataStore(); <del> var Invoice = datastore.entity("Invoice"); <del> var Customer = datastore.entity("Customer"); <del> assertThrows("Exactly one entity needs to be primary.", function(){ <del> datastore.join({ <del> invoice:{join:Invoice}, <del> customer:{join:Customer} <del> }); <del> }); <del>}; <del> <del>DataStoreTest.prototype.testItShouldThrowIfLoopInReferences = function() { <del> var datastore = new DataStore(); <del> var Invoice = datastore.entity("Invoice"); <del> var Customer = datastore.entity("Customer"); <del> assertThrows("Infinite loop in join: invoice -> customer", function(){ <del> datastore.join({ <del> invoice:{join:Invoice, on:"customer.invoice"}, <del> customer:{join:Customer, on:"invoice.customer"} <del> }); <del> }); <del>}; <del> <del>DataStoreTest.prototype.testItShouldThrowIfReferenceToNonExistantJoin = function() { <del> var datastore = new DataStore(); <del> var Invoice = datastore.entity("Invoice"); <del> var Customer = datastore.entity("Customer"); <del> assertThrows("Named entity 'x' is undefined.", function(){ <del> datastore.join({ <del> invoice:{join:Invoice, on:"x.invoice"}, <del> customer:{join:Customer, on:"invoice.customer"} <del> }); <del> }); <del>}; <del> <del>DataStoreTest.prototype.testItShouldThrowIfQueryOnNonPrimary = function() { <del> var datastore = new DataStore(); <del> var Invoice = datastore.entity("Invoice"); <del> var Customer = datastore.entity("Customer"); <del> var InvoiceWithCustomer = datastore.join({ <del> invoice:{join:Invoice}, <del> customer:{join:Customer, on:"invoice.customer"} <del> }); <del> assertThrows("Named entity 'customer' is not a primary entity.", function(){ <del> InvoiceWithCustomer.query("customer.month", 1); <del> }); <del>}; <ide><path>test/moveToAngularCom/EntityDeclarationTest.js <del>EntityDeclarationTest = TestCase('EntityDeclarationTest'); <del> <del>EntityDeclarationTest.prototype.testEntityTypeOnly = function(){ <del> expectAsserts(2); <del> var datastore = {entity:function(name){ <del> assertEquals("Person", name); <del> }}; <del> var scope = new Scope(); <del> var init = scope.entity("Person", datastore); <del> assertEquals("", init); <del>}; <del> <del>EntityDeclarationTest.prototype.testWithDefaults = function(){ <del> expectAsserts(4); <del> var datastore = {entity:function(name, init){ <del> assertEquals("Person", name); <del> assertEquals("=a:", init.a); <del> assertEquals(0, init.b.length); <del> }}; <del> var scope = new Scope(); <del> var init = scope.entity('Person:{a:"=a:", b:[]}', datastore); <del> assertEquals("", init); <del>}; <del> <del>EntityDeclarationTest.prototype.testWithName = function(){ <del> expectAsserts(2); <del> var datastore = {entity:function(name, init){ <del> assertEquals("Person", name); <del> return function (){ return {}; }; <del> }}; <del> var scope = new Scope(); <del> var init = scope.entity('friend=Person', datastore); <del> assertEquals("$anchor.friend:{friend=Person.load($anchor.friend);friend.$$anchor=\"friend\";};", init); <del>}; <del> <del>EntityDeclarationTest.prototype.testMultipleEntities = function(){ <del> expectAsserts(3); <del> var expect = ['Person', 'Book']; <del> var i=0; <del> var datastore = {entity:function(name, init){ <del> assertEquals(expect[i], name); <del> i++; <del> return function (){ return {}; }; <del> }}; <del> var scope = new Scope(); <del> var init = scope.entity('friend=Person;book=Book;', datastore); <del> assertEquals("$anchor.friend:{friend=Person.load($anchor.friend);friend.$$anchor=\"friend\";};" + <del> "$anchor.book:{book=Book.load($anchor.book);book.$$anchor=\"book\";};", <del> init); <del>}; <ide><path>test/moveToAngularCom/FileControllerTest.js <del>FileControllerTest = TestCase('FileControllerTest'); <del> <del>FileControllerTest.prototype.XtestOnSelectUpdateView = function(){ <del> var view = jQuery('<span><a/><span/></span>'); <del> var swf = {}; <del> var controller = new FileController(view, null, swf); <del> swf.uploadFile = function(path){}; <del> controller.select('A', 9, '9 bytes'); <del> assertEquals(view.find('a').text(), "A"); <del> assertEquals(view.find('span').text(), "9 bytes"); <del>}; <del> <del>FileControllerTest.prototype.XtestUpdateModelView = function(){ <del> var view = FileController.template(''); <del> var input = $('<input name="value.input">'); <del> var controller; <del> var scope = new Scope({value:{}, $binder:{updateView:function(){ <del> controller.updateView(scope); <del> }}}); <del> view.data('scope', scope); <del> controller = new FileController(view, 'value.input', null, "http://server_base"); <del> var value = '{"text":"A", "size":123, "id":"890"}'; <del> controller.uploadCompleteData(value); <del> controller.updateView(scope); <del> assertEquals(scope.get('value.input.text'), 'A'); <del> assertEquals(scope.get('value.input.size'), 123); <del> assertEquals(scope.get('value.input.id'), '890'); <del> assertEquals(scope.get('value.input.url'), 'http://server_base/_attachments/890/A'); <del> assertEquals(view.find('a').text(), "A"); <del> assertEquals(view.find('a').attr('href'), "http://server_base/_attachments/890/A"); <del> assertEquals(view.find('span').text(), "123 bytes"); <del>}; <del> <del>FileControllerTest.prototype.XtestFileUpload = function(){ <del> expectAsserts(1); <del> var swf = {}; <del> var controller = new FileController(null, null, swf, "http://server_base"); <del> swf.uploadFile = function(path){ <del> assertEquals("http://server_base/_attachments", path); <del> }; <del> controller.name = "Name"; <del> controller.upload(); <del>}; <del> <del>FileControllerTest.prototype.XtestFileUploadNoFileIsNoop = function(){ <del> expectAsserts(0); <del> var swf = {uploadFile:function(path){ <del> fail(); <del> }}; <del> var controller = new FileController(null, swf); <del> controller.upload("basePath", null); <del>}; <del> <del>FileControllerTest.prototype.XtestRemoveAttachment = function(){ <del> var doc = FileController.template(); <del> var input = $('<input name="file">'); <del> var scope = new Scope(); <del> input.data('scope', scope); <del> var controller = new FileController(doc, 'file', null, null); <del> controller.updateView(scope); <del> assertEquals(false, doc.find('input').attr('checked')); <del> <del> scope.set('file', {url:'url', size:123}); <del> controller.updateView(scope); <del> assertEquals(true, doc.find('input').attr('checked')); <del> <del> doc.find('input').attr('checked', false); <del> controller.updateModel(scope); <del> assertNull(scope.get('file')); <del> <del> doc.find('input').attr('checked', true); <del> controller.updateModel(scope); <del> assertEquals('url', scope.get('file.url')); <del> assertEquals(123, scope.get('file.size')); <del>}; <del> <del>FileControllerTest.prototype.XtestShouldEmptyOutOnUndefined = function () { <del> var view = FileController.template('hello'); <del> var controller = new FileController(view, 'abc', null, null); <del> <del> var scope = new Scope(); <del> scope.set('abc', {text: 'myname', url: 'myurl', size: 1234}); <del> <del> controller.updateView(scope); <del> assertEquals("myurl", view.find('a').attr('href')); <del> assertEquals("myname", view.find('a').text()); <del> assertEquals(true, view.find('input').is(':checked')); <del> assertEquals("1.2 KB", view.find('span').text()); <del> <del> scope.set('abc', undefined); <del> controller.updateView(scope); <del> assertEquals("myurl", view.find('a').attr('href')); <del> assertEquals("myname", view.find('a').text()); <del> assertEquals(false, view.find('input').is(':checked')); <del> assertEquals("1.2 KB", view.find('span').text()); <del>}; <del> <del> <ide><path>test/moveToAngularCom/MiscTest.js <del>BinderTest.prototype.testExpandEntityTagWithName = function(){ <del> var c = this.compile('<div ng-entity="friend=Person"/>'); <del> assertEquals( <del> '<div ng-entity="friend=Person" ng-watch="$anchor.friend:{friend=Person.load($anchor.friend);friend.$$anchor=\"friend\";};"></div>', <del> sortedHtml(c.node)); <del> assertEquals("Person", c.scope.$get("friend.$entity")); <del> assertEquals("friend", c.scope.$get("friend.$$anchor")); <del>}; <del> <del>BinderTest.prototype.testExpandSubmitButtonToAction = function(){ <del> var html = this.compileToHtml('<input type="submit" value="Save">'); <del> assertTrue(html, html.indexOf('ng-action="$save()"') > 0 ); <del> assertTrue(html, html.indexOf('ng-bind-attr="{"disabled":"{{$invalidWidgets}}"}"') > 0 ); <del>}; <del> <del>BinderTest.prototype.testReplaceFileUploadWithSwf = function(){ <del> expectAsserts(1); <del> var form = jQuery("body").append('<div id="testTag"><input type="file"></div>'); <del> form.data('scope', new Scope()); <del> var factory = {}; <del> var binder = new Binder(form.get(0), factory, new MockLocation()); <del> factory.createController = function(node){ <del> assertEquals(node.attr('type'), 'file'); <del> return {updateModel:function(){}}; <del> }; <del> binder.compile(); <del> jQuery("#testTag").remove(); <del>}; <del> <del>BinderTest.prototype.testExpandEntityTagWithDefaults = function(){ <del> assertEquals( <del> '<div ng-entity="Person:{a:\"a\"}" ng-watch=""></div>', <del> this.compileToHtml('<div ng-entity=\'Person:{a:"a"}\'/>')); <del>}; <del> <ide><path>test/moveToAngularCom/ModelTest.js <del>ModelTest = TestCase('ModelTest'); <del> <del>ModelTest.prototype.testLoadSaveOperations = function(){ <del> var m1 = new DataStore().entity('A')(); <del> m1.a = 1; <del> <del> var m2 = {b:1}; <del> <del> m1.$loadFrom(m2); <del> <del> assertTrue(!m1.a); <del> assertEquals(m1.b, 1); <del>}; <del> <del>ModelTest.prototype.testLoadfromDoesNotClobberFunctions = function(){ <del> var m1 = new DataStore().entity('A')(); <del> m1.id = function(){return 'OK';}; <del> m1.$loadFrom({id:null}); <del> assertEquals(m1.id(), 'OK'); <del> <del> m1.b = 'OK'; <del> m1.$loadFrom({b:function(){}}); <del> assertEquals(m1.b, 'OK'); <del>}; <del> <del>ModelTest.prototype.testDataStoreDoesNotGetClobbered = function(){ <del> var ds = new DataStore(); <del> var m = ds.entity('A')(); <del> assertTrue(m.$$entity.datastore === ds); <del> m.$loadFrom({}); <del> assertTrue(m.$$entity.datastore === ds); <del>}; <del> <del>ModelTest.prototype.testManagedModelDelegatesMethodsToDataStore = function(){ <del> expectAsserts(7); <del> var datastore = new DataStore(); <del> var model = datastore.entity("A", {a:1})(); <del> var fn = {}; <del> datastore.save = function(instance, callback) { <del> assertTrue(model === instance); <del> assertTrue(callback === fn); <del> }; <del> datastore.remove = function(instance, callback) { <del> assertTrue(model === instance); <del> assertTrue(callback === fn); <del> }; <del> datastore.load = function(instance, id, callback) { <del> assertTrue(model === instance); <del> assertTrue(id === "123"); <del> assertTrue(callback === fn); <del> }; <del> model.$save(fn); <del> model.$delete(fn); <del> model.$loadById("123", fn); <del>}; <del> <del>ModelTest.prototype.testManagedModelCanBeForcedToFlush = function(){ <del> expectAsserts(6); <del> var datastore = new DataStore(); <del> var model = datastore.entity("A", {a:1})(); <del> <del> datastore.save = function(instance, callback) { <del> assertTrue(model === instance); <del> assertTrue(callback === undefined); <del> }; <del> datastore.remove = function(instance, callback) { <del> assertTrue(model === instance); <del> assertTrue(callback === undefined); <del> }; <del> datastore.flush = function(){ <del> assertTrue(true); <del> }; <del> model.$save(true); <del> model.$delete(true); <del>}; <del> <del> <del>ModelTest.prototype.testItShouldMakeDeepCopyOfInitialValues = function (){ <del> var initial = {a:[]}; <del> var entity = new DataStore().entity("A", initial); <del> var model = entity(); <del> model.a.push(1); <del> assertEquals(0, entity().a.length); <del>}; <ide><path>test/moveToAngularCom/ServerTest.js <del>ServerTest = TestCase("ServerTest"); <del>ServerTest.prototype.testBreakLargeRequestIntoPackets = function() { <del> var log = ""; <del> var server = new Server("http://server", function(url){ <del> log += "|" + url; <del> }); <del> server.maxSize = 30; <del> server.uuid = "uuid"; <del> server.request("POST", "/data/database", {}, function(code, r){ <del> assertEquals(200, code); <del> assertEquals("response", r); <del> }); <del> angularCallbacks.uuid0("response"); <del> assertEquals( <del> "|http://server/$/uuid0/2/1?h=eyJtIjoiUE9TVCIsInAiOnt9LCJ1Ij" + <del> "|http://server/$/uuid0/2/2?h=oiL2RhdGEvZGF0YWJhc2UifQ==", <del> log); <del>}; <del> <del>ServerTest.prototype.testItShouldEncodeUsingUrlRules = function() { <del> var server = new Server("http://server"); <del> assertEquals("fn5-fn5-", server.base64url("~~~~~~")); <del> assertEquals("fn5_fn5_", server.base64url("~~\u007f~~\u007f")); <del>}; <del> <del>FrameServerTest = TestCase("FrameServerTest"); <del> <del>FrameServerTest.prototype = { <del> testRead:function(){ <del> var window = {name:'$DATASET:"MyData"'}; <del> var server = new FrameServer(window); <del> server.read(); <del> assertEquals("MyData", server.data); <del> }, <del> testWrite:function(){ <del> var window = {}; <del> var server = new FrameServer(window); <del> server.data = "TestData"; <del> server.write(); <del> assertEquals('$DATASET:"TestData"', window.name); <del> } <del>}; <ide><path>test/moveToAngularCom/UsersTest.js <del>// Copyright (C) 2008,2009 BRAT Tech LLC <del> <del>UsersTest = TestCase("UsersTest"); <del> <del>UsersTest.prototype = { <del> setUp:function(){}, <del> <del> tearDown:function(){}, <del> <del> testItShouldFetchCurrentUser:function(){ <del> expectAsserts(5); <del> var user; <del> var users = new Users({request:function(method, url, request, callback){ <del> assertEquals("GET", method); <del> assertEquals("/account.json", url); <del> assertEquals("{}", toJson(request)); <del> callback(200, {$status_code:200, user:{name:'misko'}}); <del> }}); <del> users.fetchCurrentUser(function(u){ <del> user = u; <del> assertEquals("misko", u.name); <del> assertEquals("misko", users.current.name); <del> }); <del> } <del> <del>};
19
Python
Python
choose format according to filename when plotting
e3a64cc8a74a0fd2f50615e80970df1d6263e7e8
<ide><path>keras/utils/visualize_util.py <add>import os <add> <ide> try: <ide> # pydot-ng is a fork of pydot that is better maintained <ide> import pydot_ng as pydot <ide> def model_to_dot(model, show_shapes=False, show_layer_names=True): <ide> <ide> def plot(model, to_file='model.png', show_shapes=False, show_layer_names=True): <ide> dot = model_to_dot(model, show_shapes, show_layer_names) <del> dot.write_png(to_file) <add> _, format = os.path.splitext(to_file) <add> if not format: <add> format = 'png' <add> else: <add> format = format[1:] <add> dot.write(to_file, format=format)
1
Javascript
Javascript
fix coding style in web/viewer.js
9e0ed5ca7ec7dee99951e883abe09daaab190389
<ide><path>web/viewer.js <ide> var PDFView = { <ide> viewAreaElement.addEventListener('scroll', function webViewerScroll(evt) { <ide> var currentY = viewAreaElement.scrollTop; <ide> var lastY = state.lastY; <del> if (currentY > lastY) <add> if (currentY > lastY) { <ide> state.down = true; <del> else if (currentY < lastY) <add> } else if (currentY < lastY) { <ide> state.down = false; <add> } <ide> // else do nothing and use previous value <ide> state.lastY = currentY; <ide> callback(); <ide> var PDFView = { <ide> } <ide> var args = e.data; <ide> <del> if (typeof args !== 'object' || !('pdfjsLoadAction' in args)) <add> if (typeof args !== 'object' || !('pdfjsLoadAction' in args)) { <ide> return; <add> } <ide> switch (args.pdfjsLoadAction) { <ide> case 'supportsRangedLoading': <ide> PDFView.open(args.pdfUrl, 0, undefined, pdfDataRangeTransport, { <ide> var PDFView = { <ide> }, <ide> <ide> getDestinationHash: function pdfViewGetDestinationHash(dest) { <del> if (typeof dest === 'string') <add> if (typeof dest === 'string') { <ide> return PDFView.getAnchorUrl('#' + escape(dest)); <add> } <ide> if (dest instanceof Array) { <ide> var destRef = dest[0]; // see navigateTo method for dest format <ide> var pageNumber = destRef instanceof Object ? <ide> var PDFView = { <ide> var thumbsView = document.getElementById('thumbnailView'); <ide> thumbsView.parentNode.scrollTop = 0; <ide> <del> while (thumbsView.hasChildNodes()) <add> while (thumbsView.hasChildNodes()) { <ide> thumbsView.removeChild(thumbsView.lastChild); <add> } <ide> <del> if ('_loadingInterval' in thumbsView) <add> if ('_loadingInterval' in thumbsView) { <ide> clearInterval(thumbsView._loadingInterval); <add> } <ide> <ide> var container = document.getElementById('viewer'); <del> while (container.hasChildNodes()) <add> while (container.hasChildNodes()) { <ide> container.removeChild(container.lastChild); <add> } <ide> <ide> var pagesCount = pdfDocument.numPages; <ide> <ide> var PDFView = { <ide> (PDFJS.version ? ' (PDF.js: ' + PDFJS.version + ')' : '')); <ide> <ide> var pdfTitle; <del> if (metadata) { <del> if (metadata.has('dc:title')) <del> pdfTitle = metadata.get('dc:title'); <add> if (metadata && metadata.has('dc:title')) { <add> pdfTitle = metadata.get('dc:title'); <ide> } <ide> <del> if (!pdfTitle && info && info['Title']) <add> if (!pdfTitle && info && info['Title']) { <ide> pdfTitle = info['Title']; <add> } <ide> <del> if (pdfTitle) <add> if (pdfTitle) { <ide> self.setTitle(pdfTitle + ' - ' + document.title); <add> } <ide> <ide> if (info.IsAcroFormPresent) { <ide> console.warn('Warning: AcroForm/XFA is not supported'); <ide> var PDFView = { <ide> } <ide> for (var i = 0; i < numVisible; ++i) { <ide> var view = visibleViews[i].view; <del> if (!this.isViewFinished(view)) <add> if (!this.isViewFinished(view)) { <ide> return view; <add> } <ide> } <ide> <ide> // All the visible views have rendered, try to render next/previous pages. <ide> if (scrolledDown) { <ide> var nextPageIndex = visible.last.id; <ide> // ID's start at 1 so no need to add 1. <del> if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) <add> if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) { <ide> return views[nextPageIndex]; <add> } <ide> } else { <ide> var previousPageIndex = visible.first.id - 2; <ide> if (views[previousPageIndex] && <del> !this.isViewFinished(views[previousPageIndex])) <add> !this.isViewFinished(views[previousPageIndex])) { <ide> return views[previousPageIndex]; <add> } <ide> } <ide> // Everything that needs to be rendered has been. <ide> return false; <ide> var PDFView = { <ide> }, <ide> <ide> setHash: function pdfViewSetHash(hash) { <del> if (!hash) <add> if (!hash) { <ide> return; <add> } <ide> <ide> if (hash.indexOf('=') >= 0) { <ide> var params = PDFView.parseQueryString(hash); <ide> var PDFView = { <ide> thumbsView.classList.add('hidden'); <ide> outlineView.classList.remove('hidden'); <ide> <del> if (outlineButton.getAttribute('disabled')) <add> if (outlineButton.getAttribute('disabled')) { <ide> return; <add> } <ide> break; <ide> } <ide> }, <ide> var PDFView = { <ide> <ide> afterPrint: function pdfViewSetupAfterPrint() { <ide> var div = document.getElementById('printContainer'); <del> while (div.hasChildNodes()) <add> while (div.hasChildNodes()) { <ide> div.removeChild(div.lastChild); <add> } <ide> }, <ide> <ide> rotatePages: function pdfViewRotatePages(delta) { <ide> var PDFView = { <ide> // In case one page has already been flipped there is a cooldown time <ide> // which has to expire before next page can be scrolled on to. <ide> if (currentTime > storedTime && <del> currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) <add> currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) { <ide> return; <add> } <ide> <ide> // In case the user decides to scroll to the opposite direction than before <ide> // clear the accumulated delta. <ide> if ((this.mouseScrollDelta > 0 && mouseScrollDelta < 0) || <del> (this.mouseScrollDelta < 0 && mouseScrollDelta > 0)) <add> (this.mouseScrollDelta < 0 && mouseScrollDelta > 0)) { <ide> this.clearMouseScrollState(); <add> } <ide> <ide> this.mouseScrollDelta += mouseScrollDelta; <ide> <ide> var PDFView = { <ide> // to do anything. <ide> if ((currentPage == 1 && pageFlipDirection == PageFlipDirection.UP) || <ide> (currentPage == this.pages.length && <del> pageFlipDirection == PageFlipDirection.DOWN)) <add> pageFlipDirection == PageFlipDirection.DOWN)) { <ide> return; <add> } <ide> <ide> this.page += pageFlipDirection; <ide> this.mouseScrollTimeStamp = currentTime; <ide> var PDFView = { <ide> var DocumentOutlineView = function documentOutlineView(outline) { <ide> var outlineView = document.getElementById('outlineView'); <ide> var outlineButton = document.getElementById('viewOutline'); <del> while (outlineView.firstChild) <add> while (outlineView.firstChild) { <ide> outlineView.removeChild(outlineView.firstChild); <add> } <ide> <ide> if (!outline) { <del> if (!outlineView.classList.contains('hidden')) <add> if (!outlineView.classList.contains('hidden')) { <ide> PDFView.switchSidebarView('thumbs'); <del> <add> } <ide> return; <ide> } <ide> <ide> function webViewerLoad(evt) { <ide> <ide> //#if !(FIREFOX || MOZCENTRAL) <ide> var locale = PDFJS.locale || navigator.language; <del> if ('locale' in hashParams) <add> if ('locale' in hashParams) { <ide> locale = hashParams['locale']; <add> } <ide> mozL10n.setLanguage(locale); <ide> //#endif <ide> //#if (FIREFOX || MOZCENTRAL) <ide> document.addEventListener('DOMContentLoaded', webViewerLoad, true); <ide> <ide> function updateViewarea() { <ide> <del> if (!PDFView.initialized) <add> if (!PDFView.initialized) { <ide> return; <add> } <ide> var visible = PDFView.getVisiblePages(); <ide> var visiblePages = visible.views; <ide> if (visiblePages.length === 0) { <ide> function updateViewarea() { <ide> i < ii; ++i) { <ide> var page = visiblePages[i]; <ide> <del> if (page.percent < 100) <add> if (page.percent < 100) { <ide> break; <del> <add> } <ide> if (page.id === PDFView.page) { <ide> stillFullyVisible = true; <ide> break; <ide> window.addEventListener('hashchange', function webViewerHashchange(evt) { <ide> //#if !(FIREFOX || MOZCENTRAL || CHROME) <ide> window.addEventListener('change', function webViewerChange(evt) { <ide> var files = evt.target.files; <del> if (!files || files.length === 0) <add> if (!files || files.length === 0) { <ide> return; <del> <add> } <ide> var file = files[0]; <ide> <ide> if (!PDFJS.disableCreateObjectURL &&
1
Javascript
Javascript
fix typo in api docs
b62327ec2de6d78b85e0662bb55b3d5b54a50f34
<ide><path>src/ng/directive/booleanAttrs.js <ide> * The HTML specs do not require browsers to preserve the special attributes such as open. <ide> * (The presence of them means true and absence means false) <ide> * This prevents the angular compiler from correctly retrieving the binding expression. <del> * To solve this problem, we introduce the `ngMultiple` directive. <add> * To solve this problem, we introduce the `ngOpen` directive. <ide> * <ide> * @example <ide> <doc:example>
1
Text
Text
fix broken link
d1da2c711c68bb2e59f68de53dcc369f8c669c61
<ide><path>docs/tutorials/quick-start.md <ide> Here's the complete counter application as a running CodeSandbox: <ide> <ide> ## What's Next? <ide> <del>We recommend going through [**the "Redux Essentials" and "Redux Fundamentals" tutorials in the Redux core docs**](./tutorials-index), which will give you a complete understanding of how Redux works, what Redux Toolkit does, and how to use it correctly. <add>We recommend going through [**the "Redux Essentials" and "Redux Fundamentals" tutorials in the Redux core docs**](./tutorials-index.md), which will give you a complete understanding of how Redux works, what Redux Toolkit does, and how to use it correctly.
1
Text
Text
update permissions.md to fix garden path sentences
53a0585dacea328ce74083f0da0dea10c4df03e5
<ide><path>docs/api-guide/permissions.md <ide> A slightly less strict style of permission would be to allow full access to auth <ide> Permissions in REST framework are always defined as a list of permission classes. <ide> <ide> Before running the main body of the view each permission in the list is checked. <del>If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run. <add>If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run. <ide> <del>When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules: <add>When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules: <ide> <ide> * The request was successfully authenticated, but permission was denied. *&mdash; An HTTP 403 Forbidden response will be returned.* <ide> * The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *&mdash; An HTTP 403 Forbidden response will be returned.*
1
Python
Python
remove erronous _delete attribute
32e0e5e18c84e7b720c74df8aeba26e0f335bbf6
<ide><path>rest_framework/serializers.py <ide> def __init__(self, instance=None, data=None, files=None, <ide> self._data = None <ide> self._files = None <ide> self._errors = None <del> self._delete = False <ide> <ide> ##### <ide> # Methods to determine which fields to use when (de)serializing objects.
1
Ruby
Ruby
stop safebuffer#clone_empty from issuing warnings
681d89f96bc1784edecf74992177a48be07e2b99
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def initialize_copy(other) <ide> end <ide> <ide> def clone_empty <del> new_safe_buffer = self[0, 0] <del> new_safe_buffer.instance_variable_set(:@dirty, @dirty) <del> new_safe_buffer <add> self[0, 0] <ide> end <ide> <ide> def concat(value)
1
Javascript
Javascript
add animationiterationcount in isunitlessnumber
28329e86550eab061dd36175fbcfc053188f6bff
<ide><path>src/renderers/dom/shared/CSSProperty.js <ide> * CSS properties which accept numbers but are not in units of "px". <ide> */ <ide> var isUnitlessNumber = { <add> animationIterationCount: true, <ide> boxFlex: true, <ide> boxFlexGroup: true, <ide> columnCount: true,
1
Javascript
Javascript
fix uiexplorer freezing / persistence
d178e27939fe596ec4740c145e384e7aeb3bef85
<ide><path>Examples/UIExplorer/UIExplorerList.ios.js <ide> class UIExplorerList extends React.Component { <ide> ); <ide> } <ide> <del> componentWillMount() { <del> this.props.navigator.navigationContext.addListener('didfocus', function(event) { <del> if (event.data.route.title === 'UIExplorer') { <del> Settings.set({visibleExample: null}); <del> } <del> }); <del> } <del> <ide> componentDidMount() { <del> var visibleExampleTitle = Settings.get('visibleExample'); <del> if (visibleExampleTitle) { <del> var predicate = (example) => example.title === visibleExampleTitle; <del> var foundExample = APIS.find(predicate) || COMPONENTS.find(predicate); <del> if (foundExample) { <del> setTimeout(() => this._openExample(foundExample), 100); <add> var wasUIExplorer = false; <add> var didOpenExample = false; <add> <add> this.props.navigator.navigationContext.addListener('didfocus', (event) => { <add> var isUIExplorer = event.data.route.title === 'UIExplorer'; <add> <add> if (!didOpenExample && isUIExplorer) { <add> didOpenExample = true; <add> <add> var visibleExampleTitle = Settings.get('visibleExample'); <add> if (visibleExampleTitle) { <add> var predicate = (example) => example.title === visibleExampleTitle; <add> var foundExample = APIS.find(predicate) || COMPONENTS.find(predicate); <add> if (foundExample) { <add> setTimeout(() => this._openExample(foundExample), 100); <add> } <add> } else if (!wasUIExplorer && isUIExplorer) { <add> Settings.set({visibleExample: null}); <add> } <ide> } <del> } <add> <add> wasUIExplorer = isUIExplorer; <add> }); <ide> } <ide> <ide> renderAdditionalView(renderRow: Function, renderTextInput: Function): React.Component { <ide><path>Examples/UIExplorer/UIExplorerList.js <ide> class UIExplorerList extends React.Component { <ide> <ide> componentDidMount() { <ide> this._search(this.state.searchText); <del> <del> var visibleExampleTitle = Settings.get('visibleExample'); <del> if (visibleExampleTitle) { <del> var predicate = (example) => example.title === visibleExampleTitle; <del> var foundExample = APIS.find(predicate) || COMPONENTS.find(predicate); <del> if (foundExample) { <del> setTimeout(() => this._openExample(foundExample), 100); <del> } <del> } <ide> } <ide> <ide> render() {
2