content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
add missing semis after classes
ad27e0e9a187fea925dd0902aa229bc7c4bdb6c0
<ide><path>doc/guides/cpp-style-guide.md <ide> For plain C-like structs snake_case can be used. <ide> ```cpp <ide> struct foo_bar { <ide> int name; <del>} <add>}; <ide> ``` <ide> <ide> ### Space after `template` <ide> struct foo_bar { <ide> template <typename T> <ide> class FancyContainer { <ide> ... <del>} <add>}; <ide> ``` <ide> <ide> ## Memory management
1
Ruby
Ruby
add note about test path to create template
6857e2ed34b35e2a8168f4cd47d3cc3e057a92bd
<ide><path>Library/Homebrew/cmd/create.rb <ide> def install <ide> # This test will fail and we won't accept that! It's enough to just replace <ide> # "false" with the main program this formula installs, but it'd be nice if you <ide> # were more thorough. Run the test with `brew test #{name}`. <add> # <add> # The installed folder is not in the path, so use the entire path to any <add> # executables being tested: `system "#{bin}/program", "--version"`. <ide> system "false" <ide> end <ide> end
1
Python
Python
add nodes names to duplicatenodenamewarning
3626b4c9b82a44fa78d4fbea3e3abc7349ffdbf3
<ide><path>celery/app/control.py <ide> __all__ = ['Inspect', 'Control', 'flatten_reply'] <ide> <ide> W_DUPNODE = """\ <del>Received multiple replies from node name: {0!r}. <add>Received multiple replies from node {0}: {1}. <ide> Please make sure you give each node a unique nodename using the `-n` option.\ <ide> """ <ide> <ide><path>celery/tests/app/test_control.py <ide> from kombu.pidbox import Mailbox <ide> <ide> from celery.app import control <add>from celery.exceptions import DuplicateNodenameWarning <ide> from celery.utils import uuid <ide> from celery.tests.case import AppCase <ide> <ide> def test_flatten_reply(self): <ide> {'[email protected]': {'hello': 20}}, <ide> {'[email protected]': {'hello': 30}} <ide> ] <del> with warnings.catch_warnings(record=True) as w: <add> with self.assertWarns(DuplicateNodenameWarning) as w: <ide> nodes = control.flatten_reply(reply) <del> self.assertIn( <del> 'multiple replies', <del> str(w[-1].message), <del> ) <del> self.assertIn('[email protected]', nodes) <del> self.assertIn('[email protected]', nodes) <add> <add> self.assertIn( <add> 'Received multiple replies from node name: [email protected].', <add> str(w.warning) <add> ) <add> self.assertIn('[email protected]', nodes) <add> self.assertIn('[email protected]', nodes) <ide> <ide> <ide> class test_inspect(AppCase):
2
PHP
PHP
add documentation for schema
8132247e3d06cb1b3fcf80fa9e288f457812a743
<ide><path>src/Form/Schema.php <ide> */ <ide> class Schema { <ide> <add>/** <add> * The fields in this schema. <add> * <add> * @var array <add> */ <ide> protected $_fields = []; <ide> <add>/** <add> * The default values for fields. <add> * <add> * @var array <add> */ <ide> protected $_fieldDefaults = [ <ide> 'type' => null, <ide> 'length' => null, <ide> 'required' => false, <ide> ]; <ide> <add>/** <add> * Adds a field to the schema. <add> * <add> * @param string $name The field name. <add> * @param string|array $attrs The attributes for the field, or the type <add> * as a string. <add> * @return $this <add> */ <ide> public function addField($name, $attrs) { <add> if (is_string($attrs)) { <add> $attrs = ['type' => $attrs]; <add> } <ide> $attrs = array_intersect_key($attrs, $this->_fieldDefaults); <ide> $this->_fields[$name] = $attrs + $this->_fieldDefaults; <ide> return $this; <ide> } <ide> <add>/** <add> * Removes a field to the schema. <add> * <add> * @param string $name The field to remove. <add> * @return $this <add> */ <ide> public function removeField($name) { <ide> unset($this->_fields[$name]); <ide> return $this; <ide> } <ide> <add>/** <add> * Get the list of fields in the schema. <add> * <add> * @return array The list of field names. <add> */ <ide> public function fields() { <ide> return array_keys($this->_fields); <ide> } <ide> <add>/** <add> * Get the attributes for a given field. <add> * <add> * @param string $name The field name. <add> * @return null|array The attributes for a field, or null. <add> */ <ide> public function field($name) { <ide> if (!isset($this->_fields[$name])) { <ide> return null; <ide> } <ide> return $this->_fields[$name]; <ide> } <add> <ide> } <ide><path>tests/TestCase/Form/SchemaTest.php <ide> public function testAddingFields() { <ide> $res = $schema->field('name'); <ide> $expected = ['type' => 'string', 'length' => null, 'required' => false]; <ide> $this->assertEquals($expected, $res); <add> <add> $res = $schema->addField('email', 'string'); <add> $this->assertSame($schema, $res, 'Should be chainable'); <add> <add> $this->assertEquals(['name', 'email'], $schema->fields()); <add> $res = $schema->field('email'); <add> $expected = ['type' => 'string', 'length' => null, 'required' => false]; <add> $this->assertEquals($expected, $res); <ide> } <ide> <ide> /**
2
Text
Text
fix a typo in /doc/sources/reference/run.md
64fd944e30c8c045f6d998cc5ca950ea272541b5
<ide><path>docs/sources/reference/run.md <ide> the number of containers running on the system. <ide> For example, consider three containers, one has a cpu-share of 1024 and <ide> two others have a cpu-share setting of 512. When processes in all three <ide> containers attempt to use 100% of CPU, the first container would receive <del>50% of the total CPU time. If you add a fouth container with a cpu-share <add>50% of the total CPU time. If you add a fourth container with a cpu-share <ide> of 1024, the first container only gets 33% of the CPU. The remaining containers <ide> receive 16.5%, 16.5% and 33% of the CPU. <ide>
1
Text
Text
add v3.13.0-beta.1 to changelog
1f5eee0f762a808d38ed1c466b5fa013fe0e6688
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.13.0-beta.1 (August 6, 2019) <add> <add>- [#16366](https://github.com/emberjs/ember.js/pull/16366) / [#16903](https://github.com/emberjs/ember.js/pull/16903) / [#17572](https://github.com/emberjs/ember.js/pull/17572) / [#17682](https://github.com/emberjs/ember.js/pull/17682) / [#17765](https://github.com/emberjs/ember.js/pull/17765) / [#17751](https://github.com/emberjs/ember.js/pull/17751) / [#17835](https://github.com/emberjs/ember.js/pull/17835) / [#18059](https://github.com/emberjs/ember.js/pull/18059) / [#17951](https://github.com/emberjs/ember.js/pull/17951) / [#18069](https://github.com/emberjs/ember.js/pull/18069) / [#18074](https://github.com/emberjs/ember.js/pull/18074) / [#18073](https://github.com/emberjs/ember.js/pull/18073) / [#18091](https://github.com/emberjs/ember.js/pull/18091) / [#18186](https://github.com/emberjs/ember.js/pull/18186) [FEATURE] Implement the [Tracked Properties](https://github.com/emberjs/rfcs/blob/master/text/0410-tracked-properties.md) and [Tracked Property Updates](https://github.com/emberjs/rfcs/blob/master/text/0478-tracked-properties-updates.md) RFCs. <add>- [#18158](https://github.com/emberjs/ember.js/pull/18158) / [#18203](https://github.com/emberjs/ember.js/pull/18203) / [#18198](https://github.com/emberjs/ember.js/pull/18198) / [#18190](https://github.com/emberjs/ember.js/pull/18190) [FEATURE] Implement the [Component Templates Co-location](https://github.com/emberjs/rfcs/blob/master/text/0481-component-templates-co-location.md). <add>- [#18214](https://github.com/emberjs/ember.js/pull/18214) [DEPRECATION] Implement the [Deprecate support for mouseEnter/Leave/Move Ember events](https://github.com/emberjs/rfcs/blob/master/text/0486-deprecate-mouseenter.md). <add>- [#18217](https://github.com/emberjs/ember.js/pull/18217) [BUGFIX] Adds ability for computed props to depend on args <add>- [#18222](https://github.com/emberjs/ember.js/pull/18222) [BUGFIX] Matches assertion behavior for CPs computing after destroy <add> <ide> ### v3.12.0 (August 5, 2019) <ide> <ide> - [#18159](https://github.com/emberjs/ember.js/pull/18159) [BUGFIX] Update router.js to ensure buildRouteInfoMetadata does not eagerly cache routes in lazy Engines
1
PHP
PHP
add method to get generated message body as string
921a1d10510ba7da7430e1f9a6a8d4fdbe7e8839
<ide><path>src/Mailer/Message.php <ide> public function getBody(?string $type = null) <ide> return $this->message; <ide> } <ide> <add> /** <add> * Get generated body as string. <add> * <add> * @param string $eol End of line string for imploding. <add> * @return string <add> * @see Message::getBody() <add> */ <add> public function getBodyString(string $eol = "\r\n"): string <add> { <add> /** @var array $lines */ <add> $lines = $this->getBody(); <add> <add> return implode($eol, $lines); <add> } <add> <ide> /** <ide> * Create unique boundary identifier <ide> * <ide><path>src/Mailer/Transport/MailTransport.php <ide> function ($val) { <ide> $subject = str_replace(["\r", "\n"], '', $message->getSubject()); <ide> $to = str_replace(["\r", "\n"], '', $to); <ide> <del> $message = implode($eol, (array)$message->getBody()); <add> $message = $message->getBodyString($eol); <ide> <ide> $params = $this->_config['additionalParameters'] ?? ''; <ide> $this->_mail($to, $subject, $message, $headers, $params);
2
Javascript
Javascript
add spaces to plugin names
d73ad04c72cf7944aa45b88010119b561e4acf9b
<ide><path>lib/BannerPlugin.js <ide> class BannerPlugin { <ide> if(arguments.length > 1) <ide> throw new Error("BannerPlugin only takes one argument (pass an options object)"); <ide> <del> validateOptions(bannerPluginSchema, options, "BannerPlugin"); <add> validateOptions(bannerPluginSchema, options, "Banner Plugin"); <ide> <ide> if(typeof options === "string") <ide> options = { <ide><path>lib/DllPlugin.js <ide> const dllPluginSchema = require("../schemas/plugins/dllPluginSchema.json"); <ide> <ide> class DllPlugin { <ide> constructor(options) { <del> validateOptions(dllPluginSchema, options, "DllPlugin"); <add> validateOptions(dllPluginSchema, options, "Dll Plugin"); <ide> this.options = options; <ide> } <ide> <ide><path>lib/DllReferencePlugin.js <ide> const dllReferencePluginSchema = require("../schemas/plugins/dllReferencePluginS <ide> <ide> class DllReferencePlugin { <ide> constructor(options) { <del> validateOptions(dllReferencePluginSchema, options, "DllReferencePlugin"); <add> validateOptions(dllReferencePluginSchema, options, "Dll Reference Plugin"); <ide> this.options = options; <ide> } <ide> <ide><path>lib/HashedModuleIdsPlugin.js <ide> const hashedModuleIdsPluginSchema = require("../schemas/plugins/hashedModuleIdsP <ide> <ide> class HashedModuleIdsPlugin { <ide> constructor(options) { <del> validateOptions(hashedModuleIdsPluginSchema, options || {}, "HashedModuleIdsPlugin"); <add> validateOptions(hashedModuleIdsPluginSchema, options || {}, "Hashed Module Ids Plugin"); <ide> <ide> this.options = Object.assign({ <ide> hashFunction: "md5", <ide><path>lib/LoaderOptionsPlugin.js <ide> const loaderOptionsPluginSchema = require("../schemas/plugins/loaderOptionsPlugi <ide> <ide> class LoaderOptionsPlugin { <ide> constructor(options) { <del> validateOptions(loaderOptionsPluginSchema, options || {}, "LoaderOptionsPlugin"); <add> validateOptions(loaderOptionsPluginSchema, options || {}, "Loader Options Plugin"); <ide> <ide> if(typeof options !== "object") options = {}; <ide> if(!options.test) options.test = { <ide><path>lib/SourceMapDevToolPlugin.js <ide> class SourceMapDevToolPlugin { <ide> if(arguments.length > 1) <ide> throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)"); <ide> <del> validateOptions(sourceMapDevToolPluginSchema, options || {}, "SourceMapDevToolPlugin"); <add> validateOptions(sourceMapDevToolPluginSchema, options || {}, "Source Map Dev Tool Plugin"); <ide> <ide> if(!options) options = {}; <ide> this.sourceMapFilename = options.filename; <ide><path>lib/WatchIgnorePlugin.js <ide> const watchIgnorePluginSchema = require("../schemas/plugins/watchIgnorePluginSch <ide> <ide> class WatchIgnorePlugin { <ide> constructor(paths) { <del> validateOptions(watchIgnorePluginSchema, paths, "WatchIgnorePlugin"); <add> validateOptions(watchIgnorePluginSchema, paths, "Watch Ignore Plugin"); <ide> this.paths = paths; <ide> } <ide> <ide><path>lib/optimize/AggressiveSplittingPlugin.js <ide> function copyWithReason(obj) { <ide> <ide> class AggressiveSplittingPlugin { <ide> constructor(options) { <del> validateOptions(aggressiveSplittingPluginSchema, options || {}, "AggressiveSplittingPlugin"); <add> validateOptions(aggressiveSplittingPluginSchema, options || {}, "Aggressive Splitting Plugin"); <ide> <ide> this.options = options || {}; <ide> if(typeof this.options.minSize !== "number") this.options.minSize = 30 * 1024; <ide><path>lib/optimize/CommonsChunkPlugin.js <ide> The available options are: <ide> minSize: number`); <ide> } <ide> <del> validateOptions(commonsChunkPluginSchema, options, "CommonsChunkPlugin"); <add> validateOptions(commonsChunkPluginSchema, options, "Commons Chunk Plugin"); <ide> <ide> const normalizedOptions = this.normalizeOptions(options); <ide> <ide><path>lib/optimize/LimitChunkCountPlugin.js <ide> const limitChunkCountPluginSchema = require("../../schemas/plugins/optimize/limi <ide> <ide> class LimitChunkCountPlugin { <ide> constructor(options) { <del> validateOptions(limitChunkCountPluginSchema, options || {}, "LimitChunkCountPlugin"); <add> validateOptions(limitChunkCountPluginSchema, options || {}, "Limit Chunk Count Plugin"); <ide> this.options = options || {}; <ide> } <ide> apply(compiler) { <ide><path>lib/optimize/MinChunkSizePlugin.js <ide> const minChunkSizePluginSchema = require("../../schemas/plugins/optimize/minChun <ide> <ide> class MinChunkSizePlugin { <ide> constructor(options) { <del> validateOptions(minChunkSizePluginSchema, options, "MinChunkSizePlugin"); <add> validateOptions(minChunkSizePluginSchema, options, "Min Chunk Size Plugin"); <ide> this.options = options; <ide> } <ide>
11
Javascript
Javascript
add proptype validation for next/head children
98568046a328ec4fb050d8770ac1d06f69e509fc
<ide><path>packages/next-server/lib/head.js <ide> function unique () { <ide> } <ide> } <ide> <add>if (process.env.NODE_ENV === 'development') { <add> const exact = require('prop-types-exact') <add> <add> Head.propTypes = exact({ <add> children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]).isRequired <add> }) <add>} <add> <ide> export default sideEffect(reduceComponents, onStateChange, mapOnServer)(Head)
1
Javascript
Javascript
fix bug in clonewithprops()
1e980a146f2e500c4beaac2240b0a072eedb70d5
<ide><path>src/core/ReactCompositeComponent.js <ide> var ReactCompositeComponent = { <ide> return instance; <ide> }; <ide> ConvenienceConstructor.componentConstructor = Constructor; <add> Constructor.ConvenienceConstructor = ConvenienceConstructor; <ide> ConvenienceConstructor.originalSpec = spec; <ide> <ide> mixSpecIntoComponent(ConvenienceConstructor, spec); <ide><path>src/utils/__tests__/cloneWithProps-test.js <ide> describe('cloneWithProps', function() { <ide> onlyChild = require('onlyChild'); <ide> }); <ide> <del> it('should clone an object with new props', function() { <add> it('should clone a DOM component with new props', function() { <ide> var Grandparent = React.createClass({ <ide> render: function() { <ide> return <Parent><div className="child" /></Parent>; <ide> describe('cloneWithProps', function() { <ide> .toBe('child xyz'); <ide> }); <ide> <add> it('should clone a composite component with new props', function() { <add> <add> var Child = React.createClass({ <add> render: function() { <add> return <div className={this.props.className} />; <add> } <add> }); <add> <add> var Grandparent = React.createClass({ <add> render: function() { <add> return <Parent><Child className="child" /></Parent>; <add> } <add> }); <add> var Parent = React.createClass({ <add> render: function() { <add> return ( <add> <div className="parent"> <add> {cloneWithProps(onlyChild(this.props.children), {className: 'xyz'})} <add> </div> <add> ); <add> } <add> }); <add> var component = ReactTestUtils.renderIntoDocument(<Grandparent />); <add> expect(component.getDOMNode().childNodes[0].className) <add> .toBe('child xyz'); <add> }); <add> <ide> it('should warn when cloning with refs', function() { <ide> var Grandparent = React.createClass({ <ide> render: function() {
2
Text
Text
fix mad libs sample in spanish translation
f7f1b4cbc730cf54b03d64367b5c4c264ac54441
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.spanish.md <ide> localeTitle: Palabras en blanco <ide> --- <ide> <ide> ## Description <del><section id="description"> Ahora usaremos nuestro conocimiento de cuerdas para construir un juego de palabras de estilo &quot; <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a> &quot; que llamamos &quot;Palabras en blanco&quot;. Creará una oración estilo &quot;Rellene los espacios en blanco&quot; (opcionalmente humorística). En un juego de &quot;Mad Libs&quot;, se te proporcionan oraciones con algunas palabras faltantes, como sustantivos, verbos, adjetivos y adverbios. Luego, completa las piezas faltantes con las palabras que elijas de manera que la oración completa tenga sentido. Considere esta oración: &quot;Fue realmente <strong>____</strong> , y nosotros <strong>____</strong> nosotros <strong>____</strong> &quot;. Esta oración tiene tres partes faltantes: un adjetivo, un verbo y un adverbio, y podemos agregar palabras de nuestra elección para completarla. Luego podemos asignar la oración completa a una variable de la siguiente manera: <blockquote> var frase = &quot;Era realmente&quot; + &quot;caliente&quot; + &quot;, y nosotros&quot; + &quot;reímos&quot; + &quot;nosotros mismos&quot; + &quot;tonto&quot;. </blockquote></section> <add><section id="description"> Ahora usaremos nuestro conocimiento de cadenas para construir un juego de palabras de estilo &quot; <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a> &quot; que llamamos &quot;Palabras en blanco&quot;. Creará una oración estilo &quot;Rellene los espacios en blanco&quot; (opcionalmente humorística). En un juego de &quot;Mad Libs&quot;, se te proporcionan oraciones con algunas palabras faltantes, como sustantivos, verbos, adjetivos y adverbios. Luego, completa las piezas faltantes con las palabras que elijas de manera que la oración completa tenga sentido. Considere esta oración: &quot;Estaba realmente <strong>____</strong> , y nosotros nos <strong>____</strong> muy <strong>____</strong> &quot;. Esta oración tiene tres partes faltantes: un adjetivo, un verbo y un adverbio, y podemos agregar palabras de nuestra elección para completarla. Luego podemos asignar la oración completa a una variable de la siguiente manera: <blockquote> var frase = &quot;Estaba realmente&quot; + &quot;soleado&quot; + &quot;, y nosotros nos&quot; + &quot;reímos&quot; + &quot;muy&quot; + &quot;tontamente&quot;. </blockquote></section> <ide> <ide> ## Instructions <ide> <section id="instructions"> En este desafío, le proporcionamos un sustantivo, un verbo, un adjetivo y un adverbio. Debe formar una oración completa con las palabras de su elección, junto con las palabras que proporcionamos. Deberá utilizar el operador de concatenación de cadenas <code>+</code> para crear una nueva cadena, utilizando las variables proporcionadas: <code>myNoun</code> , <code>myAdjective</code> , <code>myVerb</code> y <code>myAdverb</code> . A continuación, asignará la cadena formada a la variable de <code>result</code> . También deberá tener en cuenta los espacios en su cadena, de modo que la oración final tenga espacios entre todas las palabras. El resultado debe ser una oración completa. </section>
1
Text
Text
fix process.stdout fd number
88daf88bd3f6201095fbc0a70f2b672eee7f199a
<ide><path>doc/api/process.md <ide> must call `process.stdin.resume()` to read from it. Note also that calling <ide> * {Stream} <ide> <ide> The `process.stdout` property returns a [Writable][] stream connected to <del>`stdout` (fd `2`). <add>`stdout` (fd `1`). <ide> <ide> For example, to copy process.stdin to process.stdout: <ide>
1
PHP
PHP
fix return typehints in tests
30dab5436d3ca943199ece761d6b723f9785ec51
<ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testAuthenticateSingleHash(string $username, ?string $password): <ide> $this->assertSame(1, $passwordHasher->callCount); <ide> } <ide> <del> public function userList() <add> public function userList(): array <ide> { <ide> return [ <ide> ['notexist', ''], <ide><path>tests/TestCase/Cache/CacheTest.php <ide> public function testDecrementSubZero() <ide> * <ide> * @return array <ide> */ <del> public static function configProvider() <add> public static function configProvider(): array <ide> { <ide> return [ <ide> 'Array of data using engine key.' => [[ <ide><path>tests/TestCase/Collection/CollectionTest.php <ide> public function testArrayIsWrapped() <ide> * <ide> * @return array <ide> */ <del> public function avgProvider() <add> public function avgProvider(): array <ide> { <ide> $items = [1, 2, 3]; <ide> <ide> public function testAvgWithEmptyCollection() <ide> * <ide> * @return array <ide> */ <del> public function avgWithMatcherProvider() <add> public function avgWithMatcherProvider(): array <ide> { <ide> $items = [['foo' => 1], ['foo' => 2], ['foo' => 3]]; <ide> <ide> public function testAvgWithMatcher(iterable $items) <ide> * <ide> * @return array <ide> */ <del> public function medianProvider() <add> public function medianProvider(): array <ide> { <ide> $items = [5, 2, 4]; <ide> <ide> public function testMedianEven(iterable $items) <ide> * <ide> * @return array <ide> */ <del> public function medianWithMatcherProvider() <add> public function medianWithMatcherProvider(): array <ide> { <ide> $items = [ <ide> ['invoice' => ['total' => 400]], <ide> public function testEach() <ide> $this->assertSame([['a' => 1], ['b' => 2], ['c' => 3]], $results); <ide> } <ide> <del> public function filterProvider() <add> public function filterProvider(): array <ide> { <ide> $items = [1, 2, 0, 3, false, 4, null, 5, '']; <ide> <ide> public function testContains() <ide> * <ide> * @return array <ide> */ <del> public function simpleProvider() <add> public function simpleProvider(): array <ide> { <ide> $items = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; <ide> <ide> public function testReduceWithoutInitialValue(iterable $items) <ide> * <ide> * @return array <ide> */ <del> public function extractProvider() <add> public function extractProvider(): array <ide> { <ide> $items = [['a' => ['b' => ['c' => 1]]], 2]; <ide> <ide> public function testExtract(iterable $items) <ide> * <ide> * @return array <ide> */ <del> public function sortProvider() <add> public function sortProvider(): array <ide> { <ide> $items = [ <ide> ['a' => ['b' => ['c' => 4]]], <ide> public function testMinWithEntities() <ide> * <ide> * @return array <ide> */ <del> public function groupByProvider() <add> public function groupByProvider(): array <ide> { <ide> $items = [ <ide> ['id' => 1, 'name' => 'foo', 'parent_id' => 10], <ide> public function testGroupByInvalidPath() <ide> * <ide> * @return array <ide> */ <del> public function indexByProvider() <add> public function indexByProvider(): array <ide> { <ide> $items = [ <ide> ['id' => 1, 'name' => 'foo', 'parent_id' => 10], <ide> public function testInsert() <ide> * <ide> * @return array <ide> */ <del> public function nestedListProvider() <add> public function nestedListProvider(): array <ide> { <ide> return [ <ide> ['desc', [1, 2, 3, 5, 7, 4, 8, 6, 9, 10]], <ide> public function testListNestedWithCallable() <ide> * <ide> * @return array <ide> */ <del> public function sumOfProvider() <add> public function sumOfProvider(): array <ide> { <ide> $items = [ <ide> ['invoice' => ['total' => 100]], <ide> public function testSerializeWithZipIterator() <ide> * <ide> * @return array <ide> */ <del> public function chunkProvider() <add> public function chunkProvider(): array <ide> { <ide> $items = range(1, 10); <ide> <ide><path>tests/TestCase/Command/PluginUnloadCommandTest.php <ide> public function testUnloadFirstPlugin() <ide> * <ide> * @return array <ide> */ <del> public function variantProvider() <add> public function variantProvider(): array <ide> { <ide> return [ <ide> // $this->addPlugin('TestPlugin', [ <ide><path>tests/TestCase/Command/SchemaCacheCommandsTest.php <ide> <ide> use Cake\Cache\Cache; <ide> use Cake\Cache\Engine\NullEngine; <del>use Cake\Console\ConsoleIo; <del>use Cake\Database\SchemaCache; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\ConsoleIntegrationTestTrait; <ide> use Cake\TestSuite\TestCase; <ide> public function tearDown(): void <ide> Cache::drop('orm_cache'); <ide> } <ide> <del> protected function getShell() <del> { <del> $io = $this->getMockBuilder(ConsoleIo::class)->getMock(); <del> $shell = $this->getMockBuilder(SchemaCacheShell::class) <del> ->setConstructorArgs([$io]) <del> ->onlyMethods(['_getSchemaCache']) <del> ->getMock(); <del> <del> $schemaCache = new SchemaCache($this->connection); <del> $shell->expects($this->once()) <del> ->method('_getSchemaCache') <del> ->willReturn($schemaCache); <del> <del> return $shell; <del> } <del> <ide> /** <ide> * Test that clear enables the cache if it was disabled. <ide> * <ide><path>tests/TestCase/Console/CommandCollectionTest.php <ide> public function testAddInvalidInstance() <ide> * <ide> * @return array <ide> */ <del> public function invalidNameProvider() <add> public function invalidNameProvider(): array <ide> { <ide> return [ <ide> // Empty <ide><path>tests/TestCase/Console/CommandRunnerTest.php <ide> public function testRunLoadsRoutes() <ide> $this->assertGreaterThan(2, count(Router::getRouteCollection()->routes())); <ide> } <ide> <del> protected function makeAppWithCommands(array $commands) <add> protected function makeAppWithCommands(array $commands): BaseApplication <ide> { <ide> $app = $this->getMockBuilder(BaseApplication::class) <ide> ->onlyMethods(['middleware', 'bootstrap', 'console', 'routes']) <ide> protected function makeAppWithCommands(array $commands) <ide> return $app; <ide> } <ide> <del> protected function getMockIo(ConsoleOutput $output) <add> protected function getMockIo(ConsoleOutput $output): ConsoleIo <ide> { <ide> $io = $this->getMockBuilder(ConsoleIo::class) <ide> ->setConstructorArgs([$output, $output, null, null]) <ide><path>tests/TestCase/Console/ConsoleIoTest.php <ide> public function tearDown(): void <ide> * <ide> * @return array <ide> */ <del> public function choiceProvider() <add> public function choiceProvider(): array <ide> { <ide> return [ <ide> [['y', 'n']], <ide> public function testHelper() <ide> * <ide> * @return array <ide> */ <del> public function outHelperProvider() <add> public function outHelperProvider(): array <ide> { <ide> return [['info'], ['success'], ['comment']]; <ide> } <ide> public function outHelperProvider() <ide> * <ide> * @return array <ide> */ <del> public function errHelperProvider() <add> public function errHelperProvider(): array <ide> { <ide> return [['warning'], ['error']]; <ide> } <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testParamReading(string $toRead, $expected) <ide> * <ide> * @return array <ide> */ <del> public function paramReadingDataProvider() <add> public function paramReadingDataProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testAutoAjaxLayout(): void <ide> /** <ide> * @return array <ide> */ <del> public function defaultExtensionsProvider() <add> public function defaultExtensionsProvider(): array <ide> { <ide> return [['html'], ['htm']]; <ide> } <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function tearDown(): void <ide> unset($this->Controller); <ide> } <ide> <del> public function validatePost(string $expectedException = 'SecurityException', ?string $expectedExceptionMessage = null) <del> { <add> public function validatePost( <add> string $expectedException = 'SecurityException', <add> ?string $expectedExceptionMessage = null <add> ): ?bool { <ide> try { <ide> return $this->Controller->Security->validatePost($this->Controller); <ide> } catch (SecurityException $ex) { <ide><path>tests/TestCase/Core/AppTest.php <ide> public function testShortNameWithAppNamespaceUnset() <ide> * <ide> * @return array <ide> */ <del> public function classNameProvider() <add> public function classNameProvider(): array <ide> { <ide> return [ <ide> ['Does', 'Not', 'Exist'], <ide> public function classNameProvider() <ide> * <ide> * @return array <ide> */ <del> public function shortNameProvider() <add> public function shortNameProvider(): array <ide> { <ide> return [ <ide> ['TestApp\In\ExistsApp', 'In', 'App', 'Exists'], <ide><path>tests/TestCase/Core/FunctionsTest.php <ide> public function testH($value, $expected) <ide> $this->assertSame($expected, $result); <ide> } <ide> <del> public function hInputProvider() <add> public function hInputProvider(): array <ide> { <ide> return [ <ide> ['i am clean', 'i am clean'], <ide><path>tests/TestCase/Database/Driver/MysqlTest.php <ide> public function testVersion($dbVersion, $expectedVersion) <ide> $this->assertSame($expectedVersion, $result); <ide> } <ide> <del> public function versionStringProvider() <add> public function versionStringProvider(): array <ide> { <ide> return [ <ide> ['10.2.23-MariaDB', '10.2.23-MariaDB'], <ide><path>tests/TestCase/Database/Driver/SqliteTest.php <ide> public function testConnectionConfigCustom() <ide> * <ide> * @return array <ide> */ <del> public static function schemaValueProvider() <add> public static function schemaValueProvider(): array <ide> { <ide> return [ <ide> [null, 'NULL'], <ide><path>tests/TestCase/Database/Driver/SqlserverTest.php <ide> public function setUp(): void <ide> * <ide> * @return array <ide> */ <del> public function dnsStringDataProvider() <add> public function dnsStringDataProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Database/DriverTest.php <ide> public function testDestructor() <ide> * <ide> * @return array <ide> */ <del> public function schemaValueProvider() <add> public function schemaValueProvider(): array <ide> { <ide> return [ <ide> [null, 'NULL'], <ide><path>tests/TestCase/Database/Expression/QueryExpressionTest.php <ide> public function testHasNestedExpression() <ide> * <ide> * @return void <ide> */ <del> public function methodsProvider() <add> public function methodsProvider(): array <ide> { <ide> return [ <ide> ['eq'], ['notEq'], ['gt'], ['lt'], ['gte'], ['lte'], ['like'], <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> protected function _needsConnection() <ide> * <ide> * @return array <ide> */ <del> public static function convertColumnProvider() <add> public static function convertColumnProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testDescribeNonPrimaryAutoIncrement() <ide> * <ide> * @return array <ide> */ <del> public static function columnSqlProvider() <add> public static function columnSqlProvider(): array <ide> { <ide> return [ <ide> // strings <ide> public function testColumnSql(string $name, array $data, string $expected) <ide> * <ide> * @return array <ide> */ <del> public static function constraintSqlProvider() <add> public static function constraintSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testConstraintSql(string $name, array $data, string $expected) <ide> * <ide> * @return array <ide> */ <del> public static function indexSqlProvider() <add> public static function indexSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> protected function _createTables($connection) <ide> * <ide> * @return array <ide> */ <del> public static function convertColumnProvider() <add> public static function convertColumnProvider(): array <ide> { <ide> return [ <ide> // Timestamp <ide> public function testDescribeTableFunctionDefaultValue() <ide> * <ide> * @return array <ide> */ <del> public static function columnSqlProvider() <add> public static function columnSqlProvider(): array <ide> { <ide> return [ <ide> // strings <ide> public function testColumnSqlPrimaryKey() <ide> * <ide> * @return array <ide> */ <del> public static function constraintSqlProvider() <add> public static function constraintSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> protected function _needsConnection() <ide> * <ide> * @return array <ide> */ <del> public static function convertColumnProvider() <add> public static function convertColumnProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testDescribeTableIndexes() <ide> * <ide> * @return array <ide> */ <del> public static function columnSqlProvider() <add> public static function columnSqlProvider(): array <ide> { <ide> return [ <ide> // strings <ide> public function testColumnSqlPrimaryKeyBigInt() <ide> * <ide> * @return array <ide> */ <del> public static function constraintSqlProvider() <add> public static function constraintSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testConstraintSql(string $name, array $data, string $expected) <ide> * <ide> * @return array <ide> */ <del> public static function indexSqlProvider() <add> public static function indexSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php <ide> protected function _createTables(ConnectionInterface $connection) <ide> * <ide> * @return array <ide> */ <del> public static function convertColumnProvider() <add> public static function convertColumnProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testDescribeTableIndexes() <ide> * <ide> * @return array <ide> */ <del> public static function columnSqlProvider() <add> public static function columnSqlProvider(): array <ide> { <ide> return [ <ide> // strings <ide> public function testColumnSql(string $name, array $data, string $expected) <ide> * <ide> * @return array <ide> */ <del> public static function constraintSqlProvider() <add> public static function constraintSqlProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php <ide> public function testAddConstraintOverwriteUniqueIndex() <ide> * <ide> * @return array <ide> */ <del> public static function addConstraintErrorProvider() <add> public static function addConstraintErrorProvider(): array <ide> { <ide> return [ <ide> // No properties <ide> public function testAddIndex() <ide> * <ide> * @return array <ide> */ <del> public static function addIndexErrorProvider() <add> public static function addIndexErrorProvider(): array <ide> { <ide> return [ <ide> // Empty <ide> public function testConstraintForeignKeyTwoColumns() <ide> * <ide> * @return array <ide> */ <del> public static function badForeignKeyProvider() <add> public static function badForeignKeyProvider(): array <ide> { <ide> return [ <ide> 'references is bad' => [[ <ide><path>tests/TestCase/Database/Type/DateTimeFractionalTypeTest.php <ide> public function testToDatabaseNoMicroseconds() <ide> * <ide> * @return array <ide> */ <del> public function marshalProvider() <add> public function marshalProvider(): array <ide> { <ide> return [ <ide> // invalid types. <ide><path>tests/TestCase/Database/Type/DateTimeTimezoneTypeTest.php <ide> public function testToDatabaseNoMicroseconds() <ide> * <ide> * @return array <ide> */ <del> public function marshalProvider() <add> public function marshalProvider(): array <ide> { <ide> return [ <ide> // invalid types. <ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php <ide> public function testToDatabase() <ide> * <ide> * @return array <ide> */ <del> public function marshalProvider() <add> public function marshalProvider(): array <ide> { <ide> return [ <ide> // invalid types. <ide><path>tests/TestCase/Database/Type/DateTypeTest.php <ide> public function testToDatabase() <ide> * <ide> * @return array <ide> */ <del> public function marshalProvider() <add> public function marshalProvider(): array <ide> { <ide> $date = new Date('@1392387900'); <ide> <ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php <ide> public function testToDatabase() <ide> * <ide> * @return void <ide> */ <del> public function invalidIntegerProvider() <add> public function invalidIntegerProvider(): array <ide> { <ide> return [ <ide> 'array' => [['3', '4']], <ide><path>tests/TestCase/Database/Type/TimeTypeTest.php <ide> public function testToDatabase() <ide> * <ide> * @return array <ide> */ <del> public function marshalProvider() <add> public function marshalProvider(): array <ide> { <ide> $date = new Time('@1392387900'); <ide> <ide><path>tests/TestCase/Database/TypeFactoryTest.php <ide> public function testBuildBasicTypes(string $name) <ide> * <ide> * @return array <ide> */ <del> public function basicTypesProvider() <add> public function basicTypesProvider(): array <ide> { <ide> return [ <ide> ['string'], <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> public function tearDown(): void <ide> * <ide> * @return array <ide> */ <del> public static function configProvider() <add> public static function configProvider(): array <ide> { <ide> return [ <ide> 'Array of data using classname key.' => [[ <ide> public function testAliasError() <ide> * <ide> * @return array <ide> */ <del> public function dsnProvider() <add> public function dsnProvider(): array <ide> { <ide> return [ <ide> 'no user' => [ <ide><path>tests/TestCase/Datasource/PaginatorTestTrait.php <ide> public function testValidateSortInvalidAlias() <ide> /** <ide> * @return array <ide> */ <del> public function checkLimitProvider() <add> public function checkLimitProvider(): array <ide> { <ide> return [ <ide> 'out of bounds' => [ <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function testHandleErrorTraceOffset() <ide> * <ide> * @return array <ide> */ <del> public static function errorProvider() <add> public static function errorProvider(): array <ide> { <ide> return [ <ide> [E_USER_NOTICE, 'Notice'], <ide> public function testHandleFatalErrorLog() <ide> * <ide> * @return array <ide> */ <del> public function memoryLimitProvider() <add> public function memoryLimitProvider(): array <ide> { <ide> return [ <ide> // start, adjust, expected <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testMissingControllerLowerCase() <ide> * <ide> * @return array <ide> */ <del> public static function exceptionProvider() <add> public static function exceptionProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/ExceptionsTest.php <ide> public function testMissingTemplateExceptions() <ide> * <ide> * @return array <ide> */ <del> public function exceptionProvider() <add> public function exceptionProvider(): array <ide> { <ide> return [ <ide> ['Cake\Console\Exception\ConsoleException', 1], <ide><path>tests/TestCase/Filesystem/FileTest.php <ide> public function testBasename(string $path, ?string $suffix, bool $isRoot) <ide> * <ide> * @return array <ide> */ <del> public function baseNameValueProvider() <add> public function baseNameValueProvider(): array <ide> { <ide> return [ <ide> ['folder/نام.txt', null, false], <ide><path>tests/TestCase/Filesystem/FolderTest.php <ide> public function testInPath() <ide> * <ide> * @return array <ide> */ <del> public function inPathInvalidPathArgumentDataProvider() <add> public function inPathInvalidPathArgumentDataProvider(): array <ide> { <ide> return [ <ide> [''], <ide><path>tests/TestCase/Http/Client/RequestTest.php <ide> public function testMethods(array $headers, $data, $method) <ide> /** <ide> * @dataProvider additionProvider <ide> */ <del> public function additionProvider() <add> public function additionProvider(): array <ide> { <ide> $headers = [ <ide> 'Content-Type' => 'application/json', <ide><path>tests/TestCase/Http/Client/ResponseTest.php <ide> public function testIsOk() <ide> * <ide> * @return array <ide> */ <del> public static function isSuccessProvider() <add> public static function isSuccessProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testAdapterInstanceCheck() <ide> * <ide> * @return array <ide> */ <del> public static function urlProvider() <add> public static function urlProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testGetWithAuthenticationAndProxy() <ide> * <ide> * @return array <ide> */ <del> public static function methodProvider() <add> public static function methodProvider(): array <ide> { <ide> return [ <ide> [Request::METHOD_GET], <ide> public function testMethodsSimple(string $method) <ide> * <ide> * @return array <ide> */ <del> public static function typeProvider() <add> public static function typeProvider(): array <ide> { <ide> return [ <ide> ['application/json', 'application/json'], <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> class CookieTest extends TestCase <ide> * <ide> * @return array <ide> */ <del> public function invalidNameProvider() <add> public function invalidNameProvider(): array <ide> { <ide> return [ <ide> ['no='], <ide><path>tests/TestCase/Http/Middleware/BodyParserMiddlewareTest.php <ide> class BodyParserMiddlewareTest extends TestCase <ide> * <ide> * @return array <ide> */ <del> public static function safeHttpMethodProvider() <add> public static function safeHttpMethodProvider(): array <ide> { <ide> return [ <ide> ['GET'], <ide> public static function safeHttpMethodProvider() <ide> * <ide> * @return array <ide> */ <del> public static function httpMethodProvider() <add> public static function httpMethodProvider(): array <ide> { <ide> return [ <ide> ['PATCH'], ['PUT'], ['POST'], ['DELETE'], <ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php <ide> protected function createOldToken(): string <ide> * <ide> * @return array <ide> */ <del> public static function safeHttpMethodProvider() <add> public static function safeHttpMethodProvider(): array <ide> { <ide> return [ <ide> ['GET'], <ide> public static function safeHttpMethodProvider() <ide> * <ide> * @return array <ide> */ <del> public static function httpMethodProvider() <add> public static function httpMethodProvider(): array <ide> { <ide> return [ <ide> ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD'], <ide><path>tests/TestCase/Http/Middleware/SessionCsrfProtectionMiddlewareTest.php <ide> class SessionCsrfProtectionMiddlewareTest extends TestCase <ide> * <ide> * @return array <ide> */ <del> public static function safeHttpMethodProvider() <add> public static function safeHttpMethodProvider(): array <ide> { <ide> return [ <ide> ['GET'], <ide> public static function safeHttpMethodProvider() <ide> * <ide> * @return array <ide> */ <del> public static function httpMethodProvider() <add> public static function httpMethodProvider(): array <ide> { <ide> return [ <ide> ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD'], <ide><path>tests/TestCase/Http/ResponseTest.php <ide> public function testWithTypeInvalidType() <ide> * <ide> * @return array <ide> */ <del> public static function charsetTypeProvider() <add> public static function charsetTypeProvider(): array <ide> { <ide> return [ <ide> ['mp3', 'audio/mpeg'], <ide> public function testWithFileNotFoundNoDebug() <ide> * <ide> * @return array <ide> */ <del> public function invalidFileProvider() <add> public function invalidFileProvider(): array <ide> { <ide> return [ <ide> ['my/../cat.gif', 'The requested file contains `..` and will not be read.'], <ide> public function testWithFileUpperExtension() <ide> * <ide> * @return array <ide> */ <del> public static function rangeProvider() <add> public static function rangeProvider(): array <ide> { <ide> return [ <ide> // suffix-byte-range <ide> public function testWithFileRange() <ide> * <ide> * @return array <ide> */ <del> public function invalidFileRangeProvider() <add> public function invalidFileRangeProvider(): array <ide> { <ide> return [ <ide> // malformed range <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testGetParamDefault() <ide> * <ide> * @return array <ide> */ <del> public function paramReadingDataProvider() <add> public function paramReadingDataProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testGetEnv() <ide> * <ide> * @return array <ide> */ <del> public function emulatedPropertyProvider() <add> public function emulatedPropertyProvider(): array <ide> { <ide> return [ <ide> ['here'], <ide><path>tests/TestCase/Http/server_mocks.php <ide> */ <ide> namespace Cake\Http; <ide> <del>function headers_sent(?string &$file = null, ?int &$line = null) <add>function headers_sent(?string &$file = null, ?int &$line = null): bool <ide> { <ide> return $GLOBALS['mockedHeadersSent'] ?? true; <ide> } <ide> <del>function header(string $header, bool $replace = true, int $response_code = 0) <add>function header(string $header, bool $replace = true, int $response_code = 0): void <ide> { <ide> $GLOBALS['mockedHeaders'][] = $header; <ide> } <ide><path>tests/TestCase/I18n/DateTest.php <ide> public function tearDown(): void <ide> * <ide> * @return array <ide> */ <del> public static function classNameProvider() <add> public static function classNameProvider(): array <ide> { <ide> return ['mutable' => ['Cake\I18n\Date'], 'immutable' => ['Cake\I18n\FrozenDate']]; <ide> } <ide> public function testLenientParseDate(string $class) <ide> * <ide> * @return array <ide> */ <del> public static function timeAgoProvider() <add> public static function timeAgoProvider(): array <ide> { <ide> return [ <ide> ['-1 day', '1 day ago'], <ide> public function testTimeAgoInWordsTimezone(string $class) <ide> * <ide> * @return array <ide> */ <del> public function timeAgoEndProvider() <add> public function timeAgoEndProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/I18n/PluralRulesTest.php <ide> class PluralRulesTest extends TestCase <ide> * <ide> * @return array <ide> */ <del> public function localesProvider() <add> public function localesProvider(): array <ide> { <ide> return [ <ide> ['jp', 0, 0], <ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function tearDown(): void <ide> * <ide> * @return array <ide> */ <del> public static function classNameProvider() <add> public static function classNameProvider(): array <ide> { <ide> return ['mutable' => ['Cake\I18n\Time'], 'immutable' => ['Cake\I18n\FrozenTime']]; <ide> } <ide> public function testConstructFromAnotherInstance(string $class) <ide> * <ide> * @return array <ide> */ <del> public static function timeAgoProvider() <add> public static function timeAgoProvider(): array <ide> { <ide> return [ <ide> ['-12 seconds', '12 seconds ago'], <ide> public function testTimeAgoInWordsFrozenTime(string $input, string $expected) <ide> * <ide> * @return array <ide> */ <del> public function timeAgoEndProvider() <add> public function timeAgoEndProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testToString(string $class) <ide> * <ide> * @return array <ide> */ <del> public function invalidDataProvider() <add> public function invalidDataProvider(): array <ide> { <ide> return [ <ide> [null], <ide><path>tests/TestCase/Log/Engine/SyslogLogTest.php <ide> public function testDeprecatedFormatMessage() <ide> * <ide> * @return array <ide> */ <del> public function typesProvider() <add> public function typesProvider(): array <ide> { <ide> return [ <ide> ['emergency', LOG_EMERG], <ide><path>tests/TestCase/Log/LogTest.php <ide> public function testInvalidLevel() <ide> * <ide> * @return array <ide> */ <del> public static function configProvider() <add> public static function configProvider(): array <ide> { <ide> return [ <ide> 'Array of data using engine key.' => [[ <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testBodyEncodingIso2022JpMs() <ide> /** <ide> * @param array|string $message <ide> */ <del> protected function _checkContentTransferEncoding($message, string $charset) <add> protected function _checkContentTransferEncoding($message, string $charset): bool <ide> { <ide> $boundary = '--' . $this->Email->getBoundary(); <ide> $result['text'] = false; <ide><path>tests/TestCase/Mailer/MailerTest.php <ide> protected function assertLineLengths(string $message) <ide> /** <ide> * @param array|string $message <ide> */ <del> protected function _checkContentTransferEncoding($message, string $charset) <add> protected function _checkContentTransferEncoding($message, string $charset): bool <ide> { <ide> $boundary = '--' . $this->mailer->getBoundary(); <ide> $result['text'] = false; <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function testReplaceLinkBinaryUuid() <ide> * <ide> * @return array <ide> */ <del> public function emptyProvider() <add> public function emptyProvider(): array <ide> { <ide> return [ <ide> [''], <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testSaveAssociatedNotEmptyNotIterable() <ide> * <ide> * @return array <ide> */ <del> public function emptySetDataProvider() <add> public function emptySetDataProvider(): array <ide> { <ide> return [ <ide> [''], <ide><path>tests/TestCase/ORM/AssociationCollectionTest.php <ide> public function testKeys() <ide> /** <ide> * Data provider for AssociationCollection::getByType <ide> */ <del> public function associationCollectionType() <add> public function associationCollectionType(): array <ide> { <ide> return [ <ide> ['BelongsTo', 'BelongsToMany'], <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testGetAndSetSource() <ide> * <ide> * @return array <ide> */ <del> public function emptyNamesProvider() <add> public function emptyNamesProvider(): array <ide> { <ide> return [[''], [null]]; <ide> } <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testMergeAccessibleFields() <ide> * <ide> * @return array <ide> */ <del> public function emptyProvider() <add> public function emptyProvider(): array <ide> { <ide> return [ <ide> [0], <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testReciprocalBelongsToManyNoOverwrite() <ide> * <ide> * @return array <ide> */ <del> public function strategyProvider() <add> public function strategyProvider(): array <ide> { <ide> return [ <ide> ['append'], <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testDelete() <ide> * <ide> * @return array <ide> */ <del> public function collectionMethodsProvider() <add> public function collectionMethodsProvider(): array <ide> { <ide> $identity = function ($a) { <ide> return $a; <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSimplifiedFind() <ide> $table->find(); <ide> } <ide> <del> public function providerForTestGet() <add> public function providerForTestGet(): array <ide> { <ide> return [ <ide> [['fields' => ['id']]], <ide> public function testGet($options) <ide> $this->assertSame($entity, $result); <ide> } <ide> <del> public function providerForTestGetWithCustomFinder() <add> public function providerForTestGetWithCustomFinder(): array <ide> { <ide> return [ <ide> [['fields' => ['id'], 'finder' => 'custom']], <ide> public function testGetWithCustomFinder($options) <ide> $this->assertSame($entity, $result); <ide> } <ide> <del> public function providerForTestGetWithCache() <add> public function providerForTestGetWithCache(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/ORM/TableUuidTest.php <ide> public function setUp(): void <ide> * <ide> * @return array <ide> */ <del> public function uuidTableProvider() <add> public function uuidTableProvider(): array <ide> { <ide> return [['uuid_items'], ['binary_uuid_items']]; <ide> } <ide><path>tests/TestCase/Routing/Middleware/AssetMiddlewareTest.php <ide> public function testMissingPluginAsset() <ide> * <ide> * @return array <ide> */ <del> public function assetProvider() <add> public function assetProvider(): array <ide> { <ide> return [ <ide> // In plugin root. <ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> public function testInvokeScopedMiddlewareIsolatedScopes(string $url, array $exp <ide> * <ide> * @return array <ide> */ <del> public function scopedMiddlewareUrlProvider() <add> public function scopedMiddlewareUrlProvider(): array <ide> { <ide> return [ <ide> ['/api/ping', ['first', 'last']], <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function testApplyMiddlewareAttachToRoutes() <ide> /** <ide> * @return array <ide> */ <del> public static function httpMethodProvider() <add> public static function httpMethodProvider(): array <ide> { <ide> return [ <ide> ['GET'], <ide><path>tests/TestCase/Routing/RouteCollectionTest.php <ide> public function testParseRequestCheckHostCondition() <ide> * <ide> * @return array <ide> */ <del> public static function hostProvider() <add> public static function hostProvider(): array <ide> { <ide> return [ <ide> ['wrong.example'], <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testParseRoutePath() <ide> /** <ide> * @return array <ide> */ <del> public function invalidRoutePathProvider() <add> public function invalidRoutePathProvider(): array <ide> { <ide> return [ <ide> ['view'], <ide> public function testUrlGenerationWithRoutePathWithContext() <ide> /** <ide> * @return array <ide> */ <del> public function invalidRoutePathParametersArrayProvider() <add> public function invalidRoutePathParametersArrayProvider(): array <ide> { <ide> return [ <ide> [['plugin' => false]], <ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php <ide> public function testAssertionFailureMessages($assertion, $message, $command, ... <ide> * <ide> * @return array <ide> */ <del> public function assertionFailureMessagesProvider() <add> public function assertionFailureMessagesProvider(): array <ide> { <ide> return [ <ide> 'assertExitCode' => ['assertExitCode', 'Failed asserting that 1 matches exit code 0', 'routes', Command::CODE_ERROR], <ide><path>tests/TestCase/TestSuite/EmailTraitTest.php <ide> public function testFailureMessages($assertion, $expectedMessage, $params) <ide> * <ide> * @return array <ide> */ <del> public function failureMessageDataProvider() <add> public function failureMessageDataProvider(): array <ide> { <ide> return [ <ide> 'assertMailCount' => ['assertMailCount', 'Failed asserting that 2 emails were sent.', [2]], <ide><path>tests/TestCase/TestSuite/Fixture/SchemaCleanerTest.php <ide> private function assertTestTableExistsWithCount(string $table, int $count) <ide> ); <ide> } <ide> <del> private function createSchemas() <add> private function createSchemas(): array <ide> { <ide> $table1 = 'test_table_' . rand(); <ide> $table2 = 'test_table_' . rand(); <ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function testExceptionOnLoadFixture(string $method, string $expectedMessa <ide> * <ide> * @return array <ide> */ <del> public function loadErrorMessageProvider() <add> public function loadErrorMessageProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> public function testAssertionFailureMessages($assertion, $message, $url, ...$res <ide> * <ide> * @return array <ide> */ <del> public function assertionFailureMessagesProvider() <add> public function assertionFailureMessagesProvider(): array <ide> { <ide> $templateDir = TEST_APP . 'templates' . DS; <ide> <ide> public function assertionFailureMessagesProvider() <ide> * <ide> * @return array <ide> */ <del> public function methodsProvider() <add> public function methodsProvider(): array <ide> { <ide> return [ <ide> 'GET' => ['get'], <ide> public function testAssertSessionRelatedVerboseMessages(string $assertMethod, .. <ide> * <ide> * @return array <ide> */ <del> public function assertionFailureSessionVerboseProvider() <add> public function assertionFailureSessionVerboseProvider(): array <ide> { <ide> return [ <ide> 'assertFlashMessageVerbose' => ['assertFlashMessage', 'notfound'], <ide><path>tests/TestCase/Utility/InflectorTest.php <ide> public function testInflectingSingulars(string $singular, string $plural) <ide> * <ide> * @return array <ide> */ <del> public function singularizeProvider() <add> public function singularizeProvider(): array <ide> { <ide> return [ <ide> ['categoria', 'categorias'], <ide> public function testInflectingPlurals(string $plural, string $singular) <ide> * <ide> * @return array <ide> */ <del> public function pluralizeProvider() <add> public function pluralizeProvider(): array <ide> { <ide> return [ <ide> ['axmen', 'axman'], <ide><path>tests/TestCase/Utility/TextTest.php <ide> public function testWordWrap(string $text, int $width, string $break = "\n", boo <ide> * <ide> * @return array <ide> */ <del> public function wordWrapProvider() <add> public function wordWrapProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testGetSetTransliteratorId() <ide> * <ide> * @return array <ide> */ <del> public function transliterateInputProvider() <add> public function transliterateInputProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/Utility/XmlTest.php <ide> public function testBuildOrmEntity() <ide> * <ide> * @return array <ide> */ <del> public static function invalidDataProvider() <add> public static function invalidDataProvider(): array <ide> { <ide> return [ <ide> [null], <ide> public function testFromArrayPretty() <ide> * <ide> * @return array <ide> */ <del> public static function invalidArrayDataProvider() <add> public static function invalidArrayDataProvider(): array <ide> { <ide> return [ <ide> [''], <ide> public function testCdata() <ide> * <ide> * @return array <ide> */ <del> public static function invalidToArrayDataProvider() <add> public static function invalidToArrayDataProvider(): array <ide> { <ide> return [ <ide> [new \DateTime()], <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testUploadedFileWithDifferentFileParametersOrder() <ide> * <ide> * @return array <ide> */ <del> public function uploadedFileProvider() <add> public function uploadedFileProvider(): array <ide> { <ide> return [ <ide> 'minSize fail' => [false, ['minSize' => 500]], <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function testCollectionOperationsNoTableArg($collection) <ide> * <ide> * @return array <ide> */ <del> public static function collectionProvider() <add> public static function collectionProvider(): array <ide> { <ide> $one = new Article([ <ide> 'title' => 'First post', <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testCreateContextSelectionBuiltIn($data, string $class) <ide> * <ide> * @return array <ide> */ <del> public static function requestTypeProvider() <add> public static function requestTypeProvider(): array <ide> { <ide> return [ <ide> // type, method, override <ide> public function testDateTimeWithGetForms() <ide> * <ide> * @return array <ide> */ <del> public function fractionalTypeProvider() <add> public function fractionalTypeProvider(): array <ide> { <ide> return [ <ide> ['datetimefractional'], <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function testMeta() <ide> /** <ide> * @return array <ide> */ <del> public function dataMetaLinksProvider() <add> public function dataMetaLinksProvider(): array <ide> { <ide> return [ <ide> ['canonical', ['controller' => 'Posts', 'action' => 'show'], '/posts/show'], <ide><path>tests/TestCase/View/Helper/NumberHelperTest.php <ide> public function tearDown(): void <ide> * <ide> * @return array <ide> */ <del> public function methodProvider() <add> public function methodProvider(): array <ide> { <ide> return [ <ide> ['precision'], <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testUrlGenerationResetsToPage1($field, $options, $expected) <ide> * <ide> * @return array <ide> */ <del> public function urlGenerationResetsToPage1Provider() <add> public function urlGenerationResetsToPage1Provider(): array <ide> { <ide> return [ <ide> 'Sorting the field currently sorted asc, asc' => [ <ide> public function testWithZeroPages() <ide> * <ide> * @return array <ide> */ <del> public function dataMetaProvider() <add> public function dataMetaProvider(): array <ide> { <ide> return [ <ide> // Verifies that no next and prev links are created for single page results. <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> public function testAutoLinkEscape() <ide> * <ide> * @return array <ide> */ <del> public static function autoLinkProvider() <add> public static function autoLinkProvider(): array <ide> { <ide> return [ <ide> [ <ide> public function testAutoLinkUrlsQueryString() <ide> * <ide> * @return array <ide> */ <del> public function autoLinkEmailProvider() <add> public function autoLinkEmailProvider(): array <ide> { <ide> return [ <ide> [ <ide><path>tests/TestCase/View/JsonViewTest.php <ide> public function setUp(): void <ide> * <ide> * @return array <ide> */ <del> public static function renderWithoutViewProvider() <add> public static function renderWithoutViewProvider(): array <ide> { <ide> return [ <ide> // Test render with a valid string in _serialize. <ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> public function testHasVar() <ide> * <ide> * @return array <ide> */ <del> public function stringPropertyProvider() <add> public function stringPropertyProvider(): array <ide> { <ide> return [ <ide> ['layoutPath', 'Admin/'], <ide> public function stringPropertyProvider() <ide> * <ide> * @return array <ide> */ <del> public function boolPropertyProvider() <add> public function boolPropertyProvider(): array <ide> { <ide> return [ <ide> ['autoLayout', true, false], <ide> public function boolPropertyProvider() <ide> * <ide> * @return array <ide> */ <del> public function arrayPropertyProvider() <add> public function arrayPropertyProvider(): array <ide> { <ide> return [ <ide> ['helpers', ['Html', 'Form']], <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testBlockSetDecimal() <ide> * <ide> * @return array <ide> */ <del> public static function blockValueProvider() <add> public static function blockValueProvider(): array <ide> { <ide> return [ <ide> 'string' => ['A string value'], <ide><path>tests/TestCase/View/Widget/CheckboxWidgetTest.php <ide> public function testRenderChecked() <ide> * <ide> * @return array <ide> */ <del> public static function checkedProvider() <add> public static function checkedProvider(): array <ide> { <ide> return [ <ide> ['checked'], <ide> public function testRenderCheckedValue($checked) <ide> * <ide> * @return array <ide> */ <del> public static function uncheckedProvider() <add> public static function uncheckedProvider(): array <ide> { <ide> return [ <ide> [''], <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> public function setUp(): void <ide> * <ide> * @return array <ide> */ <del> public static function invalidSelectedValuesProvider() <add> public static function invalidSelectedValuesProvider(): array <ide> { <ide> return [ <ide> 'false' => [false], <ide> public function testRenderInvalid($selected) <ide> * <ide> * @return array <ide> */ <del> public static function selectedValuesProvider() <add> public static function selectedValuesProvider(): array <ide> { <ide> $date = new \DateTime('2014-01-20 12:30:45'); <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Controller/TestsController.php <ide> public function index() <ide> $this->set('test_value', 'It is a variable'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function some_method() <ide> { <ide> $this->response->body(25); <ide><path>tests/test_app/Plugin/TestPlugin/src/Plugin.php <ide> <ide> class Plugin extends BasePlugin <ide> { <del> public function events(EventManagerInterface $events) <add> public function events(EventManagerInterface $events): EventManagerInterface <ide> { <ide> $events->on('TestPlugin.load', function () { <ide> }); <ide><path>tests/test_app/TestApp/Collection/CountableIterator.php <ide> public function __construct($items) <ide> parent::__construct($f()); <ide> } <ide> <del> public function count() <add> public function count(): int <ide> { <ide> return 6; <ide> } <ide><path>tests/test_app/TestApp/Collection/TestIterator.php <ide> public function __construct($data) <ide> parent::__construct($data); <ide> } <ide> <del> public function checkValues() <add> public function checkValues(): bool <ide> { <ide> return true; <ide> } <ide><path>tests/test_app/TestApp/Controller/Component/RequestHandlerExtComponent.php <ide> class RequestHandlerExtComponent extends RequestHandlerComponent <ide> { <ide> public $ext; <ide> <del> public function getExt() <add> public function getExt(): ?string <ide> { <ide> return $this->ext; <ide> } <ide><path>tests/test_app/TestApp/Controller/DependenciesController.php <ide> public function __construct( <ide> $this->inject = $inject; <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function requiredString(string $str) <ide> { <ide> return $this->response->withStringBody(json_encode(compact('str'))); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function optionalString(string $str = 'default val') <ide> { <ide> return $this->response->withStringBody(json_encode(compact('str'))); <ide> } <ide> <ide> /** <ide> * @param mixed $any <add> * @return \Cake\Http\Response <ide> */ <ide> public function optionalDep($any = null, ?string $str = null, ?stdClass $dep = null) <ide> { <ide> public function optionalDep($any = null, ?string $str = null, ?stdClass $dep = n <ide> <ide> /** <ide> * @param mixed $any <add> * @return \Cake\Http\Response <ide> */ <ide> public function requiredDep(stdClass $dep, $any = null, ?string $str = null) <ide> { <ide> return $this->response->withStringBody(json_encode(compact('dep', 'any', 'str'))); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function variadic() <ide> { <ide> return $this->response->withStringBody(json_encode(['args' => func_get_args()])); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function spread(string ...$args) <ide> { <ide> return $this->response->withStringBody(json_encode(['args' => $args])); <ide> } <ide> <ide> /** <ide> * @param mixed $one <add> * @return \Cake\Http\Response <ide> */ <ide> public function requiredParam($one) <ide> { <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> public function securePost() <ide> return $this->response->withStringBody('Request was accepted'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function file() <ide> { <ide> return $this->response->withFile(__FILE__); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function header() <ide> { <ide> return $this->getResponse()->withHeader('X-Cake', 'custom header'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function hostData() <ide> { <ide> $data = [ <ide> public function hostData() <ide> return $this->getResponse()->withStringBody(json_encode($data)); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function empty_response() <ide> { <ide> return $this->getResponse()->withStringBody(''); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function secretCookie() <ide> { <ide> return $this->response <ide> ->withCookie(new Cookie('secrets', 'name')) <ide> ->withStringBody('ok'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function stacked_flash() <ide> { <ide> $this->Flash->error('Error 1'); <ide> public function stacked_flash() <ide> return $this->getResponse()->withStringBody(''); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function throw_exception() <ide> { <ide> $this->Flash->error('Error 1'); <ide><path>tests/test_app/TestApp/Controller/TestController.php <ide> public function reflection($passed, Table $table) <ide> { <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function returner() <ide> { <ide> return $this->response->withStringBody('I am from the controller.'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function willCauseException() <ide> { <ide> return ''; <ide><path>tests/test_app/TestApp/Controller/TestsAppsController.php <ide> public function index() <ide> $this->set('var', $var); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function some_method() <ide> { <ide> return $this->response->withStringBody('5'); <ide> public function set_action() <ide> $this->render('index'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function redirect_to() <ide> { <ide> return $this->redirect('http://cakephp.org'); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function redirect_to_permanent() <ide> { <ide> return $this->redirect('http://cakephp.org', 301); <ide> } <ide> <add> /** <add> * @return \Cake\Http\Response <add> */ <ide> public function set_type() <ide> { <ide> return $this->response->withType('json'); <ide><path>tests/test_app/TestApp/Database/ColumnSchemaAwareTypeValueObject.php <ide> public function __construct(string $value) <ide> $this->_value = $value; <ide> } <ide> <del> public function value() <add> public function value(): string <ide> { <ide> return $this->_value; <ide> } <ide><path>tests/test_app/TestApp/Error/Thing/DebuggableThing.php <ide> <ide> class DebuggableThing <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function __debugInfo() <ide> { <ide> return ['foo' => 'bar', 'inner' => new self()]; <ide><path>tests/test_app/TestApp/Form/ValidateForm.php <del><?php <del>declare(strict_types=1); <del> <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 3.6.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace TestApp\Form; <del> <del>use Cake\Form\Form; <del> <del>class ValidateForm extends Form <del>{ <del> protected function _buildValidator(\Cake\Validation\Validator $validator) <del> { <del> return $validator <del> ->requirePresence('title'); <del> } <del>} <ide><path>tests/test_app/TestApp/Http/Client/Adapter/CakeStreamWrapper.php <ide> class CakeStreamWrapper implements \ArrayAccess <ide> ], <ide> ]; <ide> <del> public function stream_open(string $path, string $mode, int $options, ?string &$openedPath) <add> public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool <ide> { <ide> if ($path === 'http://throw_exception/') { <ide> throw new \Exception(); <ide> public function stream_open(string $path, string $mode, int $options, ?string &$ <ide> return true; <ide> } <ide> <del> public function stream_close() <add> public function stream_close(): bool <ide> { <ide> return fclose($this->_stream); <ide> } <ide> <del> public function stream_read(int $count) <add> public function stream_read(int $count): string <ide> { <ide> if (isset($this->_query['sleep'])) { <ide> sleep(1); <ide> public function stream_read(int $count) <ide> return fread($this->_stream, $count); <ide> } <ide> <del> public function stream_eof() <add> public function stream_eof(): bool <ide> { <ide> return feof($this->_stream); <ide> } <ide> <del> public function stream_set_option(int $option, int $arg1, int $arg2) <add> public function stream_set_option(int $option, int $arg1, int $arg2): bool <ide> { <ide> return false; <ide> } <ide><path>tests/test_app/TestApp/Http/EventApplication.php <ide> <ide> class EventApplication extends BaseApplication <ide> { <del> public function events(EventManagerInterface $eventManager) <add> public function events(EventManagerInterface $eventManager): EventManagerInterface <ide> { <ide> $eventManager->on('My.event', function () { <ide> }); <ide><path>tests/test_app/TestApp/Mailer/TestMailer.php <ide> class TestMailer extends Mailer <ide> <ide> public $boundary = null; <ide> <del> public function deliver(string $content = '') <add> public function deliver(string $content = ''): array <ide> { <ide> $result = parent::deliver($content); <ide> $this->boundary = $this->message->getBoundary(); <ide><path>tests/test_app/TestApp/Model/Behavior/SluggableBehavior.php <ide> <ide> class SluggableBehavior extends Behavior <ide> { <del> public function beforeFind(EventInterface $event, Query $query, array $options = []) <add> public function beforeFind(EventInterface $event, Query $query, array $options = []): Query <ide> { <ide> $query->where(['slug' => 'test']); <ide> <ide> return $query; <ide> } <ide> <del> public function findNoSlug(Query $query, array $options = []) <add> public function findNoSlug(Query $query, array $options = []): Query <ide> { <ide> $query->where(['slug IS' => null]); <ide> <ide> return $query; <ide> } <ide> <del> public function slugify(string $value) <add> public function slugify(string $value): string <ide> { <ide> return Text::slug($value); <ide> } <ide><path>tests/test_app/TestApp/Model/Behavior/ValidationBehavior.php <ide> */ <ide> class ValidationBehavior extends Behavior <ide> { <add> /** <add> * @return $this <add> */ <ide> public function validationBehavior(Validator $validator) <ide> { <ide> return $validator->add('name', 'behaviorRule'); <ide><path>tests/test_app/TestApp/Model/Entity/VirtualUser.php <ide> class VirtualUser extends Entity <ide> 'bonus', <ide> ]; <ide> <del> protected function _getBonus() <add> protected function _getBonus(): string <ide> { <ide> return 'bonus'; <ide> } <ide><path>tests/test_app/TestApp/Model/Table/AuthorsTable.php <ide> public function initialize(array $config): void <ide> $this->hasMany('articles'); <ide> } <ide> <del> public function findByAuthor(Query $query, array $options = []) <add> public function findByAuthor(Query $query, array $options = []): Query <ide> { <ide> if (isset($options['author_id'])) { <ide> $query->where(['Articles.id' => $options['author_id']]); <ide><path>tests/test_app/TestApp/Model/Table/PaginatorPostsTable.php <ide> public function initialize(array $config): void <ide> /** <ide> * Finder method for find('popular'); <ide> */ <del> public function findPopular(Query $query, array $options) <add> public function findPopular(Query $query, array $options): Query <ide> { <ide> $field = $this->getAlias() . '.' . $this->getPrimaryKey(); <ide> $query->where([$field . ' >' => '1']); <ide> public function findPopular(Query $query, array $options) <ide> /** <ide> * Finder for published posts. <ide> */ <del> public function findPublished(Query $query, array $options) <add> public function findPublished(Query $query, array $options): Query <ide> { <ide> $query->where(['published' => 'Y']); <ide> <ide> public function findPublished(Query $query, array $options) <ide> * <ide> * @return \Cake\ORM\Query <ide> */ <del> public function findAuthor(Query $query, array $options = []) <add> public function findAuthor(Query $query, array $options = []): Query <ide> { <ide> if (isset($options['author_id'])) { <ide> $query->where(['PaginatorPosts.author_id' => $options['author_id']]); <ide><path>tests/test_app/TestApp/Shell/SampleShell.php <ide> public function withAbort() <ide> $this->abort('Bad things'); <ide> } <ide> <del> public function returnValue() <add> public function returnValue(): int <ide> { <ide> return 99; <ide> } <ide><path>tests/test_app/TestApp/View/Helper/BananaHelper.php <ide> <ide> class BananaHelper extends Helper <ide> { <del> public function peel() <add> public function peel(): string <ide> { <ide> return '<b>peeled</b>'; <ide> } <ide><path>tests/test_app/TestApp/View/Helper/NumberHelperTestObject.php <ide> public function attach(NumberMock $cakeNumber) <ide> $this->_engine = $cakeNumber; <ide> } <ide> <add> /** <add> * @return mixed <add> */ <ide> public function engine() <ide> { <ide> return $this->_engine;
111
Text
Text
use serve_static_files in guides [skip ci]
85f7924af1c1af847bf5d6b5661feac057cf1084
<ide><path>guides/source/configuring.md <ide> numbers. New applications filter out passwords by adding the following `config.f <ide> <ide> * `secrets.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`. <ide> <del>* `config.serve_static_files` configures Rails to serve static files. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able use page caching and requests for files that exist under the public directory. <add>* `config.serve_static_assets` configures Rails to serve static files. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able use page caching and requests for files that exist under the public directory. <ide> <ide> * `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified: <ide> <ide><path>guides/source/upgrading_ruby_on_rails.md <ide> You can help test performance with these additions to your test environment: <ide> <ide> ```ruby <ide> # Configure static asset server for tests with Cache-Control for performance <del>config.serve_static_assets = true <add>config.serve_static_files = true <ide> config.static_cache_control = 'public, max-age=3600' <ide> ``` <ide>
2
Ruby
Ruby
use fetch for downloading bottles
d47cf55f68fb1d381cfbdc9de905dc33c7ce5a83
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch <ide> the_tarball, _ = f.fetch <ide> next unless the_tarball.kind_of? Pathname <ide> <del> previous_md5 = f.instance_variable_get(:@md5).to_s.downcase <add> bottle = install_bottle? f <add> <add> previous_md5 = f.instance_variable_get(:@md5).to_s.downcase unless bottle <ide> previous_sha1 = f.instance_variable_get(:@sha1).to_s.downcase <del> previous_sha2 = f.instance_variable_get(:@sha256).to_s.downcase <add> previous_sha2 = f.instance_variable_get(:@sha256).to_s.downcase unless bottle <ide> <del> puts "MD5: #{the_tarball.md5}" <add> puts "MD5: #{the_tarball.md5}" unless bottle <ide> puts "SHA1: #{the_tarball.sha1}" <del> puts "SHA256: #{the_tarball.sha2}" <add> puts "SHA256: #{the_tarball.sha2}" unless bottle <ide> <del> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5 <add> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5 or bottle <ide> opoo "Formula reports different MD5: #{previous_md5}" <ide> end <ide> unless previous_sha1.nil? or previous_sha1.empty? or the_tarball.sha1 == previous_sha1 <ide> opoo "Formula reports different SHA1: #{previous_sha1}" <ide> end <del> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2 <add> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2 or bottle <ide> opoo "Formula reports different SHA256: #{previous_sha2}" <ide> end <ide> end <ide><path>Library/Homebrew/formula.rb <ide> def system cmd, *args <ide> <ide> # For brew-fetch and others. <ide> def fetch <del> downloader = @downloader <del> # Don't attempt mirrors if this install is not pointed at a "stable" URL. <del> # This can happen when options like `--HEAD` are invoked. <del> mirror_list = @spec_to_use == @standard ? mirrors : [] <add> if install_bottle? self <add> downloader = CurlBottleDownloadStrategy.new bottle_url, name, version, nil <add> else <add> downloader = @downloader <add> # Don't attempt mirrors if this install is not pointed at a "stable" URL. <add> # This can happen when options like `--HEAD` are invoked. <add> mirror_list = @spec_to_use == @standard ? mirrors : [] <add> end <ide> <ide> # Ensure the cache exists <ide> HOMEBREW_CACHE.mkpath <ide><path>Library/Homebrew/formula_installer.rb <ide> def clean <ide> end <ide> <ide> def pour <del> HOMEBREW_CACHE.mkpath <del> downloader = CurlBottleDownloadStrategy.new f.bottle_url, f.name, f.version, nil <del> downloader.fetch <del> f.verify_download_integrity downloader.tarball_path, f.bottle_sha1, "SHA1" <add> fetched, downloader = f.fetch <add> f.verify_download_integrity fetched, f.bottle_sha1, "SHA1" <ide> HOMEBREW_CELLAR.cd do <ide> downloader.stage <ide> end
3
Javascript
Javascript
flow type vendor/core/merge.js
419722bd07e7495a45feadc0ce116a832f880d98
<ide><path>Libraries/vendor/core/merge.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <ide> */ <ide> <del>"use strict"; <add>'use strict'; <ide> <ide> const mergeInto = require('./mergeInto'); <ide> <ide> const mergeInto = require('./mergeInto'); <ide> * @param {?object} two Optional object with properties to merge from. <ide> * @return {object} The shallow extension of one by two. <ide> */ <del>const merge = function(one, two) { <add>const merge = function<T1, T2>(one: T1, two: T2): {...T1, ...T2} { <ide> const result = {}; <ide> mergeInto(result, one); <ide> mergeInto(result, two); <add> // $FlowFixMe mergeInto is not typed <ide> return result; <ide> }; <ide>
1
PHP
PHP
restore old exception message
94d9824a218098b6e1277bf1b7997fee031d9b27
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php <ide> protected function getDictionaryKey($attribute) <ide> return $attribute->value; <ide> } <ide> <del> $msg = 'Model attribute value is an object but does not have a __toString method '. <del> 'and does not implement \Illuminate\Contracts\Database\Eloquent\StringableAttribute interface.'; <del> throw new InvalidArgumentException($msg); <add> throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.'); <ide> } <ide> <ide> return $attribute;
1
Javascript
Javascript
remove string.prototype.split polyfill warning
5c4792038474fe2c8107f925c066c260be09b2a5
<ide><path>src/renderers/dom/ReactDOM.js <ide> if (__DEV__) { <ide> Date.now, <ide> Function.prototype.bind, <ide> Object.keys, <del> String.prototype.split, <ide> String.prototype.trim, <ide> ]; <ide>
1
PHP
PHP
update version on master
62ccd385b89ca125f17d6ce45e3645517c6ce00a
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements HttpKernelInterface, TerminableIn <ide> * <ide> * @var string <ide> */ <del> const VERSION = '4.2-dev'; <add> const VERSION = '4.3-dev'; <ide> <ide> /** <ide> * Indicates if the application has "booted".
1
Javascript
Javascript
fix assertion order
98d1d53b2009b72ef85792977d3cf68e2118b381
<ide><path>test/parallel/test-utf8-scripts.js <ide> const assert = require('assert'); <ide> <ide> console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); <ide> <del>assert.strictEqual(true, /Hellö Wörld/.test('Hellö Wörld')); <add>assert.strictEqual(/Hellö Wörld/.test('Hellö Wörld'), true);
1
Javascript
Javascript
use the new uri parser
f65b36eec1e3bf07307e926981b3ec57a0145c1f
<ide><path>lib/http.js <ide> var STATUS_CODES = exports.STATUS_CODES = { <ide> 505 : 'HTTP Version not supported' <ide> }; <ide> <del>/* <del> parseUri 1.2.1 <del> (c) 2007 Steven Levithan <stevenlevithan.com> <del> MIT License <del>*/ <del> <del>function decode (s) { <del> return decodeURIComponent(s.replace(/\+/g, ' ')); <del>} <del> <del>exports.parseUri = function (str) { <del> var o = exports.parseUri.options, <del> m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), <del> uri = {}, <del> i = 14; <del> <del> while (i--) uri[o.key[i]] = m[i] || ""; <del> <del> uri[o.q.name] = {}; <del> uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { <del> if ($1) { <del> try { <del> var key = decode($1); <del> var val = decode($2); <del> } catch (e) { <del> return; <del> } <del> uri[o.q.name][key] = val; <del> } <del> }); <del> uri.toString = function () { return str; }; <del> <del> for (i = o.key.length - 1; i >= 0; i--){ <del> if (uri[o.key[i]] == "") delete uri[o.key[i]]; <del> } <del> <del> return uri; <del>}; <del> <del>exports.parseUri.options = { <del> strictMode: false, <del> key: [ <del> "source", <del> "protocol", <del> "authority", <del> "userInfo", <del> "user", <del> "password", <del> "host", <del> "port", <del> "relative", <del> "path", <del> "directory", <del> "file", <del> "query", <del> "anchor" <del> ], <del> q: { <del> name: "params", <del> parser: /(?:^|&)([^&=]*)=?([^&]*)/g <del> }, <del> parser: { <del> strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, <del> loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ <del> } <del>}; <del> <del> <ide> var connection_expression = /Connection/i; <ide> var transfer_encoding_expression = /Transfer-Encoding/i; <ide> var close_expression = /close/i; <ide> function IncomingMessage (connection) { <ide> sys.inherits(IncomingMessage, process.EventEmitter); <ide> exports.IncomingMessage = IncomingMessage; <ide> <add>var decode = require("uri").decode; <ide> IncomingMessage.prototype._parseQueryString = function () { <ide> var parts = this.uri.queryString.split('&'); <ide> for (var j = 0; j < parts.length; j++) { <ide> exports.cat = function (url, encoding, headers) { <ide> <ide> encoding = encoding || "utf8"; <ide> <del> var uri = exports.parseUri(url); <add> var uri = require("uri").parse(url); <ide> headers = headers || {}; <del> if (!headers["Host"] && uri.host) { <del> headers["Host"] = uri.host; <add> <add> var hasHost = false; <add> for (var i in headers) if (i.toLowerCase() === "host") { <add> hasHost = true; <add> break; <add> } <add> if (!hasHost) { <add> headers["Host"] = uri.domain; <ide> } <ide> <del> var client = exports.createClient(uri.port || 80, uri.host); <add> var client = exports.createClient(uri.port || 80, uri.domain); <ide> var req = client.request(uri.path || "/", headers); <ide> <ide> client.addListener("error", function () {
1
Javascript
Javascript
change assertion to deprecation
28504216e0cd9b8de8ee4bbb67da6f749addec44
<ide><path>packages/ember-application/lib/utils/validate-type.js <ide> export default function validateType(resolvedType, parsedName) { <ide> return; <ide> } <ide> <add> // 2.0TODO: Remove this deprecation warning <add> if (parsedName.type === 'service') { <add> Ember.deprecate( <add> "In Ember 2.0 service factories must have an `isServiceFactory` " + <add> `property set to true. You registered ${resolvedType} as a service ` + <add> "factory. Either add the `isServiceFactory` property to this factory or " + <add> "extend from Ember.Service.", <add> resolvedType.isServiceFactory <add> ); <add> return; <add> } <add> <ide> let [factoryFlag, expectedType] = validationAttributes; <ide> <ide> Ember.assert(`Expected ${parsedName.fullName} to resolve to an ${expectedType} but instead it was ${resolvedType}.`, function() { <ide><path>packages/ember-application/tests/system/dependency_injection/default_resolver_test.js <ide> QUnit.test("lookup description", function() { <ide> }); <ide> <ide> QUnit.test("validating resolved objects", function() { <del> let types = ['route', 'component', 'view', 'service']; <add> // 2.0TODO: Add service to this list <add> let types = ['route', 'component', 'view']; <ide> <ide> // Valid setup <ide> application.FooRoute = Route.extend(); <ide> QUnit.test("validating resolved objects", function() { <ide> }, matcher, `Should assert for ${type}`); <ide> }); <ide> }); <add> <add>QUnit.test("deprecation warning for service factories without isServiceFactory property", function() { <add> expectDeprecation(/service factories must have an `isServiceFactory` property/); <add> application.FooService = EmberObject.extend(); <add> registry.resolve('service:foo'); <add> <add>}); <add> <add>QUnit.test("no deprecation warning for service factories that extend from Ember.Service", function() { <add> expectNoDeprecation(); <add> application.FooService = Service.extend(); <add> registry.resolve('service:foo'); <add>});
2
Ruby
Ruby
use configure as the heuristic for autotools
8df33f74467641de025cabbc3ace4433bb15be76
<ide><path>Library/Homebrew/cmd/diy.rb <ide> def diy <ide> <ide> if File.file? "CMakeLists.txt" <ide> puts "-DCMAKE_INSTALL_PREFIX=#{prefix}" <del> elsif File.file? "Makefile.am" <add> elsif File.file? "configure" <ide> puts "--prefix=#{prefix}" <ide> else <ide> raise "Couldn't determine build system"
1
Ruby
Ruby
remove useless `gemfile` option
f200a52e164f9fa26bc4d0813c14281674c105d2
<ide><path>railties/test/isolation/abstract_unit.rb <ide> def build_app(options = {}) <ide> end <ide> end <ide> <del> gemfile_path = "#{app_path}/Gemfile" <del> if options[:gemfile].blank? && File.exist?(gemfile_path) <del> File.delete gemfile_path <del> end <del> <ide> routes = File.read("#{app_path}/config/routes.rb") <ide> if routes =~ /(\n\s*end\s*)\Z/ <ide> File.open("#{app_path}/config/routes.rb", "w") do |f|
1
Python
Python
fix typo in project euler sol1.py
e5dd2b1eb74751e6f42cfc100c22792a799beedb
<ide><path>project_euler/problem_31/sol1.py <ide> def two_pound(x): <ide> <ide> <ide> def solution(n): <del> """Returns the number of different ways can £n be made using any number of <add> """Returns the number of different ways can n pence be made using any number of <ide> coins? <ide> <ide> >>> solution(500)
1
Javascript
Javascript
fix more memory leaks
f01d6f4e23412b868cbf5b65b9bc2128d9680924
<ide><path>src/js/menu/menu.js <ide> class Menu extends Component { <ide> return; <ide> } <ide> <del> component.on('blur', this.boundHandleBlur_); <del> component.on(['tap', 'click'], this.boundHandleTapClick_); <add> this.on(component, 'blur', this.boundHandleBlur_); <add> this.on(component, ['tap', 'click'], this.boundHandleTapClick_); <ide> } <ide> <ide> /** <ide> class Menu extends Component { <ide> return; <ide> } <ide> <del> component.off('blur', this.boundHandleBlur_); <del> component.off(['tap', 'click'], this.boundHandleTapClick_); <add> this.off(component, 'blur', this.boundHandleBlur_); <add> this.off(component, ['tap', 'click'], this.boundHandleTapClick_); <ide> } <ide> <ide> /** <ide><path>src/js/player.js <ide> class Player extends Component { <ide> this.autoplay(this.options_.autoplay); <ide> } <ide> <add> // check plugins <add> if (options.plugins) { <add> Object.keys(options.plugins).forEach((name) => { <add> if (typeof this[name] !== 'function') { <add> throw new Error(`plugin "${name}" does not exist`); <add> } <add> }); <add> } <add> <ide> /* <ide> * Store the internal state of scrubbing <ide> * <ide> class Player extends Component { <ide> <ide> // Load plugins <ide> if (options.plugins) { <del> const plugins = options.plugins; <del> <del> Object.keys(plugins).forEach(function(name) { <del> if (typeof this[name] === 'function') { <del> this[name](plugins[name]); <del> } else { <del> throw new Error(`plugin "${name}" does not exist`); <del> } <del> }, this); <add> Object.keys(options.plugins).forEach((name) => { <add> this[name](options.plugins[name]); <add> }); <ide> } <ide> <ide> this.options_.playerOptions = playerOptionsCopy; <ide><path>src/js/tech/tech.js <ide> Tech.withSourceHandlers = function(_Tech) { <ide> } <ide> <ide> this.sourceHandler_ = sh.handleSource(source, this, this.options_); <del> this.on('dispose', this.disposeSourceHandler); <add> this.one('dispose', this.disposeSourceHandler); <ide> }; <ide> <ide> /** <ide><path>src/js/tracks/html-track-element-list.js <ide> class HtmlTrackElementList { <ide> removeTrackElement_(trackElement) { <ide> for (let i = 0, length = this.trackElements_.length; i < length; i++) { <ide> if (trackElement === this.trackElements_[i]) { <del> this.trackElements_.splice(i, 1); <add> if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') { <add> this.trackElements_[i].track.off(); <add> } <ide> <add> if (typeof this.trackElements_[i].off === 'function') { <add> this.trackElements_[i].off(); <add> } <add> this.trackElements_.splice(i, 1); <ide> break; <ide> } <ide> } <ide><path>src/js/tracks/text-track.js <ide> const loadTrack = function(src, track) { <ide> // NOTE: this is only used for the alt/video.novtt.js build <ide> if (typeof window.WebVTT !== 'function') { <ide> if (track.tech_) { <del> const loadHandler = () => parseCues(responseBody, track); <del> <del> track.tech_.on('vttjsloaded', loadHandler); <del> track.tech_.on('vttjserror', () => { <add> // to prevent use before define eslint error, we define loadHandler <add> // as a let here <add> let loadHandler; <add> const errorHandler = () => { <ide> log.error(`vttjs failed to load, stopping trying to process ${track.src}`); <ide> track.tech_.off('vttjsloaded', loadHandler); <del> }); <add> }; <add> <add> loadHandler = () => { <add> track.tech_.off('vttjserror', errorHandler); <add> return parseCues(responseBody, track); <add> }; <ide> <add> track.tech_.one('vttjsloaded', loadHandler); <add> track.tech_.one('vttjserror', errorHandler); <ide> } <ide> } else { <ide> parseCues(responseBody, track);
5
Ruby
Ruby
skip the failing tests on rubinius for now
562b0b23684333be8766dc73c419f7b753933626
<ide><path>actionpack/test/controller/live_stream_test.rb <ide> def test_write_to_stream <ide> end <ide> <ide> def test_async_stream <add> rubinius_skip "https://github.com/rubinius/rubinius/issues/2934" <add> <ide> @controller.latch = ActiveSupport::Concurrency::Latch.new <ide> parts = ['hello', 'world'] <ide> <ide><path>activemodel/test/cases/attribute_assignment_test.rb <ide> def dup <ide> end <ide> <ide> test "assign private attribute" do <add> rubinius_skip "https://github.com/rubinius/rubinius/issues/3328" <add> <ide> model = Model.new <ide> assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do <ide> model.assign_attributes(metadata: { a: 1 }) <ide><path>activesupport/test/core_ext/object/duplicable_test.rb <ide> class DuplicableTest < ActiveSupport::TestCase <ide> ALLOW_DUP << BigDecimal.new('4.56') <ide> <ide> def test_duplicable <add> rubinius_skip "* Method#dup is allowed at the moment on Rubinius\n" \ <add> "* https://github.com/rubinius/rubinius/issues/3089" <add> <ide> RAISE_DUP.each do |v| <ide> assert !v.duplicable? <ide> assert_raises(TypeError, v.class.name) { v.dup } <ide><path>activesupport/test/json/encoding_test.rb <ide> def sorted_json(json) <ide> end <ide> <ide> def test_process_status <add> rubinius_skip "https://github.com/rubinius/rubinius/issues/3334" <add> <ide> # There doesn't seem to be a good way to get a handle on a Process::Status object without actually <ide> # creating a child process, hence this to populate $? <ide> system("not_a_real_program_#{SecureRandom.hex}")
4
Ruby
Ruby
remove the default logger
23faa711c951b93df7b6ba61239e47395b766fee
<ide><path>actioncable/lib/action_cable/server/configuration.rb <ide> class Configuration <ide> attr_accessor :url <ide> <ide> def initialize <del> @logger = Rails.logger <ide> @log_tags = [] <ide> <ide> @connection_class = ApplicationCable::Connection
1
Python
Python
remove uneeded code
bd73a15363295658e150754edf6d1073cbdb3975
<ide><path>numpy/lib/format.py <ide> def descr_to_dtype(descr): <ide> <ide> This function reverses the process, eliminating the empty padding fields. <ide> ''' <del> if isinstance(descr, (str, dict)): <add> if isinstance(descr, str): <ide> # No padding removal needed <ide> return numpy.dtype(descr) <ide> elif isinstance(descr, tuple): <del> if isinstance(descr[0], list): <del> # subtype, will always have a shape descr[1] <del> dt = descr_to_dtype(descr[0]) <del> return numpy.dtype((dt, descr[1])) <del> return numpy.dtype(descr) <add> # subtype, will always have a shape descr[1] <add> dt = descr_to_dtype(descr[0]) <add> return numpy.dtype((dt, descr[1])) <ide> fields = [] <ide> offset = 0 <ide> for field in descr: <ide><path>numpy/lib/tests/test_format.py <ide> def test_pickle_disallow(): <ide> ('c', np.int32), <ide> ], align=True), <ide> (3,)), <del> np.dtype([('x', ([('a', '|i1'), <del> ('', '|V3'), <del> ('b', '|i1'), <del> ('', '|V3'), <del> ], <del> (3,)), <del> (4,), <del> )]), <ide> np.dtype([('x', np.dtype({'names':['a','b'], <ide> 'formats':['i1','i1'], <ide> 'offsets':[0,4], <ide> def test_pickle_disallow(): <ide> )), <ide> (4,) <ide> ))) <del> ]) <add> ]), <add> np.dtype([ <add> ('a', np.dtype(( <add> np.dtype(( <add> np.dtype(( <add> np.dtype([ <add> ('a', int), <add> ('b', np.dtype({'names':['a','b'], <add> 'formats':['i1','i1'], <add> 'offsets':[0,4], <add> 'itemsize':8})), <add> ]), <add> (3,), <add> )), <add> (4,), <add> )), <add> (5,), <add> ))) <add> ]), <ide> ]) <add> <ide> def test_descr_to_dtype(dt): <ide> dt1 = format.descr_to_dtype(dt.descr) <ide> assert_equal_(dt1, dt)
2
Ruby
Ruby
add support for prefetch-src directive
1007191f31d7ce8486f1f32a5d700bbac66ae242
<ide><path>actionpack/lib/action_dispatch/http/content_security_policy.rb <ide> def generate_content_security_policy_nonce <ide> manifest_src: "manifest-src", <ide> media_src: "media-src", <ide> object_src: "object-src", <add> prefetch_src: "prefetch-src", <ide> script_src: "script-src", <ide> style_src: "style-src", <ide> worker_src: "worker-src" <ide><path>actionpack/test/dispatch/content_security_policy_test.rb <ide> def test_fetch_directives <ide> @policy.object_src false <ide> assert_no_match %r{object-src}, @policy.build <ide> <add> @policy.prefetch_src :self <add> assert_match %r{prefetch-src 'self'}, @policy.build <add> <add> @policy.prefetch_src false <add> assert_no_match %r{prefetch-src}, @policy.build <add> <ide> @policy.script_src :self <ide> assert_match %r{script-src 'self'}, @policy.build <ide>
2
Text
Text
fix typo in readme.md
a6c743e2d2df82e87956c24e187940ab3d3afac5
<ide><path>examples/multi-part-library/README.md <ide> This example demonstrates how to build a complex library with webpack. The libra <ide> <ide> When using this library with script tags it exports itself to the namespace `MyLibrary` and each part to a property in this namespace (`MyLibrary.alpha` and `MyLibrary.beta`). When consuming the library with CommonsJs or AMD it just export each part. <ide> <del>We are using mutliple entry points (`entry` option) to build every part of the library as separate output file. The `output.filename` option contains `[name]` to give each output file a different name. <add>We are using multiple entry points (`entry` option) to build every part of the library as separate output file. The `output.filename` option contains `[name]` to give each output file a different name. <ide> <ide> We are using the `libraryTarget` option to generate a UMD ([Universal Module Definition](https://github.com/umdjs/umd)) module that is consumable in CommonsJs, AMD and with script tags. The `library` option defines the namespace. We are using `[name]` in the `library` option to give every entry a different namespace. <ide> <ide> chunk {0} MyLibrary.beta.js (beta) 24 bytes [entry] [rendered] <ide> chunk {1} MyLibrary.alpha.js (alpha) 25 bytes [entry] [rendered] <ide> > alpha [0] ./alpha.js <ide> [0] ./alpha.js 25 bytes {1} [built] <del>``` <ide>\ No newline at end of file <add>```
1
Python
Python
get the correct instance
1a16289edeea73253826916ca230af2bf30ba39f
<ide><path>rest_framework/tests/generics.py <ide> def test_put_as_create_on_id_based_url(self): <ide> content_type='application/json') <ide> response = self.view(request, pk=5).render() <ide> self.assertEquals(response.status_code, status.HTTP_201_CREATED) <del> new_obj = self.objects.get(slug='test_slug') <add> new_obj = self.objects.get(pk=5) <ide> self.assertEquals(new_obj.text, 'foobar') <ide> <ide> def test_put_as_create_on_slug_based_url(self):
1
PHP
PHP
fix model binding when cached
af806851931700e8dd8de0ac0333efd853b19f3d
<ide><path>src/Illuminate/Routing/AbstractRouteCollection.php <ide> public function compile() <ide> 'fallback' => $route->isFallback, <ide> 'defaults' => $route->defaults, <ide> 'wheres' => $route->wheres, <add> 'bindingFields' => $route->bindingFields(), <ide> ]; <ide> } <ide> <ide><path>src/Illuminate/Routing/CompiledRouteCollection.php <ide> public function add(Route $route) <ide> 'fallback' => $route->isFallback, <ide> 'defaults' => $route->defaults, <ide> 'wheres' => $route->wheres, <add> 'bindingFields' => $route->bindingFields(), <ide> ]; <ide> <ide> $this->compiled = []; <ide> protected function newRoute(array $attributes) <ide> ->setFallback($attributes['fallback']) <ide> ->setDefaults($attributes['defaults']) <ide> ->setWheres($attributes['wheres']) <add> ->setBindingFields($attributes['bindingFields']) <ide> ->setRouter($this->router) <ide> ->setContainer($this->container); <ide> } <ide><path>src/Illuminate/Routing/Route.php <ide> public function bindingFieldFor($parameter) <ide> return $this->bindingFields[$parameter] ?? null; <ide> } <ide> <add> /** <add> * Get the binding fields for the route. <add> * <add> * @return array <add> */ <add> public function bindingFields() <add> { <add> return $this->bindingFields ?? []; <add> } <add> <add> /** <add> * Set the binding fields for the route. <add> * <add> * @param array $bindingFields <add> * @return $this <add> */ <add> public function setBindingFields(array $bindingFields) <add> { <add> $this->bindingFields = $bindingFields; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Get the parent parameter of the given parameter. <ide> *
3
Ruby
Ruby
make `tests` an internal command
c6f1ccc2157012cdbc7a70fa9cf8595a1fb5ac1a
<add><path>Library/Homebrew/cmd/tests.rb <del><path>Library/Contributions/cmd/brew-tests.rb <ide> def tests <ide> end <ide> end <ide> end <del> <del>Homebrew.tests
1
Python
Python
fix intention of loop in test_copyto_permut
ee7ca7d14cc073453b00d73102046515ea1b077c
<ide><path>numpy/core/tests/test_api.py <ide> def test_copyto_permut(): <ide> r = np.zeros(power) <ide> mask = np.array(l) <ide> imask = np.array(l).view(np.uint8) <del> imask[mask != 0] = 0xFF <add> imask[mask != 0] = c <ide> np.copyto(r, d, where=mask) <ide> assert_array_equal(r == 1, l) <ide> assert_equal(r.sum(), sum(l))
1
Python
Python
remove unnecessary import
4491212da4430181cd4d35cee5d341de87b3ac0d
<ide><path>tests/keras/backend/test_backends.py <del>import sys <ide> import pytest <ide> from numpy.testing import assert_allclose <ide> import numpy as np
1
Javascript
Javascript
reduce hash lookups for dom properties
40963e503b4724241a3f738641bd8e4290ce4637
<ide><path>src/renderers/dom/shared/DOMProperty.js <ide> var DOMPropertyInjection = { <ide> * @param {object} domPropertyConfig the config as described above. <ide> */ <ide> injectDOMPropertyConfig: function(domPropertyConfig) { <add> var Injection = DOMPropertyInjection; <ide> var Properties = domPropertyConfig.Properties || {}; <ide> var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; <ide> var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; <ide> var DOMPropertyInjection = { <ide> <ide> for (var propName in Properties) { <ide> invariant( <del> !DOMProperty.isStandardName.hasOwnProperty(propName), <add> !DOMProperty.properties.hasOwnProperty(propName), <ide> 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + <ide> '\'%s\' which has already been injected. You may be accidentally ' + <ide> 'injecting the same DOM property config twice, or you may be ' + <ide> 'injecting two configs that have conflicting property names.', <ide> propName <ide> ); <ide> <del> DOMProperty.isStandardName[propName] = true; <del> <ide> var lowerCased = propName.toLowerCase(); <del> DOMProperty.getPossibleStandardName[lowerCased] = propName; <del> <del> if (DOMAttributeNames.hasOwnProperty(propName)) { <del> var attributeName = DOMAttributeNames[propName]; <del> DOMProperty.getPossibleStandardName[attributeName] = propName; <del> DOMProperty.getAttributeName[propName] = attributeName; <del> } else { <del> DOMProperty.getAttributeName[propName] = lowerCased; <del> } <del> <del> if (DOMAttributeNamespaces.hasOwnProperty(propName)) { <del> DOMProperty.getAttributeNamespace[propName] = <del> DOMAttributeNamespaces[propName]; <del> } else { <del> DOMProperty.getAttributeNamespace[propName] = null; <del> } <del> <del> DOMProperty.getPropertyName[propName] = <del> DOMPropertyNames.hasOwnProperty(propName) ? <del> DOMPropertyNames[propName] : <del> propName; <del> <del> if (DOMMutationMethods.hasOwnProperty(propName)) { <del> DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; <del> } else { <del> DOMProperty.getMutationMethod[propName] = null; <del> } <del> <ide> var propConfig = Properties[propName]; <del> DOMProperty.mustUseAttribute[propName] = <del> checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); <del> DOMProperty.mustUseProperty[propName] = <del> checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); <del> DOMProperty.hasSideEffects[propName] = <del> checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); <del> DOMProperty.hasBooleanValue[propName] = <del> checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); <del> DOMProperty.hasNumericValue[propName] = <del> checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); <del> DOMProperty.hasPositiveNumericValue[propName] = <del> checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); <del> DOMProperty.hasOverloadedBooleanValue[propName] = <del> checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); <add> <add> var propertyInfo = { <add> attributeName: lowerCased, <add> attributeNamespace: null, <add> propertyName: propName, <add> mutationMethod: null, <add> <add> mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), <add> mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), <add> hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), <add> hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), <add> hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), <add> hasPositiveNumericValue: <add> checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), <add> hasOverloadedBooleanValue: <add> checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE), <add> }; <ide> <ide> invariant( <del> !DOMProperty.mustUseAttribute[propName] || <del> !DOMProperty.mustUseProperty[propName], <add> !propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty, <ide> 'DOMProperty: Cannot require using both attribute and property: %s', <ide> propName <ide> ); <ide> invariant( <del> DOMProperty.mustUseProperty[propName] || <del> !DOMProperty.hasSideEffects[propName], <add> propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects, <ide> 'DOMProperty: Properties that have side effects must use property: %s', <ide> propName <ide> ); <ide> invariant( <del> !!DOMProperty.hasBooleanValue[propName] + <del> !!DOMProperty.hasNumericValue[propName] + <del> !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, <add> propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + <add> propertyInfo.hasOverloadedBooleanValue <= 1, <ide> 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + <ide> 'numeric value, but not a combination: %s', <ide> propName <ide> ); <add> <add> if (__DEV__) { <add> DOMProperty.getPossibleStandardName[lowerCased] = propName; <add> } <add> <add> if (DOMAttributeNames.hasOwnProperty(propName)) { <add> var attributeName = DOMAttributeNames[propName]; <add> propertyInfo.attributeName = attributeName; <add> if (__DEV__) { <add> DOMProperty.getPossibleStandardName[attributeName] = propName; <add> } <add> } <add> <add> if (DOMAttributeNamespaces.hasOwnProperty(propName)) { <add> propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; <add> } <add> <add> if (DOMPropertyNames.hasOwnProperty(propName)) { <add> propertyInfo.propertyName = DOMPropertyNames[propName]; <add> } <add> <add> if (DOMMutationMethods.hasOwnProperty(propName)) { <add> propertyInfo.mutationMethod = DOMMutationMethods[propName]; <add> } <add> <add> DOMProperty.properties[propName] = propertyInfo; <ide> } <ide> }, <ide> }; <ide> var DOMProperty = { <ide> ID_ATTRIBUTE_NAME: 'data-reactid', <ide> <ide> /** <del> * Checks whether a property name is a standard property. <del> * @type {Object} <add> * Map from property "standard name" to an object with info about how to set <add> * the property in the DOM. Each object contains: <add> * <add> * attributeName: <add> * Used when rendering markup or with `*Attribute()`. <add> * attributeNamespace <add> * propertyName: <add> * Used on DOM node instances. (This includes properties that mutate due to <add> * external factors.) <add> * mutationMethod: <add> * If non-null, used instead of the property or `setAttribute()` after <add> * initial render. <add> * mustUseAttribute: <add> * Whether the property must be accessed and mutated using `*Attribute()`. <add> * (This includes anything that fails `<propName> in <element>`.) <add> * mustUseProperty: <add> * Whether the property must be accessed and mutated as an object property. <add> * hasSideEffects: <add> * Whether or not setting a value causes side effects such as triggering <add> * resources to be loaded or text selection changes. If true, we read from <add> * the DOM before updating to ensure that the value is only set if it has <add> * changed. <add> * hasBooleanValue: <add> * Whether the property should be removed when set to a falsey value. <add> * hasNumericValue: <add> * Whether the property must be numeric or parse as a numeric and should be <add> * removed when set to a falsey value. <add> * hasPositiveNumericValue: <add> * Whether the property must be positive numeric or parse as a positive <add> * numeric and should be removed when set to a falsey value. <add> * hasOverloadedBooleanValue: <add> * Whether the property can be used as a flag as well as with a value. <add> * Removed when strictly equal to false; present without a value when <add> * strictly equal to true; present with a value otherwise. <ide> */ <del> isStandardName: {}, <add> properties: {}, <ide> <ide> /** <ide> * Mapping from lowercase property names to the properly cased version, used <del> * to warn in the case of missing properties. <del> * @type {Object} <del> */ <del> getPossibleStandardName: {}, <del> <del> /** <del> * Mapping from normalized names to attribute names that differ. Attribute <del> * names are used when rendering markup or with `*Attribute()`. <del> * @type {Object} <del> */ <del> getAttributeName: {}, <del> <del> /** <del> * Mapping from normalized names to namespaces. <del> * @type {Object} <del> */ <del> getAttributeNamespace: {}, <del> <del> /** <del> * Mapping from normalized names to properties on DOM node instances. <del> * (This includes properties that mutate due to external factors.) <del> * @type {Object} <del> */ <del> getPropertyName: {}, <del> <del> /** <del> * Mapping from normalized names to mutation methods. This will only exist if <del> * mutation cannot be set simply by the property or `setAttribute()`. <del> * @type {Object} <del> */ <del> getMutationMethod: {}, <del> <del> /** <del> * Whether the property must be accessed and mutated as an object property. <del> * @type {Object} <del> */ <del> mustUseAttribute: {}, <del> <del> /** <del> * Whether the property must be accessed and mutated using `*Attribute()`. <del> * (This includes anything that fails `<propName> in <element>`.) <del> * @type {Object} <del> */ <del> mustUseProperty: {}, <del> <del> /** <del> * Whether or not setting a value causes side effects such as triggering <del> * resources to be loaded or text selection changes. We must ensure that <del> * the value is only set if it has changed. <del> * @type {Object} <del> */ <del> hasSideEffects: {}, <del> <del> /** <del> * Whether the property should be removed when set to a falsey value. <del> * @type {Object} <del> */ <del> hasBooleanValue: {}, <del> <del> /** <del> * Whether the property must be numeric or parse as a <del> * numeric and should be removed when set to a falsey value. <del> * @type {Object} <del> */ <del> hasNumericValue: {}, <del> <del> /** <del> * Whether the property must be positive numeric or parse as a positive <del> * numeric and should be removed when set to a falsey value. <del> * @type {Object} <del> */ <del> hasPositiveNumericValue: {}, <del> <del> /** <del> * Whether the property can be used as a flag as well as with a value. Removed <del> * when strictly equal to false; present without a value when strictly equal <del> * to true; present with a value otherwise. <add> * to warn in the case of missing properties. Available only in __DEV__. <ide> * @type {Object} <ide> */ <del> hasOverloadedBooleanValue: {}, <add> getPossibleStandardName: __DEV__ ? {} : null, <ide> <ide> /** <ide> * All of the isCustomAttribute() functions that have been injected. <ide><path>src/renderers/dom/shared/DOMPropertyOperations.js <ide> function isAttributeNameSafe(attributeName) { <ide> return false; <ide> } <ide> <del>function shouldIgnoreValue(name, value) { <add>function shouldIgnoreValue(propertyInfo, value) { <ide> return value == null || <del> (DOMProperty.hasBooleanValue[name] && !value) || <del> (DOMProperty.hasNumericValue[name] && isNaN(value)) || <del> (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) || <del> (DOMProperty.hasOverloadedBooleanValue[name] && value === false); <add> (propertyInfo.hasBooleanValue && !value) || <add> (propertyInfo.hasNumericValue && isNaN(value)) || <add> (propertyInfo.hasPositiveNumericValue && (value < 1)) || <add> (propertyInfo.hasOverloadedBooleanValue && value === false); <ide> } <ide> <ide> if (__DEV__) { <ide> var DOMPropertyOperations = { <ide> * @return {?string} Markup string, or null if the property was invalid. <ide> */ <ide> createMarkupForProperty: function(name, value) { <del> if (DOMProperty.isStandardName.hasOwnProperty(name) && <del> DOMProperty.isStandardName[name]) { <del> if (shouldIgnoreValue(name, value)) { <add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? <add> DOMProperty.properties[name] : null; <add> if (propertyInfo) { <add> if (shouldIgnoreValue(propertyInfo, value)) { <ide> return ''; <ide> } <del> var attributeName = DOMProperty.getAttributeName[name]; <del> if (DOMProperty.hasBooleanValue[name] || <del> (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) { <add> var attributeName = propertyInfo.attributeName; <add> if (propertyInfo.hasBooleanValue || <add> (propertyInfo.hasOverloadedBooleanValue && value === true)) { <ide> return attributeName + '=""'; <ide> } <ide> return attributeName + '=' + quoteAttributeValueForBrowser(value); <ide> var DOMPropertyOperations = { <ide> * @param {*} value <ide> */ <ide> setValueForProperty: function(node, name, value) { <del> if (DOMProperty.isStandardName.hasOwnProperty(name) && <del> DOMProperty.isStandardName[name]) { <del> var mutationMethod = DOMProperty.getMutationMethod[name]; <add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? <add> DOMProperty.properties[name] : null; <add> if (propertyInfo) { <add> var mutationMethod = propertyInfo.mutationMethod; <ide> if (mutationMethod) { <ide> mutationMethod(node, value); <del> } else if (shouldIgnoreValue(name, value)) { <add> } else if (shouldIgnoreValue(propertyInfo, value)) { <ide> this.deleteValueForProperty(node, name); <del> } else if (DOMProperty.mustUseAttribute[name]) { <del> var attributeName = DOMProperty.getAttributeName[name]; <del> var namespace = DOMProperty.getAttributeNamespace[name]; <add> } else if (propertyInfo.mustUseAttribute) { <add> var attributeName = propertyInfo.attributeName; <add> var namespace = propertyInfo.attributeNamespace; <ide> // `setAttribute` with objects becomes only `[object]` in IE8/9, <ide> // ('' + value) makes it output the correct toString()-value. <ide> if (namespace) { <ide> var DOMPropertyOperations = { <ide> node.setAttribute(attributeName, '' + value); <ide> } <ide> } else { <del> var propName = DOMProperty.getPropertyName[name]; <add> var propName = propertyInfo.propertyName; <ide> // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the <ide> // property type before comparing; only `value` does and is string. <del> if (!DOMProperty.hasSideEffects[name] || <add> if (!propertyInfo.hasSideEffects || <ide> ('' + node[propName]) !== ('' + value)) { <ide> // Contrary to `setAttribute`, object properties are properly <ide> // `toString`ed by IE8/9. <ide> var DOMPropertyOperations = { <ide> * @param {string} name <ide> */ <ide> deleteValueForProperty: function(node, name) { <del> if (DOMProperty.isStandardName.hasOwnProperty(name) && <del> DOMProperty.isStandardName[name]) { <del> var mutationMethod = DOMProperty.getMutationMethod[name]; <add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? <add> DOMProperty.properties[name] : null; <add> if (propertyInfo) { <add> var mutationMethod = propertyInfo.mutationMethod; <ide> if (mutationMethod) { <ide> mutationMethod(node, undefined); <del> } else if (DOMProperty.mustUseAttribute[name]) { <del> node.removeAttribute(DOMProperty.getAttributeName[name]); <add> } else if (propertyInfo.mustUseAttribute) { <add> node.removeAttribute(propertyInfo.attributeName); <ide> } else { <del> var propName = DOMProperty.getPropertyName[name]; <add> var propName = propertyInfo.propertyName; <ide> var defaultValue = DOMProperty.getDefaultValueForProperty( <ide> node.nodeName, <ide> propName <ide> ); <del> if (!DOMProperty.hasSideEffects[name] || <add> if (!propertyInfo.hasSideEffects || <ide> ('' + node[propName]) !== defaultValue) { <ide> node[propName] = defaultValue; <ide> } <ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> ReactDOMComponent.Mixin = { <ide> deleteListener(this._rootNodeID, propKey); <ide> } <ide> } else if ( <del> DOMProperty.isStandardName[propKey] || <add> DOMProperty.properties[propKey] || <ide> DOMProperty.isCustomAttribute(propKey)) { <ide> BackendIDOperations.deletePropertyByID( <ide> this._rootNodeID, <ide> ReactDOMComponent.Mixin = { <ide> nextProp <ide> ); <ide> } else if ( <del> DOMProperty.isStandardName[propKey] || <add> DOMProperty.properties[propKey] || <ide> DOMProperty.isCustomAttribute(propKey)) { <ide> BackendIDOperations.updatePropertyByID( <ide> this._rootNodeID,
3
Javascript
Javascript
add tests for longitude wrapping
f9f4e265f4389a8ec49efaaa9dea9d72e4ee6d92
<ide><path>test/geo/path-test.js <ide> suite.addBatch({ <ide> path({type: "LineString", coordinates: [[0, 88], [180, 89]]}); <ide> assert.isTrue(testContext.buffer().filter(function(d) { return d.type === "lineTo"; }).length > 1); <ide> } <add> }, <add> "rotate([0, 0, 0])": { <add> "longitudes wrap at ±180°": function(path) { <add> path({type: "Point", coordinates: [180 + 1e-6, 0]}); <add> assert.deepEqual(testContext.buffer(), [{type: "point", x: -420, y: 250}]); <add> } <ide> } <ide> } <ide> });
1
Go
Go
fix bad order of iptables filter rules
6149b1f32f20dc971d4d18ae8e8a32d3d5704c42
<ide><path>libnetwork/drivers/bridge/setup_ip_tables.go <ide> func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairp <ide> hpNatRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}} <ide> skipDNAT = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{"-t", "nat"}, args: []string{"-i", bridgeIface, "-j", "RETURN"}} <ide> outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}} <del> inRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}} <ide> ) <ide> <ide> // Set NAT. <ide> func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairp <ide> return err <ide> } <ide> <del> // Set Accept on incoming packets for existing connections. <del> if err := programChainRule(inRule, "ACCEPT INCOMING", enable); err != nil { <del> return err <del> } <del> <ide> return nil <ide> } <ide> <ide><path>libnetwork/drivers/bridge/setup_ip_tables_test.go <ide> func TestProgramIPTable(t *testing.T) { <ide> }{ <ide> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-d", "127.1.2.3", "-i", "lo", "-o", "lo", "-j", "DROP"}}, "Test Loopback"}, <ide> {iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", iptablesTestBridgeIP, "!", "-o", DefaultBridgeName, "-j", "MASQUERADE"}}, "NAT Test"}, <del> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "!", "-o", DefaultBridgeName, "-j", "ACCEPT"}}, "Test ACCEPT NON_ICC OUTGOING"}, <ide> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-o", DefaultBridgeName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}}, "Test ACCEPT INCOMING"}, <add> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "!", "-o", DefaultBridgeName, "-j", "ACCEPT"}}, "Test ACCEPT NON_ICC OUTGOING"}, <ide> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "-o", DefaultBridgeName, "-j", "ACCEPT"}}, "Test enable ICC"}, <ide> {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "-o", DefaultBridgeName, "-j", "DROP"}}, "Test disable ICC"}, <ide> } <ide><path>libnetwork/iptables/iptables.go <ide> func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) err <ide> } <ide> <ide> } <add> establish := []string{ <add> "-o", bridgeName, <add> "-m", "conntrack", <add> "--ctstate", "RELATED,ESTABLISHED", <add> "-j", "ACCEPT"} <add> if !Exists(Filter, "FORWARD", establish...) && enable { <add> insert := append([]string{string(Insert), "FORWARD"}, establish...) <add> if output, err := Raw(insert...); err != nil { <add> return err <add> } else if len(output) != 0 { <add> return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output) <add> } <add> } else if Exists(Filter, "FORWARD", establish...) && !enable { <add> del := append([]string{string(Delete), "FORWARD"}, establish...) <add> if output, err := Raw(del...); err != nil { <add> return err <add> } else if len(output) != 0 { <add> return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output) <add> } <add> } <ide> } <ide> return nil <ide> }
3
Ruby
Ruby
fix examples of number_to_percentage
816b35e781271b0466b3f76a7c3241874331008d
<ide><path>activesupport/lib/active_support/number_helper.rb <ide> def number_to_currency(number, options = {}) <ide> # <ide> # ==== Examples <ide> # <del> # number_to_percentage(100) # => 100.000% <del> # number_to_percentage('98') # => 98.000% <del> # number_to_percentage(100, precision: 0) # => 100% <del> # number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000% <del> # number_to_percentage(302.24398923423, precision: 5) # => 302.24399% <del> # number_to_percentage(1000, locale: :fr) # => 1 000,000% <del> # number_to_percentage('98a') # => 98a% <del> # number_to_percentage(100, format: '%n %') # => 100 % <add> # number_to_percentage(100) # => 100.000% <add> # number_to_percentage('98') # => 98.000% <add> # number_to_percentage(100, precision: 0) # => 100% <add> # number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000% <add> # number_to_percentage(302.24398923423, precision: 5) # => 302.24399% <add> # number_to_percentage(1000, locale: :fr) # => 1 000,000% <add> # number_to_percentage('98a') # => 98a% <add> # number_to_percentage(100, format: '%n %') # => 100 % <ide> def number_to_percentage(number, options = {}) <ide> return unless number <ide> options = options.symbolize_keys
1
Ruby
Ruby
add math tests
2beafeddf0378c0b4b0780c0d57c694b79f1f710
<ide><path>activerecord/test/cases/arel/attributes/math_test.rb <add># frozen_string_literal: true <add> <add>require_relative "../helper" <add> <add>module Arel <add> module Attributes <add> class MathTest < Arel::Spec <add> %i[* /].each do |math_operator| <add> it "average should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].average.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> AVG("users"."id") #{math_operator} 2 <add> } <add> end <add> <add> it "count should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].count.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> COUNT("users"."id") #{math_operator} 2 <add> } <add> end <add> <add> it "maximum should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].maximum.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> MAX("users"."id") #{math_operator} 2 <add> } <add> end <add> <add> it "minimum should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].minimum.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> MIN("users"."id") #{math_operator} 2 <add> } <add> end <add> <add> it "attribute node should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].public_send(math_operator, 2)).to_sql.must_be_like %{ <add> "users"."id" #{math_operator} 2 <add> } <add> end <add> end <add> <add> %i[+ - & | ^ << >>].each do |math_operator| <add> it "average should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].average.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> (AVG("users"."id") #{math_operator} 2) <add> } <add> end <add> <add> it "count should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].count.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> (COUNT("users"."id") #{math_operator} 2) <add> } <add> end <add> <add> it "maximum should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].maximum.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> (MAX("users"."id") #{math_operator} 2) <add> } <add> end <add> <add> it "minimum should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].minimum.public_send(math_operator, 2)).to_sql.must_be_like %{ <add> (MIN("users"."id") #{math_operator} 2) <add> } <add> end <add> <add> it "attribute node should be compatiable with #{math_operator}" do <add> table = Arel::Table.new :users <add> (table[:id].public_send(math_operator, 2)).to_sql.must_be_like %{ <add> ("users"."id" #{math_operator} 2) <add> } <add> end <add> end <add> end <add> end <add>end <ide><path>activerecord/test/cases/arel/nodes/count_test.rb <ide> class Arel::Nodes::CountTest < Arel::Spec <ide> assert_equal 2, array.uniq.size <ide> end <ide> end <del> <del> describe "math" do <del> it "allows mathematical functions" do <del> table = Arel::Table.new :users <del> (table[:id].count + 1).to_sql.must_be_like %{ <del> (COUNT("users"."id") + 1) <del> } <del> end <del> end <ide> end
2
Python
Python
fix flaky order of returned dag runs
2edab57d4e8ccbd5b8f66c3951615c169fb0543e
<ide><path>airflow/www/utils.py <ide> def get_mapped_summary(parent_instance, task_instances): <ide> <ide> <ide> def get_task_summaries(task, dag_runs: List[DagRun], session: Session) -> List[Dict[str, Any]]: <del> tis = session.query( <del> TaskInstance.dag_id, <del> TaskInstance.task_id, <del> TaskInstance.run_id, <del> TaskInstance.map_index, <del> TaskInstance.state, <del> TaskInstance.start_date, <del> TaskInstance.end_date, <del> TaskInstance._try_number, <del> ).filter( <del> TaskInstance.dag_id == task.dag_id, <del> TaskInstance.run_id.in_([dag_run.run_id for dag_run in dag_runs]), <del> TaskInstance.task_id == task.task_id, <del> # Only get normal task instances or the first mapped task <del> TaskInstance.map_index <= 0, <add> tis = ( <add> session.query( <add> TaskInstance.dag_id, <add> TaskInstance.task_id, <add> TaskInstance.run_id, <add> TaskInstance.map_index, <add> TaskInstance.state, <add> TaskInstance.start_date, <add> TaskInstance.end_date, <add> TaskInstance._try_number, <add> ) <add> .filter( <add> TaskInstance.dag_id == task.dag_id, <add> TaskInstance.run_id.in_([dag_run.run_id for dag_run in dag_runs]), <add> TaskInstance.task_id == task.task_id, <add> # Only get normal task instances or the first mapped task <add> TaskInstance.map_index <= 0, <add> ) <add> .order_by(TaskInstance.run_id.asc()) <ide> ) <ide> <ide> def _get_summary(task_instance): <ide><path>airflow/www/views.py <ide> def grid_data(self): <ide> 'groups': task_group_to_grid(dag.task_group, dag, dag_runs, session), <ide> 'dag_runs': encoded_runs, <ide> } <del> <ide> # avoid spaces to reduce payload size <ide> return ( <ide> htmlsafe_json_dumps(data, separators=(',', ':')), <ide> def audit_log(self, session=None): <ide> query = query.filter(Log.event.notin_(excluded_events)) <ide> <ide> dag_audit_logs = query.all() <del> <ide> content = self.render_template( <ide> 'airflow/dag_audit_log.html', <ide> dag=dag,
2
Go
Go
move types around in native driver
8db740a38e333158e613bc5b3a7acc2605131581
<ide><path>execdriver/native/driver.go <ide> import ( <ide> "errors" <ide> "fmt" <ide> "github.com/dotcloud/docker/execdriver" <del> "github.com/dotcloud/docker/execdriver/lxc" <ide> "github.com/dotcloud/docker/pkg/cgroups" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/pkg/libcontainer/nsinit" <del> "io" <ide> "io/ioutil" <ide> "os" <ide> "os/exec" <ide> import ( <ide> ) <ide> <ide> const ( <del> DriverName = "namespaces" <add> DriverName = "native" <ide> Version = "0.1" <ide> ) <ide> <ide> var ( <ide> <ide> func init() { <ide> execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error { <del> var container *libcontainer.Container <add> var ( <add> container *libcontainer.Container <add> ns = nsinit.NewNsInit(&nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{}) <add> ) <ide> f, err := os.Open("container.json") <ide> if err != nil { <ide> return err <ide> func init() { <ide> if err != nil { <ide> return err <ide> } <del> ns := nsinit.NewNsInit(&nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{}) <ide> if err := ns.Init(container, cwd, args.Console, syncPipe, args.Args); err != nil { <ide> return err <ide> } <ide> type driver struct { <ide> root string <ide> } <ide> <del>type info struct { <del> ID string <del> driver *driver <del>} <del> <del>func (i *info) IsRunning() bool { <del> p := filepath.Join(i.driver.root, "containers", i.ID, "root", ".nspid") <del> if _, err := os.Stat(p); err == nil { <del> return true <del> } <del> return false <del>} <del> <ide> func NewDriver(root string) (*driver, error) { <ide> return &driver{ <ide> root: root, <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> c: c, <ide> dsw: &nsinit.DefaultStateWriter{c.Rootfs}, <ide> } <add> ns = nsinit.NewNsInit(factory, stateWriter) <ide> ) <del> ns := nsinit.NewNsInit(factory, stateWriter) <ide> if c.Tty { <ide> term = &dockerTtyTerm{ <ide> pipes: pipes, <ide> func createContainer(c *execdriver.Command) *libcontainer.Container { <ide> } <ide> return container <ide> } <del> <del>type dockerStdTerm struct { <del> lxc.StdConsole <del> pipes *execdriver.Pipes <del>} <del> <del>func (d *dockerStdTerm) Attach(cmd *exec.Cmd) error { <del> return d.AttachPipes(cmd, d.pipes) <del>} <del> <del>func (d *dockerStdTerm) SetMaster(master *os.File) { <del> // do nothing <del>} <del> <del>type dockerTtyTerm struct { <del> lxc.TtyConsole <del> pipes *execdriver.Pipes <del>} <del> <del>func (t *dockerTtyTerm) Attach(cmd *exec.Cmd) error { <del> go io.Copy(t.pipes.Stdout, t.MasterPty) <del> if t.pipes.Stdin != nil { <del> go io.Copy(t.MasterPty, t.pipes.Stdin) <del> } <del> return nil <del>} <del> <del>func (t *dockerTtyTerm) SetMaster(master *os.File) { <del> t.MasterPty = master <del>} <ide><path>execdriver/native/info.go <add>package native <add> <add>import ( <add> "os" <add> "path/filepath" <add>) <add> <add>type info struct { <add> ID string <add> driver *driver <add>} <add> <add>// IsRunning is determined by looking for the <add>// .nspid file for a container. If the file exists then the <add>// container is currently running <add>func (i *info) IsRunning() bool { <add> p := filepath.Join(i.driver.root, "containers", i.ID, "root", ".nspid") <add> if _, err := os.Stat(p); err == nil { <add> return true <add> } <add> return false <add>} <ide><path>execdriver/native/term.go <add>/* <add> These types are wrappers around the libcontainer Terminal interface so that <add> we can resuse the docker implementations where possible. <add>*/ <ide> package native <ide> <ide> import ( <ide> "github.com/dotcloud/docker/execdriver" <del> "github.com/dotcloud/docker/pkg/term" <add> "github.com/dotcloud/docker/execdriver/lxc" <add> "io" <ide> "os" <add> "os/exec" <ide> ) <ide> <del>type NsinitTerm struct { <del> master *os.File <add>type dockerStdTerm struct { <add> lxc.StdConsole <add> pipes *execdriver.Pipes <ide> } <ide> <del>func NewTerm(pipes *execdriver.Pipes, master *os.File) *NsinitTerm { <del> return &NsinitTerm{master} <add>func (d *dockerStdTerm) Attach(cmd *exec.Cmd) error { <add> return d.AttachPipes(cmd, d.pipes) <ide> } <ide> <del>func (t *NsinitTerm) Close() error { <del> return t.master.Close() <add>func (d *dockerStdTerm) SetMaster(master *os.File) { <add> // do nothing <ide> } <ide> <del>func (t *NsinitTerm) Resize(h, w int) error { <del> if t.master != nil { <del> return term.SetWinsize(t.master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) <add>type dockerTtyTerm struct { <add> lxc.TtyConsole <add> pipes *execdriver.Pipes <add>} <add> <add>func (t *dockerTtyTerm) Attach(cmd *exec.Cmd) error { <add> go io.Copy(t.pipes.Stdout, t.MasterPty) <add> if t.pipes.Stdin != nil { <add> go io.Copy(t.MasterPty, t.pipes.Stdin) <ide> } <ide> return nil <ide> } <add> <add>func (t *dockerTtyTerm) SetMaster(master *os.File) { <add> t.MasterPty = master <add>}
3
Ruby
Ruby
add bottle stanza by traversing ast
b8aa67be5b0aaac8c027cd57a61213150c12c55a
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge(args:) <ide> odie "--keep-old was passed but there was no existing bottle block!" if args.keep_old? <ide> puts output <ide> update_or_add = "add" <del> pattern = /( <del> (\ {2}\#[^\n]*\n)* # comments <del> \ {2}( # two spaces at the beginning <del> (url|head)\ ['"][\S\ ]+['"] # url or head with a string <del> ( <del> ,[\S\ ]*$ # url may have options <del> (\n^\ {3}[\S\ ]+$)* # options can be in multiple lines <del> )?| <del> (homepage|desc|sha256|version|mirror|license)\ ['"][\S\ ]+['"]| # specs with a string <del> license\ ( <del> [^\[]+?\[[^\]]+?\]| # license may contain a list <del> [^{]+?{[^}]+?}| # license may contain a hash <del> :\S+ # license as a symbol <del> )| <del> (revision|version_scheme)\ \d+| # revision with a number <del> (stable|livecheck)\ do(\n+^\ {4}[\S\ ]+$)*\n+^\ {2}end # components with blocks <del> )\n+ # multiple empty lines <del> )+ <del> /mx <del> string = s.sub!(pattern, "\\0#{output}\n") <del> odie "Bottle block addition failed!" unless string <add> Utils::Bottles.add_bottle_stanza!(s.inreplace_string, output) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/rubocops/components_order.rb <ide> module FormulaAudit <ide> # - `component_precedence_list` has component hierarchy in a nested list <ide> # where each sub array contains components' details which are at same precedence level <ide> class ComponentsOrder < FormulaCop <del> def audit_formula(_node, _class_node, _parent_class_node, body_node) <del> component_precedence_list = [ <del> [{ name: :include, type: :method_call }], <del> [{ name: :desc, type: :method_call }], <del> [{ name: :homepage, type: :method_call }], <del> [{ name: :url, type: :method_call }], <del> [{ name: :mirror, type: :method_call }], <del> [{ name: :version, type: :method_call }], <del> [{ name: :sha256, type: :method_call }], <del> [{ name: :license, type: :method_call }], <del> [{ name: :revision, type: :method_call }], <del> [{ name: :version_scheme, type: :method_call }], <del> [{ name: :head, type: :method_call }], <del> [{ name: :stable, type: :block_call }], <del> [{ name: :livecheck, type: :block_call }], <del> [{ name: :bottle, type: :block_call }], <del> [{ name: :pour_bottle?, type: :block_call }], <del> [{ name: :head, type: :block_call }], <del> [{ name: :bottle, type: :method_call }], <del> [{ name: :keg_only, type: :method_call }], <del> [{ name: :option, type: :method_call }], <del> [{ name: :deprecated_option, type: :method_call }], <del> [{ name: :disable!, type: :method_call }], <del> [{ name: :deprecate!, type: :method_call }], <del> [{ name: :depends_on, type: :method_call }], <del> [{ name: :uses_from_macos, type: :method_call }], <del> [{ name: :on_macos, type: :block_call }], <del> [{ name: :on_linux, type: :block_call }], <del> [{ name: :conflicts_with, type: :method_call }], <del> [{ name: :skip_clean, type: :method_call }], <del> [{ name: :cxxstdlib_check, type: :method_call }], <del> [{ name: :link_overwrite, type: :method_call }], <del> [{ name: :fails_with, type: :method_call }, { name: :fails_with, type: :block_call }], <del> [{ name: :go_resource, type: :block_call }, { name: :resource, type: :block_call }], <del> [{ name: :patch, type: :method_call }, { name: :patch, type: :block_call }], <del> [{ name: :needs, type: :method_call }], <del> [{ name: :install, type: :method_definition }], <del> [{ name: :post_install, type: :method_definition }], <del> [{ name: :caveats, type: :method_definition }], <del> [{ name: :plist_options, type: :method_call }, { name: :plist, type: :method_definition }], <del> [{ name: :test, type: :block_call }], <del> ] <add> COMPONENT_PRECEDENCE_LIST = [ <add> [{ name: :include, type: :method_call }], <add> [{ name: :desc, type: :method_call }], <add> [{ name: :homepage, type: :method_call }], <add> [{ name: :url, type: :method_call }], <add> [{ name: :mirror, type: :method_call }], <add> [{ name: :version, type: :method_call }], <add> [{ name: :sha256, type: :method_call }], <add> [{ name: :license, type: :method_call }], <add> [{ name: :revision, type: :method_call }], <add> [{ name: :version_scheme, type: :method_call }], <add> [{ name: :head, type: :method_call }], <add> [{ name: :stable, type: :block_call }], <add> [{ name: :livecheck, type: :block_call }], <add> [{ name: :bottle, type: :block_call }], <add> [{ name: :pour_bottle?, type: :block_call }], <add> [{ name: :head, type: :block_call }], <add> [{ name: :bottle, type: :method_call }], <add> [{ name: :keg_only, type: :method_call }], <add> [{ name: :option, type: :method_call }], <add> [{ name: :deprecated_option, type: :method_call }], <add> [{ name: :disable!, type: :method_call }], <add> [{ name: :deprecate!, type: :method_call }], <add> [{ name: :depends_on, type: :method_call }], <add> [{ name: :uses_from_macos, type: :method_call }], <add> [{ name: :on_macos, type: :block_call }], <add> [{ name: :on_linux, type: :block_call }], <add> [{ name: :conflicts_with, type: :method_call }], <add> [{ name: :skip_clean, type: :method_call }], <add> [{ name: :cxxstdlib_check, type: :method_call }], <add> [{ name: :link_overwrite, type: :method_call }], <add> [{ name: :fails_with, type: :method_call }, { name: :fails_with, type: :block_call }], <add> [{ name: :go_resource, type: :block_call }, { name: :resource, type: :block_call }], <add> [{ name: :patch, type: :method_call }, { name: :patch, type: :block_call }], <add> [{ name: :needs, type: :method_call }], <add> [{ name: :install, type: :method_definition }], <add> [{ name: :post_install, type: :method_definition }], <add> [{ name: :caveats, type: :method_definition }], <add> [{ name: :plist_options, type: :method_call }, { name: :plist, type: :method_definition }], <add> [{ name: :test, type: :block_call }], <add> ].freeze <ide> <del> @present_components, @offensive_nodes = check_order(component_precedence_list, body_node) <add> def audit_formula(_node, _class_node, _parent_class_node, body_node) <add> @present_components, @offensive_nodes = check_order(COMPONENT_PRECEDENCE_LIST, body_node) <ide> <ide> component_problem @offensive_nodes[0], @offensive_nodes[1] if @offensive_nodes <ide> <ide><path>Library/Homebrew/rubocops/shared/helper_functions.rb <ide> # typed: false <ide> # frozen_string_literal: true <ide> <add>require "rubocop" <add> <ide> module RuboCop <ide> module Cop <ide> # Helper functions for cops. <ide><path>Library/Homebrew/test/utils/bottles/bottles_spec.rb <ide> end <ide> end <ide> end <add> <add> describe "#add_bottle_stanza!" do <add> let(:bottle_output) do <add> require "active_support/core_ext/string/indent" <add> <add> <<~RUBY.chomp.indent(2) <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> RUBY <add> end <add> <add> context "when `license` is a string" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license "MIT" <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license "MIT" <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after `license`" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when `license` is a symbol" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license :cannot_represent <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license :cannot_represent <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after `license`" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when `license` is multiline" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license all_of: [ <add> :public_domain, <add> "MIT", <add> "GPL-3.0-or-later" => { with: "Autoconf-exception-3.0" }, <add> ] <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> license all_of: [ <add> :public_domain, <add> "MIT", <add> "GPL-3.0-or-later" => { with: "Autoconf-exception-3.0" }, <add> ] <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after `license`" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when `head` is a string" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> head "https://brew.sh/foo.git" <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> head "https://brew.sh/foo.git" <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after `head`" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when `head` is a block" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> <add> head do <add> url "https://brew.sh/foo.git" <add> end <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> <add> head do <add> url "https://brew.sh/foo.git" <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` before `head`" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when there is a comment on the same line" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" # comment <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" # comment <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after the comment" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when the next line is a comment" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> # comment <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> # comment <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` after the comment" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> <add> context "when the next line is blank and the one after it is a comment" do <add> let(:formula_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> <add> # comment <add> end <add> RUBY <add> end <add> <add> let(:new_contents) do <add> <<~RUBY.chomp <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tar.gz" <add> <add> bottle do <add> sha256 "f7b1fc772c79c20fddf621ccc791090bc1085fcef4da6cca03399424c66e06ca" => :sierra <add> end <add> <add> # comment <add> end <add> RUBY <add> end <add> <add> it "adds `bottle` before the comment" do <add> described_class.add_bottle_stanza! formula_contents, bottle_output <add> expect(formula_contents).to eq(new_contents) <add> end <add> end <add> end <ide> end <ide><path>Library/Homebrew/utils/bottles.rb <ide> def formula_contents(bottle_file, <ide> <ide> contents <ide> end <add> <add> def add_bottle_stanza!(formula_contents, bottle_output) <add> require "rubocop-ast" <add> <add> ruby_version = Version.new(HOMEBREW_REQUIRED_RUBY_VERSION).major_minor.to_f <add> processed_source = RuboCop::AST::ProcessedSource.new(formula_contents, ruby_version) <add> root_node = processed_source.ast <add> <add> class_node = if root_node.class_type? <add> root_node <add> elsif root_node.begin_type? <add> root_node.children.find do |n| <add> n.class_type? && n.parent_class&.const_name == "Formula" <add> end <add> end <add> <add> odie "Could not find formula class!" if class_node.nil? <add> <add> body_node = class_node.body <add> odie "Formula class is empty!" if body_node.nil? <add> <add> node_before_bottle = if body_node.begin_type? <add> body_node.children.compact.reduce do |previous_child, current_child| <add> break previous_child unless component_before_bottle_block? current_child <add> <add> current_child <add> end <add> else <add> body_node <add> end <add> node_before_bottle = node_before_bottle.last_argument if node_before_bottle.send_type? <add> <add> expr_before_bottle = node_before_bottle.location.expression <add> processed_source.comments.each do |comment| <add> comment_expr = comment.location.expression <add> distance = comment_expr.first_line - expr_before_bottle.first_line <add> case distance <add> when 0 <add> if comment_expr.last_line > expr_before_bottle.last_line || <add> comment_expr.end_pos > expr_before_bottle.end_pos <add> expr_before_bottle = comment_expr <add> end <add> when 1 <add> expr_before_bottle = comment_expr <add> end <add> end <add> <add> tree_rewriter = Parser::Source::TreeRewriter.new(processed_source.buffer) <add> tree_rewriter.insert_after(expr_before_bottle, "\n\n#{bottle_output.chomp}") <add> formula_contents.replace(tree_rewriter.process) <add> end <add> <add> private <add> <add> def component_before_bottle_block?(node) <add> require "rubocops/components_order" <add> <add> RuboCop::Cop::FormulaAudit::ComponentsOrder::COMPONENT_PRECEDENCE_LIST.each do |components| <add> components.each do |component| <add> return false if component[:name] == :bottle && component[:type] == :block_call <add> <add> case component[:type] <add> when :method_call <add> return true if node.send_type? && node.method_name == component[:name] <add> when :block_call <add> return true if node.block_type? && node.method_name == component[:name] <add> end <add> end <add> end <add> false <add> end <ide> end <ide> <ide> # Helper functions for bottles hosted on Bintray.
5
Ruby
Ruby
fix rubocop warnings
56fc1c725a752ef411e8f56aafe2602f2bb47592
<ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall <ide> end <ide> <ide> def rm_pin(rack) <del> Formulary.from_rack(rack).unpin rescue nil <add> Formulary.from_rack(rack).unpin <add> rescue <add> nil <ide> end <ide> end
1
Javascript
Javascript
add some basic tests
540fafaff2eb33f89e3935d39ff1c93933e3f5a1
<ide><path>lib/global-deprecation-utils.js <add>'use strict'; <add> <ide> const semver = require('semver'); <add>const validSemverRange = require('semver/ranges/valid'); <ide> <ide> function* walkAddonTree(project, pathToAddon = []) { <ide> for (let addon of project.addons) { <ide> function requirementFor(pkg, deps = {}) { <ide> return deps[pkg]; <ide> } <ide> <del>module.exports = function (project) { <del> if (process.env.EMBER_ENV === 'production') { <del> return; <del> } <add>const DEFAULT_RESULT = Object.freeze({ <add> globalMessage: '', <add> hasActionableSuggestions: false, <add> shouldIssueSingleDeprecation: false, <add> bootstrap: `require('@ember/-internals/bootstrap').default()`, <add>}); <ide> <del> let isYarnProject = ((root) => { <del> try { <del> // eslint-disable-next-line node/no-unpublished-require <del> return require('ember-cli/lib/utilities/is-yarn-project')(root); <del> } catch { <del> return undefined; <del> } <del> })(project.root); <add>module.exports = function (project, env = process.env) { <add> if (env.EMBER_ENV === 'production') { <add> return DEFAULT_RESULT; <add> } <ide> <ide> let groupedByTopLevelAddon = Object.create(null); <ide> let groupedByVersion = Object.create(null); <ide> module.exports = function (project) { <ide> let info; <ide> <ide> if (addon.parent === project) { <del> let requirement = requirementFor('ember-cli-babel', project.pkg.devDependencies); <del> let compatible = semver.satisfies('7.26.6', requirement); <add> let requirement = <add> requirementFor('ember-cli-babel', project.pkg.dependencies) || <add> requirementFor('ember-cli-babel', project.pkg.devDependencies); <add> <add> let validRange = validSemverRange(requirement); <add> let compatible = validRange ? semver.satisfies('7.26.6', requirement) : true; <ide> <ide> info = projectInfo = { <ide> parent: `${project.name()} (your app)`, <ide> module.exports = function (project) { <ide> }; <ide> } else { <ide> let requirement = requirementFor('ember-cli-babel', addon.parent.pkg.dependencies); <del> let compatible = semver.satisfies('7.26.6', requirement); <add> let validRange = validSemverRange(requirement); <add> let compatible = validRange ? semver.satisfies('7.26.6', requirement) : true; <ide> let dormant = addon.parent._fileSystemInfo <ide> ? addon.parent._fileSystemInfo().hasJSFiles === false <ide> : false; <ide> module.exports = function (project) { <ide> } <ide> <ide> if (Object.keys(groupedByVersion).length === 0) { <del> return; <add> return DEFAULT_RESULT; <ide> } <ide> <ide> let dormantTopLevelAddons = []; <ide> module.exports = function (project) { <ide> // Only show the compatible addons if the project itself is up-to-date, because updating the <ide> // project's own dependency on ember-cli-babel to latest may also get these addons to use it <ide> // as well. Otherwise, there is an unnecessary copy in the tree and it needs to be deduped. <del> if (isYarnProject === true) { <del> suggestions += <del> '* Run `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.\n'; <del> } else if (isYarnProject === false) { <del> suggestions += '* Run `npm dedupe`.\n'; <del> } else { <del> suggestions += <del> '* If using yarn, run `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.\n' + <del> '* If using npm, run `npm dedupe`.\n'; <del> } <add> suggestions += <add> '* If using yarn, run `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.\n' + <add> '* If using npm, run `npm dedupe`.\n'; <ide> <ide> hasActionableSuggestions = true; <ide> } <ide> module.exports = function (project) { <ide> if (projectInfo) { <ide> details += 'Try upgrading your `devDependencies` on `ember-cli-babel` to `^7.26.6`.\n'; <ide> } else { <del> if (isYarnProject === true) { <del> details += <del> 'Try running `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.\n'; <del> } else if (isYarnProject === false) { <del> details += 'Try running `npm dedupe`.\n'; <del> } else { <del> details += <del> 'If using yarn, try running `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.' + <del> 'If using npm, try running `npm dedupe`.\n'; <del> } <add> details += <add> 'If using yarn, try running `npx yarn-deduplicate --packages ember-cli-babel` followed by `yarn install`.' + <add> 'If using npm, try running `npm dedupe`.\n'; <ide> } <ide> } <ide> <ide><path>tests/node/global-deprecation-info-test.js <add>'use strict'; <add> <add>const globalDeprecationInfo = require('../../lib/global-deprecation-utils'); <add> <add>QUnit.module('globalDeprecationInfo', function (hooks) { <add> let project, env; <add> <add> function buildBabel(parent, version) { <add> return { <add> name: 'ember-cli-babel', <add> parent, <add> pkg: { <add> version, <add> }, <add> addons: [], <add> }; <add> } <add> <add> hooks.beforeEach(function () { <add> project = { <add> name() { <add> return 'fake-project'; <add> }, <add> pkg: { <add> dependencies: {}, <add> devDependencies: {}, <add> }, <add> addons: [], <add> }; <add> env = Object.create(null); <add> }); <add> <add> hooks.afterEach(function () {}); <add> <add> QUnit.test('when in production, does nothing', function (assert) { <add> env.EMBER_ENV = 'production'; <add> <add> let result = globalDeprecationInfo(project, env); <add> <add> assert.deepEqual(result, { <add> globalMessage: '', <add> hasActionableSuggestions: false, <add> shouldIssueSingleDeprecation: false, <add> bootstrap: `require('@ember/-internals/bootstrap').default()`, <add> }); <add> }); <add> <add> QUnit.test('without addons, does nothing', function (assert) { <add> project.addons = []; <add> let result = globalDeprecationInfo(project, env); <add> <add> assert.deepEqual(result, { <add> globalMessage: '', <add> hasActionableSuggestions: false, <add> shouldIssueSingleDeprecation: false, <add> bootstrap: `require('@ember/-internals/bootstrap').default()`, <add> }); <add> }); <add> <add> QUnit.test('projects own ember-cli-babel is too old', function (assert) { <add> project.pkg.devDependencies = { <add> 'ember-cli-babel': '^7.26.0', <add> }; <add> <add> project.addons.push({ <add> name: 'ember-cli-babel', <add> parent: project, <add> pkg: { <add> version: '7.26.5', <add> }, <add> addons: [], <add> }); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, true); <add> assert.strictEqual(result.hasActionableSuggestions, true); <add> assert.ok( <add> result.globalMessage.includes( <add> '* Upgrade your `devDependencies` on `ember-cli-babel` to `^7.26.6`' <add> ) <add> ); <add> }); <add> <add> QUnit.test('projects has ember-cli-babel in dependencies', function (assert) { <add> project.pkg.dependencies = { <add> 'ember-cli-babel': '^7.25.0', <add> }; <add> <add> project.addons.push({ <add> name: 'ember-cli-babel', <add> parent: project, <add> pkg: { <add> version: '7.26.5', <add> }, <add> addons: [], <add> }); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, true); <add> assert.strictEqual(result.hasActionableSuggestions, true); <add> assert.ok( <add> result.globalMessage.includes( <add> '* Upgrade your `devDependencies` on `ember-cli-babel` to `^7.26.6`' <add> ) <add> ); <add> }); <add> QUnit.test( <add> 'projects has no devDependencies, but old ember-cli-babel found in addons array', <add> function (assert) { <add> project.pkg.devDependencies = {}; <add> <add> project.addons.push({ <add> name: 'ember-cli-babel', <add> parent: project, <add> pkg: { <add> version: '7.26.5', <add> }, <add> addons: [], <add> }); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, true); <add> assert.strictEqual(result.hasActionableSuggestions, true); <add> assert.ok( <add> result.globalMessage.includes( <add> '* Upgrade your `devDependencies` on `ember-cli-babel` to `^7.26.6`' <add> ) <add> ); <add> } <add> ); <add> <add> QUnit.test('projects uses linked ember-cli-babel', function (assert) { <add> project.pkg.devDependencies = { <add> 'ember-cli-babel': 'link:./some/path/here', <add> }; <add> <add> let otherAddon = { <add> name: 'other-thing-here', <add> parent: project, <add> pkg: {}, <add> addons: [], <add> }; <add> <add> otherAddon.addons.push(buildBabel(otherAddon, '7.26.5')); <add> project.addons.push(buildBabel(project, '7.26.6'), otherAddon); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, true); <add> assert.strictEqual(result.hasActionableSuggestions, true); <add> <add> assert.ok( <add> result.globalMessage.includes( <add> '* If using yarn, run `npx yarn-deduplicate --packages ember-cli-babel`' <add> ) <add> ); <add> assert.ok(result.globalMessage.includes('* If using npm, run `npm dedupe`')); <add> }); <add> <add> QUnit.test('projects own ember-cli-babel is up to date', function (assert) { <add> project.pkg.devDependencies = { <add> 'ember-cli-babel': '^7.26.0', <add> }; <add> <add> project.addons.push({ <add> name: 'ember-cli-babel', <add> parent: project, <add> pkg: { <add> version: '7.26.6', <add> }, <add> addons: [], <add> }); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, false); <add> assert.strictEqual(result.hasActionableSuggestions, false); <add> assert.notOk( <add> result.globalMessage.includes( <add> '* Upgrade your `devDependencies` on `ember-cli-babel` to `^7.26.6`' <add> ) <add> ); <add> }); <add> <add> QUnit.test('transient babel that is out of date', function (assert) { <add> project.pkg.devDependencies = { <add> 'ember-cli-babel': '^7.26.0', <add> }; <add> <add> let otherAddon = { <add> name: 'other-thing-here', <add> parent: project, <add> pkg: { <add> dependencies: { <add> 'ember-cli-babel': '^7.25.0', <add> }, <add> }, <add> addons: [], <add> }; <add> <add> otherAddon.addons.push(buildBabel(otherAddon, '7.26.5')); <add> project.addons.push(buildBabel(project, '7.26.6'), otherAddon); <add> <add> let result = globalDeprecationInfo(project, env); <add> assert.strictEqual(result.shouldIssueSingleDeprecation, true); <add> assert.strictEqual(result.hasActionableSuggestions, true); <add> assert.ok(result.globalMessage.includes('* [email protected] (Compatible)')); <add> }); <add>});
2
Javascript
Javascript
add support for detached canvas element
f90ee8c786c24e44a252964c74970382d9c39016
<ide><path>src/chart.js <ide> plugins.push( <ide> <ide> Chart.plugins.register(plugins); <ide> <add>Chart.platform.initialize(); <add> <ide> module.exports = Chart; <ide> if (typeof window !== 'undefined') { <ide> window.Chart = Chart; <ide><path>src/core/core.helpers.js <ide> module.exports = function(Chart) { <ide> }; <ide> helpers.getMaximumWidth = function(domNode) { <ide> var container = domNode.parentNode; <add> if (!container) { <add> return domNode.clientWidth; <add> } <add> <ide> var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10); <ide> var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10); <ide> var w = container.clientWidth - paddingLeft - paddingRight; <ide> module.exports = function(Chart) { <ide> }; <ide> helpers.getMaximumHeight = function(domNode) { <ide> var container = domNode.parentNode; <add> if (!container) { <add> return domNode.clientHeight; <add> } <add> <ide> var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10); <ide> var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10); <ide> var h = container.clientHeight - paddingTop - paddingBottom; <ide><path>src/platforms/platform.dom.js <ide> <ide> var helpers = require('../helpers/index'); <ide> <add>var EXPANDO_KEY = '$chartjs'; <add>var CSS_PREFIX = 'chartjs-'; <add>var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor'; <add>var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation'; <add>var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart']; <add> <ide> /** <ide> * DOM event types -> Chart.js event types. <ide> * Note: only events with different types are mapped. <ide> * @see https://developer.mozilla.org/en-US/docs/Web/Events <ide> */ <del> <del>var eventTypeMap = { <del> // Touch events <add>var EVENT_TYPES = { <ide> touchstart: 'mousedown', <ide> touchmove: 'mousemove', <ide> touchend: 'mouseup', <del> <del> // Pointer events <ide> pointerenter: 'mouseenter', <ide> pointerdown: 'mousedown', <ide> pointermove: 'mousemove', <ide> function initCanvas(canvas, config) { <ide> var renderWidth = canvas.getAttribute('width'); <ide> <ide> // Chart.js modifies some canvas values that we want to restore on destroy <del> canvas._chartjs = { <add> canvas[EXPANDO_KEY] = { <ide> initial: { <ide> height: renderHeight, <ide> width: renderWidth, <ide> function createEvent(type, chart, x, y, nativeEvent) { <ide> } <ide> <ide> function fromNativeEvent(event, chart) { <del> var type = eventTypeMap[event.type] || event.type; <add> var type = EVENT_TYPES[event.type] || event.type; <ide> var pos = helpers.getRelativePosition(event, chart); <ide> return createEvent(type, chart, pos.x, pos.y, event); <ide> } <ide> <add>function throttled(fn, thisArg) { <add> var ticking = false; <add> var args = []; <add> <add> return function() { <add> args = Array.prototype.slice.call(arguments); <add> thisArg = thisArg || this; <add> <add> if (!ticking) { <add> ticking = true; <add> helpers.requestAnimFrame.call(window, function() { <add> ticking = false; <add> fn.apply(thisArg, args); <add> }); <add> } <add> }; <add>} <add> <ide> function createResizer(handler) { <ide> var iframe = document.createElement('iframe'); <ide> iframe.className = 'chartjs-hidden-iframe'; <ide> function createResizer(handler) { <ide> // https://github.com/chartjs/Chart.js/issues/3521 <ide> addEventListener(iframe, 'load', function() { <ide> addEventListener(iframe.contentWindow || iframe, 'resize', handler); <del> <ide> // The iframe size might have changed while loading, which can also <ide> // happen if the size has been changed while detached from the DOM. <ide> handler(); <ide> function createResizer(handler) { <ide> return iframe; <ide> } <ide> <del>function addResizeListener(node, listener, chart) { <del> var stub = node._chartjs = { <del> ticking: false <del> }; <del> <del> // Throttle the callback notification until the next animation frame. <del> var notify = function() { <del> if (!stub.ticking) { <del> stub.ticking = true; <del> helpers.requestAnimFrame.call(window, function() { <del> if (stub.resizer) { <del> stub.ticking = false; <del> return listener(createEvent('resize', chart)); <del> } <del> }); <add>// https://davidwalsh.name/detect-node-insertion <add>function watchForRender(node, handler) { <add> var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); <add> var proxy = expando.renderProxy = function(e) { <add> if (e.animationName === CSS_RENDER_ANIMATION) { <add> handler(); <ide> } <ide> }; <ide> <del> // Let's keep track of this added iframe and thus avoid DOM query when removing it. <del> stub.resizer = createResizer(notify); <add> helpers.each(ANIMATION_START_EVENTS, function(type) { <add> addEventListener(node, type, proxy); <add> }); <ide> <del> node.insertBefore(stub.resizer, node.firstChild); <add> node.classList.add(CSS_RENDER_MONITOR); <ide> } <ide> <del>function removeResizeListener(node) { <del> if (!node || !node._chartjs) { <del> return; <add>function unwatchForRender(node) { <add> var expando = node[EXPANDO_KEY] || {}; <add> var proxy = expando.renderProxy; <add> <add> if (proxy) { <add> helpers.each(ANIMATION_START_EVENTS, function(type) { <add> removeEventListener(node, type, proxy); <add> }); <add> <add> delete expando.renderProxy; <ide> } <ide> <del> var resizer = node._chartjs.resizer; <del> if (resizer) { <add> node.classList.remove(CSS_RENDER_MONITOR); <add>} <add> <add>function addResizeListener(node, listener, chart) { <add> var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); <add> <add> // Let's keep track of this added resizer and thus avoid DOM query when removing it. <add> var resizer = expando.resizer = createResizer(throttled(function() { <add> if (expando.resizer) { <add> return listener(createEvent('resize', chart)); <add> } <add> })); <add> <add> // The resizer needs to be attached to the node parent, so we first need to be <add> // sure that `node` is attached to the DOM before injecting the resizer element. <add> watchForRender(node, function() { <add> if (expando.resizer) { <add> var container = node.parentNode; <add> if (container && container !== resizer.parentNode) { <add> container.insertBefore(resizer, container.firstChild); <add> } <add> } <add> }); <add>} <add> <add>function removeResizeListener(node) { <add> var expando = node[EXPANDO_KEY] || {}; <add> var resizer = expando.resizer; <add> <add> delete expando.resizer; <add> unwatchForRender(node); <add> <add> if (resizer && resizer.parentNode) { <ide> resizer.parentNode.removeChild(resizer); <del> node._chartjs.resizer = null; <add> } <add>} <add> <add>function injectCSS(platform, css) { <add> // http://stackoverflow.com/q/3922139 <add> var style = platform._style || document.createElement('style'); <add> if (!platform._style) { <add> platform._style = style; <add> css = '/* Chart.js */\n' + css; <add> style.setAttribute('type', 'text/css'); <add> document.getElementsByTagName('head')[0].appendChild(style); <ide> } <ide> <del> delete node._chartjs; <add> style.appendChild(document.createTextNode(css)); <ide> } <ide> <ide> module.exports = { <add> initialize: function() { <add> var keyframes = 'from{opacity:0.99}to{opacity:1}'; <add> <add> injectCSS(this, <add> // DOM rendering detection <add> // https://davidwalsh.name/detect-node-insertion <add> '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' + <add> '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' + <add> '.' + CSS_RENDER_MONITOR + '{' + <add> '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' + <add> 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' + <add> '}' <add> ); <add> }, <add> <ide> acquireContext: function(item, config) { <ide> if (typeof item === 'string') { <ide> item = document.getElementById(item); <ide> module.exports = { <ide> <ide> releaseContext: function(context) { <ide> var canvas = context.canvas; <del> if (!canvas._chartjs) { <add> if (!canvas[EXPANDO_KEY]) { <ide> return; <ide> } <ide> <del> var initial = canvas._chartjs.initial; <add> var initial = canvas[EXPANDO_KEY].initial; <ide> ['height', 'width'].forEach(function(prop) { <ide> var value = initial[prop]; <ide> if (helpers.isNullOrUndef(value)) { <ide> module.exports = { <ide> // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html <ide> canvas.width = canvas.width; <ide> <del> delete canvas._chartjs; <add> delete canvas[EXPANDO_KEY]; <ide> }, <ide> <ide> addEventListener: function(chart, type, listener) { <ide> var canvas = chart.canvas; <ide> if (type === 'resize') { <ide> // Note: the resize event is not supported on all browsers. <del> addResizeListener(canvas.parentNode, listener, chart); <add> addResizeListener(canvas, listener, chart); <ide> return; <ide> } <ide> <del> var stub = listener._chartjs || (listener._chartjs = {}); <del> var proxies = stub.proxies || (stub.proxies = {}); <add> var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {}); <add> var proxies = expando.proxies || (expando.proxies = {}); <ide> var proxy = proxies[chart.id + '_' + type] = function(event) { <ide> listener(fromNativeEvent(event, chart)); <ide> }; <ide> module.exports = { <ide> var canvas = chart.canvas; <ide> if (type === 'resize') { <ide> // Note: the resize event is not supported on all browsers. <del> removeResizeListener(canvas.parentNode, listener); <add> removeResizeListener(canvas, listener); <ide> return; <ide> } <ide> <del> var stub = listener._chartjs || {}; <del> var proxies = stub.proxies || {}; <add> var expando = listener[EXPANDO_KEY] || {}; <add> var proxies = expando.proxies || {}; <ide> var proxy = proxies[chart.id + '_' + type]; <ide> if (!proxy) { <ide> return; <ide><path>src/platforms/platform.js <ide> var implementation = require('./platform.dom'); <ide> * @since 2.4.0 <ide> */ <ide> module.exports = helpers.extend({ <add> /** <add> * @since 2.7.0 <add> */ <add> initialize: function() {}, <add> <ide> /** <ide> * Called at chart construction time, returns a context2d instance implementing <ide> * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. <ide><path>test/jasmine.matchers.js <ide> function toBeChartOfSize() { <ide> var canvas = actual.ctx.canvas; <ide> var style = getComputedStyle(canvas); <ide> var pixelRatio = actual.options.devicePixelRatio || window.devicePixelRatio; <del> var dh = parseInt(style.height, 10); <del> var dw = parseInt(style.width, 10); <add> var dh = parseInt(style.height, 10) || 0; <add> var dw = parseInt(style.width, 10) || 0; <ide> var rh = canvas.height; <ide> var rw = canvas.width; <ide> var orh = rh / pixelRatio; <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> }); <ide> }); <ide> <add> // https://github.com/chartjs/Chart.js/issues/3790 <add> it('should resize the canvas if attached to the DOM after construction', function(done) { <add> var canvas = document.createElement('canvas'); <add> var wrapper = document.createElement('div'); <add> var body = window.document.body; <add> var chart = new Chart(canvas, { <add> type: 'line', <add> options: { <add> responsive: true, <add> maintainAspectRatio: false <add> } <add> }); <add> <add> expect(chart).toBeChartOfSize({ <add> dw: 0, dh: 0, <add> rw: 0, rh: 0, <add> }); <add> <add> wrapper.style.cssText = 'width: 455px; height: 355px'; <add> wrapper.appendChild(canvas); <add> body.appendChild(wrapper); <add> <add> waitForResize(chart, function() { <add> expect(chart).toBeChartOfSize({ <add> dw: 455, dh: 355, <add> rw: 455, rh: 355, <add> }); <add> <add> body.removeChild(wrapper); <add> chart.destroy(); <add> done(); <add> }); <add> }); <add> <add> it('should resize the canvas when attached to a different parent', function(done) { <add> var canvas = document.createElement('canvas'); <add> var wrapper = document.createElement('div'); <add> var body = window.document.body; <add> var chart = new Chart(canvas, { <add> type: 'line', <add> options: { <add> responsive: true, <add> maintainAspectRatio: false <add> } <add> }); <add> <add> expect(chart).toBeChartOfSize({ <add> dw: 0, dh: 0, <add> rw: 0, rh: 0, <add> }); <add> <add> wrapper.style.cssText = 'width: 455px; height: 355px'; <add> wrapper.appendChild(canvas); <add> body.appendChild(wrapper); <add> <add> waitForResize(chart, function() { <add> var resizer = wrapper.firstChild; <add> expect(resizer.tagName).toBe('IFRAME'); <add> expect(chart).toBeChartOfSize({ <add> dw: 455, dh: 355, <add> rw: 455, rh: 355, <add> }); <add> <add> var target = document.createElement('div'); <add> target.style.cssText = 'width: 640px; height: 480px'; <add> target.appendChild(canvas); <add> body.appendChild(target); <add> <add> waitForResize(chart, function() { <add> expect(target.firstChild).toBe(resizer); <add> expect(wrapper.firstChild).toBe(null); <add> expect(chart).toBeChartOfSize({ <add> dw: 640, dh: 480, <add> rw: 640, rh: 480, <add> }); <add> <add> body.removeChild(wrapper); <add> body.removeChild(target); <add> chart.destroy(); <add> done(); <add> }); <add> }); <add> }); <add> <ide> // https://github.com/chartjs/Chart.js/issues/3521 <ide> it('should resize the canvas after the wrapper has been re-attached to the DOM', function(done) { <ide> var chart = acquireChart({ <ide> describe('Chart', function() { <ide> }); <ide> <ide> describe('controller.destroy', function() { <del> it('should remove the resizer element when responsive: true', function() { <add> it('should remove the resizer element when responsive: true', function(done) { <ide> var chart = acquireChart({ <ide> options: { <ide> responsive: true <ide> } <ide> }); <ide> <del> var wrapper = chart.canvas.parentNode; <del> var resizer = wrapper.firstChild; <add> waitForResize(chart, function() { <add> var wrapper = chart.canvas.parentNode; <add> var resizer = wrapper.firstChild; <add> expect(wrapper.childNodes.length).toBe(2); <add> expect(resizer.tagName).toBe('IFRAME'); <ide> <del> expect(wrapper.childNodes.length).toBe(2); <del> expect(resizer.tagName).toBe('IFRAME'); <add> chart.destroy(); <ide> <del> chart.destroy(); <add> expect(wrapper.childNodes.length).toBe(1); <add> expect(wrapper.firstChild.tagName).toBe('CANVAS'); <ide> <del> expect(wrapper.childNodes.length).toBe(1); <del> expect(wrapper.firstChild.tagName).toBe('CANVAS'); <add> done(); <add> }); <ide> }); <ide> }); <ide>
6
PHP
PHP
use constraints for "unique" on postgres schemas
c002ae63371094b2cf9c731f779128e7a68e9970
<ide><path>laravel/database/schema/grammars/postgres.php <ide> public function primary(Table $table, Fluent $command) <ide> */ <ide> public function unique(Table $table, Fluent $command) <ide> { <del> return $this->key($table, $command, true); <add> $table = $this->wrap($table); <add> <add> $columns = $this->columnize($command->columns); <add> <add> return "ALTER TABLE $table ADD CONSTRAINT ".$command->name." UNIQUE ($columns)"; <ide> } <ide> <ide> /** <ide> public function drop_primary(Table $table, Fluent $command) <ide> */ <ide> public function drop_unique(Table $table, Fluent $command) <ide> { <del> return $this->drop_key($table, $command); <add> return "ALTER TABLE ".$this->wrap($table)." DROP CONSTRAINT ".$command->name; <ide> } <ide> <ide> /**
1
PHP
PHP
make view factory macroable
12f3b94c564f174b338c8ed089fc1df89aaa64d8
<ide><path>src/Illuminate/View/Factory.php <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use InvalidArgumentException; <add>use Illuminate\Support\Traits\Macroable; <ide> use Illuminate\Contracts\Events\Dispatcher; <ide> use Illuminate\Contracts\Support\Arrayable; <ide> use Illuminate\View\Engines\EngineResolver; <ide> <ide> class Factory implements FactoryContract <ide> { <del> use Concerns\ManagesComponents, <add> use Macroable, <add> Concerns\ManagesComponents, <ide> Concerns\ManagesEvents, <ide> Concerns\ManagesLayouts, <ide> Concerns\ManagesLoops, <ide><path>tests/View/ViewFactoryTest.php <ide> public function testIncrementingLoopIndicesOfUncountable() <ide> $this->assertNull($factory->getLoopStack()[0]['last']); <ide> } <ide> <add> public function testMacro() <add> { <add> $factory = $this->getFactory(); <add> $factory->macro('getFoo', function () { <add> return 'Hello World'; <add> }); <add> $this->assertEquals('Hello World', $factory->getFoo()); <add> } <add> <ide> protected function getFactory() <ide> { <ide> return new Factory(
2
Python
Python
remove exception-throwing from the signal handler
23ecf2c5a3b8264cfd102b0212984fbffba54ae2
<ide><path>celery/apps/worker.py <ide> <ide> from celery import VERSION_BANNER, platforms, signals <ide> from celery.app import trace <del>from celery.exceptions import WorkerShutdown, WorkerTerminate <ide> from celery.loaders.app import AppLoader <ide> from celery.platforms import EX_FAILURE, EX_OK, check_privileges, isatty <ide> from celery.utils import static, term <ide> def set_process_status(self, info): <ide> <ide> <ide> def _shutdown_handler(worker, sig='TERM', how='Warm', <del> exc=WorkerShutdown, callback=None, exitcode=EX_OK): <add> callback=None, exitcode=EX_OK): <ide> def _handle_request(*args): <ide> with in_sighandler(): <ide> from celery.worker import state <ide> def _handle_request(*args): <ide> sender=worker.hostname, sig=sig, how=how, <ide> exitcode=exitcode, <ide> ) <del> if active_thread_count() > 1: <del> setattr(state, {'Warm': 'should_stop', <del> 'Cold': 'should_terminate'}[how], exitcode) <del> else: <del> raise exc(exitcode) <add> setattr(state, {'Warm': 'should_stop', <add> 'Cold': 'should_terminate'}[how], exitcode) <ide> _handle_request.__name__ = str(f'worker_{how}') <ide> platforms.signals[sig] = _handle_request <ide> <ide> <ide> if REMAP_SIGTERM == "SIGQUIT": <ide> install_worker_term_handler = partial( <del> _shutdown_handler, sig='SIGTERM', how='Cold', exc=WorkerTerminate, exitcode=EX_FAILURE, <add> _shutdown_handler, sig='SIGTERM', how='Cold', exitcode=EX_FAILURE, <ide> ) <ide> else: <ide> install_worker_term_handler = partial( <del> _shutdown_handler, sig='SIGTERM', how='Warm', exc=WorkerShutdown, <add> _shutdown_handler, sig='SIGTERM', how='Warm', <ide> ) <ide> <ide> if not is_jython: # pragma: no cover <ide> install_worker_term_hard_handler = partial( <del> _shutdown_handler, sig='SIGQUIT', how='Cold', exc=WorkerTerminate, <add> _shutdown_handler, sig='SIGQUIT', how='Cold', <ide> exitcode=EX_FAILURE, <ide> ) <ide> else: # pragma: no cover
1
Python
Python
fix dot_axis api
18f122e1d98458ec60e7ea6473c440dae93ddf6f
<ide><path>keras/layers/core.py <ide> def __init__(self, layers, mode='sum', concat_axis=-1, dot_axes=-1): <ide> raise Exception(mode + " merge takes exactly 2 layers") <ide> shape1 = layers[0].output_shape <ide> shape2 = layers[1].output_shape <add> n1 = len(shape1) <add> n2 = len(shape2) <ide> if mode == 'dot': <ide> if type(dot_axes) == int: <ide> if dot_axes < 0: <del> dot_axes = dot_axes % len(shape1) <del> dot_axes = [range(len(shape1) - dot_axes, len(shape2)), range(1, dot_axes + 1)] <add> dot_axes = [range(dot_axes % n1,n1), range(dot_axes % n2,n2)] <add> else: <add> dot_axes = [range(n1 - dot_axes, n2), range(1, dot_axes + 1)] <ide> for i in range(len(dot_axes[0])): <ide> if shape1[dot_axes[0][i]] != shape2[dot_axes[1][i]]: <ide> raise Exception(" Dot incompatible layers can not be merged using dot mode")
1
Text
Text
fix typo in file name
826f947ce7078a66e93276c8102dd235bb629911
<ide><path>guides/source/classic_to_zeitwerk_howto.md <ide> VAT is an European tax. The file `app/models/vat.rb` defines `VAT` but the autol <ide> <ide> This is the most common kind of discrepancy you may find, it has to do with acronyms. Let's understand why do we get that error message. <ide> <del>The classic autoloader is able to autoload `VAT` because its input is the name of the missing constant, `VAT`, invokes `underscore` on it, which yields `vat`, and looks for a file called `var.rb`. It works. <add>The classic autoloader is able to autoload `VAT` because its input is the name of the missing constant, `VAT`, invokes `underscore` on it, which yields `vat`, and looks for a file called `vat.rb`. It works. <ide> <ide> The input of the new autoloader is the file system. Give the file `vat.rb`, Zeitwerk invokes `camelize` on `vat`, which yields `Vat`, and expects the file to define the constant `Vat`. That is what the error message says. <ide>
1
Go
Go
allow partial name match for `service ls --filter`
1d600ebcb5750c4c93356fae08e562d836ecee45
<ide><path>daemon/cluster/filters.go <ide> func newListServicesFilters(filter filters.Args) (*swarmapi.ListServicesRequest_ <ide> return nil, err <ide> } <ide> return &swarmapi.ListServicesRequest_Filters{ <del> Names: filter.Get("name"), <del> IDPrefixes: filter.Get("id"), <del> Labels: runconfigopts.ConvertKVStringsToMap(filter.Get("label")), <add> NamePrefixes: filter.Get("name"), <add> IDPrefixes: filter.Get("id"), <add> Labels: runconfigopts.ConvertKVStringsToMap(filter.Get("label")), <ide> }, nil <ide> } <ide> <ide><path>integration-cli/docker_cli_swarm_test.go <ide> func (s *DockerSwarmSuite) TestSwarmNodeListHostname(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(strings.Split(out, "\n")[0], checker.Contains, "HOSTNAME") <ide> } <add> <add>// Test case for #24270 <add>func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *check.C) { <add> d := s.AddDaemon(c, true, true) <add> <add> name1 := "redis-cluster-md5" <add> name2 := "redis-cluster" <add> name3 := "other-cluster" <add> out, err := d.Cmd("service", "create", "--name", name1, "busybox", "top") <add> c.Assert(err, checker.IsNil) <add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <add> <add> out, err = d.Cmd("service", "create", "--name", name2, "busybox", "top") <add> c.Assert(err, checker.IsNil) <add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <add> <add> out, err = d.Cmd("service", "create", "--name", name3, "busybox", "top") <add> c.Assert(err, checker.IsNil) <add> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <add> <add> filter1 := "name=redis-cluster-md5" <add> filter2 := "name=redis-cluster" <add> <add> // We search checker.Contains with `name+" "` to prevent prefix only. <add> out, err = d.Cmd("service", "ls", "--filter", filter1) <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, name1+" ") <add> c.Assert(out, checker.Not(checker.Contains), name2+" ") <add> c.Assert(out, checker.Not(checker.Contains), name3+" ") <add> <add> out, err = d.Cmd("service", "ls", "--filter", filter2) <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, name1+" ") <add> c.Assert(out, checker.Contains, name2+" ") <add> c.Assert(out, checker.Not(checker.Contains), name3+" ") <add> <add> out, err = d.Cmd("service", "ls") <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, name1+" ") <add> c.Assert(out, checker.Contains, name2+" ") <add> c.Assert(out, checker.Contains, name3+" ") <add>}
2
Javascript
Javascript
remove extraneous shebang's from bin/*.js scripts
8898e795f89255d637138f6d21d6892b050dffaf
<ide><path>bin/build-for-publishing.js <del>#!/usr/bin/env node <ide> 'use strict'; <ide> /* eslint-env node, es6 */ <ide> <ide><path>bin/publish_to_s3.js <del>#!/usr/bin/env node <ide> <ide> // To invoke this from the commandline you need the following to env vars to exist: <ide> // <ide><path>bin/run-browserstack-tests.js <del>#!/usr/bin/env node <ide> <ide> /* eslint-disable no-console */ <ide> <ide><path>bin/run-tests.js <del>#!/usr/bin/env node <ide> /* globals QUnit */ <ide> /* eslint-disable no-console */ <ide> <ide><path>bin/run-travis-browser-tests.js <del>#!/usr/bin/env node <ide> <ide> /* eslint-disable no-console */ <ide> <ide><path>bin/yarn-link-glimmer.js <del>#!/usr/bin/env node <ide> "use strict"; <ide> const child_process = require("child_process"); <ide> <ide><path>bin/yarn-unlink-glimmer.js <del>#!/usr/bin/env node <ide> "use strict"; <ide> const child_process = require("child_process"); <ide>
7
Go
Go
fix import path
ce35439015e4d2190bd82a3b6dfec98f7a12ac90
<ide><path>integration/container/mounts_linux_test.go <ide> import ( <ide> "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/client" <ide> "github.com/docker/docker/integration-cli/daemon" <del> "github.com/docker/docker/integration/util/request" <add> "github.com/docker/docker/integration/internal/request" <ide> "github.com/docker/docker/pkg/stdcopy" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/gotestyourself/gotestyourself/fs"
1
Javascript
Javascript
get curriculum path relative to tools folder
affff68bca9732350745ca3655a4dd4bf969e34c
<ide><path>curriculum/tools/utils.js <ide> const reorderSteps = () => { <ide> <ide> const curriculumPath = process.env.CALLING_DIR <ide> ? '' <del> : '../../../../../curriculum'; <add> : path.join(__dirname, '../'); <ide> <ide> const projectMetaPath = path.resolve( <ide> curriculumPath,
1
Text
Text
fix links for
fa94eb46041ad309468dbbd29faba2053f402096
<ide><path>docs/getstarted/step_one.md <ide> Docker for Mac is our newest offering for the Mac. It runs as a native Mac appli <ide> <ide> If you have an earlier Mac that doesn't meet the Docker for Mac prerequisites, <a href="https://www.docker.com/products/docker-toolbox" target="_blank">get Docker Toolbox</a> for the Mac. <ide> <del>See [Docker Toolbox Overview](toolbox/overview/) for help on installing Docker with Toolbox. <add>See [Docker Toolbox Overview](/toolbox/overview.md) for help on installing Docker with Toolbox. <ide> <ide> ### Docker for Windows <ide> <ide> Docker for Windows is our newest offering for PCs. It runs as a native Windows a <ide> <ide> If you have an earlier Windows system that doesn't meet the Docker for Windows prerequisites, <a href="https://www.docker.com/products/docker-toolbox" target="_blank">get Docker Toolbox</a>. <ide> <del>See [Docker Toolbox Overview](toolbox/overview/) for help on installing Docker with Toolbox. <add>See [Docker Toolbox Overview](/toolbox/overview.md) for help on installing Docker with Toolbox. <ide> <ide> ### Docker for Linux <ide> Docker Engine runs navitvely on Linux distributions. <ide> <del>For full instructions on getting Docker for various Linux distributions, see [Install Docker Engine](/engine/installation/). <add>For full instructions on getting Docker for various Linux distributions, see [Install Docker Engine](../installation/index.md). <ide> <ide> ## Step 2: Install Docker <ide> <del>* For install instructions for Docker for Mac, see [Getting Started with Docker for Mac](/docker-for-mac/). <add>* For install instructions for Docker for Mac, see [Getting Started with Docker for Mac](/docker-for-mac/index.md). <ide> <del>* For install instructions for Docker for Windows, see [Getting Started with Docker for Windows](/docker-for-windows/). <add>* For install instructions for Docker for Windows, see [Getting Started with Docker for Windows](/docker-for-windows/index.md). <ide> <del>* For install instructions for Docker Toolbox, see [Docker Toolbox Overview](toolbox/overview/). <add>* For install instructions for Docker Toolbox, see [Docker Toolbox Overview](/toolbox/overview.md). <ide> <ide> * For a simple example of installing Docker on Ubuntu Linux so that you can work through this tutorial, see [Installing Docker on Ubuntu Linux (Example)](linux_install_help.md). <ide> <del> For full install instructions for Docker on Linux, see [Install Docker Engine](/engine/installation/) and select the flavor of Linux you want to use. <add> For full install instructions for Docker on Linux, see [Install Docker Engine](../installation/index.md) and select the flavor of Linux you want to use. <ide> <ide> ## Step 3: Verify your installation <ide> <ide> For full instructions on getting Docker for various Linux distributions, see [In <ide> <ide> ## Looking for troubleshooting help? <ide> <del>Typically, the above steps work out-of-the-box, but some scenarios can cause problems. If your `docker run hello-world` didn't work and resulted in errors, check out [Troubleshooting](/tutorials/faqs/troubleshoot.md) for quick fixes to common problems. <add>Typically, the above steps work out-of-the-box, but some scenarios can cause problems. If your `docker run hello-world` didn't work and resulted in errors, check out [Troubleshooting](/toolbox/faqs/troubleshoot.md) for quick fixes to common problems. <ide> <ide> ## Where to go next <ide>
1
PHP
PHP
improve empty property check
094c2a2fe536636310a8e6717029db139ce07619
<ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> protected function _unsetEmptyFields(EntityInterface $entity) <ide> } <ide> } <ide> <del> // Workaround to check the remaining properties <del> $arrayEntity = $entity->toArray(); <add> $translation = $translation->extract($this->_config['fields']); <ide> <ide> // If now, the current locale property is empty, <ide> // unset it completely. <del> if (empty($arrayEntity['_translations'][$locale])) { <add> if (empty(array_filter($translation))) { <ide> unset($entity->get('_translations')[$locale]); <ide> } <ide> }
1
Mixed
Javascript
add filehandle support to read/writestream
0fd121e00c9d5987c20c27a4ee4295da7735d9de
<ide><path>doc/api/fs.md <ide> fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL); <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: <add> - REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/35922 <add> description: The `fd` option accepts FileHandle arguments. <ide> - version: <ide> - v13.6.0 <ide> - v12.17.0 <ide> changes: <ide> * `flags` {string} See [support of file system `flags`][]. **Default:** <ide> `'r'`. <ide> * `encoding` {string} **Default:** `null` <del> * `fd` {integer} **Default:** `null` <add> * `fd` {integer|FileHandle} **Default:** `null` <ide> * `mode` {integer} **Default:** `0o666` <ide> * `autoClose` {boolean} **Default:** `true` <ide> * `emitClose` {boolean} **Default:** `false` <ide> If `options` is a string, then it specifies the encoding. <ide> <!-- YAML <ide> added: v0.1.31 <ide> changes: <add> - version: <add> - REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/35922 <add> description: The `fd` option accepts FileHandle arguments. <ide> - version: <ide> - v13.6.0 <ide> - v12.17.0 <ide> changes: <ide> * `flags` {string} See [support of file system `flags`][]. **Default:** <ide> `'w'`. <ide> * `encoding` {string} **Default:** `'utf8'` <del> * `fd` {integer} **Default:** `null` <add> * `fd` {integer|FileHandle} **Default:** `null` <ide> * `mode` {integer} **Default:** `0o666` <ide> * `autoClose` {boolean} **Default:** `true` <ide> * `emitClose` {boolean} **Default:** `false` <ide> the promise-based API uses the `FileHandle` class in order to help avoid <ide> accidental leaking of unclosed file descriptors after a `Promise` is resolved or <ide> rejected. <ide> <add>#### Event: `'close'` <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>The `'close'` event is emitted when the `FileHandle` and any of its underlying <add>resources (a file descriptor, for example) have been closed. <add> <ide> #### `filehandle.appendFile(data, options)` <ide> <!-- YAML <ide> added: v10.0.0 <ide><path>lib/internal/event_target.js <ide> const { <ide> ArrayFrom, <ide> Boolean, <ide> Error, <add> FunctionPrototypeCall, <ide> NumberIsInteger, <ide> ObjectAssign, <ide> ObjectDefineProperties, <ide> ObjectDefineProperty, <ide> ObjectGetOwnPropertyDescriptor, <add> ObjectGetOwnPropertyDescriptors, <ide> ReflectApply, <ide> SafeMap, <ide> String, <ide> function defineEventHandler(emitter, name) { <ide> enumerable: true <ide> }); <ide> } <add> <add>const EventEmitterMixin = (Superclass) => { <add> class MixedEventEmitter extends Superclass { <add> constructor(...args) { <add> super(...args); <add> FunctionPrototypeCall(EventEmitter, this); <add> } <add> } <add> const protoProps = ObjectGetOwnPropertyDescriptors(EventEmitter.prototype); <add> delete protoProps.constructor; <add> ObjectDefineProperties(MixedEventEmitter.prototype, protoProps); <add> return MixedEventEmitter; <add>}; <add> <ide> module.exports = { <ide> Event, <add> EventEmitterMixin, <ide> EventTarget, <ide> NodeEventTarget, <ide> defineEventHandler, <ide><path>lib/internal/fs/promises.js <ide> const { <ide> } = require('internal/validators'); <ide> const pathModule = require('path'); <ide> const { promisify } = require('internal/util'); <add>const { EventEmitterMixin } = require('internal/event_target'); <ide> <ide> const kHandle = Symbol('kHandle'); <ide> const kFd = Symbol('kFd'); <ide> const kRefs = Symbol('kRefs'); <ide> const kClosePromise = Symbol('kClosePromise'); <ide> const kCloseResolve = Symbol('kCloseResolve'); <ide> const kCloseReject = Symbol('kCloseReject'); <add>const kRef = Symbol('kRef'); <add>const kUnref = Symbol('kUnref'); <ide> <ide> const { kUsePromises } = binding; <ide> const { <ide> const lazyDOMException = hideStackFrames((message, name) => { <ide> return new DOMException(message, name); <ide> }); <ide> <del>class FileHandle extends JSTransferable { <add>class FileHandle extends EventEmitterMixin(JSTransferable) { <ide> constructor(filehandle) { <ide> super(); <ide> this[kHandle] = filehandle; <ide> class FileHandle extends JSTransferable { <ide> ); <ide> } <ide> <add> this.emit('close'); <ide> return this[kClosePromise]; <ide> } <ide> <ide> class FileHandle extends JSTransferable { <ide> this[kHandle] = handle; <ide> this[kFd] = handle.fd; <ide> } <add> <add> [kRef]() { <add> this[kRefs]++; <add> } <add> <add> [kUnref]() { <add> this[kRefs]--; <add> if (this[kRefs] === 0) { <add> this[kFd] = -1; <add> PromisePrototypeThen( <add> this[kHandle].close(), <add> this[kCloseResolve], <add> this[kCloseReject] <add> ); <add> } <add> } <ide> } <ide> <ide> async function fsCall(fn, handle, ...args) { <ide> async function fsCall(fn, handle, ...args) { <ide> } <ide> <ide> try { <del> handle[kRefs]++; <add> handle[kRef](); <ide> return await fn(handle, ...args); <ide> } finally { <del> handle[kRefs]--; <del> if (handle[kRefs] === 0) { <del> handle[kFd] = -1; <del> PromisePrototypeThen( <del> handle[kHandle].close(), <del> handle[kCloseResolve], <del> handle[kCloseReject] <del> ); <del> } <add> handle[kUnref](); <ide> } <ide> } <ide> <ide> module.exports = { <ide> readFile, <ide> }, <ide> <del> FileHandle <add> FileHandle, <add> kRef, <add> kUnref, <ide> }; <ide><path>lib/internal/fs/streams.js <ide> <ide> const { <ide> Array, <add> FunctionPrototypeBind, <ide> MathMin, <ide> ObjectDefineProperty, <ide> ObjectSetPrototypeOf, <add> PromisePrototypeThen, <ide> ReflectApply, <ide> Symbol, <ide> } = primordials; <ide> <ide> const { <ide> ERR_INVALID_ARG_TYPE, <del> ERR_OUT_OF_RANGE <add> ERR_OUT_OF_RANGE, <add> ERR_METHOD_NOT_IMPLEMENTED, <ide> } = require('internal/errors').codes; <ide> const { deprecate } = require('internal/util'); <ide> const { validateInteger } = require('internal/validators'); <ide> const { errorOrDestroy } = require('internal/streams/destroy'); <ide> const fs = require('fs'); <add>const { kRef, kUnref, FileHandle } = require('internal/fs/promises'); <ide> const { Buffer } = require('buffer'); <ide> const { <ide> copyObject, <ide> const kIoDone = Symbol('kIoDone'); <ide> const kIsPerformingIO = Symbol('kIsPerformingIO'); <ide> <ide> const kFs = Symbol('kFs'); <add>const kHandle = Symbol('kHandle'); <ide> <ide> function _construct(callback) { <ide> const stream = this; <ide> function _construct(callback) { <ide> } <ide> } <ide> <add>// This generates an fs operations structure for a FileHandle <add>const FileHandleOperations = (handle) => { <add> return { <add> open: (path, flags, mode, cb) => { <add> throw new ERR_METHOD_NOT_IMPLEMENTED('open()'); <add> }, <add> close: (fd, cb) => { <add> handle[kUnref](); <add> PromisePrototypeThen(handle.close(), <add> () => cb(), cb); <add> }, <add> read: (fd, buf, offset, length, pos, cb) => { <add> PromisePrototypeThen(handle.read(buf, offset, length, pos), <add> (r) => cb(null, r.bytesRead, r.buffer), <add> (err) => cb(err, 0, buf)); <add> }, <add> write: (fd, buf, offset, length, pos, cb) => { <add> PromisePrototypeThen(handle.write(buf, offset, length, pos), <add> (r) => cb(null, r.bytesWritten, r.buffer), <add> (err) => cb(err, 0, buf)); <add> }, <add> writev: (fd, buffers, pos, cb) => { <add> PromisePrototypeThen(handle.writev(buffers, pos), <add> (r) => cb(null, r.bytesWritten, r.buffers), <add> (err) => cb(err, 0, buffers)); <add> } <add> }; <add>}; <add> <ide> function close(stream, err, cb) { <ide> if (!stream.fd) { <ide> // TODO(ronag) <ide> function close(stream, err, cb) { <ide> } <ide> } <ide> <add>function importFd(stream, options) { <add> stream.fd = null; <add> if (options.fd) { <add> if (typeof options.fd === 'number') { <add> // When fd is a raw descriptor, we must keep our fingers crossed <add> // that the descriptor won't get closed, or worse, replaced with <add> // another one <add> // https://github.com/nodejs/node/issues/35862 <add> stream.fd = options.fd; <add> } else if (typeof options.fd === 'object' && <add> options.fd instanceof FileHandle) { <add> // When fd is a FileHandle we can listen for 'close' events <add> if (options.fs) <add> // FileHandle is not supported with custom fs operations <add> throw new ERR_METHOD_NOT_IMPLEMENTED('FileHandle with fs'); <add> stream[kHandle] = options.fd; <add> stream.fd = options.fd.fd; <add> stream[kFs] = FileHandleOperations(stream[kHandle]); <add> stream[kHandle][kRef](); <add> options.fd.on('close', FunctionPrototypeBind(stream.close, stream)); <add> } else <add> throw ERR_INVALID_ARG_TYPE('options.fd', <add> ['number', 'FileHandle'], options.fd); <add> } <add>} <add> <ide> function ReadStream(path, options) { <ide> if (!(this instanceof ReadStream)) <ide> return new ReadStream(path, options); <ide> function ReadStream(path, options) { <ide> <ide> // Path will be ignored when fd is specified, so it can be falsy <ide> this.path = toPathIfFileURL(path); <del> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'r' : options.flags; <ide> this.mode = options.mode === undefined ? 0o666 : options.mode; <ide> <add> importFd(this, options); <add> <ide> this.start = options.start; <ide> this.end = options.end; <ide> this.pos = undefined; <ide> function WriteStream(path, options) { <ide> <ide> // Path will be ignored when fd is specified, so it can be falsy <ide> this.path = toPathIfFileURL(path); <del> this.fd = options.fd === undefined ? null : options.fd; <ide> this.flags = options.flags === undefined ? 'w' : options.flags; <ide> this.mode = options.mode === undefined ? 0o666 : options.mode; <ide> <add> importFd(this, options); <add> <ide> this.start = options.start; <ide> this.pos = undefined; <ide> this.bytesWritten = 0; <ide><path>test/parallel/test-fs-promises-file-handle-read-worker.js <add>'use strict'; <add>const common = require('../common'); <add>const fs = require('fs'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const tmpdir = require('../common/tmpdir'); <add>const file = path.join(tmpdir.path, 'read_stream_filehandle_worker.txt'); <add>const input = 'hello world'; <add>const { Worker, isMainThread, workerData } = require('worker_threads'); <add> <add>if (isMainThread || !workerData) { <add> tmpdir.refresh(); <add> fs.writeFileSync(file, input); <add> <add> fs.promises.open(file, 'r').then((handle) => { <add> handle.on('close', common.mustNotCall()); <add> new Worker(__filename, { <add> workerData: { handle }, <add> transferList: [handle] <add> }); <add> }); <add> fs.promises.open(file, 'r').then((handle) => { <add> fs.createReadStream(null, { fd: handle }); <add> assert.throws(() => { <add> new Worker(__filename, { <add> workerData: { handle }, <add> transferList: [handle] <add> }); <add> }, { <add> code: 25, <add> }); <add> }); <add>} else { <add> let output = ''; <add> <add> const handle = workerData.handle; <add> handle.on('close', common.mustCall()); <add> const stream = fs.createReadStream(null, { fd: handle }); <add> <add> stream.on('data', common.mustCallAtLeast((data) => { <add> output += data; <add> })); <add> <add> stream.on('end', common.mustCall(() => { <add> handle.close(); <add> assert.strictEqual(output, input); <add> })); <add> <add> stream.on('close', common.mustCall()); <add>} <ide><path>test/parallel/test-fs-promises-file-handle-read.js <ide> async function read(fileHandle, buffer, offset, length, position) { <ide> fileHandle.read(buffer, offset, length, position); <ide> } <ide> <del>async function validateRead() { <del> const filePath = path.resolve(tmpDir, 'tmp-read-file.txt'); <del> const fileHandle = await open(filePath, 'w+'); <del> const buffer = Buffer.from('Hello world', 'utf8'); <add>async function validateRead(data, file) { <add> const filePath = path.resolve(tmpDir, file); <add> const buffer = Buffer.from(data, 'utf8'); <ide> <ide> const fd = fs.openSync(filePath, 'w+'); <del> fs.writeSync(fd, buffer, 0, buffer.length); <del> fs.closeSync(fd); <del> const readAsyncHandle = await read(fileHandle, Buffer.alloc(11), 0, 11, 0); <del> assert.deepStrictEqual(buffer.length, readAsyncHandle.bytesRead); <del> assert.deepStrictEqual(buffer, readAsyncHandle.buffer); <del> <del> await fileHandle.close(); <del>} <del> <del>async function validateEmptyRead() { <del> const filePath = path.resolve(tmpDir, 'tmp-read-empty-file.txt'); <ide> const fileHandle = await open(filePath, 'w+'); <del> const buffer = Buffer.from('', 'utf8'); <add> const streamFileHandle = await open(filePath, 'w+'); <ide> <del> const fd = fs.openSync(filePath, 'w+'); <ide> fs.writeSync(fd, buffer, 0, buffer.length); <ide> fs.closeSync(fd); <del> const readAsyncHandle = await read(fileHandle, Buffer.alloc(11), 0, 11, 0); <del> assert.deepStrictEqual(buffer.length, readAsyncHandle.bytesRead); <ide> <add> fileHandle.on('close', common.mustCall()); <add> const readAsyncHandle = await read(fileHandle, Buffer.alloc(11), 0, 11, 0); <add> assert.deepStrictEqual(data.length, readAsyncHandle.bytesRead); <add> if (data.length) <add> assert.deepStrictEqual(buffer, readAsyncHandle.buffer); <ide> await fileHandle.close(); <add> <add> const stream = fs.createReadStream(null, { fd: streamFileHandle }); <add> let streamData = Buffer.alloc(0); <add> for await (const chunk of stream) <add> streamData = Buffer.from(chunk); <add> assert.deepStrictEqual(buffer, streamData); <add> if (data.length) <add> assert.deepStrictEqual(streamData, readAsyncHandle.buffer); <add> await streamFileHandle.close(); <ide> } <ide> <ide> async function validateLargeRead() { <ide> let useConf = false; <ide> tmpdir.refresh(); <ide> useConf = value; <ide> <del> await validateRead() <del> .then(validateEmptyRead) <del> .then(validateLargeRead) <del> .then(common.mustCall()); <add> await validateRead('Hello world', 'tmp-read-file.txt') <add> .then(validateRead('', 'tmp-read-empty-file.txt')) <add> .then(validateLargeRead) <add> .then(common.mustCall()); <ide> } <del>}); <add>})().then(common.mustCall()); <ide><path>test/parallel/test-fs-read-stream-file-handle.js <add>'use strict'; <add>const common = require('../common'); <add>const fs = require('fs'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const tmpdir = require('../common/tmpdir'); <add>const file = path.join(tmpdir.path, 'read_stream_filehandle_test.txt'); <add>const input = 'hello world'; <add> <add>let output = ''; <add>tmpdir.refresh(); <add>fs.writeFileSync(file, input); <add> <add>fs.promises.open(file, 'r').then(common.mustCall((handle) => { <add> handle.on('close', common.mustCall()); <add> const stream = fs.createReadStream(null, { fd: handle }); <add> <add> stream.on('data', common.mustCallAtLeast((data) => { <add> output += data; <add> })); <add> <add> stream.on('end', common.mustCall(() => { <add> assert.strictEqual(output, input); <add> })); <add> <add> stream.on('close', common.mustCall()); <add>})); <add> <add>fs.promises.open(file, 'r').then(common.mustCall((handle) => { <add> handle.on('close', common.mustCall()); <add> const stream = fs.createReadStream(null, { fd: handle }); <add> stream.on('data', common.mustNotCall()); <add> stream.on('close', common.mustCall()); <add> <add> handle.close(); <add>})); <add> <add>fs.promises.open(file, 'r').then(common.mustCall((handle) => { <add> handle.on('close', common.mustCall()); <add> const stream = fs.createReadStream(null, { fd: handle }); <add> stream.on('close', common.mustCall()); <add> <add> stream.on('data', common.mustCall(() => { <add> handle.close(); <add> })); <add>})); <add> <add>fs.promises.open(file, 'r').then(common.mustCall((handle) => { <add> handle.on('close', common.mustCall()); <add> const stream = fs.createReadStream(null, { fd: handle }); <add> stream.on('close', common.mustCall()); <add> <add> stream.close(); <add>})); <add> <add>fs.promises.open(file, 'r').then(common.mustCall((handle) => { <add> assert.throws(() => { <add> fs.createReadStream(null, { fd: handle, fs }); <add> }, { <add> code: 'ERR_METHOD_NOT_IMPLEMENTED', <add> name: 'Error', <add> message: 'The FileHandle with fs method is not implemented' <add> }); <add> handle.close(); <add>})); <ide><path>test/parallel/test-fs-write-stream-file-handle.js <add>'use strict'; <add>const common = require('../common'); <add>const fs = require('fs'); <add>const path = require('path'); <add>const assert = require('assert'); <add>const tmpdir = require('../common/tmpdir'); <add>const file = path.join(tmpdir.path, 'write_stream_filehandle_test.txt'); <add>const input = 'hello world'; <add> <add>tmpdir.refresh(); <add> <add>fs.promises.open(file, 'w+').then(common.mustCall((handle) => { <add> handle.on('close', common.mustCall()); <add> const stream = fs.createWriteStream(null, { fd: handle }); <add> <add> stream.end(input); <add> stream.on('close', common.mustCall(() => { <add> const output = fs.readFileSync(file, 'utf-8'); <add> assert.strictEqual(output, input); <add> })); <add>}));
8
PHP
PHP
handle dns failure
bdd8b9ca66fd43b9085b633651ddeddc00504e71
<ide><path>src/Http/Client/Adapter/Curl.php <ide> use Cake\Http\Client\AdapterInterface; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <add>use Cake\Http\Exception\HttpException; <ide> <ide> /** <ide> * Implements sending Cake\Http\Client\Request <ide> public function send(Request $request, array $options) <ide> curl_setopt_array($ch, $options); <ide> <ide> $body = $this->exec($ch); <add> if ($body === false) { <add> $errorCode = curl_errno($ch); <add> $error = curl_error($ch); <add> curl_close($ch); <add> throw new HttpException("cURL Error ({$errorCode}) {$error}"); <add> } <ide> <del> // TODO check for timeouts. <ide> $responses = $this->createResponse($ch, $body); <ide> curl_close($ch); <ide>
1
Python
Python
clarify docstrings for updated dbapihook
a158fbb6bde07cd20003680a4cf5e7811b9eda98
<ide><path>airflow/providers/common/sql/hooks/sql.py <ide> def return_single_query_results(sql: str | Iterable[str], return_last: bool, spl <ide> Determines when results of single query only should be returned. <ide> <ide> For compatibility reasons, the behaviour of the DBAPIHook is somewhat confusing. <del> In cases, when multiple queries are run, the return values will be an iterable (list) of results <del> - one for each query. However, in certain cases, when single query is run - the results will be just <del> the results of that single query without wrapping the results in a list. <add> In some cases, when multiple queries are run, the return value will be an iterable (list) of results <add> -- one for each query. However, in other cases, when single query is run, the return value will be just <add> the result of that single query without wrapping the results in a list. <ide> <del> The cases when single query results are returned without wrapping them in a list are when: <add> The cases when single query results are returned without wrapping them in a list are as follows: <ide> <del> a) sql is string and last_statement is True (regardless what split_statement value is) <del> b) sql is string and split_statement is False <add> a) sql is string and ``return_last`` is True (regardless what ``split_statements`` value is) <add> b) sql is string and ``split_statements`` is False <ide> <del> In all other cases, the results are wrapped in a list, even if there is only one statement to process: <add> In all other cases, the results are wrapped in a list, even if there is only one statement to process. <add> In particular, the return value will be a list of query results in the following circumstances: <ide> <del> a) always when sql is an iterable of string statements (regardless what last_statement value is) <del> b) when sql is string, split_statement is True and last_statement is False <add> a) when ``sql`` is an iterable of string statements (regardless what ``return_last`` value is) <add> b) when ``sql`` is string, ``split_statements`` is True and ``return_last`` is False <ide> <ide> :param sql: sql to run (either string or list of strings) <ide> :param return_last: whether last statement output should only be returned <ide> def run( <ide> where each element in the list are results of one of the queries (typically list of list of rows :D) <ide> <ide> For compatibility reasons, the behaviour of the DBAPIHook is somewhat confusing. <del> In cases, when multiple queries are run, the return values will be an iterable (list) of results <del> - one for each query. However, in certain cases, when single query is run - the results will be just <del> the results of that query without wrapping the results in a list. <add> In some cases, when multiple queries are run, the return value will be an iterable (list) of results <add> -- one for each query. However, in other cases, when single query is run, the return value will <add> be the result of that single query without wrapping the results in a list. <ide> <del> The cases when single query results are returned without wrapping them in a list are when: <add> The cases when single query results are returned without wrapping them in a list are as follows: <ide> <del> a) sql is string and last_statement is True (regardless what split_statement value is) <del> b) sql is string and split_statement is False <add> a) sql is string and ``return_last`` is True (regardless what ``split_statements`` value is) <add> b) sql is string and ``split_statements`` is False <ide> <del> In all other cases, the results are wrapped in a list, even if there is only one statement to process: <add> In all other cases, the results are wrapped in a list, even if there is only one statement to process. <add> In particular, the return value will be a list of query results in the following circumstances: <ide> <del> a) always when sql is an iterable of string statements (regardless what last_statement value is) <del> b) when sql is string, split_statement is True and last_statement is False <add> a) when ``sql`` is an iterable of string statements (regardless what ``return_last`` value is) <add> b) when ``sql`` is string, ``split_statements`` is True and ``return_last`` is False <ide> <add> After ``run`` is called, you may access the following properties on the hook object: <ide> <del> In any of those cases, however you can access the following properties of the Hook after running it: <add> * ``descriptions``: an array of cursor descriptions. If ``return_last`` is True, this will be <add> a one-element array containing the cursor ``description`` for the last statement. <add> Otherwise, it will contain the cursor description for each statement executed. <add> * ``last_description``: the description for the last statement executed <ide> <del> * descriptions - has an array of cursor descriptions - each statement executed contain the list <del> of descriptions executed. If ``return_last`` is used, this is always a one-element array <del> * last_description - description of the last statement executed <del> <del> Note that return value from the hook will ONLY be actually returned when handler is provided. Setting <del> the ``handler`` to None, results in this method returning None. <add> Note that query result will ONLY be actually returned when a handler is provided; if <add> ``handler`` is None, this method will return None. <ide> <ide> Handler is a way to process the rows from cursor (Iterator) into a value that is suitable to be <del> returned to XCom and generally fit in memory. As an optimization, handler is usually not executed <del> by the SQLExecuteQuery operator if `do_xcom_push` is not specified. <add> returned to XCom and generally fit in memory. <ide> <ide> You can use pre-defined handles (`fetch_all_handler``, ''fetch_one_handler``) or implement your <ide> own handler. <ide> def run( <ide> :param handler: The result handler which is called with the result of each statement. <ide> :param split_statements: Whether to split a single SQL string into statements and run separately <ide> :param return_last: Whether to return result for only last statement or for all after split <del> :return: return only result of the ALL SQL expressions if handler was provided. <add> :return: if handler provided, returns query results (may be list of results depending on params) <ide> """ <ide> self.descriptions = [] <ide>
1
Javascript
Javascript
add test for selection.data
354765c3092f144cdb9b2b8edf481043d9773969
<ide><path>test/core/selection-append-test.js <ide> suite.addBatch({ <ide> } <ide> }); <ide> <add>// TODO enter().append() <add> <ide> suite.export(module); <ide><path>test/core/selection-data-test.js <add>require("../env"); <add>require("../../d3"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("selection.data"); <add> <add>suite.addBatch({ <add> "select(body)": { <add> topic: function() { <add> return d3.select("body").html(""); <add> }, <add> "assigns data as an array": function(body) { <add> var data = new Object(); <add> body.data([data]); <add> assert.strictEqual(document.body.__data__, data); <add> }, <add> "assigns data as a function": function(body) { <add> var data = new Object(); <add> body.data(function() { return [data]; }); <add> assert.strictEqual(document.body.__data__, data); <add> }, <add> "stores data in the DOM": function(body) { <add> var expected = new Object(), actual; <add> document.body.__data__ = expected; <add> body.each(function(d) { actual = d; }); <add> assert.strictEqual(actual, expected); <add> } <add> } <add>}); <add> <add>suite.addBatch({ <add> "selectAll(div)": { <add> topic: function() { <add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div"); <add> }, <add> "assigns data as an array": function(div) { <add> var a = new Object(), b = new Object(); <add> div.data([a, b]); <add> assert.strictEqual(div[0][0].__data__, a); <add> assert.strictEqual(div[0][1].__data__, b); <add> }, <add> "assigns data as a function": function(div) { <add> var a = new Object(), b = new Object(); <add> div.data(function() { return [a, b]; }); <add> assert.strictEqual(div[0][0].__data__, a); <add> assert.strictEqual(div[0][1].__data__, b); <add> }, <add> "stores data in the DOM": function(div) { <add> var a = new Object(), b = new Object(), actual = []; <add> div[0][0].__data__ = a; <add> div[0][1].__data__ = b; <add> div.each(function(d) { actual.push(d); }); <add> assert.deepEqual(actual, [a, b]); <add> } <add> } <add>}); <add> <add>suite.addBatch({ <add> "selectAll(div).selectAll(span)": { <add> topic: function() { <add> return d3.select("body").html("").selectAll("div") <add> .data(d3.range(2)) <add> .enter().append("div").selectAll("span") <add> .data(d3.range(2)) <add> .enter().append("span"); <add> }, <add> "assigns data as an array": function(span) { <add> var a = new Object(), b = new Object(); <add> span.data([a, b]); <add> assert.strictEqual(span[0][0].__data__, a); <add> assert.strictEqual(span[0][1].__data__, b); <add> assert.strictEqual(span[1][0].__data__, a); <add> assert.strictEqual(span[1][1].__data__, b); <add> }, <add> "assigns data as a function": function(span) { <add> var a = new Object(), b = new Object(), c = new Object(), d = new Object(); <add> span.data(function(z, i) { return i ? [c, d] : [a, b]; }); <add> assert.strictEqual(span[0][0].__data__, a); <add> assert.strictEqual(span[0][1].__data__, b); <add> assert.strictEqual(span[1][0].__data__, c); <add> assert.strictEqual(span[1][1].__data__, d); <add> }, <add> "evaluates the function once per group": function(span) { <add> var count = 0; <add> span.data(function() { ++count; return [0, 1]; }); <add> assert.equal(count, 2); <add> }, <add> "defines an update selection for updating data": function(span) { <add> var update = span.data(d3.range(4)); <add> assert.equal(update.length, 2); <add> assert.equal(update[0].length, 4); <add> assert.equal(update[1].length, 4); <add> assert.domEqual(update[0][0], span[0][0]); <add> assert.domEqual(update[0][1], span[0][1]); <add> assert.domNull(update[0][2]); <add> assert.domNull(update[0][3]); <add> assert.domEqual(update[1][0], span[1][0]); <add> assert.domEqual(update[1][1], span[1][1]); <add> assert.domNull(update[1][2]); <add> assert.domNull(update[1][3]); <add> }, <add> "defines an enter selection for entering data": function(span) { <add> var enter = span.data(d3.range(4)).enter(); <add> assert.equal(enter.length, 2); <add> assert.equal(enter[0].length, 4); <add> assert.equal(enter[1].length, 4); <add> assert.domNull(enter[0][0]); <add> assert.domNull(enter[0][1]); <add> assert.deepEqual(enter[0][2], {__data__: 2}); <add> assert.deepEqual(enter[0][3], {__data__: 3}); <add> assert.domNull(enter[1][0]); <add> assert.domNull(enter[1][1]); <add> assert.deepEqual(enter[1][2], {__data__: 2}); <add> assert.deepEqual(enter[1][3], {__data__: 3}); <add> }, <add> "defines an exit selection for exiting data": function(span) { <add> var exit = span.data(d3.range(1)).exit(); <add> assert.equal(exit.length, 2); <add> assert.equal(exit[0].length, 2); <add> assert.equal(exit[1].length, 2); <add> assert.domNull(exit[0][0]); <add> assert.domEqual(exit[0][1], span[0][1]); <add> assert.domNull(exit[1][0]); <add> assert.domEqual(exit[1][1], span[1][1]); <add> }, <add> "observes the specified key function": function(span) { <add> var update = span.data([1, 2], Number); <add> assert.equal(update.length, 2); <add> assert.equal(update[0].length, 2); <add> assert.equal(update[1].length, 2); <add> assert.domEqual(update[0][0], span[0][1]); <add> assert.domNull(update[0][1]); <add> assert.domEqual(update[1][0], span[1][1]); <add> assert.domNull(update[1][1]); <add> <add> var enter = update.enter(); <add> assert.equal(enter.length, 2); <add> assert.equal(enter[0].length, 2); <add> assert.equal(enter[1].length, 2); <add> assert.domNull(enter[0][0]); <add> assert.deepEqual(enter[0][1], {__data__: 2}); <add> assert.domNull(enter[1][0]); <add> assert.deepEqual(enter[1][1], {__data__: 2}); <add> <add> var exit = update.exit(); <add> assert.equal(exit.length, 2); <add> assert.equal(exit[0].length, 2); <add> assert.equal(exit[1].length, 2); <add> assert.domEqual(exit[0][0], span[0][0]); <add> assert.domNull(exit[0][1]); <add> assert.domEqual(exit[1][0], span[1][0]); <add> assert.domNull(exit[1][1]); <add> } <add> } <add>}); <add> <add>suite.export(module); <ide><path>test/core/selection-sort-test.js <ide> suite.addBatch({ <ide> .data([1, 2, 10, 20]) <ide> .enter().append("div").selectAll("span") <ide> .data(function(d) { return [20 + d, 2 + d, 10, 1]; }) <del> .enter().append("span") <del> .attr("class", String); <add> .enter().append("span"); <ide> }, <ide> "sorts elements by natural order": function(span) { <ide> span.sort();
3
Text
Text
fix typo in vocab.md table
afd7a2476d2491af864d0723bff96191ea61b429
<ide><path>website/docs/api/vocab.md <ide> Load state from a binary string. <ide> > assert type(PERSON) == int <ide> > ``` <ide> <del>| Name | Description | <del>| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <del>| `strings` | A table managing the string-to-int mapping. ~~StringStore~~ | <del>| `vectors` | A table associating word IDs to word vectors. ~~Vectors~~ | <del>| `vectors_length` | Number of dimensions for each word vector. ~~int~~ | <del>| `lookups` | The available lookup tables in this vocab. ~~Lookups~~ | <del>| `writing_system` | A dict with information about the language's writing system. ~~Dict[str, Any]~~ | <del>| `get_noun_chunks` <Tag variant="new">3.0</Tag> | A function that yields base noun phrases used for [`Doc.noun_chunks`](/ap/doc#noun_chunks). ~~Optional[Callable[[Union[Doc, Span], Iterator[Tuple[int, int, int]]]]]~~ | <add>| Name | Description | <add>| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <add>| `strings` | A table managing the string-to-int mapping. ~~StringStore~~ | <add>| `vectors` | A table associating word IDs to word vectors. ~~Vectors~~ | <add>| `vectors_length` | Number of dimensions for each word vector. ~~int~~ | <add>| `lookups` | The available lookup tables in this vocab. ~~Lookups~~ | <add>| `writing_system` | A dict with information about the language's writing system. ~~Dict[str, Any]~~ | <add>| `get_noun_chunks` <Tag variant="new">3.0</Tag> | A function that yields base noun phrases used for [`Doc.noun_chunks`](/api/doc#noun_chunks). ~~Optional[Callable[[Union[Doc, Span], Iterator[Tuple[int, int, int]]]]]~~ | <ide> <ide> ## Serialization fields {#serialization-fields} <ide>
1
Python
Python
enable new theme on rtd
8f8beec1e2633c413f939e2c30531b88913005da
<ide><path>docs/conf.py <ide> <ide> if on_rtd: <ide> html_theme = 'default' <add> RTD_NEW_THEME = True <ide> else: <ide> html_theme = 'nature' <ide>
1
Javascript
Javascript
remove error messages in crypto-binary test
24d72944da402dd17542f3c958d0f033c9e20a3a
<ide><path>test/parallel/test-crypto-binary-default.js <ide> if (!common.hasFipsCrypto) { <ide> const a0 = crypto.createHash('md5').update('Test123').digest('latin1'); <ide> assert.strictEqual( <ide> a0, <del> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c', <del> 'Test MD5 as latin1' <add> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c' <ide> ); <ide> } <ide> <del>assert.strictEqual(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); <add>assert.strictEqual(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2'); <ide> <del>assert.strictEqual(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', <del> 'Test SHA256 as base64'); <add>assert.strictEqual(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4='); <ide> <ide> assert.strictEqual( <ide> a3, <ide> assert.strictEqual( <ide> <ide> assert.deepStrictEqual( <ide> a4, <del> Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), <del> 'Test SHA1' <add> Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex') <ide> ); <ide> <ide> // Test multiple updates to same hash <ide> const h1 = crypto.createHash('sha1').update('Test123').digest('hex'); <ide> const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); <del>assert.strictEqual(h1, h2, 'multipled updates'); <add>assert.strictEqual(h1, h2); <ide> <ide> // Test hashing for binary files <ide> const fn = fixtures.path('sample.png'); <ide> fileStream.on('data', function(data) { <ide> fileStream.on('close', common.mustCall(function() { <ide> assert.strictEqual( <ide> sha1Hash.digest('hex'), <del> '22723e553129a336ad96e10f6aecdf0f45e4149e', <del> 'Test SHA1 of sample.png' <add> '22723e553129a336ad96e10f6aecdf0f45e4149e' <ide> ); <ide> })); <ide> <ide> const s1Verified = crypto.createVerify('SHA1') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s1, 'base64'); <del>assert.strictEqual(s1Verified, true, 'sign and verify (base 64)'); <add>assert.strictEqual(s1Verified, true); <ide> <ide> const s2 = crypto.createSign('SHA256') <ide> .update('Test123') <ide> const s2Verified = crypto.createVerify('SHA256') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s2); // binary <del>assert.strictEqual(s2Verified, true, 'sign and verify (binary)'); <add>assert.strictEqual(s2Verified, true); <ide> <ide> const s3 = crypto.createSign('SHA1') <ide> .update('Test123') <ide> const s3Verified = crypto.createVerify('SHA1') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s3); <del>assert.strictEqual(s3Verified, true, 'sign and verify (buffer)'); <add>assert.strictEqual(s3Verified, true); <ide> <ide> <ide> function testCipher1(key) { <ide> function testCipher1(key) { <ide> let txt = decipher.update(ciph, 'hex', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <del> assert.strictEqual(txt, plaintext, 'encryption and decryption'); <add> assert.strictEqual(txt, plaintext); <ide> } <ide> <ide> <ide> function testCipher2(key) { <ide> let txt = decipher.update(ciph, 'base64', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <del> assert.strictEqual(txt, plaintext, 'encryption and decryption with Base64'); <add> assert.strictEqual(txt, plaintext); <ide> } <ide> <ide> <ide> function testCipher3(key, iv) { <ide> let txt = decipher.update(ciph, 'hex', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <del> assert.strictEqual(txt, plaintext, <del> 'encryption and decryption with key and iv'); <add> assert.strictEqual(txt, plaintext); <ide> } <ide> <ide> <ide> function testCipher4(key, iv) { <ide> let txt = decipher.update(ciph, 'buffer', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <del> assert.strictEqual(txt, plaintext, <del> 'encryption and decryption with key and iv'); <add> assert.strictEqual(txt, plaintext); <ide> } <ide> <ide> <ide> function testCipher5(key, iv) { <ide> let txt = decipher.update(ciph, 'buffer', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <del> assert.strictEqual(txt, plaintext, <del> 'encryption and decryption with key'); <add> assert.strictEqual(txt, plaintext); <ide> } <ide> <ide> if (!common.hasFipsCrypto) {
1
Python
Python
fix grammatical error in variable.get docstring
fe5aba2f1985fe6b546ac28478398a35dbb3ef26
<ide><path>airflow/models/variable.py <ide> def get( <ide> Gets a value for an Airflow Variable Key <ide> <ide> :param key: Variable Key <del> :param default_var: Default value of the Variable if the Variable doesn't exists <add> :param default_var: Default value of the Variable if the Variable doesn't exist <ide> :param deserialize_json: Deserialize the value to a Python dict <ide> """ <ide> var_val = Variable.get_variable_from_secrets(key=key)
1
PHP
PHP
show php version in shell welcome message
75de672e47d43bd51b61879031d2c36e2f3821de
<ide><path>src/Console/Shell.php <ide> protected function _welcome() <ide> $this->hr(); <ide> $this->out(sprintf('App : %s', APP_DIR)); <ide> $this->out(sprintf('Path: %s', APP)); <add> $this->out(sprintf('PHP : %s', phpversion())); <ide> $this->hr(); <ide> } <ide>
1
Javascript
Javascript
add internal assert.fail()
ce65034e63413c616b0b938e0a537c479cf51c7a
<ide><path>lib/internal/assert.js <ide> function assert(value, message) { <ide> } <ide> } <ide> <add>function fail(message) { <add> require('assert').fail(message); <add>} <add> <add>assert.fail = fail; <add> <ide> module.exports = assert; <ide><path>test/parallel/test-internal-assert.js <ide> internalAssert(true, 'fhqwhgads'); <ide> assert.throws(() => { internalAssert(false); }, assert.AssertionError); <ide> assert.throws(() => { internalAssert(false, 'fhqwhgads'); }, <ide> { code: 'ERR_ASSERTION', message: 'fhqwhgads' }); <add>assert.throws(() => { internalAssert.fail('fhqwhgads'); }, <add> { code: 'ERR_ASSERTION', message: 'fhqwhgads' });
2
Mixed
Javascript
add taskgroup tooltip to graph view
8745fb903069ac6174134d52513584538a2b8657
<ide><path>airflow/www/static/js/graph.js <ide> function groupTooltip(node, tis) { <ide> }); <ide> <ide> const groupDuration = convertSecsToHumanReadable(moment(maxEnd).diff(minStart, 'second')); <add> const tooltipText = node.tooltip ? `<p>${node.tooltip}</p>` : ''; <ide> <del> let tt = `<strong>Duration:</strong> ${groupDuration} <br><br>`; <add> let tt = ` <add> ${tooltipText} <add> <strong>Duration:</strong> ${groupDuration} <br><br> <add> `; <ide> numMap.forEach((key, val) => { <ide> if (key > 0) { <ide> tt += `<strong>${escapeHtml(val)}:</strong> ${key} <br>`; <ide><path>airflow/www/views.py <ide> def task_group_to_dict(task_group): <ide> 'rx': 5, <ide> 'ry': 5, <ide> 'clusterLabelPos': 'top', <add> 'tooltip': task_group.tooltip, <ide> }, <del> 'tooltip': task_group.tooltip, <ide> 'children': children, <ide> } <ide>
2
Mixed
Ruby
remove deprecated methods at `kernel`
481e49c64f790e46f4aff3ed539ed227d2eb46cb
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> class Astronaut < ActiveRecord::Base <ide> <ide> teardown do <ide> if defined?(@connection) <del> @connection.drop_table "astronauts" if @connection.table_exists? 'astronauts' <add> @connection.drop_table "astronauts" if @connection.table_exists? 'astronauts' <ide> @connection.drop_table "rockets" if @connection.table_exists? 'rockets' <ide> end <ide> end <ide> def test_add_foreign_key_is_reversible <ide> ensure <ide> silence_stream($stdout) { migration.migrate(:down) } <ide> end <add> <add> private <add> <add> def silence_stream(stream) <add> old_stream = stream.dup <add> stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') <add> stream.sync = true <add> yield <add> ensure <add> stream.reopen(old_stream) <add> old_stream.close <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/migration_test.rb <ide> def quietly <ide> end <ide> end <ide> end <add> <add> def silence_stream(stream) <add> old_stream = stream.dup <add> stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') <add> stream.sync = true <add> yield <add> ensure <add> stream.reopen(old_stream) <add> old_stream.close <add> end <ide> end <ide><path>activesupport/CHANGELOG.md <add>* Remove deprecated methods at `Kernel`. <add> <add> `silence_stderr`, `silence_stream`, `capture` and `quietly`. <add> <add> *Rafael Mendonça França* <add> <ide> * Remove deprecated `active_support/core_ext/big_decimal/yaml_conversions` <ide> file. <ide> <ide><path>activesupport/lib/active_support/core_ext/kernel/reporting.rb <ide> def with_warnings(flag) <ide> $VERBOSE = old_verbose <ide> end <ide> <del> # For compatibility <del> def silence_stderr #:nodoc: <del> ActiveSupport::Deprecation.warn( <del> "`#silence_stderr` is deprecated and will be removed in the next release." <del> ) #not thread-safe <del> silence_stream(STDERR) { yield } <del> end <del> <del> # Deprecated : this method is not thread safe <del> # Silences any stream for the duration of the block. <del> # <del> # silence_stream(STDOUT) do <del> # puts 'This will never be seen' <del> # end <del> # <del> # puts 'But this will' <del> # <del> # This method is not thread-safe. <del> def silence_stream(stream) <del> old_stream = stream.dup <del> stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') <del> stream.sync = true <del> yield <del> ensure <del> stream.reopen(old_stream) <del> old_stream.close <del> end <del> <ide> # Blocks and ignores any exception passed as argument if raised within the block. <ide> # <ide> # suppress(ZeroDivisionError) do <ide> def suppress(*exception_classes) <ide> yield <ide> rescue *exception_classes <ide> end <del> <del> # Captures the given stream and returns it: <del> # <del> # stream = capture(:stdout) { puts 'notice' } <del> # stream # => "notice\n" <del> # <del> # stream = capture(:stderr) { warn 'error' } <del> # stream # => "error\n" <del> # <del> # even for subprocesses: <del> # <del> # stream = capture(:stdout) { system('echo notice') } <del> # stream # => "notice\n" <del> # <del> # stream = capture(:stderr) { system('echo error 1>&2') } <del> # stream # => "error\n" <del> def capture(stream) <del> ActiveSupport::Deprecation.warn( <del> "`#capture(stream)` is deprecated and will be removed in the next release." <del> ) #not thread-safe <del> stream = stream.to_s <del> captured_stream = Tempfile.new(stream) <del> stream_io = eval("$#{stream}") <del> origin_stream = stream_io.dup <del> stream_io.reopen(captured_stream) <del> <del> yield <del> <del> stream_io.rewind <del> return captured_stream.read <del> ensure <del> captured_stream.close <del> captured_stream.unlink <del> stream_io.reopen(origin_stream) <del> end <del> alias :silence :capture <del> <del> # Silences both STDOUT and STDERR, even for subprocesses. <del> # <del> # quietly { system 'bundle install' } <del> # <del> # This method is not thread-safe. <del> def quietly <del> ActiveSupport::Deprecation.warn( <del> "`#quietly` is deprecated and will be removed in the next release." <del> ) #not thread-safe <del> silence_stream(STDOUT) do <del> silence_stream(STDERR) do <del> yield <del> end <del> end <del> end <ide> end <ide><path>activesupport/test/core_ext/kernel_test.rb <ide> def test_silence_warnings_verbose_invariant <ide> assert_equal old_verbose, $VERBOSE <ide> end <ide> <del> <ide> def test_enable_warnings <ide> enable_warnings { assert_equal true, $VERBOSE } <ide> assert_equal 1234, enable_warnings { 1234 } <ide> def test_enable_warnings_verbose_invariant <ide> assert_equal old_verbose, $VERBOSE <ide> end <ide> <del> <del> def test_silence_stream <del> old_stream_position = STDOUT.tell <del> silence_stream(STDOUT) { STDOUT.puts 'hello world' } <del> assert_equal old_stream_position, STDOUT.tell <del> rescue Errno::ESPIPE <del> # Skip if we can't stream.tell <del> end <del> <del> def test_silence_stream_closes_file_descriptors <del> stream = StringIO.new <del> dup_stream = StringIO.new <del> stream.stubs(:dup).returns(dup_stream) <del> dup_stream.expects(:close) <del> silence_stream(stream) { stream.puts 'hello world' } <del> end <del> <del> def test_quietly <del> old_stdout_position, old_stderr_position = STDOUT.tell, STDERR.tell <del> assert_deprecated do <del> quietly do <del> puts 'see me, feel me' <del> STDERR.puts 'touch me, heal me' <del> end <del> end <del> assert_equal old_stdout_position, STDOUT.tell <del> assert_equal old_stderr_position, STDERR.tell <del> rescue Errno::ESPIPE <del> # Skip if we can't STDERR.tell <del> end <del> <ide> def test_class_eval <ide> o = Object.new <ide> class << o; @x = 1; end <ide> assert_equal 1, o.class_eval { @x } <ide> end <del> <del> def test_capture <del> assert_deprecated do <del> assert_equal 'STDERR', capture(:stderr) { $stderr.print 'STDERR' } <del> end <del> assert_deprecated do <del> assert_equal 'STDOUT', capture(:stdout) { print 'STDOUT' } <del> end <del> assert_deprecated do <del> assert_equal "STDERR\n", capture(:stderr) { system('echo STDERR 1>&2') } <del> end <del> assert_deprecated do <del> assert_equal "STDOUT\n", capture(:stdout) { system('echo STDOUT') } <del> end <del> end <ide> end <ide> <ide> class KernelSuppressTest < ActiveSupport::TestCase <ide><path>railties/test/generators/generators_test_helper.rb <ide> def quietly <ide> end <ide> end <ide> end <add> <add> def silence_stream(stream) <add> old_stream = stream.dup <add> stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') <add> stream.sync = true <add> yield <add> ensure <add> stream.reopen(old_stream) <add> old_stream.close <add> end <ide> end <ide><path>railties/test/isolation/abstract_unit.rb <ide> def quietly <ide> end <ide> end <ide> end <add> <add> def silence_stream(stream) <add> old_stream = stream.dup <add> stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') <add> stream.sync = true <add> yield <add> ensure <add> stream.reopen(old_stream) <add> old_stream.close <add> end <ide> end <ide> <ide> # Create a scope and build a fixture rails app
7
Text
Text
add 4.5.0 release to eslint rules changelog
59bc52a16c5bdec6de5fc87de4d900ebc20389b2
<ide><path>packages/eslint-plugin-react-hooks/CHANGELOG.md <add>## 4.5.0 <add> <add>* Fix false positive error with large number of branches. ([@scyron6](https://github.com/scyron6) in [#24287](https://github.com/facebook/react/pull/24287)) <add> <ide> ## 4.4.0 <ide> <ide> * No changes, this was an automated release together with React 18.
1
Javascript
Javascript
avoid nexttick when possible
00d176419c538d51af702a55ce480db9b23860a8
<ide><path>lib/util/AsyncQueue.js <ide> class AsyncQueue { <ide> const entry = this._entries.get(key); <ide> if (entry !== undefined) { <ide> if (entry.state === DONE_STATE) { <del> process.nextTick(() => callback(entry.error, entry.result)); <add> if (inHandleResult++ > 3) { <add> process.nextTick(() => callback(entry.error, entry.result)); <add> } else { <add> callback(entry.error, entry.result); <add> } <add> inHandleResult--; <ide> } else if (entry.callbacks === undefined) { <ide> entry.callbacks = [callback]; <ide> } else {
1
Javascript
Javascript
add test for getdisplayname
20462fe9854525cf4f82ecb9e8a74e5bc4a57e9d
<ide><path>test/utils/getDisplayName.spec.js <add>import { expect } from 'chai'; <add>import getDisplayName from '../../src/utils/getDisplayName'; <add> <add>describe('Utils', () => { <add> describe('getDisplayName', () => { <add> <add> it('should ensure a name for the given component', () => { <add> const names = [ <add> { displayName: 'Foo'}, <add> { name: 'Bar' }, <add> {} <add> ].map(getDisplayName); <add> <add> expect(names).to.deep.equal(['Foo', 'Bar', 'Component']); <add> }); <add> }); <add>});
1
Javascript
Javascript
add preference for using tree-sitter parsers
273d708a487408516f011a6db0a7c8c7ccba21f8
<ide><path>spec/grammar-registry-spec.js <ide> const fs = require('fs-plus') <ide> const temp = require('temp').track() <ide> const TextBuffer = require('text-buffer') <ide> const GrammarRegistry = require('../src/grammar-registry') <add>const TreeSitterGrammar = require('../src/tree-sitter-grammar') <add>const FirstMate = require('first-mate') <ide> <ide> describe('GrammarRegistry', () => { <ide> let grammarRegistry <ide> describe('GrammarRegistry', () => { <ide> }) <ide> }) <ide> <add> describe('.grammarForId(languageId)', () => { <add> it('converts the language id to a text-mate language id when `core.useTreeSitterParsers` is false', () => { <add> atom.config.set('core.useTreeSitterParsers', false) <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> <add> const grammar = grammarRegistry.grammarForId('javascript') <add> expect(grammar instanceof FirstMate.Grammar).toBe(true) <add> expect(grammar.scopeName).toBe('source.js') <add> }) <add> <add> it('converts the language id to a tree-sitter language id when `core.useTreeSitterParsers` is true', () => { <add> atom.config.set('core.useTreeSitterParsers', true) <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> <add> const grammar = grammarRegistry.grammarForId('source.js') <add> expect(grammar instanceof TreeSitterGrammar).toBe(true) <add> expect(grammar.id).toBe('javascript') <add> }) <add> }) <add> <ide> describe('.autoAssignLanguageMode(buffer)', () => { <ide> it('assigns to the buffer a language mode based on the best available grammar', () => { <ide> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <ide> describe('GrammarRegistry', () => { <ide> expect(buffer.getLanguageMode().getLanguageId()).toBe('source.c') <ide> }) <ide> <del> it('updates the buffer\'s grammar when a more appropriate grammar is added for its path', async () => { <add> it('updates the buffer\'s grammar when a more appropriate text-mate grammar is added for its path', async () => { <add> atom.config.set('core.useTreeSitterParsers', false) <add> <ide> const buffer = new TextBuffer() <ide> expect(buffer.getLanguageMode().getLanguageId()).toBe(null) <ide> <ide> describe('GrammarRegistry', () => { <ide> <ide> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <ide> expect(buffer.getLanguageMode().getLanguageId()).toBe('source.js') <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> expect(buffer.getLanguageMode().getLanguageId()).toBe('source.js') <add> }) <add> <add> it('updates the buffer\'s grammar when a more appropriate tree-sitter grammar is added for its path', async () => { <add> atom.config.set('core.useTreeSitterParsers', true) <add> <add> const buffer = new TextBuffer() <add> expect(buffer.getLanguageMode().getLanguageId()).toBe(null) <add> <add> buffer.setPath('test.js') <add> grammarRegistry.maintainLanguageMode(buffer) <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> expect(buffer.getLanguageMode().getLanguageId()).toBe('javascript') <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <add> expect(buffer.getLanguageMode().getLanguageId()).toBe('javascript') <ide> }) <ide> <ide> it('can be overridden by calling .assignLanguageMode', () => { <ide> describe('GrammarRegistry', () => { <ide> await atom.packages.activatePackage('language-javascript') <ide> expect(atom.grammars.selectGrammar('foo.rb', '#!/usr/bin/env node').scopeName).toBe('source.ruby') <ide> }) <add> <add> describe('tree-sitter vs text-mate', () => { <add> it('favors a text-mate grammar over a tree-sitter grammar when `core.useTreeSitterParsers` is false', () => { <add> atom.config.set('core.useTreeSitterParsers', false) <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> <add> const grammar = grammarRegistry.selectGrammar('test.js') <add> expect(grammar.scopeName).toBe('source.js') <add> expect(grammar instanceof FirstMate.Grammar).toBe(true) <add> }) <add> <add> it('favors a tree-sitter grammar over a text-mate grammar when `core.useTreeSitterParsers` is true', () => { <add> atom.config.set('core.useTreeSitterParsers', true) <add> <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/javascript.cson')) <add> grammarRegistry.loadGrammarSync(require.resolve('language-javascript/grammars/tree-sitter-javascript.cson')) <add> <add> const grammar = grammarRegistry.selectGrammar('test.js') <add> expect(grammar.id).toBe('javascript') <add> expect(grammar instanceof TreeSitterGrammar).toBe(true) <add> }) <add> }) <ide> }) <ide> <ide> describe('.removeGrammar(grammar)', () => { <ide><path>src/config-schema.js <ide> const configSchema = { <ide> description: 'Emulated with Atom events' <ide> } <ide> ] <add> }, <add> useTreeSitterParsers: { <add> type: 'boolean', <add> default: false, <add> description: 'Use the new Tree-sitter parsing system for supported languages' <ide> } <ide> } <ide> }, <ide><path>src/grammar-registry.js <ide> const Token = require('./token') <ide> const fs = require('fs-plus') <ide> const {Point, Range} = require('text-buffer') <ide> <add>const GRAMMAR_TYPE_BONUS = 1000 <ide> const GRAMMAR_SELECTION_RANGE = Range(Point.ZERO, Point(10, 0)).freeze() <ide> const PATH_SPLIT_REGEX = new RegExp('[/.]') <ide> <add>const LANGUAGE_ID_MAP = [ <add> ['source.js', 'javascript'], <add> ['source.ts', 'typescript'] <add>] <add> <ide> // Extended: This class holds the grammars used for tokenizing. <ide> // <ide> // An instance of this class is always available as the `atom.grammars` global. <ide> class GrammarRegistry { <ide> // found. <ide> assignLanguageMode (buffer, languageId) { <ide> if (buffer.getBuffer) buffer = buffer.getBuffer() <add> languageId = this.normalizeLanguageId(languageId) <ide> <ide> let grammar = null <ide> if (languageId != null) { <ide> class GrammarRegistry { <ide> if (this.grammarMatchesContents(grammar, contents)) { <ide> score += 0.25 <ide> } <add> <add> if (score > 0 && this.isGrammarPreferredType(grammar)) { <add> score += GRAMMAR_TYPE_BONUS <add> } <add> <ide> return score <ide> } <ide> <ide> class GrammarRegistry { <ide> escaped = false <ide> } <ide> } <add> <ide> const lines = contents.split('\n') <ide> return grammar.firstLineRegex.testSync(lines.slice(0, numberOfNewlinesInRegex + 1).join('\n')) <ide> } <ide> class GrammarRegistry { <ide> } <ide> <ide> grammarForId (languageId) { <add> languageId = this.normalizeLanguageId(languageId) <add> <ide> return ( <ide> this.textmateRegistry.grammarForScopeName(languageId) || <ide> this.treeSitterGrammarsById[languageId] <ide> class GrammarRegistry { <ide> } <ide> <ide> grammarAddedOrUpdated (grammar) { <add> if (grammar.scopeName && !grammar.id) grammar.id = grammar.scopeName <add> <ide> this.grammarScoresByBuffer.forEach((score, buffer) => { <ide> const languageMode = buffer.getLanguageMode() <ide> if (grammar.injectionSelector) { <ide> class GrammarRegistry { <ide> <ide> const languageOverride = this.languageOverridesByBufferId.get(buffer.id) <ide> <del> if ((grammar.scopeName === buffer.getLanguageMode().getLanguageId() || <del> grammar.scopeName === languageOverride)) { <add> if ((grammar.id === buffer.getLanguageMode().getLanguageId() || <add> grammar.id === languageOverride)) { <ide> buffer.setLanguageMode(this.languageModeForGrammarAndBuffer(grammar, buffer)) <ide> } else if (!languageOverride) { <ide> const score = this.getGrammarScore( <ide> class GrammarRegistry { <ide> } <ide> <ide> grammarForScopeName (scopeName) { <del> return this.textmateRegistry.grammarForScopeName(scopeName) <add> return this.grammarForId(scopeName) <ide> } <ide> <ide> addGrammar (grammar) { <ide> class GrammarRegistry { <ide> // * `error` An {Error}, may be null. <ide> // * `grammar` A {Grammar} or null if an error occured. <ide> loadGrammar (grammarPath, callback) { <del> return this.textmateRegistry.loadGrammar(grammarPath, callback) <add> this.readGrammar(grammarPath, (error, grammar) => { <add> if (error) return callback(error) <add> this.addGrammar(grammar) <add> callback(grammar) <add> }) <ide> } <ide> <ide> // Extended: Read a grammar synchronously and add it to this registry. <ide> class GrammarRegistry { <ide> // <ide> // Returns a {Grammar}. <ide> loadGrammarSync (grammarPath) { <del> return this.textmateRegistry.loadGrammarSync(grammarPath) <add> const grammar = this.readGrammarSync(grammarPath) <add> this.addGrammar(grammar) <add> return grammar <ide> } <ide> <ide> // Extended: Read a grammar asynchronously but don't add it to the registry. <ide> class GrammarRegistry { <ide> scopeForId (id) { <ide> return this.textmateRegistry.scopeForId(id) <ide> } <add> <add> isGrammarPreferredType (grammar) { <add> return this.config.get('core.useTreeSitterParsers') <add> ? grammar instanceof TreeSitterGrammar <add> : grammar instanceof FirstMate.Grammar <add> } <add> <add> normalizeLanguageId (languageId) { <add> if (this.config.get('core.useTreeSitterParsers')) { <add> const row = LANGUAGE_ID_MAP.find(entry => entry[0] === languageId) <add> return row ? row[1] : languageId <add> } else { <add> const row = LANGUAGE_ID_MAP.find(entry => entry[1] === languageId) <add> return row ? row[0] : languageId <add> } <add> } <ide> } <ide><path>src/text-editor.js <ide> class TextEditor { <ide> return this.expandSelectionsBackward(selection => selection.selectToBeginningOfPreviousParagraph()) <ide> } <ide> <add> selectLargerSyntaxNode () { <add> const languageMode = this.buffer.getLanguageMode() <add> if (!languageMode.getRangeForSyntaxNodeContainingRange) return <add> <add> this.expandSelectionsForward(selection => { <add> const range = languageMode.getRangeForSyntaxNodeContainingRange(selection.getBufferRange()) <add> if (range) selection.setBufferRange(range) <add> }) <add> } <add> <ide> // Extended: Select the range of the given marker if it is valid. <ide> // <ide> // * `marker` A {DisplayMarker} <ide><path>src/tree-sitter-language-mode.js <ide> class TreeSitterLanguageMode { <ide> return this.rootScopeDescriptor <ide> } <ide> <add> hasTokenForSelector (scopeSelector) { <add> return false <add> } <add> <ide> getGrammar () { <ide> return this.grammar <ide> }
5
Python
Python
change tf.to_int32 to tf.cast
6765b16dce47a23a1da1c7b03782edc4f618e235
<ide><path>official/mnist/dataset.py <ide> def decode_image(image): <ide> def decode_label(label): <ide> label = tf.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8] <ide> label = tf.reshape(label, []) # label is a scalar <del> return tf.to_int32(label) <add> return tf.cast(label, tf.int32) <ide> <ide> images = tf.data.FixedLengthRecordDataset( <ide> images_file, 28 * 28, header_bytes=16).map(decode_image)
1
Javascript
Javascript
update apollo example for 9.5
bf9b96bd81d62d8fe62487ef58509dd958d76bcb
<ide><path>examples/with-apollo/pages/index.js <ide> export async function getStaticProps() { <ide> props: { <ide> initialApolloState: apolloClient.cache.extract(), <ide> }, <del> unstable_revalidate: 1, <add> revalidate: 1, <ide> } <ide> } <ide>
1
Javascript
Javascript
fix typo in tls_session_attack message
e9e9863ca7ba61ea4e1b5a28c18b29e449f87f00
<ide><path>lib/internal/errors.js <ide> E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout'); <ide> E('ERR_TLS_RENEGOTIATION_FAILED', 'Failed to renegotiate'); <ide> E('ERR_TLS_REQUIRED_SERVER_NAME', <ide> '"servername" is required parameter for Server.addContext'); <del>E('ERR_TLS_SESSION_ATTACK', 'TSL session renegotiation attack detected'); <add>E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected'); <ide> E('ERR_TRANSFORM_ALREADY_TRANSFORMING', <ide> 'Calling transform done when still transforming'); <ide> E('ERR_TRANSFORM_WITH_LENGTH_0',
1
Javascript
Javascript
add zipkin trace capturing with output to json.
5c24670227b36c079e26d6af3e85297dce5e2212
<ide><path>bench/capture-trace.js <add>const http = require('http') <add>const fs = require('fs') <add> <add>const PORT = 9411 <add>const HOST = '0.0.0.0' <add> <add>const traces = [] <add> <add>const onReady = () => console.log(`Listening on http://${HOST}:${PORT}`) <add>const onRequest = async (req, res) => { <add> if ( <add> req.method !== 'POST' || <add> req.url !== '/api/v2/spans' || <add> (req.headers && req.headers['content-type']) !== 'application/json' <add> ) { <add> res.writeHead(200) <add> return res.end() <add> } <add> <add> try { <add> const body = JSON.parse(await getBody(req)) <add> for (const traceEvent of body) { <add> traces.push(traceEvent) <add> } <add> res.writeHead(200) <add> } catch (err) { <add> console.warn(err) <add> res.writeHead(500) <add> } <add> <add> res.end() <add>} <add> <add>const getBody = (req) => <add> new Promise((resolve, reject) => { <add> let data = '' <add> req.on('data', (chunk) => { <add> data += chunk <add> }) <add> req.on('end', () => { <add> if (!req.complete) { <add> return reject('Connection terminated before body was received.') <add> } <add> resolve(data) <add> }) <add> req.on('aborted', () => reject('Connection aborted.')) <add> req.on('error', () => reject('Connection error.')) <add> }) <add> <add>const main = () => { <add> const args = process.argv.slice(2) <add> const outFile = args[0] || `./trace-${Date.now()}.json` <add> <add> process.on('SIGINT', () => { <add> console.log(`\nSaving to ${outFile}...`) <add> fs.writeFileSync(outFile, JSON.stringify(traces, null, 2)) <add> process.exit() <add> }) <add> <add> const server = http.createServer(onRequest) <add> server.listen(PORT, HOST, onReady) <add>} <add> <add>if (require.main === module) { <add> main() <add>}
1
Javascript
Javascript
fix broken ie8 test
908ab52b8dced67186e9f2d17a00362b28c13a86
<ide><path>test/ngAnimate/animateSpec.js <ide> describe("ngAnimate", function() { <ide> })); <ide> <ide> it("should intelligently cancel former timeouts and close off a series of elements a final timeout", function() { <del> var currentTimestamp = Date.now(); <del> spyOn(Date,'now').andCallFake(function() { <del> return currentTimestamp; <del> }); <del> <del> var cancellations = 0; <add> var currentTimestamp, cancellations = 0; <ide> module(function($provide) { <ide> $provide.decorator('$timeout', function($delegate) { <ide> var _cancel = $delegate.cancel; <ide> describe("ngAnimate", function() { <ide> }; <ide> return $delegate; <ide> }); <add> <add> return function($sniffer) { <add> if($sniffer.transitions) { <add> currentTimestamp = Date.now(); <add> spyOn(Date,'now').andCallFake(function() { <add> return currentTimestamp; <add> }); <add> } <add> } <ide> }) <ide> inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { <ide> if (!$sniffer.transitions) return;
1
PHP
PHP
remove an unnecessary checking
3dc382c5a71b180d3b848b02a71e0d7efc973222
<ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php <ide> protected function compileComponents(Builder $query) <ide> $sql = []; <ide> <ide> foreach ($this->selectComponents as $component) { <del> if (isset($query->$component) && ! is_null($query->$component)) { <add> if (isset($query->$component)) { <ide> $method = 'compile'.ucfirst($component); <ide> <ide> $sql[$component] = $this->$method($query, $query->$component);
1
PHP
PHP
consolidate duplicated code and fix a few issues
a44fb7620176fb99f8031b6dcf2ac3c9a9429564
<ide><path>src/Controller/Controller.php <ide> use Cake\Utility\MergeVariablesTrait; <ide> use Cake\View\ViewVarsTrait; <ide> use LogicException; <del>use RuntimeException; <ide> <ide> /** <ide> * Application controller class for organization of business logic. <ide> public function addComponent($name, array $config = []) { <ide> */ <ide> public function loadComponent($name, array $config = []) { <ide> list(, $prop) = pluginSplit($name); <del> $components = $this->components(); <del> <del> if (isset($components->$name) && $config && $components->$name->config() !== $config) { <del> $msg = sprintf( <del> 'The "%s" component has already been loaded with the following config: %s', <del> $name, <del> var_export($components->{$name}->config(), true) <del> ); <del> throw new RuntimeException($msg); <del> } <del> $this->{$prop} = $components->load($name, $config); <add> $this->{$prop} = $this->components()->load($name, $config); <ide> return $this->{$prop}; <ide> } <ide> <ide><path>src/Core/ObjectRegistry.php <ide> */ <ide> namespace Cake\Core; <ide> <add>use RuntimeException; <add> <ide> /** <ide> * Acts as a registry/factory for objects. <ide> * <ide> abstract class ObjectRegistry { <ide> */ <ide> public function load($objectName, $config = []) { <ide> list($plugin, $name) = pluginSplit($objectName); <del> if (isset($this->_loaded[$name])) { <add> $loaded = isset($this->_loaded[$name]); <add> if ($loaded && !empty($config)) { <add> $this->_checkDuplicate($name, $config); <add> } <add> if ($loaded) { <ide> return $this->_loaded[$name]; <ide> } <add> <ide> if (is_array($config) && isset($config['className'])) { <ide> $objectName = $config['className']; <ide> } <ide> public function load($objectName, $config = []) { <ide> return $instance; <ide> } <ide> <add>/** <add> * Check for duplicate object loading. <add> * <add> * If a duplicate is being loaded and has different configuration, that is <add> * bad and an exception will be raised. <add> * <add> * An exception is raised, as replacing the object will not update any <add> * references other objects may have. Additionally, simply updating the runtime <add> * configuration is not a good option as we may be missing important constructor <add> * logic dependent on the configuration. <add> * <add> * @param string $name The name of the alias in the registry. <add> * @param array $config The config data for the new instance. <add> * @return void <add> * @throws \RuntimeException When a duplicate is found. <add> */ <add> protected function _checkDuplicate($name, $config) { <add> $existing = $this->_loaded[$name]; <add> $msg = sprintf('The "%s" alias has already been loaded', $name); <add> $hasConfig = false; <add> if (method_exists($existing, 'config')) { <add> $hasConfig = true; <add> } <add> if (!$hasConfig) { <add> throw new RuntimeException($msg); <add> } <add> unset($config['enabled']); <add> if ($hasConfig && array_diff_assoc($config, $existing->config()) != []) { <add> $msg .= ' with the following config: '; <add> $msg .= var_export($this->{$name}->config(), true); <add> $msg .= ' which differs from ' . var_export($config, true); <add> throw new RuntimeException($msg); <add> } <add> } <add> <ide> /** <ide> * Should resolve the classname for a given object type. <ide> * <ide><path>src/Core/StaticConfigTrait.php <ide> public static function drop($config) { <ide> if (!isset(static::$_config[$config])) { <ide> return false; <ide> } <del> if (isset(static::$_registry) && isset(static::$_registry->{$config})) { <add> if (isset(static::$_registry)) { <ide> static::$_registry->unload($config); <ide> } <ide> unset(static::$_config[$config]); <ide><path>src/Log/Log.php <ide> protected static function _loadConfig() { <ide> if (isset($properties['engine'])) { <ide> $properties['className'] = $properties['engine']; <ide> } <del> static::$_registry->load($name, $properties); <add> if (!static::$_registry->loaded($name)) { <add> static::$_registry->load($name, $properties); <add> } <ide> } <ide> } <ide> <ide><path>src/ORM/Table.php <ide> public function entityClass($name = null) { <ide> * @see \Cake\ORM\Behavior <ide> */ <ide> public function addBehavior($name, array $options = []) { <del> $behaviors = $this->_behaviors; <del> if (isset($behaviors->$name) && $behaviors->{$name}->config() !== $options) { <del> $msg = sprintf( <del> 'The "%s" behavior has already been loaded with the following config: %s', <del> $name, <del> var_export($behaviors->{$name}->config(), true) <del> ); <del> throw new RuntimeException($msg); <del> } <del> $behaviors->load($name, $options); <add> $this->_behaviors->load($name, $options); <ide> } <ide> <ide> /** <ide><path>src/View/View.php <ide> use Cake\View\ViewVarsTrait; <ide> use InvalidArgumentException; <ide> use LogicException; <del>use RuntimeException; <ide> <ide> /** <ide> * View, the V in the MVC triad. View interacts with Helpers and view variables passed <ide> public function addHelper($helperName, array $config = []) { <ide> public function loadHelper($name, array $config = []) { <ide> list(, $class) = pluginSplit($name); <ide> $helpers = $this->helpers(); <del> if ($helpers->loaded($class) && $config && $helpers->$class->config() !== $config) { <del> $msg = sprintf( <del> 'The "%s" helper has already been loaded with the following config: %s', <del> $name, <del> var_export($helpers->{$class}->config(), true) <del> ); <del> throw new RuntimeException($msg); <del> } <ide> return $this->{$class} = $helpers->load($name, $config); <ide> } <ide> <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testLoadComponentDuplicate() { <ide> $controller->loadComponent('Paginator', ['bad' => 'settings']); <ide> $this->fail('No exception'); <ide> } catch (\RuntimeException $e) { <del> $this->assertContains('The "Paginator" component has already been loaded', $e->getMessage()); <add> $this->assertContains('The "Paginator" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide> <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testAddBehaviorDuplicate() { <ide> $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value'])); <ide> $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value'])); <ide> try { <del> $table->addBehavior('Sluggable'); <add> $table->addBehavior('Sluggable', ['thing' => 'thing']); <ide> $this->fail('No exception raised'); <ide> } catch (\RuntimeException $e) { <del> $this->assertContains('The "Sluggable" behavior has already been loaded', $e->getMessage()); <add> $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide> <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testLoadHelperDuplicate() { <ide> $View->loadHelper('Html', ['test' => 'value']); <ide> $this->fail('No exception'); <ide> } catch (\RuntimeException $e) { <del> $this->assertContains('The "Html" helper has already been loaded', $e->getMessage()); <add> $this->assertContains('The "Html" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide>
9
Javascript
Javascript
fix crash during server render
b305c4e034bbb3b13df2028c0503a84f91e57455
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> export function createTextInstance( <ide> } <ide> <ide> export const isPrimaryRenderer = true; <del>export const scheduleTimeout = setTimeout; <del>export const cancelTimeout = clearTimeout; <add>// This initialization code may run even on server environments <add>// if a component just imports ReactDOM (e.g. for findDOMNode). <add>// Some environments might not have setTimeout or clearTimeout. <add>export const scheduleTimeout = <add> typeof setTimeout === 'function' ? setTimeout : (undefined: any); <add>export const cancelTimeout = <add> typeof clearTimeout === 'function' ? clearTimeout : (undefined: any); <ide> export const noTimeout = -1; <ide> <ide> // -------------------
1
Javascript
Javascript
use non-symbols in isurlinstance check
8825eb4d734c78ccdaa06811a5b033e59f7fa978
<ide><path>lib/internal/url.js <ide> function pathToFileURL(filepath) { <ide> } <ide> <ide> function isURLInstance(fileURLOrPath) { <del> return fileURLOrPath != null && fileURLOrPath[searchParams] && <del> fileURLOrPath[searchParams][searchParams]; <add> return fileURLOrPath != null && fileURLOrPath.href && fileURLOrPath.origin; <ide> } <ide> <ide> function toPathIfFileURL(fileURLOrPath) {
1
Ruby
Ruby
move linkagechecker to standalone file
13730a9dadde8570e41cf5599b4f5c940014f190
<ide><path>Library/Homebrew/dev-cmd/linkage.rb <ide> # --reverse - For each dylib the keg references, print the dylib followed by the <ide> # binaries which link to it. <ide> <del>require "set" <del>require "keg" <del>require "formula" <add>require "os/mac/linkage_checker" <ide> <ide> module Homebrew <ide> def linkage <del> found_broken_dylibs = false <ide> ARGV.kegs.each do |keg| <ide> ohai "Checking #{keg.name} linkage" if ARGV.kegs.size > 1 <ide> result = LinkageChecker.new(keg) <ide> if ARGV.include?("--test") <ide> result.display_test_output <add> Homebrew.failed = true if result.broken_dylibs? <ide> elsif ARGV.include?("--reverse") <ide> result.display_reverse_output <ide> else <ide> result.display_normal_output <ide> end <del> found_broken_dylibs = true unless result.broken_dylibs.empty? <del> end <del> if ARGV.include?("--test") && found_broken_dylibs <del> exit 1 <del> end <del> end <del> <del> class LinkageChecker <del> attr_reader :keg <del> attr_reader :broken_dylibs <del> <del> def initialize(keg) <del> @keg = keg <del> @brewed_dylibs = Hash.new { |h, k| h[k] = Set.new } <del> @system_dylibs = Set.new <del> @broken_dylibs = Set.new <del> @variable_dylibs = Set.new <del> @reverse_links = Hash.new { |h, k| h[k] = Set.new } <del> check_dylibs <del> end <del> <del> def check_dylibs <del> @keg.find do |file| <del> next if file.symlink? || file.directory? <del> next unless file.dylib? || file.mach_o_executable? || file.mach_o_bundle? <del> file.dynamically_linked_libraries.each do |dylib| <del> @reverse_links[dylib] << file <del> if dylib.start_with? "@" <del> @variable_dylibs << dylib <del> else <del> begin <del> owner = Keg.for Pathname.new(dylib) <del> rescue NotAKegError <del> @system_dylibs << dylib <del> rescue Errno::ENOENT <del> @broken_dylibs << dylib <del> else <del> @brewed_dylibs[owner.name] << dylib <del> end <del> end <del> end <del> end <del> <del> begin <del> f = Formulary.from_rack(keg.rack) <del> f.build = Tab.for_keg(keg) <del> filter_out = proc do |dep| <del> dep.build? || (dep.optional? && !dep.option_names.any? { |n| f.build.with?(n) }) <del> end <del> declared_deps = f.deps.reject { |dep| filter_out.call(dep) }.map(&:name) + <del> f.requirements.reject { |req| filter_out.call(req) }.map(&:default_formula).compact <del> @undeclared_deps = @brewed_dylibs.keys - declared_deps.map { |dep| dep.split("/").last } <del> @undeclared_deps -= [f.name] <del> rescue FormulaUnavailableError <del> opoo "Formula unavailable: #{keg.name}" <del> @undeclared_deps = [] <del> end <del> end <del> <del> def display_normal_output <del> display_items "System libraries", @system_dylibs <del> display_items "Homebrew libraries", @brewed_dylibs <del> display_items "Variable-referenced libraries", @variable_dylibs <del> display_items "Missing libraries", @broken_dylibs <del> display_items "Possible undeclared dependencies", @undeclared_deps <del> end <del> <del> def display_reverse_output <del> return if @reverse_links.empty? <del> sorted = @reverse_links.sort <del> sorted.each do |dylib, files| <del> puts dylib <del> files.each do |f| <del> unprefixed = f.to_s.strip_prefix "#{@keg.to_s}/" <del> puts " #{unprefixed}" <del> end <del> puts unless dylib == sorted.last[0] <del> end <del> end <del> <del> def display_test_output <del> display_items "Missing libraries", @broken_dylibs <del> puts "No broken dylib links" if @broken_dylibs.empty? <del> end <del> <del> private <del> <del> # Display a list of things. <del> # Things may either be an array, or a hash of (label -> array) <del> def display_items(label, things) <del> return if things.empty? <del> puts "#{label}:" <del> if things.is_a? Hash <del> things.sort.each do |list_label, list| <del> list.sort.each do |item| <del> puts " #{item} (#{list_label})" <del> end <del> end <del> else <del> things.sort.each do |item| <del> puts " #{item}" <del> end <del> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/os/mac/linkage_checker.rb <add>require "set" <add>require "keg" <add>require "formula" <add> <add>class LinkageChecker <add> attr_reader :keg <add> attr_reader :brewed_dylibs, :system_dylibs, :broken_dylibs, :variable_dylibs <add> attr_reader :undeclared_deps, :reverse_links <add> <add> def initialize(keg) <add> @keg = keg <add> @brewed_dylibs = Hash.new { |h, k| h[k] = Set.new } <add> @system_dylibs = Set.new <add> @broken_dylibs = Set.new <add> @variable_dylibs = Set.new <add> @undeclared_deps = [] <add> @reverse_links = Hash.new { |h, k| h[k] = Set.new } <add> check_dylibs <add> end <add> <add> def check_dylibs <add> @keg.find do |file| <add> next if file.symlink? || file.directory? <add> next unless file.dylib? || file.mach_o_executable? || file.mach_o_bundle? <add> file.dynamically_linked_libraries.each do |dylib| <add> @reverse_links[dylib] << file <add> if dylib.start_with? "@" <add> @variable_dylibs << dylib <add> else <add> begin <add> owner = Keg.for Pathname.new(dylib) <add> rescue NotAKegError <add> @system_dylibs << dylib <add> rescue Errno::ENOENT <add> @broken_dylibs << dylib <add> else <add> @brewed_dylibs[owner.name] << dylib <add> end <add> end <add> end <add> end <add> <add> begin <add> f = Formulary.from_rack(keg.rack) <add> f.build = Tab.for_keg(keg) <add> filter_out = proc do |dep| <add> dep.build? || (dep.optional? && !dep.option_names.any? { |n| f.build.with?(n) }) <add> end <add> declared_deps = f.deps.reject { |dep| filter_out.call(dep) }.map(&:name) + <add> f.requirements.reject { |req| filter_out.call(req) }.map(&:default_formula).compact <add> @undeclared_deps = @brewed_dylibs.keys - declared_deps.map { |dep| dep.split("/").last } <add> @undeclared_deps -= [f.name] <add> rescue FormulaUnavailableError <add> opoo "Formula unavailable: #{keg.name}" <add> end <add> end <add> <add> def display_normal_output <add> display_items "System libraries", @system_dylibs <add> display_items "Homebrew libraries", @brewed_dylibs <add> display_items "Variable-referenced libraries", @variable_dylibs <add> display_items "Missing libraries", @broken_dylibs <add> display_items "Possible undeclared dependencies", @undeclared_deps <add> end <add> <add> def display_reverse_output <add> return if @reverse_links.empty? <add> sorted = @reverse_links.sort <add> sorted.each do |dylib, files| <add> puts dylib <add> files.each do |f| <add> unprefixed = f.to_s.strip_prefix "#{@keg}/" <add> puts " #{unprefixed}" <add> end <add> puts unless dylib == sorted.last[0] <add> end <add> end <add> <add> def display_test_output <add> display_items "Missing libraries", @broken_dylibs <add> puts "No broken dylib links" if @broken_dylibs.empty? <add> display_items "Possible undeclared dependencies", @undeclared_deps <add> puts "No undeclared dependencies" if @undeclared_deps.empty? <add> end <add> <add> def broken_dylibs? <add> !@broken_dylibs.empty? <add> end <add> <add> def undeclared_deps? <add> !@undeclared_deps.empty? <add> end <add> <add> private <add> <add> # Display a list of things. <add> # Things may either be an array, or a hash of (label -> array) <add> def display_items(label, things) <add> return if things.empty? <add> puts "#{label}:" <add> if things.is_a? Hash <add> things.sort.each do |list_label, list| <add> list.sort.each do |item| <add> puts " #{item} (#{list_label})" <add> end <add> end <add> else <add> things.sort.each do |item| <add> puts " #{item}" <add> end <add> end <add> end <add>end
2
PHP
PHP
prefer stricter negative comparisons.
54b406891d0e6081e2d766ec25bc64ea0f05f4ba
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> // where null clause to the query. So, we will allow a short-cut here to <ide> // that method for convenience so the developer doesn't have to check. <ide> if (is_null($value)) { <del> return $this->whereNull($column, $boolean, $operator != '='); <add> return $this->whereNull($column, $boolean, $operator !== '='); <ide> } <ide> <ide> // If the column is making a JSON reference we'll check to see if the value <ide> public function dynamicWhere($method, $parameters) <ide> // If the segment is not a boolean connector, we can assume it is a column's name <ide> // and we will add it to the query as a new constraint as a where clause, then <ide> // we can keep iterating through the dynamic method string's segments again. <del> if ($segment != 'And' && $segment != 'Or') { <add> if ($segment !== 'And' && $segment !== 'Or') { <ide> $this->addDynamic($segment, $connector, $parameters, $index); <ide> <ide> $index++; <ide><path>src/Illuminate/Database/Schema/SQLiteBuilder.php <ide> class SQLiteBuilder extends Builder <ide> */ <ide> public function dropAllTables() <ide> { <del> if ($this->connection->getDatabaseName() != ':memory:') { <add> if ($this->connection->getDatabaseName() !== ':memory:') { <ide> return $this->refreshDatabaseFile(); <ide> } <ide> <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> protected function transformHeadersToServerVars(array $headers) <ide> */ <ide> protected function formatServerHeaderKey($name) <ide> { <del> if (! Str::startsWith($name, 'HTTP_') && $name != 'CONTENT_TYPE') { <add> if (! Str::startsWith($name, 'HTTP_') && $name !== 'CONTENT_TYPE') { <ide> return 'HTTP_'.$name; <ide> } <ide> <ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php <ide> public function hasFile($key) <ide> */ <ide> protected function isValidFile($file) <ide> { <del> return $file instanceof SplFileInfo && $file->getPath() != ''; <add> return $file instanceof SplFileInfo && $file->getPath() !== ''; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Http/Request.php <ide> public function segments() <ide> $segments = explode('/', $this->decodedPath()); <ide> <ide> return array_values(array_filter($segments, function ($v) { <del> return $v != ''; <add> return $v !== ''; <ide> })); <ide> } <ide> <ide><path>src/Illuminate/Pagination/LengthAwarePaginator.php <ide> public function __construct($items, $total, $perPage, $currentPage = null, array <ide> $this->total = $total; <ide> $this->perPage = $perPage; <ide> $this->lastPage = max((int) ceil($total / $perPage), 1); <del> $this->path = $this->path != '/' ? rtrim($this->path, '/') : $this->path; <add> $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path; <ide> $this->currentPage = $this->setCurrentPage($currentPage, $this->pageName); <ide> $this->items = $items instanceof Collection ? $items : Collection::make($items); <ide> } <ide><path>src/Illuminate/Pagination/Paginator.php <ide> public function __construct($items, $perPage, $currentPage = null, array $option <ide> <ide> $this->perPage = $perPage; <ide> $this->currentPage = $this->setCurrentPage($currentPage); <del> $this->path = $this->path != '/' ? rtrim($this->path, '/') : $this->path; <add> $this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path; <ide> <ide> $this->setItems($items); <ide> } <ide><path>src/Illuminate/Support/Str.php <ide> public static function camel($value) <ide> public static function contains($haystack, $needles) <ide> { <ide> foreach ((array) $needles as $needle) { <del> if ($needle != '' && mb_strpos($haystack, $needle) !== false) { <add> if ($needle !== '' && mb_strpos($haystack, $needle) !== false) { <ide> return true; <ide> } <ide> } <ide> public static function snake($value, $delimiter = '_') <ide> public static function startsWith($haystack, $needles) <ide> { <ide> foreach ((array) $needles as $needle) { <del> if ($needle != '' && substr($haystack, 0, strlen($needle)) === (string) $needle) { <add> if ($needle !== '' && substr($haystack, 0, strlen($needle)) === (string) $needle) { <ide> return true; <ide> } <ide> } <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> public function validateMimes($attribute, $value, $parameters) <ide> return false; <ide> } <ide> <del> return $value->getPath() != '' && in_array($value->guessExtension(), $parameters); <add> return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters); <ide> } <ide> <ide> /** <ide> public function validateMimetypes($attribute, $value, $parameters) <ide> return false; <ide> } <ide> <del> return $value->getPath() != '' && <add> return $value->getPath() !== '' && <ide> (in_array($value->getMimeType(), $parameters) || <ide> in_array(explode('/', $value->getMimeType())[0].'/*', $parameters)); <ide> } <ide> public function validateRequired($attribute, $value) <ide> } elseif ((is_array($value) || $value instanceof Countable) && count($value) < 1) { <ide> return false; <ide> } elseif ($value instanceof File) { <del> return (string) $value->getPath() != ''; <add> return (string) $value->getPath() !== ''; <ide> } <ide> <ide> return true; <ide><path>src/Illuminate/Validation/DatabasePresenceVerifier.php <ide> public function getCount($collection, $column, $value, $excludeId = null, $idCol <ide> { <ide> $query = $this->table($collection)->where($column, '=', $value); <ide> <del> if (! is_null($excludeId) && $excludeId != 'NULL') { <add> if (! is_null($excludeId) && $excludeId !== 'NULL') { <ide> $query->where($idColumn ?: 'id', '<>', $excludeId); <ide> } <ide> <ide><path>src/Illuminate/Validation/ValidationData.php <ide> public static function extractDataFromPath($attribute, $masterData) <ide> <ide> $value = Arr::get($masterData, $attribute, '__missing__'); <ide> <del> if ($value != '__missing__') { <add> if ($value !== '__missing__') { <ide> Arr::set($results, $attribute, $value); <ide> } <ide>
11
Python
Python
pass additional runtests.py args to asv
0a999147c1679e212a2e4d532bae7b49bee15f1e
<ide><path>runtests.py <ide> def main(argv): <ide> "COMMIT. Note that you need to commit your " <ide> "changes first!")) <ide> parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, <del> help="Arguments to pass to Nose, Python or shell") <add> help="Arguments to pass to Nose, asv, Python or shell") <ide> args = parser.parse_args(argv) <ide> <ide> if args.durations < 0: <ide> def main(argv): <ide> site_dir = os.path.sep.join(_temp.__file__.split(os.path.sep)[:-2]) <ide> <ide> extra_argv = args.args[:] <del> if extra_argv and extra_argv[0] == '--': <del> extra_argv = extra_argv[1:] <add> if not args.bench: <add> # extra_argv may also lists selected benchmarks <add> if extra_argv and extra_argv[0] == '--': <add> extra_argv = extra_argv[1:] <ide> <ide> if args.python: <ide> # Debugging issues with warnings is much easier if you can see them <ide> def main(argv): <ide> <ide> if args.bench: <ide> # Run ASV <del> items = extra_argv <add> for i, v in enumerate(extra_argv): <add> if v.startswith("--"): <add> items = extra_argv[:i] <add> if v == "--": <add> i += 1 # skip '--' indicating further are passed on. <add> bench_args = extra_argv[i:] <add> break <add> else: <add> items = extra_argv <add> bench_args = [] <add> <ide> if args.tests: <ide> items += args.tests <ide> if args.submodule: <ide> items += [args.submodule] <del> <del> bench_args = [] <ide> for a in items: <ide> bench_args.extend(['--bench', a]) <ide>
1
Javascript
Javascript
use setpaths instead of command line paths
e376096e8fe29c6c568e329f040d6dd7be6ab2e3
<ide><path>src/main-process/parse-command-line.js <ide> module.exports = function parseCommandLine (processArgs) { <ide> let projectSettings = {} <ide> if (atomProject) { <ide> const contents = Object.assign({}, readProjectSettingsSync(atomProject, executedFrom)) <del> const paths = contents.paths <ide> const config = contents.config <ide> const originPath = atomProject <del> if (paths != null) { <del> const relativizedPaths = paths.map((curPath) => <del> relativizeToAtomProject(curPath, atomProject, executedFrom) <del> ) <del> pathsToOpen = pathsToOpen.concat(relativizedPaths) <del> } <del> console.log(pathsToOpen) <add> const paths = contents.paths.map((curPath) => <add> relativizeToAtomProject(curPath, atomProject, executedFrom) <add> ) <add> pathsToOpen.push(path.dirname(atomProject)) <ide> projectSettings = { originPath, paths, config } <ide> } <ide> <ide> const readProjectSettingsSync = (filepath, executedFrom) => { <ide> try { <ide> const readPath = path.isAbsolute(filepath) ? filepath : path.join(executedFrom, filepath) <ide> const contents = CSON.readFileSync(readPath) <del> if (contents.paths || contents.config) { <add> if (contents.paths && contents.config) { <ide> return contents <ide> } <add> throw new Error() <ide> } catch (e) { <del> throw new Error('Unable to read supplied config file.') <add> const errorMessage = `Unable to read supplied atomproject file. This file must have a valid array of paths, as well as a valid config object.` <add> throw new Error(errorMessage) <ide> } <ide> } <ide> <ide><path>src/project.js <ide> class Project extends Model { <ide> replaceAtomProject (newSettings) { <ide> atom.config.resetProjectSettings(newSettings.config) <ide> this.projectFilePath = newSettings.originPath <add> this.setPaths(newSettings.paths) <ide> this.emitter.emit('replaced-atom-project', newSettings) <ide> } <ide>
2
Javascript
Javascript
apply coding convention
9fd81ee7583fff010cf006fa42aa4f72ac714563
<ide><path>lang/ko.js <ide> }, <ide> ordinal : '%d일', <ide> meridiemParse : /(오전|오후)/i, <del> isPM : function(token){ <del> return token == "오후"; <add> isPM : function (token) { <add> return token === "오후"; <ide> } <ide> }); <ide> })); <ide><path>test/lang/ko.js <ide> exports["lang:kr"] = { <ide> test.done(); <ide> }, <ide> <del> <del> "parse meridiem" : function (test){ <del> var elements = [{ <del> expression : "1981년 9월 8일 오후 2시 30분", <del> inputFormat : "YYYY[년] M[월] D[일] A h[시] m[분]", <del> outputFormat : "A", <del> expected : "오후" <del> },{ <del> expression : "1981년 9월 8일 오전 2시 30분", <del> inputFormat : "YYYY[년] M[월] D[일] A h[시] m[분]", <del> outputFormat : "A h시", <del> expected : "오전 2시" <del> },{ <del> expression : "14시 30분", <del> inputFormat : "H[시] m[분]", <del> outputFormat : "A", <del> expected : "오후" <del> },{ <del> expression : "오후 4시", <del> inputFormat : "A h[시]", <del> outputFormat : "H", <del> expected : "16" <del> }]; <add> "parse meridiem" : function (test) { <add> var elements = [{ <add> expression : "1981년 9월 8일 오후 2시 30분", <add> inputFormat : "YYYY[년] M[월] D[일] A h[시] m[분]", <add> outputFormat : "A", <add> expected : "오후" <add> },{ <add> expression : "1981년 9월 8일 오전 2시 30분", <add> inputFormat : "YYYY[년] M[월] D[일] A h[시] m[분]", <add> outputFormat : "A h시", <add> expected : "오전 2시" <add> },{ <add> expression : "14시 30분", <add> inputFormat : "H[시] m[분]", <add> outputFormat : "A", <add> expected : "오후" <add> },{ <add> expression : "오후 4시", <add> inputFormat : "A h[시]", <add> outputFormat : "H", <add> expected : "16" <add> }]; <ide> <del> test.expect(elements.length); <del> <del> elements.forEach(function(it){ <del> var actual = moment(it.expression, it.inputFormat).format(it.outputFormat); <del> <del> test.equal( <del> actual, <del> it.expected, <del> "'" + it.outputFormat + "' of '" + it.expression + "' must be '" + it.expected + "' but was '" + actual + "'." <del> ); <del> }); <del> <del> test.done(); <add> test.expect(elements.length); <add> <add> elements.forEach(function(it){ <add> var actual = moment(it.expression, it.inputFormat).format(it.outputFormat); <add> <add> test.equal( <add> actual, <add> it.expected, <add> "'" + it.outputFormat + "' of '" + it.expression + "' must be '" + it.expected + "' but was '" + actual + "'." <add> ); <add> }); <add> <add> test.done(); <ide> }, <ide> <ide> "format" : function (test) {
2
Python
Python
migrate the swao plugin to psutil 2.0
aafa80e0db19d109b8f8095920e6cbecabb64056
<ide><path>glances/plugins/glances_memswap.py <ide> def msg_curse(self, args=None): <ide> msg = "{0}".format(format(self.auto_unit(self.stats['used'], '>6'))) <ide> ret.append(self.curse_add_line( <ide> msg, self.get_alert_log(self.stats['used'], <del> ax=self.stats['total']))) <add> max=self.stats['total']))) <ide> # New line <ide> ret.append(self.curse_new_line()) <ide> # Free memory usage
1
Text
Text
add links for fs.createwritestream()
ddbad37ecbf84a2b816e9dfa2d970a19e9fbf836
<ide><path>doc/api/fs.md <ide> added: v0.1.93 <ide> --> <ide> <ide> The path to the file the stream is writing to as specified in the first <del>argument to `fs.createWriteStream()`. If `path` is passed as a string, then <add>argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then <ide> `writeStream.path` will be a string. If `path` is passed as a `Buffer`, then <ide> `writeStream.path` will be a `Buffer`. <ide> <ide> If this method is invoked as its [`util.promisify()`][]ed version, it returns <ide> a `Promise` for an `Object` with `bytesWritten` and `buffer` properties. <ide> <ide> It is unsafe to use `fs.write()` multiple times on the same file without waiting <del>for the callback. For this scenario, `fs.createWriteStream()` is recommended. <add>for the callback. For this scenario, [`fs.createWriteStream()`][] is <add>recommended. <ide> <ide> On Linux, positional writes don't work when the file is opened in append mode. <ide> The kernel ignores the position argument and always appends the data to <ide> written is not necessarily the same as string characters written. See <ide> [`Buffer.byteLength`][]. <ide> <ide> It is unsafe to use `fs.write()` multiple times on the same file without waiting <del>for the callback. For this scenario, `fs.createWriteStream()` is recommended. <add>for the callback. For this scenario, [`fs.createWriteStream()`][] is <add>recommended. <ide> <ide> On Linux, positional writes don't work when the file is opened in append mode. <ide> The kernel ignores the position argument and always appends the data to <ide> fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback); <ide> Any specified file descriptor has to support writing. <ide> <ide> It is unsafe to use `fs.writeFile()` multiple times on the same file without <del>waiting for the callback. For this scenario, `fs.createWriteStream()` is <add>waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is <ide> recommended. <ide> <ide> If a file descriptor is specified as the `file`, it will not be closed <ide> at the current position. See pwrite(2). <ide> <ide> It is unsafe to use `filehandle.write()` multiple times on the same file <ide> without waiting for the `Promise` to be resolved (or rejected). For this <del>scenario, `fs.createWriteStream` is strongly recommended. <add>scenario, [`fs.createWriteStream()`][] is strongly recommended. <ide> <ide> On Linux, positional writes do not work when the file is opened in append mode. <ide> The kernel ignores the position argument and always appends the data to <ide> the file contents. <ide> [`fs.chmod()`]: #fs_fs_chmod_path_mode_callback <ide> [`fs.chown()`]: #fs_fs_chown_path_uid_gid_callback <ide> [`fs.copyFile()`]: #fs_fs_copyfile_src_dest_flags_callback <add>[`fs.createWriteStream()`]: #fs_fs_createwritestream_path_options <ide> [`fs.exists()`]: fs.html#fs_fs_exists_path_callback <ide> [`fs.fstat()`]: #fs_fs_fstat_fd_options_callback <ide> [`fs.ftruncate()`]: #fs_fs_ftruncate_fd_len_callback
1
Text
Text
remove outdated documentation
48e17630ad6eabeaaeb105b2371de914728796c1
<ide><path>test/README.md <ide> GitHub with the `autocrlf` git config flag set to true. <ide> |testpy | |Test configuration utility used by various test suites.| <ide> |tick-processor |No |Tests for the V8 tick processor integration. The tests are for the logic in ```lib/internal/v8_prof_processor.js``` and ```lib/internal/v8_prof_polyfill.js```. The tests confirm that the profile processor packages the correct set of scripts from V8 and introduces the correct platform specific logic.| <ide> |v8-updates |No |Tests for V8 performance integration.| <del> <del>_When a new test directory is added, make sure to update the `CI_JS_SUITES` <del>variable in the `Makefile` and the `js_test_suites` variable in <del>`vcbuild.bat`._
1
Go
Go
replace fmt.fprint* with io.writestring
6d21b2ba80e274e49d67e8f3d88bf9b3df567ff5
<ide><path>api/client/stats.go <ide> func (cli *DockerCli) CmdStats(args ...string) error { <ide> w = tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) <ide> ) <ide> printHeader := func() { <del> fmt.Fprint(cli.out, "\033[2J") <del> fmt.Fprint(cli.out, "\033[H") <del> fmt.Fprintln(w, "CONTAINER\tCPU %\tMEM USAGE/LIMIT\tMEM %\tNET I/O") <add> io.WriteString(cli.out, "\033[2J") <add> io.WriteString(cli.out, "\033[H") <add> io.WriteString(w, "CONTAINER\tCPU %\tMEM USAGE/LIMIT\tMEM %\tNET I/O\n") <ide> } <ide> for _, n := range names { <ide> s := &containerStats{Name: n}
1
Java
Java
use alternative uuid strategy in messageheaders
70dfec269b2ea249b2abf3cf252774a6fd578b39
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java <ide> import java.io.ObjectInputStream; <ide> import java.io.ObjectOutputStream; <ide> import java.io.Serializable; <add>import java.math.BigInteger; <add>import java.security.SecureRandom; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.Collection; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Random; <ide> import java.util.Set; <ide> import java.util.UUID; <ide> <ide> * @author Arjen Poutsma <ide> * @author Mark Fisher <ide> * @author Gary Russell <add> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> * @see org.springframework.messaging.support.MessageBuilder <ide> */ <ide> public final class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> private static final Log logger = LogFactory.getLog(MessageHeaders.class); <ide> <del> <ide> private static volatile IdGenerator idGenerator = null; <ide> <add> private static volatile IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator(); <add> <ide> /** <ide> * The key for the Message ID. This is an automatically generated UUID and <ide> * should never be explicitly set in the header map <b>except</b> in the <ide> public final class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> public MessageHeaders(Map<String, Object> headers) { <ide> this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>(); <del> if (MessageHeaders.idGenerator == null){ <del> this.headers.put(ID, UUID.randomUUID()); <del> } <del> else { <del> this.headers.put(ID, MessageHeaders.idGenerator.generateId()); <del> } <del> <add> IdGenerator generatorToUse = (idGenerator != null) ? idGenerator : defaultIdGenerator; <add> this.headers.put(ID, generatorToUse.generateId()); <ide> this.headers.put(TIMESTAMP, new Long(System.currentTimeMillis())); <ide> } <ide> <ide> private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE <ide> public static interface IdGenerator { <ide> UUID generateId(); <ide> } <add> <add> /** <add> * A variation of {@link UUID#randomUUID()} that uses {@link SecureRandom} only for <add> * the initial seed and {@link Random} thereafter, which provides better performance <add> * in exchange for less securely random id's. <add> */ <add> public static class AlternativeJdkIdGenerator implements IdGenerator { <add> <add> private final Random random; <add> <add> public AlternativeJdkIdGenerator() { <add> byte[] seed = new SecureRandom().generateSeed(8); <add> this.random = new Random(new BigInteger(seed).longValue()); <add> } <add> <add> public UUID generateId() { <add> <add> byte[] randomBytes = new byte[16]; <add> this.random.nextBytes(randomBytes); <add> <add> long mostSigBits = 0; <add> for (int i = 0; i < 8; i++) { <add> mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff); <add> } <add> long leastSigBits = 0; <add> for (int i = 8; i < 16; i++) { <add> leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff); <add> } <add> <add> return new UUID(mostSigBits, leastSigBits); <add> } <add> } <add> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging; <add> <add>import java.io.ByteArrayInputStream; <add>import java.io.ByteArrayOutputStream; <add>import java.io.ObjectInputStream; <add>import java.io.ObjectOutputStream; <add>import java.util.HashMap; <add>import java.util.Map; <add>import java.util.Set; <add> <add>import org.junit.Test; <add> <add>import static org.junit.Assert.*; <add> <add>/** <add> * Test fixture for {@link MessageHeaders}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class MessageHeadersTests { <add> <add> <add> @Test <add> public void testTimestamp() { <add> MessageHeaders headers = new MessageHeaders(null); <add> assertNotNull(headers.getTimestamp()); <add> } <add> <add> @Test <add> public void testTimestampOverwritten() throws Exception { <add> MessageHeaders headers1 = new MessageHeaders(null); <add> Thread.sleep(50L); <add> MessageHeaders headers2 = new MessageHeaders(headers1); <add> assertNotSame(headers1.getTimestamp(), headers2.getTimestamp()); <add> } <add> <add> @Test <add> public void testIdOverwritten() throws Exception { <add> MessageHeaders headers1 = new MessageHeaders(null); <add> MessageHeaders headers2 = new MessageHeaders(headers1); <add> assertNotSame(headers1.getId(), headers2.getId()); <add> } <add> <add> @Test <add> public void testId() { <add> MessageHeaders headers = new MessageHeaders(null); <add> assertNotNull(headers.getId()); <add> } <add> <add> @Test <add> public void testNonTypedAccessOfHeaderValue() { <add> Integer value = new Integer(123); <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("test", value); <add> MessageHeaders headers = new MessageHeaders(map); <add> assertEquals(value, headers.get("test")); <add> } <add> <add> @Test <add> public void testTypedAccessOfHeaderValue() { <add> Integer value = new Integer(123); <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("test", value); <add> MessageHeaders headers = new MessageHeaders(map); <add> assertEquals(value, headers.get("test", Integer.class)); <add> } <add> <add> @Test(expected = IllegalArgumentException.class) <add> public void testHeaderValueAccessWithIncorrectType() { <add> Integer value = new Integer(123); <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("test", value); <add> MessageHeaders headers = new MessageHeaders(map); <add> assertEquals(value, headers.get("test", String.class)); <add> } <add> <add> @Test <add> public void testNullHeaderValue() { <add> Map<String, Object> map = new HashMap<String, Object>(); <add> MessageHeaders headers = new MessageHeaders(map); <add> assertNull(headers.get("nosuchattribute")); <add> } <add> <add> @Test <add> public void testNullHeaderValueWithTypedAccess() { <add> Map<String, Object> map = new HashMap<String, Object>(); <add> MessageHeaders headers = new MessageHeaders(map); <add> assertNull(headers.get("nosuchattribute", String.class)); <add> } <add> <add> @Test <add> public void testHeaderKeys() { <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("key1", "val1"); <add> map.put("key2", new Integer(123)); <add> MessageHeaders headers = new MessageHeaders(map); <add> Set<String> keys = headers.keySet(); <add> assertTrue(keys.contains("key1")); <add> assertTrue(keys.contains("key2")); <add> } <add> <add> @Test <add> public void serializeWithAllSerializableHeaders() throws Exception { <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("name", "joe"); <add> map.put("age", 42); <add> MessageHeaders input = new MessageHeaders(map); <add> MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input); <add> assertEquals("joe", output.get("name")); <add> assertEquals(42, output.get("age")); <add> } <add> <add> @Test <add> public void serializeWithNonSerializableHeader() throws Exception { <add> Object address = new Object(); <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("name", "joe"); <add> map.put("address", address); <add> MessageHeaders input = new MessageHeaders(map); <add> MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input); <add> assertEquals("joe", output.get("name")); <add> assertNull(output.get("address")); <add> } <add> <add> <add> private static Object serializeAndDeserialize(Object object) throws Exception { <add> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <add> ObjectOutputStream out = new ObjectOutputStream(baos); <add> out.writeObject(object); <add> out.close(); <add> ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); <add> ObjectInputStream in = new ObjectInputStream(bais); <add> Object result = in.readObject(); <add> in.close(); <add> return result; <add> } <add> <add>}
2
Text
Text
remove ambiguous sentence from a11y quiz step 42
fe045b996b1c40df0d4326824369e7242ad6da49
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145f8f8bcd4370f6509078e.md <ide> California<br /> <ide> USA <ide> ``` <ide> <del>You can visit, but you might not find anything... <del> <ide> # --hints-- <ide> <ide> You should add the above text including the `<br />` tags to the `address` element.
1
Javascript
Javascript
fix lint errors 1/n
5403946f098cc72c3d33ea5cee263fb3dd03891d
<ide><path>packager/src/AssetServer/__tests__/AssetServer-test.js <ide> describe('AssetServer', () => { <ide> imgs: { <ide> 'b.png': 'b image', <ide> '[email protected]': 'b2 image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return Promise.all([ <ide> describe('AssetServer', () => { <ide> 'b.android.png': 'b android image', <ide> 'c.png': 'c general image', <ide> 'c.android.png': 'c android image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return Promise.all([ <ide> describe('AssetServer', () => { <ide> imgs: { <ide> 'b.png': 'png image', <ide> 'b.jpg': 'jpeg image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return Promise.all([ <ide> describe('AssetServer', () => { <ide> '[email protected]': 'b2 image', <ide> '[email protected]': 'b4 image', <ide> '[email protected]': 'b4.5 image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return server.get('imgs/[email protected]').then(data => <ide> describe('AssetServer', () => { <ide> '[email protected]': 'b2 ios image', <ide> '[email protected]': 'b4 ios image', <ide> '[email protected]': 'b4.5 ios image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return Promise.all([ <ide> describe('AssetServer', () => { <ide> '[email protected]': 'b2 image', <ide> '[email protected]': 'b4 image', <ide> '[email protected]': 'b4.5 image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return server.getAssetData('imgs/b.png').then(data => { <ide> describe('AssetServer', () => { <ide> '[email protected]': 'b2 image', <ide> '[email protected]': 'b4 image', <ide> '[email protected]': 'b4.5 image', <del> } <del> } <add> }, <add> }, <ide> }); <ide> <ide> return server.getAssetData('imgs/b.jpg').then(data => { <ide> describe('AssetServer', () => { <ide> '[email protected]': 'b2 image', <ide> '[email protected]': 'b4 image', <ide> '[email protected]': 'b4.5 image', <del> } <del> } <add> }, <add> }, <ide> }; <ide> <del> fs.__setMockFilesystem(mockFS); <add> fs.__setMockFilesystem(mockFS); <ide> }); <ide> <ide> it('uses the file contents to build the hash', () => { <ide><path>packager/src/AssetServer/index.js <ide> const fs = require('fs'); <ide> const getAssetDataFromName = require('../node-haste').getAssetDataFromName; <ide> const path = require('path'); <ide> <del>const createTimeoutPromise = (timeout) => new Promise((resolve, reject) => { <add>const createTimeoutPromise = timeout => new Promise((resolve, reject) => { <ide> setTimeout(reject, timeout, 'fs operation timeout'); <ide> }); <ide> function timeoutableDenodeify(fsFunc, timeout) { <ide> return function raceWrapper(...args) { <ide> return Promise.race([ <ide> createTimeoutPromise(timeout), <del> denodeify(fsFunc).apply(this, args) <add> denodeify(fsFunc).apply(this, args), <ide> ]); <ide> }; <ide> } <ide> class AssetServer { <ide> const map = this._buildAssetMap(dir, files, platform); <ide> <ide> let record; <del> if (platform != null){ <add> if (platform != null) { <ide> record = map[getAssetKey(assetData.assetName, platform)] || <ide> map[assetData.assetName]; <ide> } else { <ide><path>packager/src/Bundler/Bundle.js <ide> class Bundle extends BundleBase { <ide> } <ide> <ide> result.sections.push({ <del> offset: { line: line, column: 0 }, <add> offset: {line, column: 0}, <ide> map: (map: MixedSourceMap), <ide> }); <ide> line += module.code.split('\n').length; <ide> function generateSourceMapForVirtualModule(module): SourceMap { <ide> <ide> return { <ide> version: 3, <del> sources: [ module.sourcePath ], <add> sources: [module.sourcePath], <ide> names: [], <del> mappings: mappings, <add> mappings, <ide> file: module.sourcePath, <del> sourcesContent: [ module.sourceCode ], <add> sourcesContent: [module.sourceCode], <ide> }; <ide> } <ide> <ide><path>packager/src/Bundler/BundleBase.js <ide> class BundleBase { <ide> return this._source; <ide> } <ide> <del> this._source = this._modules.map((module) => module.code).join('\n'); <add> this._source = this._modules.map(module => module.code).join('\n'); <ide> return this._source; <ide> } <ide> <ide><path>packager/src/Bundler/HMRBundle.js <ide> const ModuleTransport = require('../lib/ModuleTransport'); <ide> class HMRBundle extends BundleBase { <ide> constructor({sourceURLFn, sourceMappingURLFn}) { <ide> super(); <del> this._sourceURLFn = sourceURLFn <add> this._sourceURLFn = sourceURLFn; <ide> this._sourceMappingURLFn = sourceMappingURLFn; <ide> this._sourceURLs = []; <ide> this._sourceMappingURLs = []; <ide><path>packager/src/Bundler/__tests__/Bundle-test.js <ide> describe('Bundle', () => { <ide> expect(bundle.getSource({dev: true})).toBe([ <ide> 'transformed foo;', <ide> 'transformed bar;', <del> '\/\/# sourceMappingURL=test_url' <add> '\/\/# sourceMappingURL=test_url', <ide> ].join('\n')); <ide> }); <ide> }); <ide> describe('Bundle', () => { <ide> const resolver = { <ide> wrapModule({name}) { <ide> return new Promise(resolve => resolves[name] = resolve); <del> } <add> }, <ide> }; <ide> <ide> const promise = Promise.all( <ide> describe('Bundle', () => { <ide> file: 'test_url', <ide> version: 3, <ide> sections: [ <del> { offset: { line: 0, column: 0 }, map: { name: 'sourcemap foo' } }, <del> { offset: { line: 2, column: 0 }, map: { name: 'sourcemap bar' } }, <add> {offset: {line: 0, column: 0}, map: {name: 'sourcemap foo'}}, <add> {offset: {line: 2, column: 0}, map: {name: 'sourcemap bar'}}, <ide> { <ide> offset: { <ide> column: 0, <del> line: 4 <add> line: 4, <ide> }, <ide> map: { <ide> file: 'image.png', <ide> mappings: 'AAAA;AACA;', <ide> names: [], <del> sources: [ 'image.png' ], <add> sources: ['image.png'], <ide> sourcesContent: ['image module;\nimage module;'], <ide> version: 3, <del> } <add> }, <ide> }, <ide> { <ide> offset: { <ide> column: 0, <del> line: 6 <add> line: 6, <ide> }, <ide> map: { <ide> file: 'require-InitializeCore.js', <ide> mappings: 'AAAA;', <ide> names: [], <del> sources: [ 'require-InitializeCore.js' ], <add> sources: ['require-InitializeCore.js'], <ide> sourcesContent: [';require("InitializeCore");'], <ide> version: 3, <del> } <add> }, <ide> }, <ide> { <ide> offset: { <ide> column: 0, <del> line: 7 <add> line: 7, <ide> }, <ide> map: { <ide> file: 'require-foo.js', <ide> mappings: 'AAAA;', <ide> names: [], <del> sources: [ 'require-foo.js' ], <add> sources: ['require-foo.js'], <ide> sourcesContent: [';require("foo");'], <ide> version: 3, <del> } <add> }, <ide> }, <ide> ], <ide> }); <ide> describe('Bundle', () => { <ide> const {groups} = bundle.getUnbundle(); <ide> expect(groups).toEqual(new Map([[ <ide> idFor('Product1'), <del> new Set(['React', 'ReactFoo', 'invariant', 'ReactBar', 'cx'].map(idFor)) <add> new Set(['React', 'ReactFoo', 'invariant', 'ReactBar', 'cx'].map(idFor)), <ide> ]])); <ide> }); <ide> <ide><path>packager/src/Bundler/__tests__/Bundler-test.js <ide> describe('Bundler', function() { <ide> <ide> Resolver.mockImplementation(function() { <ide> return { <del> getDependencies: getDependencies, <del> getModuleSystemDependencies: getModuleSystemDependencies, <add> getDependencies, <add> getModuleSystemDependencies, <ide> }; <ide> }); <ide> <ide> fs.statSync.mockImplementation(function() { <ide> return { <del> isDirectory: () => true <add> isDirectory: () => true, <ide> }; <ide> }); <ide> <ide> describe('Bundler', function() { <ide> bundler = new Bundler({ <ide> ...commonOptions, <ide> projectRoots, <del> assetServer: assetServer, <add> assetServer, <ide> }); <ide> <ide> modules = [ <ide> describe('Bundler', function() { <ide> path: '/root/img/new_image.png', <ide> isAsset: true, <ide> resolution: 2, <del> dependencies: [] <add> dependencies: [], <ide> }), <ide> createModule({ <ide> id: 'package/file.json', <ide> describe('Bundler', function() { <ide> }); <ide> <ide> sizeOf.mockImplementation(function(path, cb) { <del> cb(null, { width: 50, height: 100 }); <add> cb(null, {width: 50, height: 100}); <ide> }); <ide> }); <ide> <ide> it('create a bundle', function() { <ide> assetServer.getAssetData.mockImplementation(() => { <ide> return Promise.resolve({ <del> scales: [1,2,3], <add> scales: [1, 2, 3], <ide> files: [ <ide> '/root/img/img.png', <ide> '/root/img/[email protected]', <ide> describe('Bundler', function() { <ide> runModule: true, <ide> sourceMapUrl: 'source_map_url', <ide> }).then(bundle => { <del> const ithAddedModule = (i) => bundle.addModule.mock.calls[i][2].path; <del> <del> expect(ithAddedModule(0)).toEqual('/root/foo.js'); <del> expect(ithAddedModule(1)).toEqual('/root/bar.js'); <del> expect(ithAddedModule(2)).toEqual('/root/img/new_image.png'); <del> expect(ithAddedModule(3)).toEqual('/root/file.json'); <del> <del> expect(bundle.finalize.mock.calls[0]).toEqual([{ <del> runModule: true, <del> runBeforeMainModule: [], <del> allowUpdates: false, <del> }]); <del> <del> expect(bundle.addAsset.mock.calls[0]).toEqual([{ <del> __packager_asset: true, <del> fileSystemLocation: '/root/img', <del> httpServerLocation: '/assets/img', <del> width: 50, <del> height: 100, <del> scales: [1, 2, 3], <del> files: [ <del> '/root/img/img.png', <del> '/root/img/[email protected]', <del> '/root/img/[email protected]', <del> ], <del> hash: 'i am a hash', <del> name: 'img', <del> type: 'png', <del> }]); <add> const ithAddedModule = i => bundle.addModule.mock.calls[i][2].path; <add> <add> expect(ithAddedModule(0)).toEqual('/root/foo.js'); <add> expect(ithAddedModule(1)).toEqual('/root/bar.js'); <add> expect(ithAddedModule(2)).toEqual('/root/img/new_image.png'); <add> expect(ithAddedModule(3)).toEqual('/root/file.json'); <add> <add> expect(bundle.finalize.mock.calls[0]).toEqual([{ <add> runModule: true, <add> runBeforeMainModule: [], <add> allowUpdates: false, <add> }]); <add> <add> expect(bundle.addAsset.mock.calls[0]).toEqual([{ <add> __packager_asset: true, <add> fileSystemLocation: '/root/img', <add> httpServerLocation: '/assets/img', <add> width: 50, <add> height: 100, <add> scales: [1, 2, 3], <add> files: [ <add> '/root/img/img.png', <add> '/root/img/[email protected]', <add> '/root/img/[email protected]', <add> ], <add> hash: 'i am a hash', <add> name: 'img', <add> type: 'png', <add> }]); <ide> <ide> // TODO(amasad) This fails with 0 != 5 in OSS <ide> //expect(ProgressBar.prototype.tick.mock.calls.length).toEqual(modules.length); <del> }); <add> }); <ide> }); <ide> <ide> it('loads and runs asset plugins', function() { <ide> describe('Bundler', function() { <ide> jest.mock('asyncMockPlugin2', () => { <ide> return asset => { <ide> expect(asset.extraReverseHash).toBeDefined(); <del> return new Promise((resolve) => { <add> return new Promise(resolve => { <ide> asset.extraPixelCount = asset.width * asset.height; <ide> resolve(asset); <ide> }); <ide> }; <ide> }, {virtual: true}); <ide> <ide> const mockAsset = { <del> scales: [1,2,3], <add> scales: [1, 2, 3], <ide> files: [ <ide> '/root/img/img.png', <ide> '/root/img/[email protected]', <ide> describe('Bundler', function() { <ide> // jest calledWith does not support jasmine.any <ide> expect(getDependencies.mock.calls[0].slice(0, -2)).toEqual([ <ide> '/root/foo.js', <del> { dev: true, recursive: true }, <del> { minify: false, <add> {dev: true, recursive: true}, <add> {minify: false, <ide> dev: true, <ide> transform: { <ide> dev: true, <ide> hot: false, <ide> generateSourceMaps: false, <ide> projectRoots, <del> } <add> }, <ide> }, <ide> ]) <ide> ); <ide> describe('Bundler', function() { <ide> const b = new Bundler({ <ide> ...commonOptions, <ide> projectRoots, <del> assetServer: assetServer, <add> assetServer, <ide> platforms: ['android', 'vr'], <ide> }); <ide> expect(b._opts.platforms).toEqual(['android', 'vr']); <ide> describe('Bundler', function() { <ide> assetServer.getAssetData.mockImplementation(function(relPath) { <ide> if (relPath === 'img/new_image.png') { <ide> return Promise.resolve({ <del> scales: [1,2,3], <add> scales: [1, 2, 3], <ide> files: [ <ide> '/root/img/new_image.png', <ide> '/root/img/[email protected]', <ide> describe('Bundler', function() { <ide> }); <ide> } else if (relPath === 'img/new_image2.png') { <ide> return Promise.resolve({ <del> scales: [1,2,3], <add> scales: [1, 2, 3], <ide> files: [ <ide> '/root/img/new_image2.png', <ide> '/root/img/[email protected]', <ide> describe('Bundler', function() { <ide> path: '/root/img/new_image2.png', <ide> isAsset: true, <ide> resolution: 2, <del> dependencies: [] <add> dependencies: [], <ide> }), <ide> ); <ide> <ide> return bundler.getOrderedDependencyPaths('/root/foo.js', true) <del> .then((paths) => expect(paths).toEqual([ <add> .then(paths => expect(paths).toEqual([ <ide> '/root/foo.js', <ide> '/root/bar.js', <ide> '/root/img/new_image.png', <ide><path>packager/src/Bundler/index.js <ide> class Bundler { <ide> }); <ide> } <ide> <del> getOrderedDependencyPaths({ entryFile, dev, platform }: { <add> getOrderedDependencyPaths({entryFile, dev, platform}: { <ide> entryFile: string, <ide> dev: boolean, <ide> platform: string, <ide> }) { <ide> return this.getDependencies({entryFile, dev, platform}).then( <del> ({ dependencies }) => { <add> ({dependencies}) => { <ide> const ret = []; <ide> const promises = []; <ide> const placeHolder = {}; <ide> class Bundler { <ide> }); <ide> <ide> return Promise.all(promises).then(assetsData => { <del> assetsData.forEach(({ files }) => { <add> assetsData.forEach(({files}) => { <ide> const index = ret.indexOf(placeHolder); <ide> ret.splice(index, 1, ...files); <ide> }); <ide> class Bundler { <ide> map, <ide> meta: {dependencies, dependencyOffsets, preloaded, dependencyPairs}, <ide> sourceCode: source, <del> sourcePath: module.path <add> sourcePath: module.path, <ide> }); <ide> }); <ide> } <ide> class Bundler { <ide> // Test extension against all types supported by image-size module. <ide> // If it's not one of these, we won't treat it as an image. <ide> const isImage = [ <del> 'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff' <add> 'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff', <ide> ].indexOf(extname(module.path).slice(1)) !== -1; <ide> <del> return this._assetServer.getAssetData(relPath, platform).then((assetData) => { <add> return this._assetServer.getAssetData(relPath, platform).then(assetData => { <ide> return Promise.all([isImage ? sizeOf(assetData.files[0]) : null, assetData]); <del> }).then((res) => { <add> }).then(res => { <ide> const dimensions = res[0]; <ide> const assetData = res[1]; <ide> const scale = assetData.scales[0]; <ide> class Bundler { <ide> }; <ide> <ide> return this._applyAssetPlugins(assetPlugins, asset); <del> }).then((asset) => { <add> }).then(asset => { <ide> const json = JSON.stringify(filterObject(asset, assetPropertyBlacklist)); <ide> const assetRegistryPath = 'react-native/Libraries/Image/AssetRegistry'; <ide> const code = <ide> class Bundler { <ide> return { <ide> asset, <ide> code, <del> meta: {dependencies, dependencyOffsets} <add> meta: {dependencies, dependencyOffsets}, <ide> }; <ide> }); <ide> } <ide> class Bundler { <ide> name, <ide> id: moduleId, <ide> code, <del> meta: meta, <add> meta, <ide> sourceCode: code, <ide> sourcePath: module.path, <ide> virtual: true, <ide><path>packager/src/Bundler/source-map/__tests__/source-map-test.js <ide> describe('build map from raw mappings', () => { <ide> [1, 2], <ide> [3, 4, 5, 6, 'apples'], <ide> [7, 8, 9, 10], <del> [11, 12, 13, 14, 'pears'] <add> [11, 12, 13, 14, 'pears'], <ide> ], <ide> sourceCode: 'code1', <ide> sourcePath: 'path1', <ide> describe('build map from raw mappings', () => { <ide> [11, 12], <ide> [13, 14, 15, 16, 'bananas'], <ide> [17, 18, 19, 110], <del> [21, 112, 113, 114, 'pears'] <add> [21, 112, 113, 114, 'pears'], <ide> ], <ide> sourceCode: 'code3', <ide> sourcePath: 'path3', <ide><path>packager/src/Bundler/source-map/encode.js <ide> function encode(value: number, buffer: Buffer, position: number): number { <ide> let digit, vlq = toVLQSigned(value); <ide> do { <ide> digit = vlq & VLQ_BASE_MASK; <del> vlq = vlq >>> VLQ_BASE_SHIFT; <add> vlq >>>= VLQ_BASE_SHIFT; <ide> if (vlq > 0) { <ide> // There are still more digits in this value, so we must make sure the <ide> // continuation bit is marked. <del> digit = digit | VLQ_CONTINUATION_BIT; <add> digit |= VLQ_CONTINUATION_BIT; <ide> } <ide> buffer[position++] = CHAR_MAP[digit]; <ide> } while (vlq > 0); <ide><path>packager/src/Bundler/source-map/source-map.js <ide> function fromRawMappings(modules: Array<ModuleTransport>): Generator { <ide> ); <ide> } <ide> <del> carryOver = carryOver + countLines(code); <add> carryOver += countLines(code); <ide> } <ide> <ide> return generator; <ide><path>packager/src/JSTransformer/__mocks__/worker.js <ide> */ <ide> 'use strict'; <ide> <del>module.exports = function (data, callback) { <add>module.exports = function(data, callback) { <ide> callback(null, {}); <ide> }; <ide><path>packager/src/JSTransformer/index.js <ide> function makeFarm(worker, methods, timeout) { <ide> { <ide> autoStart: true, <ide> maxConcurrentCallsPerWorker: 1, <del> maxConcurrentWorkers: maxConcurrentWorkers, <add> maxConcurrentWorkers, <ide> maxCallsPerWorker: MAX_CALLS_PER_WORKER, <ide> maxCallTime: timeout, <ide> maxRetries: MAX_RETRIES, <ide><path>packager/src/JSTransformer/worker/__tests__/worker-test.js <ide> describe('code transformation worker:', () => { <ide> it('calls back with the result of the transform in the cache', done => { <ide> const result = { <ide> code: 'some.other(code)', <del> map: {} <add> map: {}, <ide> }; <ide> <ide> transformCode(transformer, 'filename', result.code, {}, (error, data) => { <ide> describe('code transformation worker:', () => { <ide> const code = '{a:1,b:2}'; <ide> const filePath = 'arbitrary/file.json'; <ide> transformCode(transformer, filePath, code, {}, (error, data) => { <del> expect(error).toBeNull(); <del> expect(data.result.code).toEqual(code); <del> done(); <del> }, <add> expect(error).toBeNull(); <add> expect(data.result.code).toEqual(code); <add> done(); <add> }, <ide> ); <ide> } <ide> ); <ide> describe('code transformation worker:', () => { <ide> it('passes the transformed code the `extractDependencies`', done => { <ide> const code = 'arbitrary(code)'; <ide> <del> transformCode(transformer, 'filename', code, {}, (error) => { <add> transformCode(transformer, 'filename', code, {}, error => { <ide> expect(error).toBeNull(); <ide> expect(extractDependencies).toBeCalledWith(code); <ide> done(); <ide> describe('code transformation worker:', () => { <ide> it('does not extract requires if files are marked as "extern"', done => { <ide> const opts = {extern: true}; <ide> transformCode(transformer, 'filename', 'code', opts, (error, data) => { <del> expect(error).toBeNull(); <del> const {dependencies, dependencyOffsets} = data.result; <del> expect(extractDependencies).not.toBeCalled(); <del> expect(dependencies).toEqual([]); <del> expect(dependencyOffsets).toEqual([]); <del> done(); <add> expect(error).toBeNull(); <add> const {dependencies, dependencyOffsets} = data.result; <add> expect(extractDependencies).not.toBeCalled(); <add> expect(dependencies).toEqual([]); <add> expect(dependencyOffsets).toEqual([]); <add> done(); <ide> }); <ide> }); <ide> <ide> it('does not extract requires of JSON files', done => { <ide> const jsonStr = '{"arbitrary":"json"}'; <ide> transformCode(transformer, 'arbitrary.json', jsonStr, {}, (error, data) => { <del> expect(error).toBeNull(); <del> const {dependencies, dependencyOffsets} = data.result; <del> expect(extractDependencies).not.toBeCalled(); <del> expect(dependencies).toEqual([]); <del> expect(dependencyOffsets).toEqual([]); <del> done(); <del> } <add> expect(error).toBeNull(); <add> const {dependencies, dependencyOffsets} = data.result; <add> expect(extractDependencies).not.toBeCalled(); <add> expect(dependencies).toEqual([]); <add> expect(dependencyOffsets).toEqual([]); <add> done(); <add> } <ide> ); <ide> }); <ide> }); <ide> describe('code transformation worker:', () => { <ide> options = {minify: true, transform: {generateSourceMaps: true}}; <ide> dependencyData = { <ide> dependencies: ['a', 'b', 'c'], <del> dependencyOffsets: [100, 120, 140] <add> dependencyOffsets: [100, 120, 140], <ide> }; <ide> <ide> extractDependencies.mockImplementation( <ide><path>packager/src/JSTransformer/worker/constant-folding.js <ide> const plugin = { <ide> path.replaceWith(value ? node.right : left); <ide> } <ide> } <del> } <add> }, <ide> }, <ide> UnaryExpression: { <ide> exit(path) { <ide> const node = path.node; <ide> if (node.operator === '!' && t.isLiteral(node.argument)) { <ide> path.replaceWith(t.valueToNode(!node.argument.value)); <ide> } <del> } <add> }, <ide> }, <ide> }, <ide> }; <ide><path>packager/src/JSTransformer/worker/extract-dependencies.js <ide> function extractDependencies(code: string) { <ide> } <ide> dependencyOffsets.push(arg.start); <ide> dependencies.add(arg.value); <del> } <add> }, <ide> }); <ide> <ide> return {dependencyOffsets, dependencies: Array.from(dependencies)}; <ide><path>packager/src/JSTransformer/worker/inline.js <ide> const dev = {name: '__DEV__'}; <ide> <ide> const importMap = new Map([['ReactNative', 'react-native']]); <ide> <del>const isGlobal = (binding) => !binding; <add>const isGlobal = binding => !binding; <ide> <ide> const isToplevelBinding = (binding, isWrappedModule) => <ide> isGlobal(binding) || <ide> const inlinePlugin = { <ide> <ide> path.replaceWith(replacement); <ide> } <del> } <add> }, <ide> }, <ide> }; <ide> <ide><path>packager/src/JSTransformer/worker/worker.js <ide> function transformCode( <ide> action_name: 'Transforming file', <ide> action_phase: 'end', <ide> file_name: filename, <del> duration_ms: duration_ms, <add> duration_ms, <ide> log_entry_label: 'Transforming file', <ide> }; <ide> <ide><path>packager/src/ModuleGraph/__tests__/Graph-test.js <ide> describe('Graph:', () => { <ide> }); <ide> <ide> it('calls back an error when called without any entry point', done => { <del> graph([], anyPlatform, {log: quiet}, (error) => { <add> graph([], anyPlatform, {log: quiet}, error => { <ide> expect(error).toEqual(any(Error)); <ide> done(); <ide> }); <ide> describe('Graph:', () => { <ide> <ide> const ids = [ <ide> 'a', <del> 'b', <del> 'c', 'd', <del> 'e', <del> 'f', 'g', <del> 'h', <add> 'b', <add> 'c', 'd', <add> 'e', <add> 'f', 'g', <add> 'h', <ide> ]; <ide> ids.forEach(id => { <ide> const path = idToPath(id); <ide> function createFile(id) { <ide> function createModule(id, dependencies = []): Module { <ide> return { <ide> file: createFile(id), <del> dependencies: dependencies.map(createDependency) <add> dependencies: dependencies.map(createDependency), <ide> }; <ide> } <ide> <ide><path>packager/src/ModuleGraph/node-haste/Package.js <ide> function getReplacements(pkg) { <ide> <ide> const main = getMain(pkg); <ide> if (typeof rn !== 'object') { <del> rn = { [main]: rn }; <add> rn = {[main]: rn}; <ide> } <ide> <ide> if (typeof browser !== 'object') { <del> browser = { [main]: browser }; <add> browser = {[main]: browser}; <ide> } <ide> <ide> // merge with "browser" as default, <ide> // "react-native" as override <del> return { ...browser, ...rn }; <add> return {...browser, ...rn}; <ide> } <ide><path>packager/src/ModuleGraph/node-haste/node-haste.js <ide> <ide> 'use strict'; <ide> <del>import type { // eslint-disable-line sort-requires <add> import type { // eslint-disable-line sort-requires <ide> Extensions, <ide> Path, <ide> } from './node-haste.flow'; <ide> <del>import type { <add> import type { <ide> ResolveFn, <ide> TransformedFile, <ide> } from '../types.flow'; <ide> <del>const DependencyGraphHelpers = require('../../node-haste/DependencyGraph/DependencyGraphHelpers'); <del>const HasteFS = require('./HasteFS'); <del>const HasteMap = require('../../node-haste/DependencyGraph/HasteMap'); <del>const Module = require('./Module'); <del>const ModuleCache = require('./ModuleCache'); <del>const ResolutionRequest = require('../../node-haste/DependencyGraph/ResolutionRequest'); <add> const DependencyGraphHelpers = require('../../node-haste/DependencyGraph/DependencyGraphHelpers'); <add> const HasteFS = require('./HasteFS'); <add> const HasteMap = require('../../node-haste/DependencyGraph/HasteMap'); <add> const Module = require('./Module'); <add> const ModuleCache = require('./ModuleCache'); <add> const ResolutionRequest = require('../../node-haste/DependencyGraph/ResolutionRequest'); <ide> <del>const defaults = require('../../../defaults'); <add> const defaults = require('../../../defaults'); <ide> <del>type ResolveOptions = {| <add> type ResolveOptions = {| <ide> assetExts: Extensions, <ide> extraNodeModules: {[id: string]: string}, <ide> transformedFiles: {[path: Path]: TransformedFile}, <ide> |}; <ide> <del>const platforms = new Set(defaults.platforms); <add> const platforms = new Set(defaults.platforms); <ide> <del>exports.createResolveFn = function(options: ResolveOptions): ResolveFn { <del> const { <add> exports.createResolveFn = function(options: ResolveOptions): ResolveFn { <add> const { <ide> assetExts, <ide> extraNodeModules, <ide> transformedFiles, <ide> } = options; <del> const files = Object.keys(transformedFiles); <del> const getTransformedFile = <add> const files = Object.keys(transformedFiles); <add> const getTransformedFile = <ide> path => Promise.resolve( <ide> transformedFiles[path] || Promise.reject(new Error(`"${path} does not exist`)) <ide> ); <ide> <del> const helpers = new DependencyGraphHelpers({ <del> assetExts, <del> providesModuleNodeModules: defaults.providesModuleNodeModules, <del> }); <add> const helpers = new DependencyGraphHelpers({ <add> assetExts, <add> providesModuleNodeModules: defaults.providesModuleNodeModules, <add> }); <ide> <del> const hasteFS = new HasteFS(files); <del> const moduleCache = new ModuleCache( <add> const hasteFS = new HasteFS(files); <add> const moduleCache = new ModuleCache( <ide> filePath => hasteFS.closest(filePath, 'package.json'), <ide> getTransformedFile, <ide> ); <del> const hasteMap = new HasteMap({ <del> extensions: ['js', 'json'], <del> files, <del> helpers, <del> moduleCache, <del> platforms, <del> preferNativePlatform: true, <del> }); <add> const hasteMap = new HasteMap({ <add> extensions: ['js', 'json'], <add> files, <add> helpers, <add> moduleCache, <add> platforms, <add> preferNativePlatform: true, <add> }); <ide> <del> const hasteMapBuilt = hasteMap.build(); <del> const resolutionRequests = {}; <del> return (id, source, platform, _, callback) => { <del> let resolutionRequest = resolutionRequests[platform]; <del> if (!resolutionRequest) { <del> resolutionRequest = resolutionRequests[platform] = new ResolutionRequest({ <del> dirExists: filePath => hasteFS.dirExists(filePath), <del> entryPath: '', <del> extraNodeModules, <del> hasteFS, <del> hasteMap, <del> helpers, <del> moduleCache, <del> platform, <del> platforms, <del> preferNativePlatform: true, <del> }); <del> } <add> const hasteMapBuilt = hasteMap.build(); <add> const resolutionRequests = {}; <add> return (id, source, platform, _, callback) => { <add> let resolutionRequest = resolutionRequests[platform]; <add> if (!resolutionRequest) { <add> resolutionRequest = resolutionRequests[platform] = new ResolutionRequest({ <add> dirExists: filePath => hasteFS.dirExists(filePath), <add> entryPath: '', <add> extraNodeModules, <add> hasteFS, <add> hasteMap, <add> helpers, <add> moduleCache, <add> platform, <add> platforms, <add> preferNativePlatform: true, <add> }); <add> } <ide> <del> const from = new Module(source, moduleCache, getTransformedFile(source)); <del> hasteMapBuilt <add> const from = new Module(source, moduleCache, getTransformedFile(source)); <add> hasteMapBuilt <ide> .then(() => resolutionRequest.resolveDependency(from, id)) <ide> .then( <ide> // nextTick to escape promise error handling <ide> module => process.nextTick(callback, null, module.path), <ide> error => process.nextTick(callback, error), <ide> ); <del> }; <del>}; <add> }; <add> }; <ide><path>packager/src/ModuleGraph/output/as-plain-bundle.js <ide> module.exports = ( <ide> if (file.map) { <ide> sections.push({ <ide> map: file.map, <del> offset: {column: 0, line} <add> offset: {column: 0, line}, <ide> }); <ide> } <ide> line += countLines(moduleCode); <ide><path>packager/src/ModuleGraph/output/util.js <ide> function virtualModule(code: string) { <ide> code, <ide> path: '', <ide> type: 'script', <del> } <add> }, <ide> }; <ide> } <ide><path>packager/src/ModuleGraph/worker/__tests__/optimize-module-test.js <ide> describe('optimizing JS modules', () => { <ide> const result = optimizeModule(transformResult, optimizationOptions); <ide> optimized = result.transformed.default; <ide> injectedVars = optimized.code.match(/function\(([^)]*)/)[1].split(','); <del> [,requireName,,, dependencyMapName] = injectedVars; <add> [, requireName,,, dependencyMapName] = injectedVars; <ide> }); <ide> <ide> it('optimizes code', () => { <ide><path>packager/src/ModuleGraph/worker/__tests__/transform-module-test.js <ide> function createTestData() { <ide> if (path.node.callee.name === 'some') { <ide> path.replaceWith(path.node.arguments[0]); <ide> } <del> } <add> }, <ide> }); <ide> return { <ide> bodyAst: fileAst.program.body, <ide><path>packager/src/Resolver/__tests__/Resolver-test.js <ide> describe('Resolver', function() { <ide> .getDependencies(entry, {platform}, transformOptions); <ide> expect(DependencyGraph.prototype.getDependencies).toBeCalledWith({ <ide> entryPath: entry, <del> platform: platform, <del> transformOptions: transformOptions, <add> platform, <add> transformOptions, <ide> recursive: true, <ide> }); <ide> }); <ide> describe('Resolver', function() { <ide> return depResolver <ide> .getDependencies( <ide> '/root/index.js', <del> { dev: false }, <add> {dev: false}, <ide> undefined, <ide> undefined, <ide> createGetModuleId() <ide> describe('Resolver', function() { <ide> .createPolyfill <ide> .mock <ide> .calls <del> .map((call) => call[0])) <add> .map(call => call[0])) <ide> .toEqual([ <del> { id: 'polyfills/Object.es6.js', <add> {id: 'polyfills/Object.es6.js', <ide> file: 'polyfills/Object.es6.js', <del> dependencies: [] <add> dependencies: [], <ide> }, <del> { id: 'polyfills/console.js', <add> {id: 'polyfills/console.js', <ide> file: 'polyfills/console.js', <ide> dependencies: [ <del> 'polyfills/Object.es6.js' <add> 'polyfills/Object.es6.js', <ide> ], <ide> }, <del> { id: 'polyfills/error-guard.js', <add> {id: 'polyfills/error-guard.js', <ide> file: 'polyfills/error-guard.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <del> 'polyfills/console.js' <add> 'polyfills/console.js', <ide> ], <ide> }, <del> { id: 'polyfills/Number.es6.js', <add> {id: 'polyfills/Number.es6.js', <ide> file: 'polyfills/Number.es6.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> 'polyfills/console.js', <del> 'polyfills/error-guard.js' <add> 'polyfills/error-guard.js', <ide> ], <ide> }, <del> { id: 'polyfills/String.prototype.es6.js', <add> {id: 'polyfills/String.prototype.es6.js', <ide> file: 'polyfills/String.prototype.es6.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> 'polyfills/Number.es6.js', <ide> ], <ide> }, <del> { id: 'polyfills/Array.prototype.es6.js', <add> {id: 'polyfills/Array.prototype.es6.js', <ide> file: 'polyfills/Array.prototype.es6.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> 'polyfills/String.prototype.es6.js', <ide> ], <ide> }, <del> { id: 'polyfills/Array.es6.js', <add> {id: 'polyfills/Array.es6.js', <ide> file: 'polyfills/Array.es6.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> 'polyfills/Array.prototype.es6.js', <ide> ], <ide> }, <del> { id: 'polyfills/Object.es7.js', <add> {id: 'polyfills/Object.es7.js', <ide> file: 'polyfills/Object.es7.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> 'polyfills/Array.es6.js', <ide> ], <ide> }, <del> { id: 'polyfills/babelHelpers.js', <add> {id: 'polyfills/babelHelpers.js', <ide> file: 'polyfills/babelHelpers.js', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> ].map(({id, file, dependencies}) => ({ <ide> id: pathJoin(__dirname, '..', id), <ide> file: pathJoin(__dirname, '..', file), <del> dependencies: dependencies.map((d => pathJoin(__dirname, '..', d))), <add> dependencies: dependencies.map(d => pathJoin(__dirname, '..', d)), <ide> }))); <ide> }); <ide> }); <ide> describe('Resolver', function() { <ide> return depResolver <ide> .getDependencies( <ide> '/root/index.js', <del> { dev: true }, <add> {dev: true}, <ide> undefined, <ide> undefined, <ide> createGetModuleId() <ide> describe('Resolver', function() { <ide> return depResolver <ide> .getDependencies( <ide> '/root/index.js', <del> { dev: false }, <add> {dev: false}, <ide> undefined, <ide> undefined, <ide> createGetModuleId() <del> ).then((result) => { <add> ).then(result => { <ide> expect(result.mainModuleId).toEqual('index'); <ide> expect(DependencyGraph.prototype.createPolyfill.mock.calls[result.dependencies.length - 2]).toEqual([ <del> { file: 'some module', <add> {file: 'some module', <ide> id: 'some module', <ide> dependencies: [ <ide> 'polyfills/Object.es6.js', <ide> describe('Resolver', function() { <ide> 'polyfills/Array.es6.js', <ide> 'polyfills/Object.es7.js', <ide> 'polyfills/babelHelpers.js', <del> ].map(d => pathJoin(__dirname, '..', d)) <add> ].map(d => pathJoin(__dirname, '..', d)), <ide> }, <ide> ]); <ide> }); <ide><path>packager/src/Resolver/index.js <ide> class Resolver { <ide> forceNodeFilesystemAPI: false, <ide> getTransformCacheKey: opts.getTransformCacheKey, <ide> globalTransformCache: opts.globalTransformCache, <del> ignoreFilePath: function(filepath) { <add> ignoreFilePath(filepath) { <ide> return filepath.indexOf('__tests__') !== -1 || <ide> (opts.blacklistRE != null && opts.blacklistRE.test(filepath)); <ide> }, <ide> function defineModuleCode(moduleName, code, verboseName = '', dev = true) { <ide> return [ <ide> `__d(/* ${verboseName} */`, <ide> 'function(global, require, module, exports) {', // module factory <del> code, <add> code, <ide> '\n}, ', <ide> `${JSON.stringify(moduleName)}`, // module id, null = id map. used in ModuleGraph <ide> dev ? `, null, ${JSON.stringify(verboseName)}` : '', <ide><path>packager/src/Resolver/polyfills/error-guard.js <ide> let _globalHandler = function onError(e) { <ide> * set) globally before requiring anything. <ide> */ <ide> const ErrorUtils = { <del> setGlobalHandler: function(fun) { <add> setGlobalHandler(fun) { <ide> _globalHandler = fun; <ide> }, <del> getGlobalHandler: function() { <add> getGlobalHandler() { <ide> return _globalHandler; <ide> }, <del> reportError: function(error) { <add> reportError(error) { <ide> _globalHandler && _globalHandler(error); <ide> }, <del> reportFatalError: function(error) { <add> reportFatalError(error) { <ide> _globalHandler && _globalHandler(error, true); <ide> }, <del> applyWithGuard: function(fun, context, args) { <add> applyWithGuard(fun, context, args) { <ide> try { <ide> _inGuard++; <ide> return fun.apply(context, args); <ide> const ErrorUtils = { <ide> _inGuard--; <ide> } <ide> }, <del> applyWithGuardIfNeeded: function(fun, context, args) { <add> applyWithGuardIfNeeded(fun, context, args) { <ide> if (ErrorUtils.inGuard()) { <ide> return fun.apply(context, args); <ide> } else { <ide> ErrorUtils.applyWithGuard(fun, context, args); <ide> } <ide> }, <del> inGuard: function() { <add> inGuard() { <ide> return _inGuard; <ide> }, <del> guard: function(fun, name, context) { <add> guard(fun, name, context) { <ide> if (typeof fun !== 'function') { <ide> console.warn('A function must be passed to ErrorUtils.guard, got ', fun); <ide> return null; <ide> const ErrorUtils = { <ide> } <ide> <ide> return guarded; <del> } <add> }, <ide> }; <ide> <ide> global.ErrorUtils = ErrorUtils; <ide><path>packager/src/Resolver/polyfills/require.js <ide> <ide> 'use strict'; <ide> <del>declare var __DEV__: boolean; <add> declare var __DEV__: boolean; <ide> <del>type DependencyMap = Array<ModuleID>; <del>type Exports = any; <del>type FactoryFn = ( <add> type DependencyMap = Array<ModuleID>; <add> type Exports = any; <add> type FactoryFn = ( <ide> global: Object, <ide> require: RequireFn, <ide> moduleObject: {exports: {}}, <ide> exports: {}, <ide> dependencyMap: ?DependencyMap, <ide> ) => void; <del>type HotModuleReloadingAcceptFn = Function; <del>type HotModuleReloadingData = {| <add> type HotModuleReloadingAcceptFn = Function; <add> type HotModuleReloadingData = {| <ide> acceptCallback: ?HotModuleReloadingAcceptFn, <ide> accept: (callback: HotModuleReloadingAcceptFn) => void, <ide> |}; <del>type Module = { <add> type Module = { <ide> exports: Exports, <ide> hot?: HotModuleReloadingData, <ide> }; <del>type ModuleID = number; <del>type ModuleDefinition = {| <add> type ModuleID = number; <add> type ModuleDefinition = {| <ide> dependencyMap: ?DependencyMap, <ide> exports: Exports, <ide> factory: FactoryFn, <ide> type ModuleDefinition = {| <ide> isInitialized: boolean, <ide> verboseName?: string, <ide> |}; <del>type ModuleMap = <add> type ModuleMap = <ide> {[key: ModuleID]: (ModuleDefinition)}; <del>type RequireFn = (id: ModuleID | VerboseModuleNameForDev) => Exports; <del>type VerboseModuleNameForDev = string; <add> type RequireFn = (id: ModuleID | VerboseModuleNameForDev) => Exports; <add> type VerboseModuleNameForDev = string; <ide> <del>global.require = require; <del>global.__d = define; <add> global.require = require; <add> global.__d = define; <ide> <del>const modules: ModuleMap = Object.create(null); <del>if (__DEV__) { <del> var verboseNamesToModuleIds: {[key: string]: number} = Object.create(null); <del>} <add> const modules: ModuleMap = Object.create(null); <add> if (__DEV__) { <add> var verboseNamesToModuleIds: {[key: string]: number} = Object.create(null); <add> } <ide> <del>function define( <add> function define( <ide> factory: FactoryFn, <ide> moduleId: number, <ide> dependencyMap?: DependencyMap, <ide> ) { <del> if (moduleId in modules) { <add> if (moduleId in modules) { <ide> // prevent repeated calls to `global.nativeRequire` to overwrite modules <ide> // that are already loaded <del> return; <del> } <del> modules[moduleId] = { <del> dependencyMap, <del> exports: undefined, <del> factory, <del> hasError: false, <del> isInitialized: false, <del> }; <del> if (__DEV__) { <add> return; <add> } <add> modules[moduleId] = { <add> dependencyMap, <add> exports: undefined, <add> factory, <add> hasError: false, <add> isInitialized: false, <add> }; <add> if (__DEV__) { <ide> // HMR <del> modules[moduleId].hot = createHotReloadingObject(); <add> modules[moduleId].hot = createHotReloadingObject(); <ide> <ide> // DEBUGGABLE MODULES NAMES <ide> // we take `verboseName` from `arguments` to avoid an unused named parameter <ide> // in `define` in production. <del> const verboseName: string | void = arguments[3]; <del> if (verboseName) { <del> modules[moduleId].verboseName = verboseName; <del> verboseNamesToModuleIds[verboseName] = moduleId; <del> } <del> } <del>} <del> <del>function require(moduleId: ModuleID | VerboseModuleNameForDev) { <del> if (__DEV__ && typeof moduleId === 'string') { <del> const verboseName = moduleId; <del> moduleId = verboseNamesToModuleIds[moduleId]; <del> if (moduleId == null) { <del> throw new Error(`Unknown named module: '${verboseName}'`); <del> } else { <del> console.warn( <add> const verboseName: string | void = arguments[3]; <add> if (verboseName) { <add> modules[moduleId].verboseName = verboseName; <add> verboseNamesToModuleIds[verboseName] = moduleId; <add> } <add> } <add> } <add> <add> function require(moduleId: ModuleID | VerboseModuleNameForDev) { <add> if (__DEV__ && typeof moduleId === 'string') { <add> const verboseName = moduleId; <add> moduleId = verboseNamesToModuleIds[moduleId]; <add> if (moduleId == null) { <add> throw new Error(`Unknown named module: '${verboseName}'`); <add> } else { <add> console.warn( <ide> `Requiring module '${verboseName}' by name is only supported for ` + <ide> 'debugging purposes and will BREAK IN PRODUCTION!' <ide> ); <del> } <del> } <add> } <add> } <ide> <ide> //$FlowFixMe: at this point we know that moduleId is a number <del> const moduleIdReallyIsNumber: number = moduleId; <del> const module = modules[moduleIdReallyIsNumber]; <del> return module && module.isInitialized <add> const moduleIdReallyIsNumber: number = moduleId; <add> const module = modules[moduleIdReallyIsNumber]; <add> return module && module.isInitialized <ide> ? module.exports <ide> : guardedLoadModule(moduleIdReallyIsNumber, module); <del>} <del> <del>let inGuard = false; <del>function guardedLoadModule(moduleId: ModuleID , module) { <del> if (!inGuard && global.ErrorUtils) { <del> inGuard = true; <del> let returnValue; <del> try { <del> returnValue = loadModuleImplementation(moduleId, module); <del> } catch (e) { <del> global.ErrorUtils.reportFatalError(e); <del> } <del> inGuard = false; <del> return returnValue; <del> } else { <del> return loadModuleImplementation(moduleId, module); <del> } <del>} <del> <del>function loadModuleImplementation(moduleId, module) { <del> const nativeRequire = global.nativeRequire; <del> if (!module && nativeRequire) { <del> nativeRequire(moduleId); <del> module = modules[moduleId]; <del> } <del> <del> if (!module) { <del> throw unknownModuleError(moduleId); <del> } <del> <del> if (module.hasError) { <del> throw moduleThrewError(moduleId); <del> } <add> } <add> <add> let inGuard = false; <add> function guardedLoadModule(moduleId: ModuleID, module) { <add> if (!inGuard && global.ErrorUtils) { <add> inGuard = true; <add> let returnValue; <add> try { <add> returnValue = loadModuleImplementation(moduleId, module); <add> } catch (e) { <add> global.ErrorUtils.reportFatalError(e); <add> } <add> inGuard = false; <add> return returnValue; <add> } else { <add> return loadModuleImplementation(moduleId, module); <add> } <add> } <add> <add> function loadModuleImplementation(moduleId, module) { <add> const nativeRequire = global.nativeRequire; <add> if (!module && nativeRequire) { <add> nativeRequire(moduleId); <add> module = modules[moduleId]; <add> } <add> <add> if (!module) { <add> throw unknownModuleError(moduleId); <add> } <add> <add> if (module.hasError) { <add> throw moduleThrewError(moduleId); <add> } <ide> <ide> // `require` calls int the require polyfill itself are not analyzed and <ide> // replaced so that they use numeric module IDs. <ide> // The systrace module will expose itself on the require function so that <ide> // it can be used here. <ide> // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686) <del> if (__DEV__) { <del> var {Systrace} = require; <del> } <add> if (__DEV__) { <add> var {Systrace} = require; <add> } <ide> <ide> // We must optimistically mark module as initialized before running the <ide> // factory to keep any require cycles inside the factory from causing an <ide> // infinite require loop. <del> module.isInitialized = true; <del> const exports = module.exports = {}; <del> const {factory, dependencyMap} = module; <del> try { <del> if (__DEV__) { <add> module.isInitialized = true; <add> const exports = module.exports = {}; <add> const {factory, dependencyMap} = module; <add> try { <add> if (__DEV__) { <ide> // $FlowFixMe: we know that __DEV__ is const and `Systrace` exists <del> Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId)); <del> } <add> Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId)); <add> } <ide> <del> const moduleObject: Module = {exports}; <del> if (__DEV__ && module.hot) { <del> moduleObject.hot = module.hot; <del> } <add> const moduleObject: Module = {exports}; <add> if (__DEV__ && module.hot) { <add> moduleObject.hot = module.hot; <add> } <ide> <ide> // keep args in sync with with defineModuleCode in <ide> // packager/src//Resolver/index.js <ide> // and packager/src//ModuleGraph/worker.js <del> factory(global, require, moduleObject, exports, dependencyMap); <add> factory(global, require, moduleObject, exports, dependencyMap); <ide> <ide> // avoid removing factory in DEV mode as it breaks HMR <del> if (!__DEV__) { <add> if (!__DEV__) { <ide> // $FlowFixMe: This is only sound because we never access `factory` again <del> module.factory = undefined; <del> } <add> module.factory = undefined; <add> } <ide> <del> if (__DEV__) { <add> if (__DEV__) { <ide> // $FlowFixMe: we know that __DEV__ is const and `Systrace` exists <del> Systrace.endEvent(); <del> } <del> return (module.exports = moduleObject.exports); <del> } catch (e) { <del> module.hasError = true; <del> module.isInitialized = false; <del> module.exports = undefined; <del> throw e; <del> } <del>} <del> <del>function unknownModuleError(id) { <del> let message = 'Requiring unknown module "' + id + '".'; <del> if (__DEV__) { <del> message += <add> Systrace.endEvent(); <add> } <add> return (module.exports = moduleObject.exports); <add> } catch (e) { <add> module.hasError = true; <add> module.isInitialized = false; <add> module.exports = undefined; <add> throw e; <add> } <add> } <add> <add> function unknownModuleError(id) { <add> let message = 'Requiring unknown module "' + id + '".'; <add> if (__DEV__) { <add> message += <ide> 'If you are sure the module is there, try restarting the packager or running "npm install".'; <del> } <del> return Error(message); <del>} <add> } <add> return Error(message); <add> } <ide> <del>function moduleThrewError(id) { <del> return Error('Requiring module "' + id + '", which threw an exception.'); <del>} <add> function moduleThrewError(id) { <add> return Error('Requiring module "' + id + '", which threw an exception.'); <add> } <ide> <del>if (__DEV__) { <del> require.Systrace = { beginEvent: () => {}, endEvent: () => {} }; <add> if (__DEV__) { <add> require.Systrace = {beginEvent: () => {}, endEvent: () => {}}; <ide> <ide> // HOT MODULE RELOADING <del> var createHotReloadingObject = function() { <del> const hot: HotModuleReloadingData = { <del> acceptCallback: null, <del> accept: callback => { hot.acceptCallback = callback; }, <del> }; <del> return hot; <del> }; <del> <del> const acceptAll = function( <add> var createHotReloadingObject = function() { <add> const hot: HotModuleReloadingData = { <add> acceptCallback: null, <add> accept: callback => { hot.acceptCallback = callback; }, <add> }; <add> return hot; <add> }; <add> <add> const acceptAll = function( <ide> dependentModules, <ide> inverseDependencies, <ide> ) { <del> if (!dependentModules || dependentModules.length === 0) { <del> return true; <del> } <add> if (!dependentModules || dependentModules.length === 0) { <add> return true; <add> } <ide> <del> const notAccepted = dependentModules.filter( <add> const notAccepted = dependentModules.filter( <ide> module => !accept(module, /*factory*/ undefined, inverseDependencies)); <ide> <del> const parents = []; <del> for (let i = 0; i < notAccepted.length; i++) { <add> const parents = []; <add> for (let i = 0; i < notAccepted.length; i++) { <ide> // if the module has no parents then the change cannot be hot loaded <del> if (inverseDependencies[notAccepted[i]].length === 0) { <del> return false; <del> } <add> if (inverseDependencies[notAccepted[i]].length === 0) { <add> return false; <add> } <ide> <del> parents.push(...inverseDependencies[notAccepted[i]]); <del> } <add> parents.push(...inverseDependencies[notAccepted[i]]); <add> } <ide> <del> return acceptAll(parents, inverseDependencies); <del> }; <add> return acceptAll(parents, inverseDependencies); <add> }; <ide> <del> const accept = function( <add> const accept = function( <ide> id: ModuleID, <ide> factory?: FactoryFn, <ide> inverseDependencies: {[key: ModuleID]: Array<ModuleID>}, <ide> ) { <del> const mod = modules[id]; <add> const mod = modules[id]; <ide> <del> if (!mod && factory) { // new modules need a factory <del> define(factory, id); <del> return true; // new modules don't need to be accepted <del> } <add> if (!mod && factory) { // new modules need a factory <add> define(factory, id); <add> return true; // new modules don't need to be accepted <add> } <ide> <del> const {hot} = mod; <del> if (!hot) { <del> console.warn( <add> const {hot} = mod; <add> if (!hot) { <add> console.warn( <ide> 'Cannot accept module because Hot Module Replacement ' + <ide> 'API was not installed.' <ide> ); <del> return false; <del> } <add> return false; <add> } <ide> <ide> // replace and initialize factory <del> if (factory) { <del> mod.factory = factory; <del> } <del> mod.hasError = false; <del> mod.isInitialized = false; <del> require(id); <del> <del> if (hot.acceptCallback) { <del> hot.acceptCallback(); <del> return true; <del> } else { <add> if (factory) { <add> mod.factory = factory; <add> } <add> mod.hasError = false; <add> mod.isInitialized = false; <add> require(id); <add> <add> if (hot.acceptCallback) { <add> hot.acceptCallback(); <add> return true; <add> } else { <ide> // need to have inverseDependencies to bubble up accept <del> if (!inverseDependencies) { <del> throw new Error('Undefined `inverseDependencies`'); <del> } <add> if (!inverseDependencies) { <add> throw new Error('Undefined `inverseDependencies`'); <add> } <ide> <ide> // accept parent modules recursively up until all siblings are accepted <del> return acceptAll(inverseDependencies[id], inverseDependencies); <del> } <del> }; <add> return acceptAll(inverseDependencies[id], inverseDependencies); <add> } <add> }; <ide> <del> global.__accept = accept; <del>} <add> global.__accept = accept; <add> } <ide><path>packager/src/Server/MultipartResponse.js <ide> class MultipartResponse { <ide> <ide> static serializeHeaders(headers) { <ide> return Object.keys(headers) <del> .map((key) => `${key}: ${headers[key]}`) <add> .map(key => `${key}: ${headers[key]}`) <ide> .join(CRLF); <ide> } <ide> } <ide><path>packager/src/Server/__tests__/MultipartResponse-test.js <ide> function mockNodeResponse() { <ide> headers = {...headers, ...hdrs}; <ide> }), <ide> setHeader: jest.fn((key, val) => { headers[key] = val; }), <del> write: jest.fn((data) => { body += data; }), <del> end: jest.fn((data) => { body += (data || ''); }), <add> write: jest.fn(data => { body += data; }), <add> end: jest.fn(data => { body += (data || ''); }), <ide> <ide> // For testing only <ide> toString() { <ide> function mockNodeResponse() { <ide> '', <ide> body, <ide> ].join('\r\n'); <del> } <add> }, <ide> }; <ide> } <del> <ide><path>packager/src/Server/__tests__/Server-test.js <ide> jest.disableAutomock(); <ide> <ide> jest.mock('worker-farm', () => () => () => {}) <del> .mock('timers', () => ({ setImmediate: (fn) => setTimeout(fn, 0) })) <add> .mock('timers', () => ({setImmediate: fn => setTimeout(fn, 0)})) <ide> .mock('uglify-js') <ide> .mock('crypto') <ide> .mock( <ide> describe('processRequest', () => { <ide> let server; <ide> <ide> const options = { <del> projectRoots: ['root'], <del> blacklistRE: null, <del> cacheVersion: null, <del> polyfillModuleNames: null, <del> reporter: require('../../lib/reporting').nullReporter, <add> projectRoots: ['root'], <add> blacklistRE: null, <add> cacheVersion: null, <add> polyfillModuleNames: null, <add> reporter: require('../../lib/reporting').nullReporter, <ide> }; <ide> <ide> const makeRequest = (reqHandler, requrl, reqOptions) => new Promise(resolve => <ide> reqHandler( <del> { url: requrl, headers:{}, ...reqOptions }, <add> {url: requrl, headers:{}, ...reqOptions}, <ide> { <ide> statusCode: 200, <ide> headers: {}, <ide> describe('processRequest', () => { <ide> resolve(this); <ide> }, <ide> }, <del> { next: () => {} }, <add> {next: () => {}}, <ide> ) <ide> ); <ide> <ide> describe('processRequest', () => { <ide> return makeRequest( <ide> requestHandler, <ide> 'mybundle.bundle?runModule=true', <del> { headers : { 'if-none-match' : 'this is an etag' } } <add> {headers : {'if-none-match' : 'this is an etag'}} <ide> ).then(response => { <ide> expect(response.statusCode).toEqual(304); <ide> }); <ide> describe('processRequest', () => { <ide> expect(bundleFunc.mock.calls.length).toBe(2); <ide> }); <ide> jest.runAllTicks(); <del> }); <add> }); <ide> }); <ide> <ide> describe('/onchange endpoint', () => { <ide> describe('processRequest', () => { <ide> req.url = '/onchange'; <ide> res = { <ide> writeHead: jest.fn(), <del> end: jest.fn() <add> end: jest.fn(), <ide> }; <ide> }); <ide> <ide> describe('processRequest', () => { <ide> describe('buildbundle(options)', () => { <ide> it('Calls the bundler with the correct args', () => { <ide> return server.buildBundle({ <del> entryFile: 'foo file' <add> entryFile: 'foo file', <ide> }).then(() => <ide> expect(Bundler.prototype.bundle).toBeCalledWith({ <ide> entryFile: 'foo file', <ide> describe('processRequest', () => { <ide> return makeRequest( <ide> requestHandler, <ide> '/symbolicate', <del> { rawBody: body } <add> {rawBody: body} <ide> ).then(response => { <ide> expect(response.statusCode).toEqual(500); <ide> expect(JSON.parse(response.body)).toEqual({ <ide><path>packager/src/Server/index.js <ide> const { <ide> <ide> function debounceAndBatch(fn, delay) { <ide> let timeout, args = []; <del> return (value) => { <add> return value => { <ide> args.push(value); <ide> clearTimeout(timeout); <ide> timeout = setTimeout(() => { <ide> class Server { <ide> <ide> watchers.forEach(function(w) { <ide> w.res.writeHead(205, headers); <del> w.res.end(JSON.stringify({ changed: true })); <add> w.res.end(JSON.stringify({changed: true})); <ide> }); <ide> <ide> this._changeWatchers = []; <ide> class Server { <ide> const watchers = this._changeWatchers; <ide> <ide> watchers.push({ <del> req: req, <del> res: res, <add> req, <add> res, <ide> }); <ide> <ide> req.on('close', () => { <ide> class Server { <ide> <ide> optionsHash(options: {}) { <ide> // onProgress is a function, can't be serialized <del> return JSON.stringify(Object.assign({}, options, { onProgress: null })); <add> return JSON.stringify(Object.assign({}, options, {onProgress: null})); <ide> } <ide> <ide> /** <ide> class Server { <ide> <ide> debug('Successfully updated existing bundle'); <ide> return bundle; <add> }); <add> }).catch(e => { <add> debug('Failed to update existing bundle, rebuilding...', e.stack || e.message); <add> return bundleFromScratch(); <ide> }); <del> }).catch(e => { <del> debug('Failed to update existing bundle, rebuilding...', e.stack || e.message); <del> return bundleFromScratch(); <del> }); <ide> return this._reportBundlePromise(options, bundlePromise); <ide> } else { <ide> debug('Using cached bundle'); <ide> class Server { <ide> }).then( <ide> stack => { <ide> debug('Symbolication done'); <del> res.end(JSON.stringify({stack: stack})); <add> res.end(JSON.stringify({stack})); <ide> process.nextTick(() => { <ide> log(createActionEndEntry(symbolicatingLogEntry)); <ide> }); <ide> class Server { <ide> query: urlObj.query, <ide> search: urlObj.search, <ide> }), <del> entryFile: entryFile, <add> entryFile, <ide> dev, <ide> minify, <ide> hot: this._getBoolOptionFromQuery(urlObj.query, 'hot', false), <ide> class Server { <ide> 'inlineSourceMap', <ide> false <ide> ), <del> platform: platform, <add> platform, <ide> entryModuleOnly: this._getBoolOptionFromQuery( <ide> urlObj.query, <ide> 'entryModuleOnly', <ide><path>packager/src/Server/symbolicate/symbolicate.js <ide> function startupChild(socket) { <ide> child.removeAllListeners(); <ide> resolve(child); <ide> }); <del> child.send(socket); <add> child.send(socket); <ide> }); <ide> } <ide> <ide><path>packager/src/Server/symbolicate/worker.js <ide> function symbolicateStack(data) { <ide> } <ide> <ide> function mapFrame(frame, consumers) { <del> const sourceUrl = frame.file; <del> const consumer = consumers.get(sourceUrl); <del> if (consumer == null) { <del> return frame; <del> } <del> const original = consumer.originalPositionFor({ <del> line: frame.lineNumber, <del> column: frame.column, <del> }); <del> if (!original) { <del> return frame; <del> } <del> return Object.assign({}, frame, { <del> file: original.source, <del> lineNumber: original.line, <del> column: original.column, <del> }); <add> const sourceUrl = frame.file; <add> const consumer = consumers.get(sourceUrl); <add> if (consumer == null) { <add> return frame; <add> } <add> const original = consumer.originalPositionFor({ <add> line: frame.lineNumber, <add> column: frame.column, <add> }); <add> if (!original) { <add> return frame; <add> } <add> return Object.assign({}, frame, { <add> file: original.source, <add> lineNumber: original.line, <add> column: original.column, <add> }); <ide> } <ide> <ide> function makeErrorMessage(error) { <ide><path>packager/src/lib/TerminalReporter.js <ide> class TerminalReporter { <ide> constructor() { <ide> this._dependencyGraphHasLoaded = false; <ide> this._activeBundles = new Map(); <del> this._scheduleUpdateBundleProgress = throttle((data) => { <add> this._scheduleUpdateBundleProgress = throttle(data => { <ide> this.update({...data, type: 'bundle_transform_progressed_throttled'}); <ide> }, 200); <ide> } <ide><path>packager/src/lib/TransformCache.js <ide> export type GetTransformCacheKey = (sourceCode: string, filename: string, option <ide> * will be, for example, installed in a different `node_modules/` folder for <ide> * different projects. <ide> */ <del>const getCacheDirPath = (function () { <add>const getCacheDirPath = (function() { <ide> let dirPath; <del> return function () { <add> return function() { <ide> if (dirPath == null) { <ide> dirPath = path.join( <ide> require('os').tmpdir(), <ide> module.exports = { <ide> const msg = result ? 'Cache hit: ' : 'Cache miss: '; <ide> debugRead(msg + props.filePath); <ide> return result; <del> } <add> }, <ide> }; <ide><path>packager/src/lib/__mocks__/TransformCache.js <ide> const mock = { <ide> }, <ide> }; <ide> <del>const transformCacheKeyOf = (props) => <add>const transformCacheKeyOf = props => <ide> props.filePath + '-' + imurmurhash(props.sourceCode) <ide> .hash(props.getTransformCacheKey(props.sourceCode, props.filePath, props.transformOptions)) <ide> .hash(jsonStableStringify(props.transformOptions || {})) <ide><path>packager/src/lib/__mocks__/declareOpts.js <ide> module.exports = function(declared) { <ide> return function(opts) { <ide> for (var p in declared) { <del> if (opts[p] == null && declared[p].default != null){ <add> if (opts[p] == null && declared[p].default != null) { <ide> opts[p] = declared[p].default; <ide> } <ide> } <ide><path>packager/src/lib/__tests__/BatchProcessor-test.js <ide> describe('BatchProcessor', () => { <ide> const batches = []; <ide> let concurrency = 0; <ide> let maxConcurrency = 0; <del> const bp = new BatchProcessor(options, (items) => new Promise(resolve => { <add> const bp = new BatchProcessor(options, items => new Promise(resolve => { <ide> ++concurrency; <ide> expect(concurrency).toBeLessThanOrEqual(options.concurrency); <ide> maxConcurrency = Math.max(maxConcurrency, concurrency); <ide> describe('BatchProcessor', () => { <ide> <ide> it('report errors', async () => { <ide> const error = new Error('oh noes'); <del> const bp = new BatchProcessor(options, (items) => new Promise((_, reject) => { <add> const bp = new BatchProcessor(options, items => new Promise((_, reject) => { <ide> setTimeout(reject.bind(null, error), 0); <ide> })); <ide> let receivedError; <ide><path>packager/src/lib/__tests__/TransformCache-test.js <ide> jest.mock('fs', () => ({ <ide> readdirSync(dirPath) { <ide> // Not required for it to work. <ide> return []; <del> } <add> }, <ide> })); <ide> <ide> jest.mock('write-file-atomic', () => ({ <ide><path>packager/src/lib/__tests__/declareOpts-test.js <ide> describe('declareOpts', function() { <ide> age: { <ide> type: 'number', <ide> default: 21, <del> } <add> }, <ide> }); <del> var opts = validate({ name: 'fooer' }); <add> var opts = validate({name: 'fooer'}); <ide> <ide> expect(opts).toEqual({ <ide> name: 'fooer', <del> age: 21 <add> age: 21, <ide> }); <ide> }); <ide> <ide> describe('declareOpts', function() { <ide> stuff: { <ide> type: 'object', <ide> required: true, <del> } <add> }, <ide> }); <ide> <del> var opts = validate({ things: [1, 2, 3], stuff: {hai: 1} }); <add> var opts = validate({things: [1, 2, 3], stuff: {hai: 1}}); <ide> expect(opts).toEqual({ <del> things: [1,2,3], <add> things: [1, 2, 3], <ide> stuff: {hai: 1}, <ide> }); <ide> }); <ide> describe('declareOpts', function() { <ide> foo: { <ide> required: true, <ide> type: 'number', <del> } <add> }, <ide> }); <ide> <ide> expect(function() { <ide> describe('declareOpts', function() { <ide> var validate = declareOpts({ <ide> foo: { <ide> required: true, <del> type: 'number' <del> } <add> type: 'number', <add> }, <ide> }); <ide> <ide> expect(function() { <ide> describe('declareOpts', function() { <ide> foo: { <ide> required: true, <ide> type: 'number', <del> } <add> }, <ide> }); <ide> <ide> expect(function() { <ide><path>packager/src/lib/relativizeSourceMap.js <ide> <ide> const path = require('path'); <ide> <del>import type { MixedSourceMap } from './SourceMap'; <add>import type {MixedSourceMap} from './SourceMap'; <ide> <ide> function relativizeSourceMapInternal(sourceMap: any, sourcesRoot: string) { <ide> if (sourceMap.sections) { <ide><path>packager/src/node-haste/AssetModule.js <ide> class AssetModule extends Module { <ide> <ide> constructor(args: ConstructorArgs & {dependencies: Array<string>}, platforms: Set<string>) { <ide> super(args); <del> const { resolution, name, type } = getAssetDataFromName(this.path, platforms); <add> const {resolution, name, type} = getAssetDataFromName(this.path, platforms); <ide> this.resolution = resolution; <ide> this._name = name; <ide> this._type = type; <ide><path>packager/src/node-haste/Cache/__tests__/Cache-test.js <ide> describe('Cache', () => { <ide> }); <ide> <ide> describe('writing cache to disk', () => { <del> it('should write cache to disk', (done) => { <add> it('should write cache to disk', done => { <ide> var index = 0; <ide> var mtimes = [10, 20, 30]; <ide> <ide><path>packager/src/node-haste/DependencyGraph/DependencyGraphHelpers.js <ide> class DependencyGraphHelpers { <ide> _providesModuleNodeModules: Array<string>; <ide> _assetExts: Array<string>; <ide> <del> constructor({ providesModuleNodeModules, assetExts }: { <add> constructor({providesModuleNodeModules, assetExts}: { <ide> providesModuleNodeModules: Array<string>, <ide> assetExts: Array<string>, <ide> }) { <ide><path>packager/src/node-haste/DependencyGraph/ResolutionRequest.js <ide> class ResolutionRequest { <ide> } <ide> <ide> _tryResolve(action: () => Promise<string>, secondaryAction: () => ?Promise<string>) { <del> return action().catch((error) => { <add> return action().catch(error => { <ide> if (error.type !== 'UnableToResolveError') { <ide> throw error; <ide> } <ide> class ResolutionRequest { <ide> return Promise.resolve(this._immediateResolutionCache[resHash]); <ide> } <ide> <del> const cacheResult = (result) => { <add> const cacheResult = result => { <ide> this._immediateResolutionCache[resHash] = result; <ide> return result; <ide> }; <ide> class ResolutionRequest { <ide> p = Promise.resolve(toModuleName); <ide> } <ide> <del> return p.then((realModuleName) => { <add> return p.then(realModuleName => { <ide> let dep = this._hasteMap.getModule(realModuleName, this._platform); <ide> if (dep && dep.type === 'Module') { <ide> return dep; <ide> class ResolutionRequest { <ide> if (this._hasteFS.exists(packageJsonPath)) { <ide> return this._moduleCache.getPackage(packageJsonPath) <ide> .getMain().then( <del> (main) => this._tryResolve( <add> main => this._tryResolve( <ide> () => this._loadAsFile(main, fromModule, toModule), <ide> () => this._loadAsDir(main, fromModule, toModule) <ide> ) <ide><path>packager/src/node-haste/Package.js <ide> function getReplacements(pkg) { <ide> if (typeof rn === 'string') { <ide> /* $FlowFixMe: It is likely unsafe to assume all packages would <ide> * contain a "main" */ <del> rn = { [pkg.main]: rn }; <add> rn = {[pkg.main]: rn}; <ide> } <ide> <ide> if (typeof browser === 'string') { <ide> /* $FlowFixMe: It is likely unsafe to assume all packages would <ide> * contain a "main" */ <del> browser = { [pkg.main]: browser }; <add> browser = {[pkg.main]: browser}; <ide> } <ide> <ide> // merge with "browser" as default, <ide> // "react-native" as override <ide> // $FlowFixMe(>=0.35.0) browser and rn should be objects <del> return { ...browser, ...rn }; <add> return {...browser, ...rn}; <ide> } <ide> <ide> module.exports = Package; <ide><path>packager/src/node-haste/__mocks__/graceful-fs.js <ide> fs.realpath.mockImplementation((filepath, callback) => { <ide> callback(null, filepath); <ide> }); <ide> <del>fs.readdirSync.mockImplementation((filepath) => Object.keys(getToNode(filepath))); <add>fs.readdirSync.mockImplementation(filepath => Object.keys(getToNode(filepath))); <ide> <ide> fs.readdir.mockImplementation((filepath, callback) => { <ide> callback = asyncCallback(callback); <ide> fs.createReadStream.mockImplementation(filepath => { <ide> read() { <ide> this.push(file, 'utf8'); <ide> this.push(null); <del> } <add> }, <ide> }); <ide> }); <ide> <ide> fs.createWriteStream.mockImplementation(file => { <ide> const writeStream = new stream.Writable({ <ide> write(chunk) { <ide> this.__chunks.push(chunk); <del> } <add> }, <ide> }); <ide> writeStream.__file = file; <ide> writeStream.__chunks = []; <ide> fs.createWriteStream.mockImplementation(file => { <ide> }); <ide> fs.createWriteStream.mock.returned = []; <ide> <del>fs.__setMockFilesystem = (object) => (filesystem = object); <add>fs.__setMockFilesystem = object => (filesystem = object); <ide> <ide> function getToNode(filepath) { <ide> // Ignore the drive for Windows paths. <ide> function getToNode(filepath) { <ide> throw new Error('Make sure all paths are absolute.'); <ide> } <ide> let node = filesystem; <del> parts.slice(1).forEach((part) => { <add> parts.slice(1).forEach(part => { <ide> if (node && node.SYMLINK) { <ide> node = getToNode(node.SYMLINK); <ide> } <ide><path>packager/src/node-haste/__tests__/DependencyGraph-test.js <ide> describe('DependencyGraph', function() { <ide> function getOrderedDependenciesAsJSON(dgraph, entryPath, platform, recursive = true) { <ide> return dgraph.getDependencies({entryPath, platform, recursive}) <ide> .then(response => response.finalize()) <del> .then(({ dependencies }) => Promise.all(dependencies.map(dep => Promise.all([ <add> .then(({dependencies}) => Promise.all(dependencies.map(dep => Promise.all([ <ide> dep.getName(), <ide> dep.getDependencies(), <ide> ]).then(([name, moduleDependencies]) => ({ <ide> describe('DependencyGraph', function() { <ide> ...defaults, <ide> roots: [root], <ide> }); <del> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js', null, false).then((deps) => { <add> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js', null, false).then(deps => { <ide> expect(deps) <ide> .toEqual([ <ide> { <ide> describe('DependencyGraph', function() { <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/client.js', <add> {id: 'aPackage/client.js', <ide> path: '/root/aPackage/client.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/client.js', <add> {id: 'aPackage/client.js', <ide> path: '/root/aPackage/client.js', <ide> dependencies: ['./node', './dir/server.js'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/not-node.js', <add> {id: 'aPackage/not-node.js', <ide> path: '/root/aPackage/not-node.js', <ide> dependencies: ['./not-browser'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/browser.js', <add> {id: 'aPackage/browser.js', <ide> path: '/root/aPackage/browser.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['node-package'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'browser-package/index.js', <add> {id: 'browser-package/index.js', <ide> path: '/root/aPackage/browser-package/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['./dir/ooga'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/dir/ooga.js', <add> {id: 'aPackage/dir/ooga.js', <ide> path: '/root/aPackage/dir/ooga.js', <ide> dependencies: ['node-package'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/dir/browser.js', <add> {id: 'aPackage/dir/browser.js', <ide> path: '/root/aPackage/dir/browser.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['node-package'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'browser-package/index.js', <add> {id: 'browser-package/index.js', <ide> path: '/root/aPackage/browser-package/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['booga'], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['node-package'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'rn-package/index.js', <add> {id: 'rn-package/index.js', <ide> path: '/root/aPackage/node_modules/rn-package/index.js', <ide> dependencies: ['nested-package'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'nested-browser-package/index.js', <add> {id: 'nested-browser-package/index.js', <ide> path: '/root/aPackage/node_modules/nested-browser-package/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { <ide> expect(deps) <ide> .toEqual([ <del> { id: 'index', <add> {id: 'index', <ide> path: '/root/index.js', <ide> dependencies: ['aPackage'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'aPackage/index.js', <add> {id: 'aPackage/index.js', <ide> path: '/root/aPackage/index.js', <ide> dependencies: ['node-package-a', 'node-package-b', 'node-package-c'], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'rn-package-a/index.js', <add> {id: 'rn-package-a/index.js', <ide> path: '/root/aPackage/node_modules/rn-package-a/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'rn-package-b/index.js', <add> {id: 'rn-package-b/index.js', <ide> path: '/root/aPackage/node_modules/rn-package-b/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> isJSON: false, <ide> isPolyfill: false, <ide> resolution: undefined, <ide> }, <del> { id: 'rn-package-d/index.js', <add> {id: 'rn-package-d/index.js', <ide> path: '/root/aPackage/node_modules/rn-package-d/index.js', <ide> dependencies: [], <ide> isAsset: false, <ide> describe('DependencyGraph', function() { <ide> setMockFileSystem({ <ide> [root.slice(1)]: { <ide> 'index.js': 'require("bar")', <del> 'node_modules': { 'bar.js': '' }, <del> 'provides-bar': { 'index.js': '' }, <add> 'node_modules': {'bar.js': ''}, <add> 'provides-bar': {'index.js': ''}, <ide> }, <ide> }); <ide> <ide> describe('DependencyGraph', function() { <ide> ...defaults, <ide> roots: [root], <ide> }); <del> return getOrderedDependenciesAsJSON(dgraph, 'C:\\root\\index.js').then((deps) => { <add> return getOrderedDependenciesAsJSON(dgraph, 'C:\\root\\index.js').then(deps => { <ide> expect(deps) <ide> .toEqual([ <ide> { <ide> describe('DependencyGraph', function() { <ide> resolution: undefined, <ide> }, <ide> ]); <del> }); <add> }); <ide> }); <ide> }); <ide> <ide><path>packager/src/node-haste/__tests__/Module-test.js <ide> describe('Module', () => { <ide> }); <ide> <ide> let transformCacheKey; <del> const createModule = (options) => <add> const createModule = options => <ide> new Module({ <ide> options: { <ide> cacheTransformResults: true, <ide> describe('Module', () => { <ide> }); <ide> <ide> const createJSONModule = <del> (options) => createModule({...options, file: '/root/package.json'}); <add> options => createModule({...options, file: '/root/package.json'}); <ide> <ide> beforeEach(function() { <ide> process.platform = 'linux'; <ide> describe('Module', () => { <ide> }; <ide> const module = createModule({transformCode}); <ide> <del> return module.read().then((result) => { <add> return module.read().then(result => { <ide> expect(result).toEqual(jasmine.objectContaining(transformResult)); <ide> }); <ide> }); <ide> describe('Module', () => { <ide> cacheTransformResults: false, <ide> }}); <ide> <del> return module.read().then((result) => { <add> return module.read().then(result => { <ide> expect(result).toEqual({ <ide> dependencies: ['foo', 'bar'], <ide> }); <ide> describe('Module', () => { <ide> }; <ide> const module = createModule({transformCode, options: undefined}); <ide> <del> return module.read().then((result) => { <del> expect(result).toEqual({ ...transformResult, source: 'arbitrary(code);'}); <add> return module.read().then(result => { <add> expect(result).toEqual({...transformResult, source: 'arbitrary(code);'}); <ide> }); <ide> }); <ide> <ide><path>packager/src/node-haste/index.js <ide> class DependencyGraph { <ide> dir = path.dirname(dir); <ide> } while (dir !== '.' && dir !== root); <ide> return null; <del> } <add> }, <ide> }, this._opts.platforms); <ide> <ide> this._hasteMap = new HasteMap({ <ide><path>packager/src/node-haste/lib/__tests__/getInverseDependencies-test.js <ide> describe('getInverseDependencies', () => { <ide> <ide> const resolutionResponse = { <ide> dependencies: [module1, module2, module3, module4], <del> getResolvedDependencyPairs: (module) => { <add> getResolvedDependencyPairs: module => { <ide> return modulePairs[module.hash()]; <ide> }, <ide> }; <ide><path>packager/src/node-haste/lib/getAssetDataFromName.js <ide> function getAssetDataFromName(filename, platforms) { <ide> assetName = decodeURIComponent(assetName); <ide> <ide> return { <del> resolution: resolution, <del> assetName: assetName, <add> resolution, <add> assetName, <ide> type: ext.slice(1), <ide> name: path.basename(assetName, ext), <ide> platform: platformExt,
54
Text
Text
fix broken link
b5ecc8da181a40c710684e8c501e8d5bb95e2150
<ide><path>docs/Navigation.md <ide> This guide covers the various navigation components available in React Native. I <ide> <ide> ## Navigator <ide> <del>`Navigator` provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize. This is the same component you used to build your first navigation stack in the [navigators tutorial](docs/navigators.html). <add>`Navigator` provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize. This is the same component you used to build your first navigation stack in the [navigators tutorial](docs/using-navigators.html). <ide> <ide> ![](img/NavigationStack-Navigator.gif) <ide>
1
Ruby
Ruby
restore check for broken xcode-select path
1f622843844e5d52d598c2f8be360a13416454c9
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_xcode_prefix <ide> <ide> def check_xcode_select_path <ide> # with the advent of CLT-only support, we don't need xcode-select <del> return if MacOS::CLT.installed? <del> unless File.file? "#{MacOS::Xcode.folder}/usr/bin/xcodebuild" and not MacOS::Xcode.bad_xcode_select_path? <add> <add> if MacOS::Xcode.bad_xcode_select_path? <add> <<-EOS.undent <add> Your xcode-select path is set to / <add> You must unset it or builds will hang: <add> sudo rm /usr/share/xcode-select/xcode_dir_link <add> EOS <add> elsif not MacOS::CLT.installed? and not File.file? "#{MacOS::Xcode.folder}/usr/bin/xcodebuild" <ide> path = MacOS.app_with_bundle_id(MacOS::Xcode::V4_BUNDLE_ID) || MacOS.app_with_bundle_id(MacOS::Xcode::V3_BUNDLE_ID) <ide> path = '/Developer' if path.nil? or not path.directory? <ide> <<-EOS.undent
1
Go
Go
increase test timeouts for node state changes
2e5da4434126309f2395cc3d5b2013674155ae5c
<ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) testAPISwarmManualAcceptance(c *check.C, secret strin <ide> if info.LocalNodeState == swarm.LocalNodeStateActive { <ide> break <ide> } <del> if i > 10 { <del> c.Errorf("node did not become active") <add> if i > 100 { <add> c.Fatalf("node did not become active") <ide> } <ide> time.Sleep(200 * time.Millisecond) <ide> } <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> if info.ControlAvailable { <ide> break <ide> } <del> if i > 10 { <add> if i > 100 { <ide> c.Errorf("node did not turn into manager") <ide> } else { <ide> break <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> if !info.ControlAvailable { <ide> break <ide> } <del> if i > 10 { <add> if i > 100 { <ide> c.Errorf("node did not turn into manager") <ide> } else { <ide> break <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> <ide> go d2.Join("nosuchhost:1234", "", "", false) // will block on pending state <ide> <del> time.Sleep(1 * time.Second) <del> <del> info, err := d2.info() <del> c.Assert(err, checker.IsNil) <del> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <add> for i := 0; ; i++ { <add> info, err := d2.info() <add> c.Assert(err, checker.IsNil) <add> if info.LocalNodeState == swarm.LocalNodeStatePending { <add> break <add> } <add> if i > 100 { <add> c.Fatalf("node did not go to pending state: %v", info.LocalNodeState) <add> } <add> time.Sleep(100 * time.Millisecond) <add> } <ide> <ide> c.Assert(d2.Leave(true), checker.IsNil) <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmRestoreOnPendingJoin(c *check.C) { <ide> if info.LocalNodeState == swarm.LocalNodeStatePending { <ide> break <ide> } <del> if i > 10 { <add> if i > 100 { <ide> c.Fatalf("node did not go to pending state: %v", info.LocalNodeState) <ide> } <ide> time.Sleep(100 * time.Millisecond)
1
Python
Python
fix breakage on mask addition to batch norm
2f59b1b7c2a2d352ec2de14fd52ac425959bad79
<ide><path>keras/layers/normalization/batch_normalization.py <ide> def _calculate_mean_and_var( <ide> return self._sync_calculate_mean_and_var( <ide> inputs, reduction_axes, keep_dims, mask=mask <ide> ) <add> return self._no_sync_calculate_mean_and_var( <add> inputs, reduction_axes, keep_dims, mask=mask <add> ) <add> <add> def _no_sync_calculate_mean_and_var( <add> self, inputs, reduction_axes, keep_dims, mask=None <add> ): <ide> if mask is None: <ide> return tf.nn.moments(inputs, reduction_axes, keepdims=keep_dims) <ide> else: <ide> def _sync_calculate_mean_and_var(self, x, axes, keep_dims, mask=None): <ide> replica_ctx = tf.distribute.get_replica_context() <ide> <ide> if not replica_ctx: <del> return super()._calculate_mean_and_var( <add> return self._no_sync_calculate_mean_and_var( <ide> x, axes, keep_dims, mask=mask <ide> ) <ide>
1
Javascript
Javascript
add hmm and hmmss formatting tokens
0fce088830b264c7137a28179053b8df4a312f30
<ide><path>src/lib/format/format.js <ide> import zeroFill from '../utils/zero-fill'; <ide> <del>export var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; <add>export var formattingTokens = /(\[[^\[]*\])|(\\)?(hmmss|hmm|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; <ide> <ide> var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; <ide> <ide><path>src/lib/parse/regex.js <ide> export var match3 = /\d{3}/; // 000 - 999 <ide> export var match4 = /\d{4}/; // 0000 - 9999 <ide> export var match6 = /[+-]?\d{6}/; // -999999 - 999999 <ide> export var match1to2 = /\d\d?/; // 0 - 99 <add>export var match3to4 = /\d\d\d\d?/; // 999 - 9999 <add>export var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 <ide> export var match1to3 = /\d{1,3}/; // 0 - 999 <ide> export var match1to4 = /\d{1,4}/; // 0 - 9999 <ide> export var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 <ide><path>src/lib/units/hour.js <ide> import { makeGetSet } from '../moment/get-set'; <ide> import { addFormatToken } from '../format/format'; <ide> import { addUnitAlias } from './aliases'; <del>import { addRegexToken, match1to2, match2 } from '../parse/regex'; <add>import { addRegexToken, match1to2, match2, match3to4, match5to6 } from '../parse/regex'; <ide> import { addParseToken } from '../parse/token'; <del>import { HOUR } from './constants'; <add>import { HOUR, MINUTE, SECOND } from './constants'; <ide> import toInt from '../utils/to-int'; <add>import zeroFill from '../utils/zero-fill'; <ide> import getParsingFlags from '../create/parsing-flags'; <ide> <ide> // FORMATTING <ide> <del>addFormatToken('H', ['HH', 2], 0, 'hour'); <del>addFormatToken('h', ['hh', 2], 0, function () { <add>function hFormat() { <ide> return this.hours() % 12 || 12; <add>} <add> <add>addFormatToken('H', ['HH', 2], 0, 'hour'); <add>addFormatToken('h', ['hh', 2], 0, hFormat); <add> <add>addFormatToken('hmm', 0, 0, function () { <add> return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); <add>}); <add> <add>addFormatToken('hmmss', 0, 0, function () { <add> return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + <add> zeroFill(this.seconds(), 2); <ide> }); <ide> <ide> function meridiem (token, lowercase) { <ide> addRegexToken('h', match1to2); <ide> addRegexToken('HH', match1to2, match2); <ide> addRegexToken('hh', match1to2, match2); <ide> <add>addRegexToken('hmm', match3to4); <add>addRegexToken('hmmss', match5to6); <add> <ide> addParseToken(['H', 'HH'], HOUR); <ide> addParseToken(['a', 'A'], function (input, array, config) { <ide> config._isPm = config._locale.isPM(input); <ide> addParseToken(['h', 'hh'], function (input, array, config) { <ide> array[HOUR] = toInt(input); <ide> getParsingFlags(config).bigHour = true; <ide> }); <add>addParseToken('hmm', function (input, array, config) { <add> var pos = input.length - 2; <add> array[HOUR] = toInt(input.substr(0, pos)); <add> array[MINUTE] = toInt(input.substr(pos)); <add> getParsingFlags(config).bigHour = true; <add>}); <add>addParseToken('hmmss', function (input, array, config) { <add> var pos1 = input.length - 4; <add> var pos2 = input.length - 2; <add> array[HOUR] = toInt(input.substr(0, pos1)); <add> array[MINUTE] = toInt(input.substr(pos1, 2)); <add> array[SECOND] = toInt(input.substr(pos2)); <add> getParsingFlags(config).bigHour = true; <add>}); <ide> <ide> // LOCALES <ide> <ide><path>src/test/moment/create.js <ide> test('milliseconds', function (assert) { <ide> assert.equal(moment('12345678', 'SSSSSSSS').millisecond(), 123); <ide> assert.equal(moment('123456789', 'SSSSSSSSS').millisecond(), 123); <ide> }); <add> <add>test('hmm', function (assert) { <add> assert.equal(moment('123', 'hmm', true).format('HH:mm:ss'), '01:23:00', '123 with hmm'); <add> assert.equal(moment('123a', 'hmmA', true).format('HH:mm:ss'), '01:23:00', '123a with hmmA'); <add> assert.equal(moment('123p', 'hmmA', true).format('HH:mm:ss'), '13:23:00', '123p with hmmA'); <add> <add> assert.equal(moment('1234', 'hmm', true).format('HH:mm:ss'), '12:34:00', '1234 with hmm'); <add> assert.equal(moment('1234a', 'hmmA', true).format('HH:mm:ss'), '00:34:00', '1234a with hmmA'); <add> assert.equal(moment('1234p', 'hmmA', true).format('HH:mm:ss'), '12:34:00', '1234p with hmmA'); <add> <add> assert.equal(moment('12345', 'hmmss', true).format('HH:mm:ss'), '01:23:45', '12345 with hmmss'); <add> assert.equal(moment('12345a', 'hmmssA', true).format('HH:mm:ss'), '01:23:45', '12345a with hmmssA'); <add> assert.equal(moment('12345p', 'hmmssA', true).format('HH:mm:ss'), '13:23:45', '12345p with hmmssA'); <add> assert.equal(moment('112345', 'hmmss', true).format('HH:mm:ss'), '11:23:45', '112345 with hmmss'); <add> assert.equal(moment('112345a', 'hmmssA', true).format('HH:mm:ss'), '11:23:45', '112345a with hmmssA'); <add> assert.equal(moment('112345p', 'hmmssA', true).format('HH:mm:ss'), '23:23:45', '112345p with hmmssA'); <add>}); <ide><path>src/test/moment/format.js <ide> test('milliseconds', function (assert) { <ide> assert.equal(m.format('SSSSSSSS'), '12300000'); <ide> assert.equal(m.format('SSSSSSSSS'), '123000000'); <ide> }); <add> <add>test('hmm and hmmss', function (assert) { <add> assert.equal(moment('12:34:56', 'HH:mm:ss').format('hmm'), '1234'); <add> assert.equal(moment('01:34:56', 'HH:mm:ss').format('hmm'), '134'); <add> assert.equal(moment('13:34:56', 'HH:mm:ss').format('hmm'), '134'); <add> <add> assert.equal(moment('12:34:56', 'HH:mm:ss').format('hmmss'), '123456'); <add> assert.equal(moment('01:34:56', 'HH:mm:ss').format('hmmss'), '13456'); <add> assert.equal(moment('13:34:56', 'HH:mm:ss').format('hmmss'), '13456'); <add>});
5