content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Python | Python | fix typo for protocol, fixes | cb19ccc8b205d71449e6f3223797b16f24f2d06b | <ide><path>glances/exports/glances_influxdb.py
<ide> def __init__(self, config=None, args=None):
<ide> self.db = None
<ide>
<ide> # Optionals configuration keys
<del> self.protocole = 'http'
<add> self.protocol = 'http'
<ide> self.prefix = None
<ide> self.tags = None
<ide> | 1 |
Javascript | Javascript | fix backwards incompatibility | 7cd0d4f644e304d4c8239dca532ca4de50d981ba | <ide><path>lib/buffer.js
<ide> function byteLength(string, encoding) {
<ide> return len >>> 1;
<ide> break;
<ide> }
<del> if (mustMatch)
<del> throw new TypeError('Unknown encoding: ' + encoding);
<del> else
<del> return binding.byteLengthUtf8(string);
<add> return (mustMatch ? -1 : binding.byteLengthUtf8(string));
<ide> }
<ide>
<ide> Buffer.byteLength = byteLength;
<ide><path>test/parallel/test-buffer-alloc.js
<ide> assert.throws(() => Buffer.allocUnsafe(8).writeFloatLE(0.0, -1), RangeError);
<ide> }
<ide>
<ide> // Regression test for #5482: should throw but not assert in C++ land.
<del>assert.throws(() => Buffer.from('', 'buffer'), TypeError);
<add>assert.throws(() => Buffer.from('', 'buffer'),
<add> /^TypeError: "encoding" must be a valid string encoding$/);
<ide>
<ide> // Regression test for #6111. Constructing a buffer from another buffer
<ide> // should a) work, and b) not corrupt the source buffer. | 2 |
Javascript | Javascript | clarify argument name | 202087f03da20741b8e4b248e53994a6ff1cce3e | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> * @param {Object} templateAttrs The shared attribute function
<ide> * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
<ide> * scope argument is auto-generated to the new child of the transcluded parent scope.
<del> * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
<del> * argument has the root jqLite array so that we can replace widgets on it.
<add> * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
<add> * argument has the root jqLite array so that we can replace nodes on it.
<ide> * @returns linkFn
<ide> */
<del> function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
<add> function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) {
<ide> var terminalPriority = -Number.MAX_VALUE,
<ide> preLinkFns = [],
<ide> postLinkFns = [],
<ide> function $CompileProvider($provide) {
<ide> $compileNode = templateAttrs.$$element =
<ide> jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
<ide> compileNode = $compileNode[0];
<del> replaceWith($rootElement, jqLite($template[0]), compileNode);
<add> replaceWith(jqCollection, jqLite($template[0]), compileNode);
<ide> childTranscludeFn = compile($template, transcludeFn, terminalPriority);
<ide> } else {
<ide> $template = jqLite(JQLiteClone(compileNode)).contents();
<ide> function $CompileProvider($provide) {
<ide> throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
<ide> }
<ide>
<del> replaceWith($rootElement, $compileNode, compileNode);
<add> replaceWith(jqCollection, $compileNode, compileNode);
<ide>
<ide> var newTemplateAttrs = {$attr: {}};
<ide>
<ide> function $CompileProvider($provide) {
<ide> assertNoDuplicate('template', templateDirective, directive, $compileNode);
<ide> templateDirective = directive;
<ide> nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
<del> nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
<add> nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
<ide> childTranscludeFn);
<ide> ii = directives.length;
<ide> } else if (directive.compile) { | 1 |
Python | Python | perform the squeeze in a more appropriate location | 9dd2c618e8425ee5ac0b9e5ca1c4daddf8275581 | <ide><path>slim/nets/resnet_v2.py
<ide> def resnet_v2(inputs,
<ide> if num_classes is not None:
<ide> net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,
<ide> normalizer_fn=None, scope='logits')
<add> logits = tf.squeeze(net, [1, 2], name='SpatialSqueeze')
<ide> # Convert end_points_collection into a dictionary of end_points.
<ide> end_points = slim.utils.convert_collection_to_dict(end_points_collection)
<ide> if num_classes is not None:
<ide> end_points['predictions'] = slim.softmax(net, scope='predictions')
<del> return net, end_points
<del>resnet_v2.default_image_size = 224
<add> return logits, end_points
<ide>
<ide>
<ide> def resnet_v2_50(inputs,
<ide><path>slim/train_image_classifier.py
<ide> def clone_fn(batch_queue):
<ide> end_points['AuxLogits'], labels,
<ide> label_smoothing=FLAGS.label_smoothing, weights=0.4, scope='aux_loss')
<ide> tf.losses.softmax_cross_entropy(
<del> tf.squeeze(logits), labels, label_smoothing=FLAGS.label_smoothing, weights=1.0)
<add> logits, labels, label_smoothing=FLAGS.label_smoothing, weights=1.0)
<ide> return end_points
<ide>
<ide> # Gather initial summaries. | 2 |
Python | Python | simplify the tests for [15296] | 09a63632c5072695d3b3293a046c197ea3c3299a | <ide><path>tests/regressiontests/inspectdb/bug/__init__.py
<del>
<ide><path>tests/regressiontests/inspectdb/bug/models.py
<del>from django.db import models
<del>
<del>class People(models.Model):
<del> name = models.CharField(max_length=255)
<del>
<del>class Message(models.Model):
<del> from_field = models.ForeignKey(People, db_column='from_id')
<ide><path>tests/regressiontests/inspectdb/models.py
<add>from django.db import models
<ide>
<add>
<add>class People(models.Model):
<add> name = models.CharField(max_length=255)
<add>
<add>class Message(models.Model):
<add> from_field = models.ForeignKey(People, db_column='from_id')
<ide><path>tests/regressiontests/inspectdb/tests.py
<del>import os
<del>import sys
<ide> from StringIO import StringIO
<ide>
<del>from django.conf import settings
<ide> from django.core.management import call_command
<del>from django.db.models.loading import load_app
<ide> from django.test import TestCase
<ide>
<add>
<ide> class InspectDBTestCase(TestCase):
<del>
<del> def setUp(self):
<del> self.old_sys_path = sys.path[:]
<del> sys.path.append(os.path.dirname(os.path.abspath(__file__)))
<del> self.old_installed_apps = settings.INSTALLED_APPS
<del> settings.INSTALLED_APPS = ('bug',)
<del> map(load_app, settings.INSTALLED_APPS)
<del> call_command('syncdb', verbosity=0)
<del>
<ide> def test_attribute_name_not_python_keyword(self):
<ide> out = StringIO()
<ide> call_command('inspectdb', stdout=out)
<ide> error_message = "inspectdb generated an attribute name which is a python keyword"
<del> self.assertNotIn("from = models.ForeignKey(BugPeople)", out.getvalue(), msg=error_message)
<add> self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message)
<add> self.assertIn("from_field = models.ForeignKey(InspectdbPeople)", out.getvalue())
<ide> out.close()
<del>
<del> def tearDown(self):
<del> settings.INSTALLED_APPS = self.old_installed_apps
<del> sys.path = self.old_sys_path | 4 |
Ruby | Ruby | add missing assert_not_deprecated deprecator args | 8a7aba0c768cb30d45e0fe33a4722ca46e43cbf5 | <ide><path>activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb
<ide> def close
<ide> )
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveRecord.deprecator) do
<ide> ActiveRecord::ConnectionAdapters::Mysql2Adapter.new(
<ide> fake_connection,
<ide> ActiveRecord::Base.logger,
<ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_should_count_field_of_root_table_with_conflicting_group_by_column
<ide> end
<ide>
<ide> def test_count_with_no_parameters_isnt_deprecated
<del> assert_not_deprecated { Account.count }
<add> assert_not_deprecated(ActiveRecord.deprecator) { Account.count }
<ide> end
<ide>
<ide> def test_count_with_too_many_parameters_raises
<ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb
<ide> def test_establish_connection_with_primary_works_without_deprecation
<ide>
<ide> @handler.establish_connection(:primary)
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveRecord.deprecator) do
<ide> @handler.retrieve_connection("primary")
<ide> @handler.remove_connection_pool("primary")
<ide> end
<ide><path>activerecord/test/cases/locking_test.rb
<ide> def test_locking_in_after_save_callback
<ide> assert_nothing_raised do
<ide> frog = ::Frog.create(name: "Old Frog")
<ide> frog.name = "New Frog"
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveRecord.deprecator) do
<ide> frog.save!
<ide> end
<ide> end
<ide><path>activerecord/test/cases/transactions_test.rb
<ide> def test_rollback_on_ruby_timeout
<ide> end
<ide>
<ide> def test_early_return_from_transaction
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveRecord.deprecator) do
<ide> @first.with_lock do
<ide> break
<ide> end
<ide><path>activesupport/test/core_ext/date_and_time_compatibility_test.rb
<ide> def test_string_to_time_frozen_does_not_preserve_time_zone
<ide> def test_to_time_preserves_timezone_is_deprecated
<ide> current_preserve_tz = ActiveSupport.to_time_preserves_timezone
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> ActiveSupport.to_time_preserves_timezone
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> ActiveSupport.to_time_preserves_timezone = true
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/digest/uuid_test.rb
<ide> def test_constants
<ide>
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_enabled
<ide> with_use_rfc4122_namespaced_uuids_set do
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "3d813cbb-47fb-32ba-91df-831e1593ac29", Digest::UUID.uuid_v3("6BA7B810-9DAD-11D1-80B4-00C04FD430C8", "www.widgets.com")
<ide> assert_equal "3d813cbb-47fb-32ba-91df-831e1593ac29", Digest::UUID.uuid_v3("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "www.widgets.com")
<ide> assert_equal "3d813cbb-47fb-32ba-91df-831e1593ac29", Digest::UUID.uuid_v3(Digest::UUID::DNS_NAMESPACE, "www.widgets.com")
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "fe5a52d1-703f-3326-b919-2d96003288f3", Digest::UUID.uuid_v3("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "www.widgets.com")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "3d813cbb-47fb-32ba-91df-831e1593ac29", Digest::UUID.uuid_v3(Digest::UUID::DNS_NAMESPACE, "www.widgets.com")
<ide> end
<ide>
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "2676127a-9073-36e3-b9db-14bc16b7c083", Digest::UUID.uuid_v3("6ba7b811-9dad-11d1-80b4-00c04fd430c8", "http://www.widgets.com")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "86df55fb-428e-3843-8583-ba3c05f290bc", Digest::UUID.uuid_v3(Digest::UUID::URL_NAMESPACE, "http://www.widgets.com")
<ide> end
<ide>
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "719357e1-54f1-3930-8113-a1faffde48fa", Digest::UUID.uuid_v3("6ba7b812-9dad-11d1-80b4-00c04fd430c8", "1.2.3")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "8c29ab0e-a2dc-3482-b5eb-20cb2e2387a1", Digest::UUID.uuid_v3(Digest::UUID::OID_NAMESPACE, "1.2.3")
<ide> end
<ide>
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "32560c4a-c9f1-3974-9c1c-5e52761e091f", Digest::UUID.uuid_v3("6ba7b814-9dad-11d1-80b4-00c04fd430c8", "cn=John Doe, ou=People, o=Acme, Inc., c=US")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "ee49149d-53a4-304a-890b-468229f6afc3", Digest::UUID.uuid_v3(Digest::UUID::X500_NAMESPACE, "cn=John Doe, ou=People, o=Acme, Inc., c=US")
<ide> end
<ide>
<ide> def test_v3_uuids_with_rfc4122_namespaced_uuids_disabled
<ide>
<ide> def test_v5_uuids_with_rfc4122_namespaced_uuids_enabled
<ide> with_use_rfc4122_namespaced_uuids_set do
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "21f7f8de-8051-5b89-8680-0195ef798b6a", Digest::UUID.uuid_v5("6BA7B810-9DAD-11D1-80B4-00C04FD430C8", "www.widgets.com")
<ide> assert_equal "21f7f8de-8051-5b89-8680-0195ef798b6a", Digest::UUID.uuid_v5("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "www.widgets.com")
<ide> assert_equal "21f7f8de-8051-5b89-8680-0195ef798b6a", Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, "www.widgets.com")
<ide> def test_v5_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "027963ef-431c-5670-ab2c-820168da74e9", Digest::UUID.uuid_v5("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "www.widgets.com")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "21f7f8de-8051-5b89-8680-0195ef798b6a", Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, "www.widgets.com")
<ide> end
<ide>
<ide> def test_v5_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "d8e1e518-2337-58e5-bf52-6c563631db90", Digest::UUID.uuid_v5("6ba7b811-9dad-11d1-80b4-00c04fd430c8", "http://www.widgets.com")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "4e570fd8-186d-5a74-90f0-4d28e34673a1", Digest::UUID.uuid_v5(Digest::UUID::URL_NAMESPACE, "http://www.widgets.com")
<ide> end
<ide>
<ide> def test_v5_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "b9b86653-48bb-5059-861a-2c72974b5c8d", Digest::UUID.uuid_v5("6ba7b812-9dad-11d1-80b4-00c04fd430c8", "1.2.3")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "42d5e23b-3a02-5135-85c6-52d1102f1f00", Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, "1.2.3")
<ide> end
<ide>
<ide> def test_v5_uuids_with_rfc4122_namespaced_uuids_disabled
<ide> assert_equal "e84a8a4e-a5c7-55b8-ad09-020c0b5662a7", Digest::UUID.uuid_v5("6ba7b814-9dad-11d1-80b4-00c04fd430c8", "cn=John Doe, ou=People, o=Acme, Inc., c=US")
<ide> end
<ide>
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal "fd5b2ddf-bcfe-58b6-90d6-db50f74db527", Digest::UUID.uuid_v5(Digest::UUID::X500_NAMESPACE, "cn=John Doe, ou=People, o=Acme, Inc., c=US")
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/time_with_zone_test.rb
<ide> def test_to_yaml
<ide> EOF
<ide>
<ide> # TODO: Remove assertion in Rails 7.1
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal(yaml, @twz.to_yaml)
<ide> end
<ide> end
<ide> def test_ruby_to_yaml
<ide> EOF
<ide>
<ide> # TODO: Remove assertion in Rails 7.1
<del> assert_not_deprecated do
<add> assert_not_deprecated(ActiveSupport.deprecator) do
<ide> assert_equal(yaml, { "twz" => @twz }.to_yaml)
<ide> end
<ide> end | 8 |
Javascript | Javascript | fix parsing of requires in requires | 26231576a8119247a4a9cc259ad0dc29021bf5c4 | <ide><path>lib/dependencies/CommonJsImportsParserPlugin.js
<ide> class CommonJsImportsParserPlugin {
<ide> dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
<ide> dep.loc = expr.callee.loc;
<ide> parser.state.module.addDependency(dep);
<add> parser.walkExpressions(expr.arguments);
<ide> return true;
<ide> }
<ide> };
<ide><path>test/cases/cjs-tree-shaking/parsing/index.js
<add>it("should parse nested requires successfully", () => {
<add> expect(require("./nested-require").value).toBe(42);
<add>});
<ide><path>test/cases/cjs-tree-shaking/parsing/module.js
<add>exports.fn = a => a + 1;
<add>exports.value = 41;
<ide><path>test/cases/cjs-tree-shaking/parsing/nested-require.js
<add>exports.value = require("./module").fn(require("./module").value); | 4 |
PHP | PHP | catch symfony exception | 7ab5b4bbd5e7a662395f5cec0ece7497cec16806 | <ide><path>src/Illuminate/Routing/CompiledRouteCollection.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Support\Collection;
<add>use Symfony\Component\Routing\Exception\ResourceNotFoundException;
<ide> use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
<ide> use Symfony\Component\Routing\RequestContext;
<ide>
<ide> public function match(Request $request)
<ide> $this->compiled, (new RequestContext)->fromRequest($request)
<ide> );
<ide>
<del> if ($result = $matcher->matchRequest($request)) {
<del> $route = $this->getByName($result['_route']);
<add> try {
<add> if ($result = $matcher->matchRequest($request)) {
<add> $route = $this->getByName($result['_route']);
<add> }
<add> } catch (ResourceNotFoundException $e) {
<add> //
<ide> }
<ide>
<ide> return $this->handleMatchedRoute($request, $route); | 1 |
Javascript | Javascript | update wiki hotkey | 7193b9c725ed97cd8cc99aba72ceffa40a79c8f8 | <ide><path>client/sagas/mouse-trap-saga.js
<ide> const softRedirects = {
<ide> 'g n n': '/challenges/next-challenge',
<ide> 'g n a': '/about',
<ide> 'g n m': '/map',
<del> 'g n w': '/wiki',
<ide> 'g n s': '/shop',
<ide> 'g n o': '/settings'
<ide> };
<ide> export default function mouseTrapSaga(actions$) {
<ide> 'g n r',
<ide> () => hardGoTo('https://github.com/freecodecamp/freecodecamp')
<ide> ),
<add> bindKey$(
<add> 'g n w',
<add> () => hardGoTo('http://forum.freecodecamp.com')
<add> ),
<ide> bindKey$('g m', toggleMapDrawer),
<ide> bindKey$('g t n', toggleNightMode),
<ide> bindKey$('g c', toggleMainChat) | 1 |
PHP | PHP | add messages method to message bag | dcd02818805175725aecc01a14ec2bb7340f7586 | <ide><path>src/Illuminate/Support/MessageBag.php
<ide> protected function checkFormat($format)
<ide> *
<ide> * @return array
<ide> */
<del> public function getMessages()
<add> public function messages()
<ide> {
<ide> return $this->messages;
<ide> }
<ide>
<add> /**
<add> * Get the raw messages in the container.
<add> *
<add> * @return array
<add> */
<add> public function getMessages()
<add> {
<add> return $this->messages();
<add> }
<add>
<ide> /**
<ide> * Get the messages for the instance.
<ide> * | 1 |
Python | Python | fix typo in dataproccreateclusteroperator | c5e302030de7512a07120f71f388ad1859b26ca2 | <ide><path>airflow/providers/google/cloud/operators/dataproc.py
<ide> class DataprocCreateClusterOperator(BaseOperator):
<ide> :type cluster_config: Union[Dict, google.cloud.dataproc_v1.types.ClusterConfig]
<ide> :param region: The specified region where the dataproc cluster is created.
<ide> :type region: str
<del> :parm delete_on_error: If true the cluster will be deleted if created with ERROR state. Default
<add> :param delete_on_error: If true the cluster will be deleted if created with ERROR state. Default
<ide> value is true.
<ide> :type delete_on_error: bool
<del> :parm use_if_exists: If true use existing cluster
<add> :param use_if_exists: If true use existing cluster
<ide> :type use_if_exists: bool
<ide> :param request_id: Optional. A unique id used to identify the request. If the server receives two
<ide> ``DeleteClusterRequest`` requests with the same id, then the second request will be ignored and the | 1 |
Python | Python | remove redundant kwargs, improve docstrings | ad7233fc019c1c6b2d66978ad9aec9e31d7b889c | <ide><path>src/transformers/modeling_bart.py
<ide> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
<ide> inputs = tokenizer.batch_encode_plus([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='pt')
<ide> # Generate Summary
<del> summary_ids = model.generate(inputs['input_ids'], attention_mask=inputs['attention_mask'], num_beams=4, max_length=5)
<add> summary_ids = model.generate(inputs['input_ids'], num_beams=4, max_length=5, early_stopping=True)
<ide> print([tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summary_ids])
<ide>
<ide> """
<ide> def _prepare_bart_decoder_inputs(
<ide> config, input_ids, decoder_input_ids=None, decoder_attn_mask=None, mask_dtype=None,
<ide> ):
<del> """Prepare masks that ignore padding tokens decoder and a causal lm mask for the decoder if
<add> """Prepare masks that ignore padding tokens in the decoder and a causal lm mask for the decoder if
<ide> none are provided. This mimics the default behavior in fairseq. To override it pass in masks.
<add> Note: this is not called during generation
<ide> """
<ide> pad_token_id = config.pad_token_id
<ide> need_causal_mask = not config.output_past
<ide> class PretrainedBartModel(PreTrainedModel):
<ide>
<ide> def _init_weights(self, module):
<ide> std = self.config.init_std
<del>
<del> # called init_bert_params in fairseq
<ide> if isinstance(module, nn.Linear):
<ide> module.weight.data.normal_(mean=0.0, std=std)
<ide> if module.bias is not None:
<ide> def _init_weights(self, module):
<ide>
<ide> @property
<ide> def dummy_inputs(self):
<del> pad_token = 1
<del> input_ids = torch.Tensor(
<del> [
<del> [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2],
<del> [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 2, pad_token],
<del> ]
<del> ).long()
<del> decoder_input_ids, decoder_attn_mask = _prepare_bart_decoder_inputs(
<del> self.config, input_ids, attention_mask=None, decoder_input_ids=None, decoder_attn_mask=None
<del> )
<add> pad_token = self.config.pad_token_id
<add> input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]])
<add> decoder_input_ids, decoder_attn_mask = _prepare_bart_decoder_inputs(self.config, input_ids,)
<ide> dummy_inputs = {
<ide> "decoder_input_ids": decoder_input_ids,
<ide> "attention_mask": input_ids.ne(pad_token),
<ide> def dummy_inputs(self):
<ide> def _make_linear_from_emb(emb):
<ide> vocab_size, emb_size = emb.weight.shape
<ide> lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
<del> lin_layer.weight.data = emb.weight.data # .T
<add> lin_layer.weight.data = emb.weight.data
<ide> return lin_layer
<ide>
<ide>
<ide> def _check_shapes(shape_1, shape2):
<ide>
<ide>
<ide> def _combine_masks(key_padding_mask, causal_lm_mask, targ_size):
<del> # targ_size = (bsz, tgt_len, src_len)
<del> a = torch.zeros(targ_size)
<add> """Make one mask of shape (bsz, 1, tgt_len, src_len) """
<add> a = torch.zeros(targ_size) # targ_size is(bsz, tgt_len, src_len)
<ide> b = torch.zeros(targ_size)
<ide> if key_padding_mask is not None: # (bsz, tgt_len) -> targ_size
<ide> _check_shapes(key_padding_mask.shape, targ_size[:2])
<ide> def forward(self, x, encoder_padding_mask):
<ide> encoded output of shape `(seq_len, batch, embed_dim)`
<ide> """
<ide> residual = x
<del> x, attn_weights = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask,)
<add> x, attn_weights = self.self_attn(query=x, key=x, key_padding_mask=encoder_padding_mask,)
<ide> x = F.dropout(x, p=self.dropout, training=self.training)
<ide> x = residual + x
<ide> x = self.self_attn_layer_norm(x)
<ide> def __init__(self, config: BartConfig, embed_tokens):
<ide> self.layernorm_embedding = LayerNorm(embed_dim)
<ide>
<ide> def forward(
<del> self, input_ids=None, attention_mask=None,
<add> self, input_ids, attention_mask=None,
<ide> ):
<ide> """
<ide> Args:
<ide> input_ids (LongTensor): tokens in the source language of shape
<ide> `(batch, src_len)`
<ide> attention_mask (torch.LongTensor): indicating which indices are padding tokens.
<ide> Returns:
<del> namedtuple:
<add> Tuple comprised of:
<ide> - **x** (Tensor): the last encoder layer's output of
<ide> shape `(src_len, batch, embed_dim)`
<del>
<ide> - **encoder_states** (List[Tensor]): all intermediate
<ide> hidden states of shape `(src_len, batch, embed_dim)`.
<del> Only populated if *return_all_hiddens* is True.
<add> Only populated if *self.output_hidden_states:* is True.
<ide> - **all_attentions** (List[Tensor]): Attention weights for each layer.
<ide> During training might not be of length n_layers because of layer dropout.
<ide> """
<ide> # check attention mask and invert
<ide> if attention_mask is not None:
<ide> assert attention_mask.dim() == 2
<del>
<del> attention_mask = (1.0 - attention_mask.long()) * -10000.0
<add> attention_mask = (1.0 - attention_mask.long()) * LARGE_NEGATIVE
<ide> assert attention_mask.max() <= 0
<ide> inputs_embeds = self.embed_tokens(input_ids)
<ide> embed_pos = self.embed_positions(input_ids)
<ide> def forward(
<ide> x = x.transpose(0, 1)
<ide>
<ide> encoder_states, all_attentions = [], []
<del>
<del> # encoder layers
<ide> for encoder_layer in self.layers:
<del>
<ide> if self.output_hidden_states:
<ide> encoder_states.append(x)
<ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
<ide> def forward(
<ide> encoder_states.append(x)
<ide>
<ide> encoder_states = [hidden_state.transpose(0, 1) for hidden_state in encoder_states]
<del>
<ide> return x, encoder_states, all_attentions
<ide>
<ide>
<ide> def forward(
<ide> attention_mask=None,
<ide> need_attn_weights=False,
<ide> ):
<del> """
<del> Args:
<del> x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
<del> encoder_attn_mask (ByteTensor, optional): binary
<del> ByteTensor of shape `(batch, src_len)` where padding
<del> elements are indicated by ``1``.
<del> need_attn_weights (bool, optional): return attention weights
<del> for each head (default: return average over heads).
<del>
<del> Returns:
<del> encoded output of shape `(seq_len, batch, embed_dim)`
<del> """
<del>
<ide> residual = x
<del> y = x # TODO(SS): figure out why fairseq did this, then hopefully delete it
<ide>
<ide> if layer_state is None:
<ide> layer_state = {}
<ide> # next line mutates layer state
<del> x, self_attn_weights = self.self_attn(
<del> query=x, key=y, value=y, layer_state=layer_state, attn_mask=attention_mask,
<del> )
<add> x, self_attn_weights = self.self_attn(query=x, key=x, layer_state=layer_state, attn_mask=attention_mask,)
<ide> x = F.dropout(x, p=self.dropout, training=self.training)
<ide> x = residual + x
<ide> x = self.self_attn_layer_norm(x)
<ide> def forward(
<ide>
<ide> x, encoder_attn_weights = self.encoder_attn(
<ide> query=x,
<del> key=encoder_hidden_states, # could be None
<del> value=encoder_hidden_states,
<add> key=encoder_hidden_states,
<ide> key_padding_mask=encoder_attn_mask,
<ide> layer_state=layer_state, # mutates layer state
<del> static_kv=True,
<ide> )
<ide> x = F.dropout(x, p=self.dropout, training=self.training)
<ide> x = residual + x
<ide> def forward(
<ide> return x, next_cache, all_hidden_states, list(all_self_attns)
<ide>
<ide>
<del>def reorder_attn_buffer(input_buffer, new_order):
<del> """Reorder buffered internal state (for incremental generation)."""
<del> # input_buffer = self._get_input_buffer(incremental_state)
<del> for k in input_buffer.keys():
<del> input_buffer_k = input_buffer[k]
<add>def _reorder_buffer(attn_cache, new_order):
<add> for k, input_buffer_k in attn_cache.items():
<ide> if input_buffer_k is not None:
<del> input_buffer[k] = input_buffer_k.index_select(0, new_order)
<del> # incremental_state = self._set_input_buffer(incremental_state, input_buffer)
<del> return input_buffer
<add> attn_cache[k] = input_buffer_k.index_select(0, new_order)
<add> return attn_cache
<ide>
<ide>
<ide> class SelfAttention(nn.Module):
<del> """Multi-headed attention from "Attention Is All You Need"""
<add> """Multi-headed attention from 'Attention Is All You Need' paper"""
<ide>
<ide> def __init__(
<ide> self,
<ide> def __init__(
<ide> ):
<ide> super().__init__()
<ide> self.embed_dim = embed_dim
<del>
<ide> self.num_heads = num_heads
<ide> self.dropout = dropout
<ide> self.head_dim = embed_dim // num_heads
<ide> def forward(
<ide> self,
<ide> query,
<ide> key: Optional[Tensor],
<del> value: Optional[Tensor],
<ide> key_padding_mask: Optional[Tensor] = None,
<del> layer_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
<del> static_kv: bool = False,
<add> layer_state: Optional[Dict[str, Optional[Tensor]]] = None,
<ide> attn_mask: Optional[Tensor] = None,
<ide> ) -> Tuple[Tensor, Optional[Tensor]]:
<del> """Input shape: Time(SeqLen) x Batch x Channel
<del>
<del> Args:
<del>
<del> key_padding_mask (ByteTensor, optional): mask to exclude
<del> keys that are pads, of shape `(batch, src_len)`, where
<del> padding elements are indicated by 1s.
<del> attn_mask (ByteTensor, optional): typically used to
<del> implement causal attention, where the mask prevents the
<del> attention from looking forward in time (default: None).
<del> """
<add> """Input shape: Time(SeqLen) x Batch x Channel"""
<add> static_kv = self.encoder_decoder_attention # type: bool
<ide> tgt_len, bsz, embed_dim = query.size()
<ide> assert embed_dim == self.embed_dim
<ide> assert list(query.size()) == [tgt_len, bsz, embed_dim]
<ide> # get here for encoder decoder cause of static_kv
<del> if layer_state is not None: # get the last k,v and mask for reuse
<add> if layer_state is not None: # reuse k,v and encoder_padding_mask
<ide> saved_state = layer_state.get(self.cache_key, {})
<ide> if "prev_key" in saved_state:
<ide> # previous time steps are cached - no need to recompute key and value if they are static
<ide> if static_kv:
<del> assert self.encoder_decoder_attention
<del> key = value = None
<add> key = None
<ide> else:
<ide> saved_state = None
<ide> layer_state = {}
<ide>
<ide> q = self.q_proj(query) * self.scaling
<del> if self.encoder_decoder_attention:
<add> if static_kv:
<ide> if key is None:
<del> assert value is None
<ide> k = v = None
<ide> else:
<ide> k = self.k_proj(key)
<ide> def forward(
<ide>
<ide> if saved_state is not None:
<ide> k, v, key_padding_mask = self._use_saved_state(k, v, saved_state, key_padding_mask, static_kv, bsz)
<del> # assert self.cache_key != 'encoder_decoder' or key_padding_mask is None
<ide>
<ide> # Update cache
<ide> layer_state[self.cache_key] = {
<ide> def forward(
<ide> assert k is not None
<ide> src_len = k.size(1)
<ide> attn_weights = torch.bmm(q, k.transpose(1, 2))
<del>
<ide> assert attn_weights.size() == (bsz * self.num_heads, tgt_len, src_len)
<ide>
<ide> if attn_mask is not None:
<ide> def _reorder_cache(past, beam_idx):
<ide> for layer_past in decoder_cached_states:
<ide> # get the correct batch idx from decoder layer's batch dim for cross and self-attn
<ide> layer_past_new = {
<del> attn_key: reorder_attn_buffer(attn_cache, beam_idx) for attn_key, attn_cache in layer_past.items()
<add> attn_key: _reorder_buffer(attn_cache, beam_idx) for attn_key, attn_cache in layer_past.items()
<ide> }
<ide> # reordered_layer_past = [layer_past[:, i].unsqueeze(1).clone().detach() for i in beam_idx]
<ide> # reordered_layer_past = torch.cat(reordered_layer_past, dim=1)
<ide><path>tests/test_modeling_bart.py
<ide> def test_base_model_fp16(self):
<ide> lm_model = BartForConditionalGeneration(config).eval().to(torch_device).half()
<ide> lm_model(input_ids, attention_mask=attention_mask)
<ide>
<add> def test_default_generate_kwargs(self):
<add> config, input_ids, _ = self._get_config_and_data(output_past=True)
<add> model = BartForConditionalGeneration(config).eval().to(torch_device)
<add> model.generate(input_ids)
<add> model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
<add>
<add> def test_dummy_inputs(self):
<add> config, *_ = self._get_config_and_data(output_past=True)
<add> model = BartForConditionalGeneration(config).eval().to(torch_device)
<add> model(**model.dummy_inputs)
<add>
<ide> def test_prepare_bart_decoder_inputs(self):
<ide> config, *_ = self._get_config_and_data(output_past=False)
<ide> input_ids = _long_tensor(([4, 4, 2])) # only used for .device if decoder_input_ids is passed | 2 |
Javascript | Javascript | remove bad chars instead of replaces all | b9cd526a35c1e6fb0b3eb4497f6013a4abda7021 | <ide><path>src/fonts.js
<ide> var Type2CFF = (function Type2CFFClosure() {
<ide> var length = data.length;
<ide> if (length > 127)
<ide> warn('Font had name longer than 127 chars, will be rejected.');
<del> // Only certain chars are permitted in the font name. Set them all to
<del> // 'A' to avoid being rejected.
<del> for (var j = 0; j < length; ++j)
<del> data[j] = 65;
<add> // Only certain chars are permitted in the font name.
<add> for (var j = 0; j < length; ++j) {
<add> var c = data[j];
<add> if (j === 0 && c === 0)
<add> continue;
<add> if (c < 33 || c > 126) {
<add> data[j] = 95;
<add> continue;
<add> }
<add> switch (c) {
<add> case 91: // [
<add> case 93: // ]
<add> case 40: // (
<add> case 41: // )
<add> case 123: // {
<add> case 125: // }
<add> case 60: // <
<add> case 62: // >
<add> case 47: // /
<add> case 37: // %
<add> data[j] = 95;
<add> break;
<add> }
<add> }
<ide> }
<ide> },
<ide> getStrings: function cff_getStrings(stringIndex) { | 1 |
Text | Text | restore documentation for two error codes | cdb59854ee6c13712d17af729a42d5221d6af8f2 | <ide><path>doc/api/errors.md
<ide> forbidden.
<ide> For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is
<ide> forbidden.
<ide>
<add><a id="ERR_HTTP2_ERROR"></a>
<add>### ERR_HTTP2_ERROR
<add>
<add>A non-specific HTTP/2 error has occurred.
<add>
<ide> <a id="ERR_HTTP2_GOAWAY_SESSION"></a>
<ide> ### ERR_HTTP2_GOAWAY_SESSION
<ide>
<ide> A string that contained unescaped characters was received.
<ide> An unhandled error occurred (for instance, when an `'error'` event is emitted
<ide> by an [`EventEmitter`][] but an `'error'` handler is not registered).
<ide>
<add><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a>
<add>### ERR_UNKNOWN_BUILTIN_MODULE
<add>
<add>Used to identify a specific kind of internal Node.js error that should not
<add>typically be triggered by user code. Instances of this error point to an
<add>internal bug within the Node.js binary itself.
<add>
<ide> <a id="ERR_UNKNOWN_CREDENTIAL"></a>
<ide> ### ERR_UNKNOWN_CREDENTIAL
<ide> | 1 |
Javascript | Javascript | allow handlebars rc1 | 059ceb0f72ad0f54a022f61d621d73b9470f1b16 | <ide><path>packages/ember-handlebars/lib/ext.js
<ide> require("ember-views/system/render_buffer");
<ide> @description Helpers for Handlebars templates
<ide> */
<ide>
<del>Ember.assert("Ember Handlebars requires Handlebars 1.0.beta.5 or greater", window.Handlebars && window.Handlebars.VERSION.match(/^1\.0\.beta\.[56789]$/));
<add>Ember.assert("Ember Handlebars requires Handlebars 1.0.beta.5 or greater", window.Handlebars && window.Handlebars.VERSION.match(/^1\.0\.beta\.[56789]$|^1\.0\.rc\.[123456789]+/));
<ide>
<ide> /**
<ide> @class | 1 |
Go | Go | fix some typos | 97915bde4438ba8b14b3068c5231c6fcf052264a | <ide><path>libnetwork/error.go
<ide> func (nnr NetworkNameError) Error() string {
<ide> // Forbidden denotes the type of this error
<ide> func (nnr NetworkNameError) Forbidden() {}
<ide>
<del>// UnknownNetworkError is returned when libnetwork could not find in it's database
<add>// UnknownNetworkError is returned when libnetwork could not find in its database
<ide> // a network with the same name and id.
<ide> type UnknownNetworkError struct {
<ide> name string
<ide> func (aee *ActiveEndpointsError) Error() string {
<ide> // Forbidden denotes the type of this error
<ide> func (aee *ActiveEndpointsError) Forbidden() {}
<ide>
<del>// UnknownEndpointError is returned when libnetwork could not find in it's database
<add>// UnknownEndpointError is returned when libnetwork could not find in its database
<ide> // an endpoint with the same name and id.
<ide> type UnknownEndpointError struct {
<ide> name string | 1 |
Python | Python | remove unused import | cdc61155fa7efd6f6e0d1dd675c7698e57f22a6a | <ide><path>libcloud/drivers/rimuhosting.py
<ide> from libcloud.types import Provider, NodeState, InvalidCredsException
<ide> from libcloud.base import ConnectionKey, Response, NodeAuthPassword, NodeDriver, NodeSize, Node, NodeLocation
<ide> from libcloud.base import NodeImage
<del>from copy import copy
<ide>
<ide> # JSON is included in the standard library starting with Python 2.6. For 2.5
<ide> # and 2.4, there's a simplejson egg at: http://pypi.python.org/pypi/simplejson | 1 |
Text | Text | correct the instructions for functional tests | 2ad908b3a9ba77ec6883e74b2fbfd820603cce0c | <ide><path>curriculum/challenges/english/09-information-security/information-security-projects/anonymous-message-board.md
<ide> Write the following tests in `tests/2_functional-tests.js`:
<ide> - Reporting a thread: PUT request to `/api/threads/{board}`
<ide> - Creating a new reply: POST request to `/api/replies/{board}`
<ide> - Viewing a single thread with all replies: GET request to `/api/replies/{board}`
<del>- Deleting a reply with the incorrect password: DELETE request to `/api/threads/{board}` with an invalid `delete_password`
<del>- Deleting a reply with the correct password: DELETE request to `/api/threads/{board}` with a valid `delete_password`
<add>- Deleting a reply with the incorrect password: DELETE request to `/api/replies/{board}` with an invalid `delete_password`
<add>- Deleting a reply with the correct password: DELETE request to `/api/replies/{board}` with a valid `delete_password`
<ide> - Reporting a reply: PUT request to `/api/replies/{board}`
<ide>
<ide> # --hints-- | 1 |
Ruby | Ruby | add tests for our minitest reporter | ff79441d49a52a2669e147cd8264a2dc6e452b80 | <ide><path>railties/test/test_unit/reporter_test.rb
<add>require 'abstract_unit'
<add>require 'rails/test_unit/reporter'
<add>
<add>class TestUnitReporterTest < ActiveSupport::TestCase
<add> class ExampleTest < Minitest::Test
<add> def woot; end
<add> end
<add>
<add> setup do
<add> @output = StringIO.new
<add> @reporter = Rails::TestUnitReporter.new @output
<add> end
<add>
<add> test "prints rerun snippet to run a single failed test" do
<add> @reporter.results << failed_test
<add> @reporter.report
<add>
<add> assert_match %r{^bin/rails test .*test/test_unit/reporter_test.rb:6$}, @output.string
<add> assert_rerun_snippet_count 1
<add> end
<add>
<add> test "prints rerun snippet for every failed test" do
<add> @reporter.results << failed_test
<add> @reporter.results << failed_test
<add> @reporter.results << failed_test
<add> @reporter.report
<add>
<add> assert_rerun_snippet_count 3
<add> end
<add>
<add> test "does not print snippet for successful and skipped tests" do
<add> skip "confirm the expected behavior with Arthur"
<add> @reporter.results << passing_test
<add> @reporter.results << skipped_test
<add> @reporter.report
<add> assert_rerun_snippet_count 0
<add> end
<add>
<add> test "prints rerun snippet for skipped tests if run in verbose mode" do
<add> skip "confirm the expected behavior with Arthur"
<add> verbose = Rails::TestUnitReporter.new @output, verbose: true
<add> verbose.results << skipped_test
<add> verbose.report
<add>
<add> assert_rerun_snippet_count 1
<add> end
<add>
<add> private
<add> def assert_rerun_snippet_count(snippet_count)
<add> assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size
<add> end
<add>
<add> def failed_test
<add> ft = ExampleTest.new(:woot)
<add> ft.failures << begin
<add> raise Minitest::Assertion, "boo"
<add> rescue Minitest::Assertion => e
<add> e
<add> end
<add> ft
<add> end
<add>
<add> def passing_test
<add> ExampleTest.new(:woot)
<add> end
<add>
<add> def skipped_test
<add> st = ExampleTest.new(:woot)
<add> st.failures << begin
<add> raise Minitest::Skip
<add> rescue Minitest::Assertion => e
<add> e
<add> end
<add> st
<add> end
<add>end | 1 |
Python | Python | fix edgecase for bool containers | 6244c0631e1a78926db27143bf936bfb5e95c852 | <ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None):
<ide> ar2 = ar2.reshape(-1, 1)
<ide> # Convert booleans to uint8 so we can use the fast integer algorithm
<ide> if ar1.dtype == bool:
<del> ar1 = ar1.view(np.uint8)
<add> ar1 = ar1 + np.uint8(0)
<ide> if ar2.dtype == bool:
<del> ar2 = ar2.view(np.uint8)
<add> ar2 = ar2 + np.uint8(0)
<ide>
<ide> # Check if we can use a fast integer algorithm:
<ide> integer_arrays = (np.issubdtype(ar1.dtype, np.integer) and | 1 |
Python | Python | fix typo in comment | a2bc743e4732338e1b19f87ae1e7e2303ffac2bd | <ide><path>spacy/pipeline/attributeruler.py
<ide> def __call__(self, doc: Doc) -> Doc:
<ide>
<ide> def match(self, doc: Doc):
<ide> matches = self.matcher(doc, allow_missing=True)
<del> # Sort by the attribute ID, so that later rules have precendence
<add> # Sort by the attribute ID, so that later rules have precedence
<ide> matches = [
<ide> (int(self.vocab.strings[m_id]), m_id, s, e) for m_id, s, e in matches
<ide> ] | 1 |
Text | Text | add active job info to 5.1 release notes | 31f27aa25806670545a7d17f5c6a04d0acd27beb | <ide><path>guides/source/5_1_release_notes.md
<ide> Please refer to the [Changelog][active-job] for detailed changes.
<ide>
<ide> ### Removals
<ide>
<del>### Deprecations
<add>* Removed deprecated support to passing the adapter class to `.queue_adapter`.
<add> ([commit](https://github.com/rails/rails/commit/d1fc0a5eb286600abf8505516897b96c2f1ef3f6))
<add>
<add>* Removed deprecated `#original_exception` in `ActiveJob::DeserializationError`.
<add> ([commit](https://github.com/rails/rails/commit/d861a1fcf8401a173876489d8cee1ede1cecde3b))
<ide>
<ide> ### Notable changes
<ide>
<add>* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`.
<add> ([Pull Request](https://github.com/rails/rails/pull/25991))
<add>
<add>* Yield the job instance so you have access to things like `job.arguments` on
<add> the custom logic after retries fail.
<add> ([commit](https://github.com/rails/rails/commit/a1e4c197cb12fef66530a2edfaeda75566088d1f))
<add>
<ide> Active Support
<ide> --------------
<ide> | 1 |
Ruby | Ruby | add tests for autocorrect | 0786003fe9d3aef49e62b329d2ed7795d5f871cc | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> shell_metacharacters = %w[> < < | ; : & * $ ? : ~ + @ !` ( ) [ ]]
<ide>
<ide> find_every_method_call_by_name(body_node, :system).each do |method|
<del> # Continue if a shell metacharacter is present
<add> # Only separate when no shell metacharacters are present
<ide> next if shell_metacharacters.any? { |meta| string_content(parameters(method).first).include?(meta) }
<ide>
<ide> next unless match = regex_match_group(parameters(method).first, shell_cmd_with_spaces_regex)
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> find_instance_method_call(body_node, "Utils", command) do |method|
<ide> index = parameters(method).first.hash_type? ? 1 : 0
<ide>
<del> # Continue if a shell metacharacter is present
<add> # Only separate when no shell metacharacters are present
<ide> next if shell_metacharacters.any? { |meta| string_content(parameters(method)[index]).include?(meta) }
<ide>
<ide> next unless match = regex_match_group(parameters(method)[index], shell_cmd_with_spaces_regex)
<ide><path>Library/Homebrew/test/rubocops/lines_spec.rb
<ide> def install
<ide> end
<ide> RUBY
<ide> end
<add>
<add> it "separates shell commands in system" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> system "foo bar"
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> system "foo", "bar"
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<add>
<add> it "separates shell commands with string interpolation in system" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> system "\#{foo}/bar baz"
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> system "\#{foo}/bar", "baz"
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<add>
<add> it "separates shell commands in Utils.popen_read" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo bar")
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo", "bar")
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<add>
<add> it "separates shell commands with string interpolation in Utils.popen_read" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("\#{foo}/bar baz")
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("\#{foo}/bar", "baz")
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<add>
<add> it "separates shell commands following a shell variable in Utils.popen_read" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read({ "SHELL" => "bash" }, "foo bar")
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read({ "SHELL" => "bash" }, "foo", "bar")
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<ide> end
<ide> end
<ide> | 2 |
Ruby | Ruby | add generic codesign_patched_binary method | 35f426e3e23efe1385bc30cda9923367dbd77ac6 | <ide><path>Library/Homebrew/keg.rb
<ide> def binary_executable_or_library_files
<ide> elf_files
<ide> end
<ide>
<add> def codesign_patched_binary(_binary_file); end
<add>
<ide> private
<ide>
<ide> def resolve_any_conflicts(dst, dry_run: false, verbose: false, overwrite: false) | 1 |
Go | Go | copy values out of hostconfig | 4e12484ea12d23fd70fd3bf636e786f4f741ab64 | <ide><path>daemon/container.go
<ide> func (container *Container) allocateNetwork() error {
<ide> if container.Config.ExposedPorts != nil {
<ide> portSpecs = container.Config.ExposedPorts
<ide> }
<add>
<ide> if container.hostConfig.PortBindings != nil {
<del> bindings = container.hostConfig.PortBindings
<add> for p, b := range container.hostConfig.PortBindings {
<add> bindings[p] = []nat.PortBinding{}
<add> for _, bb := range b {
<add> bindings[p] = append(bindings[p], nat.PortBinding{
<add> HostIp: bb.HostIp,
<add> HostPort: bb.HostPort,
<add> })
<add> }
<add> }
<ide> }
<ide>
<ide> container.NetworkSettings.PortMapping = nil | 1 |
Go | Go | fix flaky testexec | 0a7755ab4e2fc8df1992813d5364fe0f201ab913 | <ide><path>integration-cli/docker_cli_exec_test.go
<ide> import (
<ide>
<ide> func (s *DockerSuite) TestExec(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top")
<add> out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top")
<add> c.Assert(waitRun(strings.TrimSpace(out)), check.IsNil)
<ide>
<del> out, _ := dockerCmd(c, "exec", "testing", "cat", "/tmp/file")
<add> out, _ = dockerCmd(c, "exec", "testing", "cat", "/tmp/file")
<ide> out = strings.Trim(out, "\r\n")
<ide> c.Assert(out, checker.Equals, "test")
<ide>
<ide> func (s *DockerSuite) TestExecInteractive(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> out, _ := runSleepingContainer(c, "-d")
<add> out, _ := runSleepingContainer(c)
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide> c.Assert(waitRun(cleanedContainerID), check.IsNil)
<ide> dockerCmd(c, "restart", cleanedContainerID) | 1 |
Python | Python | check minimum icu in configure for system-icu | ed1c40e977cc5bb87645bc1dcf62d2e25386a2c0 | <ide><path>configure.py
<ide> dest='with_icu_source',
<ide> help='Intl mode: optional local path to icu/ dir, or path/URL of '
<ide> 'the icu4c source archive. '
<del> 'v%d.x or later recommended.' % icu_versions["minimum_icu"])
<add> 'v%d.x or later recommended.' % icu_versions['minimum_icu'])
<ide>
<ide> parser.add_option('--with-ltcg',
<ide> action='store_true',
<ide> def b(value):
<ide>
<ide>
<ide> def pkg_config(pkg):
<add> """Run pkg-config on the specified package
<add> Returns ("-l flags", "-I flags", "-L flags", "version")
<add> otherwise (None, None, None, None)"""
<ide> pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
<ide> retval = ()
<del> for flag in ['--libs-only-l', '--cflags-only-I', '--libs-only-L']:
<add> for flag in ['--libs-only-l', '--cflags-only-I',
<add> '--libs-only-L', '--modversion']:
<ide> try:
<ide> proc = subprocess.Popen(
<ide> shlex.split(pkg_config) + ['--silence-errors', flag, pkg],
<ide> stdout=subprocess.PIPE)
<ide> val = proc.communicate()[0].strip()
<ide> except OSError as e:
<ide> if e.errno != errno.ENOENT: raise e # Unexpected error.
<del> return (None, None, None) # No pkg-config/pkgconf installed.
<add> return (None, None, None, None) # No pkg-config/pkgconf installed.
<ide> retval += (val,)
<ide> return retval
<ide>
<ide> def configure_library(lib, output):
<ide> output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib))
<ide>
<ide> if getattr(options, shared_lib):
<del> (pkg_libs, pkg_cflags, pkg_libpath) = pkg_config(lib)
<add> (pkg_libs, pkg_cflags, pkg_libpath, pkg_modversion) = pkg_config(lib)
<ide>
<ide> if options.__dict__[shared_lib + '_includes']:
<ide> output['include_dirs'] += [options.__dict__[shared_lib + '_includes']]
<ide> def write_config(data, name):
<ide> if pkgicu[0] is None:
<ide> error('''Could not load pkg-config data for "icu-i18n".
<ide> See above errors or the README.md.''')
<del> (libs, cflags, libpath) = pkgicu
<add> (libs, cflags, libpath, icuversion) = pkgicu
<add> icu_ver_major = icuversion.split('.')[0]
<add> o['variables']['icu_ver_major'] = icu_ver_major
<add> if int(icu_ver_major) < icu_versions['minimum_icu']:
<add> error('icu4c v%s is too old, v%d.x or later is required.' %
<add> (icuversion, icu_versions['minimum_icu']))
<ide> # libpath provides linker path which may contain spaces
<ide> if libpath:
<ide> o['libraries'] += [libpath]
<ide> def write_config(data, name):
<ide> icu_ver_major = m.group(1)
<ide> if not icu_ver_major:
<ide> error('Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h)
<del> elif int(icu_ver_major) < icu_versions["minimum_icu"]:
<del> error('icu4c v%d.x is too old, v%d.x or later is required.' % (int(icu_ver_major),
<del> icu_versions["minimum_icu"]))
<add> elif int(icu_ver_major) < icu_versions['minimum_icu']:
<add> error('icu4c v%s.x is too old, v%d.x or later is required.' %
<add> (icu_ver_major, icu_versions['minimum_icu']))
<ide> icu_endianness = sys.byteorder[0];
<ide> o['variables']['icu_ver_major'] = icu_ver_major
<ide> o['variables']['icu_endianness'] = icu_endianness | 1 |
Javascript | Javascript | add ember.select control | 8061b909c33024b93ec163882be3ec7dad921495 | <ide><path>packages/ember-handlebars/lib/controls.js
<ide> require("ember-handlebars/controls/button");
<ide> require("ember-handlebars/controls/radio_button");
<ide> require("ember-handlebars/controls/text_area");
<ide> require("ember-handlebars/controls/tabs");
<add>require("ember-handlebars/controls/select");
<ide><path>packages/ember-handlebars/lib/controls/select.js
<add>var set = Ember.set, get = Ember.get, getPath = Ember.getPath;
<add>
<add>Ember.Select = Ember.CollectionView.extend({
<add> tagName: 'select',
<add>
<add> optionLabelPath: 'content',
<add> optionValuePath: 'content',
<add>
<add> selection: null,
<add>
<add> didInsertElement: function() {
<add> var selection = get(this, 'selection');
<add>
<add> if (selection) { this.selectionDidChange(); }
<add>
<add> this.change();
<add> },
<add>
<add> change: function() {
<add> var selectedIndex = this.$()[0].selectedIndex,
<add> content = get(this, 'content');
<add>
<add> if (!content) { return; }
<add>
<add> set(this, 'selection', content.objectAt(selectedIndex));
<add> },
<add>
<add> selectionDidChange: Ember.observer(function() {
<add> var el = this.$()[0],
<add> content = get(this, 'content'),
<add> selection = get(this, 'selection'),
<add> selectionIndex = content.indexOf(selection);
<add>
<add> if (el) { el.selectedIndex = selectionIndex; }
<add> }, 'selection'),
<add>
<add> itemViewClass: Ember.View.extend({
<add> template: Ember.Handlebars.compile("{{label}}"),
<add> attributeBindings: ['value'],
<add>
<add> init: function() {
<add> this.labelPathDidChange();
<add> this.valuePathDidChange();
<add>
<add> this._super();
<add> },
<add>
<add> labelPathDidChange: Ember.observer(function() {
<add> var labelPath = getPath(this, 'parentView.optionLabelPath');
<add>
<add> if (!labelPath) { return; }
<add>
<add> Ember.defineProperty(this, 'label', Ember.computed(function() {
<add> return getPath(this, labelPath);
<add> }).property(labelPath).cacheable());
<add> }, 'parentView.optionLabelPath'),
<add>
<add> valuePathDidChange: Ember.observer(function() {
<add> var valuePath = getPath(this, 'parentView.optionValuePath');
<add>
<add> if (!valuePath) { return; }
<add>
<add> Ember.defineProperty(this, 'value', Ember.computed(function() {
<add> return getPath(this, valuePath);
<add> }).property(valuePath).cacheable());
<add> }, 'parentView.optionValuePath')
<add> })
<add>});
<ide><path>packages/ember-handlebars/tests/controls/select_test.js
<add>var application, select;
<add>
<add>module("Ember.Select", {
<add> setup: function() {
<add> application = Ember.Application.create();
<add> select = Ember.Select.create();
<add> },
<add>
<add> teardown: function() {
<add> select.destroy();
<add> application.destroy();
<add> }
<add>});
<add>
<add>function append() {
<add> Ember.run(function() {
<add> select.appendTo('#qunit-fixture');
<add> });
<add>}
<add>
<add>test("should render", function() {
<add> append();
<add>
<add> ok(select.$().length, "Select renders");
<add>});
<add>
<add>test("can have options", function() {
<add> select.set('content', Ember.A([1, 2, 3]));
<add>
<add> append();
<add>
<add> equals(select.$('option').length, 3, "Should have three options");
<add> equals(select.$().text(), "123", "Options should have content");
<add>});
<add>
<add>test("can specify the property path for an option's label and value", function() {
<add> select.set('content', Ember.A([
<add> { id: 1, firstName: 'Yehuda' },
<add> { id: 2, firstName: 'Tom' }
<add> ]));
<add>
<add> select.set('optionLabelPath', 'content.firstName');
<add> select.set('optionValuePath', 'content.id');
<add>
<add> append();
<add>
<add> equals(select.$('option').length, 2, "Should have two options");
<add> equals(select.$().text(), "YehudaTom", "Options should have content");
<add> deepEqual(select.$('option').toArray().map(function(el) { return $(el).attr('value'); }), ["1", "2"], "Options should have values");
<add>});
<add>
<add>test("can retrieve the current selected option", function() {
<add> var yehuda = { id: 1, firstName: 'Yehuda' },
<add> tom = { id: 2, firstName: 'Tom' };
<add> select.set('content', Ember.A([yehuda, tom]));
<add>
<add> append();
<add>
<add> equals(select.get('selection'), yehuda, "By default, the first option is selected");
<add>
<add> select.$()[0].selectedIndex = 1; // select Tom
<add> select.$().trigger('change');
<add>
<add> equals(select.get('selection'), tom, "On change, the new option should be selected");
<add>});
<add>
<add>test("selection can be set", function() {
<add> var yehuda = { id: 1, firstName: 'Yehuda' },
<add> tom = { id: 2, firstName: 'Tom' };
<add> select.set('content', Ember.A([yehuda, tom]));
<add>
<add> select.set('selection', tom);
<add>
<add> append();
<add>
<add> equals(select.get('selection'), tom, "Initial selection should be correct");
<add>
<add> select.set('selection', yehuda);
<add>
<add> equals(select.$()[0].selectedIndex, 0, "After changing it, selection should be correct");
<add>}); | 3 |
Javascript | Javascript | add test for template literal analysis | 154c5799f8119aff637b03ddfe53f2cb627b53c4 | <ide><path>test/Parser.test.js
<ide> describe("Parser", () => {
<ide> "b.Number": "number=123",
<ide> "b['Number']": "number=123",
<ide> "b[Number]": "",
<add> "`start${obj}mid${obj2}end`": "template=[start string=start],[mid string=mid],[end string=end]", // eslint-disable-line no-template-curly-in-string
<add> "`start${'str'}mid${obj2}end`": "template=[start${'str'}mid string=startstrmid],[end string=end]", // eslint-disable-line no-template-curly-in-string
<ide> "'abc'.substr(1)": "string=bc",
<ide> "'abcdef'.substr(2, 3)": "string=cde",
<ide> "'abcdef'.substring(2, 3)": "string=c",
<ide> describe("Parser", () => {
<ide> if(evalExpr.isConditional()) result.push("options=[" + evalExpr.options.map(evalExprToString).join("],[") + "]");
<ide> if(evalExpr.isArray()) result.push("items=[" + evalExpr.items.map(evalExprToString).join("],[") + "]");
<ide> if(evalExpr.isConstArray()) result.push("array=[" + evalExpr.array.join("],[") + "]");
<add> if(evalExpr.isTemplateString()) result.push("template=[" + evalExpr.quasis.map(evalExprToString).join("],[") + "]");
<ide> if(evalExpr.isWrapped()) result.push("wrapped=[" + evalExprToString(evalExpr.prefix) + "]+[" + evalExprToString(evalExpr.postfix) + "]");
<ide> if(evalExpr.range) {
<ide> const start = evalExpr.range[0] - 5; | 1 |
Javascript | Javascript | fix lint error | 9157597175822fba5ebc0b09827abbd31062a8a9 | <ide><path>web/viewer.js
<ide> window.addEventListener('scalechange', function scalechange(evt) {
<ide> return;
<ide> }
<ide>
<del> var predefinedValueFound = selectScaleOption('' + evt.scale);
<add> var predefinedValueFound = selectScaleOption('' + evt.scale);
<ide> if (!predefinedValueFound) {
<ide> customScaleOption.textContent = Math.round(evt.scale * 10000) / 100 + '%';
<ide> customScaleOption.selected = true; | 1 |
PHP | PHP | implement the querycacher class | ff57e192241801b09c1a00075562cf9e7a686832 | <ide><path>Cake/ORM/QueryCacher.php
<ide> */
<ide> namespace Cake\ORM;
<ide>
<add>use Cake\Cache\Cache;
<add>use Cake\Cache\CacheEngine;
<ide> use Cake\ORM\Query;
<add>use RuntimeException;
<ide>
<ide> /**
<ide> * Handles caching queries and loading results from the cache.
<ide> class QueryCacher {
<ide> * @param string|CacheEngine $config
<ide> */
<ide> public function __construct($key, $config) {
<add> if (!is_string($key) && !is_callable($key)) {
<add> throw new RuntimeException('Cache keys must be strings or callables.');
<add> }
<ide> $this->_key = $key;
<add>
<add> if (!is_string($config) && !($config instanceof CacheEngine)) {
<add> throw new RuntimeException('Cache configs must be strings or CacheEngine instances.');
<add> }
<ide> $this->_config = $config;
<ide> }
<ide>
<ide> public function __construct($key, $config) {
<ide> * @return ResultSet|null Either the cached results or null.
<ide> */
<ide> public function fetch(Query $query) {
<add> $key = $this->_resolveKey($query);
<add> $storage = $this->_resolveCacher();
<add> $result = $storage->read($key);
<add> if (empty($result)) {
<add> return null;
<add> }
<add> return $result;
<add> }
<add>
<add>/**
<add> * Get/generate the cache key.
<add> *
<add> * @param Query $query
<add> * @return string
<add> */
<add> protected function _resolveKey($query) {
<add> if (is_string($this->_key)) {
<add> return $this->_key;
<add> }
<add> $func = $this->_key;
<add> $key = $func($query);
<add> if (!is_string($key)) {
<add> $msg = sprintf('Cache key functions must return a string. Got %s.', var_export($key, true));
<add> throw new RuntimeException($msg);
<add> }
<add> return $key;
<add> }
<add>
<add>/**
<add> * Get the cache engine.
<add> *
<add> * @return Cake\Cache\CacheEngine
<add> */
<add> protected function _resolveCacher() {
<add> if (is_string($this->_config)) {
<add> return Cache::engine($this->_config);
<add> }
<add> return $this->_config;
<ide> }
<ide>
<ide> }
<ide><path>Cake/Test/TestCase/ORM/QueryCacherTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<add>use Cake\Cache\Cache;
<add>use Cake\ORM\QueryCacher;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> class QueryCacherTest extends TestCase {
<ide> public function setUp() {
<ide> parent::setUp();
<ide> $this->engine = $this->getMock('Cake\Cache\CacheEngine');
<add> $this->engine->expects($this->any())
<add> ->method('init')
<add> ->will($this->returnValue(true));
<add>
<ide> Cache::config('queryCache', $this->engine);
<ide> }
<ide>
<ide> public function tearDown() {
<ide> * @return void
<ide> */
<ide> public function testFetchFunctionKey() {
<add> $this->_mockRead('my_key', 'A winner');
<add> $query = $this->getMock('Cake\ORM\Query', [], [], '', false);
<add>
<add> $cacher = new QueryCacher(function($q) use ($query) {
<add> $this->assertSame($query, $q);
<add> return 'my_key';
<add> }, 'queryCache');
<add>
<add> $result = $cacher->fetch($query);
<add> $this->assertEquals('A winner', $result);
<ide> }
<ide>
<ide> /**
<ide> * Test fetching with a function to generate the key but the function is poop.
<ide> *
<add> * @expectedException \RuntimeException
<add> * @expectedExceptionMessage Cache key functions must return a string. Got false.
<ide> * @return void
<ide> */
<ide> public function testFetchFunctionKeyNoString() {
<add> $this->_mockRead('my_key', 'A winner');
<add> $query = $this->getMock('Cake\ORM\Query', [], [], '', false);
<add>
<add> $cacher = new QueryCacher(function($q) {
<add> return false;
<add> }, 'queryCache');
<add>
<add> $cacher->fetch($query);
<ide> }
<ide>
<ide> /**
<ide> * Test fetching with a cache instance.
<ide> *
<ide> * @return void
<ide> */
<del> public function testFetchCacheInstance() {
<add> public function testFetchCacheHitStringEngine() {
<add> $this->_mockRead('my_key', 'A winner');
<add> $cacher = new QueryCacher('my_key', 'queryCache');
<add> $query = $this->getMock('Cake\ORM\Query', [], [], '', false);
<add> $result = $cacher->fetch($query);
<add> $this->assertEquals('A winner', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testFetchCacheInstance() {
<ide> * @return void
<ide> */
<ide> public function testFetchCacheHit() {
<add> $this->_mockRead('my_key', 'A winner');
<add> $cacher = new QueryCacher('my_key', $this->engine);
<add> $query = $this->getMock('Cake\ORM\Query', [], [], '', false);
<add> $result = $cacher->fetch($query);
<add> $this->assertEquals('A winner', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testFetchCacheHit() {
<ide> * @return void
<ide> */
<ide> public function testFetchCacheMiss() {
<add> $this->_mockRead('my_key', false);
<add> $cacher = new QueryCacher('my_key', $this->engine);
<add> $query = $this->getMock('Cake\ORM\Query', [], [], '', false);
<add> $result = $cacher->fetch($query);
<add> $this->assertNull($result, 'Cache miss should not have an isset() return.');
<add> }
<add>
<add>/**
<add> * Helper for building mocks.
<add> */
<add> protected function _mockRead($key, $value = false) {
<add> $this->engine->expects($this->any())
<add> ->method('read')
<add> ->with($key)
<add> ->will($this->returnValue($value));
<ide> }
<ide>
<ide> } | 2 |
Ruby | Ruby | apply suggestions from code review | 0118e6ec41a4fb2e2638165fee0a4f492f19bf81 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report
<ide>
<ide> if ENV["HOMEBREW_CORE_DEFAULT_GIT_REMOTE"] != ENV["HOMEBREW_CORE_GIT_REMOTE"]
<ide> opoo <<~EOS
<del> HOMEBREW_CORE_GIT_REMOTE was set. It has been unset for the migration.
<add> HOMEBREW_CORE_GIT_REMOTE was set: #{ENV["HOMEBREW_CORE_GIT_REMOTE"]}.
<add> It has been unset for the migration.
<ide> You may need to change this from a linuxbrew-core mirror to a homebrew-core one.
<ide>
<ide> EOS
<ide> def update_report
<ide>
<ide> if ENV["HOMEBREW_BOTTLE_DEFAULT_DOMAIN"] != ENV["HOMEBREW_BOTTLE_DOMAIN"]
<ide> opoo <<~EOS
<del> HOMEBREW_BOTTLE_DOMAIN was set. It has been unset for the migration.
<del> You may need to change this Linuxbrew packages to Homebrew packages.
<add> HOMEBREW_BOTTLE_DOMAIN was set: #{ENV["HOMEBREW_BOTTLE_DOMAIN"]}.
<add> It has been unset for the migration.
<add> You may need to change this from a Linuxbrew package mirror to a Homebrew one.
<ide>
<ide> EOS
<ide> end
<ide><path>Library/Homebrew/extend/os/linux/diagnostic.rb
<ide> def check_linuxbrew_core
<ide> end
<ide>
<ide> def check_linuxbrew_bottle_domain
<del> return unless Homebrew::EnvConfig.bottle_domain.include?("linuxbrew-core")
<add> return unless Homebrew::EnvConfig.bottle_domain.include?("linuxbrew")
<ide>
<ide> <<~EOS
<del> Your HOMEBREW_BOTTLE_DOMAIN still contains linuxbrew-core.
<del> You must unset it (or adjust it to not contain linuxbrew-core
<del> e.g. by using homebrew-core instead).
<add> Your HOMEBREW_BOTTLE_DOMAIN still contains "linuxbrew".
<add> You must unset it (or adjust it to not contain linuxbrew
<add> e.g. by using homebrew instead).
<ide> EOS
<ide> end
<ide> end | 2 |
Ruby | Ruby | use canonical name for default formula | 2f02942a84c641ac8890654a0bf7f239029d6f34 | <ide><path>Library/Homebrew/requirements.rb
<ide> def message; <<-EOS.undent
<ide>
<ide> class PostgresqlDependency < Requirement
<ide> fatal true
<del> default_formula 'postgres'
<add> default_formula 'postgresql'
<ide>
<ide> satisfy { which 'pg_config' }
<ide> | 1 |
Javascript | Javascript | reset awaitdrain after manual .resume() | e2e615e87e52773274619d0167716a766c16ac64 | <ide><path>lib/_stream_readable.js
<ide> function resume_(stream, state) {
<ide> }
<ide>
<ide> state.resumeScheduled = false;
<add> state.awaitDrain = 0;
<ide> stream.emit('resume');
<ide> flow(stream);
<ide> if (state.flowing && !state.reading)
<ide><path>test/parallel/test-stream-pipe-await-drain-manual-resume.js
<add>'use strict';
<add>const common = require('../common');
<add>const stream = require('stream');
<add>
<add>// A consumer stream with a very low highWaterMark, which starts in a state
<add>// where it buffers the chunk it receives rather than indicating that they
<add>// have been consumed.
<add>const writable = new stream.Writable({
<add> highWaterMark: 5
<add>});
<add>
<add>let isCurrentlyBufferingWrites = true;
<add>const queue = [];
<add>
<add>writable._write = (chunk, encoding, cb) => {
<add> if (isCurrentlyBufferingWrites)
<add> queue.push({chunk, cb});
<add> else
<add> cb();
<add>};
<add>
<add>const readable = new stream.Readable({
<add> read() {}
<add>});
<add>
<add>readable.pipe(writable);
<add>
<add>readable.once('pause', common.mustCall(() => {
<add> // First pause, resume manually. The next write() to writable will still
<add> // return false, because chunks are still being buffered, so it will increase
<add> // the awaitDrain counter again.
<add> process.nextTick(common.mustCall(() => {
<add> readable.resume();
<add> }));
<add>
<add> readable.once('pause', common.mustCall(() => {
<add> // Second pause, handle all chunks from now on. Once all callbacks that
<add> // are currently queued up are handled, the awaitDrain drain counter should
<add> // fall back to 0 and all chunks that are pending on the readable side
<add> // should be flushed.
<add> isCurrentlyBufferingWrites = false;
<add> for (const queued of queue)
<add> queued.cb();
<add> }));
<add>}));
<add>
<add>readable.push(Buffer.alloc(100)); // Fill the writable HWM, first 'pause'.
<add>readable.push(Buffer.alloc(100)); // Second 'pause'.
<add>readable.push(Buffer.alloc(100)); // Should get through to the writable.
<add>readable.push(null);
<add>
<add>writable.on('finish', common.mustCall(() => {
<add> // Everything okay, all chunks were written.
<add>})); | 2 |
Text | Text | add docs on testing | c5c9b3c1907b8213e137c343ab6f5934a52f5491 | <ide><path>docs/NativeModulesIOS.md
<ide> title: Native Modules (iOS)
<ide> layout: docs
<ide> category: Guides
<ide> permalink: docs/nativemodulesios.html
<del>next: activityindicatorios
<add>next: testing
<ide> ---
<ide>
<ide> Sometimes an app needs access to platform API, and React Native doesn't have a corresponding wrapper yet. Maybe you want to reuse some existing Objective-C or C++ code without having to reimplement it in JavaScript. Or write some high performance, multi-threaded code such as image processing, network stack, database or rendering.
<ide> var subscription = DeviceEventEmitter.addListener(
<ide> subscription.remove();
<ide> ```
<ide> For more examples of sending events to JavaScript, see [`RCTLocationObserver`](https://github.com/facebook/react-native/blob/master/Libraries/Geolocation/RCTLocationObserver.m).
<del>
<ide><path>docs/Testing.md
<add>---
<add>id: testing
<add>title: Testing
<add>layout: docs
<add>category: Guides
<add>permalink: docs/testing.html
<add>next: activityindicatorios
<add>---
<add>
<add>## Running Tests and Contributing
<add>
<add>The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the [Travis](http://docs.travis-ci.com/) continuous integration system, and will automatically post the results to your PR. You can also run them locally with cmd+U in the IntegrationTest and UIExplorer apps in Xcode. You can run the jest tests via `npm test` on the command line. We don't have great test coverage yet, however, so most changes will still require significant manual verification, but we would love it if you want to help us increase our test coverage!
<add>
<add>## Jest Tests
<add>
<add>[Jest](http://facebook.github.io/jest/) tests are JS-only tests run on the command line with node. The tests themselves live in the `__tests__` directories of the files they test, and there is a large emphasis on aggressively mocking out functionality that is not under test for failure isolation and maximum speed. You can run the existing React Native jest tests with `npm test` from the react-native root, and we encourage you to add your own tests for any components you want to contribute to. See [`getImageSource-test.js`](https://github.com/facebook/react-native/blob/master/Examples/Movies/__tests__/getImageSource-test.js) for a basic example.
<add>
<add>## Integration Tests.
<add>
<add>React Native provides facilities to make it easier to test integrated components that require both native and JS components to communicate across the bridge. The two main components are `RCTTestRunner` and `RCTTestModule`. `RCTTestRunner` sets up the ReactNative environment and provides facilities to run the tests as `XCTestCase`s in Xcode (`runTest:module` is the simplest method). `RCTTestModule` is exported to JS via `NativeModules` as `TestModule`. The tests themselves are written in JS, and must call `TestModule.markTestCompleted()` when they are done, otherwise the test will timeout and fail. Test failures are primarily indicated by throwing an exception. It is also possible to test error conditions with `runTest:module:initialProps:expectErrorRegex:` or `runTest:module:initialProps:expectErrorBlock:` which will expect an error to be thrown and verify the error matches the provided criteria. See [`IntegrationTestHarnessTest.js`](https://github.com/facebook/react-native/blob/master/IntegrationTests/IntegrationTestHarnessTest.js) and [`IntegrationTestsTests.m`](https://github.com/facebook/react-native/blob/master/IntegrationTests/IntegrationTestsTests/IntegrationTestsTests.m) for example usage.
<add>
<add>## Snapshot Tests
<add>
<add>A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using `TestModule.verifySnapshot()`, using the [`FBSnapshotTestCase`](https://github.com/facebook/ios-snapshot-test-case) library behind the scenes. Reference images are recorded by setting `recordMode = YES` on the `RCTTestRunner`, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See [`SimpleSnapshotTest`](https://github.com/facebook/react-native/blob/master/IntegrationTests/SimpleSnapshotTest.js) for a basic example. | 2 |
Text | Text | add simple docs on statics to reference section | 31bc18d39e1c194fcd451e48964c9813b9993d27 | <ide><path>docs/docs/ref-03-component-specs.md
<ide> The `mixins` array allows you to use mixins to share behavior among multiple com
<ide> <!-- TODO: Document mixins here directly. -->
<ide>
<ide>
<add>### statics
<add>
<add>```javascript
<add>object statics
<add>```
<add>
<add>The `statics` object allows you to define static methods that can be called on the component class. For example:
<add>
<add>```javascript
<add>var MyComponent = React.createClass({
<add> statics: {
<add> customMethod: function(foo) {
<add> return foo === 'bar';
<add> }
<add> },
<add> render: function() {
<add> }
<add>});
<add>
<add>MyComponent.customMethod('bar'); // true
<add>```
<add>
<add>Methods defined within this block are _static_, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method.
<add>
<add>
<ide> ### displayName
<ide>
<ide> ```javascript | 1 |
Python | Python | fix conditional convs by adding relu | 65407126c5adc216d606d360429fe12ed3c3f187 | <ide><path>research/object_detection/meta_architectures/deepmac_meta_arch.py
<ide> def per_pixel_conditional_conv(input_tensor, parameters, channels, depth):
<ide> output = input_tensor
<ide> for i in range(depth):
<ide>
<del> if i == (depth - 1):
<add> is_last_layer = i == (depth - 1)
<add> if is_last_layer:
<ide> channels = 1
<ide>
<ide> num_params_single_conv = channels * input_channels + channels
<ide> params = parameters[:, start:start + num_params_single_conv]
<ide>
<ide> start += num_params_single_conv
<ide> output = _per_pixel_single_conv(output, params, channels)
<add>
<add> if not is_last_layer:
<add> output = tf.nn.relu(output)
<add>
<ide> input_channels = channels
<ide>
<ide> return output
<ide><path>research/object_detection/meta_architectures/deepmac_meta_arch_test.py
<ide> def test_per_pixel_conditional_conv_depth1_error(self):
<ide> _ = deepmac_meta_arch.per_pixel_conditional_conv(
<ide> tf.zeros((10, 32, 32, 7)), tf.zeros((10, 8)), 99, 1)
<ide>
<del> def test_per_pixel_conditional_conv_depth1(self):
<add> @parameterized.parameters([
<add> {
<add> 'num_input_channels': 7,
<add> 'instance_embedding_dim': 8,
<add> 'channels': 7,
<add> 'depth': 1
<add> },
<add> {
<add> 'num_input_channels': 7,
<add> 'instance_embedding_dim': 82,
<add> 'channels': 9,
<add> 'depth': 2
<add> },
<add> { # From https://arxiv.org/abs/2003.05664
<add> 'num_input_channels': 10,
<add> 'instance_embedding_dim': 169,
<add> 'channels': 8,
<add> 'depth': 3
<add> },
<add> {
<add> 'num_input_channels': 8,
<add> 'instance_embedding_dim': 433,
<add> 'channels': 16,
<add> 'depth': 3
<add> },
<add> {
<add> 'num_input_channels': 8,
<add> 'instance_embedding_dim': 1377,
<add> 'channels': 32,
<add> 'depth': 3
<add> },
<add> {
<add> 'num_input_channels': 8,
<add> 'instance_embedding_dim': 4801,
<add> 'channels': 64,
<add> 'depth': 3
<add> },
<add> ])
<add> def test_per_pixel_conditional_conv_shape(
<add> self, num_input_channels, instance_embedding_dim, channels, depth):
<ide>
<ide> out = deepmac_meta_arch.per_pixel_conditional_conv(
<del> tf.zeros((10, 32, 32, 7)), tf.zeros((10, 8)), 7, 1)
<add> tf.zeros((10, 32, 32, num_input_channels)),
<add> tf.zeros((10, instance_embedding_dim)), channels, depth)
<ide>
<ide> self.assertEqual(out.shape, (10, 32, 32, 1))
<ide>
<del> def test_per_pixel_conditional_conv_depth2(self):
<add> def test_per_pixel_conditional_conv_value_depth1(self):
<ide>
<del> num_params = (
<del> 7 * 9 + 9 + # layer 1
<del> 9 + 1) # layer 2
<add> input_tensor = tf.constant(np.array([1, 2, 3]))
<add> input_tensor = tf.reshape(input_tensor, (1, 1, 1, 3))
<add> instance_embedding = tf.constant(
<add> np.array([1, 10, 100, 1000]))
<add> instance_embedding = tf.reshape(instance_embedding, (1, 4))
<ide> out = deepmac_meta_arch.per_pixel_conditional_conv(
<del> tf.zeros((10, 32, 32, 7)), tf.zeros((10, num_params)), 9, 2)
<add> input_tensor, instance_embedding, channels=3, depth=1)
<ide>
<del> self.assertEqual(out.shape, (10, 32, 32, 1))
<add> expected_output = np.array([1321])
<add> expected_output = np.reshape(expected_output, (1, 1, 1, 1))
<add> self.assertAllClose(expected_output, out)
<ide>
<del> def test_per_pixel_conditional_conv_depth3(self):
<add> def test_per_pixel_conditional_conv_value_depth2_single(self):
<ide>
<del> # From the paper https://arxiv.org/abs/2003.05664
<add> input_tensor = tf.constant(np.array([2]))
<add> input_tensor = tf.reshape(input_tensor, (1, 1, 1, 1))
<add> instance_embedding = tf.constant(
<add> np.array([-2, 3, 100, 5]))
<add> instance_embedding = tf.reshape(instance_embedding, (1, 4))
<ide> out = deepmac_meta_arch.per_pixel_conditional_conv(
<del> tf.zeros((10, 32, 32, 10)), tf.zeros((10, 169)), 8, 3)
<add> input_tensor, instance_embedding, channels=1, depth=2)
<ide>
<del> self.assertEqual(out.shape, (10, 32, 32, 1))
<add> expected_output = np.array([5])
<add> expected_output = np.reshape(expected_output, (1, 1, 1, 1))
<add> self.assertAllClose(expected_output, out)
<add>
<add> def test_per_pixel_conditional_conv_value_depth2_identity(self):
<add>
<add> input_tensor = tf.constant(np.array([1, 2]))
<add> input_tensor = tf.reshape(input_tensor, (1, 1, 1, 2))
<add> instance_embedding = tf.constant(
<add> np.array([1, 0, 0, 1, 1, -3, 5, 100, -9]))
<add> instance_embedding = tf.reshape(
<add> instance_embedding, (1, 9))
<add> out = deepmac_meta_arch.per_pixel_conditional_conv(
<add> input_tensor, instance_embedding, channels=2, depth=2)
<add>
<add> expected_output = np.array([1])
<add> expected_output = np.reshape(expected_output, (1, 1, 1, 1))
<add> self.assertAllClose(expected_output, out)
<ide>
<ide>
<ide> @unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.')
<ide> def test_mask_network_embedding_projection_small(self):
<ide> self.assertAllLess(out.numpy(), np.inf)
<ide>
<ide> @parameterized.parameters([
<del> {'mask_net': 'resnet4', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 4, 'input_channels': 16,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'hourglass10', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 4, 'input_channels': 16,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'hourglass20', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 4, 'input_channels': 16,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'cond_inst3', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 153, 'input_channels': 8,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'cond_inst3', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 169, 'input_channels': 10,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'cond_inst1', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 9, 'input_channels': 8,
<del> 'use_instance_embedding': False},
<del> {'mask_net': 'cond_inst2', 'mask_net_channels': 8,
<del> 'instance_embedding_dim': 81, 'input_channels': 8,
<del> 'use_instance_embedding': False},
<add> {
<add> 'mask_net': 'resnet4',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 4,
<add> 'input_channels': 16,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'hourglass10',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 4,
<add> 'input_channels': 16,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'hourglass20',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 4,
<add> 'input_channels': 16,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'cond_inst3',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 153,
<add> 'input_channels': 8,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'cond_inst3',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 169,
<add> 'input_channels': 10,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'cond_inst1',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 9,
<add> 'input_channels': 8,
<add> 'use_instance_embedding': False
<add> },
<add> {
<add> 'mask_net': 'cond_inst2',
<add> 'mask_net_channels': 8,
<add> 'instance_embedding_dim': 81,
<add> 'input_channels': 8,
<add> 'use_instance_embedding': False
<add> },
<ide> ])
<ide> def test_mask_network(self, mask_net, mask_net_channels,
<ide> instance_embedding_dim, input_channels, | 2 |
Python | Python | add files via upload | 1568432e82cfc69c7c02b334e0bcc89542d79881 | <ide><path>Project Euler/Problem 01/sol4.py
<add>def mulitples(limit):
<add> xmulti = []
<add> zmulti = []
<add> z = 3
<add> x = 5
<add> temp = 1
<add> while True:
<add> result = z * temp
<add> if (result < limit):
<add> zmulti.append(result)
<add> temp += 1
<add> continue
<add> else:
<add> temp = 1
<add> break
<add> while True:
<add> result = x * temp
<add> if (result < limit):
<add> xmulti.append(result)
<add> temp += 1
<add> continue
<add> else:
<add> temp = 1
<add> break
<add> return (sum(zmulti) + sum(xmulti))
<add>
<add>
<add>
<add>
<add>
<add>
<add>print (mulitples(100)) | 1 |
PHP | PHP | add tests for previous commit | fde081f105664d435d39bafb031a1f10e4c593e1 | <ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> public function testProperty()
<ide> $this->assertEquals('thing', $this->association->property());
<ide> }
<ide>
<add> /**
<add> * Test that warning is shown if property name clashes with table field.
<add> *
<add> * @return void
<add> * @expectedException PHPUnit_Framework_Error_Warning
<add> */
<add> public function testPropertyNameClash()
<add> {
<add> $this->source->schema(['foo' => ['type' => 'string']]);
<add> $this->assertEquals('foo', $this->association->property());
<add> }
<add>
<add> /**
<add> * Test that warning is not shown if "propertyName" option is explicitly specified.
<add> *
<add> * @return void
<add> */
<add> public function testPropertyNameExplicitySet()
<add> {
<add> $this->source->schema(['foo' => ['type' => 'string']]);
<add>
<add> $config = [
<add> 'className' => '\Cake\Test\TestCase\ORM\TestTable',
<add> 'foreignKey' => 'a_key',
<add> 'conditions' => ['field' => 'value'],
<add> 'dependent' => true,
<add> 'sourceTable' => $this->source,
<add> 'joinType' => 'INNER',
<add> 'propertyName' => 'foo'
<add> ];
<add> $association = $this->getMock(
<add> '\Cake\ORM\Association',
<add> [
<add> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<add> 'saveAssociated', 'eagerLoader', 'type'
<add> ],
<add> ['Foo', $config]
<add> );
<add>
<add> $this->assertEquals('foo', $association->property());
<add> }
<add>
<ide> /**
<ide> * Tests strategy method
<ide> * | 1 |
Text | Text | use the gitlab link as project moved to gitlab | 5f939b6475c4eabbd758298d77aded9e568c85fa | <ide><path>docs/introduction/Ecosystem.md
<ide> Redux bindings for custom elements
<ide>
<ide> #### Reducer Combination
<ide>
<del>**[ryo33/combineSectionReducers](https://github.com/ryo33/combine-section-reducers)**
<add>**[ryo33/combineSectionReducers](https://gitlab.com/ryo33/combine-section-reducers)**
<ide> An expanded version of `combineReducers`, which allows passing `state` as a third argument to all slice reducers.
<ide>
<ide> **[KodersLab/topologically-combine-reducers](https://github.com/KodersLab/topologically-combine-reducers)** | 1 |
PHP | PHP | simplify the code for sanitize class | 44f8f84cd7e334535fda8edb725ad10b6e8f9bac | <ide><path>lib/Cake/Utility/Sanitize.php
<ide> public static function paranoid($string, $allowed = array()) {
<ide> }
<ide> }
<ide>
<del> if (is_array($string)) {
<del> $cleaned = array();
<del> foreach ($string as $key => $clean) {
<del> $cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
<del> }
<del> } else {
<del> $cleaned = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
<add> if (!is_array($string)) {
<add> return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
<add> }
<add>
<add> $cleaned = array();
<add> foreach ($string as $key => $clean) {
<add> $cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
<ide> }
<add>
<ide> return $cleaned;
<ide> }
<ide>
<ide> public static function escape($string, $connection = 'default') {
<ide> return $string;
<ide> }
<ide> $string = $db->value($string, 'string');
<del> if ($string[0] === 'N') {
<del> $string = substr($string, 2);
<del> } else {
<del> $string = substr($string, 1);
<add> $start = 1;
<add> if ($string{0} === 'N') {
<add> $start = 2;
<ide> }
<ide>
<del> $string = substr($string, 0, -1);
<del> return $string;
<add> return substr(substr($string, 1), 0, -1);
<ide> }
<ide>
<ide> /**
<ide> public static function html($string, $options = array()) {
<ide> * @return string whitespace sanitized string
<ide> */
<ide> public static function stripWhitespace($str) {
<del> $r = preg_replace('/[\n\r\t]+/', '', $str);
<del> return preg_replace('/\s{2,}/u', ' ', $r);
<add> return preg_replace('/\s{2,}/u', ' ', preg_replace('/[\n\r\t]+/', '', $str));
<ide> }
<ide>
<ide> /**
<ide> public static function stripWhitespace($str) {
<ide> * @return string Sting with images stripped.
<ide> */
<ide> public static function stripImages($str) {
<del> $str = preg_replace('/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i', '$1$3$5<br />', $str);
<del> $str = preg_replace('/(<img[^>]+alt=")([^"]*)("[^>]*>)/i', '$2<br />', $str);
<del> $str = preg_replace('/<img[^>]*>/i', '', $str);
<del> return $str;
<add> $preg = array(
<add> '/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i' => '$1$3$5<br />',
<add> '/(<img[^>]+alt=")([^"]*)("[^>]*>)/i' => '$2<br />',
<add> '/<img[^>]*>/i' => ''
<add> );
<add>
<add> return preg_replace(array_keys($preg), array_values($preg), $str);
<ide> }
<ide>
<ide> /**
<ide> public static function stripImages($str) {
<ide> * @return string String with <script>, <style>, <link>, <img> elements removed.
<ide> */
<ide> public static function stripScripts($str) {
<del> return preg_replace('/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/is', '', $str);
<add> $regex = '/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/is';
<add> return preg_replace($regex, '', $str);
<ide> }
<ide>
<ide> /**
<ide> public static function stripScripts($str) {
<ide> * @return string sanitized string
<ide> */
<ide> public static function stripAll($str) {
<del> $str = Sanitize::stripWhitespace($str);
<del> $str = Sanitize::stripImages($str);
<del> $str = Sanitize::stripScripts($str);
<del> return $str;
<add> return Sanitize::stripScripts(
<add> Sanitize::stripImages(
<add> Sanitize::stripWhitespace($str)
<add> )
<add> );
<ide> }
<ide>
<ide> /**
<ide> public static function clean($data, $options = array()) {
<ide> return $data;
<ide> }
<ide>
<del> if (is_string($options)) {
<add> if (!is_array($options)) {
<ide> $options = array('connection' => $options);
<del> } elseif (!is_array($options)) {
<del> $options = array();
<ide> }
<ide>
<ide> $options = array_merge(array(
<ide> public static function clean($data, $options = array()) {
<ide> $data[$key] = Sanitize::clean($val, $options);
<ide> }
<ide> return $data;
<del> } else {
<del> if ($options['odd_spaces']) {
<del> $data = str_replace(chr(0xCA), '', $data);
<del> }
<del> if ($options['encode']) {
<del> $data = Sanitize::html($data, array('remove' => $options['remove_html']));
<del> }
<del> if ($options['dollar']) {
<del> $data = str_replace("\\\$", "$", $data);
<del> }
<del> if ($options['carriage']) {
<del> $data = str_replace("\r", "", $data);
<del> }
<del> if ($options['unicode']) {
<del> $data = preg_replace("/&#([0-9]+);/s", "&#\\1;", $data);
<del> }
<del> if ($options['escape']) {
<del> $data = Sanitize::escape($data, $options['connection']);
<del> }
<del> if ($options['backslash']) {
<del> $data = preg_replace("/\\\(?!&#|\?#)/", "\\", $data);
<del> }
<del> return $data;
<ide> }
<del> }
<ide>
<add> if ($options['odd_spaces']) {
<add> $data = str_replace(chr(0xCA), '', $data);
<add> }
<add> if ($options['encode']) {
<add> $data = Sanitize::html($data, array('remove' => $options['remove_html']));
<add> }
<add> if ($options['dollar']) {
<add> $data = str_replace("\\\$", "$", $data);
<add> }
<add> if ($options['carriage']) {
<add> $data = str_replace("\r", "", $data);
<add> }
<add> if ($options['unicode']) {
<add> $data = preg_replace("/&#([0-9]+);/s", "&#\\1;", $data);
<add> }
<add> if ($options['escape']) {
<add> $data = Sanitize::escape($data, $options['connection']);
<add> }
<add> if ($options['backslash']) {
<add> $data = preg_replace("/\\\(?!&#|\?#)/", "\\", $data);
<add> }
<add> return $data;
<add> }
<ide> } | 1 |
Javascript | Javascript | add new reactperf | 67b1dbf75f3960c5aabf905876eddd5b1260c541 | <ide><path>grunt/tasks/npm-react-addons.js
<ide> var addons = {
<ide> docs: 'two-way-binding-helpers',
<ide> },
<ide> Perf: {
<del> module: 'ReactDefaultPerf',
<add> module: 'ReactPerfAnalysis',
<ide> name: 'perf',
<ide> docs: 'perf',
<ide> },
<ide><path>src/addons/ReactWithAddons.js
<ide> React.addons = {
<ide> };
<ide>
<ide> if (__DEV__) {
<del> React.addons.Perf = require('ReactDefaultPerf');
<add> React.addons.Perf = require('ReactPerfAnalysis');
<ide> React.addons.TestUtils = require('ReactTestUtils');
<ide> }
<ide>
<ide><path>src/isomorphic/ReactDebugTool.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactInvalidSetStateWarningDevTool = require('ReactInvalidSetStateWarningDevTool');
<add>var ExecutionEnvironment = require('ExecutionEnvironment');
<add>
<add>var performanceNow = require('performanceNow');
<ide> var warning = require('warning');
<ide>
<ide> var eventHandlers = [];
<ide> function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
<ide> }
<ide> }
<ide>
<add>var isProfiling = false;
<add>var flushHistory = [];
<add>var currentFlushNesting = 0;
<add>var currentFlushMeasurements = null;
<add>var currentFlushStartTime = null;
<add>var currentTimerDebugID = null;
<add>var currentTimerStartTime = null;
<add>var currentTimerType = null;
<add>
<add>function resetMeasurements() {
<add> if (__DEV__) {
<add> if (!isProfiling || currentFlushNesting === 0) {
<add> currentFlushStartTime = null;
<add> currentFlushMeasurements = null;
<add> return;
<add> }
<add>
<add> var previousStartTime = currentFlushStartTime;
<add> var previousMeasurements = currentFlushMeasurements || [];
<add> var previousOperations = ReactNativeOperationHistoryDevtool.getHistory();
<add>
<add> if (previousMeasurements.length || previousOperations.length) {
<add> var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs();
<add> flushHistory.push({
<add> duration: performanceNow() - previousStartTime,
<add> measurements: previousMeasurements || [],
<add> operations: previousOperations || [],
<add> treeSnapshot: registeredIDs.reduce((tree, id) => {
<add> var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
<add> var parentID = ReactComponentTreeDevtool.getParentID(id);
<add> tree[id] = {
<add> displayName: ReactComponentTreeDevtool.getDisplayName(id),
<add> text: ReactComponentTreeDevtool.getText(id),
<add> childIDs: ReactComponentTreeDevtool.getChildIDs(id),
<add> // Text nodes don't have owners but this is close enough.
<add> ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
<add> parentID,
<add> };
<add> return tree;
<add> }, {}),
<add> });
<add> }
<add>
<add> currentFlushStartTime = performanceNow();
<add> currentFlushMeasurements = [];
<add> ReactComponentTreeDevtool.purgeUnmountedComponents();
<add> ReactNativeOperationHistoryDevtool.clearHistory();
<add> }
<add>}
<add>
<ide> var ReactDebugTool = {
<ide> addDevtool(devtool) {
<ide> eventHandlers.push(devtool);
<ide> var ReactDebugTool = {
<ide> }
<ide> }
<ide> },
<add> beginProfiling() {
<add> if (__DEV__) {
<add> if (isProfiling) {
<add> return;
<add> }
<add>
<add> isProfiling = true;
<add> flushHistory.length = 0;
<add> resetMeasurements();
<add> }
<add> },
<add> endProfiling() {
<add> if (__DEV__) {
<add> if (!isProfiling) {
<add> return;
<add> }
<add>
<add> isProfiling = false;
<add> resetMeasurements();
<add> }
<add> },
<add> getFlushHistory() {
<add> if (__DEV__) {
<add> return flushHistory;
<add> }
<add> },
<add> onBeginFlush() {
<add> if (__DEV__) {
<add> currentFlushNesting++;
<add> resetMeasurements();
<add> }
<add> emitEvent('onBeginFlush');
<add> },
<add> onEndFlush() {
<add> if (__DEV__) {
<add> resetMeasurements();
<add> currentFlushNesting--;
<add> }
<add> emitEvent('onEndFlush');
<add> },
<add> onBeginLifeCycleTimer(debugID, timerType) {
<add> emitEvent('onBeginLifeCycleTimer', debugID, timerType);
<add> if (__DEV__) {
<add> if (isProfiling) {
<add> warning(
<add> !currentTimerType,
<add> 'There is an internal error in the React performance measurement code. ' +
<add> 'Did not expect %s timer to start while %s timer is still in ' +
<add> 'progress for %s instance.',
<add> timerType,
<add> currentTimerType || 'no',
<add> (debugID === currentTimerDebugID) ? 'the same' : 'another'
<add> );
<add> currentTimerStartTime = performanceNow();
<add> currentTimerDebugID = debugID;
<add> currentTimerType = timerType;
<add> }
<add> }
<add> },
<add> onEndLifeCycleTimer(debugID, timerType) {
<add> if (__DEV__) {
<add> if (isProfiling) {
<add> warning(
<add> currentTimerType === timerType,
<add> 'There is an internal error in the React performance measurement code. ' +
<add> 'We did not expect %s timer to stop while %s timer is still in ' +
<add> 'progress for %s instance. Please report this as a bug in React.',
<add> timerType,
<add> currentTimerType || 'no',
<add> (debugID === currentTimerDebugID) ? 'the same' : 'another'
<add> );
<add> currentFlushMeasurements.push({
<add> timerType,
<add> instanceID: debugID,
<add> duration: performance.now() - currentTimerStartTime,
<add> });
<add> currentTimerStartTime = null;
<add> currentTimerDebugID = null;
<add> currentTimerType = null;
<add> }
<add> }
<add> emitEvent('onEndLifeCycleTimer', debugID, timerType);
<add> },
<add> onBeginReconcilerTimer(debugID, timerType) {
<add> emitEvent('onBeginReconcilerTimer', debugID, timerType);
<add> },
<add> onEndReconcilerTimer(debugID, timerType) {
<add> emitEvent('onEndReconcilerTimer', debugID, timerType);
<add> },
<ide> onBeginProcessingChildContext() {
<ide> emitEvent('onBeginProcessingChildContext');
<ide> },
<ide> var ReactDebugTool = {
<ide> },
<ide> };
<ide>
<del>ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool);
<add>if (__DEV__) {
<add> var ReactInvalidSetStateWarningDevTool = require('ReactInvalidSetStateWarningDevTool');
<add> var ReactNativeOperationHistoryDevtool = require('ReactNativeOperationHistoryDevtool');
<add> var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
<add> ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool);
<add> ReactDebugTool.addDevtool(ReactComponentTreeDevtool);
<add> ReactDebugTool.addDevtool(ReactNativeOperationHistoryDevtool);
<add> var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
<add> if ((/[?&]react_perf\b/).test(url)) {
<add> ReactDebugTool.beginProfiling();
<add> }
<add>}
<ide>
<ide> module.exports = ReactDebugTool;
<ide><path>src/isomorphic/ReactPerfAnalysis.js
<add>/**
<add> * Copyright 2016-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactPerfAnalysis
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactDebugTool = require('ReactDebugTool');
<add>var warning = require('warning');
<add>
<add>function roundFloat(val, base = 2) {
<add> var n = Math.pow(10, base);
<add> return Math.floor(val * n) / n;
<add>}
<add>
<add>function getFlushHistory() {
<add> return ReactDebugTool.getFlushHistory();
<add>}
<add>
<add>function getExclusive(flushHistory = getFlushHistory()) {
<add> var aggregatedStats = {};
<add> var affectedIDs = {};
<add>
<add> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<add> var {displayName} = treeSnapshot[instanceID];
<add>
<add> var key = displayName;
<add> var stats = aggregatedStats[key];
<add>
<add> if (!stats) {
<add> affectedIDs[key] = {};
<add> stats = aggregatedStats[key] = {
<add> key,
<add> instanceCount: 0,
<add> counts: {},
<add> durations: {},
<add> totalDuration: 0,
<add> };
<add> }
<add>
<add> affectedIDs[key][instanceID] = true;
<add> applyUpdate(stats);
<add> }
<add>
<add> flushHistory.forEach(flush => {
<add> var {measurements, treeSnapshot} = flush;
<add> measurements.forEach(measurement => {
<add> var {duration, instanceID, timerType} = measurement;
<add> updateAggregatedStats(treeSnapshot, instanceID, stats => {
<add> stats.totalDuration += duration;
<add>
<add> if (!stats.durations[timerType]) {
<add> stats.durations[timerType] = 0;
<add> }
<add> stats.durations[timerType] += duration;
<add>
<add> if (!stats.counts[timerType]) {
<add> stats.counts[timerType] = 0;
<add> }
<add> stats.counts[timerType]++;
<add> });
<add> });
<add> });
<add>
<add> return Object.keys(aggregatedStats)
<add> .map(key => ({
<add> ...aggregatedStats[key],
<add> instanceCount: Object.keys(affectedIDs[key]).length,
<add> }))
<add> .sort((a, b) => b.totalDuration - a.totalDuration);
<add>}
<add>
<add>function getInclusive(flushHistory = getFlushHistory(), wastedOnly) {
<add> var aggregatedStats = {};
<add> var affectedIDs = {};
<add>
<add> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<add> var {displayName, ownerID} = treeSnapshot[instanceID];
<add>
<add> var owner = treeSnapshot[ownerID];
<add> var key = `${owner ? owner.displayName : '(no owner)'} > ${displayName}`;
<add> var stats = aggregatedStats[key];
<add>
<add> if (!stats) {
<add> affectedIDs[key] = {};
<add> stats = aggregatedStats[key] = {
<add> key,
<add> instanceCount: 0,
<add> inclusiveRenderDuration: 0,
<add> renderCount: 0,
<add> };
<add> }
<add>
<add> affectedIDs[key][instanceID] = true;
<add> applyUpdate(stats);
<add> }
<add>
<add> var hasRenderedByID = {};
<add> flushHistory.forEach(flush => {
<add> var {measurements} = flush;
<add> measurements.forEach(measurement => {
<add> var {instanceID, timerType} = measurement;
<add> if (timerType !== 'render') {
<add> return;
<add> }
<add> hasRenderedByID[instanceID] = true;
<add> });
<add> });
<add>
<add> flushHistory.forEach(flush => {
<add> var {measurements, treeSnapshot} = flush;
<add> measurements.forEach(measurement => {
<add> var {duration, instanceID, timerType} = measurement;
<add> if (timerType !== 'render') {
<add> return;
<add> }
<add> updateAggregatedStats(treeSnapshot, instanceID, stats => {
<add> stats.renderCount++;
<add> });
<add> var nextParentID = instanceID;
<add> while (nextParentID) {
<add> if (hasRenderedByID[nextParentID]) {
<add> updateAggregatedStats(treeSnapshot, nextParentID, stats => {
<add> stats.inclusiveRenderDuration += duration;
<add> });
<add> }
<add> nextParentID = treeSnapshot[nextParentID].parentID;
<add> }
<add> });
<add> });
<add>
<add> return Object.keys(aggregatedStats)
<add> .map(key => ({
<add> ...aggregatedStats[key],
<add> instanceCount: Object.keys(affectedIDs[key]).length,
<add> }))
<add> .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
<add>}
<add>
<add>function getWasted(flushHistory = getFlushHistory()) {
<add> var aggregatedStats = {};
<add> var affectedIDs = {};
<add>
<add> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<add> var {displayName, ownerID} = treeSnapshot[instanceID];
<add>
<add> var owner = treeSnapshot[ownerID];
<add> var key = `${owner ? owner.displayName : '(no owner)'} > ${displayName}`;
<add> var stats = aggregatedStats[key];
<add>
<add> if (!stats) {
<add> affectedIDs[key] = {};
<add> stats = aggregatedStats[key] = {
<add> key,
<add> instanceCount: 0,
<add> inclusiveRenderDuration: 0,
<add> renderCount: 0,
<add> };
<add> }
<add>
<add> affectedIDs[key][instanceID] = true;
<add> applyUpdate(stats);
<add> }
<add>
<add> flushHistory.forEach(flush => {
<add> var {measurements, treeSnapshot, operations} = flush;
<add> var dirtyInstanceIDs = {};
<add>
<add> operations.forEach(operation => {
<add> var {instanceID} = operation;
<add>
<add> var nextParentID = instanceID;
<add> while (nextParentID) {
<add> dirtyInstanceIDs[nextParentID] = true;
<add> nextParentID = treeSnapshot[nextParentID].parentID;
<add> }
<add> });
<add>
<add> var renderedCompositeIDs = {};
<add> measurements.forEach(measurement => {
<add> var {instanceID, timerType} = measurement;
<add> if (timerType !== 'render') {
<add> return;
<add> }
<add> renderedCompositeIDs[instanceID] = true;
<add> });
<add>
<add> measurements.forEach(measurement => {
<add> var {duration, instanceID, timerType} = measurement;
<add> if (timerType !== 'render') {
<add> return;
<add> }
<add> var { updateCount } = treeSnapshot[instanceID];
<add> if (dirtyInstanceIDs[instanceID] || updateCount === 0) {
<add> return;
<add> }
<add> updateAggregatedStats(treeSnapshot, instanceID, stats => {
<add> stats.renderCount++;
<add> });
<add> var nextParentID = instanceID;
<add> while (nextParentID) {
<add> if (!renderedCompositeIDs[nextParentID]) {
<add> break;
<add> }
<add> updateAggregatedStats(treeSnapshot, nextParentID, stats => {
<add> stats.inclusiveRenderDuration += duration;
<add> });
<add> nextParentID = treeSnapshot[nextParentID].parentID;
<add> }
<add> });
<add> });
<add>
<add> return Object.keys(aggregatedStats)
<add> .map(key => ({
<add> ...aggregatedStats[key],
<add> instanceCount: Object.keys(affectedIDs[key]).length,
<add> }))
<add> .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
<add>}
<add>
<add>function getOperations(flushHistory = getFlushHistory()) {
<add> var stats = [];
<add> flushHistory.forEach((flush, flushIndex) => {
<add> var {operations, treeSnapshot} = flush;
<add> operations.forEach(operation => {
<add> var {instanceID, type, payload} = operation;
<add> var {displayName, ownerID} = treeSnapshot[instanceID];
<add> var owner = treeSnapshot[ownerID];
<add> var key = `${(owner ? owner.displayName : '(no owner)')} > ${displayName}`;
<add>
<add> stats.push({
<add> flushIndex,
<add> instanceID,
<add> key,
<add> type,
<add> ownerID,
<add> payload,
<add> });
<add> });
<add> });
<add> return stats;
<add>}
<add>
<add>function printExclusive(flushHistory) {
<add> var stats = getExclusive(flushHistory);
<add> var table = stats.map(item => {
<add> var {key, instanceCount, totalDuration} = item;
<add> var renderCount = item.counts.render || 0;
<add> var renderDuration = item.durations.render || 0;
<add> return {
<add> 'Component': key,
<add> 'Total time (ms)': roundFloat(totalDuration),
<add> 'Instance count': instanceCount,
<add> 'Total render time (ms)': roundFloat(renderDuration),
<add> 'Average render time (ms)': renderCount ?
<add> roundFloat(renderDuration / renderCount) :
<add> undefined,
<add> 'Render count': renderCount,
<add> 'Total lifecycle time (ms)': roundFloat(totalDuration - renderDuration),
<add> };
<add> });
<add> console.table(table);
<add>}
<add>
<add>function printInclusive(flushHistory) {
<add> var stats = getInclusive(flushHistory);
<add> var table = stats.map(item => {
<add> var {key, instanceCount, inclusiveRenderDuration, renderCount} = item;
<add> return {
<add> 'Owner > Component': key,
<add> 'Inclusive render time (ms)': roundFloat(inclusiveRenderDuration),
<add> 'Instance count': instanceCount,
<add> 'Render count': renderCount,
<add> };
<add> });
<add> console.table(table);
<add>}
<add>
<add>function printWasted(flushHistory) {
<add> var stats = getWasted(flushHistory);
<add> var table = stats.map(item => {
<add> var {key, instanceCount, inclusiveRenderDuration, renderCount} = item;
<add> return {
<add> 'Owner > Component': key,
<add> 'Inclusive wasted time (ms)': roundFloat(inclusiveRenderDuration),
<add> 'Instance count': instanceCount,
<add> 'Render count': renderCount,
<add> };
<add> });
<add> console.table(table);
<add>}
<add>
<add>function printOperations(flushHistory) {
<add> var stats = getOperations(flushHistory);
<add> var table = stats.map(stat => ({
<add> 'Owner > Node': stat.key,
<add> 'Operation': stat.type,
<add> 'Payload': typeof stat.payload === 'object' ?
<add> JSON.stringify(stat.payload) :
<add> stat.payload,
<add> 'Flush index': stat.flushIndex,
<add> 'Owner Component ID': stat.ownerID,
<add> 'DOM Component ID': stat.instanceID,
<add> }));
<add> console.table(table);
<add>}
<add>
<add>var warnedAboutPrintDOM = false;
<add>function printDOM(measurements) {
<add> warning(
<add> warnedAboutPrintDOM,
<add> '`ReactPerf.printDOM(...)` is deprecated. Use ' +
<add> '`ReactPerf.printOperations(...)` instead.'
<add> );
<add> warnedAboutPrintDOM = true;
<add> return printOperations(measurements);
<add>}
<add>
<add>var warnedAboutGetMeasurementsSummaryMap = false;
<add>function getMeasurementsSummaryMap(measurements) {
<add> warning(
<add> warnedAboutGetMeasurementsSummaryMap,
<add> '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' +
<add> '`ReactPerf.getWasted(...)` instead.'
<add> );
<add> warnedAboutGetMeasurementsSummaryMap = true;
<add> return getWasted(measurements);
<add>}
<add>
<add>function start() {
<add> ReactDebugTool.beginProfiling();
<add>}
<add>
<add>function stop() {
<add> ReactDebugTool.endProfiling();
<add>}
<add>
<add>var ReactPerfAnalysis = {
<add> getFlushHistory,
<add> getExclusive,
<add> getInclusive,
<add> getWasted,
<add> getOperations,
<add> printExclusive,
<add> printInclusive,
<add> printWasted,
<add> printOperations,
<add> start,
<add> stop,
<add> // Deprecated:
<add> printDOM,
<add> getMeasurementsSummaryMap,
<add>};
<add>
<add>module.exports = ReactPerfAnalysis;
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide>
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> var React;
<del> var ReactDebugTool;
<ide> var ReactDOM;
<ide> var ReactDOMServer;
<ide> var ReactInstanceMap;
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> jest.resetModuleRegistry();
<ide>
<ide> React = require('React');
<del> ReactDebugTool = require('ReactDebugTool');
<ide> ReactDOM = require('ReactDOM');
<ide> ReactDOMServer = require('ReactDOMServer');
<ide> ReactInstanceMap = require('ReactInstanceMap');
<ide> ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
<del>
<del> ReactDebugTool.addDevtool(ReactComponentTreeDevtool);
<del> });
<del>
<del> afterEach(() => {
<del> ReactDebugTool.removeDevtool(ReactComponentTreeDevtool);
<ide> });
<ide>
<ide> function getRootDisplayNames() {
<ide><path>src/isomorphic/devtools/__tests__/ReactNativeOperationHistoryDevtool-test.js
<ide>
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> var React;
<del> var ReactDebugTool;
<ide> var ReactDOM;
<ide> var ReactDOMComponentTree;
<ide> var ReactDOMFeatureFlags;
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> jest.resetModuleRegistry();
<ide>
<ide> React = require('React');
<del> ReactDebugTool = require('ReactDebugTool');
<ide> ReactDOM = require('ReactDOM');
<ide> ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
<ide> ReactNativeOperationHistoryDevtool = require('ReactNativeOperationHistoryDevtool');
<del>
<del> ReactDebugTool.addDevtool(ReactNativeOperationHistoryDevtool);
<del> });
<del>
<del> afterEach(() => {
<del> ReactDebugTool.removeDevtool(ReactNativeOperationHistoryDevtool);
<ide> });
<ide>
<ide> function assertHistoryMatches(expectedHistory) {
<ide><path>src/renderers/dom/client/ReactMount.js
<ide> var ReactMount = {
<ide> shouldReuseMarkup,
<ide> context
<ide> ) {
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onBeginFlush();
<add> }
<add>
<ide> // Various parts of our code (such as ReactCompositeComponent's
<ide> // _renderValidatedComponent) assume that calls to render aren't nested;
<ide> // verify that that's the case.
<ide> var ReactMount = {
<ide> ReactInstrumentation.debugTool.onMountRootComponent(
<ide> componentInstance._renderedComponent._debugID
<ide> );
<add> ReactInstrumentation.debugTool.onEndFlush();
<ide> }
<ide>
<ide> return componentInstance;
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> ReactDOMComponent.Mixin = {
<ide> this._domID = null;
<ide> this._wrapperState = null;
<ide>
<del> if (this._contentDebugID) {
<del> ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID);
<del> this._contentDebugID = null;
<add> if (__DEV__) {
<add> if (this._contentDebugID) {
<add> ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID);
<add> this._contentDebugID = null;
<add> }
<ide> }
<ide> },
<ide>
<ide><path>src/renderers/dom/shared/ReactDOMTextComponent.js
<ide> Object.assign(ReactDOMTextComponent.prototype, {
<ide> );
<ide>
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetText(this._debugID, nextStringText);
<add> ReactInstrumentation.debugTool.onSetText(
<add> this._debugID,
<add> nextStringText
<add> );
<ide> }
<ide> }
<ide> }
<ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js
<ide> function warnIfInvalidElement(Component, element) {
<ide> }
<ide> }
<ide>
<add>function invokeComponentDidMountWithTimer() {
<add> var publicInstance = this._instance;
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentDidMount'
<add> );
<add> }
<add> publicInstance.componentDidMount();
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentDidMount'
<add> );
<add> }
<add>}
<add>
<add>function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
<add> var publicInstance = this._instance;
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentDidUpdate'
<add> );
<add> }
<add> publicInstance.componentDidUpdate(prevProps, prevState, prevContext);
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentDidUpdate'
<add> );
<add> }
<add>}
<add>
<ide> function shouldConstruct(Component) {
<ide> return Component.prototype && Component.prototype.isReactComponent;
<ide> }
<ide> var ReactCompositeComponentMixin = {
<ide> }
<ide>
<ide> if (inst.componentDidMount) {
<del> transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
<add> if (__DEV__) {
<add> transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this);
<add> } else {
<add> transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
<add> }
<ide> }
<ide>
<ide> return markup;
<ide> var ReactCompositeComponentMixin = {
<ide>
<ide> _constructComponentWithoutOwner: function(publicProps, publicContext) {
<ide> var Component = this._currentElement.type;
<add> var instanceOrElement;
<ide> if (shouldConstruct(Component)) {
<del> return new Component(publicProps, publicContext, ReactUpdateQueue);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'ctor'
<add> );
<add> }
<add> }
<add> instanceOrElement = new Component(publicProps, publicContext, ReactUpdateQueue);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'ctor'
<add> );
<add> }
<add> }
<ide> } else {
<del> return Component(publicProps, publicContext, ReactUpdateQueue);
<add> // This can still be an instance in case of factory components
<add> // but we'll count this as time spent rendering as the more common case.
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'render'
<add> );
<add> }
<add> }
<add> instanceOrElement = Component(publicProps, publicContext, ReactUpdateQueue);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'render'
<add> );
<add> }
<add> }
<ide> }
<add> return instanceOrElement;
<ide> },
<ide>
<ide> performInitialMountWithErrorHandling: function(
<ide> var ReactCompositeComponentMixin = {
<ide> performInitialMount: function(renderedElement, nativeParent, nativeContainerInfo, transaction, context) {
<ide> var inst = this._instance;
<ide> if (inst.componentWillMount) {
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillMount'
<add> );
<add> }
<add> }
<ide> inst.componentWillMount();
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillMount'
<add> );
<add> }
<add> }
<ide> // When mounting, calls to `setState` by `componentWillMount` will set
<ide> // `this._pendingStateQueue` without triggering a re-render.
<ide> if (this._pendingStateQueue) {
<ide> var ReactCompositeComponentMixin = {
<ide>
<ide> if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
<ide> inst._calledComponentWillUnmount = true;
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillUnmount'
<add> );
<add> }
<add> }
<ide> if (safely) {
<ide> var name = this.getName() + '.componentWillUnmount()';
<ide> ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
<ide> } else {
<ide> inst.componentWillUnmount();
<ide> }
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillUnmount'
<add> );
<add> }
<add> }
<ide> }
<ide>
<ide> if (this._renderedComponent) {
<ide> var ReactCompositeComponentMixin = {
<ide> // _pendingStateQueue which will ensure that any state updates gets
<ide> // immediately reconciled instead of waiting for the next batch.
<ide> if (willReceive && inst.componentWillReceiveProps) {
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillReceiveProps'
<add> );
<add> }
<add> }
<ide> inst.componentWillReceiveProps(nextProps, nextContext);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillReceiveProps'
<add> );
<add> }
<add> }
<ide> }
<ide>
<ide> var nextState = this._processPendingState(nextProps, nextContext);
<add> var shouldUpdate = true;
<ide>
<del> var shouldUpdate =
<del> this._pendingForceUpdate ||
<del> !inst.shouldComponentUpdate ||
<del> inst.shouldComponentUpdate(nextProps, nextState, nextContext);
<add> if (!this._pendingForceUpdate && inst.shouldComponentUpdate) {
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'shouldComponentUpdate'
<add> );
<add> }
<add> }
<add> shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'shouldComponentUpdate'
<add> );
<add> }
<add> }
<add> }
<ide>
<ide> if (__DEV__) {
<ide> warning(
<ide> var ReactCompositeComponentMixin = {
<ide> }
<ide>
<ide> if (inst.componentWillUpdate) {
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillUpdate'
<add> );
<add> }
<add> }
<ide> inst.componentWillUpdate(nextProps, nextState, nextContext);
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'componentWillUpdate'
<add> );
<add> }
<add> }
<ide> }
<ide>
<ide> this._currentElement = nextElement;
<ide> var ReactCompositeComponentMixin = {
<ide> this._updateRenderedComponent(transaction, unmaskedContext);
<ide>
<ide> if (hasComponentDidUpdate) {
<del> transaction.getReactMountReady().enqueue(
<del> inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
<del> inst
<del> );
<add> if (__DEV__) {
<add> transaction.getReactMountReady().enqueue(
<add> invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext),
<add> this
<add> );
<add> } else {
<add> transaction.getReactMountReady().enqueue(
<add> inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
<add> inst
<add> );
<add> }
<ide> }
<ide> },
<ide>
<ide> var ReactCompositeComponentMixin = {
<ide> */
<ide> _renderValidatedComponentWithoutOwnerOrContext: function() {
<ide> var inst = this._instance;
<add>
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
<add> this._debugID,
<add> 'render'
<add> );
<add> }
<add> }
<ide> var renderedComponent = inst.render();
<add> if (__DEV__) {
<add> if (this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onEndLifeCycleTimer(
<add> this._debugID,
<add> 'render'
<add> );
<add> }
<add> }
<add>
<ide> if (__DEV__) {
<ide> // We allow auto-mocks to proceed as if they're returning null.
<ide> if (renderedComponent === undefined &&
<ide> var ReactCompositeComponentMixin = {
<ide> 'returned undefined, an array or some other invalid object.',
<ide> this.getName() || 'ReactCompositeComponent'
<ide> );
<add>
<ide> return renderedComponent;
<ide> },
<ide>
<ide><path>src/renderers/shared/reconciler/ReactReconciler.js
<ide> var ReactReconciler = {
<ide> nativeContainerInfo,
<ide> context
<ide> ) {
<add> if (__DEV__) {
<add> if (internalInstance._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginReconcilerTimer(
<add> internalInstance._debugID,
<add> 'mountComponent'
<add> );
<add> }
<add> }
<ide> var markup = internalInstance.mountComponent(
<ide> transaction,
<ide> nativeParent,
<ide> var ReactReconciler = {
<ide> }
<ide> if (__DEV__) {
<ide> if (internalInstance._debugID !== 0) {
<del> ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
<add> ReactInstrumentation.debugTool.onEndReconcilerTimer(
<add> internalInstance._debugID,
<add> 'mountComponent'
<add> );
<add> ReactInstrumentation.debugTool.onMountComponent(
<add> internalInstance._debugID
<add> );
<ide> }
<ide> }
<ide> return markup;
<ide> var ReactReconciler = {
<ide> * @internal
<ide> */
<ide> unmountComponent: function(internalInstance, safely) {
<add> if (__DEV__) {
<add> if (internalInstance._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginReconcilerTimer(
<add> internalInstance._debugID,
<add> 'unmountComponent'
<add> );
<add> }
<add> }
<ide> ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
<ide> internalInstance.unmountComponent(safely);
<ide> if (__DEV__) {
<ide> if (internalInstance._debugID !== 0) {
<del> ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
<add> ReactInstrumentation.debugTool.onEndReconcilerTimer(
<add> internalInstance._debugID,
<add> 'unmountComponent'
<add> );
<add> ReactInstrumentation.debugTool.onUnmountComponent(
<add> internalInstance._debugID
<add> );
<ide> }
<ide> }
<ide> },
<ide> var ReactReconciler = {
<ide> return;
<ide> }
<ide>
<add> if (__DEV__) {
<add> if (internalInstance._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginReconcilerTimer(
<add> internalInstance._debugID,
<add> 'receiveComponent'
<add> );
<add> }
<add> }
<add>
<ide> var refsChanged = ReactRef.shouldUpdateRefs(
<ide> prevElement,
<ide> nextElement
<ide> var ReactReconciler = {
<ide>
<ide> if (__DEV__) {
<ide> if (internalInstance._debugID !== 0) {
<del> ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
<add> ReactInstrumentation.debugTool.onEndReconcilerTimer(
<add> internalInstance._debugID,
<add> 'receiveComponent'
<add> );
<add> ReactInstrumentation.debugTool.onUpdateComponent(
<add> internalInstance._debugID
<add> );
<ide> }
<ide> }
<ide> },
<ide> var ReactReconciler = {
<ide> internalInstance,
<ide> transaction
<ide> ) {
<add> if (__DEV__) {
<add> if (internalInstance._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onBeginReconcilerTimer(
<add> internalInstance._debugID,
<add> 'performUpdateIfNecessary'
<add> );
<add> }
<add> }
<ide> internalInstance.performUpdateIfNecessary(transaction);
<ide> if (__DEV__) {
<ide> if (internalInstance._debugID !== 0) {
<del> ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
<add> ReactInstrumentation.debugTool.onEndReconcilerTimer(
<add> internalInstance._debugID,
<add> 'performUpdateIfNecessary'
<add> );
<add> ReactInstrumentation.debugTool.onUpdateComponent(
<add> internalInstance._debugID
<add> );
<ide> }
<ide> }
<ide> },
<ide><path>src/renderers/shared/reconciler/ReactUpdates.js
<ide> var CallbackQueue = require('CallbackQueue');
<ide> var PooledClass = require('PooledClass');
<ide> var ReactFeatureFlags = require('ReactFeatureFlags');
<add>var ReactInstrumentation = require('ReactInstrumentation');
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactReconciler = require('ReactReconciler');
<ide> var Transaction = require('Transaction');
<ide> function runBatchedUpdates(transaction) {
<ide> }
<ide>
<ide> var flushBatchedUpdates = function() {
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onBeginFlush();
<add> }
<add>
<ide> // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
<ide> // array and perform any updates enqueued by mount-ready handlers (i.e.,
<ide> // componentDidUpdate) but we need to check here too in order to catch
<ide> var flushBatchedUpdates = function() {
<ide> CallbackQueue.release(queue);
<ide> }
<ide> }
<add>
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onEndFlush();
<add> }
<ide> };
<ide> flushBatchedUpdates = ReactPerf.measure(
<ide> 'ReactUpdates', | 12 |
Text | Text | remove old doc files | d5af01b2c76e144c6c7a7830903a67709cb17763 | <ide><path>docs/01-Line-Chart.md
<del>---
<del>title: Line Chart
<del>anchor: line-chart
<del>---
<del>###Introduction
<del>A line chart is a way of plotting data points on a line.
<del>
<del>Often, it is used to show trend data, and the comparison of two data sets.
<del>
<del><div class="canvas-holder">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del>###Example usage
<del>```javascript
<del>var myLineChart = new Chart(ctx).Line(data, options);
<del>```
<del>###Data structure
<del>
<del>```javascript
<del>var data = {
<del> labels: ["January", "February", "March", "April", "May", "June", "July"],
<del> datasets: [
<del> {
<del> label: "My First dataset",
<del> fillColor: "rgba(220,220,220,0.2)",
<del> strokeColor: "rgba(220,220,220,1)",
<del> pointColor: "rgba(220,220,220,1)",
<del> pointStrokeColor: "#fff",
<del> pointHighlightFill: "#fff",
<del> pointHighlightStroke: "rgba(220,220,220,1)",
<del> data: [65, 59, 80, 81, 56, 55, 40]
<del> },
<del> {
<del> label: "My Second dataset",
<del> fillColor: "rgba(151,187,205,0.2)",
<del> strokeColor: "rgba(151,187,205,1)",
<del> pointColor: "rgba(151,187,205,1)",
<del> pointStrokeColor: "#fff",
<del> pointHighlightFill: "#fff",
<del> pointHighlightStroke: "rgba(151,187,205,1)",
<del> data: [28, 48, 40, 19, 86, 27, 90]
<del> }
<del> ]
<del>};
<del>```
<del>
<del>The line chart requires an array of labels. This labels are shown on the X axis. There must be one label for each data point. More labels than datapoints are allowed, in which case the line ends at the last data point.
<del>The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation.
<del>
<del>The label key on each dataset is optional, and can be used when generating a scale for the chart.
<del>
<del>### Chart options
<del>
<del>These are the customisation options specific to Line charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
<del>
<del>```javascript
<del>{
<del>
<del> ///Boolean - Whether grid lines are shown across the chart
<del> scaleShowGridLines : true,
<del>
<del> //String - Colour of the grid lines
<del> scaleGridLineColor : "rgba(0,0,0,.05)",
<del>
<del> //Number - Width of the grid lines
<del> scaleGridLineWidth : 1,
<del>
<del> //Boolean - Whether to show horizontal lines (except X axis)
<del> scaleShowHorizontalLines: true,
<del>
<del> //Boolean - Whether to show vertical lines (except Y axis)
<del> scaleShowVerticalLines: true,
<del>
<del> //Boolean - Whether the line is curved between points
<del> bezierCurve : true,
<del>
<del> //Number - Tension of the bezier curve between points
<del> bezierCurveTension : 0.4,
<del>
<del> //Boolean - Whether to show a dot for each point
<del> pointDot : true,
<del>
<del> //Number - Radius of each point dot in pixels
<del> pointDotRadius : 4,
<del>
<del> //Number - Pixel width of point dot stroke
<del> pointDotStrokeWidth : 1,
<del>
<del> //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
<del> pointHitDetectionRadius : 20,
<del>
<del> //Boolean - Whether to show a stroke for datasets
<del> datasetStroke : true,
<del>
<del> //Number - Pixel width of dataset stroke
<del> datasetStrokeWidth : 2,
<del>
<del> //Boolean - Whether to fill the dataset with a colour
<del> datasetFill : true,
<del> {% raw %}
<del> //String - A legend template
<del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>"
<del> {% endraw %}
<del>
<del> //Boolean - Whether to horizontally center the label and point dot inside the grid
<del> offsetGridLines : false
<del>};
<del>```
<del>
<del>You can override these for your `Chart` instance by passing a second argument into the `Line` method as an object with the keys you want to override.
<del>
<del>For example, we could have a line chart without bezier curves between points by doing the following:
<del>
<del>```javascript
<del>new Chart(ctx).Line(data, {
<del> bezierCurve: false
<del>});
<del>// This will create a chart with all of the default options, merged from the global config,
<del>// and the Line chart defaults, but this particular instance will have `bezierCurve` set to false.
<del>```
<del>
<del>We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.Line`.
<del>
<del>
<del>### Prototype methods
<del>
<del>#### .getPointsAtEvent( event )
<del>
<del>Calling `getPointsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
<del>
<del>```javascript
<del>canvas.onclick = function(evt){
<del> var activePoints = myLineChart.getPointsAtEvent(evt);
<del> // => activePoints is an array of points on the canvas that are at the same position as the click event.
<del>};
<del>```
<del>
<del>This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
<del>
<del>#### .update( )
<del>
<del>Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
<del>
<del>```javascript
<del>myLineChart.datasets[0].points[2].value = 50;
<del>// Would update the first dataset's value of 'March' to be 50
<del>myLineChart.update();
<del>// Calling update now animates the position of March from 90 to 50.
<del>```
<del>
<del>#### .addData( valuesArray, label )
<del>
<del>Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those points.
<del>
<del>```javascript
<del>// The values array passed into addData should be one for each dataset in the chart
<del>myLineChart.addData([40, 60], "August");
<del>// This new data will now animate at the end of the chart.
<del>```
<del>
<del>#### .removeData( )
<del>
<del>Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
<del>
<del>```javascript
<del>myLineChart.removeData();
<del>// The chart will remove the first point and animate other points into place
<del>```
<ide><path>docs/02-Bar-Chart.md
<del>---
<del>title: Bar Chart
<del>anchor: bar-chart
<del>---
<del>
<del>### Introduction
<del>A bar chart is a way of showing data as bars.
<del>
<del>It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
<del>
<del><div class="canvas-holder">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del>### Example usage
<del>```javascript
<del>var myBarChart = new Chart(ctx).Bar(data, options);
<del>```
<del>
<del>### Data structure
<del>
<del>```javascript
<del>var data = {
<del> labels: ["January", "February", "March", "April", "May", "June", "July"],
<del> datasets: [
<del> {
<del> label: "My First dataset",
<del> fillColor: "rgba(220,220,220,0.5)",
<del> strokeColor: "rgba(220,220,220,0.8)",
<del> highlightFill: "rgba(220,220,220,0.75)",
<del> highlightStroke: "rgba(220,220,220,1)",
<del> data: [65, 59, 80, 81, 56, 55, 40]
<del> },
<del> {
<del> label: "My Second dataset",
<del> fillColor: "rgba(151,187,205,0.5)",
<del> strokeColor: "rgba(151,187,205,0.8)",
<del> highlightFill: "rgba(151,187,205,0.75)",
<del> highlightStroke: "rgba(151,187,205,1)",
<del> data: [28, 48, 40, 19, 86, 27, 90]
<del> }
<del> ]
<del>};
<del>```
<del>The bar chart has the a very similar data structure to the line chart, and has an array of datasets, each with colours and an array of data. Again, colours are in CSS format.
<del>We have an array of labels too for display. In the example, we are showing the same data as the previous line chart example.
<del>
<del>The label key on each dataset is optional, and can be used when generating a scale for the chart.
<del>
<del>### Chart Options
<del>
<del>These are the customisation options specific to Bar charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
<del>
<del>```javascript
<del>{
<del> //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
<del> scaleBeginAtZero : true,
<del>
<del> //Boolean - Whether grid lines are shown across the chart
<del> scaleShowGridLines : true,
<del>
<del> //String - Colour of the grid lines
<del> scaleGridLineColor : "rgba(0,0,0,.05)",
<del>
<del> //Number - Width of the grid lines
<del> scaleGridLineWidth : 1,
<del>
<del> //Boolean - Whether to show horizontal lines (except X axis)
<del> scaleShowHorizontalLines: true,
<del>
<del> //Boolean - Whether to show vertical lines (except Y axis)
<del> scaleShowVerticalLines: true,
<del>
<del> //Boolean - If there is a stroke on each bar
<del> barShowStroke : true,
<del>
<del> //Number - Pixel width of the bar stroke
<del> barStrokeWidth : 2,
<del>
<del> //Number - Spacing between each of the X value sets
<del> barValueSpacing : 5,
<del>
<del> //Number - Spacing between data sets within X values
<del> barDatasetSpacing : 1,
<del> {% raw %}
<del> //String - A legend template
<del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>"
<del> {% endraw %}
<del>}
<del>```
<del>
<del>You can override these for your `Chart` instance by passing a second argument into the `Bar` method as an object with the keys you want to override.
<del>
<del>For example, we could have a bar chart without a stroke on each bar by doing the following:
<del>
<del>```javascript
<del>new Chart(ctx).Bar(data, {
<del> barShowStroke: false
<del>});
<del>// This will create a chart with all of the default options, merged from the global config,
<del>// and the Bar chart defaults but this particular instance will have `barShowStroke` set to false.
<del>```
<del>
<del>We can also change these defaults values for each Bar type that is created, this object is available at `Chart.defaults.Bar`.
<del>
<del>### Prototype methods
<del>
<del>#### .getBarsAtEvent( event )
<del>
<del>Calling `getBarsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the bar elements that are at that the same position of that event.
<del>
<del>```javascript
<del>canvas.onclick = function(evt){
<del> var activeBars = myBarChart.getBarsAtEvent(evt);
<del> // => activeBars is an array of bars on the canvas that are at the same position as the click event.
<del>};
<del>```
<del>
<del>This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
<del>
<del>#### .update( )
<del>
<del>Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
<del>
<del>```javascript
<del>myBarChart.datasets[0].bars[2].value = 50;
<del>// Would update the first dataset's value of 'March' to be 50
<del>myBarChart.update();
<del>// Calling update now animates the position of March from 90 to 50.
<del>```
<del>
<del>#### .addData( valuesArray, label )
<del>
<del>Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those bars.
<del>
<del>```javascript
<del>// The values array passed into addData should be one for each dataset in the chart
<del>myBarChart.addData([40, 60], "August");
<del>// The new data will now animate at the end of the chart.
<del>```
<del>
<del>#### .removeData( )
<del>
<del>Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
<del>
<del>```javascript
<del>myBarChart.removeData();
<del>// The chart will now animate and remove the first bar
<del>```
<ide><path>docs/03-Radar-Chart.md
<del>---
<del>title: Radar Chart
<del>anchor: radar-chart
<del>---
<del>
<del>###Introduction
<del>A radar chart is a way of showing multiple data points and the variation between them.
<del>
<del>They are often useful for comparing the points of two or more different data sets.
<del>
<del><div class="canvas-holder">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del>###Example usage
<del>
<del>```javascript
<del>var myRadarChart = new Chart(ctx).Radar(data, options);
<del>```
<del>
<del>###Data structure
<del>```javascript
<del>var data = {
<del> labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
<del> datasets: [
<del> {
<del> label: "My First dataset",
<del> fillColor: "rgba(220,220,220,0.2)",
<del> strokeColor: "rgba(220,220,220,1)",
<del> pointColor: "rgba(220,220,220,1)",
<del> pointStrokeColor: "#fff",
<del> pointHighlightFill: "#fff",
<del> pointHighlightStroke: "rgba(220,220,220,1)",
<del> data: [65, 59, 90, 81, 56, 55, 40]
<del> },
<del> {
<del> label: "My Second dataset",
<del> fillColor: "rgba(151,187,205,0.2)",
<del> strokeColor: "rgba(151,187,205,1)",
<del> pointColor: "rgba(151,187,205,1)",
<del> pointStrokeColor: "#fff",
<del> pointHighlightFill: "#fff",
<del> pointHighlightStroke: "rgba(151,187,205,1)",
<del> data: [28, 48, 40, 19, 96, 27, 100]
<del> }
<del> ]
<del>};
<del>```
<del>For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart.
<del>For the radar chart data, we have an array of datasets. Each of these is an object, with a fill colour, a stroke colour, a colour for the fill of each point, and a colour for the stroke of each point. We also have an array of data values.
<del>
<del>The label key on each dataset is optional, and can be used when generating a scale for the chart.
<del>
<del>### Chart options
<del>
<del>These are the customisation options specific to Radar charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
<del>
<del>
<del>```javascript
<del>{
<del> //Boolean - Whether to show lines for each scale point
<del> scaleShowLine : true,
<del>
<del> //Boolean - Whether we show the angle lines out of the radar
<del> angleShowLineOut : true,
<del>
<del> //Boolean - Whether to show labels on the scale
<del> scaleShowLabels : false,
<del>
<del> // Boolean - Whether the scale should begin at zero
<del> scaleBeginAtZero : true,
<del>
<del> //String - Colour of the angle line
<del> angleLineColor : "rgba(0,0,0,.1)",
<del>
<del> //Number - Pixel width of the angle line
<del> angleLineWidth : 1,
<del>
<del> //Number - Interval at which to draw angle lines ("every Nth point")
<del> angleLineInterval: 1,
<del>
<del> //String - Point label font declaration
<del> pointLabelFontFamily : "'Arial'",
<del>
<del> //String - Point label font weight
<del> pointLabelFontStyle : "normal",
<del>
<del> //Number - Point label font size in pixels
<del> pointLabelFontSize : 10,
<del>
<del> //String - Point label font colour
<del> pointLabelFontColor : "#666",
<del>
<del> //Boolean - Whether to show a dot for each point
<del> pointDot : true,
<del>
<del> //Number - Radius of each point dot in pixels
<del> pointDotRadius : 3,
<del>
<del> //Number - Pixel width of point dot stroke
<del> pointDotStrokeWidth : 1,
<del>
<del> //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
<del> pointHitDetectionRadius : 20,
<del>
<del> //Boolean - Whether to show a stroke for datasets
<del> datasetStroke : true,
<del>
<del> //Number - Pixel width of dataset stroke
<del> datasetStrokeWidth : 2,
<del>
<del> //Boolean - Whether to fill the dataset with a colour
<del> datasetFill : true,
<del> {% raw %}
<del> //String - A legend template
<del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>"
<del> {% endraw %}
<del>}
<del>```
<del>
<del>
<del>You can override these for your `Chart` instance by passing a second argument into the `Radar` method as an object with the keys you want to override.
<del>
<del>For example, we could have a radar chart without a point for each on piece of data by doing the following:
<del>
<del>```javascript
<del>new Chart(ctx).Radar(data, {
<del> pointDot: false
<del>});
<del>// This will create a chart with all of the default options, merged from the global config,
<del>// and the Bar chart defaults but this particular instance will have `pointDot` set to false.
<del>```
<del>
<del>We can also change these defaults values for each Radar type that is created, this object is available at `Chart.defaults.Radar`.
<del>
<del>
<del>### Prototype methods
<del>
<del>#### .getPointsAtEvent( event )
<del>
<del>Calling `getPointsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
<del>
<del>```javascript
<del>canvas.onclick = function(evt){
<del> var activePoints = myRadarChart.getPointsAtEvent(evt);
<del> // => activePoints is an array of points on the canvas that are at the same position as the click event.
<del>};
<del>```
<del>
<del>This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
<del>
<del>#### .update( )
<del>
<del>Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
<del>
<del>```javascript
<del>myRadarChart.datasets[0].points[2].value = 50;
<del>// Would update the first dataset's value of 'Sleeping' to be 50
<del>myRadarChart.update();
<del>// Calling update now animates the position of Sleeping from 90 to 50.
<del>```
<del>
<del>#### .addData( valuesArray, label )
<del>
<del>Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those points.
<del>
<del>```javascript
<del>// The values array passed into addData should be one for each dataset in the chart
<del>myRadarChart.addData([40, 60], "Dancing");
<del>// The new data will now animate at the end of the chart.
<del>```
<del>
<del>#### .removeData( )
<del>
<del>Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
<del>
<del>```javascript
<del>myRadarChart.removeData();
<del>// Other points will now animate to their correct positions.
<del>```
<ide><path>docs/04-Polar-Area-Chart.md
<del>---
<del>title: Polar Area Chart
<del>anchor: polar-area-chart
<del>---
<del>### Introduction
<del>Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.
<del>
<del>This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.
<del>
<del><div class="canvas-holder">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del>### Example usage
<del>
<del>```javascript
<del>new Chart(ctx).PolarArea(data, options);
<del>```
<del>
<del>### Data structure
<del>
<del>```javascript
<del>var data = [
<del> {
<del> value: 300,
<del> color:"#F7464A",
<del> highlight: "#FF5A5E",
<del> label: "Red"
<del> },
<del> {
<del> value: 50,
<del> color: "#46BFBD",
<del> highlight: "#5AD3D1",
<del> label: "Green"
<del> },
<del> {
<del> value: 100,
<del> color: "#FDB45C",
<del> highlight: "#FFC870",
<del> label: "Yellow"
<del> },
<del> {
<del> value: 40,
<del> color: "#949FB1",
<del> highlight: "#A8B3C5",
<del> label: "Grey"
<del> },
<del> {
<del> value: 120,
<del> color: "#4D5360",
<del> highlight: "#616774",
<del> label: "Dark Grey"
<del> }
<del>
<del>];
<del>```
<del>As you can see, for the chart data you pass in an array of objects, with a value and a colour. The value attribute should be a number, while the color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.
<del>
<del>### Chart options
<del>
<del>These are the customisation options specific to Polar Area charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
<del>
<del>```javascript
<del>{
<del> //Boolean - Show a backdrop to the scale label
<del> scaleShowLabelBackdrop : true,
<del>
<del> //String - The colour of the label backdrop
<del> scaleBackdropColor : "rgba(255,255,255,0.75)",
<del>
<del> // Boolean - Whether the scale should begin at zero
<del> scaleBeginAtZero : true,
<del>
<del> //Number - The backdrop padding above & below the label in pixels
<del> scaleBackdropPaddingY : 2,
<del>
<del> //Number - The backdrop padding to the side of the label in pixels
<del> scaleBackdropPaddingX : 2,
<del>
<del> //Boolean - Show line for each value in the scale
<del> scaleShowLine : true,
<del>
<del> //Boolean - Stroke a line around each segment in the chart
<del> segmentShowStroke : true,
<del>
<del> //String - The colour of the stroke on each segment.
<del> segmentStrokeColor : "#fff",
<del>
<del> //Number - The width of the stroke value in pixels
<del> segmentStrokeWidth : 2,
<del>
<del> //Number - Amount of animation steps
<del> animationSteps : 100,
<del>
<del> //String - Animation easing effect.
<del> animationEasing : "easeOutBounce",
<del>
<del> //Boolean - Whether to animate the rotation of the chart
<del> animateRotate : true,
<del>
<del> //Boolean - Whether to animate scaling the chart from the centre
<del> animateScale : false,
<del> {% raw %}
<del> //String - A legend template
<del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>"
<del> {% endraw %}
<del>}
<del>```
<del>
<del>You can override these for your `Chart` instance by passing a second argument into the `PolarArea` method as an object with the keys you want to override.
<del>
<del>For example, we could have a polar area chart with a black stroke on each segment like so:
<del>
<del>```javascript
<del>new Chart(ctx).PolarArea(data, {
<del> segmentStrokeColor: "#000000"
<del>});
<del>// This will create a chart with all of the default options, merged from the global config,
<del>// and the PolarArea chart defaults but this particular instance will have `segmentStrokeColor` set to `"#000000"`.
<del>```
<del>
<del>We can also change these defaults values for each PolarArea type that is created, this object is available at `Chart.defaults.PolarArea`.
<del>
<del>### Prototype methods
<del>
<del>#### .getSegmentsAtEvent( event )
<del>
<del>Calling `getSegmentsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at that the same position of that event.
<del>
<del>```javascript
<del>canvas.onclick = function(evt){
<del> var activePoints = myPolarAreaChart.getSegmentsAtEvent(evt);
<del> // => activePoints is an array of segments on the canvas that are at the same position as the click event.
<del>};
<del>```
<del>
<del>This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
<del>
<del>#### .update( )
<del>
<del>Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
<del>
<del>```javascript
<del>myPolarAreaChart.segments[1].value = 10;
<del>// Would update the first dataset's value of 'Green' to be 10
<del>myPolarAreaChart.update();
<del>// Calling update now animates the position of Green from 50 to 10.
<del>```
<del>
<del>#### .addData( segmentData, index )
<del>
<del>Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an option second argument of 'index', this determines at what index the new segment should be inserted into the chart.
<del>
<del>```javascript
<del>// An object in the same format as the original data source
<del>myPolarAreaChart.addData({
<del> value: 130,
<del> color: "#B48EAD",
<del> highlight: "#C69CBE",
<del> label: "Purple"
<del>});
<del>// The new segment will now animate in.
<del>```
<del>
<del>#### .removeData( index )
<del>
<del>Calling `removeData(index)` on your Chart instance will remove segment at that particular index. If none is provided, it will default to the last segment.
<del>
<del>```javascript
<del>myPolarAreaChart.removeData();
<del>// Other segments will update to fill the empty space left.
<del>```
<ide><path>docs/05-Pie-Doughnut-Chart.md
<del>---
<del>title: Pie & Doughnut Charts
<del>anchor: doughnut-pie-chart
<del>---
<del>###Introduction
<del>Pie and doughnut charts are probably the most commonly used chart there are. They are divided into segments, the arc of each segment shows the proportional value of each piece of data.
<del>
<del>They are excellent at showing the relational proportions between data.
<del>
<del>Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their `percentageInnerCutout`. This equates what percentage of the inner should be cut out. This defaults to `0` for pie charts, and `50` for doughnuts.
<del>
<del>They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same.
<del>
<del><div class="canvas-holder half">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del><div class="canvas-holder half">
<del> <canvas width="250" height="125"></canvas>
<del></div>
<del>
<del>
<del>### Example usage
<del>
<del>```javascript
<del>// For a pie chart
<del>var myPieChart = new Chart(ctx[0]).Pie(data,options);
<del>
<del>// And for a doughnut chart
<del>var myDoughnutChart = new Chart(ctx[1]).Doughnut(data,options);
<del>```
<del>
<del>### Data structure
<del>
<del>```javascript
<del>var data = [
<del> {
<del> value: 300,
<del> color:"#F7464A",
<del> highlight: "#FF5A5E",
<del> label: "Red"
<del> },
<del> {
<del> value: 50,
<del> color: "#46BFBD",
<del> highlight: "#5AD3D1",
<del> label: "Green"
<del> },
<del> {
<del> value: 100,
<del> color: "#FDB45C",
<del> highlight: "#FFC870",
<del> label: "Yellow"
<del> }
<del>]
<del>```
<del>
<del>For a pie chart, you must pass in an array of objects with a value and an optional color property. The value attribute should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. The color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.
<del>
<del>### Chart options
<del>
<del>These are the customisation options specific to Pie & Doughnut charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
<del>
<del>```javascript
<del>{
<del> //Boolean - Whether we should show a stroke on each segment
<del> segmentShowStroke : true,
<del>
<del> //String - The colour of each segment stroke
<del> segmentStrokeColor : "#fff",
<del>
<del> //Number - The width of each segment stroke
<del> segmentStrokeWidth : 2,
<del>
<del> //Number - The percentage of the chart that we cut out of the middle
<del> percentageInnerCutout : 50, // This is 0 for Pie charts
<del>
<del> //Number - Amount of animation steps
<del> animationSteps : 100,
<del>
<del> //String - Animation easing effect
<del> animationEasing : "easeOutBounce",
<del>
<del> //Boolean - Whether we animate the rotation of the Doughnut
<del> animateRotate : true,
<del>
<del> //Boolean - Whether we animate scaling the Doughnut from the centre
<del> animateScale : false,
<del> {% raw %}
<del> //String - A legend template
<del> legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>"
<del> {% endraw %}
<del>}
<del>```
<del>You can override these for your `Chart` instance by passing a second argument into the `Doughnut` method as an object with the keys you want to override.
<del>
<del>For example, we could have a doughnut chart that animates by scaling out from the centre like so:
<del>
<del>```javascript
<del>new Chart(ctx).Doughnut(data, {
<del> animateScale: true
<del>});
<del>// This will create a chart with all of the default options, merged from the global config,
<del>// and the Doughnut chart defaults but this particular instance will have `animateScale` set to `true`.
<del>```
<del>
<del>We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.Doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.Pie`, with the only difference being `percentageInnerCutout` being set to 0.
<del>
<del>### Prototype methods
<del>
<del>#### .getSegmentsAtEvent( event )
<del>
<del>Calling `getSegmentsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at the same position of that event.
<del>
<del>```javascript
<del>canvas.onclick = function(evt){
<del> var activePoints = myDoughnutChart.getSegmentsAtEvent(evt);
<del> // => activePoints is an array of segments on the canvas that are at the same position as the click event.
<del>};
<del>```
<del>
<del>This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
<del>
<del>#### .update( )
<del>
<del>Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
<del>
<del>```javascript
<del>myDoughnutChart.segments[1].value = 10;
<del>// Would update the first dataset's value of 'Green' to be 10
<del>myDoughnutChart.update();
<del>// Calling update now animates the circumference of the segment 'Green' from 50 to 10.
<del>// and transitions other segment widths
<del>```
<del>
<del>#### .addData( segmentData, index )
<del>
<del>Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an optional second argument of 'index', this determines at what index the new segment should be inserted into the chart.
<del>
<del>If you don't specify a color and highliht, one will be chosen from the global default array: segmentColorDefault and the corresponding segmentHighlightColorDefault. The index of the addded data is used to lookup a corresponding color from the defaults.
<del>
<del>```javascript
<del>// An object in the same format as the original data source
<del>myDoughnutChart.addData({
<del> value: 130,
<del> color: "#B48EAD",
<del> highlight: "#C69CBE",
<del> label: "Purple"
<del>});
<del>// The new segment will now animate in.
<del>```
<del>
<del>#### .removeData( index )
<del>
<del>Calling `removeData(index)` on your Chart instance will remove segment at that particular index. If none is provided, it will default to the last segment.
<del>
<del>```javascript
<del>myDoughnutChart.removeData();
<del>// Other segments will update to fill the empty space left.
<del>```
<ide><path>docs/06-Advanced.md
<del>---
<del>title: Advanced usage
<del>anchor: advanced-usage
<del>---
<del>
<del>
<del>### Prototype methods
<del>
<del>For each chart, there are a set of global prototype methods on the shared `ChartType` which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made.
<del>
<del>```javascript
<del>// For example:
<del>var myLineChart = new Chart(ctx).Line(data);
<del>```
<del>
<del>#### .clear()
<del>
<del>Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.
<del>
<del>```javascript
<del>// Will clear the canvas that myLineChart is drawn on
<del>myLineChart.clear();
<del>// => returns 'this' for chainability
<del>```
<del>
<del>#### .stop()
<del>
<del>Use this to stop any current animation loop. This will pause the chart during any current animation frame. Call `.render()` to re-animate.
<del>
<del>```javascript
<del>// Stops the charts animation loop at its current frame
<del>myLineChart.stop();
<del>// => returns 'this' for chainability
<del>```
<del>
<del>#### .resize()
<del>
<del>Use this to manually resize the canvas element. This is run each time the browser is resized, but you can call this method manually if you change the size of the canvas nodes container element.
<del>
<del>```javascript
<del>// Resizes & redraws to fill its container element
<del>myLineChart.resize();
<del>// => returns 'this' for chainability
<del>```
<del>
<del>#### .destroy()
<del>
<del>Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js.
<del>
<del>```javascript
<del>// Destroys a specific chart instance
<del>myLineChart.destroy();
<del>```
<del>
<del>#### .toBase64Image()
<del>
<del>This returns a base 64 encoded string of the chart in its current state.
<del>
<del>```javascript
<del>myLineChart.toBase64Image();
<del>// => returns png data url of the image on the canvas
<del>```
<del>
<del>#### .generateLegend()
<del>
<del>Returns an HTML string of a legend for that chart. The template for this legend is at `legendTemplate` in the chart options.
<del>
<del>```javascript
<del>myLineChart.generateLegend();
<del>// => returns HTML string of a legend for this chart
<del>```
<del>
<del>### External Tooltips
<del>
<del>You can enable custom tooltips in the global or chart configuration like so:
<del>
<del>```javascript
<del>var myPieChart = new Chart(ctx).Pie(data, {
<del> customTooltips: function(tooltip) {
<del>
<del> // tooltip will be false if tooltip is not visible or should be hidden
<del> if (!tooltip) {
<del> return;
<del> }
<del>
<del> // Otherwise, tooltip will be an object with all tooltip properties like:
<del>
<del> // tooltip.caretHeight
<del> // tooltip.caretPadding
<del> // tooltip.chart
<del> // tooltip.cornerRadius
<del> // tooltip.fillColor
<del> // tooltip.font...
<del> // tooltip.text
<del> // tooltip.x
<del> // tooltip.y
<del> // etc...
<del>
<del> }
<del>});
<del>```
<del>
<del>See files `sample/pie-customTooltips.html` and `sample/line-customTooltips.html` for examples on how to get started.
<del>
<del>
<del>### Writing new chart types
<del>
<del>Chart.js 1.0 has been rewritten to provide a platform for developers to create their own custom chart types, and be able to share and utilise them through the Chart.js API.
<del>
<del>The format is relatively simple, there are a set of utility helper methods under `Chart.helpers`, including things such as looping over collections, requesting animation frames, and easing equations.
<del>
<del>On top of this, there are also some simple base classes of Chart elements, these all extend from `Chart.Element`, and include things such as points, bars and scales.
<del>
<del>```javascript
<del>Chart.Type.extend({
<del> // Passing in a name registers this chart in the Chart namespace
<del> name: "Scatter",
<del> // Providing a defaults will also register the deafults in the chart namespace
<del> defaults : {
<del> options: "Here",
<del> available: "at this.options"
<del> },
<del> // Initialize is fired when the chart is initialized - Data is passed in as a parameter
<del> // Config is automatically merged by the core of Chart.js, and is available at this.options
<del> initialize: function(data){
<del> this.chart.ctx // The drawing context for this chart
<del> this.chart.canvas // the canvas node for this chart
<del> },
<del> // Used to draw something on the canvas
<del> draw: function() {
<del> }
<del>});
<del>
<del>// Now we can create a new instance of our chart, using the Chart.js API
<del>new Chart(ctx).Scatter(data);
<del>// initialize is now run
<del>```
<del>
<del>### Extending existing chart types
<del>
<del>We can also extend existing chart types, and expose them to the API in the same way. Let's say for example, we might want to run some more code when we initialize every Line chart.
<del>
<del>```javascript
<del>// Notice now we're extending the particular Line chart type, rather than the base class.
<del>Chart.types.Line.extend({
<del> // Passing in a name registers this chart in the Chart namespace in the same way
<del> name: "LineAlt",
<del> initialize: function(data){
<del> console.log('My Line chart extension');
<del> Chart.types.Line.prototype.initialize.apply(this, arguments);
<del> }
<del>});
<del>
<del>// Creates a line chart in the same way
<del>new Chart(ctx).LineAlt(data);
<del>// but this logs 'My Line chart extension' in the console.
<del>```
<del>
<del>### Community extensions
<del>
<del>- <a href="https://github.com/Regaddi/Chart.StackedBar.js" target="_blank">Stacked Bar Chart</a> by <a href="https://twitter.com/Regaddi" target="_blank">@Regaddi</a>
<del>- <a href="https://github.com/tannerlinsley/Chart.StackedArea.js" target="_blank">Stacked Bar Chart</a> by <a href="https://twitter.com/tannerlinsley" target="_blank">@tannerlinsley</a>
<del>- <a href="https://github.com/CAYdenberg/Chart.js" target="_blank">Error bars (bar and line charts)</a> by <a href="https://twitter.com/CAYdenberg" target="_blank">@CAYdenberg</a>
<del>- <a href="http://dima117.github.io/Chart.Scatter/" target="_blank">Scatter chart (number & date scales are supported)</a> by <a href="https://github.com/dima117" target="_blank">@dima117</a>
<del>
<del>### Creating custom builds
<del>
<del>Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. We can use this same build script with custom parameters in order to build a custom version.
<del>
<del>Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
<del>
<del>```bash
<del>npm install
<del>npm install -g gulp
<del>```
<del>
<del>This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
<del>
<del>Now, we can run the `gulp build` task, and pass in a comma-separated list of types as an argument to build a custom version of Chart.js with only specified chart types.
<del>
<del>Here we will create a version of Chart.js with only Line, Radar and Bar charts included:
<del>
<del>```bash
<del>gulp build --types=Line,Radar,Bar
<del>```
<del>
<del>This will output to the `/custom` directory, and write two files, Chart.js, and Chart.min.js with only those chart types included. | 6 |
PHP | PHP | relax interface requirements | 218ba6b811441313aa5122ee793fc6b854d735e9 | <ide><path>src/Controller/ControllerFactory.php
<ide> namespace Cake\Controller;
<ide>
<ide> use Cake\Core\App;
<del>use Cake\Core\ContainerInterface;
<ide> use Cake\Http\ControllerFactoryInterface;
<ide> use Cake\Http\Exception\MissingControllerException;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Utility\Inflector;
<add>use Psr\Container\ContainerInterface;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use ReflectionClass;
<ide> class ControllerFactory implements ControllerFactoryInterface
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Core\ContainerInterface $container The container to build controllers with.
<add> * @param \Psr\Container\ContainerInterface $container The container to build controllers with.
<ide> */
<ide> public function __construct(ContainerInterface $container)
<ide> { | 1 |
Go | Go | prefix errors with their source | 03211ecce07ab64f5263232e1aa3c6248530c5b4 | <ide><path>pkg/libcontainer/nsinit/nsinit/main.go
<ide> func main() {
<ide> }
<ide> container, err := loadContainer()
<ide> if err != nil {
<del> log.Fatal(err)
<add> log.Fatalf("Unable to load container: %s", err)
<ide> }
<ide> ns, err := newNsInit()
<ide> if err != nil {
<del> log.Fatal(err)
<add> log.Fatalf("Unable to initialize nsinit: %s", err)
<ide> }
<ide>
<ide> switch flag.Arg(0) {
<ide> func main() {
<ide> nspid, err := readPid()
<ide> if err != nil {
<ide> if !os.IsNotExist(err) {
<del> log.Fatal(err)
<add> log.Fatalf("Unable to read pid: %s", err)
<ide> }
<ide> }
<ide> if nspid > 0 {
<ide> func main() {
<ide> exitCode, err = ns.Exec(container, term, flag.Args()[1:])
<ide> }
<ide> if err != nil {
<del> log.Fatal(err)
<add> log.Fatalf("Failed to exec: %s", err)
<ide> }
<ide> os.Exit(exitCode)
<ide> case "init": // this is executed inside of the namespace to setup the container
<ide> func main() {
<ide> }
<ide> syncPipe, err := nsinit.NewSyncPipeFromFd(0, uintptr(pipeFd))
<ide> if err != nil {
<del> log.Fatal(err)
<add> log.Fatalf("Unable to create sync pipe: %s", err)
<ide> }
<ide> if err := ns.Init(container, cwd, console, syncPipe, flag.Args()[1:]); err != nil {
<del> log.Fatal(err)
<add> log.Fatalf("Unable to initialize for container: %s", err)
<ide> }
<ide> default:
<ide> log.Fatalf("command not supported for nsinit %s", flag.Arg(0)) | 1 |
Go | Go | move middleware to interfaces | 8d3467626ee26cad48ad84f2181552dce7afccb6 | <ide><path>api/server/middleware.go
<ide> package server
<ide>
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/server/middleware"
<del> "github.com/docker/docker/pkg/authorization"
<ide> )
<ide>
<ide> // handleWithGlobalMiddlwares wraps the handler function for a request with
<ide> import (
<ide> func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc {
<ide> next := handler
<ide>
<del> handleVersion := middleware.NewVersionMiddleware(s.cfg.Version, api.DefaultVersion, api.MinVersion)
<del> next = handleVersion(next)
<del>
<del> if s.cfg.EnableCors {
<del> handleCORS := middleware.NewCORSMiddleware(s.cfg.CorsHeaders)
<del> next = handleCORS(next)
<add> for _, m := range s.middlewares {
<add> next = m.WrapHandler(next)
<ide> }
<ide>
<del> handleUserAgent := middleware.NewUserAgentMiddleware(s.cfg.Version)
<del> next = handleUserAgent(next)
<del>
<del> // Only want this on debug level
<ide> if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
<ide> next = middleware.DebugRequestMiddleware(next)
<ide> }
<ide>
<del> if len(s.cfg.AuthorizationPluginNames) > 0 {
<del> s.authZPlugins = authorization.NewPlugins(s.cfg.AuthorizationPluginNames)
<del> handleAuthorization := middleware.NewAuthorizationMiddleware(s.authZPlugins)
<del> next = handleAuthorization(next)
<del> }
<del>
<ide> return next
<ide> }
<ide><path>api/server/middleware/authorization.go
<del>package middleware
<del>
<del>import (
<del> "net/http"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/api/server/httputils"
<del> "github.com/docker/docker/pkg/authorization"
<del> "golang.org/x/net/context"
<del>)
<del>
<del>// NewAuthorizationMiddleware creates a new Authorization middleware.
<del>func NewAuthorizationMiddleware(plugins []authorization.Plugin) Middleware {
<del> return func(handler httputils.APIFunc) httputils.APIFunc {
<del> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del>
<del> user := ""
<del> userAuthNMethod := ""
<del>
<del> // Default authorization using existing TLS connection credentials
<del> // FIXME: Non trivial authorization mechanisms (such as advanced certificate validations, kerberos support
<del> // and ldap) will be extracted using AuthN feature, which is tracked under:
<del> // https://github.com/docker/docker/pull/20883
<del> if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
<del> user = r.TLS.PeerCertificates[0].Subject.CommonName
<del> userAuthNMethod = "TLS"
<del> }
<del>
<del> authCtx := authorization.NewCtx(plugins, user, userAuthNMethod, r.Method, r.RequestURI)
<del>
<del> if err := authCtx.AuthZRequest(w, r); err != nil {
<del> logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
<del> return err
<del> }
<del>
<del> rw := authorization.NewResponseModifier(w)
<del>
<del> if err := handler(ctx, rw, r, vars); err != nil {
<del> logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
<del> return err
<del> }
<del>
<del> if err := authCtx.AuthZResponse(rw, r); err != nil {
<del> logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
<del> return err
<del> }
<del> return nil
<del> }
<del> }
<del>}
<ide><path>api/server/middleware/cors.go
<ide> import (
<ide> "net/http"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/api/server/httputils"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<del>// NewCORSMiddleware creates a new CORS middleware.
<del>func NewCORSMiddleware(defaultHeaders string) Middleware {
<del> return func(handler httputils.APIFunc) httputils.APIFunc {
<del> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
<del> // otherwise, all head values will be passed to HTTP handler
<del> corsHeaders := defaultHeaders
<del> if corsHeaders == "" {
<del> corsHeaders = "*"
<del> }
<add>// CORSMiddleware injects CORS headers to each request
<add>// when it's configured.
<add>type CORSMiddleware struct {
<add> defaultHeaders string
<add>}
<ide>
<del> writeCorsHeaders(w, r, corsHeaders)
<del> return handler(ctx, w, r, vars)
<del> }
<del> }
<add>// NewCORSMiddleware creates a new CORSMiddleware with default headers.
<add>func NewCORSMiddleware(d string) CORSMiddleware {
<add> return CORSMiddleware{defaultHeaders: d}
<ide> }
<ide>
<del>func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
<del> logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
<del> w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
<del> w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
<del> w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
<add>// WrapHandler returns a new handler function wrapping the previous one in the request chain.
<add>func (c CORSMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
<add> // otherwise, all head values will be passed to HTTP handler
<add> corsHeaders := c.defaultHeaders
<add> if corsHeaders == "" {
<add> corsHeaders = "*"
<add> }
<add>
<add> logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
<add> w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
<add> w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
<add> w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
<add> return handler(ctx, w, r, vars)
<add> }
<ide> }
<ide><path>api/server/middleware/debug.go
<ide> import (
<ide> )
<ide>
<ide> // DebugRequestMiddleware dumps the request to logger
<del>func DebugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
<add>func DebugRequestMiddleware(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> logrus.Debugf("Calling %s %s", r.Method, r.RequestURI)
<ide>
<ide><path>api/server/middleware/middleware.go
<ide> package middleware
<ide>
<del>import "github.com/docker/docker/api/server/httputils"
<add>import (
<add> "net/http"
<ide>
<del>// Middleware is an adapter to allow the use of ordinary functions as Docker API filters.
<del>// Any function that has the appropriate signature can be registered as a middleware.
<del>type Middleware func(handler httputils.APIFunc) httputils.APIFunc
<add> "golang.org/x/net/context"
<add>)
<add>
<add>// Middleware is an interface to allow the use of ordinary functions as Docker API filters.
<add>// Any struct that has the appropriate signature can be registered as a middleware.
<add>type Middleware interface {
<add> WrapHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error
<add>}
<ide><path>api/server/middleware/user_agent.go
<ide> import (
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<del>// NewUserAgentMiddleware creates a new UserAgent middleware.
<del>func NewUserAgentMiddleware(versionCheck string) Middleware {
<del> serverVersion := version.Version(versionCheck)
<del>
<del> return func(handler httputils.APIFunc) httputils.APIFunc {
<del> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> ctx = context.WithValue(ctx, httputils.UAStringKey, r.Header.Get("User-Agent"))
<del>
<del> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<del> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<del>
<del> // v1.20 onwards includes the GOOS of the client after the version
<del> // such as Docker/1.7.0 (linux)
<del> if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
<del> userAgent[1] = strings.Split(userAgent[1], " ")[0]
<del> }
<del>
<del> if len(userAgent) == 2 && !serverVersion.Equal(version.Version(userAgent[1])) {
<del> logrus.Debugf("Client and server don't have the same version (client: %s, server: %s)", userAgent[1], serverVersion)
<del> }
<add>// UserAgentMiddleware is a middleware that
<add>// validates the client user-agent.
<add>type UserAgentMiddleware struct {
<add> serverVersion version.Version
<add>}
<add>
<add>// NewUserAgentMiddleware creates a new UserAgentMiddleware
<add>// with the server version.
<add>func NewUserAgentMiddleware(s version.Version) UserAgentMiddleware {
<add> return UserAgentMiddleware{
<add> serverVersion: s,
<add> }
<add>}
<add>
<add>// WrapHandler returns a new handler function wrapping the previous one in the request chain.
<add>func (u UserAgentMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> ctx = context.WithValue(ctx, httputils.UAStringKey, r.Header.Get("User-Agent"))
<add>
<add> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<add> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<add>
<add> // v1.20 onwards includes the GOOS of the client after the version
<add> // such as Docker/1.7.0 (linux)
<add> if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
<add> userAgent[1] = strings.Split(userAgent[1], " ")[0]
<add> }
<add>
<add> if len(userAgent) == 2 && !u.serverVersion.Equal(version.Version(userAgent[1])) {
<add> logrus.Debugf("Client and server don't have the same version (client: %s, server: %s)", userAgent[1], u.serverVersion)
<ide> }
<del> return handler(ctx, w, r, vars)
<ide> }
<add> return handler(ctx, w, r, vars)
<ide> }
<ide> }
<ide><path>api/server/middleware/version.go
<ide> import (
<ide> "net/http"
<ide> "runtime"
<ide>
<del> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/pkg/version"
<ide> "golang.org/x/net/context"
<ide> )
<ide> func (badRequestError) HTTPErrorStatusCode() int {
<ide> return http.StatusBadRequest
<ide> }
<ide>
<del>// NewVersionMiddleware creates a new Version middleware.
<del>func NewVersionMiddleware(versionCheck string, defaultVersion, minVersion version.Version) Middleware {
<del> serverVersion := version.Version(versionCheck)
<del>
<del> return func(handler httputils.APIFunc) httputils.APIFunc {
<del> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> apiVersion := version.Version(vars["version"])
<del> if apiVersion == "" {
<del> apiVersion = defaultVersion
<del> }
<del>
<del> if apiVersion.GreaterThan(defaultVersion) {
<del> return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, defaultVersion)}
<del> }
<del> if apiVersion.LessThan(minVersion) {
<del> return badRequestError{fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, minVersion)}
<del> }
<del>
<del> header := fmt.Sprintf("Docker/%s (%s)", serverVersion, runtime.GOOS)
<del> w.Header().Set("Server", header)
<del> ctx = context.WithValue(ctx, httputils.APIVersionKey, apiVersion)
<del> return handler(ctx, w, r, vars)
<add>// VersionMiddleware is a middleware that
<add>// validates the client and server versions.
<add>type VersionMiddleware struct {
<add> serverVersion version.Version
<add> defaultVersion version.Version
<add> minVersion version.Version
<add>}
<add>
<add>// NewVersionMiddleware creates a new VersionMiddleware
<add>// with the default versions.
<add>func NewVersionMiddleware(s, d, m version.Version) VersionMiddleware {
<add> return VersionMiddleware{
<add> serverVersion: s,
<add> defaultVersion: d,
<add> minVersion: m,
<add> }
<add>}
<add>
<add>// WrapHandler returns a new handler function wrapping the previous one in the request chain.
<add>func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> apiVersion := version.Version(vars["version"])
<add> if apiVersion == "" {
<add> apiVersion = v.defaultVersion
<ide> }
<add>
<add> if apiVersion.GreaterThan(v.defaultVersion) {
<add> return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, v.defaultVersion)}
<add> }
<add> if apiVersion.LessThan(v.minVersion) {
<add> return badRequestError{fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, v.minVersion)}
<add> }
<add>
<add> header := fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS)
<add> w.Header().Set("Server", header)
<add> ctx = context.WithValue(ctx, "api-version", apiVersion)
<add> return handler(ctx, w, r, vars)
<ide> }
<add>
<ide> }
<ide><path>api/server/middleware/version_test.go
<ide> func TestVersionMiddleware(t *testing.T) {
<ide>
<ide> defaultVersion := version.Version("1.10.0")
<ide> minVersion := version.Version("1.2.0")
<del> m := NewVersionMiddleware(defaultVersion.String(), defaultVersion, minVersion)
<del> h := m(handler)
<add> m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion)
<add> h := m.WrapHandler(handler)
<ide>
<ide> req, _ := http.NewRequest("GET", "/containers/json", nil)
<ide> resp := httptest.NewRecorder()
<ide> func TestVersionMiddlewareWithErrors(t *testing.T) {
<ide>
<ide> defaultVersion := version.Version("1.10.0")
<ide> minVersion := version.Version("1.2.0")
<del> m := NewVersionMiddleware(defaultVersion.String(), defaultVersion, minVersion)
<del> h := m(handler)
<add> m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion)
<add> h := m.WrapHandler(handler)
<ide>
<ide> req, _ := http.NewRequest("GET", "/containers/json", nil)
<ide> resp := httptest.NewRecorder()
<ide><path>api/server/server.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/server/httputils"
<add> "github.com/docker/docker/api/server/middleware"
<ide> "github.com/docker/docker/api/server/router"
<del> "github.com/docker/docker/pkg/authorization"
<ide> "github.com/gorilla/mux"
<ide> "golang.org/x/net/context"
<ide> )
<ide> const versionMatcher = "/v{version:[0-9.]+}"
<ide>
<ide> // Config provides the configuration for the API server
<ide> type Config struct {
<del> Logging bool
<del> EnableCors bool
<del> CorsHeaders string
<del> AuthorizationPluginNames []string
<del> Version string
<del> SocketGroup string
<del> TLSConfig *tls.Config
<add> Logging bool
<add> EnableCors bool
<add> CorsHeaders string
<add> Version string
<add> SocketGroup string
<add> TLSConfig *tls.Config
<ide> }
<ide>
<ide> // Server contains instance details for the server
<ide> type Server struct {
<ide> cfg *Config
<ide> servers []*HTTPServer
<ide> routers []router.Router
<del> authZPlugins []authorization.Plugin
<ide> routerSwapper *routerSwapper
<add> middlewares []middleware.Middleware
<ide> }
<ide>
<ide> // New returns a new instance of the server based on the specified configuration.
<ide> func New(cfg *Config) *Server {
<ide> }
<ide> }
<ide>
<add>// UseMiddleware appends a new middleware to the request chain.
<add>// This needs to be called before the API routes are configured.
<add>func (s *Server) UseMiddleware(m middleware.Middleware) {
<add> s.middlewares = append(s.middlewares, m)
<add>}
<add>
<ide> // Accept sets a listener the server accepts connections into.
<ide> func (s *Server) Accept(addr string, listeners ...net.Listener) {
<ide> for _, listener := range listeners {
<ide><path>api/server/server_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<add> "github.com/docker/docker/api/server/middleware"
<add> "github.com/docker/docker/pkg/version"
<ide>
<ide> "golang.org/x/net/context"
<ide> )
<ide> func TestMiddlewares(t *testing.T) {
<ide> cfg: cfg,
<ide> }
<ide>
<add> srv.UseMiddleware(middleware.NewVersionMiddleware(version.Version("0.1omega2"), api.DefaultVersion, api.MinVersion))
<add>
<ide> req, _ := http.NewRequest("GET", "/containers/json", nil)
<ide> resp := httptest.NewRecorder()
<ide> ctx := context.Background()
<ide><path>docker/daemon.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/uuid"
<add> "github.com/docker/docker/api"
<ide> apiserver "github.com/docker/docker/api/server"
<add> "github.com/docker/docker/api/server/middleware"
<ide> "github.com/docker/docker/api/server/router"
<ide> "github.com/docker/docker/api/server/router/build"
<ide> "github.com/docker/docker/api/server/router/container"
<ide> import (
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/libcontainerd"
<ide> "github.com/docker/docker/opts"
<add> "github.com/docker/docker/pkg/authorization"
<ide> "github.com/docker/docker/pkg/jsonlog"
<ide> "github.com/docker/docker/pkg/listeners"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/pidfile"
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/system"
<add> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> }
<ide>
<ide> serverConfig := &apiserver.Config{
<del> AuthorizationPluginNames: cli.Config.AuthorizationPlugins,
<del> Logging: true,
<del> SocketGroup: cli.Config.SocketGroup,
<del> Version: dockerversion.Version,
<add> Logging: true,
<add> SocketGroup: cli.Config.SocketGroup,
<add> Version: dockerversion.Version,
<ide> }
<ide> serverConfig = setPlatformServerConfig(serverConfig, cli.Config)
<ide>
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> "graphdriver": d.GraphDriverName(),
<ide> }).Info("Docker daemon")
<ide>
<add> cli.initMiddlewares(api, serverConfig)
<ide> initRouter(api, d)
<ide>
<ide> reload := func(config *daemon.Config) {
<ide> func initRouter(s *apiserver.Server, d *daemon.Daemon) {
<ide>
<ide> s.InitRouter(utils.IsDebugEnabled(), routers...)
<ide> }
<add>
<add>func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config) {
<add> v := version.Version(cfg.Version)
<add>
<add> vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
<add> s.UseMiddleware(vm)
<add>
<add> if cfg.EnableCors {
<add> c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
<add> s.UseMiddleware(c)
<add> }
<add>
<add> u := middleware.NewUserAgentMiddleware(v)
<add> s.UseMiddleware(u)
<add>
<add> if len(cli.Config.AuthorizationPlugins) > 0 {
<add> authZPlugins := authorization.NewPlugins(cli.Config.AuthorizationPlugins)
<add> handleAuthorization := authorization.NewMiddleware(authZPlugins)
<add> s.UseMiddleware(handleAuthorization)
<add> }
<add>}
<ide><path>pkg/authorization/middleware.go
<add>package authorization
<add>
<add>import (
<add> "net/http"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "golang.org/x/net/context"
<add>)
<add>
<add>// Middleware uses a list of plugins to
<add>// handle authorization in the API requests.
<add>type Middleware struct {
<add> plugins []Plugin
<add>}
<add>
<add>// NewMiddleware creates a new Middleware
<add>// with a slice of plugins.
<add>func NewMiddleware(p []Plugin) Middleware {
<add> return Middleware{
<add> plugins: p,
<add> }
<add>}
<add>
<add>// WrapHandler returns a new handler function wrapping the previous one in the request chain.
<add>func (m Middleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>
<add> user := ""
<add> userAuthNMethod := ""
<add>
<add> // Default authorization using existing TLS connection credentials
<add> // FIXME: Non trivial authorization mechanisms (such as advanced certificate validations, kerberos support
<add> // and ldap) will be extracted using AuthN feature, which is tracked under:
<add> // https://github.com/docker/docker/pull/20883
<add> if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
<add> user = r.TLS.PeerCertificates[0].Subject.CommonName
<add> userAuthNMethod = "TLS"
<add> }
<add>
<add> authCtx := NewCtx(m.plugins, user, userAuthNMethod, r.Method, r.RequestURI)
<add>
<add> if err := authCtx.AuthZRequest(w, r); err != nil {
<add> logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
<add> return err
<add> }
<add>
<add> rw := NewResponseModifier(w)
<add>
<add> if err := handler(ctx, rw, r, vars); err != nil {
<add> logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
<add> return err
<add> }
<add>
<add> if err := authCtx.AuthZResponse(rw, r); err != nil {
<add> logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
<add> return err
<add> }
<add> return nil
<add> }
<add>} | 12 |
PHP | PHP | add boolean validation option | 95aaa4de97bdddd4156b06afdad0a66196086565 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateAccepted($attribute, $value)
<ide> return ($this->validateRequired($attribute, $value) && in_array($value, $acceptable, true));
<ide> }
<ide>
<add> /**
<add> * Validate that an attribute is a boolean.
<add> *
<add> * @param string $attribute
<add> * @param mixed $value
<add> * @return bool
<add> */
<add> protected function validateBoolean($attribute, $value)
<add> {
<add> $acceptable = array(true, false, 0, 1, '0', '1');
<add>
<add> return in_array($value, $acceptable, true);
<add> }
<add>
<ide> /**
<ide> * Validate that an attribute is an array.
<ide> *
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateAccepted()
<ide> }
<ide>
<ide>
<add> public function testValidateBoolean()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, array('foo' => 'no'), array('foo' => 'Boolean'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => 'yes'), array('foo' => 'Boolean'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => 'false'), array('foo' => 'Boolean'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => 'true'), array('foo' => 'Boolean'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array(), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => false), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => true), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => '1'), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => 1), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => '0'), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('foo' => 0), array('foo' => 'Boolean'));
<add> $this->assertTrue($v->passes());
<add> }
<add>
<add>
<ide> public function testValidateNumeric()
<ide> {
<ide> $trans = $this->getRealTranslator(); | 2 |
Ruby | Ruby | add sprockets md5s to asset tags | 628c31b353706877322e7613702d1bd4a59e3514 | <ide><path>actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
<ide> def javascript_path(source)
<ide> #
<ide> # javascript_include_tag :all, :cache => true, :recursive => true
<ide> def javascript_include_tag(*sources)
<add> if config.perform_caching
<add> sources = sources.map do |source|
<add> if source =~ /^\/assets\/(.+)/
<add> "/assets/#{Rails.application.assets.url($1)}"
<add> else
<add> source
<add> end
<add> end
<add> end
<add>
<ide> @javascript_include ||= JavascriptIncludeTag.new(config, asset_paths)
<ide> @javascript_include.include_tag(*sources)
<ide> end
<ide><path>actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
<ide> def stylesheet_path(source)
<ide> # stylesheet_link_tag :all, :concat => true
<ide> #
<ide> def stylesheet_link_tag(*sources)
<add> if config.perform_caching
<add> sources = sources.map do |source|
<add> if source =~ /^\/assets\/(.+)/
<add> "/assets/#{Rails.application.assets.url($1)}"
<add> else
<add> source
<add> end
<add> end
<add> end
<add>
<ide> @stylesheet_include ||= StylesheetIncludeTag.new(config, asset_paths)
<ide> @stylesheet_include.include_tag(*sources)
<ide> end | 2 |
Python | Python | use resolvematch.view_name so namespaces work | 5bded1ecf03936621806991bf7f68434dd44c4ac | <ide><path>rest_framework/relations.py
<ide> def from_native(self, value):
<ide> except:
<ide> raise ValidationError(self.error_messages['no_match'])
<ide>
<del> if match.url_name != self.view_name:
<add> if match.view_name != self.view_name:
<ide> raise ValidationError(self.error_messages['incorrect_match'])
<ide>
<ide> pk = match.kwargs.get(self.pk_url_kwarg, None) | 1 |
Javascript | Javascript | simplify the `getfilenamefromurl` helper function | f3e0f866412ac7c4d04afef9cadd9b6433e32602 | <ide><path>src/display/display_utils.js
<ide> function isPdfFile(filename) {
<ide> * @returns {string}
<ide> */
<ide> function getFilenameFromUrl(url, onlyStripPath = false) {
<del> let end = url.length;
<ide> if (!onlyStripPath) {
<del> const anchor = url.indexOf("#");
<del> const query = url.indexOf("?");
<del> end = Math.min(anchor > 0 ? anchor : end, query > 0 ? query : end);
<add> [url] = url.split(/[#?]/, 1);
<ide> }
<del> return url.substring(url.lastIndexOf("/", end) + 1, end);
<add> return url.substring(url.lastIndexOf("/") + 1);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | improve the starting sentence | c1a661479ef75dac5afa2414413e1538ca72a19d | <ide><path>guides/source/action_view_overview.md
<ide> You can read more about the Rails Internationalization (I18n) API [here](i18n.ht
<ide> Using Action View outside of Rails
<ide> ----------------------------------
<ide>
<del>Action View works well with Active Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small [Rack](http://rack.rubyforge.org/) application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
<add>Action View is a Rails component, but it can also be used without Rails. We can demonstrate this by creating a small [Rack](http://rack.rubyforge.org/) application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
<ide>
<ide> Let's start by ensuring that you have the Action Pack and Rack gems installed:
<ide> | 1 |
Ruby | Ruby | fix rubocop warnings | fe661a809c8ec497c8096ec062908ddcb2c84a03 | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> module SharedEnvExtension
<ide> include CompilerConstants
<ide>
<ide> # @private
<del> CC_FLAG_VARS = %w[CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS]
<add> CC_FLAG_VARS = %w[CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS].freeze
<ide> # @private
<del> FC_FLAG_VARS = %w[FCFLAGS FFLAGS]
<add> FC_FLAG_VARS = %w[FCFLAGS FFLAGS].freeze
<ide> # @private
<ide> SANITIZED_VARS = %w[
<ide> CDPATH GREP_OPTIONS CLICOLOR_FORCE
<ide> module SharedEnvExtension
<ide> CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_FRAMEWORK_PATH
<ide> GOBIN GOPATH GOROOT PERL_MB_OPT PERL_MM_OPT
<ide> LIBRARY_PATH
<del> ]
<add> ].freeze
<ide>
<ide> # @private
<ide> def setup_build_environment(formula = nil)
<ide> def ncurses_define
<ide> def userpaths!
<ide> paths = self["PATH"].split(File::PATH_SEPARATOR)
<ide> # put Superenv.bin and opt path at the first
<del> new_paths = paths.select { |p| p.start_with?("#{HOMEBREW_REPOSITORY}/Library/ENV") || p.start_with?("#{HOMEBREW_PREFIX}/opt") }
<add> new_paths = paths.select { |p| p.start_with?("#{HOMEBREW_REPOSITORY}/Library/ENV", "#{HOMEBREW_PREFIX}/opt") }
<ide> # XXX hot fix to prefer brewed stuff (e.g. python) over /usr/bin.
<ide> new_paths << "#{HOMEBREW_PREFIX}/bin"
<ide> # reset of self["PATH"]
<ide> new_paths += paths
<ide> # user paths
<del> new_paths += ORIGINAL_PATHS.map { |p| p.realpath.to_s rescue nil } - %w[/usr/X11/bin /opt/X11/bin]
<add> new_paths += ORIGINAL_PATHS.map do |p|
<add> begin
<add> p.realpath.to_s
<add> rescue
<add> nil
<add> end
<add> end - %w[/usr/X11/bin /opt/X11/bin]
<ide> self["PATH"] = new_paths.uniq.join(File::PATH_SEPARATOR)
<ide> end
<ide> | 1 |
Javascript | Javascript | allow jest globals in __mocks__ directories | e78c01375aef88e0bb4029479acac9e85ecaf080 | <ide><path>packages/eslint-config-react-native-community/index.js
<ide> module.exports = {
<ide> },
<ide> },
<ide> {
<del> files: ['*.{spec,test}.{js,ts,tsx}', '**/__tests__/**/*.{js,ts,tsx}'],
<add> files: [
<add> '*.{spec,test}.{js,ts,tsx}',
<add> '**/__{mocks,tests}__/**/*.{js,ts,tsx}',
<add> ],
<ide> env: {
<ide> jest: true,
<ide> 'jest/globals': true, | 1 |
Python | Python | fix typo in docstrings [ci skip] | f5d3afb1a3a54201583a08ed201b28c21b5ac3d5 | <ide><path>spacy/pipeline/entityruler.py
<ide> def to_disk(self, path, **kwargs):
<ide>
<ide> path (unicode / Path): The JSONL file to save.
<ide> **kwargs: Other config paramters, mostly for consistency.
<del> RETURNS (EntityRuler): The loaded entity ruler.
<ide>
<ide> DOCS: https://spacy.io/api/entityruler#to_disk
<ide> """ | 1 |
Java | Java | remove pojo from tests that shouldn't depend on it | 22a6ca1f412856f8a83494f83fee2c7ca3e48a9e | <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/WebReactiveConfigurationTests.java
<ide> import java.util.List;
<ide> import java.util.concurrent.CompletableFuture;
<ide>
<add>import javax.xml.bind.annotation.XmlRootElement;
<add>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Flux;
<ide> import org.springframework.core.codec.support.JacksonJsonEncoder;
<ide> import org.springframework.core.codec.support.Jaxb2Decoder;
<ide> import org.springframework.core.codec.support.Jaxb2Encoder;
<del>import org.springframework.core.codec.support.Pojo;
<ide> import org.springframework.core.codec.support.StringDecoder;
<ide> import org.springframework.core.codec.support.StringEncoder;
<ide> import org.springframework.core.convert.ConversionService;
<ide> public void requestMappingHandlerAdapter() throws Exception {
<ide> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM);
<ide> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN);
<ide> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG);
<del> assertHasConverter(converters, Pojo.class, MediaType.APPLICATION_XML);
<del> assertHasConverter(converters, Pojo.class, MediaType.APPLICATION_JSON);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON);
<ide>
<ide> name = "mvcConversionService";
<ide> ConversionService service = context.getBean(name, ConversionService.class);
<ide> public void customMessageConverterConfig() throws Exception {
<ide> assertEquals(2, converters.size());
<ide>
<ide> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN);
<del> assertHasConverter(converters, Pojo.class, MediaType.APPLICATION_XML);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML);
<ide> }
<ide>
<ide> @Test
<ide> public void responseBodyResultHandler() throws Exception {
<ide> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM);
<ide> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN);
<ide> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG);
<del> assertHasConverter(converters, Pojo.class, MediaType.APPLICATION_XML);
<del> assertHasConverter(converters, Pojo.class, MediaType.APPLICATION_JSON);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON);
<ide> }
<ide>
<ide> @Test
<ide> public FreeMarkerConfigurer freeMarkerConfig() {
<ide> }
<ide>
<ide> }
<add>
<add> @XmlRootElement
<add> static class TestBean {
<add> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolverTests.java
<ide> import java.util.Set;
<ide> import java.util.concurrent.CompletableFuture;
<ide>
<add>import javax.xml.bind.annotation.XmlRootElement;
<add>
<ide> import org.junit.Before;
<ide> import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.support.JacksonJsonDecoder;
<ide> import org.springframework.core.codec.support.JsonObjectDecoder;
<del>import org.springframework.core.codec.support.Pojo;
<ide> import org.springframework.core.codec.support.StringDecoder;
<ide> import org.springframework.core.convert.support.GenericConversionService;
<ide> import org.springframework.core.convert.support.ReactiveStreamsToCompletableFutureConverter;
<ide> public void setUp() throws Exception {
<ide> public void supports() throws Exception {
<ide> RequestBodyArgumentResolver resolver = resolver(new StringDecoder());
<ide>
<del> assertTrue(resolver.supportsParameter(parameter("monoPojo")));
<add> assertTrue(resolver.supportsParameter(parameter("monoTestBean")));
<ide> assertFalse(resolver.supportsParameter(parameter("paramWithoutAnnotation")));
<ide> }
<ide>
<ide> @Test
<ide> public void missingContentType() throws Exception {
<ide> String body = "{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}";
<ide> this.request.writeWith(Flux.just(dataBuffer(body)));
<del> Mono<Object> result = this.resolver.resolveArgument(parameter("monoPojo"), this.model, this.exchange);
<add> Mono<Object> result = this.resolver.resolveArgument(parameter("monoTestBean"), this.model, this.exchange);
<ide>
<ide> TestSubscriber.subscribe(result)
<ide> .assertError(UnsupportedMediaTypeStatusException.class);
<ide> }
<ide>
<ide> @Test @SuppressWarnings("unchecked")
<del> public void monoPojo() throws Exception {
<add> public void monoTestBean() throws Exception {
<ide> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}";
<del> Mono<Pojo> mono = (Mono<Pojo>) resolve("monoPojo", Mono.class, body);
<del> assertEquals(new Pojo("f1", "b1"), mono.block());
<add> Mono<TestBean> mono = (Mono<TestBean>) resolve("monoTestBean", Mono.class, body);
<add> assertEquals(new TestBean("f1", "b1"), mono.block());
<ide> }
<ide>
<ide> @Test @SuppressWarnings("unchecked")
<del> public void fluxPojo() throws Exception {
<add> public void fluxTestBean() throws Exception {
<ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<del> Flux<Pojo> flux = (Flux<Pojo>) resolve("fluxPojo", Flux.class, body);
<del> assertEquals(Arrays.asList(new Pojo("f1", "b1"), new Pojo("f2", "b2")), flux.collectList().block());
<add> Flux<TestBean> flux = (Flux<TestBean>) resolve("fluxTestBean", Flux.class, body);
<add> assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), flux.collectList().block());
<ide> }
<ide>
<ide> @Test @SuppressWarnings("unchecked")
<del> public void singlePojo() throws Exception {
<add> public void singleTestBean() throws Exception {
<ide> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}";
<del> Single<Pojo> single = (Single<Pojo>) resolve("singlePojo", Single.class, body);
<del> assertEquals(new Pojo("f1", "b1"), single.toBlocking().value());
<add> Single<TestBean> single = (Single<TestBean>) resolve("singleTestBean", Single.class, body);
<add> assertEquals(new TestBean("f1", "b1"), single.toBlocking().value());
<ide> }
<ide>
<ide> @Test @SuppressWarnings("unchecked")
<del> public void observablePojo() throws Exception {
<add> public void observableTestBean() throws Exception {
<ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<del> Observable<?> observable = (Observable<?>) resolve("observablePojo", Observable.class, body);
<del> assertEquals(Arrays.asList(new Pojo("f1", "b1"), new Pojo("f2", "b2")),
<add> Observable<?> observable = (Observable<?>) resolve("observableTestBean", Observable.class, body);
<add> assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")),
<ide> observable.toList().toBlocking().first());
<ide> }
<ide>
<ide> @Test @SuppressWarnings("unchecked")
<del> public void futurePojo() throws Exception {
<add> public void futureTestBean() throws Exception {
<ide> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}";
<del> assertEquals(new Pojo("f1", "b1"), resolve("futurePojo", CompletableFuture.class, body).get());
<add> assertEquals(new TestBean("f1", "b1"), resolve("futureTestBean", CompletableFuture.class, body).get());
<ide> }
<ide>
<ide> @Test
<del> public void pojo() throws Exception {
<add> public void testBean() throws Exception {
<ide> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}";
<del> assertEquals(new Pojo("f1", "b1"), resolve("pojo", Pojo.class, body));
<add> assertEquals(new TestBean("f1", "b1"), resolve("testBean", TestBean.class, body));
<ide> }
<ide>
<ide> @Test
<ide> public void map() throws Exception {
<ide> @Ignore
<ide> public void list() throws Exception {
<ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<del> assertEquals(Arrays.asList(new Pojo("f1", "b1"), new Pojo("f2", "b2")),
<add> assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")),
<ide> resolve("list", List.class, body));
<ide> }
<ide>
<ide> @Test
<ide> @Ignore
<ide> public void array() throws Exception {
<ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<del> assertArrayEquals(new Pojo[] {new Pojo("f1", "b1"), new Pojo("f2", "b2")},
<del> resolve("array", Pojo[].class, body));
<add> assertArrayEquals(new TestBean[] {new TestBean("f1", "b1"), new TestBean("f2", "b2")},
<add> resolve("array", TestBean[].class, body));
<ide> }
<ide>
<ide>
<ide> private DataBuffer dataBuffer(String body) {
<ide>
<ide> @SuppressWarnings("unused")
<ide> void handle(
<del> @RequestBody Mono<Pojo> monoPojo,
<del> @RequestBody Flux<Pojo> fluxPojo,
<del> @RequestBody Single<Pojo> singlePojo,
<del> @RequestBody Observable<Pojo> observablePojo,
<del> @RequestBody CompletableFuture<Pojo> futurePojo,
<del> @RequestBody Pojo pojo,
<add> @RequestBody Mono<TestBean> monoTestBean,
<add> @RequestBody Flux<TestBean> fluxTestBean,
<add> @RequestBody Single<TestBean> singleTestBean,
<add> @RequestBody Observable<TestBean> observableTestBean,
<add> @RequestBody CompletableFuture<TestBean> futureTestBean,
<add> @RequestBody TestBean testBean,
<ide> @RequestBody Map<String, String> map,
<del> @RequestBody List<Pojo> list,
<del> @RequestBody Set<Pojo> set,
<del> @RequestBody Pojo[] array,
<del> Pojo paramWithoutAnnotation) {
<add> @RequestBody List<TestBean> list,
<add> @RequestBody Set<TestBean> set,
<add> @RequestBody TestBean[] array,
<add> TestBean paramWithoutAnnotation) {
<ide> }
<ide>
<add>
<add> @XmlRootElement
<add> static class TestBean {
<add>
<add> private String foo;
<add>
<add> private String bar;
<add>
<add> public TestBean() {
<add> }
<add>
<add> public TestBean(String foo, String bar) {
<add> this.foo = foo;
<add> this.bar = bar;
<add> }
<add>
<add> public String getFoo() {
<add> return this.foo;
<add> }
<add>
<add> public void setFoo(String foo) {
<add> this.foo = foo;
<add> }
<add>
<add> public String getBar() {
<add> return this.bar;
<add> }
<add>
<add> public void setBar(String bar) {
<add> this.bar = bar;
<add> }
<add>
<add> @Override
<add> public boolean equals(Object o) {
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o instanceof TestBean) {
<add> TestBean other = (TestBean) o;
<add> return this.foo.equals(other.foo) && this.bar.equals(other.bar);
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return 31 * foo.hashCode() + bar.hashCode();
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return "TestBean[foo='" + this.foo + "\'" + ", bar='" + this.bar + "\']";
<add> }
<add> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/view/HttpMessageConverterViewTests.java
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<add>import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.support.JacksonJsonEncoder;
<ide> import org.springframework.core.codec.support.Jaxb2Encoder;
<del>import org.springframework.core.codec.support.Pojo;
<ide> import org.springframework.core.codec.support.StringEncoder;
<ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<ide> import org.springframework.http.HttpMethod;
<ide> public void extractObjectNotSupported() throws Exception {
<ide>
<ide> @Test
<ide> public void render() throws Exception {
<del> this.model.addAttribute("pojo", new Pojo("foo", "bar"));
<del> this.view.setModelKeys(Collections.singleton("pojo"));
<add> Map<String, String> pojoData = new LinkedHashMap<>();
<add> pojoData.put("foo", "f");
<add> pojoData.put("bar", "b");
<add> this.model.addAttribute("pojoData", pojoData);
<add> this.view.setModelKeys(Collections.singleton("pojoData"));
<ide>
<ide> MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI("/path"));
<ide> MockServerHttpResponse response = new MockServerHttpResponse();
<ide> public void render() throws Exception {
<ide>
<ide> TestSubscriber
<ide> .subscribe(response.getBody())
<del> .assertValuesWith(buf -> assertEquals("{\"foo\":\"foo\",\"bar\":\"bar\"}",
<add> .assertValuesWith(buf -> assertEquals("{\"foo\":\"f\",\"bar\":\"b\"}",
<ide> DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8"))));
<ide> }
<ide>
<add>
<ide> } | 3 |
Python | Python | move generic views into seperate module | b79833ecddcea788b4a8d8901bd25f0afe83bbf7 | <ide><path>djangorestframework/generics.py
<add>"""
<add>Generic views that provide commmonly needed behaviour.
<add>"""
<add>
<add>from djangorestframework import views, mixins
<add>from django.views.generic.detail import SingleObjectMixin
<add>from django.views.generic.list import MultipleObjectMixin
<add>
<add>
<add>### Base classes for the generic views ###
<add>
<add>class BaseView(views.APIView):
<add> """
<add> Base class for all other generic views.
<add> """
<add> serializer_class = None
<add>
<add> def get_serializer(self, data=None, files=None, instance=None):
<add> # TODO: add support for files
<add> # TODO: add support for seperate serializer/deserializer
<add> context = {
<add> 'request': self.request,
<add> 'format': self.kwargs.get('format', None)
<add> }
<add> return self.serializer_class(data, instance=instance, context=context)
<add>
<add>
<add>class MultipleObjectBaseView(MultipleObjectMixin, BaseView):
<add> """
<add> Base class for generic views onto a queryset.
<add> """
<add> pass
<add>
<add>
<add>class SingleObjectBaseView(SingleObjectMixin, BaseView):
<add> """
<add> Base class for generic views onto a model instance.
<add> """
<add>
<add> def get_object(self):
<add> """
<add> Override default to add support for object-level permissions.
<add> """
<add> super(self, SingleObjectBaseView).get_object()
<add> self.check_permissions(self.request, self.object)
<add>
<add>
<add>### Concrete view classes that provide method handlers ###
<add>### by composing the mixin classes with a base view. ###
<add>
<add>class ListAPIView(mixins.ListModelMixin,
<add> mixins.MetadataMixin,
<add> MultipleObjectBaseView):
<add> """
<add> Concrete view for listing a queryset.
<add> """
<add> def get(self, request, *args, **kwargs):
<add> return self.list(request, *args, **kwargs)
<add>
<add> def options(self, request, *args, **kwargs):
<add> return self.metadata(request, *args, **kwargs)
<add>
<add>
<add>class RootAPIView(mixins.ListModelMixin,
<add> mixins.CreateModelMixin,
<add> mixins.MetadataMixin,
<add> MultipleObjectBaseView):
<add> """
<add> Concrete view for listing a queryset or creating a model instance.
<add> """
<add> def get(self, request, *args, **kwargs):
<add> return self.list(request, *args, **kwargs)
<add>
<add> def post(self, request, *args, **kwargs):
<add> return self.create(request, *args, **kwargs)
<add>
<add> def options(self, request, *args, **kwargs):
<add> return self.metadata(request, *args, **kwargs)
<add>
<add>
<add>class DetailAPIView(mixins.RetrieveModelMixin,
<add> mixins.MetadataMixin,
<add> SingleObjectBaseView):
<add> """
<add> Concrete view for retrieving a model instance.
<add> """
<add> def get(self, request, *args, **kwargs):
<add> return self.retrieve(request, *args, **kwargs)
<add>
<add> def options(self, request, *args, **kwargs):
<add> return self.metadata(request, *args, **kwargs)
<add>
<add>
<add>class InstanceAPIView(mixins.RetrieveModelMixin,
<add> mixins.UpdateModelMixin,
<add> mixins.DestroyModelMixin,
<add> mixins.MetadataMixin,
<add> SingleObjectBaseView):
<add> """
<add> Concrete view for retrieving, updating or deleting a model instance.
<add> """
<add> def get(self, request, *args, **kwargs):
<add> return self.retrieve(request, *args, **kwargs)
<add>
<add> def put(self, request, *args, **kwargs):
<add> return self.update(request, *args, **kwargs)
<add>
<add> def delete(self, request, *args, **kwargs):
<add> return self.destroy(request, *args, **kwargs)
<add>
<add> def options(self, request, *args, **kwargs):
<add> return self.metadata(request, *args, **kwargs)
<ide><path>djangorestframework/views.py
<ide> from django.utils.html import escape
<ide> from django.utils.safestring import mark_safe
<ide> from django.views.decorators.csrf import csrf_exempt
<del>from django.views.generic.detail import SingleObjectMixin
<del>from django.views.generic.list import MultipleObjectMixin
<ide>
<ide> from djangorestframework.compat import View as _View, apply_markdown
<ide> from djangorestframework.response import Response
<ide> from djangorestframework.request import Request
<ide> from djangorestframework.settings import api_settings
<del>from djangorestframework import parsers, authentication, status, exceptions, mixins
<add>from djangorestframework import status, exceptions
<ide>
<ide>
<ide> def _remove_trailing_string(content, trailing):
<ide> def _camelcase_to_spaces(content):
<ide>
<ide> class APIView(_View):
<ide> renderers = api_settings.DEFAULT_RENDERERS
<del> """
<del> List of renderer classes the view can serialize the response with, ordered by preference.
<del> """
<del>
<del> parsers = parsers.DEFAULT_PARSERS
<del> """
<del> List of parser classes the view can parse the request with.
<del> """
<del>
<del> authentication = (authentication.SessionAuthentication,
<del> authentication.UserBasicAuthentication)
<del> """
<del> List of all authenticating methods to attempt.
<del> """
<del>
<del> throttle_classes = ()
<del> """
<del> List of all throttles to check.
<del> """
<del>
<del> permission_classes = ()
<del> """
<del> List of all permissions that must be checked.
<del> """
<add> parsers = api_settings.DEFAULT_PARSERS
<add> authentication = api_settings.DEFAULT_AUTHENTICATION
<add> throttle_classes = api_settings.DEFAULT_THROTTLES
<add> permission_classes = api_settings.DEFAULT_PERMISSIONS
<ide>
<ide> @classmethod
<ide> def as_view(cls, **initkwargs):
<ide> def dispatch(self, request, *args, **kwargs):
<ide>
<ide> self.response = self.finalize_response(request, response, *args, **kwargs)
<ide> return self.response
<del>
<del>
<del># Abstract view classes that do not provide any method handlers,
<del># but which provide required behaviour for concrete views to build on.
<del>
<del>class BaseView(APIView):
<del> """
<del> Base class for all generic views.
<del> """
<del> serializer_class = None
<del>
<del> def get_serializer(self, data=None, files=None, instance=None):
<del> # TODO: add support for files
<del> context = {
<del> 'request': self.request,
<del> 'format': self.kwargs.get('format', None)
<del> }
<del> return self.serializer_class(data, instance=instance, context=context)
<del>
<del>
<del>class MultipleObjectBaseView(MultipleObjectMixin, BaseView):
<del> """
<del> Base class for generic views onto a queryset.
<del> """
<del> pass
<del>
<del>
<del>class SingleObjectBaseView(SingleObjectMixin, BaseView):
<del> """
<del> Base class for generic views onto a model instance.
<del> """
<del>
<del> def get_object(self):
<del> """
<del> Override default to add support for object-level permissions.
<del> """
<del> super(self, SingleObjectBaseView).get_object()
<del> self.check_permissions(self.request, self.object)
<del>
<del>
<del># Concrete view classes that provide method handlers
<del># by composing the mixin classes with a base view.
<del>
<del>class ListAPIView(mixins.ListModelMixin,
<del> mixins.MetadataMixin,
<del> MultipleObjectBaseView):
<del> """
<del> Concrete view for listing a queryset.
<del> """
<del> def get(self, request, *args, **kwargs):
<del> return self.list(request, *args, **kwargs)
<del>
<del> def options(self, request, *args, **kwargs):
<del> return self.metadata(request, *args, **kwargs)
<del>
<del>
<del>class RootAPIView(mixins.ListModelMixin,
<del> mixins.CreateModelMixin,
<del> mixins.MetadataMixin,
<del> MultipleObjectBaseView):
<del> """
<del> Concrete view for listing a queryset or creating a model instance.
<del> """
<del> def get(self, request, *args, **kwargs):
<del> return self.list(request, *args, **kwargs)
<del>
<del> def post(self, request, *args, **kwargs):
<del> return self.create(request, *args, **kwargs)
<del>
<del> def options(self, request, *args, **kwargs):
<del> return self.metadata(request, *args, **kwargs)
<del>
<del>
<del>class DetailAPIView(mixins.RetrieveModelMixin,
<del> mixins.MetadataMixin,
<del> SingleObjectBaseView):
<del> """
<del> Concrete view for retrieving a model instance.
<del> """
<del> def get(self, request, *args, **kwargs):
<del> return self.retrieve(request, *args, **kwargs)
<del>
<del> def options(self, request, *args, **kwargs):
<del> return self.metadata(request, *args, **kwargs)
<del>
<del>
<del>class InstanceAPIView(mixins.RetrieveModelMixin,
<del> mixins.UpdateModelMixin,
<del> mixins.DestroyModelMixin,
<del> mixins.MetadataMixin,
<del> SingleObjectBaseView):
<del> """
<del> Concrete view for retrieving, updating or deleting a model instance.
<del> """
<del> def get(self, request, *args, **kwargs):
<del> return self.retrieve(request, *args, **kwargs)
<del>
<del> def put(self, request, *args, **kwargs):
<del> return self.update(request, *args, **kwargs)
<del>
<del> def delete(self, request, *args, **kwargs):
<del> return self.destroy(request, *args, **kwargs)
<del>
<del> def options(self, request, *args, **kwargs):
<del> return self.metadata(request, *args, **kwargs) | 2 |
Ruby | Ruby | convert naked test to spec | 59668d27108c34499ae8d00dd9354dc57a112de0 | <add><path>Library/Homebrew/cask/spec/cask/container/naked_spec.rb
<del><path>Library/Homebrew/cask/test/cask/container/naked_test.rb
<del>require "test_helper"
<add>require "spec_helper"
<ide>
<ide> describe Hbc::Container::Naked do
<ide> it "saves files with spaces in them from uris with encoded spaces" do
<ide> Hbc::FakeSystemCommand.stubs_command(expected_command)
<ide>
<ide> container = Hbc::Container::Naked.new(cask, path, Hbc::FakeSystemCommand)
<del> container.extract
<ide>
<del> Hbc::FakeSystemCommand.system_calls[expected_command].must_equal 1
<add> expect {
<add> shutup do
<add> container.extract
<add> end
<add> }.not_to raise_error
<add>
<add> expect(Hbc::FakeSystemCommand.system_calls[expected_command]).to eq(1)
<ide> end
<ide> end | 1 |
Javascript | Javascript | handle sparse arrays in deepstrictequal | 4381100371b6377f2d51d55deeb300a9bc1f39da | <ide><path>lib/assert.js
<ide> function strictDeepEqual(actual, expected) {
<ide> if (Object.getPrototypeOf(actual) !== Object.getPrototypeOf(expected)) {
<ide> return false;
<ide> }
<del> if (isObjectOrArrayTag(actualTag)) {
<add> if (actualTag === '[object Array]') {
<add> // Check for sparse arrays and general fast path
<add> if (actual.length !== expected.length)
<add> return false;
<add> // Skip testing the part below and continue in the callee function.
<add> return;
<add> }
<add> if (actualTag === '[object Object]') {
<ide> // Skip testing the part below and continue in the callee function.
<ide> return;
<ide> }
<ide><path>test/parallel/test-assert-deep.js
<ide> assertOnlyDeepEqual(
<ide> assertDeepAndStrictEqual(m3, m4);
<ide> }
<ide>
<add>assertDeepAndStrictEqual([1, , , 3], [1, , , 3]);
<add>assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]);
<add>
<ide> /* eslint-enable */ | 2 |
Ruby | Ruby | fetch all resources with livecheck block | 8ef6118ba06a5ae45b11681829cd925e424f92a8 | <ide><path>Library/Homebrew/dev-cmd/livecheck.rb
<ide> def livecheck
<ide> resources = Formula.all do |formula|
<ide> formula.resources.any do |resource|
<ide> if resource.livecheckable?
<del> p resource
<add> resource
<ide> end
<ide> end
<add> # formula.resources.filter? { |resource| !resource.livecheckable? }
<ide> end
<add> resources
<ide> elsif args.all?
<ide> formulae = args.cask? ? [] : Formula.all
<ide> casks = args.formula? ? [] : Cask::Cask.all | 1 |
Java | Java | fix typo in javadoc | 010b7375fc99f2bc9adf1cc0d21c8a62d5139d07 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/MatchableHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> default PathPatternParser getPatternParser() {
<ide> /**
<ide> * Determine whether the request matches the given pattern. Use this method
<ide> * when {@link #getPatternParser()} returns {@code null} which means that the
<del> * {@code HandlerMapping} is uses String pattern matching.
<add> * {@code HandlerMapping} is using String pattern matching.
<ide> * @param request the current request
<ide> * @param pattern the pattern to match
<ide> * @return the result from request matching, or {@code null} if none | 1 |
Go | Go | add verification of image manifest digests | 9ececa14ba860c9934d3cd8d3e704e53e828e22b | <ide><path>graph/manifest.go
<ide> import (
<ide> "fmt"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/registry"
<add> "github.com/docker/docker/utils"
<ide> "github.com/docker/libtrust"
<ide> )
<ide>
<ide> import (
<ide> // contains no signatures by a trusted key for the name in the manifest, the
<ide> // image is not considered verified. The parsed manifest object and a boolean
<ide> // for whether the manifest is verified is returned.
<del>func (s *TagStore) loadManifest(eng *engine.Engine, manifestBytes []byte) (*registry.ManifestData, bool, error) {
<add>func (s *TagStore) loadManifest(eng *engine.Engine, manifestBytes []byte, dgst, ref string) (*registry.ManifestData, bool, error) {
<ide> sig, err := libtrust.ParsePrettySignature(manifestBytes, "signatures")
<ide> if err != nil {
<ide> return nil, false, fmt.Errorf("error parsing payload: %s", err)
<ide> func (s *TagStore) loadManifest(eng *engine.Engine, manifestBytes []byte) (*regi
<ide> return nil, false, fmt.Errorf("error retrieving payload: %s", err)
<ide> }
<ide>
<add> var manifestDigest digest.Digest
<add>
<add> if dgst != "" {
<add> manifestDigest, err = digest.ParseDigest(dgst)
<add> if err != nil {
<add> return nil, false, fmt.Errorf("invalid manifest digest from registry: %s", err)
<add> }
<add>
<add> dgstVerifier, err := digest.NewDigestVerifier(manifestDigest)
<add> if err != nil {
<add> return nil, false, fmt.Errorf("unable to verify manifest digest from registry: %s", err)
<add> }
<add>
<add> dgstVerifier.Write(payload)
<add>
<add> if !dgstVerifier.Verified() {
<add> computedDigest, _ := digest.FromBytes(payload)
<add> return nil, false, fmt.Errorf("unable to verify manifest digest: registry has %q, computed %q", manifestDigest, computedDigest)
<add> }
<add> }
<add>
<add> if utils.DigestReference(ref) && ref != manifestDigest.String() {
<add> return nil, false, fmt.Errorf("mismatching image manifest digest: got %q, expected %q", manifestDigest, ref)
<add> }
<add>
<ide> var manifest registry.ManifestData
<ide> if err := json.Unmarshal(payload, &manifest); err != nil {
<ide> return nil, false, fmt.Errorf("error unmarshalling manifest: %s", err)
<ide><path>graph/pull.go
<ide> func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out
<ide>
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, endpoint *registry.Endpoint, repoInfo *registry.RepositoryInfo, tag string, sf *utils.StreamFormatter, parallel bool, auth *registry.RequestAuthorization) (bool, error) {
<ide> log.Debugf("Pulling tag from V2 registry: %q", tag)
<add>
<ide> manifestBytes, manifestDigest, err := r.GetV2ImageManifest(endpoint, repoInfo.RemoteName, tag, auth)
<ide> if err != nil {
<ide> return false, err
<ide> }
<ide>
<del> manifest, verified, err := s.loadManifest(eng, manifestBytes)
<add> // loadManifest ensures that the manifest payload has the expected digest
<add> // if the tag is a digest reference.
<add> manifest, verified, err := s.loadManifest(eng, manifestBytes, manifestDigest, tag)
<ide> if err != nil {
<ide> return false, fmt.Errorf("error verifying manifest: %s", err)
<ide> }
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide> out.Write(sf.FormatStatus(utils.ImageReference(repoInfo.CanonicalName, tag), "The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security."))
<ide> }
<ide>
<del> if len(manifestDigest) > 0 {
<add> if manifestDigest != "" {
<ide> out.Write(sf.FormatStatus("", "Digest: %s", manifestDigest))
<ide> }
<ide>
<ide><path>graph/push.go
<ide> package graph
<ide>
<ide> import (
<del> "bytes"
<ide> "crypto/sha256"
<ide> "encoding/json"
<ide> "errors"
<ide> func (s *TagStore) pushV2Repository(r *registry.Session, localRepo Repository, o
<ide> log.Infof("Signed manifest for %s:%s using daemon's key: %s", repoInfo.LocalName, tag, s.trustKey.KeyID())
<ide>
<ide> // push the manifest
<del> digest, err := r.PutV2ImageManifest(endpoint, repoInfo.RemoteName, tag, bytes.NewReader(signedBody), auth)
<add> digest, err := r.PutV2ImageManifest(endpoint, repoInfo.RemoteName, tag, signedBody, mBytes, auth)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> if len(digest) > 0 {
<del> out.Write(sf.FormatStatus("", "Digest: %s", digest))
<del> }
<add> out.Write(sf.FormatStatus("", "Digest: %s", digest))
<ide> }
<ide> return nil
<ide> }
<ide><path>registry/session_v2.go
<ide> package registry
<ide>
<ide> import (
<add> "bytes"
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> "strconv"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<add> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/registry/v2"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide> func (r *Session) GetV2ImageManifest(ep *Endpoint, imageName, tagName string, au
<ide> return nil, "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch for %s:%s", res.StatusCode, imageName, tagName), res)
<ide> }
<ide>
<del> buf, err := ioutil.ReadAll(res.Body)
<add> manifestBytes, err := ioutil.ReadAll(res.Body)
<ide> if err != nil {
<ide> return nil, "", fmt.Errorf("Error while reading the http response: %s", err)
<ide> }
<del> return buf, res.Header.Get(DockerDigestHeader), nil
<add>
<add> return manifestBytes, res.Header.Get(DockerDigestHeader), nil
<ide> }
<ide>
<ide> // - Succeeded to head image blob (already exists)
<ide> func (r *Session) PutV2ImageBlob(ep *Endpoint, imageName, sumType, sumStr string
<ide> }
<ide>
<ide> // Finally Push the (signed) manifest of the blobs we've just pushed
<del>func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, manifestRdr io.Reader, auth *RequestAuthorization) (string, error) {
<add>func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, signedManifest, rawManifest []byte, auth *RequestAuthorization) (digest.Digest, error) {
<ide> routeURL, err := getV2Builder(ep).BuildManifestURL(imageName, tagName)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide>
<ide> method := "PUT"
<ide> log.Debugf("[registry] Calling %q %s", method, routeURL)
<del> req, err := r.reqFactory.NewRequest(method, routeURL, manifestRdr)
<add> req, err := r.reqFactory.NewRequest(method, routeURL, bytes.NewReader(signedManifest))
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, ma
<ide> return "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s:%s manifest", res.StatusCode, imageName, tagName), res)
<ide> }
<ide>
<del> return res.Header.Get(DockerDigestHeader), nil
<add> hdrDigest, err := digest.ParseDigest(res.Header.Get(DockerDigestHeader))
<add> if err != nil {
<add> return "", fmt.Errorf("invalid manifest digest from registry: %s", err)
<add> }
<add>
<add> dgstVerifier, err := digest.NewDigestVerifier(hdrDigest)
<add> if err != nil {
<add> return "", fmt.Errorf("invalid manifest digest from registry: %s", err)
<add> }
<add>
<add> dgstVerifier.Write(rawManifest)
<add>
<add> if !dgstVerifier.Verified() {
<add> computedDigest, _ := digest.FromBytes(rawManifest)
<add> return "", fmt.Errorf("unable to verify manifest digest: registry has %q, computed %q", hdrDigest, computedDigest)
<add> }
<add>
<add> return hdrDigest, nil
<ide> }
<ide>
<ide> type remoteTags struct { | 4 |
Text | Text | update colours + example values in docs | 527e7d9b7a5fe198e9cf096890bc30fb6a4bdafc | <ide><path>docs/02-Line-Chart.md
<ide> var data = {
<ide> label: "My First dataset",
<ide>
<ide> // Boolean - if true fill the area under the line
<del> fill: false,
<del>
<del> // Tension - bezier curve tension of the line. Set to 0 to draw straight lines connecting points
<del> // Used to be called "tension" but was renamed for consistency. The old option name continues to work for compatibility.
<del> lineTension: 0.1,
<add> fill: false,
<add>
<add> // Tension - bezier curve tension of the line. Set to 0 to draw straight lines connecting points
<add> // Used to be called "tension" but was renamed for consistency. The old option name continues to work for compatibility.
<add> lineTension: 0.1,
<ide>
<ide> // String - the color to fill the area under the line with if fill is true
<del> backgroundColor: "rgba(220,220,220,0.2)",
<add> backgroundColor: "rgba(75,192,192,0.4)",
<ide>
<del> // String - Line color
<del> borderColor: "rgba(220,220,220,1)",
<add> // String - Line color
<add> borderColor: "rgba(75,192,192,1)",
<ide>
<ide> // String - cap style of the line. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap
<ide> borderCapStyle: 'butt',
<ide> var data = {
<ide> borderDashOffset: 0.0,
<ide>
<ide> // String - line join style. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
<del> borderJoinStyle: 'miter',
<del>
<del> // The properties below allow an array to be specified to change the value of the item at the given index
<add> borderJoinStyle: 'miter',
<add>
<add> // The properties below allow an array to be specified to change the value of the item at the given index
<ide>
<del> // String or Array - Point stroke color
<del> pointBorderColor: "rgba(220,220,220,1)",
<add> // String or Array - Point stroke color
<add> pointBorderColor: "rgba(75,192,192,1)",
<ide>
<del> // String or Array - Point fill color
<add> // String or Array - Point fill color
<ide> pointBackgroundColor: "#fff",
<ide>
<del> // Number or Array - Stroke width of point border
<add> // Number or Array - Stroke width of point border
<ide> pointBorderWidth: 1,
<ide>
<del> // Number or Array - Radius of point when hovered
<add> // Number or Array - Radius of point when hovered
<ide> pointHoverRadius: 5,
<ide>
<del> // String or Array - point background color when hovered
<del> pointHoverBackgroundColor: "rgba(220,220,220,1)",
<add> // String or Array - point background color when hovered
<add> pointHoverBackgroundColor: "rgba(75,192,192,1)",
<ide>
<del> // String or Array - Point border color when hovered
<add> // String or Array - Point border color when hovered
<ide> pointHoverBorderColor: "rgba(220,220,220,1)",
<ide>
<del> // Number or Array - border width of point when hovered
<del> pointHoverBorderWidth: 2,
<add> // Number or Array - border width of point when hovered
<add> pointHoverBorderWidth: 2,
<add>
<add> // Number or Array - the pixel size of the point shape. Can be set to 0 to not render a circle over the point
<add> // Used to be called "radius" but was renamed for consistency. The old option name continues to work for compatibility.
<add> pointRadius: 1,
<ide>
<del> // Number or Array - the pixel size of the point shape. Can be set to 0 to not render a circle over the point
<del> // Used to be called "radius" but was renamed for consistency. The old option name continues to work for compatibility.
<del> pointRadius: 1,
<del>
<del> // Number or Array - the pixel size of the non-displayed point that reacts to mouse hover events
<del> //
<del> // Used to be called "hitRadius" but was renamed for consistency. The old option name continues to work for compatibility.
<del> pointHitRadius: 10,
<add> // Number or Array - the pixel size of the non-displayed point that reacts to mouse hover events
<add> //
<add> // Used to be called "hitRadius" but was renamed for consistency. The old option name continues to work for compatibility.
<add> pointHitRadius: 10,
<ide>
<ide> // The actual data
<ide> data: [65, 59, 80, 81, 56, 55, 40],
<ide> var data = {
<ide> {
<ide> label: "My Second dataset",
<ide> fill: false,
<del> backgroundColor: "rgba(220,220,220,0.2)",
<del> borderColor: "rgba(220,220,220,1)",
<del> pointBorderColor: "rgba(220,220,220,1)",
<add> backgroundColor: "rgba(255,205,86,0.4)",
<add> borderColor: "rgba(255,205,86,1)",
<add> pointBorderColor: "rgba(255,205,86,1)",
<ide> pointBackgroundColor: "#fff",
<ide> pointBorderWidth: 1,
<ide> pointHoverRadius: 5,
<del> pointHoverBackgroundColor: "rgba(220,220,220,1)",
<del> pointHoverBorderColor: "rgba(220,220,220,1)",
<add> pointHoverBackgroundColor: "rgba(255,205,86,1)",
<add> pointHoverBorderColor: "rgba(255,205,86,1)",
<ide> pointHoverBorderWidth: 2,
<ide> data: [28, 48, 40, 19, 86, 27, 90]
<ide> }
<ide><path>docs/03-Bar-Chart.md
<ide> var data = {
<ide>
<ide> // The properties below allow an array to be specified to change the value of the item at the given index
<ide> // String or array - the bar color
<del> backgroundColor: "rgba(220,220,220,0.2)",
<add> backgroundColor: "rgba(255,99,132,0.2)",
<ide>
<ide> // String or array - bar stroke color
<del> borderColor: "rgba(220,220,220,1)",
<add> borderColor: "rgba(255,99,132,1)",
<ide>
<ide> // Number or array - bar border width
<ide> borderWidth: 1,
<ide>
<ide> // String or array - fill color when hovered
<del> hoverBackgroundColor: "rgba(220,220,220,0.2)",
<add> hoverBackgroundColor: "rgba(255,99,132,0.4)",
<ide>
<ide> // String or array - border color when hovered
<del> hoverBorderColor: "rgba(220,220,220,1)",
<add> hoverBorderColor: "rgba(255,99,132,1)",
<ide>
<ide> // The actual data
<ide> data: [65, 59, 80, 81, 56, 55, 40],
<ide> var data = {
<ide> },
<ide> {
<ide> label: "My Second dataset",
<del> backgroundColor: "rgba(220,220,220,0.2)",
<del> borderColor: "rgba(220,220,220,1)",
<add> backgroundColor: "rgba(54,162,235,0.2)",
<add> borderColor: "rgba(54,162,235,1)",
<ide> borderWidth: 1,
<del> hoverBackgroundColor: "rgba(220,220,220,0.2)",
<del> hoverBorderColor: "rgba(220,220,220,1)",
<add> hoverBackgroundColor: "rgba(54,162,235,0.4)",
<add> hoverBorderColor: "rgba(54,162,235,1)",
<ide> data: [28, 48, 40, 19, 86, 27, 90]
<ide> }
<ide> ]
<ide><path>docs/04-Radar-Chart.md
<ide> var data = {
<ide> datasets: [
<ide> {
<ide> label: "My First dataset",
<del> backgroundColor: "rgba(220,220,220,0.2)",
<del> borderColor: "rgba(220,220,220,1)",
<del> pointBackgroundColor: "rgba(220,220,220,1)",
<add> backgroundColor: "rgba(179,181,198,0.2)",
<add> borderColor: "rgba(179,181,198,1)",
<add> pointBackgroundColor: "rgba(179,181,198,1)",
<ide> pointBorderColor: "#fff",
<ide> pointHoverBackgroundColor: "#fff",
<del> pointHoverBorderColor: "rgba(220,220,220,1)",
<add> pointHoverBorderColor: "rgba(179,181,198,1)",
<ide> data: [65, 59, 90, 81, 56, 55, 40]
<ide> },
<ide> {
<ide> label: "My Second dataset",
<del> backgroundColor: "rgba(151,187,205,0.2)",
<del> borderColor: "rgba(151,187,205,1)",
<del> pointBackgroundColor: "rgba(151,187,205,1)",
<add> backgroundColor: "rgba(255,99,132,0.2)",
<add> borderColor: "rgba(255,99,132,1)",
<add> pointBackgroundColor: "rgba(255,99,132,1)",
<ide> pointBorderColor: "#fff",
<ide> pointHoverBackgroundColor: "#fff",
<del> pointHoverBorderColor: "rgba(151,187,205,1)",
<add> pointHoverBorderColor: "rgba(255,99,132,1)",
<ide> data: [28, 48, 40, 19, 96, 27, 100]
<ide> }
<ide> ]
<ide><path>docs/05-Polar-Area-Chart.md
<ide> new Chart(ctx, {
<ide> var data = {
<ide> datasets: [{
<ide> data: [
<del> 10,
<del> 32,
<del> 53,
<del> 14,
<del> 22,
<add> 11,
<add> 16,
<add> 7,
<add> 3,
<add> 14
<ide> ],
<ide> backgroundColor: [
<del> "#F7464A",
<del> "#46BFBD",
<del> "#FDB45C",
<del> "#949FB1",
<del> "#4D5360",
<add> "#FF6384",
<add> "#4BC0C0",
<add> "#FFCE56",
<add> "#E7E9ED",
<add> "#36A2EB"
<ide> ],
<ide> label: 'My dataset' // for legend
<ide> }],
<ide> var data = {
<ide> "Green",
<ide> "Yellow",
<ide> "Grey",
<del> "Dark Grey"
<add> "Blue"
<ide> ]
<ide> };
<ide> ```
<ide><path>docs/06-Pie-Doughnut-Chart.md
<ide> var data = {
<ide> {
<ide> data: [300, 50, 100],
<ide> backgroundColor: [
<del> "#F7464A",
<del> "#46BFBD",
<del> "#FDB45C"
<add> "#FF6384",
<add> "#36A2EB",
<add> "#FFCE56"
<ide> ],
<ide> hoverBackgroundColor: [
<del> "#FF5A5E",
<del> "#5AD3D1",
<del> "#FFC870"
<add> "#FF6384",
<add> "#36A2EB",
<add> "#FFCE56"
<ide> ]
<ide> }]
<ide> }; | 5 |
Python | Python | remove unused import | b81b040110d18d6aa3633c1132420bf29be00c6b | <ide><path>examples/persona/persona.py
<del>from flask import Flask, render_template, session, request, json, abort, g
<add>from flask import Flask, render_template, session, request, abort, g
<ide>
<ide> import requests
<ide> | 1 |
Javascript | Javascript | use hooks in test cases | e58e1f9261fd26873573db10d066fa43d45ed956 | <ide><path>test/Compiler-caching.test.js
<ide> describe("Compiler (caching)", function() {
<ide> callback();
<ide> }
<ide> };
<del> c.plugin("compilation", (compilation) => compilation.bail = true);
<add> c.hooks.compilation.tap("CompilerCachingTest", (compilation) => compilation.bail = true);
<ide>
<ide> let compilerIteration = 1;
<ide>
<ide> describe("Compiler (caching)", function() {
<ide> });
<ide> }
<ide>
<del> const postCompileCallbackStack = [];
<del>
<del> function addAfterCompileCallback(callback) {
<del> postCompileCallbackStack.push(callback);
<del> }
<del>
<del> c.plugin("after-compile", (stats, callback) => {
<del>
<del> if(postCompileCallbackStack.length > 0) {
<del> postCompileCallbackStack.shift(arguments);
<del> }
<del>
<del> callback();
<del> });
<del>
<ide> runCompiler(callback);
<ide>
<ide> return {
<ide> compilerInstance: c,
<del> runAgain: runCompiler,
<del> addAfterCompileCallback: addAfterCompileCallback
<add> runAgain: runCompiler
<ide> };
<ide> }
<ide>
<ide><path>test/Compiler.test.js
<ide> describe("Compiler", () => {
<ide> callback();
<ide> }
<ide> };
<del> c.plugin("compilation", (compilation) => compilation.bail = true);
<add> c.hooks.compilation.tap("CompilerTest", (compilation) => compilation.bail = true);
<ide> c.run((err, stats) => {
<ide> if(err) throw err;
<ide> should.strictEqual(typeof stats, "object");
<ide> describe("Compiler", () => {
<ide> done();
<ide> });
<ide> });
<del> describe("constructor", () => {
<del> let compiler;
<del> beforeEach(() => {
<del> compiler = webpack({
<del> entry: "./c",
<del> context: path.join(__dirname, "fixtures"),
<del> output: {
<del> path: "/",
<del> pathinfo: true,
<del> }
<del> });
<del> });
<del> describe("parser", () => {
<del> describe("plugin", () => {
<del> it("invokes sets a 'compilation' plugin", (done) => {
<del> compiler.plugin = sinon.spy();
<del> compiler.parser.plugin();
<del> compiler.plugin.callCount.should.be.exactly(1);
<del> done();
<del> });
<del> });
<del> describe("apply", () => {
<del> it("invokes sets a 'compilation' plugin", (done) => {
<del> compiler.plugin = sinon.spy();
<del> compiler.parser.apply();
<del> compiler.plugin.callCount.should.be.exactly(1);
<del> done();
<del> });
<del> });
<del> });
<del> });
<ide> describe("methods", () => {
<ide> let compiler;
<ide> beforeEach(() => {
<ide><path>test/Integration.test.js
<ide> describe("Integration", function() {
<ide> }
<ide> }),
<ide> function() {
<del> this.plugin("normal-module-factory", (nmf) => {
<del> nmf.plugin("after-resolve", (data, callback) => {
<add> this.hooks.normalModuleFactory.tap("IntegrationTest", (nmf) => {
<add> nmf.hooks.afterResolve.tapAsync("IntegrationTest", (data, callback) => {
<ide> data.resource = data.resource.replace(/extra\.js/, "extra2.js");
<ide> setTimeout(() => callback(null, data), 50);
<ide> });
<ide><path>test/MultiCompiler.unittest.js
<ide> describe("MultiCompiler", () => {
<ide> describe("when called for first compiler", () => {
<ide> beforeEach(() => {
<ide> env.mockDonePlugin = sinon.spy();
<del> env.myMultiCompiler.plugin("done", env.mockDonePlugin);
<add> env.myMultiCompiler.hooks.done.tap("MultiCompilerTest", env.mockDonePlugin);
<ide> env.doneEventBinding1.handler({
<ide> hash: "foo"
<ide> });
<ide> describe("MultiCompiler", () => {
<ide> describe("when called", () => {
<ide> beforeEach(() => {
<ide> env.mockInvalidPlugin = sinon.spy();
<del> env.myMultiCompiler.plugin("invalid", env.mockInvalidPlugin);
<add> env.myMultiCompiler.hooks.invalid.tap("MultiCompilerTest", env.mockInvalidPlugin);
<ide> env.invalidEventBinding.handler();
<ide> });
<ide>
<ide><path>test/Parser.unittest.js
<ide> describe("Parser", () => {
<ide> const state = testCases[name][1];
<ide>
<ide> const testParser = new Parser({});
<del> testParser.plugin("can-rename abc", (expr) => true);
<del> testParser.plugin("can-rename ijk", (expr) => true);
<del> testParser.plugin("call abc", (expr) => {
<add> testParser.hooks.canRename.tap("abc", "ParserTest", (expr) => true);
<add> testParser.hooks.canRename.tap("ijk", "ParserTest", (expr) => true);
<add> testParser.hooks.call.tap("abc", "ParserTest", (expr) => {
<ide> if(!testParser.state.abc) testParser.state.abc = [];
<ide> testParser.state.abc.push(testParser.parseString(expr.arguments[0]));
<ide> return true;
<ide> });
<del> testParser.plugin("call cde.abc", (expr) => {
<add> testParser.hooks.call.tap("cde.abc", "ParserTest", (expr) => {
<ide> if(!testParser.state.cdeabc) testParser.state.cdeabc = [];
<ide> testParser.state.cdeabc.push(testParser.parseString(expr.arguments[0]));
<ide> return true;
<ide> });
<del> testParser.plugin("call cde.ddd.abc", (expr) => {
<add> testParser.hooks.call.tap("cde.ddd.abc", "ParserTest", (expr) => {
<ide> if(!testParser.state.cdedddabc) testParser.state.cdedddabc = [];
<ide> testParser.state.cdedddabc.push(testParser.parseString(expr.arguments[0]));
<ide> return true;
<ide> });
<del> testParser.plugin("expression fgh", (expr) => {
<add> testParser.hooks.expression.tap("fgh", "ParserTest", (expr) => {
<ide> if(!testParser.state.fgh) testParser.state.fgh = [];
<ide> testParser.state.fgh.push(Array.from(testParser.scope.definitions.asSet()).join(" "));
<ide> return true;
<ide> });
<del> testParser.plugin("expression fgh.sub", (expr) => {
<add> testParser.hooks.expression.tap("fgh.sub", "ParserTest", (expr) => {
<ide> if(!testParser.state.fghsub) testParser.state.fghsub = [];
<ide> testParser.state.fghsub.push(testParser.scope.inTry ? "try" : "notry");
<ide> return true;
<ide> });
<del> testParser.plugin("expression ijk.sub", (expr) => {
<add> testParser.hooks.expression.tap("ijk.sub", "ParserTest", (expr) => {
<ide> if(!testParser.state.ijksub) testParser.state.ijksub = [];
<ide> testParser.state.ijksub.push("test");
<ide> return true;
<ide> });
<del> testParser.plugin("expression memberExpr", (expr) => {
<add> testParser.hooks.expression.tap("memberExpr", "ParserTest", (expr) => {
<ide> if(!testParser.state.expressions) testParser.state.expressions = [];
<ide> testParser.state.expressions.push(expr.name);
<ide> return true;
<ide> });
<del> testParser.plugin("new xyz", (expr) => {
<add> testParser.hooks.new.tap("xyz", "ParserTest", (expr) => {
<ide> if(!testParser.state.xyz) testParser.state.xyz = [];
<ide> testParser.state.xyz.push(testParser.parseString(expr.arguments[0]));
<ide> return true;
<ide> describe("Parser", () => {
<ide>
<ide> const testParser = new Parser({});
<ide>
<del> testParser.plugin("program", (ast, comments) => {
<add> testParser.hooks.program.tap("ParserTest", (ast, comments) => {
<ide> if(!testParser.state.comments) testParser.state.comments = comments;
<ide> return true;
<ide> });
<ide> describe("Parser", () => {
<ide> describe("expression evaluation", () => {
<ide> function evaluateInParser(source) {
<ide> const parser = new Parser();
<del> parser.plugin("call test", (expr) => {
<add> parser.hooks.call.tap("test", "ParserTest", (expr) => {
<ide> parser.state.result = parser.evaluateExpression(expr.arguments[0]);
<ide> });
<del> parser.plugin("evaluate Identifier aString", (expr) =>
<add> parser.hooks.evaluateIdentifier.tap("aString", "ParserTest", (expr) =>
<ide> new BasicEvaluatedExpression().setString("aString").setRange(expr.range));
<del> parser.plugin("evaluate Identifier b.Number", (expr) =>
<add> parser.hooks.evaluateIdentifier.tap("b.Number", "ParserTest", (expr) =>
<ide> new BasicEvaluatedExpression().setNumber(123).setRange(expr.range));
<ide> return parser.parse("test(" + source + ");").result;
<ide> }
<ide> describe("Parser", () => {
<ide> };
<ide>
<ide> const parser = new Parser();
<del> parser.plugin("call require", (expr) => {
<add> parser.hooks.call.tap("require", "ParserTest", (expr) => {
<ide> const param = parser.evaluateExpression(expr.arguments[0]);
<ide> parser.state.param = param.string;
<ide> });
<del> parser.plugin("call System.import", (expr) => {
<add> parser.hooks.call.tap("System.import", "ParserTest", (expr) => {
<ide> const param = parser.evaluateExpression(expr.arguments[0]);
<ide> parser.state.param = param.string;
<ide> });
<ide><path>test/TestCases.test.js
<ide> describe("TestCases", () => {
<ide> }]
<ide> },
<ide> plugins: (config.plugins || []).concat(function() {
<del> this.plugin("compilation", (compilation) => {
<del> ["optimize", "optimize-modules-basic", "optimize-chunks-basic", "after-optimize-tree", "after-optimize-assets"].forEach((hook) => {
<del> compilation.plugin(hook, () => compilation.checkConstraints());
<add> this.hooks.compilation.tap("TestCasesTest", (compilation) => {
<add> ["optimize", "optimizeModulesBasic", "optimizeChunksBasic", "afterOptimizeTree", "afterOptimizeAssets"].forEach((hook) => {
<add> compilation.hooks[hook].tap("TestCasesTest", () => compilation.checkConstraints());
<ide> });
<ide> });
<ide> })
<ide><path>test/WatchDetection.test.js
<ide> describe("WatchDetection", () => {
<ide> });
<ide> const memfs = compiler.outputFileSystem = new MemoryFs();
<ide> let onChange;
<del> compiler.plugin("done", () => {
<add> compiler.hooks.done.tap("WatchDetectionTest", () => {
<ide> if(onChange)
<ide> onChange();
<ide> });
<ide><path>test/WatchTestCases.test.js
<ide> describe("WatchTestCases", () => {
<ide>
<ide> setTimeout(() => {
<ide> const compiler = webpack(options);
<del> compiler.plugin("invalid", (filename, mtime) => {
<add> compiler.hooks.invalid.tap("WatchTestCasesTest", (filename, mtime) => {
<ide> triggeringFilename = filename;
<ide> });
<ide> const watching = compiler.watch({
<ide><path>test/WatcherEvents.test.js
<ide> describe("WatcherEvents", function() {
<ide> done(err);
<ide> });
<ide>
<del> compiler.plugin("watch-close", () => {
<add> compiler.hooks.watchClose.tap("WatcherEventsTest", () => {
<ide> called = true;
<ide> });
<ide>
<del> compiler.plugin("done", () => {
<add> compiler.hooks.done.tap("WatcherEventsTest", () => {
<ide> watcher.close();
<ide> });
<ide>
<ide> describe("WatcherEvents", function() {
<ide> done(err);
<ide> });
<ide>
<del> compiler.plugin("watch-close", () => {
<add> compiler.hooks.watchClose.tap("WatcherEventsTest", () => {
<ide> called = true;
<ide> });
<ide>
<del> compiler.plugin("done", () => {
<add> compiler.hooks.done.tap("WatcherEventsTest", () => {
<ide> watcher.close();
<ide> });
<ide>
<ide><path>test/configCases/additional-pass/simple/webpack.config.js
<ide> var testPlugin = function() {
<ide> var counter = 1;
<del> this.plugin("compilation", function(compilation) {
<add> this.hooks.compilation.tap("TestPlugin", compilation => {
<ide> var nr = counter++;
<del> compilation.plugin("need-additional-pass", function() {
<add> compilation.hooks.needAdditionalPass.tap("TestPlugin", function() {
<ide> if(nr < 5)
<ide> return true;
<ide> });
<ide><path>test/configCases/issues/issue-3596/webpack.config.js
<ide> module.exports = {
<ide> },
<ide> plugins: [
<ide> function() {
<del> this.plugin("emit", function(compilation, callback) {
<add> this.hooks.emit.tap("TestPlugin", function(compilation) {
<ide> delete compilation.assets["b.js"];
<del> callback();
<ide> });
<ide> }
<ide> ]
<ide><path>test/statsCases/resolve-plugin-context/ResolvePackageFromRootPlugin.js
<ide> module.exports = class ResolvePackageFromRootPlugin {
<ide> }
<ide>
<ide> apply(resolver) {
<del> resolver.plugin("resolved", (originalResolved, callback) => {
<add> resolver.hooks.resolved.tapAsync("ResolvePackageFromRootPlugin", (originalResolved, _, callback) => {
<ide>
<ide> if (!nestedNodeModuleRegex.test(originalResolved.path) || !originalResolved.context || !originalResolved.context.issuer) {
<ide> return callback(null, originalResolved) | 12 |
Python | Python | add border_mode = same to convolution1d | b057624707be574d78a741516be2f98c03f3e193 | <ide><path>keras/layers/convolutional.py
<ide> def __init__(self, input_dim, nb_filter, filter_length,
<ide> W_regularizer=None, b_regularizer=None, activity_regularizer=None,
<ide> W_constraint=None, b_constraint=None):
<ide>
<del> if border_mode not in {'valid', 'full'}:
<add> if border_mode not in {'valid', 'full', 'same'}:
<ide> raise Exception('Invalid border mode for Convolution1D:', border_mode)
<ide>
<ide> super(Convolution1D, self).__init__()
<ide> def __init__(self, input_dim, nb_filter, filter_length,
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> X = T.reshape(X, (X.shape[0], X.shape[1], X.shape[2], 1)).dimshuffle(0, 2, 1, 3)
<del> conv_out = T.nnet.conv.conv2d(X, self.W, border_mode=self.border_mode, subsample=self.subsample)
<add>
<add> border_mode = self.border_mode
<add> if border_mode == 'same':
<add> border_mode = 'full'
<add>
<add> conv_out = T.nnet.conv.conv2d(X, self.W, border_mode=border_mode, subsample=self.subsample)
<add> if self.border_mode == 'same':
<add> shift_x = (self.filter_length - 1) // 2
<add> conv_out = conv_out[:, :, shift_x:X.shape[2] + shift_x, :]
<add>
<ide> output = self.activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x'))
<del> return T.reshape(output, (output.shape[0], output.shape[1], output.shape[2])).dimshuffle(0, 2, 1)
<add> output = T.reshape(output, (output.shape[0], output.shape[1], output.shape[2])).dimshuffle(0, 2, 1)
<add> return output
<ide>
<ide> def get_config(self):
<ide> return {"name": self.__class__.__name__,
<ide> def get_output(self, train):
<ide> border_mode = 'full'
<ide>
<ide> conv_out = T.nnet.conv.conv2d(X, self.W,
<del> border_mode=border_mode, subsample=self.subsample)
<del>
<add> border_mode=border_mode,
<add> subsample=self.subsample)
<ide> if self.border_mode == 'same':
<ide> shift_x = (self.nb_row - 1) // 2
<ide> shift_y = (self.nb_col - 1) // 2 | 1 |
Text | Text | improve checkserveridentity docs | da429c3d20ee31873eb9d76b8142f68fb3514408 | <ide><path>doc/api/tls.md
<ide> changes:
<ide> * `servername`: {string} Server name for the SNI (Server Name Indication) TLS
<ide> extension.
<ide> * `checkServerIdentity(servername, cert)` {Function} A callback function
<del> to be used when checking the server's hostname against the certificate.
<del> This should throw an error if verification fails. The method should return
<add> to be used (instead of the builtin `tls.checkServerIdentity()` function)
<add> when checking the server's hostname against the certificate.
<add> This should return an {Error} if verification fails. The method should return
<ide> `undefined` if the `servername` and `cert` are verified.
<ide> * `session` {Buffer} A `Buffer` instance, containing TLS session.
<ide> * `minDHSize` {number} Minimum size of the DH parameter in bits to accept a | 1 |
Javascript | Javascript | use module.exports consistently | 25d29da10adfa00cb10e7ff89535749453add775 | <ide><path>test/common/shared-lib-util.js
<ide> const common = require('../common');
<ide> const path = require('path');
<ide>
<add>const kNodeShared = Boolean(process.config.variables.node_shared);
<add>const kShlibSuffix = process.config.variables.shlib_suffix;
<add>const kExecPath = path.dirname(process.execPath);
<add>
<ide> // If node executable is linked to shared lib, need to take care about the
<ide> // shared lib path.
<del>exports.addLibraryPath = function(env) {
<del> if (!process.config.variables.node_shared) {
<add>function addLibraryPath(env) {
<add> if (!kNodeShared) {
<ide> return;
<ide> }
<ide>
<ide> env = env || process.env;
<ide>
<ide> env.LD_LIBRARY_PATH =
<ide> (env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') +
<del> path.join(path.dirname(process.execPath), 'lib.target');
<add> path.join(kExecPath, 'lib.target');
<ide> // For AIX.
<ide> env.LIBPATH =
<ide> (env.LIBPATH ? env.LIBPATH + path.delimiter : '') +
<del> path.join(path.dirname(process.execPath), 'lib.target');
<add> path.join(kExecPath, 'lib.target');
<ide> // For Mac OSX.
<ide> env.DYLD_LIBRARY_PATH =
<ide> (env.DYLD_LIBRARY_PATH ? env.DYLD_LIBRARY_PATH + path.delimiter : '') +
<del> path.dirname(process.execPath);
<add> kExecPath;
<ide> // For Windows.
<del> env.PATH =
<del> (env.PATH ? env.PATH + path.delimiter : '') +
<del> path.dirname(process.execPath);
<del>};
<add> env.PATH = (env.PATH ? env.PATH + path.delimiter : '') + kExecPath;
<add>}
<ide>
<ide> // Get the full path of shared lib.
<del>exports.getSharedLibPath = function() {
<add>function getSharedLibPath() {
<ide> if (common.isWindows) {
<del> return path.join(path.dirname(process.execPath), 'node.dll');
<add> return path.join(kExecPath, 'node.dll');
<ide> } else if (common.isOSX) {
<del> return path.join(path.dirname(process.execPath),
<del> `libnode.${process.config.variables.shlib_suffix}`);
<add> return path.join(kExecPath, `libnode.${kShlibSuffix}`);
<ide> } else {
<del> return path.join(path.dirname(process.execPath),
<del> 'lib.target',
<del> `libnode.${process.config.variables.shlib_suffix}`);
<add> return path.join(kExecPath, 'lib.target', `libnode.${kShlibSuffix}`);
<ide> }
<del>};
<add>}
<ide>
<ide> // Get the binary path of stack frames.
<del>exports.getBinaryPath = function() {
<del> return process.config.variables.node_shared ?
<del> exports.getSharedLibPath() : process.execPath;
<add>function getBinaryPath() {
<add> return kNodeShared ? getSharedLibPath() : process.execPath;
<add>}
<add>
<add>module.exports = {
<add> addLibraryPath,
<add> getBinaryPath,
<add> getSharedLibPath
<ide> };
<ide><path>test/common/tmpdir.js
<ide> let tmpdirName = '.tmp';
<ide> if (process.env.TEST_THREAD_ID) {
<ide> tmpdirName += `.${process.env.TEST_THREAD_ID}`;
<ide> }
<del>exports.path = path.join(testRoot, tmpdirName);
<ide>
<del>exports.refresh = () => {
<del> rimrafSync(exports.path);
<del> fs.mkdirSync(exports.path);
<add>const tmpPath = path.join(testRoot, tmpdirName);
<add>
<add>function refresh() {
<add> rimrafSync(this.path);
<add> fs.mkdirSync(this.path);
<add>}
<add>
<add>module.exports = {
<add> path: tmpPath,
<add> refresh
<ide> }; | 2 |
Python | Python | add library of matrix functions | 5ee14815b3520074e73b2b2836a8a11de0cc9fc2 | <ide><path>numpy/core/defmatrix.py
<ide>
<del>__all__ = ['matrix', 'bmat', 'mat', 'asmatrix', 'asmat']
<add>__all__ = ['matrix', 'bmat', 'mat', 'asmatrix']
<ide>
<ide> import numeric as N
<ide> from numeric import concatenate, isscalar, binary_repr
<ide> def bmat(obj, ldict=None, gdict=None):
<ide> if isinstance(obj, N.ndarray):
<ide> return matrix(obj)
<ide>
<del>mat = matrix
<del>asmat = asmatrix
<add>mat = asmatrix
<ide><path>numpy/matlib.py
<add>__all__ = ['ones','zeros','empty','identity','rand','randn','eye']
<add>
<add>from numpy.core.defmatrix import matrix, asmatrix
<add>from numpy import ndarray, array
<add>import numpy as N
<add>
<add>def empty(shape, dtype=None, order='C'):
<add> """return an empty matrix of the given shape
<add> """
<add> return ndarray.__new__(matrix, shape, dtype, order=order)
<add>
<add>def ones(shape, dtype=None, order='C'):
<add> """return a matrix initialized to all ones
<add> """
<add> a = ndarray.__new__(matrix, shape, dtype, order=order)
<add> a.fill(1)
<add> return a
<add>
<add>def zeros(shape, dtype=None, order='C'):
<add> """return a matrix initialized to all zeros
<add> """
<add> a = ndarray.__new__(matrix, shape, dtype, order=order)
<add> a.fill(0)
<add> return a
<add>
<add>def identity(n,dtype=None):
<add> """identity(n) returns the identity matrix of shape n x n.
<add> """
<add> a = array([1]+n*[0],dtype=dtype)
<add> b = empty((n,n),dtype=dtype)
<add> b.flat = a
<add> return b
<add>
<add>def eye(N,M=None, k=0, dtype=float):
<add> return asmatrix(N.eye(N,M,k,dtype))
<add>
<add>def rand(*args):
<add> return asmatrix(N.rand(*args))
<add>
<add>def randn(*args):
<add> return asmatrix(N.rand(*args)) | 2 |
Text | Text | add security.md file, linking to security policy | b37a2d53e161f4b139b7d98d31ee83ee98647648 | <ide><path>.github/security.md
<add># Security Policy
<add>
<add>## Reporting a Vulnerability
<add>
<add>**Do not open up a GitHub issue if the bug is a security vulnerability in Rails**.
<add>Instead refer to our [security policy](https://rubyonrails.org/security/).
<add>
<add>## Supported Versions
<add>
<add>Security backports are provided for some previous release series. For details
<add>of which release series are currently receiving security backports see our
<add>[security policy](https://rubyonrails.org/security/). | 1 |
Text | Text | add free cdn for version 5.4 | 3a6ec39739df31f6f07b158e871244d4ee48f3cb | <ide><path>guide/english/bootstrap/fontawesome-icons/index.md
<ide> Complete list of icons provided by Font Awesome is available [here](http://fonta
<ide> _Note: Do not include the dot in the HTML Class Attribute, referring to the classes with a dot is only used when adjusting the classes in CSS._
<ide>
<ide>
<add>#### Font Awesome Free CDN for Version 5
<add>
<add>Font Awesome Version 5 extends the free icons to 1480.
<add>
<add>*Use this free CDN for version 5 (currently v5.6.3)*
<add>
<add>```html
<add><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<add>```
<add>
<add>List of v5 free icons is available [here](https://fontawesome.com/icons?d=gallery&m=free)
<add>
<add>
<ide> #### More Information:
<ide> [Font Awesome Cheatsheet](http://fontawesome.io/cheatsheet/)
<ide> | 1 |
Ruby | Ruby | allow empty arrays in where predicates | f2135aceeb679a14f017cd677eeaf67b84a76582 | <ide><path>activerecord/lib/active_record/relation/predicate_builder/array_handler.rb
<ide> module ActiveRecord
<ide> class PredicateBuilder
<ide> class ArrayHandler # :nodoc:
<ide> def call(attribute, value)
<add> return attribute.in([]) if value.empty?
<add>
<ide> values = value.map { |x| x.is_a?(Base) ? x.id : x }
<ide> ranges, values = values.partition { |v| v.is_a?(Range) }
<ide> nils, values = values.partition(&:nil?) | 1 |
Ruby | Ruby | remove unused methods in connection handling | 1bbaf0d581e5b48653af9b614da7d30e64d48fa8 | <ide><path>activerecord/lib/active_record/connection_handling.rb
<ide> def establish_connection(config_or_env = nil)
<ide> # Connects a model to the databases specified. The +database+ keyword
<ide> # takes a hash consisting of a +role+ and a +database_key+.
<ide> #
<del> # This will create a connection handler for switching between connections,
<del> # look up the config hash using the +database_key+ and finally
<del> # establishes a connection to that config.
<add> # This will look up the database config using the +database_key+ and
<add> # establish a connection to that config.
<ide> #
<ide> # class AnimalsModel < ApplicationRecord
<ide> # self.abstract_class = true
<ide> def establish_connection(config_or_env = nil)
<ide> # end
<ide> #
<ide> # +connects_to+ also supports horizontal sharding. The horizontal sharding API
<del> # also supports read replicas. Connect a model to a list of shards like this:
<add> # supports read replicas as well. You can connect a model to a list of shards like this:
<ide> #
<ide> # class AnimalsModel < ApplicationRecord
<ide> # self.abstract_class = true
<ide> def connects_to(database: {}, shards: {})
<ide>
<ide> database.each do |role, database_key|
<ide> db_config, owner_name = resolve_config_for_connection(database_key)
<del> handler = lookup_connection_handler(role.to_sym)
<ide>
<ide> self.connection_class = true
<del> connections << handler.establish_connection(db_config, owner_name: owner_name, role: role)
<add> connections << connection_handler.establish_connection(db_config, owner_name: owner_name, role: role)
<ide> end
<ide>
<ide> shards.each do |shard, database_keys|
<ide> database_keys.each do |role, database_key|
<ide> db_config, owner_name = resolve_config_for_connection(database_key)
<del> handler = lookup_connection_handler(role.to_sym)
<ide>
<ide> self.connection_class = true
<del> connections << handler.establish_connection(db_config, owner_name: owner_name, role: role, shard: shard.to_sym)
<add> connections << connection_handler.establish_connection(db_config, owner_name: owner_name, role: role, shard: shard.to_sym)
<ide> end
<ide> end
<ide>
<ide> def while_preventing_writes(enabled = true, &block)
<ide> connected_to(role: current_role, prevent_writes: enabled, &block)
<ide> end
<ide>
<del> # Returns true if role is the current connected role.
<add> # Returns true if role and/or is the current connected role and/or
<add> # current connected shard. If no shard is passed the default will be
<add> # used.
<ide> #
<ide> # ActiveRecord::Base.connected_to(role: :writing) do
<ide> # ActiveRecord::Base.connected_to?(role: :writing) #=> true
<ide> # ActiveRecord::Base.connected_to?(role: :reading) #=> false
<ide> # end
<add> #
<add> # ActiveRecord::Base.connected_to(role: :reading, shard: :shard_one) do
<add> # ActiveRecord::Base.connected_to?(role: :reading, shard: :shard_one) #=> true
<add> # ActiveRecord::Base.connected_to?(role: :reading, shard: :default) #=> false
<add> # ActiveRecord::Base.connected_to?(role: :writing, shard: :shard_one) #=> true
<add> # end
<ide> def connected_to?(role:, shard: ActiveRecord::Base.default_shard)
<ide> current_role == role.to_sym && current_shard == shard.to_sym
<ide> end
<ide>
<del> def lookup_connection_handler(handler_key) # :nodoc:
<del> ActiveRecord::Base.connection_handler
<del> end
<del>
<ide> # Clears the query cache for all connections associated with the current thread.
<ide> def clear_query_caches_for_current_thread
<del> ActiveRecord::Base.connection_handler.all_connection_pools.each do |pool|
<add> connection_handler.all_connection_pools.each do |pool|
<ide> pool.connection.clear_query_cache if pool.active_connection?
<ide> end
<ide> end
<ide> def resolve_config_for_connection(config_or_env)
<ide> [db_config, self]
<ide> end
<ide>
<del> def with_handler(handler_key, &blk)
<del> handler = lookup_connection_handler(handler_key)
<del> swap_connection_handler(handler, &blk)
<del> end
<del>
<ide> def with_role_and_shard(role, shard, prevent_writes)
<ide> prevent_writes = true if role == ActiveRecord.reading_role
<ide>
<ide> def append_to_connected_to_stack(entry)
<ide>
<ide> connected_to_stack << entry
<ide> end
<del>
<del> def swap_connection_handler(handler, &blk) # :nodoc:
<del> old_handler, ActiveRecord::Base.connection_handler = ActiveRecord::Base.connection_handler, handler
<del> return_value = yield
<del> return_value.load if return_value.is_a? ActiveRecord::Relation
<del> return_value
<del> ensure
<del> ActiveRecord::Base.connection_handler = old_handler
<del> end
<ide> end
<ide> end | 1 |
PHP | PHP | consolidate path display | 0cd21effd087eca7abd6b0d2339e634a24d8e32e | <ide><path>src/Command/HelpCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io)
<ide> {
<ide> if (!$args->getOption('xml')) {
<ide> $io->out('<info>Current Paths:</info>', 2);
<del> $io->out('* app: ' . APP_DIR);
<del> $io->out('* root: ' . rtrim(ROOT, DIRECTORY_SEPARATOR));
<del> $io->out('* core: ' . rtrim(CORE_PATH, DIRECTORY_SEPARATOR));
<add> $io->out('* app: ' . APP_DIR . DIRECTORY_SEPARATOR);
<add> $io->out('* root: ' . ROOT . DIRECTORY_SEPARATOR);
<add> $io->out('* core: ' . CORE_PATH);
<ide> $io->out('');
<ide>
<ide> $io->out('<info>Available Commands:</info>', 2);
<ide><path>src/Shell/CommandListShell.php
<ide> public function main()
<ide> {
<ide> if (!$this->param('xml') && !$this->param('version')) {
<ide> $this->out('<info>Current Paths:</info>', 2);
<del> $this->out('* app: ' . APP_DIR);
<del> $this->out('* root: ' . rtrim(ROOT, DIRECTORY_SEPARATOR));
<del> $this->out('* core: ' . rtrim(CORE_PATH, DIRECTORY_SEPARATOR));
<add> $this->out('* app: ' . APP_DIR . DIRECTORY_SEPARATOR);
<add> $this->out('* root: ' . ROOT . DIRECTORY_SEPARATOR);
<add> $this->out('* core: ' . CORE_PATH);
<ide> $this->out('');
<ide>
<ide> $this->out('<info>Available Shells:</info>', 2); | 2 |
PHP | PHP | add resource helper | 2c31fd5954699613cba04eacedd2a942e28b8abf | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function get($uri, $action)
<ide> }
<ide> }
<ide>
<add>if ( ! function_exists('resource'))
<add>{
<add> /**
<add> * Route a resource to a controller.
<add> *
<add> * @param string $name
<add> * @param string $controller
<add> * @param array $options
<add> * @return void
<add> */
<add> function resource($name, $controller, array $options = [])
<add> {
<add> return app('router')->resource($name, $controller, $options);
<add> }
<add>}
<add>
<ide> if ( ! function_exists('info'))
<ide> {
<ide> /** | 1 |
Text | Text | fix small typo in rails guides [ci skip] | 804b4092e8f88ced525394a39849168d0285f7d4 | <ide><path>guides/source/active_record_querying.md
<ide> After reading this guide, you will know:
<ide> * How to specify the order, retrieved attributes, grouping, and other properties of the found records.
<ide> * How to use eager loading to reduce the number of database queries needed for data retrieval.
<ide> * How to use dynamic finder methods.
<del>* How to use method chaining to use multiple ActiveRecord methods together.
<add>* How to use method chaining to use multiple Active Record methods together.
<ide> * How to check for the existence of particular records.
<ide> * How to perform various calculations on Active Record models.
<ide> * How to run EXPLAIN on relations.
<ide><path>guides/source/active_record_validations.md
<ide> false` as an argument. This technique should be used with caution.
<ide>
<ide> ### `valid?` and `invalid?`
<ide>
<del>Before saving an ActiveRecord object, Rails runs your validations.
<add>Before saving an Active Record object, Rails runs your validations.
<ide> If these validations produce any errors, Rails does not save the object.
<ide>
<ide> You can also run these validations on your own. `valid?` triggers your validations
<ide><path>guides/source/i18n.md
<ide> After reading this guide, you will know:
<ide>
<ide> * How I18n works in Ruby on Rails
<ide> * How to correctly use I18n into a RESTful application in various ways
<del>* How to use I18n to translate ActiveRecord errors or ActionMailer E-mail subjects
<add>* How to use I18n to translate Active Record errors or Action Mailer E-mail subjects
<ide> * Some other tools to go further with the translation process of your application
<ide>
<ide> -------------------------------------------------------------------------------- | 3 |
Text | Text | fix typo in tls.md | 95c8503d8866187a003aba01187877ad8ebd38df | <ide><path>doc/api/tls.md
<ide> changes:
<ide>
<ide> * `socket` {net.Socket} An instance of [`net.Socket`][]
<ide> * `options` {Object}
<del> * `isServer`: The SSL/TLS protocol is asymetrical, TLSSockets must know if
<add> * `isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if
<ide> they are to behave as a server or a client. If `true` the TLS socket will be
<ide> instantiated as a server. Defaults to `false`.
<ide> * `server` {net.Server} An optional [`net.Server`][] instance. | 1 |
Go | Go | remove increment flag on imagecontexts.new() | aafd7fa96909f48e43fd1b785c3c3a1f8b656ede | <ide><path>builder/dockerfile/dispatchers.go
<ide> func from(b *Builder, args []string, attributes map[string]bool, original string
<ide> return err
<ide> }
<ide> b.resetImageCache()
<del> if _, err := b.imageContexts.new(ctxName, true); err != nil {
<add> if _, err := b.imageContexts.add(ctxName); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func mountByRef(b *Builder, name string) (*imageMount, error) {
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> im, err := b.imageContexts.new("", false)
<del> if err != nil {
<del> return nil, err
<del> }
<del> im.id = image.ImageID()
<add> im := b.imageContexts.newImageMount(image.ImageID())
<ide> return im, nil
<ide> }
<ide>
<ide><path>builder/dockerfile/imagecontext.go
<ide> type imageContexts struct {
<ide> currentName string
<ide> }
<ide>
<del>func (ic *imageContexts) new(name string, increment bool) (*imageMount, error) {
<add>func (ic *imageContexts) newImageMount(id string) *imageMount {
<add> return &imageMount{ic: ic, id: id}
<add>}
<add>
<add>func (ic *imageContexts) add(name string) (*imageMount, error) {
<ide> im := &imageMount{ic: ic}
<ide> if len(name) > 0 {
<ide> if ic.byName == nil {
<ide> func (ic *imageContexts) new(name string, increment bool) (*imageMount, error) {
<ide> }
<ide> ic.byName[name] = im
<ide> }
<del> if increment {
<del> ic.list = append(ic.list, im)
<del> }
<ide> ic.currentName = name
<add> ic.list = append(ic.list, im)
<ide> return im, nil
<ide> }
<ide> | 2 |
Ruby | Ruby | exclude repository from brew list --unbrewed | 5a140c0f45c96056e7a2de99f58029ea6ad38e27 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list_unbrewed
<ide> cache_folder = (HOMEBREW_CACHE.relative_path_from(HOMEBREW_PREFIX)).to_s
<ide> dirs -= [cache_folder]
<ide>
<add> # Exclude the repository, if it has been located under the prefix
<add> cache_folder = (HOMEBREW_REPOSITORY.relative_path_from(HOMEBREW_PREFIX)).to_s
<add> dirs -= [cache_folder]
<add>
<ide> cd HOMEBREW_PREFIX
<ide> exec 'find', *dirs + %w[-type f ( ! -iname .ds_store ! -iname brew ! -iname brew-man.1 ! -iname brew.1 )]
<ide> end | 1 |
Javascript | Javascript | use streams-lib as polyfill | 01b47d9012b15c857f423dcbf2f7238f341c1985 | <ide><path>gulpfile.js
<ide> gulp.task('lib', ['buildnumber'], function () {
<ide> var buildLib = merge([
<ide> gulp.src([
<ide> 'src/{core,display}/*.js',
<del> 'src/shared/{compatibility,util}.js',
<add> 'src/shared/{compatibility,util,streams_polyfill}.js',
<ide> 'src/{pdf,pdf.worker}.js',
<ide> ], { base: 'src/', }),
<ide> gulp.src([
<ide><path>src/shared/streams_polyfill.js
<add>/* Copyright 2017 Mozilla Foundation
<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>if (typeof ReadableStream !== 'undefined') {
<add> exports.ReadableStream = ReadableStream;
<add>} else {
<add> if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('CHROME')) {
<add> throw new Error('ReadableStream polyfill is not found for Chrome bundle');
<add> }
<add> exports.ReadableStream =
<add> require('../../external/streams/streams-lib').ReadableStream;
<add>}
<ide><path>src/shared/util.js
<ide> */
<ide>
<ide> import './compatibility';
<del>import { ReadableStream } from '../../external/streams/streams-lib';
<add>import { ReadableStream } from './streams_polyfill';
<ide>
<ide> var globalScope =
<ide> (typeof window !== 'undefined' && window.Math === Math) ? window : | 3 |
Javascript | Javascript | remove unnecessary line | 3ce4adf3c6bd73fcd8de93a5bbaf8bdb321d43af | <ide><path>test/common.js
<ide> exports.ddCommand = function(filename, kilobytes) {
<ide> if (process.platform == 'win32') {
<ide> return 'fsutil.exe file createnew "' + filename + '" ' + (kilobytes * 1024);
<ide> } else {
<del> var blocks = Integer(size / 1024);
<ide> return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes;
<ide> }
<ide> }; | 1 |
PHP | PHP | fix typo in property name | 1e603954048b8a7241961488528bf5b8c01d4eb2 | <ide><path>src/View/Helper/FormHelper.php
<ide> class FormHelper extends Helper {
<ide> *
<ide> * @var array
<ide> */
<del> protected $_defaultWigets = [
<add> protected $_defaultWidgets = [
<ide> 'button' => ['Cake\View\Widget\ButtonWidget'],
<ide> 'checkbox' => ['Cake\View\Widget\CheckboxWidget'],
<ide> 'file' => ['Cake\View\Widget\FileWidget'],
<ide> class FormHelper extends Helper {
<ide> */
<ide> public function __construct(View $View, array $config = []) {
<ide> $registry = null;
<del> $widgets = $this->_defaultWigets;
<add> $widgets = $this->_defaultWidgets;
<ide> if (isset($config['registry'])) {
<ide> $registry = $config['registry'];
<ide> unset($config['registry']); | 1 |
Python | Python | move parser tests to correct directory | 959e23426088661e12f5c8c3fafc64da42d1fc24 | <ide><path>tests/test_parsers.py
<del>#-*- coding: utf-8 -*-
<add># -*- coding: utf-8 -*-
<ide>
<ide> from __future__ import unicode_literals
<ide> from rest_framework.compat import StringIO
<ide> def test_get_encoded_filename(self):
<ide>
<ide> def __replace_content_disposition(self, disposition):
<ide> self.parser_context['request'].META['HTTP_CONTENT_DISPOSITION'] = disposition
<del>
<del> | 1 |
Text | Text | add fastutil lists for lists of primitives | 080c0ae12b1e6e396a96ed4845dd005ce7906ce6 | <ide><path>guide/english/java/arraylist/index.md
<ide> Always import the most specific package in order to save memory size and perform
<ide>
<ide> `ArrayList` is a class that is used to create dynamic arrays. It is slower than regular arrays but allows for a lot of manipulation. It should be initialized to have a specific size or it will have the default size of 10 units.
<ide>
<del>
<del> ```java
<del> ArrayList<String> names = new ArrayList<>();
<del> ArrayList<Integer> ages = new ArrayList<>(5);
<del> ```
<add>
<add>```java
<add>ArrayList<String> names = new ArrayList<>();
<add>ArrayList<Integer> ages = new ArrayList<>(5);
<add>```
<ide>
<ide> In the above snippet, the angle brackets `<>` take a generic data type as argument specifying data type of the elements in the ArrayList. The first ArrayList `names` is specified as containing *String* elements. Thus, it will only be allowed to contain String elements. Its size is not specified so it will have a default size of 10. The second ArrayList `ages` has specified that it will only hold integers. But ArrayList cannot hold primitives, it only holds objects. Thus to make it store integers, floats, etc., we can use wrapper classes. `names` will have a specified size of 5.
<ide>
<ide> Since ArrayList implements *List*, an ArrayList can be created using the following syntax:
<del> ```java
<del> List<Integer> students = new ArrayList<>();
<del> ```
<add>```java
<add>List<Integer> students = new ArrayList<>();
<add>```
<ide>
<del> An ArrayList is dynamic, meaning it will grow in size if required and similarly shrink in size if elements are deleted from it. This is what makes it more flexible than normal arrays.
<add>An ArrayList is dynamic, meaning it will grow in size if required and similarly shrink in size if elements are deleted from it. This is what makes it more flexible than normal arrays.
<ide>
<ide> **Add elements to the list**
<del> ```java
<del> variable.add(String e);
<del> variable.add(int index, String element);
<del> ```
<add>```java
<add>variable.add(String e);
<add>variable.add(int index, String element);
<add>```
<ide>
<ide> **Clear/Delete all elements from the list**
<del> ```java
<del> variable.clear();
<del> ```
<add>```java
<add>variable.clear();
<add>```
<ide>
<ide> **Delete element at specified index from the list**
<del> ```java
<del> variable_name.remove(index_number);
<del> ```
<add>```java
<add>variable_name.remove(index_number);
<add>```
<ide>
<ide> **Access element at specified index**
<del> ```java
<del> variable_name.get(index_number);
<del> ```
<add>```java
<add>variable_name.get(index_number);
<add>```
<ide>
<ide> **Modify/update element at specified index**
<ide>
<del> ```java
<del> variable_name.set(index_number,element);
<del> ```
<add>```java
<add>variable_name.set(index_number,element);
<add>```
<ide>
<ide> **Get the size of the list**
<ide>
<del> ```java
<del> variable_name.size();
<del> ```
<add>```java
<add>variable_name.size();
<add>```
<ide>
<ide> **Get a sublist of the list**
<ide>
<del> ```java
<del> variable_name.subList(int fromIndex, int toIndex);
<del> ```
<add>```java
<add>variable_name.subList(int fromIndex, int toIndex);
<add>```
<ide>
<ide> **Reverse elements in list**
<ide>
<del> ```java
<del> import java.util.Collections; // package
<del> Collections.reverse(variable_name);
<del> ```
<add>```java
<add>import java.util.Collections; // package
<add>Collections.reverse(variable_name);
<add>```
<ide>
<ide> **Sort elements in ascending order**
<del> ```java
<del> Collections.sort(variable_name);
<del> ```
<add>```java
<add>Collections.sort(variable_name);
<add>```
<ide>
<ide> **Sort elements in descending order**
<ide>
<del> ```java
<add>```java
<ide> Collections.sort(variable_name, Collections.reverseOrder());
<del> ```
<add>```
<ide>
<ide> **Creating Array from ArrayList**
<ide>
<del> ```java
<del> Object[] arr = variable_name.toArray(new Object[variable_name.size()]);
<del> ```
<add>```java
<add>Object[] arr = variable_name.toArray(new Object[variable_name.size()]);
<add>```
<ide>
<ide> **Creating ArrayList from Array**
<ide>
<ide> for(Object obj : arr) {
<ide> variable_name.add(obj);
<ide> }
<ide> ```
<del>
<add>
<ide> An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways, but it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not.
<del>
<add>
<ide> So when it comes down to choosing between the two - if speed is critical then Vectors should be considered for a small set of items, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently. Vectors are synchronized and arraylist are not, thats why choose vector for frequent update of elements otherwise Arraylist is efficient for traversing.
<ide>
<ide> ## Basic Big O for ArrayList Methods:
<ide> So when it comes down to choosing between the two - if speed is critical then Ve
<ide> `.remove(int ind)`
<ide> - O(n). For the same reason as above. The elements must be shifted after removal.
<ide>
<del> It is important to understand the Big O for methods of data structures. This way, you can choose the most efficient data structure for your program.
<add>It is important to understand the Big O for methods of data structures. This way, you can choose the most efficient data structure for your program.
<add>
<add>## ArrayLists and primitives
<add>As mentioned before, ArrayLists cannot hold primitive types, and one has to use their corresponding wrapper classes.
<add>However it comes with a cost: every time you put a primitive value in the list, or every time you get a wrapped value from the list and put it into a primitive variable, the value is automatically converted from the wrapper objet to the primitive value or the other way around. This is called boxing and unboxing. To avoid these additionnal (useless) conversions, there is the FastUtil library. They have specialkinds of lists that use directly the primitive types.
<add>Here are a few examples:
<add>- IntList (and its implementation IntArrayList)
<add>- BooleanList (and its implementation BooleanArrayList)
<add>- DoubleList (and its implementation DoubleArrayList)
<add>- and so on with all 8 primitive java types
<add>
<add>Of course they implement the java.util List interface, so they can be used exactly like usual ArrayLists.
<ide>
<del>#### More Information
<add>## More Information
<ide> - [ArrayList Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html) | 1 |
Go | Go | add variant to image.image and legacy builder | c21a3cf432bd89f9ceb5724b8a90f30f789433a5 | <ide><path>api/types/types.go
<ide> type ImageInspect struct {
<ide> Author string
<ide> Config *container.Config
<ide> Architecture string
<add> Variant string `json:",omitempty"`
<ide> Os string
<ide> OsVersion string `json:",omitempty"`
<ide> Size int64
<ide><path>builder/dockerfile/imagecontext.go
<ide> import (
<ide> "context"
<ide> "runtime"
<ide>
<add> "github.com/containerd/containerd/platforms"
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/builder"
<ide> dockerimage "github.com/docker/docker/image"
<ide> func (m *imageSources) Get(idOrRef string, localOnly bool, platform *specs.Platf
<ide> return nil, err
<ide> }
<ide> im := newImageMount(image, layer)
<del> m.Add(im)
<add> m.Add(im, platform)
<ide> return im, nil
<ide> }
<ide>
<ide> func (m *imageSources) Unmount() (retErr error) {
<ide> return
<ide> }
<ide>
<del>func (m *imageSources) Add(im *imageMount) {
<add>func (m *imageSources) Add(im *imageMount, platform *specs.Platform) {
<ide> switch im.image {
<ide> case nil:
<del> // set the OS for scratch images
<del> os := runtime.GOOS
<add> // Set the platform for scratch images
<add> if platform == nil {
<add> p := platforms.DefaultSpec()
<add> platform = &p
<add> }
<add>
<ide> // Windows does not support scratch except for LCOW
<add> os := platform.OS
<ide> if runtime.GOOS == "windows" {
<ide> os = "linux"
<ide> }
<del> im.image = &dockerimage.Image{V1Image: dockerimage.V1Image{OS: os}}
<add>
<add> im.image = &dockerimage.Image{V1Image: dockerimage.V1Image{
<add> OS: os,
<add> Architecture: platform.Architecture,
<add> Variant: platform.Variant,
<add> }}
<ide> default:
<ide> m.byImageID[im.image.ImageID()] = im
<ide> }
<ide><path>builder/dockerfile/imagecontext_test.go
<add>package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<add>
<add>import (
<add> "fmt"
<add> "runtime"
<add> "testing"
<add>
<add> "github.com/containerd/containerd/platforms"
<add> "github.com/docker/docker/builder"
<add> "github.com/docker/docker/image"
<add> ocispec "github.com/opencontainers/image-spec/specs-go/v1"
<add> "gotest.tools/assert"
<add>)
<add>
<add>func getMockImageSource(getImageImage builder.Image, getImageLayer builder.ROLayer, getImageError error) *imageSources {
<add> return &imageSources{
<add> byImageID: make(map[string]*imageMount),
<add> mounts: []*imageMount{},
<add> getImage: func(name string, localOnly bool, platform *ocispec.Platform) (builder.Image, builder.ROLayer, error) {
<add> return getImageImage, getImageLayer, getImageError
<add> },
<add> }
<add>}
<add>
<add>func getMockImageMount() *imageMount {
<add> return &imageMount{
<add> image: nil,
<add> layer: nil,
<add> }
<add>}
<add>
<add>func TestAddScratchImageAddsToMounts(t *testing.T) {
<add> is := getMockImageSource(nil, nil, fmt.Errorf("getImage is not implemented"))
<add> im := getMockImageMount()
<add>
<add> // We are testing whether the imageMount is added to is.mounts
<add> assert.Equal(t, len(is.mounts), 0)
<add> is.Add(im, nil)
<add> assert.Equal(t, len(is.mounts), 1)
<add>}
<add>
<add>func TestAddFromScratchPopulatesPlatform(t *testing.T) {
<add> is := getMockImageSource(nil, nil, fmt.Errorf("getImage is not implemented"))
<add>
<add> platforms := []*ocispec.Platform{
<add> {
<add> OS: "linux",
<add> Architecture: "amd64",
<add> },
<add> {
<add> OS: "linux",
<add> Architecture: "arm64",
<add> Variant: "v8",
<add> },
<add> }
<add>
<add> for i, platform := range platforms {
<add> im := getMockImageMount()
<add> assert.Equal(t, len(is.mounts), i)
<add> is.Add(im, platform)
<add> image, ok := im.image.(*image.Image)
<add> assert.Assert(t, ok)
<add> assert.Equal(t, image.OS, platform.OS)
<add> assert.Equal(t, image.Architecture, platform.Architecture)
<add> assert.Equal(t, image.Variant, platform.Variant)
<add> }
<add>}
<add>
<add>func TestAddFromScratchDoesNotModifyArgPlatform(t *testing.T) {
<add> is := getMockImageSource(nil, nil, fmt.Errorf("getImage is not implemented"))
<add> im := getMockImageMount()
<add>
<add> platform := &ocispec.Platform{
<add> OS: "windows",
<add> Architecture: "amd64",
<add> }
<add> argPlatform := *platform
<add>
<add> is.Add(im, &argPlatform)
<add> // The way the code is written right now, this test
<add> // really doesn't do much except on Windows.
<add> assert.DeepEqual(t, *platform, argPlatform)
<add>}
<add>
<add>func TestAddFromScratchPopulatesPlatformIfNil(t *testing.T) {
<add> is := getMockImageSource(nil, nil, fmt.Errorf("getImage is not implemented"))
<add> im := getMockImageMount()
<add> is.Add(im, nil)
<add> image, ok := im.image.(*image.Image)
<add> assert.Assert(t, ok)
<add>
<add> expectedPlatform := platforms.DefaultSpec()
<add> if runtime.GOOS == "windows" {
<add> expectedPlatform.OS = "linux"
<add> }
<add> assert.Equal(t, expectedPlatform.OS, image.OS)
<add> assert.Equal(t, expectedPlatform.Architecture, image.Architecture)
<add> assert.Equal(t, expectedPlatform.Variant, image.Variant)
<add>}
<add>
<add>func TestImageSourceGetAddsToMounts(t *testing.T) {
<add> is := getMockImageSource(nil, nil, nil)
<add> _, err := is.Get("test", false, nil)
<add> assert.NilError(t, err)
<add> assert.Equal(t, len(is.mounts), 1)
<add>}
<ide><path>builder/dockerfile/internals.go
<ide> import (
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/go-connections/nat"
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func (b *Builder) exportImage(state *dispatchState, layer builder.RWLayer, paren
<ide> return err
<ide> }
<ide>
<del> // add an image mount without an image so the layer is properly unmounted
<del> // if there is an error before we can add the full mount with image
<del> b.imageSources.Add(newImageMount(nil, newLayer))
<del>
<ide> parentImage, ok := parent.(*image.Image)
<ide> if !ok {
<ide> return errors.Errorf("unexpected image type")
<ide> }
<ide>
<add> platform := &specs.Platform{
<add> OS: parentImage.OS,
<add> Architecture: parentImage.Architecture,
<add> Variant: parentImage.Variant,
<add> }
<add>
<add> // add an image mount without an image so the layer is properly unmounted
<add> // if there is an error before we can add the full mount with image
<add> b.imageSources.Add(newImageMount(nil, newLayer), platform)
<add>
<ide> newImage := image.NewChildImage(parentImage, image.ChildConfig{
<ide> Author: state.maintainer,
<ide> ContainerConfig: runConfig,
<ide> func (b *Builder) exportImage(state *dispatchState, layer builder.RWLayer, paren
<ide> }
<ide>
<ide> state.imageID = exportedImage.ImageID()
<del> b.imageSources.Add(newImageMount(exportedImage, newLayer))
<add> b.imageSources.Add(newImageMount(exportedImage, newLayer), platform)
<ide> return nil
<ide> }
<ide>
<ide><path>builder/dockerfile/internals_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builder/remotecontext"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/go-connections/nat"
<add> "github.com/opencontainers/go-digest"
<ide> "gotest.tools/assert"
<ide> is "gotest.tools/assert/cmp"
<ide> "gotest.tools/skip"
<ide> func TestDeepCopyRunConfig(t *testing.T) {
<ide> copy.Shell[0] = "sh"
<ide> assert.Check(t, is.DeepEqual(fullMutableRunConfig(), runConfig))
<ide> }
<add>
<add>type MockRWLayer struct{}
<add>
<add>func (l *MockRWLayer) Release() error { return nil }
<add>func (l *MockRWLayer) Root() containerfs.ContainerFS { return nil }
<add>func (l *MockRWLayer) Commit() (builder.ROLayer, error) {
<add> return &MockROLayer{
<add> diffID: layer.DiffID(digest.Digest("sha256:1234")),
<add> }, nil
<add>}
<add>
<add>type MockROLayer struct {
<add> diffID layer.DiffID
<add>}
<add>
<add>func (l *MockROLayer) Release() error { return nil }
<add>func (l *MockROLayer) NewRWLayer() (builder.RWLayer, error) { return nil, nil }
<add>func (l *MockROLayer) DiffID() layer.DiffID { return l.diffID }
<add>
<add>func getMockBuildBackend() builder.Backend {
<add> return &MockBackend{}
<add>}
<add>
<add>func TestExportImage(t *testing.T) {
<add> ds := newDispatchState(NewBuildArgs(map[string]*string{}))
<add> layer := &MockRWLayer{}
<add> parentImage := &image.Image{
<add> V1Image: image.V1Image{
<add> OS: "linux",
<add> Architecture: "arm64",
<add> Variant: "v8",
<add> },
<add> }
<add> runConfig := &container.Config{}
<add>
<add> b := &Builder{
<add> imageSources: getMockImageSource(nil, nil, nil),
<add> docker: getMockBuildBackend(),
<add> }
<add> err := b.exportImage(ds, layer, parentImage, runConfig)
<add> assert.NilError(t, err)
<add>}
<ide><path>builder/dockerfile/mockbackend_test.go
<ide> func (m *MockBackend) MakeImageCache(cacheFrom []string) builder.ImageCache {
<ide> }
<ide>
<ide> func (m *MockBackend) CreateImage(config []byte, parent string) (builder.Image, error) {
<del> return nil, nil
<add> return &mockImage{id: "test"}, nil
<ide> }
<ide>
<ide> type mockImage struct {
<ide><path>daemon/images/image_inspect.go
<ide> func (i *ImageService) LookupImage(name string) (*types.ImageInspect, error) {
<ide> Author: img.Author,
<ide> Config: img.Config,
<ide> Architecture: img.Architecture,
<add> Variant: img.Variant,
<ide> Os: img.OperatingSystem(),
<ide> OsVersion: img.OSVersion,
<ide> Size: size,
<ide><path>distribution/config.go
<ide> func (s *imageConfigStore) PlatformFromConfig(c []byte) (*specs.Platform, error)
<ide> if !system.IsOSSupported(os) {
<ide> return nil, system.ErrNotSupportedOperatingSystem
<ide> }
<del> return &specs.Platform{OS: os, Architecture: unmarshalledConfig.Architecture, OSVersion: unmarshalledConfig.OSVersion}, nil
<add> return &specs.Platform{OS: os, Architecture: unmarshalledConfig.Architecture, Variant: unmarshalledConfig.Variant, OSVersion: unmarshalledConfig.OSVersion}, nil
<ide> }
<ide>
<ide> type storeLayerProvider struct {
<ide><path>image/image.go
<ide> type V1Image struct {
<ide> Config *container.Config `json:"config,omitempty"`
<ide> // Architecture is the hardware that the image is built and runs on
<ide> Architecture string `json:"architecture,omitempty"`
<add> // Variant is the CPU architecture variant (presently ARM-only)
<add> Variant string `json:"variant,omitempty"`
<ide> // OS is the operating system used to build and run the image
<ide> OS string `json:"os,omitempty"`
<ide> // Size is the total size of the image including all layers it is composed of
<ide> func (img *Image) BaseImgArch() string {
<ide> return arch
<ide> }
<ide>
<add>// BaseImgVariant returns the image's variant, whether populated or not.
<add>// This avoids creating an inconsistency where the stored image variant
<add>// is "greater than" (i.e. v8 vs v6) the actual image variant.
<add>func (img *Image) BaseImgVariant() string {
<add> return img.Variant
<add>}
<add>
<ide> // OperatingSystem returns the image's operating system. If not populated, defaults to the host runtime OS.
<ide> func (img *Image) OperatingSystem() string {
<ide> os := img.OS
<ide> func NewChildImage(img *Image, child ChildConfig, os string) *Image {
<ide> DockerVersion: dockerversion.Version,
<ide> Config: child.Config,
<ide> Architecture: img.BaseImgArch(),
<add> Variant: img.BaseImgVariant(),
<ide> OS: os,
<ide> Container: child.ContainerID,
<ide> ContainerConfig: *child.ContainerConfig, | 9 |
Text | Text | fix spelling error | cd36e8c9d40c70d075c725da9befd94f5e5d5a7e | <ide><path>docs/api-reference/next/image.md
<ide> module.exports = {
<ide>
<ide> You can specify a list of image widths using the `images.imageSizes` property in your `next.config.js` file. These widths are concatenated with the array of [device sizes](#device-sizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset)s.
<ide>
<del>The reason there are two seperate lists is that imageSizes is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. **Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.**
<add>The reason there are two separate lists is that imageSizes is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. **Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.**
<ide>
<ide> If no configuration is provided, the default below is used.
<ide> | 1 |
Javascript | Javascript | fix monthparse functions for en family | e78353d268f427a4630b045950fb7451e9106b0f | <ide><path>src/lib/locale/en.js
<ide> import './prototype';
<ide> import { getSetGlobalLocale } from './locales';
<ide> import toInt from '../utils/to-int';
<ide>
<del>var monthsParse = [/^Jan/i, /^Feb/i, /^Mar/i, /^Apr/i, /^May/i, /^Jun/i, /^Jul/i, /^Aug/i, /^Sep/i, /^Oct/i, /^Nov/i, /^Dec/i];
<del>
<ide> getSetGlobalLocale('en', {
<del> monthsParse : monthsParse,
<del> longMonthsParse : monthsParse,
<del> shortMonthsParse : monthsParse,
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> ordinalParse: /\d{1,2}(th|st|nd|rd)/,
<ide> ordinal : function (number) {
<ide> var b = number % 10,
<ide><path>src/locale/en-au.js
<ide>
<ide> import moment from '../moment';
<ide>
<del>var monthsParse = [/^Jan/i, /^Feb/i, /^Mar/i, /^Apr/i, /^May/i, /^Jun/i, /^Jul/i, /^Aug/i, /^Sep/i, /^Oct/i, /^Nov/i, /^Dec/i];
<del>
<ide> export default moment.defineLocale('en-au', {
<ide> months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
<ide> monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sept_Oct_Nov_Dec'.split('_'),
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
<ide> weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
<ide> weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
<del> monthsParse : monthsParse,
<del> longMonthsParse : monthsParse,
<del> shortMonthsParse : monthsParse,
<ide> longDateFormat : {
<ide> LT : 'h:mm A',
<ide> LTS : 'h:mm:ss A',
<ide><path>src/locale/en-ca.js
<ide>
<ide> import moment from '../moment';
<ide>
<del>var monthsParse = [/^Jan/i, /^Feb/i, /^Mar/i, /^Apr/i, /^May/i, /^Jun/i, /^Jul/i, /^Aug/i, /^Sep/i, /^Oct/i, /^Nov/i, /^Dec/i];
<del>
<ide> export default moment.defineLocale('en-ca', {
<ide> months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
<ide> monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sept_Oct_Nov_Dec'.split('_'),
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
<ide> weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
<ide> weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
<del> monthsParse : monthsParse,
<del> longMonthsParse : monthsParse,
<del> shortMonthsParse : monthsParse,
<ide> longDateFormat : {
<ide> LT : 'h:mm A',
<ide> LTS : 'h:mm:ss A',
<ide><path>src/locale/en-gb.js
<ide>
<ide> import moment from '../moment';
<ide>
<del>var monthsParse = [/^Jan/i, /^Feb/i, /^Mar/i, /^Apr/i, /^May/i, /^Jun/i, /^Jul/i, /^Aug/i, /^Sep/i, /^Oct/i, /^Nov/i, /^Dec/i];
<del>
<ide> export default moment.defineLocale('en-gb', {
<ide> months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
<ide> monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sept_Oct_Nov_Dec'.split('_'),
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
<ide> weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
<ide> weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
<del> monthsParse : monthsParse,
<del> longMonthsParse : monthsParse,
<del> shortMonthsParse : monthsParse,
<ide> longDateFormat : {
<ide> LT : 'HH:mm',
<ide> LTS : 'HH:mm:ss',
<ide><path>src/locale/en-ie.js
<ide> import moment from '../moment';
<ide> export default moment.defineLocale('en-ie', {
<ide> months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
<ide> monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
<ide> weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
<ide> weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
<ide><path>src/locale/en-nz.js
<ide>
<ide> import moment from '../moment';
<ide>
<del>var monthsParse = [/^Jan/i, /^Feb/i, /^Mar/i, /^Apr/i, /^May/i, /^Jun/i, /^Jul/i, /^Aug/i, /^Sep/i, /^Oct/i, /^Nov/i, /^Dec/i];
<del>
<ide> export default moment.defineLocale('en-nz', {
<ide> months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
<ide> monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sept_Oct_Nov_Dec'.split('_'),
<add> monthsParse : [/^jan/i, /^feb/i, /^mar/i, /^apr/i, /^may/i, /^jun/i, /^jul/i, /^aug/i, /^sep/i, /^oct/i, /^nov/i, /^dec/i],
<add> longMonthsParse : [/^january$/i, /^february$/i, /^march$/i, /^april$/i, /^may$/i, /^june$/i, /^july$/i, /^august$/i, /^september$/i, /^october$/i, /^november$/i, /^december$/i],
<add> shortMonthsParse : [/^jan$/i, /^feb$/i, /^mar$/i, /^apr$/i, /^may$/i, /^jun$/i, /^jul$/i, /^aug/i, /^sept?$/i, /^oct$/i, /^nov$/i, /^dec$/i],
<ide> weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
<ide> weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
<ide> weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
<del> monthsParse : monthsParse,
<del> longMonthsParse : monthsParse,
<del> shortMonthsParse : monthsParse,
<ide> longDateFormat : {
<ide> LT : 'h:mm A',
<ide> LTS : 'h:mm:ss A', | 6 |
Go | Go | fix the panic caused by resizing a starting exec | ba5e0980527d3477cb85925e07eecb28dfe50e08 | <ide><path>daemon/container.go
<ide> func (container *Container) Exec(execConfig *execConfig) error {
<ide> container.Lock()
<ide> defer container.Unlock()
<ide>
<del> waitStart := make(chan struct{})
<del>
<ide> callback := func(processConfig *execdriver.ProcessConfig, pid int) {
<ide> if processConfig.Tty {
<ide> // The callback is called after the process Start()
<ide> func (container *Container) Exec(execConfig *execConfig) error {
<ide> c.Close()
<ide> }
<ide> }
<del> close(waitStart)
<add> close(execConfig.waitStart)
<ide> }
<ide>
<ide> // We use a callback here instead of a goroutine and an chan for
<ide> func (container *Container) Exec(execConfig *execConfig) error {
<ide>
<ide> // Exec should not return until the process is actually running
<ide> select {
<del> case <-waitStart:
<add> case <-execConfig.waitStart:
<ide> case err := <-cErr:
<ide> return err
<ide> }
<ide><path>daemon/exec.go
<ide> type execConfig struct {
<ide> OpenStdout bool
<ide> Container *Container
<ide> canRemove bool
<add>
<add> // waitStart will be closed immediately after the exec is really started.
<add> waitStart chan struct{}
<ide> }
<ide>
<ide> type execStore struct {
<ide> func (e *execStore) List() []string {
<ide> }
<ide>
<ide> func (execConfig *execConfig) Resize(h, w int) error {
<add> select {
<add> case <-execConfig.waitStart:
<add> case <-time.After(time.Second):
<add> return fmt.Errorf("Exec %s is not running, so it can not be resized.", execConfig.ID)
<add> }
<ide> return execConfig.ProcessConfig.Terminal.Resize(h, w)
<ide> }
<ide>
<ide> func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, erro
<ide> ProcessConfig: processConfig,
<ide> Container: container,
<ide> Running: false,
<add> waitStart: make(chan struct{}),
<ide> }
<ide>
<ide> d.registerExecCommand(execConfig)
<ide><path>integration-cli/docker_api_exec_resize_test.go
<ide> package main
<ide>
<ide> import (
<add> "bytes"
<add> "encoding/json"
<add> "fmt"
<add> "io"
<ide> "net/http"
<ide> "strings"
<ide>
<ide> func (s *DockerSuite) TestExecResizeApiHeightWidthNoInt(c *check.C) {
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> c.Assert(err, check.IsNil)
<ide> }
<add>
<add>// Part of #14845
<add>func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) {
<add> name := "exec_resize_test"
<add> dockerCmd(c, "run", "-d", "-i", "-t", "--name", name, "--restart", "always", "busybox", "/bin/sh")
<add>
<add> // The panic happens when daemon.ContainerExecStart is called but the
<add> // container.Exec is not called.
<add> // Because the panic is not 100% reproducible, we send the requests concurrently
<add> // to increase the probability that the problem is triggered.
<add> n := 10
<add> ch := make(chan struct{})
<add> for i := 0; i < n; i++ {
<add> go func() {
<add> defer func() {
<add> ch <- struct{}{}
<add> }()
<add>
<add> data := map[string]interface{}{
<add> "AttachStdin": true,
<add> "Cmd": []string{"/bin/sh"},
<add> }
<add> status, body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), data)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, http.StatusCreated)
<add>
<add> out := map[string]string{}
<add> err = json.Unmarshal(body, &out)
<add> c.Assert(err, check.IsNil)
<add>
<add> execID := out["Id"]
<add> if len(execID) < 1 {
<add> c.Fatal("ExecCreate got invalid execID")
<add> }
<add>
<add> payload := bytes.NewBufferString(`{"Tty":true}`)
<add> conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json")
<add> c.Assert(err, check.IsNil)
<add> defer conn.Close()
<add>
<add> _, rc, err := sockRequestRaw("POST", fmt.Sprintf("/exec/%s/resize?h=24&w=80", execID), nil, "text/plain")
<add> // It's probably a panic of the daemon if io.ErrUnexpectedEOF is returned.
<add> if err == io.ErrUnexpectedEOF {
<add> c.Fatal("The daemon might have crashed.")
<add> }
<add>
<add> if err == nil {
<add> rc.Close()
<add> }
<add> }()
<add> }
<add>
<add> for i := 0; i < n; i++ {
<add> <-ch
<add> }
<add>}
<ide><path>integration-cli/docker_utils.go
<ide> package main
<ide>
<ide> import (
<add> "bufio"
<ide> "bytes"
<ide> "encoding/json"
<ide> "errors"
<ide> func sockRequest(method, endpoint string, data interface{}) (int, []byte, error)
<ide> }
<ide>
<ide> func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
<add> req, client, err := newRequestClient(method, endpoint, data, ct)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add>
<add> resp, err := client.Do(req)
<add> if err != nil {
<add> client.Close()
<add> return nil, nil, err
<add> }
<add> body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
<add> defer resp.Body.Close()
<add> return client.Close()
<add> })
<add>
<add> return resp, body, nil
<add>}
<add>
<add>func sockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {
<add> req, client, err := newRequestClient(method, endpoint, data, ct)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add>
<add> client.Do(req)
<add> conn, br := client.Hijack()
<add> return conn, br, nil
<add>}
<add>
<add>func newRequestClient(method, endpoint string, data io.Reader, ct string) (*http.Request, *httputil.ClientConn, error) {
<ide> c, err := sockConn(time.Duration(10 * time.Second))
<ide> if err != nil {
<ide> return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
<ide> func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.R
<ide> if ct != "" {
<ide> req.Header.Set("Content-Type", ct)
<ide> }
<del>
<del> resp, err := client.Do(req)
<del> if err != nil {
<del> client.Close()
<del> return nil, nil, fmt.Errorf("could not perform request: %v", err)
<del> }
<del> body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
<del> defer resp.Body.Close()
<del> return client.Close()
<del> })
<del>
<del> return resp, body, nil
<add> return req, client, nil
<ide> }
<ide>
<ide> func readBody(b io.ReadCloser) ([]byte, error) { | 4 |
Text | Text | move package.import content higher | 8d8e06a345043bec787e904edc9a2f5c5e9c275f | <ide><path>doc/api/packages.md
<ide> import submodule from 'es-module-package/private-module.js';
<ide> // Throws ERR_PACKAGE_PATH_NOT_EXPORTED
<ide> ```
<ide>
<del>### Subpath export patterns
<add>### Subpath imports
<ide>
<ide> > Stability: 1 - Experimental
<ide>
<del>For packages with a small number of exports, we recommend explicitly listing
<del>each exports subpath entry. But for packages that have large numbers of
<del>subpaths, this might cause `package.json` bloat and maintenance issues.
<add>In addition to the [`"exports"`][] field, it is possible to define internal
<add>package import maps that only apply to import specifiers from within the package
<add>itself.
<add>
<add>Entries in the imports field must always start with `#` to ensure they are
<add>disambiguated from package specifiers.
<add>
<add>For example, the imports field can be used to gain the benefits of conditional
<add>exports for internal modules:
<add>
<add>```json
<add>// package.json
<add>{
<add> "imports": {
<add> "#dep": {
<add> "node": "dep-node-native",
<add> "default": "./dep-polyfill.js"
<add> }
<add> },
<add> "dependencies": {
<add> "dep-node-native": "^1.0.0"
<add> }
<add>}
<add>```
<add>
<add>where `import '#dep'` does not get the resolution of the external package
<add>`dep-node-native` (including its exports in turn), and instead gets the local
<add>file `./dep-polyfill.js` relative to the package in other environments.
<add>
<add>Unlike the `"exports"` field, the `"imports"` field permits mapping to external
<add>packages.
<add>
<add>The resolution rules for the imports field are otherwise
<add>analogous to the exports field.
<add>
<add>### Subpath patterns
<add>
<add>> Stability: 1 - Experimental
<add>
<add>For packages with a small number of exports or imports, we recommend
<add>explicitly listing each exports subpath entry. But for packages that have
<add>large numbers of subpaths, this might cause `package.json` bloat and
<add>maintenance issues.
<ide>
<ide> For these use cases, subpath export patterns can be used instead:
<ide>
<ide> For these use cases, subpath export patterns can be used instead:
<ide> {
<ide> "exports": {
<ide> "./features/*": "./src/features/*.js"
<add> },
<add> "imports": {
<add> "#internal/*": "./src/internal/*.js"
<ide> }
<ide> }
<ide> ```
<ide> import featureX from 'es-module-package/features/x';
<ide>
<ide> import featureY from 'es-module-package/features/y/y';
<ide> // Loads ./node_modules/es-module-package/src/features/y/y.js
<add>
<add>import internalZ from '#internal/z';
<add>// Loads ./node_modules/es-module-package/src/internal/z.js
<ide> ```
<ide>
<ide> This is a direct static replacement without any special handling for file
<ide> added: v14.6.0
<ide>
<ide> * Type: {Object}
<ide>
<del>In addition to the [`"exports"`][] field it is possible to define internal
<del>package import maps that only apply to import specifiers from within the package
<del>itself.
<del>
<del>Entries in the imports field must always start with `#` to ensure they are
<del>clearly disambiguated from package specifiers.
<del>
<del>For example, the imports field can be used to gain the benefits of conditional
<del>exports for internal modules:
<del>
<ide> ```json
<ide> // package.json
<ide> {
<ide> exports for internal modules:
<ide> }
<ide> ```
<ide>
<del>where `import '#dep'` would now get the resolution of the external package
<del>`dep-node-native` (including its exports in turn), and instead get the local
<del>file `./dep-polyfill.js` relative to the package in other environments.
<add>Entries in the imports field must be strings starting with `#`.
<ide>
<del>Unlike the `"exports"` field, import maps permit mapping to external packages,
<del>providing an important use case for conditional loading scenarios.
<add>Import maps permit mapping to external packages.
<ide>
<del>Apart from the above, the resolution rules for the imports field are otherwise
<del>analogous to the exports field.
<add>This field defines [subpath imports][] for the current package.
<ide>
<ide> [Babel]: https://babeljs.io/
<ide> [Conditional exports]: #packages_conditional_exports
<ide> analogous to the exports field.
<ide> [entry points]: #packages_package_entry_points
<ide> [self-reference]: #packages_self_referencing_a_package_using_its_name
<ide> [subpath exports]: #packages_subpath_exports
<add>[subpath imports]: #packages_subpath_imports
<ide> [the full specifier path]: esm.md#esm_mandatory_file_extensions
<ide> [the dual CommonJS/ES module packages section]: #packages_dual_commonjs_es_module_packages | 1 |
Ruby | Ruby | remove unneeded back-references | e3646c9b4e9dea9204f3c8a3bb472638546c4534 | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def fcflags
<ide> # end</pre>
<ide> def compiler
<ide> @compiler ||= if (cc = @cc)
<del> warn_about_non_apple_gcc($&) if cc =~ GNU_GCC_REGEXP
<add> warn_about_non_apple_gcc(cc) if cc.match?(GNU_GCC_REGEXP)
<add>
<ide> fetch_compiler(cc, "--cc")
<ide> elsif (cc = homebrew_cc)
<del> warn_about_non_apple_gcc($&) if cc =~ GNU_GCC_REGEXP
<add> warn_about_non_apple_gcc(cc) if cc.match?(GNU_GCC_REGEXP)
<add>
<ide> compiler = fetch_compiler(cc, "HOMEBREW_CC")
<ide>
<ide> if @formula
<ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def setup_build_environment(**options)
<ide>
<ide> send(compiler)
<ide>
<del> return unless cc =~ GNU_GCC_REGEXP
<add> return unless cc.match?(GNU_GCC_REGEXP)
<ide>
<del> gcc_formula = gcc_version_formula($&)
<add> gcc_formula = gcc_version_formula(cc)
<ide> append_path "PATH", gcc_formula.opt_bin.to_s
<ide> end
<ide> alias generic_setup_build_environment setup_build_environment
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def determine_path
<ide> path.append("/usr/bin", "/bin", "/usr/sbin", "/sbin")
<ide>
<ide> begin
<del> path.append(gcc_version_formula($&).opt_bin) if homebrew_cc =~ GNU_GCC_REGEXP
<add> path.append(gcc_version_formula(homebrew_cc).opt_bin) if homebrew_cc.match?(GNU_GCC_REGEXP)
<ide> rescue FormulaUnavailableError
<ide> # Don't fail and don't add these formulae to the path if they don't exist.
<ide> nil | 3 |
Ruby | Ruby | reduce calls to stringify_keys | 47e06c988e8377d04a6a6e28e798b06187326d87 | <ide><path>activerecord/lib/active_record/relation/predicate_builder.rb
<ide> def initialize(table)
<ide> end
<ide>
<ide> def build_from_hash(attributes)
<del> attributes = convert_dot_notation_to_hash(attributes.stringify_keys)
<add> attributes = convert_dot_notation_to_hash(attributes)
<ide> expand_from_hash(attributes)
<ide> end
<ide>
<ide> def create_binds(attributes)
<del> attributes = convert_dot_notation_to_hash(attributes.stringify_keys)
<add> attributes = convert_dot_notation_to_hash(attributes)
<ide> create_binds_for_hash(attributes)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb
<ide> def call(attribute, value)
<ide>
<ide> table = value.associated_table
<ide> if value.base_class
<del> queries[table.association_foreign_type] = value.base_class.name
<add> queries[table.association_foreign_type.to_s] = value.base_class.name
<ide> end
<ide>
<del> queries[table.association_foreign_key] = value.ids
<add> queries[table.association_foreign_key.to_s] = value.ids
<ide> predicate_builder.build_from_hash(queries)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/relation/where_clause_factory.rb
<ide> def build(opts, other)
<ide> when Hash
<ide> attributes = predicate_builder.resolve_column_aliases(opts)
<ide> attributes = klass.send(:expand_hash_conditions_for_aggregates, attributes)
<add> attributes.stringify_keys!
<ide>
<ide> attributes, binds = predicate_builder.create_binds(attributes)
<ide> | 3 |
Javascript | Javascript | fix formatting and clarify | 12ae60052f2850d8e325d1090e3b06c6620cdd36 | <ide><path>src/ng/directive/booleanAttrs.js
<ide> * @restrict A
<ide> *
<ide> * @description
<del> * Using Angular markup like {{hash}} in an href attribute makes
<del> * the page open to a wrong URL, if the user clicks that link before
<del> * angular has a chance to replace the {{hash}} with actual URL, the
<del> * link will be broken and will most likely return a 404 error.
<add> * Using Angular markup like `{{hash}}` in an href attribute will
<add> * make the link go to the wrong URL if the user clicks it before
<add> * Angular has a chance to replace the `{{hash}}` markup with its
<add> * value. Until Angular replaces the markup the link will be broken
<add> * and will most likely return a 404 error.
<add> *
<ide> * The `ngHref` directive solves this problem.
<ide> *
<del> * The buggy way to write it:
<add> * The wrong way to write it:
<ide> * <pre>
<ide> * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
<ide> * </pre>
<ide> * @param {template} ngHref any string which can contain `{{}}` markup.
<ide> *
<ide> * @example
<del> * This example uses `link` variable inside `href` attribute:
<add> * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
<add> * in links and their different behaviors:
<ide> <doc:example>
<ide> <doc:source>
<ide> <input ng-model="value" /><br /> | 1 |
Text | Text | add new line for numbers 1., 2., and 3. | 7b56a52b58267ede76c26e6ab104396211c237c2 | <ide><path>guide/english/react/installation/index.md
<ide> to create an optimized build of your app in the `build`folder.
<ide>
<ide> #### Sources
<ide> [1. The React tutorial on installing](https://reactjs.org/docs/installation.html)
<add>
<ide> [2. Link to the React minimal JavaScript library on cdnjs.org](https://cdnjs.com/libraries/react)
<add>
<ide> [3. npm start command](https://docs.npmjs.com/cli/start) | 1 |
Javascript | Javascript | fix a bug in transitions (`tx` is undefined) | 7048af6b028528017cf4a140c9e6965897e2ac91 | <ide><path>d3.js
<del>(function(){d3 = {version: "0.28.9"}; // semver
<add>(function(){d3 = {version: "0.28.10"}; // semver
<ide> if (!Date.now) Date.now = function() {
<ide> return +new Date();
<ide> };
<ide> function d3_transition(groups) {
<ide> // 1 - In progress.
<ide> // 2 - Ended.
<ide> if (stage[k]) {
<del> if (tx.active != transitionId) {
<add> if (!tx || tx.active != transitionId) {
<ide> stage[k] = 2;
<ide> return;
<ide> }
<ide><path>d3.min.js
<ide> Math.sqrt(1-a*a)}function sa(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1
<ide> (c-a)/d+2:(a-b)/d+4;a*=60}else g=a=0;return Q(a,g,h)}function P(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function Q(a,b,c){return{h:a,s:b,l:c,toString:va}}function va(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function ca(a,b,c){function g(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return e+(d-e)*h/60;if(h<180)return d;if(h<240)return e+(d-e)*(240-h)/60;return e}var e,d;a%=360;if(a<0)a+=360;b=b<0?0:b>1?1:b;c=c<0?0:c>1?1:c;d=c<=0.5?c*(1+b):c+b-
<ide> c*b;e=2*c-d;return G(Math.round(g(a+120)*255),Math.round(g(a)*255),Math.round(g(a-120)*255))}function x(a){function b(e){for(var d=[],h,f,i,j,l=0,o=a.length;l<o;l++){i=a[l];d.push(h=[]);h.parentNode=i.parentNode;h.parentData=i.parentData;for(var p=0,k=i.length;p<k;p++)if(j=i[p]){h.push(f=e(j));if(f&&"__data__"in j)f.__data__=j.__data__}else h.push(null)}return x(d)}function c(e){for(var d=[],h,f,i,j=0,l=a.length;j<l;j++){f=a[j];for(var o=0,p=f.length;o<p;o++)if(i=f[o]){d.push(h=e(i));h.parentNode=
<ide> i;h.parentData=i.__data__}}return x(d)}function g(e){for(var d=0,h=a.length;d<h;d++)for(var f=a[d],i=0,j=f.length;i<j;i++){var l=f[i];if(l)return e.call(l,l.__data__,i)}return null}a.select=function(e){return b(function(d){return d.querySelector(e)})};a.selectAll=function(e){return c(function(d){return L(d.querySelectorAll(e))})};a.filter=function(e){for(var d=[],h,f,i,j=0,l=a.length;j<l;j++){f=a[j];d.push(h=[]);h.parentNode=f.parentNode;h.parentData=f.parentData;for(var o=0,p=f.length;o<p;o++)if((i=
<del>f[o])&&e.call(i,i.__data__,o))h.push(i)}return x(d)};a.data=function(e,d){function h(k,n){function q(wa){return k.parentNode.appendChild(wa)}var m=0,s=k.length,t=n.length,r=Math.min(s,t),u=Math.max(s,t),y=[],z=[],v=[],A,B;if(d){r={};u=[];var C;B=n.length;for(m=0;m<s;m++){C=d.nodeKey(A=k[m]);if(C in r)v[B++]=k[m];else{r[C]=A;u.push(C)}}for(m=0;m<t;m++){if(A=r[C=d.dataKey(B=n[m])]){A.__data__=B;y[m]=A;z[m]=v[m]=null}else{z[m]={appendChild:q,__data__:B};y[m]=v[m]=null}delete r[C]}for(m=0;m<s;m++)if(u[m]in
<del>r)v[m]=k[m]}else{for(;m<r;m++){A=k[m];B=n[m];if(A){A.__data__=B;y[m]=A;z[m]=v[m]=null}else{z[m]={appendChild:q,__data__:B};y[m]=v[m]=null}}for(;m<t;m++){z[m]={appendChild:q,__data__:n[m]};y[m]=v[m]=null}for(;m<u;m++){v[m]=k[m];z[m]=y[m]=null}}z.parentNode=y.parentNode=v.parentNode=k.parentNode;z.parentData=y.parentData=v.parentData=k.parentData;l.push(z);o.push(y);p.push(v)}var f=-1,i=a.length,j,l=[],o=[],p=[];if(typeof d=="string")d=xa(d);if(typeof e=="function")for(;++f<i;)h(j=a[f],e.call(j,j.parentData,
<add>f[o])&&e.call(i,i.__data__,o))h.push(i)}return x(d)};a.data=function(e,d){function h(k,n){function q(wa){return k.parentNode.appendChild(wa)}var m=0,r=k.length,t=n.length,s=Math.min(r,t),u=Math.max(r,t),y=[],z=[],v=[],A,B;if(d){s={};u=[];var C;B=n.length;for(m=0;m<r;m++){C=d.nodeKey(A=k[m]);if(C in s)v[B++]=k[m];else{s[C]=A;u.push(C)}}for(m=0;m<t;m++){if(A=s[C=d.dataKey(B=n[m])]){A.__data__=B;y[m]=A;z[m]=v[m]=null}else{z[m]={appendChild:q,__data__:B};y[m]=v[m]=null}delete s[C]}for(m=0;m<r;m++)if(u[m]in
<add>s)v[m]=k[m]}else{for(;m<s;m++){A=k[m];B=n[m];if(A){A.__data__=B;y[m]=A;z[m]=v[m]=null}else{z[m]={appendChild:q,__data__:B};y[m]=v[m]=null}}for(;m<t;m++){z[m]={appendChild:q,__data__:n[m]};y[m]=v[m]=null}for(;m<u;m++){v[m]=k[m];z[m]=y[m]=null}}z.parentNode=y.parentNode=v.parentNode=k.parentNode;z.parentData=y.parentData=v.parentData=k.parentData;l.push(z);o.push(y);p.push(v)}var f=-1,i=a.length,j,l=[],o=[],p=[];if(typeof d=="string")d=xa(d);if(typeof e=="function")for(;++f<i;)h(j=a[f],e.call(j,j.parentData,
<ide> f));else for(;++f<i;)h(j=a[f],e);f=x(o);f.enter=function(k){return x(l).append(k)};f.exit=function(){return x(p)};return f};a.each=function(e){for(var d=0,h=a.length;d<h;d++)for(var f=a[d],i=0,j=f.length;i<j;i++){var l=f[i];l&&e.call(l,l.__data__,i)}return a};a.node=function(){return g(function(){return this})};a.attr=function(e,d){function h(){this.removeAttribute(e)}function f(){this.removeAttributeNS(e.space,e.local)}function i(){this.setAttribute(e,d)}function j(){this.setAttributeNS(e.space,
<ide> e.local,d)}function l(){var p=d.apply(this,arguments);p==null?this.removeAttribute(e):this.setAttribute(e,p)}function o(){var p=d.apply(this,arguments);p==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,p)}e=d3.ns.qualify(e);if(arguments.length<2)return g(e.local?function(){return this.getAttributeNS(e.space,e.local)}:function(){return this.getAttribute(e)});return a.each(d==null?e.local?f:h:typeof d=="function"?e.local?o:l:e.local?j:i)};a.classed=function(e,d){function h(){var l=
<ide> this.className;j.lastIndex=0;if(!j.test(l))this.className=Z(l+" "+e)}function f(){var l=Z(this.className.replace(j," "));this.className=l.length?l:null}function i(){(d.apply(this,arguments)?h:f).call(this)}var j=RegExp("(^|\\s+)"+d3.requote(e)+"(\\s+|$)","g");if(arguments.length<2)return g(function(){j.lastIndex=0;return j.test(this.className)});return a.each(typeof d=="function"?i:d?h:f)};a.style=function(e,d,h){function f(){this.style.removeProperty(e)}function i(){this.style.setProperty(e,d,h)}
<ide> function j(){var l=d.apply(this,arguments);l==null?this.style.removeProperty(e):this.style.setProperty(e,l,h)}if(arguments.length<3)h=null;if(arguments.length<2)return g(function(){return window.getComputedStyle(this,null).getPropertyValue(e)});return a.each(d==null?f:typeof d=="function"?j:i)};a.property=function(e,d){function h(){delete this[e]}function f(){this[e]=d}function i(){var j=d.apply(this,arguments);if(j==null)delete this[e];else this[e]=j}e=d3.ns.qualify(e);if(arguments.length<2)return g(function(){return this[e]});
<ide> return a.each(d==null?h:typeof d=="function"?i:f)};a.text=function(e){function d(){this.appendChild(document.createTextNode(e))}function h(){var f=e.apply(this,arguments);f!=null&&this.appendChild(document.createTextNode(f))}if(arguments.length<1)return g(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return e==null?a:a.each(typeof e=="function"?h:d)};a.html=function(e){function d(){this.innerHTML=e}function h(){this.innerHTML=e.apply(this,
<ide> arguments)}if(arguments.length<1)return g(function(){return this.innerHTML});return a.each(typeof e=="function"?h:d)};a.append=function(e){function d(f){return f.appendChild(document.createElement(e))}function h(f){return f.appendChild(document.createElementNS(e.space,e.local))}e=d3.ns.qualify(e);return b(e.local?h:d)};a.remove=function(){return b(function(e){var d=e.parentNode;d.removeChild(e);return d})};a.sort=function(e){e=ya.apply(this,arguments);for(var d=0,h=a.length;d<h;d++){var f=a[d];f.sort(e);
<ide> for(var i=1,j=f.length,l=f[0];i<j;i++){var o=f[i];if(o){l&&l.parentNode.insertBefore(o,l.nextSibling);l=o}}}return a};a.on=function(e,d){e="on"+e;return a.each(function(h,f){this[e]=function(i){var j=d3.event;d3.event=i;try{d.call(this,h,f)}finally{d3.event=j}}})};a.transition=function(){return R(a)};a.call=$;return a}function xa(a){return{nodeKey:function(b){return b.getAttribute(a)},dataKey:function(b){return b[a]}}}function ya(a){if(!arguments.length)a=d3.ascending;return function(b,c){return a(b&&
<del>b.__data__,c&&c.__data__)}}function R(a){function b(k){var n=true,q=-1;a.each(function(){if(i[++q]!=2){var m=(k-j[q])/l[q],s=this.__transition__,t,r,u=d[q];if(m<1){n=false;if(m<0)return}else m=1;if(i[q]){if(s.active!=g){i[q]=2;return}}else if(!s||s.active>g){i[q]=2;return}else{i[q]=1;f.start.dispatch.apply(this,arguments);u=d[q]={};s.active=g;for(r in e)u[r]=e[r].apply(this,arguments)}t=p(m);for(r in e)u[r].call(this,t);if(m==1){i[q]=2;if(s.active==g){m=s.owner;if(m==g){delete this.__transition__;
<del>h&&this.parentNode.removeChild(this)}S=g;f.end.dispatch.apply(this,arguments);S=0;s.owner=m}}}});return n}var c={},g=S||++za,e={},d=[],h=false,f=d3.dispatch("start","end"),i=[],j=[],l=[],o,p=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=g});c.delay=function(k){var n=Infinity,q=-1;if(typeof k=="function")a.each(function(){var m=j[++q]=+k.apply(this,arguments);if(m<n)n=m});else{n=+k;a.each(function(){j[++q]=n})}Aa(b,n);return c};c.duration=function(k){var n=
<del>-1;if(typeof k=="function"){o=0;a.each(function(){var q=l[++n]=+k.apply(this,arguments);if(q>o)o=q})}else{o=+k;a.each(function(){l[++n]=o})}return c};c.ease=function(k){p=typeof k=="string"?d3.ease(k):k;return c};c.attrTween=function(k,n){function q(s,t){var r=n.call(this,s,t,this.getAttribute(k));return function(u){this.setAttribute(k,r(u))}}function m(s,t){var r=n.call(this,s,t,this.getAttributeNS(k.space,k.local));return function(u){this.setAttributeNS(k.space,k.local,r(u))}}e["attr."+k]=k.local?
<del>m:q;return c};c.attr=function(k,n){return c.attrTween(k,da(n))};c.styleTween=function(k,n,q){e["style."+k]=function(m,s){var t=n.call(this,m,s,window.getComputedStyle(this,null).getPropertyValue(k));return function(r){this.style.setProperty(k,t(r),q)}};return c};c.style=function(k,n,q){return c.styleTween(k,da(n),q)};c.select=function(k){var n;k=R(a.select(k)).ease(p);n=-1;k.delay(function(){return j[++n]});n=-1;k.duration(function(){return l[++n]});return k};c.selectAll=function(k){var n;k=R(a.selectAll(k)).ease(p);
<add>b.__data__,c&&c.__data__)}}function R(a){function b(k){var n=true,q=-1;a.each(function(){if(i[++q]!=2){var m=(k-j[q])/l[q],r=this.__transition__,t,s,u=d[q];if(m<1){n=false;if(m<0)return}else m=1;if(i[q]){if(!r||r.active!=g){i[q]=2;return}}else if(!r||r.active>g){i[q]=2;return}else{i[q]=1;f.start.dispatch.apply(this,arguments);u=d[q]={};r.active=g;for(s in e)u[s]=e[s].apply(this,arguments)}t=p(m);for(s in e)u[s].call(this,t);if(m==1){i[q]=2;if(r.active==g){m=r.owner;if(m==g){delete this.__transition__;
<add>h&&this.parentNode.removeChild(this)}S=g;f.end.dispatch.apply(this,arguments);S=0;r.owner=m}}}});return n}var c={},g=S||++za,e={},d=[],h=false,f=d3.dispatch("start","end"),i=[],j=[],l=[],o,p=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=g});c.delay=function(k){var n=Infinity,q=-1;if(typeof k=="function")a.each(function(){var m=j[++q]=+k.apply(this,arguments);if(m<n)n=m});else{n=+k;a.each(function(){j[++q]=n})}Aa(b,n);return c};c.duration=function(k){var n=
<add>-1;if(typeof k=="function"){o=0;a.each(function(){var q=l[++n]=+k.apply(this,arguments);if(q>o)o=q})}else{o=+k;a.each(function(){l[++n]=o})}return c};c.ease=function(k){p=typeof k=="string"?d3.ease(k):k;return c};c.attrTween=function(k,n){function q(r,t){var s=n.call(this,r,t,this.getAttribute(k));return function(u){this.setAttribute(k,s(u))}}function m(r,t){var s=n.call(this,r,t,this.getAttributeNS(k.space,k.local));return function(u){this.setAttributeNS(k.space,k.local,s(u))}}e["attr."+k]=k.local?
<add>m:q;return c};c.attr=function(k,n){return c.attrTween(k,da(n))};c.styleTween=function(k,n,q){e["style."+k]=function(m,r){var t=n.call(this,m,r,window.getComputedStyle(this,null).getPropertyValue(k));return function(s){this.style.setProperty(k,t(s),q)}};return c};c.style=function(k,n,q){return c.styleTween(k,da(n),q)};c.select=function(k){var n;k=R(a.select(k)).ease(p);n=-1;k.delay(function(){return j[++n]});n=-1;k.duration(function(){return l[++n]});return k};c.selectAll=function(k){var n;k=R(a.selectAll(k)).ease(p);
<ide> n=-1;k.delay(function(q,m){return j[m?n:++n]});n=-1;k.duration(function(q,m){return l[m?n:++n]});return k};c.remove=function(){h=true;return c};c.each=function(k,n){f[k].add(n);return c};c.call=$;return c.delay(0).duration(250)}function Aa(a,b){var c=Date.now(),g=false,e=c+b,d=D;if(isFinite(b)){for(;d;){if(d.callback==a){d.then=c;d.delay=b;g=true}else{var h=d.then+d.delay;if(h<e)e=h}d=d.next}g||(D={callback:a,then:c,delay:b,next:D});if(!H){clearTimeout(T);T=setTimeout(Ba,Math.max(24,e-c))}}}function Ba(){H=
<ide> setInterval(Ca,24);T=0}function Ca(){for(var a,b=Date.now(),c=D;c;){a=b-c.then;if(a>c.delay)c.flush=c.callback(a);c=c.next}a=null;for(b=D;b;)b=b.flush?a?a.next=b.next:D=b.next:(a=b).next;a||(H=clearInterval(H))}function da(a){return typeof a=="function"?function(b,c,g){return d3.interpolate(g,a.call(this,b,c))}:function(b,c,g){return d3.interpolate(g,a)}}function Da(a){return a.innerRadius}function Ea(a){return a.outerRadius}function ea(a){return a.startAngle}function fa(a){return a.endAngle}function U(a,
<ide> b,c,g){var e=[],d=-1,h=b.length,f=typeof c=="function",i=typeof g=="function",j;if(f&&i)for(;++d<h;)e.push([c.call(a,j=b[d],d),g.call(a,j,d)]);else if(f)for(;++d<h;)e.push([c.call(a,b[d],d),g]);else if(i)for(;++d<h;)e.push([c,g.call(a,b[d],d)]);else for(;++d<h;)e.push([c,g]);return e}function ga(a){return a.x}function ha(a){return a.y}function ia(a){if(a.length<1)return null;var b=[],c=0,g=a.length,e=a[0];for(b.push(e[0],",",e[1]);++c<g;)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function E(a,
<del>b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function V(a,b,c){a.push("C",E(ja,b),",",E(ja,c),",",E(ka,b),",",E(ka,c),",",E(la,b),",",E(la,c))}function Fa(){return 0}function Ga(a){return a.source}function Ha(a){return a.target}function Ia(a){return a.radius}d3={version:"0.28.9"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<
<add>b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function V(a,b,c){a.push("C",E(ja,b),",",E(ja,c),",",E(ka,b),",",E(ka,c),",",E(la,b),",",E(la,c))}function Fa(){return 0}function Ga(a){return a.source}function Ha(a){return a.target}function Ia(a){return a.radius}d3={version:"0.28.10"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<
<ide> a?-1:b>a?1:0};d3.nest=function(){function a(d,h){if(d>=c.length)return e?e.call(b,h):g?h.sort(g):h;for(var f=-1,i=h.length,j=c[d],l,o=[],p,k={};++f<i;)if((l=j(p=h[f]))in k)k[l].push(p);else{k[l]=[p];o.push(l)}d++;f=-1;for(i=o.length;++f<i;){p=k[l=o[f]];k[l]=a(d,p)}return k}var b={},c=[],g,e;b.map=function(d){return a(0,d)};b.key=function(d){c.push(d);return b};b.sortKeys=function(){return b};b.sortValues=function(d){g=d;return b};b.rollup=function(d){e=d;return b};return b};d3.keys=function(a){var b=
<ide> [],c;for(c in a)b.push(c);return b};d3.values=function(a){var b=[],c;for(c in a)b.push(a[c]);return b};d3.entries=function(a){var b=[],c;for(c in a)b.push({key:c,value:a[c]});return b};d3.merge=function(a){return Array.prototype.concat.apply([],a)};d3.split=function(a,b){var c=[],g=[],e,d=-1,h=a.length;if(arguments.length<2)b=ma;for(;++d<h;)if(b.call(g,e=a[d],d)){c.push(g);g=[]}else g.push(e);c.push(g);return c};d3.range=function(a,b,c){if(arguments.length==1){b=a;a=0}if(c==null)c=1;if((b-a)/c==Infinity)throw Error("infinite range");
<ide> var g=[],e=-1,d;if(c<0)for(;(d=a+c*++e)>b;)g.push(d);else for(;(d=a+c*++e)<b;)g.push(d);return g};d3.requote=function(a){return a.replace(Ja,"\\$&")};var Ja=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var g=new XMLHttpRequest;if(arguments.length<3)c=b;else b&&g.overrideMimeType(b);g.open("GET",a,true);g.onreadystatechange=function(){if(g.readyState==4)c(g.status<300?g:null)};g.send(null)};d3.text=function(a,b,c){if(arguments.length<3){c=b;b=null}d3.xhr(a,b,function(g){c(g&&g.responseText)})};
<ide><path>src/core/core.js
<del>d3 = {version: "0.28.9"}; // semver
<add>d3 = {version: "0.28.10"}; // semver
<ide><path>src/core/transition.js
<ide> function d3_transition(groups) {
<ide> // 1 - In progress.
<ide> // 2 - Ended.
<ide> if (stage[k]) {
<del> if (tx.active != transitionId) {
<add> if (!tx || tx.active != transitionId) {
<ide> stage[k] = 2;
<ide> return;
<ide> } | 4 |
Javascript | Javascript | add option to only see failed tests | 6733ee135867b65c4f7569ab6d09baf642df0be3 | <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js
<ide> import * as React from 'react';
<ide> import {useMemo, useState, useCallback} from 'react';
<ide> import {
<ide> Button,
<add> Switch,
<ide> View,
<ide> Text,
<ide> StyleSheet,
<ide> const DISPLAY_STATUS_MAPPING: {[PlatformTestResultStatus]: string} = {
<ide> type FilterModalProps = $ReadOnly<{
<ide> filterText: string,
<ide> setFilterText: (newFilterText: string) => void,
<add> filterFail: boolean,
<add> setFilterFail: (newFilterFail: boolean) => void,
<ide> }>;
<ide> function FilterModalButton(props: FilterModalProps) {
<del> const {filterText, setFilterText} = props;
<add> const {filterText, setFilterText, filterFail, setFilterFail} = props;
<ide>
<ide> const [modalVisible, setModalVisible] = useState(false);
<ide> const [pendingFilterText, setPendingFilterText] = useState(filterText);
<ide> function FilterModalButton(props: FilterModalProps) {
<ide> setModalVisible(false);
<ide> }, []);
<ide>
<add> const onFilterFailStatus = useCallback(
<add> value => {
<add> setFilterFail(value);
<add> },
<add> [setFilterFail],
<add> );
<add>
<ide> const onPendingTextChange = useCallback((newText: string) => {
<ide> setPendingFilterText(newText);
<ide> }, []);
<ide> function FilterModalButton(props: FilterModalProps) {
<ide> onChangeText={onPendingTextChange}
<ide> onSubmitEditing={onFilterSubmit}
<ide> />
<add> <View style={styles.filterFail}>
<add> <Text>
<add> {filterFail ? 'Filter All Status' : 'Filter Only Failed'}
<add> </Text>
<add> <Switch
<add> value={filterFail}
<add> onValueChange={onFilterFailStatus}
<add> />
<add> </View>
<ide> </View>
<ide> <View style={styles.filterModalActionsContainer}>
<ide> <Button title="Cancel" onPress={onFilterCancel} />
<ide> export default function RNTesterPlatformTestResultView(
<ide> const {numPending, reset, results, style} = props;
<ide>
<ide> const [filterText, setFilterText] = useState('');
<add> const [filterFailStatus, setFilterFailStatus] = useState(false);
<ide>
<ide> const filteredResults = useMemo(() => {
<add> const statusFiltered = filterFailStatus
<add> ? results.filter(result => result.status === 'FAIL')
<add> : results;
<add>
<ide> if (filterText === '') {
<del> return results;
<add> return statusFiltered;
<ide> }
<del> return results.filter(result =>
<add> return statusFiltered.filter(result =>
<ide> result.name.toLowerCase().includes(filterText.toLowerCase()),
<ide> );
<del> }, [filterText, results]);
<add> }, [filterFailStatus, filterText, results]);
<ide>
<ide> const {numPass, numFail, numError, numSkipped} = useMemo(
<ide> () =>
<ide> export default function RNTesterPlatformTestResultView(
<ide> const [resultsExpanded, setResultsExpanded] = useState(false);
<ide>
<ide> const handleReset = useCallback(() => {
<add> setFilterFailStatus(false);
<ide> setFilterText('');
<ide> reset();
<ide> setResultsExpanded(false);
<ide> export default function RNTesterPlatformTestResultView(
<ide> setResultsExpanded(false);
<ide> }, []);
<ide>
<add> const filteredNotice = `Filtered${filterFailStatus ? ' (Failed)' : ''}${
<add> filterText !== '' ? `: ${filterText}` : ''
<add> }
<add> `;
<add>
<ide> return (
<ide> <>
<ide> <RNTesterPlatformTestMinimizedResultView
<ide> export default function RNTesterPlatformTestResultView(
<ide> <View style={styles.resultsHeader}>
<ide> <View style={styles.titleContainer}>
<ide> <Text style={styles.title}>Results</Text>
<del> {filterText !== '' ? (
<del> <Text style={styles.filteredText}>
<del> (Filtered: '{filterText}')
<del> </Text>
<del> ) : null}
<add> <Text style={styles.filteredText}>{filteredNotice}</Text>
<ide> <Text style={styles.summaryContainer}>
<ide> <RNTesterPlatformTestResultsText
<ide> numError={numError}
<ide> export default function RNTesterPlatformTestResultView(
<ide> <FilterModalButton
<ide> filterText={filterText}
<ide> setFilterText={setFilterText}
<add> filterFail={filterFailStatus}
<add> setFilterFail={setFilterFailStatus}
<ide> />
<ide> <View style={styles.buttonSpacer} />
<ide> <Button title="Reset" onPress={handleReset} />
<ide> const styles = StyleSheet.create({
<ide> alignItems: 'center',
<ide> justifyContent: 'center',
<ide> },
<add> filterFail: {
<add> alignItems: 'center',
<add> padding: 10,
<add> flexDirection: 'row',
<add> justifyContent: 'space-between',
<add> },
<ide> passText: {
<ide> color: 'green',
<ide> }, | 1 |
Javascript | Javascript | remove thunk middleware from the core | 0b5207f4a423ab1d7cc83d0533de10904c100a8a | <ide><path>examples/counter/containers/App.js
<ide> import { createStore, applyMiddleware } from 'redux';
<ide> import { Provider } from 'react-redux';
<ide> import * as reducers from '../reducers';
<ide>
<del>const createStoreWithMiddleware = applyMiddleware()(createStore);
<add>// TODO: move into a separate project
<add>function thunk({ dispatch, getState }) {
<add> return next => action =>
<add> typeof action === 'function' ?
<add> action(dispatch, getState) :
<add> next(action);
<add>}
<add>
<add>const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
<ide> const store = createStoreWithMiddleware(reducers);
<ide>
<ide> export default class App {
<ide><path>src/utils/applyMiddleware.js
<ide> import compose from './compose';
<ide> import composeMiddleware from './composeMiddleware';
<del>import thunk from '../middleware/thunk';
<ide>
<ide> /**
<ide> * Creates a higher-order store that applies middleware to a store's dispatch.
<ide> import thunk from '../middleware/thunk';
<ide> * @return {Function} A higher-order store
<ide> */
<ide> export default function applyMiddleware(...middlewares) {
<del> const finalMiddlewares = middlewares.length ?
<del> middlewares :
<del> [thunk];
<del>
<ide> return next => (...args) => {
<ide> const store = next(...args);
<del> const middleware = composeMiddleware(...finalMiddlewares);
<add> const middleware = composeMiddleware(...middlewares);
<add>
<add> function dispatch(action) {
<add> const methods = {
<add> dispatch,
<add> getState: store.getState
<add> };
<add>
<add> return compose(
<add> middleware(methods),
<add> store.dispatch
<add> )(action);
<add> }
<ide>
<ide> return {
<ide> ...store,
<del> dispatch: function dispatch(action) {
<del> const methods = { dispatch, getState: store.getState };
<del>
<del> return compose(
<del> middleware(methods),
<del> store.dispatch
<del> )(action);
<del> }
<add> dispatch
<ide> };
<ide> };
<ide> }
<ide><path>test/applyMiddleware.spec.js
<ide> import expect from 'expect';
<ide> import { createStore, applyMiddleware } from '../src/index';
<ide> import * as reducers from './helpers/reducers';
<ide> import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators';
<del>import thunk from '../src/middleware/thunk';
<add>import { thunk } from './helpers/middleware';
<ide>
<ide> describe('applyMiddleware', () => {
<ide> it('wraps dispatch method with middleware', () => {
<ide> describe('applyMiddleware', () => {
<ide> }
<ide>
<ide> const spy = expect.createSpy(() => {});
<del>
<ide> const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos);
<ide>
<ide> return store.dispatch(addTodoAsync('Use Redux')).then(() => {
<ide> expect(spy.calls.length).toEqual(2);
<ide> });
<del>
<ide> });
<ide>
<del> it('uses thunk middleware by default', done => {
<del> const store = applyMiddleware()(createStore)(reducers.todos);
<add> it('works with thunk middleware', done => {
<add> const store = applyMiddleware(thunk)(createStore)(reducers.todos);
<ide>
<ide> store.dispatch(addTodoIfEmpty('Hello'));
<ide> expect(store.getState()).toEqual([{
<add><path>test/helpers/middleware.js
<del><path>src/middleware/thunk.js
<del>export default function thunkMiddleware({ dispatch, getState }) {
<add>export function thunk({ dispatch, getState }) {
<ide> return next => action =>
<ide> typeof action === 'function' ?
<ide> action(dispatch, getState) : | 4 |
Go | Go | add required capabilities | fcf2e9a9107c6c9aebaf63ce044f636333e7eed8 | <ide><path>daemon/execdriver/native/template/default_template.go
<ide> func New() *libcontainer.Container {
<ide> "NET_RAW",
<ide> "SETGID",
<ide> "SETUID",
<add> "SETFCAP",
<add> "SETPCAP",
<add> "NET_BIND_SERVICE",
<ide> },
<ide> Namespaces: map[string]bool{
<ide> "NEWNS": true, | 1 |
Python | Python | add test of sign ufunc removed from test_ufunclike | 73651a6ceba09729ee7a28558187ffa7e295dc22 | <ide><path>numpy/core/tests/test_umath.py
<ide> import numpy.core.umath as ncu
<ide> import numpy as np
<ide>
<add>
<ide> class TestDivision(TestCase):
<ide> def test_division_int(self):
<ide> # int division should follow Python
<ide> def test_floor_division_complex(self):
<ide> y = np.floor_divide(x**2, x)
<ide> assert_equal(y, [1.e+110, 0], err_msg=msg)
<ide>
<add>
<ide> class TestPower(TestCase):
<ide> def test_power_float(self):
<ide> x = np.array([1., 2., 3.])
<ide> def assert_complex_equal(x, y):
<ide> finally:
<ide> np.seterr(**err)
<ide>
<add>
<ide> class TestLog2(TestCase):
<ide> def test_log2_values(self) :
<ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<ide> def test_log2_values(self) :
<ide> yf = np.array(y, dtype=dt)
<ide> assert_almost_equal(np.log2(xf), yf)
<ide>
<add>
<ide> class TestExp2(TestCase):
<ide> def test_exp2_values(self) :
<ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<ide> def test_exp2_values(self) :
<ide> yf = np.array(y, dtype=dt)
<ide> assert_almost_equal(np.exp2(yf), xf)
<ide>
<add>
<ide> class TestLogAddExp2(object):
<ide> # Need test for intermediate precisions
<ide> def test_logaddexp2_values(self) :
<ide> def test_nan(self):
<ide> assert np.isnan(np.logaddexp2(0, np.nan))
<ide> assert np.isnan(np.logaddexp2(np.nan, np.nan))
<ide>
<add>
<ide> class TestLog(TestCase):
<ide> def test_log_values(self) :
<ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<ide> def test_log_values(self) :
<ide> yf = np.array(y, dtype=dt)*log2_
<ide> assert_almost_equal(np.log(xf), yf)
<ide>
<add>
<ide> class TestExp(TestCase):
<ide> def test_exp_values(self) :
<ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<ide> def test_exp_values(self) :
<ide> yf = np.array(y, dtype=dt)*log2_
<ide> assert_almost_equal(np.exp(yf), xf)
<ide>
<add>
<ide> class TestLogAddExp(object):
<ide> def test_logaddexp_values(self) :
<ide> x = [1, 2, 3, 4, 5]
<ide> def test_nan(self):
<ide> assert np.isnan(np.logaddexp(0, np.nan))
<ide> assert np.isnan(np.logaddexp(np.nan, np.nan))
<ide>
<add>
<ide> class TestLog1p(TestCase):
<ide> def test_log1p(self):
<ide> assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))
<ide> assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6))
<ide>
<add>
<ide> class TestExpm1(TestCase):
<ide> def test_expm1(self):
<ide> assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1)
<ide> assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1)
<ide>
<add>
<ide> class TestHypot(TestCase, object):
<ide> def test_simple(self):
<ide> assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2))
<ide> assert_almost_equal(ncu.hypot(0, 0), 0)
<ide>
<add>
<ide> def assert_hypot_isnan(x, y):
<ide> err = np.seterr(invalid='ignore')
<ide> try:
<ide> assert np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))
<ide> finally:
<ide> np.seterr(**err)
<ide>
<add>
<ide> def assert_hypot_isinf(x, y):
<ide> err = np.seterr(invalid='ignore')
<ide> try:
<ide> assert np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))
<ide> finally:
<ide> np.seterr(**err)
<ide>
<add>
<ide> class TestHypotSpecialValues(TestCase):
<ide> def test_nan_outputs(self):
<ide> assert_hypot_isnan(np.nan, np.nan)
<ide> def test_nan_outputs(self):
<ide> assert_hypot_isinf(np.inf, 0)
<ide> assert_hypot_isinf(0, np.inf)
<ide>
<add>
<ide> def assert_arctan2_isnan(x, y):
<ide> assert np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y))
<ide>
<add>
<ide> def assert_arctan2_ispinf(x, y):
<ide> assert (np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y))
<ide>
<add>
<ide> def assert_arctan2_isninf(x, y):
<ide> assert (np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y))
<ide>
<add>
<ide> def assert_arctan2_ispzero(x, y):
<ide> assert (ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y))
<ide>
<add>
<ide> def assert_arctan2_isnzero(x, y):
<ide> assert (ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))
<ide>
<add>
<ide> class TestArctan2SpecialValues(TestCase):
<ide> def test_one_one(self):
<ide> # atan2(1, 1) returns pi/4.
<ide> def test_nan_any(self):
<ide> assert_arctan2_isnan(np.inf, np.nan)
<ide> assert_arctan2_isnan(np.nan, np.nan)
<ide>
<add>
<ide> class TestMaximum(TestCase):
<ide> def test_reduce_complex(self):
<ide> assert_equal(np.maximum.reduce([1,2j]),1)
<ide> def test_complex_nans(self):
<ide> out = np.array([nan, nan, nan], dtype=np.complex)
<ide> assert_equal(np.maximum(arg1, arg2), out)
<ide>
<add>
<ide> class TestMinimum(TestCase):
<ide> def test_reduce_complex(self):
<ide> assert_equal(np.minimum.reduce([1,2j]),2j)
<ide> def test_complex_nans(self):
<ide> out = np.array([nan, nan, nan], dtype=np.complex)
<ide> assert_equal(np.minimum(arg1, arg2), out)
<ide>
<add>
<ide> class TestFmax(TestCase):
<ide> def test_reduce_complex(self):
<ide> assert_equal(np.fmax.reduce([1,2j]),1)
<ide> def test_complex_nans(self):
<ide> out = np.array([0, 0, nan], dtype=np.complex)
<ide> assert_equal(np.fmax(arg1, arg2), out)
<ide>
<add>
<ide> class TestFmin(TestCase):
<ide> def test_reduce_complex(self):
<ide> assert_equal(np.fmin.reduce([1,2j]),2j)
<ide> def test_complex_nans(self):
<ide> out = np.array([0, 0, nan], dtype=np.complex)
<ide> assert_equal(np.fmin(arg1, arg2), out)
<ide>
<add>
<ide> class TestFloatingPoint(TestCase):
<ide> def test_floating_point(self):
<ide> assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
<ide>
<add>
<ide> class TestDegrees(TestCase):
<ide> def test_degrees(self):
<ide> assert_almost_equal(ncu.degrees(np.pi), 180.0)
<ide> assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0)
<ide>
<add>
<ide> class TestRadians(TestCase):
<ide> def test_radians(self):
<ide> assert_almost_equal(ncu.radians(180.0), np.pi)
<ide> assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi)
<ide>
<add>
<add>class TestSign(TestCase):
<add> def test_sign(self):
<add> a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
<add> out = np.zeros(a.shape)
<add> tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
<add>
<add> olderr = np.seterr(invalid='ignore')
<add> try:
<add> res = ncu.sign(a)
<add> assert_equal(res, tgt)
<add> res = ncu.sign(a, out)
<add> assert_equal(res, tgt)
<add> assert_equal(out, tgt)
<add> finally:
<add> np.seterr(**olderr)
<add>
<add>
<ide> class TestSpecialMethods(TestCase):
<ide> def test_wrap(self):
<ide> class with_wrap(object):
<ide> def is_longdouble_finfo_bogus():
<ide> info = np.finfo(np.longcomplex)
<ide> return not np.isfinite(np.log10(info.tiny/info.eps))
<ide>
<add>
<ide> class TestComplexFunctions(object):
<ide> funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh,
<ide> np.arctanh, np.sin, np.cos, np.tan, np.exp,
<ide> def test_loss_of_precision(self):
<ide> def test_loss_of_precision_longcomplex(self):
<ide> self.check_loss_of_precision(np.longcomplex)
<ide>
<add>
<ide> class TestAttributes(TestCase):
<ide> def test_attributes(self):
<ide> add = ncu.add
<ide> def test_attributes(self):
<ide> assert_equal(add.nout, 1)
<ide> assert_equal(add.identity, 0)
<ide>
<add>
<ide> class TestSubclass(TestCase):
<ide> def test_subclass_op(self):
<ide> class simple(np.ndarray): | 1 |
Python | Python | fix unk_token test | ac27548b25ffef5966bd11c90419230cbeafe06e | <ide><path>pytorch_transformers/tokenization_gpt2.py
<ide> class GPT2Tokenizer(PreTrainedTokenizer):
<ide>
<ide> def __init__(self, vocab_file, merges_file, errors='replace', unk_token="<|endoftext|>",
<ide> bos_token="<|endoftext|>", eos_token="<|endoftext|>", **kwargs):
<del> super(GPT2Tokenizer, self).__init__(bos_token=bos_token, eos_token=eos_token, **kwargs)
<add> super(GPT2Tokenizer, self).__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, **kwargs)
<ide>
<ide> self.encoder = json.load(open(vocab_file))
<ide> self.decoder = {v:k for k,v in self.encoder.items()} | 1 |
Python | Python | replace logger.warn by logger.warning | 773314ab8070db69cdd07d615108b83259e7415d | <ide><path>src/transformers/commands/pt_to_tf.py
<ide> def run(self):
<ide> if architectures is None: # No architecture defined -- use auto classes
<ide> pt_class = getattr(import_module("transformers"), "AutoModel")
<ide> tf_class = getattr(import_module("transformers"), "TFAutoModel")
<del> self._logger.warn("No detected architecture, using AutoModel/TFAutoModel")
<add> self._logger.warning("No detected architecture, using AutoModel/TFAutoModel")
<ide> else: # Architecture defined -- use it
<ide> if len(architectures) > 1:
<ide> raise ValueError(f"More than one architecture was found, aborting. (architectures = {architectures})")
<del> self._logger.warn(f"Detected architecture: {architectures[0]}")
<add> self._logger.warning(f"Detected architecture: {architectures[0]}")
<ide> pt_class = getattr(import_module("transformers"), architectures[0])
<ide> try:
<ide> tf_class = getattr(import_module("transformers"), "TF" + architectures[0])
<ide> def run(self):
<ide> repo.git_add(auto_lfs_track=True)
<ide> repo.git_commit(commit_message)
<ide> repo.git_push(blocking=True) # this prints a progress bar with the upload
<del> self._logger.warn(f"TF weights pushed into {self._model_name}")
<add> self._logger.warning(f"TF weights pushed into {self._model_name}")
<ide> elif not self._no_pr:
<del> self._logger.warn("Uploading the weights into a new PR...")
<add> self._logger.warning("Uploading the weights into a new PR...")
<ide> commit_descrition = (
<ide> "Model converted by the [`transformers`' `pt_to_tf`"
<ide> " CLI](https://github.com/huggingface/transformers/blob/main/src/transformers/commands/pt_to_tf.py). "
<ide> def run(self):
<ide> repo_type="model",
<ide> create_pr=True,
<ide> )
<del> self._logger.warn(f"PR open in {hub_pr_url}")
<add> self._logger.warning(f"PR open in {hub_pr_url}")
<ide><path>src/transformers/utils/hub.py
<ide> def move_cache(cache_dir=None, new_cache_dir=None, token=None):
<ide>
<ide> if cache_version < 1:
<ide> if is_offline_mode():
<del> logger.warn(
<add> logger.warning(
<ide> "You are offline and the cache for model files in Transformers v4.22.0 has been updated while your local "
<ide> "cache seems to be the one of a previous version. It is very likely that all your calls to any "
<ide> "`from_pretrained()` method will fail. Remove the offline mode and enable internet connection to have "
<ide> "your cache be updated automatically, then you can go back to offline mode."
<ide> )
<ide> else:
<del> logger.warn(
<add> logger.warning(
<ide> "The cache for model files in Transformers v4.22.0 has been updated. Migrating your old cache. This is a "
<ide> "one-time only operation. You can interrupt this and resume the migration later on by calling "
<ide> "`transformers.utils.move_cache()`."
<ide> def move_cache(cache_dir=None, new_cache_dir=None, token=None):
<ide> with open(cache_version_file, "w") as f:
<ide> f.write("1")
<ide> except Exception:
<del> logger.warn(
<add> logger.warning(
<ide> f"There was a problem when trying to write in your cache folder ({TRANSFORMERS_CACHE}). You should set "
<ide> "the environment variable TRANSFORMERS_CACHE to a writable directory."
<ide> ) | 2 |
Text | Text | fix a space | 1f80d93d1b7921e35c8cfefcf7f6fbc1bb907a44 | <ide><path>share/doc/homebrew/Acceptable-Formulae.md
<ide> point it to the downloaded archive in order to avoid loading.
<ide> ### We don’t like binary formulae
<ide> Our policy is that formulae in the core repository
<ide> ([Homebrew/homebrew](https://github.com/Homebrew/homebrew)) must be built
<del>from source (or produce cross-platform binaries like e.g. Java).Binary-only
<add>from source (or produce cross-platform binaries like e.g. Java). Binary-only
<ide> formulae should go to [Homebrew/homebrew-binary](https://github.com/Homebrew/homebrew-binary).
<ide>
<ide> ### Stable versions | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.