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
PHP
PHP
return all possible form context attributes
f82b76878750e170265ce5ccf610295762882c66
<ide><path>src/View/Form/ArrayContext.php <ide> public function attributes(string $field): array <ide> if ($schema === null) { <ide> $schema = Hash::get($this->_context['schema'], $this->stripNesting($field)); <ide> } <del> $allowed = ['length' => null, 'precision' => null]; <ide> <del> return array_intersect_key((array)$schema, $allowed); <add> return (array)$schema; <ide> } <ide> <ide> /** <ide><path>src/View/Form/EntityContext.php <ide> public function attributes(string $field): array <ide> return []; <ide> } <ide> <del> $column = (array)$table->getSchema()->getColumn(array_pop($parts)); <del> $allowed = ['length' => null, 'precision' => null]; <del> <del> return array_intersect_key($column, $allowed); <add> return (array)$table->getSchema()->getColumn(array_pop($parts)); <ide> } <ide> <ide> /** <ide><path>src/View/Form/FormContext.php <ide> public function type(string $field): ?string <ide> */ <ide> public function attributes(string $field): array <ide> { <del> $column = (array)$this->_form->getSchema()->field($field); <del> $allowed = ['length' => null, 'precision' => null]; <del> <del> return array_intersect_key($column, $allowed); <add> return (array)$this->_form->getSchema()->field($field); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Form/ArrayContextTest.php <ide> public function testAttributes() <ide> ], <ide> ], <ide> ]); <del> $this->assertEquals([], $context->attributes('Comments.id')); <del> $this->assertEquals(['length' => 25], $context->attributes('Comments.0.tags')); <del> $this->assertEquals(['length' => 255], $context->attributes('Comments.comment')); <del> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('Comments.decimal')); <del> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('Comments.floaty')); <add> $this->assertEquals(['type' => 'integer'], $context->attributes('Comments.id')); <add> $this->assertEquals(['length' => 25, 'type' => 'string'], $context->attributes('Comments.0.tags')); <add> $this->assertEquals(['length' => 255, 'type' => 'string'], $context->attributes('Comments.comment')); <add> $this->assertEquals(['precision' => 2, 'length' => 5, 'type' => 'decimal'], $context->attributes('Comments.decimal')); <add> $this->assertEquals(['precision' => 2, 'length' => 5, 'type' => 'float'], $context->attributes('Comments.floaty')); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function testSchemaOnCollections($collection) <ide> $this->assertSame('string', $context->type('99.title')); <ide> $this->assertNull($context->type('0.nope')); <ide> <del> $expected = ['length' => 255, 'precision' => null]; <add> $expected = [ <add> 'length' => 255, 'precision' => null, 'type' => 'string', <add> 'null' => null, 'default' => null, 'comment' => null, 'collate' => null, <add> ]; <ide> $this->assertEquals($expected, $context->attributes('0.user.username')); <ide> } <ide> <ide> public function testAttributes() <ide> ]); <ide> <ide> $expected = [ <del> 'length' => 255, 'precision' => null, <add> 'length' => 255, 'precision' => null, 'type' => 'string', <add> 'null' => null, 'default' => null, 'comment' => null, 'collate' => null, <ide> ]; <ide> $this->assertEquals($expected, $context->attributes('title')); <ide> <ide> $expected = [ <del> 'length' => null, 'precision' => null, <add> 'length' => null, 'precision' => null, 'type' => 'crazy_text', <add> 'null' => null, 'default' => null, 'comment' => null, <ide> ]; <ide> $this->assertEquals($expected, $context->attributes('body')); <ide> <ide> $expected = [ <del> 'length' => 10, 'precision' => 3, <add> 'length' => 10, 'precision' => 3, 'type' => 'decimal', <add> 'null' => null, 'default' => null, 'comment' => null, 'unsigned' => null, <ide> ]; <ide> $this->assertEquals($expected, $context->attributes('user.rating')); <ide> <ide> $expected = [ <del> 'length' => 11, 'precision' => null, <add> 'length' => 11, 'precision' => null, 'type' => 'integer', <add> 'null' => false, 'default' => null, 'comment' => null, 'unsigned' => null, 'autoIncrement' => null, <ide> ]; <ide> $this->assertEquals($expected, $context->attributes('tags.0._joinData.article_id')); <ide> } <ide><path>tests/TestCase/View/Form/FormContextTest.php <ide> public function testAttributes() <ide> 'entity' => $form, <ide> ]); <ide> $this->assertEquals([], $context->attributes('id')); <del> $this->assertEquals(['length' => 10, 'precision' => null], $context->attributes('email')); <del> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('amount')); <add> $this->assertEquals( <add> ['length' => 10, 'precision' => null, 'type' => 'string', 'default' => null], <add> $context->attributes('email') <add> ); <add> $this->assertEquals( <add> ['precision' => 2, 'length' => 5, 'type' => 'decimal', 'default' => null], <add> $context->attributes('amount') <add> ); <ide> } <ide> <ide> /**
6
Text
Text
fix a typo on the engine guide
20985257a1866e29b7251a218aca275d886939df
<ide><path>guides/source/engines.md <ide> def create <ide> @post = Post.find(params[:post_id]) <ide> @comment = @post.comments.create(params[:comment]) <ide> flash[:notice] = "Comment has been created!" <del> redirect_to post_path <add> redirect_to posts_path <ide> end <ide> ``` <ide>
1
Mixed
Javascript
add string shortcut for fork stdio
3268863ebc40d1f0beee61b044c492b43fa57fa5
<ide><path>doc/api/child_process.md <ide> added: v0.5.0 <ide> piped to the parent, otherwise they will be inherited from the parent, see <ide> the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s <ide> [`stdio`][] for more details (Default: `false`) <del> * `stdio` {Array} Supports the array version of [`child_process.spawn()`][]'s <del> [`stdio`][] option. When this option is provided, it overrides `silent`. <del> The array must contain exactly one item with value `'ipc'` or an error will <del> be thrown. For instance `[0, 1, 2, 'ipc']`. <add> * `stdio` {Array|String} See [`child_process.spawn()`][]'s [`stdio`][]. <add> When this option is provided, it overrides `silent`. If the array variant <add> is used, it must contain exactly one item with value `'ipc'` or an error <add> will be thrown. For instance `[0, 1, 2, 'ipc']`. <ide> * `uid` {Number} Sets the user identity of the process. (See setuid(2).) <ide> * `gid` {Number} Sets the group identity of the process. (See setgid(2).) <ide> * Returns: {ChildProcess} <ide><path>lib/child_process.js <ide> const _validateStdio = child_process._validateStdio; <ide> const setupChannel = child_process.setupChannel; <ide> const ChildProcess = exports.ChildProcess = child_process.ChildProcess; <ide> <add>function stdioStringToArray(option) { <add> return [option, option, option, 'ipc']; <add>} <add> <ide> exports.fork = function(modulePath /*, args, options*/) { <ide> <ide> // Get options and args arguments. <ide> exports.fork = function(modulePath /*, args, options*/) { <ide> <ide> args = execArgv.concat([modulePath], args); <ide> <del> if (!Array.isArray(options.stdio)) { <add> if (typeof options.stdio === 'string') { <add> switch (options.stdio) { <add> case 'ignore': <add> case 'pipe': <add> case 'inherit': <add> options.stdio = stdioStringToArray(options.stdio); <add> break; <add> default: <add> throw new TypeError('Unknown stdio option'); <add> } <add> } else if (!Array.isArray(options.stdio)) { <ide> // Use a separate fd=3 for the IPC channel. Inherit stdin, stdout, <ide> // and stderr from the parent if silent isn't set. <del> options.stdio = options.silent ? ['pipe', 'pipe', 'pipe', 'ipc'] : <del> [0, 1, 2, 'ipc']; <add> options.stdio = options.silent ? stdioStringToArray('pipe') : <add> stdioStringToArray('inherit'); <ide> } else if (options.stdio.indexOf('ipc') === -1) { <ide> throw new TypeError('Forked processes must have an IPC channel'); <ide> } <ide><path>test/parallel/test-child-process-fork-stdio-string-variant.js <add>'use strict'; <add>const common = require('../common'); <add> <add>// Ensures that child_process.fork can accept string <add>// variant of stdio parameter in options object and <add>// throws a TypeError when given an unexpected string <add> <add>const assert = require('assert'); <add>const fork = require('child_process').fork; <add> <add>const childScript = `${common.fixturesDir}/child-process-spawn-node`; <add>const errorRegexp = /^TypeError: Unknown stdio option$/; <add>const malFormedOpts = {stdio: '33'}; <add>const payload = {hello: 'world'}; <add>const stringOpts = {stdio: 'pipe'}; <add> <add>assert.throws(() => fork(childScript, malFormedOpts), errorRegexp); <add> <add>const child = fork(childScript, stringOpts); <add> <add>child.on('message', (message) => { <add> assert.deepStrictEqual(message, {foo: 'bar'}); <add>}); <add> <add>child.send(payload); <add> <add>child.on('exit', common.mustCall((code) => assert.strictEqual(code, 0)));
3
Ruby
Ruby
add failing test for where with joins
b42e594a43e00d00b018868481927584d358f756
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb <ide> def test_with_polymorphic_has_one_with_custom_columns_name <ide> class SpecialBook < ActiveRecord::Base <ide> self.table_name = "books" <ide> belongs_to :author, class_name: "SpecialAuthor" <add> has_one :subscription, class_name: "SpecialSupscription", foreign_key: "subscriber_id" <ide> end <ide> <ide> class SpecialAuthor < ActiveRecord::Base <ide> self.table_name = "authors" <ide> has_one :book, class_name: "SpecialBook", foreign_key: "author_id" <ide> end <ide> <add> class SpecialSupscription < ActiveRecord::Base <add> self.table_name = "subscriptions" <add> belongs_to :book, class_name: "SpecialBook" <add> end <add> <ide> def test_assocation_enum_works_properly <ide> author = SpecialAuthor.create!(name: "Test") <ide> book = SpecialBook.create!(status: "published") <ide> author.book = book <ide> <ide> refute_equal 0, SpecialAuthor.joins(:book).where(books: { status: "published" }).count <ide> end <add> <add> def test_assocation_enum_works_properly_with_nested_join <add> author = SpecialAuthor.create!(name: "Test") <add> book = SpecialBook.create!(status: "published") <add> author.book = book <add> <add> where_clause = { books: { subscriptions: { subscriber_id: nil } } } <add> assert_nothing_raised do <add> SpecialAuthor.joins(book: :subscription).where.not(where_clause) <add> end <add> end <ide> end
1
Javascript
Javascript
add helper to decode the debug hash when needed
e320176d4d099d2408f5bb573fda9a0d06c09d45
<ide><path>tooling/decode-debug-hash.js <add>const fs = require("fs"); <add> <add>const file = process.argv[2]; <add> <add>let content = fs.readFileSync(file, "utf-8"); <add>content = content.replace(/debug-digest-([a-f0-9]+)/g, (match, bin) => { <add> return Buffer.from(bin, "hex").toString("utf-8"); <add>}); <add> <add>fs.writeFileSync(file, content);
1
Python
Python
add labels param to google mlengine operators
c29533888fadd40f5e9ce63e728bd8691182e542
<ide><path>airflow/providers/google/cloud/example_dags/example_mlengine.py <ide> package_uris=[TRAINER_URI], <ide> training_python_module=TRAINER_PY_MODULE, <ide> training_args=[], <add> labels={"job_type": "training"}, <ide> ) <ide> # [END howto_operator_gcp_mlengine_training] <ide> <ide> data_format="TEXT", <ide> input_paths=[PREDICTION_INPUT], <ide> output_path=PREDICTION_OUTPUT, <add> labels={"job_type": "prediction"}, <ide> ) <ide> # [END howto_operator_gcp_mlengine_get_prediction] <ide> <ide><path>airflow/providers/google/cloud/operators/mlengine.py <ide> import logging <ide> import re <ide> import warnings <del>from typing import List, Optional <add>from typing import Dict, List, Optional <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.models import BaseOperator, BaseOperatorLink <ide> class MLEngineStartBatchPredictionJobOperator(BaseOperator): <ide> For this to work, the service account making the request must <ide> have domain-wide delegation enabled. <ide> :type delegate_to: str <add> :param labels: a dictionary containing labels for the job; passed to BigQuery <add> :type labels: Dict[str, str] <ide> :raises: ``ValueError``: if a unique model/version origin cannot be <ide> determined. <ide> """ <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> project_id: Optional[str] = None, <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <add> labels: Optional[Dict[str, str]] = None, <ide> **kwargs) -> None: <ide> super().__init__(**kwargs) <ide> <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> self._signature_name = signature_name <ide> self._gcp_conn_id = gcp_conn_id <ide> self._delegate_to = delegate_to <add> self._labels = labels <ide> <ide> if not self._project_id: <ide> raise AirflowException('Google Cloud project id is required.') <ide> def execute(self, context): <ide> 'region': self._region <ide> } <ide> } <add> if self._labels: <add> prediction_request['labels'] = self._labels <ide> <ide> if self._uri: <ide> prediction_request['predictionInput']['uri'] = self._uri <ide> class MLEngineStartTrainingJobOperator(BaseOperator): <ide> will be printed out. In 'CLOUD' mode, a real MLEngine training job <ide> creation request will be issued. <ide> :type mode: str <add> :param labels: a dictionary containing labels for the job; passed to BigQuery <add> :type labels: Dict[str, str] <ide> """ <ide> <ide> template_fields = [ <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <ide> mode: str = 'PRODUCTION', <add> labels: Optional[Dict[str, str]] = None, <ide> **kwargs) -> None: <ide> super().__init__(**kwargs) <ide> self._project_id = project_id <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> self._gcp_conn_id = gcp_conn_id <ide> self._delegate_to = delegate_to <ide> self._mode = mode <add> self._labels = labels <ide> <ide> if not self._project_id: <ide> raise AirflowException('Google Cloud project id is required.') <ide> def execute(self, context): <ide> 'args': self._training_args, <ide> } <ide> } <add> if self._labels: <add> training_request['labels'] = self._labels <ide> <ide> if self._runtime_version: <ide> training_request['trainingInput']['runtimeVersion'] = self._runtime_version <ide><path>tests/providers/google/cloud/operators/test_mlengine.py <ide> class TestMLEngineBatchPredictionOperator(unittest.TestCase): <ide> } <ide> SUCCESS_MESSAGE_MISSING_INPUT = { <ide> 'jobId': 'test_prediction', <add> 'labels': {'some': 'labels'}, <ide> 'predictionOutput': { <ide> 'outputPath': 'gs://fake-output-path', <ide> 'predictionCount': 5000, <ide> class TestMLEngineBatchPredictionOperator(unittest.TestCase): <ide> BATCH_PREDICTION_DEFAULT_ARGS = { <ide> 'project_id': 'test-project', <ide> 'job_id': 'test_prediction', <add> 'labels': {'some': 'labels'}, <ide> 'region': 'us-east1', <ide> 'data_format': 'TEXT', <ide> 'input_paths': ['gs://legal-bucket-dash-Capital/legal-input-path/*'], <ide> def test_success_with_model(self, mock_hook): <ide> input_paths=input_with_model['inputPaths'], <ide> output_path=input_with_model['outputPath'], <ide> model_name=input_with_model['modelName'].split('/')[-1], <add> labels={'some': 'labels'}, <ide> dag=self.dag, <ide> task_id='test-prediction') <ide> prediction_output = prediction_task.execute(None) <ide> def test_success_with_model(self, mock_hook): <ide> project_id='test-project', <ide> job={ <ide> 'jobId': 'test_prediction', <add> 'labels': {'some': 'labels'}, <ide> 'predictionInput': input_with_model <ide> }, <ide> use_existing_job_fn=ANY <ide> class TestMLEngineTrainingOperator(unittest.TestCase): <ide> 'training_args': '--some_arg=\'aaa\'', <ide> 'region': 'us-east1', <ide> 'scale_tier': 'STANDARD_1', <add> 'labels': {'some': 'labels'}, <ide> 'task_id': 'test-training', <ide> 'start_date': days_ago(1) <ide> } <ide> TRAINING_INPUT = { <ide> 'jobId': 'test_training', <add> 'labels': {'some': 'labels'}, <ide> 'trainingInput': { <ide> 'scaleTier': 'STANDARD_1', <ide> 'packageUris': ['gs://some-bucket/package1'],
3
PHP
PHP
remove cruft related to csrf protection token
6091811e6d66b48bceda05c285f4f42974003cdd
<ide><path>src/Controller/Component/SecurityComponent.php <ide> protected function _fieldsList(array $check): array <ide> if (strpos($token, ':')) { <ide> [$token, $locked] = explode(':', $token, 2); <ide> } <del> unset($check['_Token'], $check['_csrfToken']); <add> unset($check['_Token']); <ide> <ide> $locked = explode('|', $locked); <ide> $unlocked = explode('|', $unlocked); <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testValidatePostIgnoresCsrfToken(): void <ide> $debug = 'not used'; <ide> <ide> $this->Controller->setRequest($this->Controller->getRequest()->withParsedBody([ <del> '_csrfToken' => 'abc123', <ide> 'Model' => ['multi_field' => ['1', '3']], <ide> '_Token' => compact('fields', 'unlocked', 'debug'), <ide> ]));
2
Python
Python
restore tests for beam parser
de7e8703e35f1e0d6090e2e4ce81779e8e17e03f
<ide><path>spacy/tests/parser/test_neural_parser.py <ide> def test_predict_doc_beam(parser, tok2vec, model, doc): <ide> parser(doc, beam_width=32, beam_density=0.001) <ide> for word in doc: <ide> print(word.text, word.head, word.dep_) <add> <add> <add>def test_update_doc_beam(parser, tok2vec, model, doc, gold): <add> parser.model = model <add> tokvecs, bp_tokvecs = tok2vec.begin_update([doc]) <add> d_tokvecs = parser.update_beam(([doc], tokvecs), [gold]) <add> assert d_tokvecs[0].shape == tokvecs[0].shape <add> def optimize(weights, gradient, key=None): <add> weights -= 0.001 * gradient <add> bp_tokvecs(d_tokvecs, sgd=optimize) <add> assert d_tokvecs[0].sum() == 0. <add> <add> <ide><path>spacy/tests/parser/test_nn_beam.py <add>from __future__ import unicode_literals <add>import pytest <add>import numpy <add>from thinc.api import layerize <add> <add>from ...vocab import Vocab <add>from ...syntax.arc_eager import ArcEager <add>from ...tokens import Doc <add>from ...gold import GoldParse <add>from ...syntax._beam_utils import ParserBeam, update_beam <add>from ...syntax.stateclass import StateClass <add> <add> <add>@pytest.fixture <add>def vocab(): <add> return Vocab() <add> <add>@pytest.fixture <add>def moves(vocab): <add> aeager = ArcEager(vocab.strings, {}) <add> aeager.add_action(2, 'nsubj') <add> aeager.add_action(3, 'dobj') <add> aeager.add_action(2, 'aux') <add> return aeager <add> <add> <add>@pytest.fixture <add>def docs(vocab): <add> return [Doc(vocab, words=['Rats', 'bite', 'things'])] <add> <add>@pytest.fixture <add>def states(docs): <add> return [StateClass(doc) for doc in docs] <add> <add>@pytest.fixture <add>def tokvecs(docs, vector_size): <add> output = [] <add> for doc in docs: <add> vec = numpy.random.uniform(-0.1, 0.1, (len(doc), vector_size)) <add> output.append(numpy.asarray(vec)) <add> return output <add> <add> <add>@pytest.fixture <add>def golds(docs): <add> return [GoldParse(doc) for doc in docs] <add> <add> <add>@pytest.fixture <add>def batch_size(docs): <add> return len(docs) <add> <add> <add>@pytest.fixture <add>def beam_width(): <add> return 4 <add> <add> <add>@pytest.fixture <add>def vector_size(): <add> return 6 <add> <add> <add>@pytest.fixture <add>def beam(moves, states, golds, beam_width): <add> return ParserBeam(moves, states, golds, width=beam_width) <add> <add>@pytest.fixture <add>def scores(moves, batch_size, beam_width): <add> return [ <add> numpy.asarray( <add> numpy.random.uniform(-0.1, 0.1, (batch_size, moves.n_moves)), <add> dtype='f') <add> for _ in range(batch_size)] <add> <add> <add>def test_create_beam(beam): <add> pass <add> <add> <add>def test_beam_advance(beam, scores): <add> beam.advance(scores) <add> <add> <add>def test_beam_advance_too_few_scores(beam, scores): <add> with pytest.raises(IndexError): <add> beam.advance(scores[:-1])
2
PHP
PHP
change some syntax
19317c9a545c58d8274df23da96c0d2a9c261fc6
<ide><path>src/Illuminate/Console/Scheduling/Schedule.php <ide> public function call($callback, array $parameters = array()) <ide> * @param string $command <ide> * @return \Illuminate\Console\Scheduling\Event <ide> */ <del> public function artisan($command) <add> public function command($command) <ide> { <del> return $this->command(PHP_BINARY.' artisan '.$command); <add> return $this->exec(PHP_BINARY.' artisan '.$command); <ide> } <ide> <ide> /** <ide> public function artisan($command) <ide> * @param string $command <ide> * @return \Illuminate\Console\Scheduling\Event <ide> */ <del> public function command($command) <add> public function exec($command) <ide> { <ide> $this->events[] = $event = new Event($command); <ide>
1
Ruby
Ruby
change gid calls to to_gid
a7dbfcf532650118a7522cb02e696188bb53ef50
<ide><path>activejob/test/cases/parameters_test.rb <ide> class ParameterSerializationTest < ActiveSupport::TestCase <ide> end <ide> <ide> test 'should dive deep into arrays or hashes' do <del> assert_equal [ { "a" => Person.find(5).gid.to_s }.with_indifferent_access ], ActiveJob::Arguments.serialize([ { a: Person.find(5) } ]) <del> assert_equal [ [ Person.find(5).gid.to_s ] ], ActiveJob::Arguments.serialize([ [ Person.find(5) ] ]) <add> assert_equal [ { "a" => Person.find(5).to_gid.to_s }.with_indifferent_access ], ActiveJob::Arguments.serialize([ { a: Person.find(5) } ]) <add> assert_equal [ [ Person.find(5).to_gid.to_s ] ], ActiveJob::Arguments.serialize([ [ Person.find(5) ] ]) <ide> end <ide> <ide> test 'should dive deep into arrays or hashes and raise exception on complex objects' do <ide> class ParameterSerializationTest < ActiveSupport::TestCase <ide> end <ide> <ide> test 'should serialize records with global id' do <del> assert_equal [ Person.find(5).gid.to_s ], ActiveJob::Arguments.serialize([ Person.find(5) ]) <add> assert_equal [ Person.find(5).to_gid.to_s ], ActiveJob::Arguments.serialize([ Person.find(5) ]) <ide> end <ide> <ide> test 'should serialize values and records together' do <del> assert_equal [ 3, Person.find(5).gid.to_s ], ActiveJob::Arguments.serialize([ 3, Person.find(5) ]) <add> assert_equal [ 3, Person.find(5).to_gid.to_s ], ActiveJob::Arguments.serialize([ 3, Person.find(5) ]) <ide> end <ide> end <ide> <ide> class ParameterDeserializationTest < ActiveSupport::TestCase <ide> end <ide> <ide> test 'should deserialize records with global id' do <del> assert_equal [ Person.find(5) ], ActiveJob::Arguments.deserialize([ Person.find(5).gid ]) <add> assert_equal [ Person.find(5) ], ActiveJob::Arguments.deserialize([ Person.find(5).to_gid ]) <ide> end <ide> <ide> test 'should serialize values and records together' do <del> assert_equal [ 3, Person.find(5) ], ActiveJob::Arguments.deserialize([ 3, Person.find(5).gid ]) <add> assert_equal [ 3, Person.find(5) ], ActiveJob::Arguments.deserialize([ 3, Person.find(5).to_gid ]) <ide> end <ide> <ide> test 'should dive deep when deserialising arrays' do <del> assert_equal [ [ 3, Person.find(5) ] ], ActiveJob::Arguments.deserialize([ [ 3, Person.find(5).gid ] ]) <add> assert_equal [ [ 3, Person.find(5) ] ], ActiveJob::Arguments.deserialize([ [ 3, Person.find(5).to_gid ] ]) <ide> end <ide> <ide> test 'should dive deep when deserialising hashes' do <del> assert_equal [ { "5" => Person.find(5) } ], ActiveJob::Arguments.deserialize([ { "5" => Person.find(5).gid } ]) <add> assert_equal [ { "5" => Person.find(5) } ], ActiveJob::Arguments.deserialize([ { "5" => Person.find(5).to_gid } ]) <ide> end <ide> <ide> end
1
Python
Python
remove unused old test
fa8f67596daa1a658ddabceea07b346e9c4ad375
<ide><path>spacy/tests/spans/test_times.py <del>from __future__ import unicode_literals <del> <del>import pytest <del> <del># This approach is deprecated for now <del># <del>#@pytest.mark.models <del>#def test_am_pm(en_nlp): <del># numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] <del># variants = ['a.m.', 'am', 'p.m.', 'pm'] <del># spaces = ['', ' '] <del># for num in numbers: <del># for var in variants: <del># for space in spaces: <del># string = u"The meeting was at %s%s%s wasn't it?" % (num, space, var) <del># tokens = en_nlp(string, merge_mwes=True) <del># assert tokens[4].orth_ == '%s%s%s' % (num, space, var) <del># ents = list(tokens.ents) <del># assert len(ents) == 1, ents <del># assert ents[0].label_ == 'TIME', string <del># if ents[0].start == 4 and ents[0].end == 5: <del># assert ents[0].orth_ == '%s%s%s' % (num, space, var)
1
Go
Go
fix exec form of healthcheck cmd
e95b6b51daed868094c7b66113381d5088e831b4
<ide><path>builder/dockerfile/parser/line_parsers.go <ide> func parseHealthConfig(rest string, d *Directive) (*Node, map[string]bool, error <ide> return nil, nil, err <ide> } <ide> <del> return &Node{Value: typ, Next: cmd, Attributes: attrs}, nil, err <add> return &Node{Value: typ, Next: cmd}, attrs, err <ide> } <ide><path>integration-cli/docker_cli_health_test.go <ide> func (s *DockerSuite) TestHealth(c *check.C) { <ide> c.Check(last.ExitCode, checker.Equals, -1) <ide> c.Check(last.Output, checker.Equals, "Health check exceeded timeout (1ms)") <ide> dockerCmd(c, "rm", "-f", "test") <add> <add> // Check JSON-format <add> _, err = buildImage(imageName, <add> `FROM busybox <add> RUN echo OK > /status <add> CMD ["/bin/sleep", "120"] <add> STOPSIGNAL SIGKILL <add> HEALTHCHECK --interval=1s --timeout=30s \ <add> CMD ["cat", "/my status"]`, <add> true) <add> c.Check(err, check.IsNil) <add> out, _ = dockerCmd(c, "inspect", <add> "--format={{.Config.Healthcheck.Test}}", imageName) <add> c.Check(out, checker.Equals, "[CMD cat /my status]\n") <add> <ide> }
2
PHP
PHP
use better exception
79c3905a595e328d9df83005e8f3b15b3999028c
<ide><path>src/View/Helper/PaginatorHelper.php <ide> use Cake\View\Helper; <ide> use Cake\View\StringTemplateTrait; <ide> use Cake\View\View; <del>use RuntimeException; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * Pagination Helper class for easy generation of pagination links. <ide> public function hasNext($model = null) <ide> * @param string|null $model Optional model name. Uses the default if none is specified. <ide> * @return bool True if the given result set has the specified page number. <ide> * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state <del> * @throws \RuntimeException <add> * @throws \InvalidArgumentException <ide> */ <ide> public function hasPage($page = 1, $model = null) <ide> { <ide> if (!is_numeric($page)) { <del> throw new RuntimeException('First argument "page" has to be int. Note that argument order switched from 3.x to 4.x.'); <add> throw new InvalidArgumentException('First argument "page" has to be int. Note that argument order switched from 3.x to 4.x.'); <ide> } <ide> <ide> $paging = $this->params($model);
1
Javascript
Javascript
use custom element on text editor element
510d04bffe34d2ff5102920316f6501572055110
<ide><path>spec/text-editor-element-spec.js <ide> describe('TextEditorElement', () => { <ide> }); <ide> <ide> function buildTextEditorElement(options = {}) { <del> const element = new TextEditorElement(); <add> const element = TextEditorElement.createTextEditorElement(); <ide> element.setUpdatedSynchronously(false); <ide> if (options.attach !== false) jasmine.attachToDOM(element); <ide> return element; <ide><path>src/text-editor-component.js <ide> module.exports = class TextEditorComponent { <ide> } else { <ide> if (!TextEditorElement) <ide> TextEditorElement = require('./text-editor-element'); <del> this.element = new TextEditorElement(); <add> this.element = TextEditorElement.createTextEditorElement(); <ide> } <ide> this.element.initialize(this); <ide> this.virtualNode = $('atom-text-editor'); <ide><path>src/text-editor-element.js <ide> class TextEditorElement extends HTMLElement { <ide> return this; <ide> } <ide> <del> createdCallback() { <add> constructor() { <add> super(); <ide> this.emitter = new Emitter(); <ide> this.initialText = this.textContent; <ide> if (this.tabIndex == null) this.tabIndex = -1; <ide> class TextEditorElement extends HTMLElement { <ide> this.addEventListener('blur', event => this.getComponent().didBlur(event)); <ide> } <ide> <del> attachedCallback() { <add> connectedCallback() { <ide> this.getComponent().didAttach(); <ide> this.emitter.emit('did-attach'); <ide> } <ide> <del> detachedCallback() { <add> disconnectedCallback() { <ide> this.emitter.emit('did-detach'); <ide> this.getComponent().didDetach(); <ide> } <ide> <add> static get observedAttributes() { <add> return ['mini', 'placeholder-text', 'gutter-hidden', 'readonly']; <add> } <add> <ide> attributeChangedCallback(name, oldValue, newValue) { <ide> if (this.component) { <ide> switch (name) { <ide> class TextEditorElement extends HTMLElement { <ide> getFirstVisibleScreenColumn() { <ide> return this.getModel().getFirstVisibleScreenColumn(); <ide> } <add> <add> static createTextEditorElement() { <add> return document.createElement('atom-text-editor'); <add> } <ide> } <ide> <del>module.exports = document.registerElement('atom-text-editor', { <del> prototype: TextEditorElement.prototype <del>}); <add>window.customElements.define('atom-text-editor', TextEditorElement); <add> <add>module.exports = TextEditorElement;
3
Javascript
Javascript
change @param to use valid types
f296e2ee12bb60f9ff988d2be4fbe9ec7c5dc42f
<ide><path>src/ng/animate.js <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @function <ide> * @description Inserts the element into the DOM either after the `after` element or within <ide> * the `parent` element. Once complete, the done() callback will be fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will be inserted into the DOM <del> * @param {jQuery/jqLite element} parent the parent element which will append the element as <add> * @param {DOMElement} element the element which will be inserted into the DOM <add> * @param {DOMElement} parent the parent element which will append the element as <ide> * a child (if the after element is not present) <del> * @param {jQuery/jqLite element} after the sibling element which will append the element <add> * @param {DOMElement} after the sibling element which will append the element <ide> * after itself <ide> * @param {function=} done callback function that will be called after the element has been <ide> * inserted into the DOM <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @function <ide> * @description Removes the element from the DOM. Once complete, the done() callback will be <ide> * fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will be removed from the DOM <add> * @param {DOMElement} element the element which will be removed from the DOM <ide> * @param {function=} done callback function that will be called after the element has been <ide> * removed from the DOM <ide> */ <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * either after the `after` element or inside of the `parent` element. Once complete, the <ide> * done() callback will be fired (if provided). <ide> * <del> * @param {jQuery/jqLite element} element the element which will be moved around within the <add> * @param {DOMElement} element the element which will be moved around within the <ide> * DOM <del> * @param {jQuery/jqLite element} parent the parent element where the element will be <add> * @param {DOMElement} parent the parent element where the element will be <ide> * inserted into (if the after element is not present) <del> * @param {jQuery/jqLite element} after the sibling element where the element will be <add> * @param {DOMElement} after the sibling element where the element will be <ide> * positioned next to <ide> * @param {function=} done the callback function (if provided) that will be fired after the <ide> * element has been moved to its new position <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @function <ide> * @description Adds the provided className CSS class value to the provided element. Once <ide> * complete, the done() callback will be fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will have the className value <add> * @param {DOMElement} element the element which will have the className value <ide> * added to it <ide> * @param {string} className the CSS class which will be added to the element <ide> * @param {function=} done the callback function (if provided) that will be fired after the <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @function <ide> * @description Removes the provided className CSS class value from the provided element. <ide> * Once complete, the done() callback will be fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will have the className value <add> * @param {DOMElement} element the element which will have the className value <ide> * removed from it <ide> * @param {string} className the CSS class which will be removed from the element <ide> * @param {function=} done the callback function (if provided) that will be fired after the <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @function <ide> * @description Adds and/or removes the given CSS classes to and from the element. <ide> * Once complete, the done() callback will be fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will it's CSS classes changed <add> * @param {DOMElement} element the element which will it's CSS classes changed <ide> * removed from it <ide> * @param {string} add the CSS classes which will be added to the element <ide> * @param {string} remove the CSS class which will be removed from the element <ide><path>src/ngAnimate/animate.js <ide> angular.module('ngAnimate', ['ng']) <ide> * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <ide> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | <ide> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation <del> * @param {jQuery/jqLite element} parentElement the parent element of the element that will be the focus of the enter animation <del> * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation <add> * @param {DOMElement} element the element that will be the focus of the enter animation <add> * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation <add> * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation <ide> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> enter : function(element, parentElement, afterElement, doneCallback) { <ide> angular.module('ngAnimate', ['ng']) <ide> * | 9. The element is removed from the DOM | ... | <ide> * | 10. The doneCallback() callback is fired (if provided) | ... | <ide> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation <add> * @param {DOMElement} element the element that will be the focus of the leave animation <ide> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> leave : function(element, doneCallback) { <ide> angular.module('ngAnimate', ['ng']) <ide> * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <ide> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | <ide> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the move animation <del> * @param {jQuery/jqLite element} parentElement the parentElement element of the element that will be the focus of the move animation <del> * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation <add> * @param {DOMElement} element the element that will be the focus of the move animation <add> * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation <add> * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation <ide> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> move : function(element, parentElement, afterElement, doneCallback) { <ide> angular.module('ngAnimate', ['ng']) <ide> * | 9. The super class is kept on the element | class="my-animation super" | <ide> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | <ide> * <del> * @param {jQuery/jqLite element} element the element that will be animated <add> * @param {DOMElement} element the element that will be animated <ide> * @param {string} className the CSS class that will be added to the element and then animated <ide> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> angular.module('ngAnimate', ['ng']) <ide> * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | <ide> * <ide> * <del> * @param {jQuery/jqLite element} element the element that will be animated <add> * @param {DOMElement} element the element that will be animated <ide> * @param {string} className the CSS class that will be animated and then removed from the element <ide> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> angular.module('ngAnimate', ['ng']) <ide> * @function <ide> * @description Adds and/or removes the given CSS classes to and from the element. <ide> * Once complete, the done() callback will be fired (if provided). <del> * @param {jQuery/jqLite element} element the element which will it's CSS classes changed <add> * @param {DOMElement} element the element which will it's CSS classes changed <ide> * removed from it <ide> * @param {string} add the CSS classes which will be added to the element <ide> * @param {string} remove the CSS class which will be removed from the element
2
Go
Go
add event logs for pause/unpuase
e1ec91fc582f10d57025e39f0f7e7d6695f7454e
<ide><path>integration-cli/docker_cli_events_test.go <ide> package main <ide> <ide> import ( <add> "fmt" <ide> "os/exec" <ide> "strings" <ide> "testing" <add> "time" <ide> ) <ide> <del>func TestCLIGetEvents(t *testing.T) { <add>func TestCLIGetEventsUntag(t *testing.T) { <ide> out, _, _ := cmd(t, "images", "-q") <ide> image := strings.Split(out, "\n")[0] <ide> cmd(t, "tag", image, "utest:tag1") <ide> func TestCLIGetEvents(t *testing.T) { <ide> } <ide> logDone("events - untags are logged") <ide> } <add> <add>func TestCLIGetEventsPause(t *testing.T) { <add> out, _, _ := cmd(t, "images", "-q") <add> image := strings.Split(out, "\n")[0] <add> cmd(t, "run", "-d", "--name", "testeventpause", image, "sleep", "2") <add> cmd(t, "pause", "testeventpause") <add> cmd(t, "unpause", "testeventpause") <add> eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", time.Now().Unix())) <add> out, _, _ = runCommandWithOutput(eventsCmd) <add> events := strings.Split(out, "\n") <add> if len(events) <= 1 { <add> t.Fatalf("Missing expected event") <add> } <add> <add> pauseEvent := strings.Fields(events[len(events)-3]) <add> unpauseEvent := strings.Fields(events[len(events)-2]) <add> <add> if pauseEvent[len(pauseEvent)-1] != "pause" { <add> t.Fatalf("event should be pause, not %#v", pauseEvent) <add> } <add> if unpauseEvent[len(unpauseEvent)-1] != "unpause" { <add> t.Fatalf("event should be pause, not %#v", unpauseEvent) <add> } <add> <add> logDone("events - pause/unpause is logged") <add>} <ide><path>server/server.go <ide> func (srv *Server) ContainerPause(job *engine.Job) engine.Status { <ide> if err := container.Pause(); err != nil { <ide> return job.Errorf("Cannot pause container %s: %s", name, err) <ide> } <add> srv.LogEvent("pause", container.ID, srv.daemon.Repositories().ImageName(container.Image)) <ide> return engine.StatusOK <ide> } <ide> <ide> func (srv *Server) ContainerUnpause(job *engine.Job) engine.Status { <ide> if err := container.Unpause(); err != nil { <ide> return job.Errorf("Cannot unpause container %s: %s", name, err) <ide> } <add> srv.LogEvent("unpause", container.ID, srv.daemon.Repositories().ImageName(container.Image)) <ide> return engine.StatusOK <ide> } <ide>
2
Ruby
Ruby
fix argument order in test_comparableset
646102c31118144545127b7ed70512de753d1d40
<ide><path>Library/Homebrew/test/test_comparableset.rb <ide> def setup <ide> def test_merging_multiple_dependencies <ide> @set << X11Dependency.new <ide> @set << X11Dependency.new <del> assert_equal @set.count, 1 <add> assert_equal 1, @set.count <ide> @set << Requirement.new <del> assert_equal @set.count, 2 <add> assert_equal 2, @set.count <ide> end <ide> <ide> def test_comparison_prefers_larger <ide> @set << X11Dependency.new <ide> @set << X11Dependency.new('x11', '2.6') <del> assert_equal @set.count, 1 <del> assert_equal @set.to_a, [X11Dependency.new('x11', '2.6')] <add> assert_equal 1, @set.count <add> assert_equal [X11Dependency.new('x11', '2.6')], @set.to_a <ide> end <ide> <ide> def test_comparison_does_not_merge_smaller <ide> @set << X11Dependency.new('x11', '2.6') <ide> @set << X11Dependency.new <del> assert_equal @set.count, 1 <del> assert_equal @set.to_a, [X11Dependency.new('x11', '2.6')] <add> assert_equal 1, @set.count <add> assert_equal [X11Dependency.new('x11', '2.6')], @set.to_a <ide> end <ide> <ide> def test_merging_sets <ide> def test_merging_sets <ide> reqs = Set.new [X11Dependency.new('x11', '2.6'), Requirement.new] <ide> assert_same @set, @set.merge(reqs) <ide> <del> assert_equal @set.count, 2 <del> assert_equal @set.find {|r| r.is_a? X11Dependency}, X11Dependency.new('x11', '2.6') <add> assert_equal 2, @set.count <add> assert_equal X11Dependency.new('x11', '2.6'), @set.find {|r| r.is_a? X11Dependency} <ide> end <ide> end
1
Javascript
Javascript
parse numbers correctly
a89f5c21562fe75b083a270090eadfbe318e5954
<ide><path>lib/querystring.js <ide> var hexTable = new Array(256); <ide> for (var i = 0; i < 256; ++i) <ide> hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); <ide> QueryString.escape = function(str) { <add> // replaces encodeURIComponent <add> // http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 <add> str = '' + str; <ide> var len = str.length; <ide> var out = ''; <ide> var i, c; <ide><path>test/parallel/test-querystring.js <ide> qsWeirdObjects.forEach(function(testCase) { <ide> assert.equal(testCase[1], qs.stringify(testCase[0])); <ide> }); <ide> <add>// coerce numbers to string <add>assert.strictEqual('foo=0', qs.stringify({ foo: 0 })); <add>assert.strictEqual('foo=0', qs.stringify({ foo: -0 })); <add>assert.strictEqual('foo=3', qs.stringify({ foo: 3 })); <add>assert.strictEqual('foo=-72.42', qs.stringify({ foo: -72.42 })); <add>assert.strictEqual('foo=', qs.stringify({ foo: NaN })); <add>assert.strictEqual('foo=', qs.stringify({ foo: Infinity })); <add> <ide> // nested <ide> var f = qs.stringify({ <ide> a: 'b',
2
PHP
PHP
add test case for default sort fallback
f3c89fc5e2461574f26a04aca06e69d7b273981a
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testDefaultSortRemovedFromUrl() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * Tests that generated default order URL doesn't include sort and direction parameters. <add> * <add> * @return void <add> */ <add> public function testDefaultSortRemovedFromUrlWithAliases() <add> { <add> $request = new ServerRequest([ <add> 'params' => ['controller' => 'articles', 'action' => 'index', 'plugin' => null], <add> 'url' => '/articles?sort=title&direction=asc' <add> ]); <add> Router::setRequestInfo($request); <add> <add> $this->Paginator->options(['model' => 'Articles']); <add> $this->Paginator->request = $this->Paginator->request->withParam('paging', [ <add> 'Articles' => [ <add> 'page' => 1, 'current' => 3, 'count' => 13, <add> 'prevPage' => false, 'nextPage' => true, 'pageCount' => 8, <add> 'sort' => 'Articles.title', 'direction' => 'asc', <add> 'sortDefault' => 'Articles.title', 'directionDefault' => 'desc', <add> ], <add> ]); <add> <add> $result = $this->Paginator->sort('title'); <add> $expected = [ <add> 'a' => ['class' => 'asc', 'href' => '/articles/index'], <add> 'Title', <add> '/a', <add> ]; <add> $this->assertHtml($expected, $result); <add> } <add> <ide> /** <ide> * Test the prev() method. <ide> *
1
Javascript
Javascript
remove use of reactcomponentexpect in our tests
c567b6e6187538b996db0da605806b0b91fc9c96
<ide><path>src/isomorphic/classic/__tests__/ReactContextValidator-test.js <ide> var React; <ide> var ReactDOM; <ide> var ReactTestUtils; <ide> <del>var reactComponentExpect; <del> <ide> describe('ReactContextValidator', () => { <ide> function normalizeCodeLocInfo(str) { <ide> return str.replace(/\(at .+?:\d+\)/g, '(at **)'); <ide> describe('ReactContextValidator', () => { <ide> React = require('React'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactTestUtils = require('ReactTestUtils'); <del> reactComponentExpect = require('reactComponentExpect'); <ide> }); <ide> <ide> // TODO: This behavior creates a runtime dependency on propTypes. We should <ide> describe('ReactContextValidator', () => { <ide> }, <ide> <ide> render: function() { <del> return <Component />; <add> return <Component ref="child" />; <ide> }, <ide> }); <ide> <ide> var instance = ReactTestUtils.renderIntoDocument(<ComponentInFooBarContext />); <del> reactComponentExpect(instance).expectRenderedChild().scalarContextEqual({foo: 'abc'}); <add> expect(instance.refs.child.context).toEqual({foo: 'abc'}); <ide> }); <ide> <ide> it('should filter context properly in callbacks', () => { <ide><path>src/isomorphic/classic/class/__tests__/ReactBind-test.js <ide> <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <del>var reactComponentExpect = require('reactComponentExpect'); <ide> <ide> // TODO: Test render and all stock methods. <ide> describe('autobinding', () => { <ide> describe('autobinding', () => { <ide> render: function() { <ide> return ( <ide> <div <add> ref="child" <ide> onMouseOver={this.onMouseEnter} <ide> onMouseOut={this.onMouseLeave} <ide> onClick={this.onClick} <ide> describe('autobinding', () => { <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <del> var instance2 = <TestBindComponent />; <del> var mountedInstance2 = ReactTestUtils.renderIntoDocument(instance2); <del> var rendered2 = reactComponentExpect(mountedInstance2) <del> .expectRenderedChild() <del> .instance(); <add> var instance2 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered2 = instance2.refs.child; <ide> <ide> expect(function() { <ide> var badIdea = instance1.badIdeas.badBind; <ide> badIdea(); <ide> }).toThrow(); <ide> <del> expect(mountedInstance1.onClick).not.toBe(mountedInstance2.onClick); <add> expect(instance1.onClick).not.toBe(instance2.onClick); <ide> <ide> ReactTestUtils.Simulate.click(rendered1); <ide> expect(mouseDidClick.mock.instances.length).toBe(1); <del> expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidClick.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.click(rendered2); <ide> expect(mouseDidClick.mock.instances.length).toBe(2); <del> expect(mouseDidClick.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidClick.mock.instances[1]).toBe(instance2); <ide> <ide> ReactTestUtils.Simulate.mouseOver(rendered1); <ide> expect(mouseDidEnter.mock.instances.length).toBe(1); <del> expect(mouseDidEnter.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidEnter.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.mouseOver(rendered2); <ide> expect(mouseDidEnter.mock.instances.length).toBe(2); <del> expect(mouseDidEnter.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidEnter.mock.instances[1]).toBe(instance2); <ide> <ide> ReactTestUtils.Simulate.mouseOut(rendered1); <ide> expect(mouseDidLeave.mock.instances.length).toBe(1); <del> expect(mouseDidLeave.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidLeave.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.mouseOut(rendered2); <ide> expect(mouseDidLeave.mock.instances.length).toBe(2); <del> expect(mouseDidLeave.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidLeave.mock.instances[1]).toBe(instance2); <ide> }); <ide> <ide> it('works with mixins', () => { <ide> describe('autobinding', () => { <ide> mixins: [TestMixin], <ide> <ide> render: function() { <del> return <div onClick={this.onClick} />; <add> return <div ref="child" onClick={this.onClick} />; <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <ide> ReactTestUtils.Simulate.click(rendered1); <ide> expect(mouseDidClick.mock.instances.length).toBe(1); <del> expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidClick.mock.instances[0]).toBe(instance1); <ide> }); <ide> <ide> it('warns if you try to bind to this', () => { <ide><path>src/isomorphic/classic/class/__tests__/ReactBindOptout-test.js <ide> <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <del>var reactComponentExpect = require('reactComponentExpect'); <ide> <ide> // TODO: Test render and all stock methods. <ide> describe('autobind optout', () => { <ide> describe('autobind optout', () => { <ide> render: function() { <ide> return ( <ide> <div <add> ref="child" <ide> onMouseOver={this.onMouseEnter.bind(this)} <ide> onMouseOut={this.onMouseLeave.bind(this)} <ide> onClick={this.onClick.bind(this)} <ide> describe('autobind optout', () => { <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <del> var instance2 = <TestBindComponent />; <del> var mountedInstance2 = ReactTestUtils.renderIntoDocument(instance2); <del> var rendered2 = reactComponentExpect(mountedInstance2) <del> .expectRenderedChild() <del> .instance(); <add> var instance2 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered2 = instance2.refs.child; <ide> <ide> ReactTestUtils.Simulate.click(rendered1); <ide> expect(mouseDidClick.mock.instances.length).toBe(1); <del> expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidClick.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.click(rendered2); <ide> expect(mouseDidClick.mock.instances.length).toBe(2); <del> expect(mouseDidClick.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidClick.mock.instances[1]).toBe(instance2); <ide> <ide> ReactTestUtils.Simulate.mouseOver(rendered1); <ide> expect(mouseDidEnter.mock.instances.length).toBe(1); <del> expect(mouseDidEnter.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidEnter.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.mouseOver(rendered2); <ide> expect(mouseDidEnter.mock.instances.length).toBe(2); <del> expect(mouseDidEnter.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidEnter.mock.instances[1]).toBe(instance2); <ide> <ide> ReactTestUtils.Simulate.mouseOut(rendered1); <ide> expect(mouseDidLeave.mock.instances.length).toBe(1); <del> expect(mouseDidLeave.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidLeave.mock.instances[0]).toBe(instance1); <ide> <ide> ReactTestUtils.Simulate.mouseOut(rendered2); <ide> expect(mouseDidLeave.mock.instances.length).toBe(2); <del> expect(mouseDidLeave.mock.instances[1]).toBe(mountedInstance2); <add> expect(mouseDidLeave.mock.instances[1]).toBe(instance2); <ide> }); <ide> <ide> it('should not hold reference to instance', () => { <ide> describe('autobind optout', () => { <ide> render: function() { <ide> return ( <ide> <div <add> ref="child" <ide> onClick={this.onClick} <ide> /> <ide> ); <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <del> var instance2 = <TestBindComponent />; <del> var mountedInstance2 = ReactTestUtils.renderIntoDocument(instance2); <del> var rendered2 = reactComponentExpect(mountedInstance2) <del> .expectRenderedChild() <del> .instance(); <add> var instance2 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered2 = instance2.refs.child; <ide> <ide> expect(function() { <ide> var badIdea = instance1.badIdeas.badBind; <ide> badIdea(); <ide> }).toThrow(); <ide> <del> expect(mountedInstance1.onClick).toBe(mountedInstance2.onClick); <add> expect(instance1.onClick).toBe(instance2.onClick); <ide> <ide> expect(function() { <ide> ReactTestUtils.Simulate.click(rendered1); <ide> describe('autobind optout', () => { <ide> mixins: [TestMixin], <ide> <ide> render: function() { <del> return <div onClick={this.onClick} />; <add> return <div ref="child" onClick={this.onClick} />; <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <ide> ReactTestUtils.Simulate.click(rendered1); <ide> expect(mouseDidClick.mock.instances.length).toBe(1); <del> expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidClick.mock.instances[0]).toBe(instance1); <ide> }); <ide> <ide> it('works with mixins that have opted out of autobinding', () => { <ide> describe('autobind optout', () => { <ide> mixins: [TestMixin], <ide> <ide> render: function() { <del> return <div onClick={this.onClick.bind(this)} />; <add> return <div ref="child" onClick={this.onClick.bind(this)} />; <ide> }, <ide> }); <ide> <del> var instance1 = <TestBindComponent />; <del> var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); <del> var rendered1 = reactComponentExpect(mountedInstance1) <del> .expectRenderedChild() <del> .instance(); <add> var instance1 = ReactTestUtils.renderIntoDocument(<TestBindComponent />); <add> var rendered1 = instance1.refs.child; <ide> <ide> ReactTestUtils.Simulate.click(rendered1); <ide> expect(mouseDidClick.mock.instances.length).toBe(1); <del> expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); <add> expect(mouseDidClick.mock.instances[0]).toBe(instance1); <ide> }); <ide> <ide> it('does not warn if you try to bind to this', () => { <ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js <ide> var ReactServerRendering; <ide> var ReactTestUtils; <ide> var ReactUpdates; <ide> <del>var reactComponentExpect; <del> <ide> describe('ReactCompositeComponent', () => { <ide> <ide> beforeEach(() => { <ide> jest.resetModuleRegistry(); <del> reactComponentExpect = require('reactComponentExpect'); <ide> React = require('React'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactCurrentOwner = require('ReactCurrentOwner'); <ide> describe('ReactCompositeComponent', () => { <ide> }); <ide> <ide> it('should support rendering to different child types over time', () => { <del> var instance = <MorphingComponent />; <del> instance = ReactTestUtils.renderIntoDocument(instance); <del> <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeComponentOfType('a'); <add> var instance = ReactTestUtils.renderIntoDocument(<MorphingComponent />); <add> var el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('A'); <ide> <ide> instance._toggleActivatedState(); <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeComponentOfType('b'); <add> el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('B'); <ide> <ide> instance._toggleActivatedState(); <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeComponentOfType('a'); <add> el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('A'); <ide> }); <ide> <ide> it('should not thrash a server rendered layout with client side one', () => { <ide> describe('ReactCompositeComponent', () => { <ide> }); <ide> <ide> it('should react to state changes from callbacks', () => { <del> var instance = <MorphingComponent />; <del> instance = ReactTestUtils.renderIntoDocument(instance); <del> <del> var renderedChild = reactComponentExpect(instance) <del> .expectRenderedChild() <del> .instance(); <add> var instance = ReactTestUtils.renderIntoDocument(<MorphingComponent />); <add> var el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('A'); <ide> <del> ReactTestUtils.Simulate.click(renderedChild); <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeComponentOfType('b'); <add> ReactTestUtils.Simulate.click(el); <add> el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('B'); <ide> }); <ide> <ide> it('should rewire refs when rendering to different child types', () => { <del> var instance = <MorphingComponent />; <del> instance = ReactTestUtils.renderIntoDocument(instance); <add> var instance = ReactTestUtils.renderIntoDocument(<MorphingComponent />); <ide> <ide> expect(ReactDOM.findDOMNode(instance.refs.x).tagName).toBe('A'); <ide> instance._toggleActivatedState(); <ide> describe('ReactCompositeComponent', () => { <ide> } <ide> } <ide> <del> var instance1 = <Component />; <del> instance1 = ReactTestUtils.renderIntoDocument(instance1); <del> reactComponentExpect(instance1).scalarPropsEqual({prop: 'testKey'}); <add> var instance1 = ReactTestUtils.renderIntoDocument(<Component />); <add> expect(instance1.props).toEqual({prop: 'testKey'}); <ide> <del> var instance2 = <Component prop={undefined} />; <del> instance2 = ReactTestUtils.renderIntoDocument(instance2); <del> reactComponentExpect(instance2).scalarPropsEqual({prop: 'testKey'}); <add> var instance2 = ReactTestUtils.renderIntoDocument(<Component prop={undefined} />); <add> expect(instance2.props).toEqual({prop: 'testKey'}); <ide> <del> var instance3 = <Component prop={null} />; <del> instance3 = ReactTestUtils.renderIntoDocument(instance3); <del> reactComponentExpect(instance3).scalarPropsEqual({prop: null}); <add> var instance3 = ReactTestUtils.renderIntoDocument(<Component prop={null} />); <add> expect(instance3.props).toEqual({prop: null}); <ide> }); <ide> <ide> it('should not mutate passed-in props object', () => { <ide> describe('ReactCompositeComponent', () => { <ide> ); <ide> <ide> expect(parentInstance.state.flag).toBe(false); <del> reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', flag: false}); <add> expect(childInstance.context).toEqual({foo: 'bar', flag: false}); <ide> <ide> parentInstance.setState({flag: true}); <ide> expect(parentInstance.state.flag).toBe(true); <del> <del> reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', flag: true}); <add> expect(childInstance.context).toEqual({foo: 'bar', flag: true}); <ide> }); <ide> <ide> it('should pass context when re-rendered for static child within a composite component', () => { <ide> describe('ReactCompositeComponent', () => { <ide> ); <ide> <ide> expect(wrapper.refs.parent.state.flag).toEqual(true); <del> reactComponentExpect(wrapper.refs.child).scalarContextEqual({flag: true}); <add> expect(wrapper.refs.child.context).toEqual({flag: true}); <ide> <ide> // We update <Parent /> while <Child /> is still a static prop relative to this update <ide> wrapper.refs.parent.setState({flag: false}); <ide> <ide> expect(wrapper.refs.parent.state.flag).toEqual(false); <del> reactComponentExpect(wrapper.refs.child).scalarContextEqual({flag: false}); <add> expect(wrapper.refs.child.context).toEqual({flag: false}); <ide> }); <ide> <ide> it('should pass context transitively', () => { <ide> describe('ReactCompositeComponent', () => { <ide> } <ide> <ide> ReactTestUtils.renderIntoDocument(<Parent />); <del> reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', depth: 0}); <del> reactComponentExpect(grandchildInstance).scalarContextEqual({foo: 'bar', depth: 1}); <add> expect(childInstance.context).toEqual({foo: 'bar', depth: 0}); <add> expect(grandchildInstance.context).toEqual({foo: 'bar', depth: 1}); <ide> }); <ide> <ide> it('should pass context when re-rendered', () => { <ide> describe('ReactCompositeComponent', () => { <ide> }); <ide> expect(parentInstance.state.flag).toBe(true); <ide> <del> reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', depth: 0}); <add> expect(childInstance.context).toEqual({foo: 'bar', depth: 0}); <ide> }); <ide> <ide> it('unmasked context propagates through updates', () => { <ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js <ide> <ide> // Requires <ide> var React; <add>var ReactDOM; <ide> var ReactTestUtils; <del>var reactComponentExpect; <ide> <ide> // Test components <ide> var LowerLevelComposite; <ide> var expectSingleChildlessDiv; <ide> describe('ReactCompositeComponentDOMMinimalism', () => { <ide> <ide> beforeEach(() => { <del> reactComponentExpect = require('reactComponentExpect'); <ide> React = require('React'); <add> ReactDOM = require('ReactDOM'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> <ide> LowerLevelComposite = class extends React.Component { <ide> describe('ReactCompositeComponentDOMMinimalism', () => { <ide> }; <ide> <ide> expectSingleChildlessDiv = function(instance) { <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeCompositeComponentWithType(LowerLevelComposite) <del> .expectRenderedChild() <del> .toBeComponentOfType('div') <del> .toBeDOMComponentWithNoChildren(); <add> var el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('DIV'); <add> expect(el.children.length).toBe(0); <ide> }; <ide> }); <ide> <ide> describe('ReactCompositeComponentDOMMinimalism', () => { <ide> </MyCompositeComponent> <ide> ); <ide> instance = ReactTestUtils.renderIntoDocument(instance); <del> reactComponentExpect(instance) <del> .expectRenderedChild() <del> .toBeCompositeComponentWithType(LowerLevelComposite) <del> .expectRenderedChild() <del> .toBeComponentOfType('div') <del> .toBeDOMComponentWithChildCount(1) <del> .expectRenderedChildAt(0) <del> .toBeComponentOfType('ul') <del> .toBeDOMComponentWithNoChildren(); <add> var el = ReactDOM.findDOMNode(instance); <add> expect(el.tagName).toBe('DIV'); <add> expect(el.children.length).toBe(1); <add> expect(el.children[0].tagName).toBe('UL'); <add> expect(el.children[0].children.length).toBe(0); <ide> }); <ide> <ide> }); <ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactEmptyComponent-test.js <ide> var ReactDOM; <ide> var ReactTestUtils; <ide> var TogglingComponent; <ide> <del>var reactComponentExpect; <del> <ide> var log; <ide> <ide> describe('ReactEmptyComponent', () => { <ide> describe('ReactEmptyComponent', () => { <ide> ReactDOM = require('ReactDOM'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> <del> reactComponentExpect = require('reactComponentExpect'); <del> <ide> log = jasmine.createSpy(); <ide> <ide> TogglingComponent = class extends React.Component { <ide> describe('ReactEmptyComponent', () => { <ide> }; <ide> }); <ide> <del> it('should render null and false as a noscript tag under the hood', () => { <add> it('should not produce child DOM nodes for null and false', () => { <ide> class Component1 extends React.Component { <ide> render() { <ide> return null; <ide> describe('ReactEmptyComponent', () => { <ide> } <ide> } <ide> <del> var instance1 = ReactTestUtils.renderIntoDocument(<Component1 />); <del> var instance2 = ReactTestUtils.renderIntoDocument(<Component2 />); <del> reactComponentExpect(instance1) <del> .expectRenderedChild() <del> .toBeEmptyComponent(); <del> reactComponentExpect(instance2) <del> .expectRenderedChild() <del> .toBeEmptyComponent(); <add> var container1 = document.createElement('div'); <add> ReactDOM.render(<Component1 />, container1); <add> expect(container1.children.length).toBe(0); <add> <add> var container2 = document.createElement('div'); <add> ReactDOM.render(<Component2 />, container2); <add> expect(container2.children.length).toBe(0); <ide> }); <ide> <ide> it('should still throw when rendering to undefined', () => { <ide><path>src/renderers/shared/stack/reconciler/__tests__/refs-test.js <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <ide> <del>var reactComponentExpect = require('reactComponentExpect'); <del> <del> <ide> /** <ide> * Counts clicks and has a renders an item for each click. Each item rendered <ide> * has a ref of the form "clickLogN". <ide> class TestRefsComponent extends React.Component { <ide> var renderTestRefsComponent = function() { <ide> var testRefsComponent = <ide> ReactTestUtils.renderIntoDocument(<TestRefsComponent />); <del> <del> reactComponentExpect(testRefsComponent) <del> .toBeCompositeComponentWithType(TestRefsComponent); <add> expect(testRefsComponent instanceof TestRefsComponent).toBe(true); <ide> <ide> var generalContainer = testRefsComponent.refs.myContainer; <del> var counter = testRefsComponent.refs.myCounter; <add> expect(generalContainer instanceof GeneralContainerComponent).toBe(true); <ide> <del> reactComponentExpect(generalContainer) <del> .toBeCompositeComponentWithType(GeneralContainerComponent); <del> reactComponentExpect(counter) <del> .toBeCompositeComponentWithType(ClickCounter); <add> var counter = testRefsComponent.refs.myCounter; <add> expect(counter instanceof ClickCounter).toBe(true); <ide> <ide> return testRefsComponent; <ide> };
7
PHP
PHP
add session support for psr7 requests
61ef064686e6eac5599ef566e1796b291d521225
<ide><path>src/TestSuite/MiddlewareDispatcher.php <ide> public function execute($request) <ide> $request['post'], <ide> $request['cookies'] <ide> ); <add> $psrRequest = $psrRequest->withAttribute('session', $request['session']); <ide> $response = $server->run($psrRequest); <ide> return ResponseTransformer::toCake($response); <ide> } <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function testPostDataHttpServer() <ide> $this->assertHeader('X-Middleware', 'true'); <ide> } <ide> <add> /** <add> * Test that the PSR7 requests get cookies <add> * <add> * @return void <add> */ <add> public function testSessionHttpServer() <add> { <add> $this->useHttpServer(true); <add> <add> $this->session(['foo' => 'session data']); <add> $this->get('/request_action/session_test'); <add> $this->assertResponseOk(); <add> $this->assertResponseContains('session data'); <add> $this->assertHeader('X-Middleware', 'true'); <add> } <ide> <ide> /** <ide> * Test sending requests stores references to controller/view/layout.
2
Python
Python
update celery to 4.4.2
876ca9bb645ac7f3e49063bf7a8d4639d9cd72b5
<ide><path>setup.py <ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version <ide> 'cassandra-driver>=3.13.0,<3.21.0', <ide> ] <ide> celery = [ <del> 'celery~=4.3', <add> 'celery~=4.4.2', <ide> 'flower>=0.7.3, <1.0', <ide> 'tornado>=4.2.0, <6.0', # Dep of flower. Pin to a version that works on Py3.5.2 <ide> ]
1
Text
Text
update the runtime version in bash script
fc918584cf35b093928a96916c503c9a17de1633
<ide><path>research/object_detection/g3doc/running_pets.md <ide> To start training and evaluation, execute the following command from the <ide> ```bash <ide> # From tensorflow/models/research/ <ide> gcloud ml-engine jobs submit training `whoami`_object_detection_pets_`date +%m_%d_%Y_%H_%M_%S` \ <del> --runtime-version 1.8 \ <add> --runtime-version 1.9 \ <ide> --job-dir=gs://${YOUR_GCS_BUCKET}/model_dir \ <ide> --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz \ <ide> --module-name object_detection.model_main \
1
Ruby
Ruby
expect xcode 8.3.3
a88350425bbee7a610143911badaca933baad05e
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when "10.9" then "6.2" <ide> when "10.10" then "7.2.1" <ide> when "10.11" then "8.2.1" <del> when "10.12" then "8.3.2" <add> when "10.12" then "8.3.3" <ide> else <ide> raise "macOS '#{MacOS.version}' is invalid" unless OS::Mac.prerelease? <ide> <ide> # Default to newest known version of Xcode for unreleased macOS versions. <del> "8.3.2" <add> "8.3.3" <ide> end <ide> end <ide>
1
Ruby
Ruby
fix typo in actionview error message
328ae33d78103de242e9d64fa471c64a76aae348
<ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> def method_tag(method) <ide> def to_form_params(attribute, namespace = nil) <ide> attribute = if attribute.respond_to?(:permitted?) <ide> unless attribute.permitted? <del> raise ArgumentError, "Attempting to generate a buttom from non-sanitized request parameters!" \ <add> raise ArgumentError, "Attempting to generate a button from non-sanitized request parameters!" \ <ide> " Whitelist and sanitize passed parameters to be secure." <ide> end <ide>
1
Javascript
Javascript
fix material accessors
d4ee29216cfbd37cff37d02efbf0ed5179745376
<ide><path>src/materials/Material.js <ide> function Material() { <ide> <ide> } <ide> <del>Object.assign( Material.prototype, EventDispatcher.prototype, { <del> <del> constructor: Material, <del> <del> isMaterial: true, <add>Object.defineProperty( Material.prototype, "needsUpdate", { <ide> <del> get needsUpdate() { <add> get: function() { <ide> <ide> return this._needsUpdate; <ide> <ide> }, <del> <del> set needsUpdate( value ) { <add> set: function(value) { <ide> <ide> if ( value === true ) this.update(); <ide> this._needsUpdate = value; <ide> <del> }, <add> } <add> <add>}); <add> <add>Object.assign( Material.prototype, EventDispatcher.prototype, { <add> <add> constructor: Material, <add> <add> isMaterial: true, <ide> <ide> setValues: function ( values ) { <ide>
1
Ruby
Ruby
fix bad require for rake test
427d0a8d14aaca59bbf2d33dba6b4a1232f895f0
<ide><path>actionpack/test/controller/routing_test.rb <ide> require File.dirname(__FILE__) + '/../abstract_unit' <ide> require 'test/unit' <del>require 'fake_controllers' <add>require File.dirname(__FILE__) + '/fake_controllers' <ide> require 'stringio' <ide> <ide> RunTimeTests = ARGV.include? 'time'
1
Javascript
Javascript
apply promises api to fourth appendfile test
8530b58493c1da6c7bf21b4bb59824eda45521b2
<ide><path>test/parallel/test-fs-append-file.js <ide> const s = '南越国是前203年至前111年存在于岭南地区的一个国家 <ide> '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + <ide> '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; <ide> <del>let ncallbacks = 0; <del> <ide> tmpdir.refresh(); <ide> <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; <ide> .catch(throwNextTick); <ide> } <ide> <del>// test that appendFile accepts file descriptors <del>const filename5 = join(tmpdir.path, 'append5.txt'); <del>fs.writeFileSync(filename5, currentFileData); <del> <del>fs.open(filename5, 'a+', function(e, fd) { <del> assert.ifError(e); <del> <del> ncallbacks++; <add>// test that appendFile accepts file descriptors (callback API) <add>{ <add> const filename = join(tmpdir.path, 'append-descriptors.txt'); <add> fs.writeFileSync(filename, currentFileData); <ide> <del> fs.appendFile(fd, s, function(e) { <add> fs.open(filename, 'a+', common.mustCall((e, fd) => { <ide> assert.ifError(e); <ide> <del> ncallbacks++; <del> <del> fs.close(fd, function(e) { <add> fs.appendFile(fd, s, common.mustCall((e) => { <ide> assert.ifError(e); <ide> <del> ncallbacks++; <del> <del> fs.readFile(filename5, function(e, buffer) { <add> fs.close(fd, common.mustCall((e) => { <ide> assert.ifError(e); <ide> <del> ncallbacks++; <del> assert.strictEqual(Buffer.byteLength(s) + currentFileData.length, <del> buffer.length); <del> }); <del> }); <del> }); <del>}); <add> fs.readFile(filename, common.mustCall((e, buffer) => { <add> assert.ifError(e); <add> assert.strictEqual(Buffer.byteLength(s) + currentFileData.length, <add> buffer.length); <add> })); <add> })); <add> })); <add> })); <add>} <add> <add>// test that appendFile accepts file descriptors (promises API) <add>{ <add> const filename = join(tmpdir.path, 'append-descriptors-promises.txt'); <add> fs.writeFileSync(filename, currentFileData); <add> <add> let fd; <add> fs.promises.open(filename, 'a+') <add> .then(common.mustCall((fileDescriptor) => { <add> fd = fileDescriptor; <add> return fs.promises.appendFile(fd, s); <add> })) <add> .then(common.mustCall(() => fd.close())) <add> .then(common.mustCall(() => fs.promises.readFile(filename))) <add> .then(common.mustCall((buffer) => { <add> assert.strictEqual(Buffer.byteLength(s) + currentFileData.length, <add> buffer.length); <add> })) <add> .catch(throwNextTick); <add>} <ide> <ide> assert.throws( <ide> () => fs.appendFile(join(tmpdir.path, 'append6.txt'), console.log), <ide> { code: 'ERR_INVALID_CALLBACK' }); <del> <del>process.on('exit', function() { <del> assert.strictEqual(ncallbacks, 4); <del> <del> fs.unlinkSync(filename5); <del>});
1
Text
Text
fix module name in section 2
af8beb90c256586d9016d9e6411ecd9ac01f4f22
<ide><path>docs/tutorial/2-requests-and-responses.md <ide> Now update the `urls.py` file slightly, to append a set of `format_suffix_patter <ide> from django.conf.urls import patterns, url <ide> from rest_framework.urlpatterns import format_suffix_patterns <ide> <del> urlpatterns = patterns('snippet.views', <add> urlpatterns = patterns('snippets.views', <ide> url(r'^snippets/$', 'snippet_list'), <ide> url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail') <ide> )
1
Python
Python
update some annotations updated from the spec
7ce435c610fcd7fee01da9d9e7ff5c1ab4ae6ef6
<ide><path>numpy/_array_api/_array_object.py <ide> def __and__(self: array, other: array, /) -> array: <ide> res = self._array.__and__(asarray(other)._array) <ide> return self.__class__._new(res) <ide> <del> def __array_namespace__(self, /, *, api_version=None): <add> def __array_namespace__(self: array, /, *, api_version: Optional[str] = None) -> object: <ide> if api_version is not None: <ide> raise ValueError("Unrecognized array API version") <ide> from numpy import _array_api <ide> def _validate_index(key, shape): <ide> # ndarray() form, like a list of booleans. <ide> raise IndexError("Only integers, slices (`:`), ellipsis (`...`), and boolean arrays are valid indices in the array API namespace") <ide> <del> def __getitem__(self: array, key: Union[int, slice, Tuple[Union[int, slice], ...], array], /) -> array: <add> def __getitem__(self: array, key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array], /) -> array: <ide> """ <ide> Performs the operation __getitem__. <ide> """ <ide><path>numpy/_array_api/_data_type_functions.py <ide> <ide> import numpy as np <ide> <del>def finfo(type: Union[dtype, array], /) -> finfo: <add>def finfo(type: Union[dtype, array], /) -> finfo_object: <ide> """ <ide> Array API compatible wrapper for :py:func:`np.finfo <numpy.finfo>`. <ide> <ide> See its docstring for more information. <ide> """ <ide> return np.finfo(type) <ide> <del>def iinfo(type: Union[dtype, array], /) -> iinfo: <add>def iinfo(type: Union[dtype, array], /) -> iinfo_object: <ide> """ <ide> Array API compatible wrapper for :py:func:`np.iinfo <numpy.iinfo>`. <ide> <ide><path>numpy/_array_api/_manipulation_functions.py <ide> <ide> import numpy as np <ide> <del>def concat(arrays: Tuple[array], /, *, axis: Optional[int] = 0) -> array: <add>def concat(arrays: Tuple[array, ...], /, *, axis: Optional[int] = 0) -> array: <ide> """ <ide> Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`. <ide> <ide> def squeeze(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) <ide> """ <ide> return ndarray._array(np.squeeze(x._array, axis=axis)) <ide> <del>def stack(arrays: Tuple[array], /, *, axis: int = 0) -> array: <add>def stack(arrays: Tuple[array, ...], /, *, axis: int = 0) -> array: <ide> """ <ide> Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`. <ide>
3
Ruby
Ruby
remove another call to rendered_format=
df12a1b2413906ee38a977e3cbb325512c184837
<ide><path>actionview/lib/action_view/digestor.rb <ide> def tree(name, finder, partial = false, seen = {}) <ide> logical_name = name.gsub(%r|/_|, "/") <ide> <ide> if template = find_template(finder, logical_name, [], partial, []) <del> finder.rendered_format ||= template.formats.first <del> <ide> if node = seen[template.identifier] # handle cycles in the tree <ide> node <ide> else
1
Python
Python
remove testing change
2e0a2a718ac8d9094576f3efcfb4cfa8fe1246d3
<ide><path>libcloud/compute/drivers/ec2.py <ide> class EC2Connection(SignedAWSConnection): <ide> """ <ide> <ide> version = API_VERSION <del> host = "aaa.com" <add> host = REGION_DETAILS['us-east-1']['endpoint'] <ide> responseCls = EC2Response <ide> service_name = 'ec2' <ide>
1
Javascript
Javascript
trim cat output for windows
9826159bf102aaa5dad6eaea7998ede8460de471
<ide><path>test/simple/test-child-process-stdio-inherit.js <ide> function grandparent() { <ide> child.on('close', function(code, signal) { <ide> assert.equal(code, 0); <ide> assert.equal(signal, null); <del> assert.equal(output, input); <add> // cat on windows adds a \r\n at the end. <add> assert.equal(output.trim(), input.trim()); <ide> }); <ide> } <ide>
1
Javascript
Javascript
fix rgbatodepth artefacts
247b93f14e3f883ec285c0ba76264ec3286c85a8
<ide><path>src/renderers/shaders/ShaderChunk/packing.glsl.js <ide> vec4 packDepthToRGBA( const in float v ) { <ide> } <ide> <ide> float unpackRGBAToDepth( const in vec4 v ) { <del> return dot( v, UnpackFactors ); <add> return dot( floor( v * 255.0 + 0.5 ) / 255.0, UnpackFactors ); <ide> } <ide> <ide> vec4 encodeHalfRGBA ( vec2 v ) {
1
Text
Text
update slim readme as well
7b4d025aa03d2cdd684970e0dc7404f12bb98cd4
<ide><path>slim/README.md <ide> prerequisite packages. <ide> <ide> ## Installing latest version of TF-slim <ide> <del>As of 8/28/16, the latest [stable release of TF](https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#pip-installation) <del>is r0.10, which contains most of TF-Slim but not some later additions. To obtain the <del>latest version, you must install the most recent nightly build of <del>TensorFlow. You can find the latest nightly binaries at <del>[TensorFlow Installation](https://github.com/tensorflow/tensorflow#installation) <del>in the section that reads "People who are a little more adventurous can <del>also try our nightly binaries". Copy the link address that corresponds to <del>the appropriate machine architecture and python version, and pip install <del>it. For example: <del> <del>```shell <del>export TF_BINARY_URL=https://ci.tensorflow.org/view/Nightly/job/nightly-matrix-cpu/TF_BUILD_CONTAINER_TYPE=CPU,TF_BUILD_IS_OPT=OPT,TF_BUILD_IS_PIP=PIP,TF_BUILD_PYTHON_VERSION=PYTHON2,label=cpu-slave/lastSuccessfulBuild/artifact/pip_test/whl/tensorflow-0.10.0rc0-cp27-none-linux_x86_64.whl <del>sudo pip install --upgrade $TF_BINARY_URL <del>``` <del> <del>To test this has worked, execute the following command; it should run <del>without raising any errors. <add>TF-Slim is available as `tf.contrib.slim` via TensorFlow 1.0. To test that your <add>installation is working, execute the following command; it should run without <add>raising any errors. <ide> <ide> ``` <ide> python -c "import tensorflow.contrib.slim as slim; eval = slim.evaluation.evaluate_once" <ide> You can use the same script to create the mnist and cifar10 datasets. <ide> However, for ImageNet, you have to follow the instructions <ide> [here](https://github.com/tensorflow/models/blob/master/inception/README.md#getting-started). <ide> Note that you first have to sign up for an account at image-net.org. <del>Also, the download can take several hours, and uses about 500MB. <add>Also, the download can take several hours, and could use up to 500GB. <ide> <ide> <ide> ## Creating a TF-Slim Dataset Descriptor.
1
Text
Text
add devtools monitors to ecosystem
03134a881025c5c4ea4d400bb4129014e97476da
<ide><path>docs/introduction/Ecosystem.md <ide> On this page we will only feature a few of them that the Redux maintainers have <ide> * [redux-tcomb](https://github.com/gcanti/redux-tcomb) — Immutable and type-checked state and actions for Redux <ide> * [redux-mock-store](https://github.com/arnaudbenard/redux-mock-store) — Mock redux store for testing your app <ide> <del>### Developer Tools <add>### DevTools <ide> <ide> * [Redux DevTools](http://github.com/gaearon/redux-devtools) — An action logger with time travel UI, hot reloading and error handling for the reducers, [first demoed at React Europe](https://www.youtube.com/watch?v=xsSnOQynTHs) <ide> * [Redux DevTools Extension](https://github.com/zalmoxisus/redux-devtools-extension) — A Chrome extension wrapping Redux DevTools and providing additional functionality <ide> <add>### DevTools Monitors <add> <add>* [Log Monitor](https://github.com/gaearon/redux-devtools-log-monitor) — The default monitor for Redux DevTools with a tree view <add>* [Dock Monitor](https://github.com/gaearon/redux-devtools-dock-monitor) — A resizable and movable dock for Redux DevTools monitors <add>* [Slider Monitor](https://github.com/calesce/redux-slider-monitor) — A custom monitor for Redux DevTools to replay recorded Redux actions <add>* [Diff Monitor](https://github.com/whetstone/redux-devtools-diff-monitor) — A monitor for Redux Devtools that diffs the Redux store mutations between actions <add>* [Filterable Log Monitor](https://github.com/bvaughn/redux-devtools-filterable-log-monitor/) — Filterable tree view monitor for Redux DevTools <add>* [Chart Monitor](https://github.com/romseguy/redux-devtools-chart-monitor) — A chart monitor for Redux DevTools <add>* [Filter Actions](https://github.com/zalmoxisus/redux-devtools-filter-actions) — Redux DevTools composable monitor with the ability to filter actions <add> <add> <ide> ### Community Conventions <ide> <ide> * [Flux Standard Action](https://github.com/acdlite/flux-standard-action) — A human-friendly standard for Flux action objects
1
PHP
PHP
add allowdynamicproperties attribute to component
c1f24403b58bafb3c2d2fc206b803d40e045679f
<ide><path>src/Controller/Component.php <ide> * @link https://book.cakephp.org/4/en/controllers/components.html <ide> * @see \Cake\Controller\Controller::$components <ide> */ <add>#[\AllowDynamicPropeties] <ide> class Component implements EventListenerInterface <ide> { <ide> use InstanceConfigTrait;
1
PHP
PHP
use correct interface in tests
982c68121c2645a6ec812b6a5eae1b0244e16094
<ide><path>tests/Auth/AuthGuardTest.php <ide> public function testLoginStoresIdentifierInSession() <ide> $user = m::mock('Illuminate\Contracts\Auth\User'); <ide> $mock->expects($this->once())->method('getName')->will($this->returnValue('foo')); <ide> $user->shouldReceive('getAuthIdentifier')->once()->andReturn('bar'); <del> $mock->getSession()->shouldReceive('put')->with('foo', 'bar')->once(); <add> $mock->getSession()->shouldReceive('set')->with('foo', 'bar')->once(); <ide> $session->shouldReceive('migrate')->once(); <ide> $mock->login($user); <ide> } <ide> public function testLoginFiresLoginEvent() <ide> $events->shouldReceive('fire')->once()->with('auth.login', array($user, false)); <ide> $mock->expects($this->once())->method('getName')->will($this->returnValue('foo')); <ide> $user->shouldReceive('getAuthIdentifier')->once()->andReturn('bar'); <del> $mock->getSession()->shouldReceive('put')->with('foo', 'bar')->once(); <add> $mock->getSession()->shouldReceive('set')->with('foo', 'bar')->once(); <ide> $session->shouldReceive('migrate')->once(); <ide> $mock->login($user); <ide> } <ide> public function testLogoutRemovesSessionTokenAndRememberMeCookie() <ide> $cookie = m::mock('Symfony\Component\HttpFoundation\Cookie'); <ide> $cookies->shouldReceive('forget')->once()->with('bar')->andReturn($cookie); <ide> $cookies->shouldReceive('queue')->once()->with($cookie); <del> $mock->getSession()->shouldReceive('forget')->once()->with('foo'); <add> $mock->getSession()->shouldReceive('remove')->once()->with('foo'); <ide> $mock->setUser($user); <ide> $mock->logout(); <ide> $this->assertNull($mock->getUser()); <ide> public function testLoginMethodQueuesCookieWhenRemembering() <ide> $foreverCookie = new Symfony\Component\HttpFoundation\Cookie($guard->getRecallerName(), 'foo'); <ide> $cookie->shouldReceive('forever')->once()->with($guard->getRecallerName(), 'foo|recaller')->andReturn($foreverCookie); <ide> $cookie->shouldReceive('queue')->once()->with($foreverCookie); <del> $guard->getSession()->shouldReceive('put')->once()->with($guard->getName(), 'foo'); <add> $guard->getSession()->shouldReceive('set')->once()->with($guard->getName(), 'foo'); <ide> $session->shouldReceive('migrate')->once(); <ide> $user = m::mock('Illuminate\Contracts\Auth\User'); <ide> $user->shouldReceive('getAuthIdentifier')->andReturn('foo'); <ide> public function testLoginMethodCreatesRememberTokenIfOneDoesntExist() <ide> $foreverCookie = new Symfony\Component\HttpFoundation\Cookie($guard->getRecallerName(), 'foo'); <ide> $cookie->shouldReceive('forever')->once()->andReturn($foreverCookie); <ide> $cookie->shouldReceive('queue')->once()->with($foreverCookie); <del> $guard->getSession()->shouldReceive('put')->once()->with($guard->getName(), 'foo'); <add> $guard->getSession()->shouldReceive('set')->once()->with($guard->getName(), 'foo'); <ide> $session->shouldReceive('migrate')->once(); <ide> $user = m::mock('Illuminate\Contracts\Auth\User'); <ide> $user->shouldReceive('getAuthIdentifier')->andReturn('foo'); <ide> public function testLoginUsingIdStoresInSessionAndLogsInWithUser() <ide> { <ide> list($session, $provider, $request, $cookie) = $this->getMocks(); <ide> $guard = $this->getMock('Illuminate\Auth\Guard', array('login', 'user'), array($provider, $session, $request)); <del> $guard->getSession()->shouldReceive('put')->once()->with($guard->getName(), 10); <add> $guard->getSession()->shouldReceive('set')->once()->with($guard->getName(), 10); <ide> $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user = m::mock('Illuminate\Contracts\Auth\User')); <ide> $guard->expects($this->once())->method('login')->with($this->equalTo($user), $this->equalTo(false))->will($this->returnValue($user)); <ide> <ide> protected function getGuard() <ide> protected function getMocks() <ide> { <ide> return array( <del> m::mock('Illuminate\Session\Store'), <add> m::mock('Symfony\Component\HttpFoundation\Session\SessionInterface'), <ide> m::mock('Illuminate\Auth\UserProviderInterface'), <ide> Symfony\Component\HttpFoundation\Request::create('/', 'GET'), <ide> m::mock('Illuminate\Cookie\CookieJar'),
1
Ruby
Ruby
extract exec_migration []
24653c945ad3fdce4cb5890a9cc7565753decda0
<ide><path>activerecord/lib/active_record/migration.rb <ide> def migrate(direction) <ide> time = nil <ide> ActiveRecord::Base.connection_pool.with_connection do |conn| <ide> time = Benchmark.measure do <del> @connection = conn <del> if respond_to?(:change) <del> if direction == :down <del> revert { change } <del> else <del> change <del> end <del> else <del> send(direction) <del> end <del> @connection = nil <add> exec_migration(conn, direction) <ide> end <ide> end <ide> <ide> def migrate(direction) <ide> end <ide> end <ide> <add> def exec_migration(conn, direction) <add> @connection = conn <add> if respond_to?(:change) <add> if direction == :down <add> revert { change } <add> else <add> change <add> end <add> else <add> send(direction) <add> end <add> ensure <add> @connection = nil <add> end <add> <ide> def write(text="") <ide> puts(text) if verbose <ide> end
1
Javascript
Javascript
do jquery.trim in less bytes (-5)
26bdbb806eeb1d8e1881b3fc11ff298eb4d1dca0
<ide><path>src/core.js <ide> var <ide> // Used for detecting and trimming whitespace <ide> core_rnotwhite = /\S/, <ide> core_rspace = /\s+/, <del> trimLeft = /^\s+/, <del> trimRight = /\s+$/, <add> <add> // IE doesn't match non-breaking spaces with \s <add> rtrim = core_rnotwhite.test("\xA0") ? (/^[\s\xA0]+|[\s\xA0]+$/g) : /^\s+|\s+$/g, <ide> <ide> // A simple way to check for HTML strings <ide> // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) <ide> jQuery.extend({ <ide> function( text ) { <ide> return text == null ? <ide> "" : <del> text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); <add> text.toString().replace( rtrim, "" ); <ide> }, <ide> <ide> // results is for internal usage only <ide> if ( jQuery.browser.webkit ) { <ide> jQuery.browser.safari = true; <ide> } <ide> <del>// IE doesn't match non-breaking spaces with \s <del>if ( core_rnotwhite.test( "\xA0" ) ) { <del> trimLeft = /^[\s\xA0]+/; <del> trimRight = /[\s\xA0]+$/; <del>} <del> <ide> // All jQuery objects should point back to these <ide> rootjQuery = jQuery(document);
1
PHP
PHP
prefix seeders automatically if necessary
cadad245ff1d5e294ef6d3f312d66dc63f728619
<ide><path>src/Illuminate/Database/Console/Seeds/SeedCommand.php <ide> protected function getSeeder() <ide> { <ide> $class = $this->input->getOption('class'); <ide> <add> if (strpos($class, '\\') === false) { <add> $class = 'Database\\Seeders\\'.$class; <add> } <add> <ide> if ($class === 'Database\\Seeders\\DatabaseSeeder' && <ide> ! class_exists($class)) { <ide> $class = 'DatabaseSeeder';
1
Python
Python
update mgrid test from code review
f82c7d73ce116471f8009d481ded4449dfec3106
<ide><path>numpy/lib/tests/test_index_tricks.py <ide> def test_accepts_npfloating(self): <ide> assert_array_almost_equal(grid64, grid32) <ide> <ide> def test_accepts_npcomplexfloating(self): <del> grid = mgrid[0.1:0.3:np.complex64(3j), ] <del> assert_array_almost_equal(grid, np.array([[0.1, 0.2, 0.3]])) <add> assert_array_almost_equal( <add> mgrid[0.1:0.3:3j, ], mgrid[0.1:0.3:np.complex64(3j), ] <add> ) <ide> <ide> # different code path for single slice <del> grid = mgrid[0.1:0.3:np.complex64(3j)] <del> assert_array_almost_equal(grid, np.array([0.1, 0.2, 0.3])) <add> assert_array_almost_equal( <add> mgrid[0.1:0.3:3j], mgrid[0.1:0.3:np.complex64(3j)] <add> ) <ide> <ide> class TestConcatenator: <ide> def test_1d(self):
1
Text
Text
introduce bundler and gemfiles in a note
83cb6fbd13f3c5ea3106b9a57964b1a6fb243682
<ide><path>guides/source/getting_started.md <ide> $ rails new blog <ide> <ide> This will create a Rails application called Blog in a directory called blog and install the gem dependencies that are already mentioned in `Gemfile` using `bundle install`. <ide> <add>NOTE: A Gemfile is a file that contains the list of all the gems that you require to run your application - the so called dependencies. With it, a program called Bundler can make sure that your machine has all of the requirements installed. This is the de facto way in Ruby to make sure that a machine is set up correctly to run a given program and Rails takes advantage of it to install some commonly-used gems. For more information, visit [Bundler's homepage](http://gembundler.com/). <add> <ide> TIP: You can see all of the command line options that the Rails <ide> application builder accepts by running `rails new -h`. <ide>
1
Ruby
Ruby
remove stubs from logsubscriber tests
731bb2fe6815ac6a1888d9fb54bb1782e4768c0b
<ide><path>actionpack/test/template/log_subscriber_test.rb <ide> class AVLogSubscriberTest < ActiveSupport::TestCase <ide> <ide> def setup <ide> super <del> @controller = Object.new <del> @controller.stubs(:_prefixes).returns(%w(test)) <del> @view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller) <add> view_paths = ActionController::Base.view_paths <add> lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"]) <add> renderer = ActionView::Renderer.new(lookup_context) <add> @view = ActionView::Base.new(renderer, {}) <ide> Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) <ide> ActionView::LogSubscriber.attach_to :action_view <ide> end
1
Javascript
Javascript
run all of test-timers-blocking-callback
2c6ca32e8bcc6759a704bb525df71ac7b3b151ca
<ide><path>test/parallel/test-timers-blocking-callback.js <ide> function blockingCallback(callback) { <ide> common.busyLoop(TIMEOUT); <ide> <ide> timeCallbackScheduled = Timer.now(); <del> setTimeout(blockingCallback, TIMEOUT); <add> setTimeout(blockingCallback.bind(null, callback), TIMEOUT); <ide> } <ide> } <ide> <del>function testAddingTimerToEmptyTimersList(callback) { <add>const testAddingTimerToEmptyTimersList = common.mustCall(function(callback) { <ide> initTest(); <ide> // Call setTimeout just once to make sure the timers list is <ide> // empty when blockingCallback is called. <ide> setTimeout(blockingCallback.bind(null, callback), TIMEOUT); <del>} <add>}); <ide> <del>function testAddingTimerToNonEmptyTimersList() { <add>const testAddingTimerToNonEmptyTimersList = common.mustCall(function() { <ide> initTest(); <ide> // Call setTimeout twice with the same timeout to make <ide> // sure the timers list is not empty when blockingCallback is called. <ide> setTimeout(blockingCallback, TIMEOUT); <ide> setTimeout(blockingCallback, TIMEOUT); <del>} <add>}); <ide> <ide> // Run the test for the empty timers list case, and then for the non-empty <ide> // timers list one
1
Javascript
Javascript
fix todo in `freeze_intrinsics`
411fb2172314588a6503f8f7aa14263b117c04df
<ide><path>lib/internal/freeze_intrinsics.js <ide> module.exports = function() { <ide> const descs = ObjectGetOwnPropertyDescriptors(obj); <ide> enqueue(proto); <ide> ArrayPrototypeForEach(ReflectOwnKeys(descs), (name) => { <del> // TODO: Uncurried form <del> // TODO: getOwnPropertyDescriptors is guaranteed to return well-formed <del> // descriptors, but they still inherit from Object.prototype. If <del> // someone has poisoned Object.prototype to add 'value' or 'get' <del> // properties, then a simple 'if ("value" in desc)' or 'desc.value' <del> // test could be confused. We use hasOwnProperty to be sure about <del> // whether 'value' is present or not, which tells us for sure that <del> // this is a data property. <ide> const desc = descs[name]; <del> if ('value' in desc) { <add> if (ObjectPrototypeHasOwnProperty(desc, 'value')) { <ide> // todo uncurried form <ide> enqueue(desc.value); <ide> } else { <ide> module.exports = function() { <ide> * objects succeed if otherwise possible. <ide> */ <ide> function enableDerivedOverride(obj, prop, desc) { <del> if ('value' in desc && desc.configurable) { <add> if (ObjectPrototypeHasOwnProperty(desc, 'value') && desc.configurable) { <ide> const value = desc.value; <ide> <ide> function getter() {
1
Python
Python
set version to 2.0.12.dev1
1a1c7304cfd1fb3f8544cb8a55e1012db799f5ee
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy' <del>__version__ = '2.0.12.dev0' <add>__version__ = '2.0.12.dev1' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI' <ide> __email__ = 'contact@explosion.ai' <ide> __license__ = 'MIT' <del>__release__ = True <add>__release__ = False <ide> <ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download' <ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
1
Javascript
Javascript
use private field in abortcontroller
73ba8830d59015e8554903301245ee32c31baa9f
<ide><path>lib/internal/abort_controller.js <ide> function abortSignal(signal, reason) { <ide> signal.dispatchEvent(event); <ide> } <ide> <del>// TODO(joyeecheung): use private fields and we'll get invalid access <del>// validation from V8 instead of throwing ERR_INVALID_THIS ourselves. <del>const kSignal = Symbol('signal'); <del> <del>function validateAbortController(obj) { <del> if (obj?.[kSignal] === undefined) <del> throw new ERR_INVALID_THIS('AbortController'); <del>} <del> <ide> class AbortController { <del> constructor() { <del> this[kSignal] = createAbortSignal(); <del> } <add> #signal = createAbortSignal(); <ide> <ide> /** <ide> * @type {AbortSignal} <ide> */ <ide> get signal() { <del> validateAbortController(this); <del> return this[kSignal]; <add> return this.#signal; <ide> } <ide> <ide> /** <ide> * @param {any} reason <ide> */ <ide> abort(reason = new DOMException('This operation was aborted', 'AbortError')) { <del> validateAbortController(this); <del> abortSignal(this[kSignal], reason); <add> abortSignal(this.#signal, reason); <ide> } <ide> <ide> [customInspectSymbol](depth, options) { <ide><path>test/parallel/test-abortcontroller.js <ide> const { setTimeout: sleep } = require('timers/promises'); <ide> for (const badController of badAbortControllers) { <ide> throws( <ide> () => acSignalGet.call(badController), <del> { code: 'ERR_INVALID_THIS', name: 'TypeError' } <add> { name: 'TypeError' } <ide> ); <ide> throws( <ide> () => acAbort.call(badController), <del> { code: 'ERR_INVALID_THIS', name: 'TypeError' } <add> { name: 'TypeError' } <ide> ); <ide> } <ide> } <ide> const { setTimeout: sleep } = require('timers/promises'); <ide> for (const badSignal of badAbortSignals) { <ide> throws( <ide> () => signalAbortedGet.call(badSignal), <del> { code: 'ERR_INVALID_THIS', name: 'TypeError' } <add> { name: 'TypeError' } <ide> ); <ide> } <ide> }
2
Ruby
Ruby
require rubygems for activesupport
6670ae620229d7030b0e0feee96cd550c686e117
<ide><path>Library/Homebrew/cask/dsl/depends_on.rb <ide> # frozen_string_literal: true <ide> <del>require "rubygems" <del> <ide> module Cask <ide> class DSL <ide> class DependsOn < DelegateClass(Hash) <ide><path>Library/Homebrew/cask/installer.rb <ide> # frozen_string_literal: true <ide> <del>require "rubygems" <del> <ide> require "formula_installer" <ide> require "unpack_strategy" <ide> <ide><path>Library/Homebrew/formula_assertions.rb <ide> <ide> module Homebrew <ide> module Assertions <del> require "rubygems" <ide> require "test/unit/assertions" <ide> include ::Test::Unit::Assertions <ide> <ide><path>Library/Homebrew/global.rb <ide> <ide> require_relative "load_path" <ide> <add>require "rubygems" <ide> require "active_support/core_ext/object/blank" <ide> require "active_support/core_ext/numeric/time" <ide> require "active_support/core_ext/array/access" <ide><path>Library/Homebrew/test/cask/cmd/style_spec.rb <ide> # frozen_string_literal: true <ide> <ide> require "open3" <del>require "rubygems" <ide> <ide> require_relative "shared_examples/invalid_option" <ide> <ide><path>Library/Homebrew/test/support/helper/spec/shared_context/integration_test.rb <ide> def brew(*args) <ide> "-I", $LOAD_PATH.join(File::PATH_SEPARATOR) <ide> ] <ide> if ENV["HOMEBREW_TESTS_COVERAGE"] <del> require "rubygems" <ide> simplecov_spec = Gem.loaded_specs["simplecov"] <ide> specs = [simplecov_spec] <ide> simplecov_spec.runtime_dependencies.each do |dep|
6
Text
Text
fix typo in obj detection's running_pets.md
c9bb58f2c86375dce38a80853f55fcf282a8b6cd
<ide><path>object_detection/g3doc/running_pets.md <ide> command from `tensorflow/models/object_detection`: <ide> ``` bash <ide> # From tensorflow/models <ide> gsutil cp gs://${YOUR_GCS_BUCKET}/train/model.ckpt-${CHECKPOINT_NUMBER}.* . <del>python object_detection/export_inference_graph \ <add>python object_detection/export_inference_graph.py \ <ide> --input_type image_tensor \ <ide> --pipeline_config_path object_detection/samples/configs/faster_rcnn_resnet101_pets.config \ <ide> --checkpoint_path model.ckpt-${CHECKPOINT_NUMBER} \
1
Java
Java
improve javadoc on requestentity#geturl
ae8b7973b408fac8dd666cbd03486227e440e820
<ide><path>spring-web/src/main/java/org/springframework/http/RequestEntity.java <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.web.util.UriTemplateHandler; <ide> <ide> /** <ide> * Extension of {@link HttpEntity} that also exposes the HTTP method and the <ide> public HttpMethod getMethod() { <ide> } <ide> <ide> /** <del> * Return the URL of the request. <add> * Return the {@link URI} for the target HTTP endpoint. <add> * <p><strong>Note:</strong> This method raises <add> * {@link UnsupportedOperationException} if the {@code RequestEntity} was <add> * created with a URI template and variables rather than with a {@link URI} <add> * instance. This is because a URI cannot be created without further input <add> * on how to expand template and encode the URI. In such cases, the <add> * {@code URI} is prepared by the <add> * {@link org.springframework.web.client.RestTemplate} with the help of the <add> * {@link UriTemplateHandler} it is configured with. <ide> */ <ide> public URI getUrl() { <ide> if (this.url == null) { <del> throw new UnsupportedOperationException(); <add> throw new UnsupportedOperationException( <add> "The RequestEntity was created with a URI template and variables, " + <add> "and there is not enough information on how to correctly expand and " + <add> "encode the URI template. This will be done by the RestTemplate instead " + <add> "with help from the UriTemplateHandler it is configured with."); <ide> } <ide> return this.url; <ide> }
1
Ruby
Ruby
show information based on build options
5b321ffb5a5308f1de96e7bfa79e83828e9c9552
<ide><path>Library/Homebrew/caveats.rb <ide> def initialize(f) <ide> <ide> def caveats <ide> caveats = [] <del> s = f.caveats.to_s <del> caveats << s.chomp + "\n" if s.length > 0 <add> begin <add> build, f.build = f.build, Tab.for_formula(f) <add> s = f.caveats.to_s <add> caveats << s.chomp + "\n" if s.length > 0 <add> ensure <add> f.build = build <add> end <ide> caveats << keg_only_text <ide> caveats << bash_completion_caveats <ide> caveats << zsh_completion_caveats
1
Java
Java
allow custom urlpathhelper for websocket requests
fc91add35ee7c51e854d80838bfceed545873801
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/ServletWebSocketHandlerRegistry.java <ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping; <ide> import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; <ide> import org.springframework.web.socket.WebSocketHandler; <add>import org.springframework.web.util.UrlPathHelper; <ide> <ide> /** <ide> * A {@link WebSocketHandlerRegistry} that maps {@link WebSocketHandler}s to URLs for use <ide> public class ServletWebSocketHandlerRegistry implements WebSocketHandlerRegistry <ide> <ide> private TaskScheduler sockJsTaskScheduler; <ide> <add> private int order = 1; <add> <add> private UrlPathHelper urlPathHelper; <add> <ide> <ide> public ServletWebSocketHandlerRegistry(ThreadPoolTaskScheduler sockJsTaskScheduler) { <ide> this.sockJsTaskScheduler = sockJsTaskScheduler; <ide> public WebSocketHandlerRegistration addHandler(WebSocketHandler webSocketHandler <ide> return registration; <ide> } <ide> <add> /** <add> * Set the order for the resulting {@link SimpleUrlHandlerMapping} relative to <add> * other handler mappings configured in Spring MVC. <add> * <p>The default value is 1. <add> */ <add> public void setOrder(int order) { <add> this.order = order; <add> } <add> <add> public int getOrder() { <add> return this.order; <add> } <add> <add> /** <add> * Set the UrlPathHelper to configure on the {@code SimpleUrlHandlerMapping} <add> * used to map handshake requests. <add> */ <add> public void setUrlPathHelper(UrlPathHelper urlPathHelper) { <add> this.urlPathHelper = urlPathHelper; <add> } <add> <add> public UrlPathHelper getUrlPathHelper() { <add> return this.urlPathHelper; <add> } <add> <ide> /** <ide> * Return a {@link HandlerMapping} with mapped {@link HttpRequestHandler}s. <ide> */ <ide> public AbstractHandlerMapping getHandlerMapping() { <ide> } <ide> SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping(); <ide> hm.setUrlMap(urlMap); <add> hm.setOrder(this.order); <add> if (this.urlPathHelper != null) { <add> hm.setUrlPathHelper(this.urlPathHelper); <add> } <ide> return hm; <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebMvcStompEndpointRegistry.java <ide> import org.springframework.web.socket.messaging.StompSubProtocolHandler; <ide> import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler; <ide> import org.springframework.web.socket.handler.WebSocketHandlerDecorator; <add>import org.springframework.web.util.UrlPathHelper; <ide> <ide> /** <ide> * A registry for STOMP over WebSocket endpoints that maps the endpoints with a <ide> public class WebMvcStompEndpointRegistry implements StompEndpointRegistry { <ide> <ide> private int order = 1; <ide> <add> private UrlPathHelper urlPathHelper; <add> <ide> <ide> public WebMvcStompEndpointRegistry(WebSocketHandler webSocketHandler, <ide> WebSocketTransportRegistration transportRegistration, <ide> public int getOrder() { <ide> return this.order; <ide> } <ide> <add> /** <add> * Set the UrlPathHelper to configure on the {@code SimpleUrlHandlerMapping} <add> * used to map handshake requests. <add> */ <add> public void setUrlPathHelper(UrlPathHelper urlPathHelper) { <add> this.urlPathHelper = urlPathHelper; <add> } <add> <add> public UrlPathHelper getUrlPathHelper() { <add> return this.urlPathHelper; <add> } <add> <ide> /** <ide> * Return a handler mapping with the mapped ViewControllers; or {@code null} in case of no registrations. <ide> */ <ide> public AbstractHandlerMapping getHandlerMapping() { <ide> SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping(); <ide> hm.setUrlMap(urlMap); <ide> hm.setOrder(this.order); <add> if (this.urlPathHelper != null) { <add> hm.setUrlPathHelper(this.urlPathHelper); <add> } <ide> return hm; <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketConfigurationSupport.java <ide> public HandlerMapping webSocketHandlerMapping() { <ide> ServletWebSocketHandlerRegistry registry = new ServletWebSocketHandlerRegistry(defaultSockJsTaskScheduler()); <ide> registerWebSocketHandlers(registry); <ide> AbstractHandlerMapping hm = registry.getHandlerMapping(); <del> hm.setOrder(1); <ide> return hm; <ide> } <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebMvcStompEndpointRegistryTests.java <ide> import org.springframework.web.socket.messaging.StompSubProtocolHandler; <ide> import org.springframework.web.socket.messaging.SubProtocolHandler; <ide> import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler; <add>import org.springframework.web.util.UrlPathHelper; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> public void handlerMapping() { <ide> SimpleUrlHandlerMapping hm = (SimpleUrlHandlerMapping) this.registry.getHandlerMapping(); <ide> assertEquals(0, hm.getUrlMap().size()); <ide> <add> UrlPathHelper pathHelper = new UrlPathHelper(); <add> this.registry.setUrlPathHelper(pathHelper); <ide> this.registry.addEndpoint("/stompOverWebSocket"); <ide> this.registry.addEndpoint("/stompOverSockJS").withSockJS(); <ide> <ide> hm = (SimpleUrlHandlerMapping) this.registry.getHandlerMapping(); <ide> assertEquals(2, hm.getUrlMap().size()); <ide> assertNotNull(hm.getUrlMap().get("/stompOverWebSocket")); <ide> assertNotNull(hm.getUrlMap().get("/stompOverSockJS/**")); <add> assertSame(pathHelper, hm.getUrlPathHelper()); <ide> } <ide> <ide> }
4
Java
Java
update copyright date
63c6a7e15efe741adc38a4bccaef389468bb808b
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.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><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAroundAdvice.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><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/config/AspectJAutoProxyBeanDefinitionParser.java <ide> /* <del> * Copyright 2002-2016 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><path>spring-aop/src/main/java/org/springframework/aop/config/ConfigBeanDefinitionParser.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/config/ScopedProxyBeanDefinitionDecorator.java <ide> /* <del> * Copyright 2002-2012 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><path>spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.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><path>spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.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><path>spring-aop/src/main/java/org/springframework/aop/framework/adapter/DefaultAdvisorAdapterRegistry.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisors.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><path>spring-aop/src/main/java/org/springframework/aop/scope/ScopedProxyFactoryBean.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/support/AbstractPointcutAdvisor.java <ide> /* <del> * Copyright 2002-2017 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><path>spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java <ide> /* <del> * Copyright 2002-2019 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><path>spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java <ide> /* <del> * Copyright 2002-2019 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><path>spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java <ide> /* <del> * Copyright 2002-2017 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><path>spring-aop/src/main/java/org/springframework/aop/support/MethodMatchers.java <ide> /* <del> * Copyright 2002-2019 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><path>spring-aop/src/main/java/org/springframework/aop/support/annotation/AnnotationClassFilter.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/support/annotation/AnnotationMatchingPointcut.java <ide> /* <del> * Copyright 2002-2019 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><path>spring-aop/src/main/java/org/springframework/aop/support/annotation/AnnotationMethodMatcher.java <ide> /* <del> * Copyright 2002-2019 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><path>spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java <ide> /* <del> * Copyright 2002-2018 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><path>spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java <ide> /* <del> * Copyright 2002-2018 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.
22
Text
Text
keep the names in sorted order
0a1859d33add447a75d858254f39c6d8639ab772
<ide><path>README.md <ide> Releases of Node.js and io.js will be signed with one of the following GPG keys: <ide> <ide> * **Chris Dickinson** &lt;christopher.s.dickinson@gmail.com&gt; `9554F04D7259F04124DE6B476D5A82AC7E37093B` <ide> * **Colin Ihrig** &lt;cjihrig@gmail.com&gt; `94AE36675C464D64BAFA68DD7434390BDBE9B9C5` <del>* **Sam Roberts** &lt;octetcloud@keybase.io&gt; `0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93` <del>* **Jeremiah Senkpiel** &lt;fishrock@keybase.io&gt; `FD3A5288F042B6850C66B31F09FE44734EB7990E` <add>* **Evan Lucas** &lt;evanlucas@me.com&gt; `B9AE9905FFD7803F25714661B63B535A4C206CA9` <ide> * **James M Snell** &lt;jasnell@keybase.io&gt; `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1` <del>* **Rod Vagg** &lt;rod@vagg.org&gt; `DD8F2338BAE7501E3DD5AC78C273792F7D83545D` <add>* **Jeremiah Senkpiel** &lt;fishrock@keybase.io&gt; `FD3A5288F042B6850C66B31F09FE44734EB7990E` <ide> * **Myles Borins** &lt;myles.borins@gmail.com&gt; `C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8` <del>* **Evan Lucas** &lt;evanlucas@me.com&gt; `B9AE9905FFD7803F25714661B63B535A4C206CA9` <add>* **Rod Vagg** &lt;rod@vagg.org&gt; `DD8F2338BAE7501E3DD5AC78C273792F7D83545D` <add>* **Sam Roberts** &lt;octetcloud@keybase.io&gt; `0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93` <ide> <ide> The full set of trusted release keys can be imported by running: <ide> <ide> details on what to do with these keys to verify that a downloaded file is offici <ide> Previous releases of Node.js have been signed with one of the following GPG <ide> keys: <ide> <del>* Julien Gilli &lt;jgilli@fastmail.fm&gt; `114F43EE0176B71C7BC219DD50A3051F888C628D` <del>* Timothy J Fontaine &lt;tjfontaine@gmail.com&gt; `7937DFD2AB06298B2293C3187D33FF9D0246406D` <del>* Isaac Z. Schlueter &lt;i@izs.me&gt; `93C7E9E91B49E432C2F75674B0A78B0A6C481CF6` <add>* **Isaac Z. Schlueter** &lt;i@izs.me&gt; `93C7E9E91B49E432C2F75674B0A78B0A6C481CF6` <add>* **Julien Gilli** &lt;jgilli@fastmail.fm&gt; `114F43EE0176B71C7BC219DD50A3051F888C628D` <add>* **Timothy J Fontaine** &lt;tjfontaine@gmail.com&gt; `7937DFD2AB06298B2293C3187D33FF9D0246406D`
1
PHP
PHP
change allowedsort -> sortablefields
d5d19497acfb8918a3c41393196ceca5ee00df19
<ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function implementedEvents(): array <ide> * $settings = [ <ide> * 'Articles' => [ <ide> * 'finder' => 'custom', <del> * 'allowedSort' => ['title', 'author_id', 'comment_count'], <add> * 'sortableFields' => ['title', 'author_id', 'comment_count'], <ide> * ] <ide> * ]; <ide> * ``` <ide><path>src/Datasource/Paginator.php <ide> class Paginator implements PaginatorInterface <ide> * $settings = [ <ide> * 'Articles' => [ <ide> * 'finder' => 'custom', <del> * 'allowedSort' => ['title', 'author_id', 'comment_count'], <add> * 'sortableFields' => ['title', 'author_id', 'comment_count'], <ide> * ] <ide> * ]; <ide> * ``` <ide> * <del> * Passing an empty array as allowedSort disallows sorting altogether. <add> * Passing an empty array as sortableFields disallows sorting altogether. <ide> * <ide> * ### Paginating with custom finders <ide> * <ide> protected function getAllowedParameters(): array <ide> } <ide> <ide> /** <del> * Shim method for reading the deprecated sortWhitelist or allowedSort options. <add> * Shim method for reading the deprecated sortWhitelist or sortableFields options. <ide> * <ide> * @param array $config The configuration data to coalesce and emit warnings on. <ide> * @return string[]|null <ide> */ <ide> protected function getAllowedSort(array $config): ?array <ide> { <del> $allowed = $config['allowedSort'] ?? null; <add> $allowed = $config['sortableFields'] ?? null; <ide> if ($allowed !== null) { <ide> return $allowed; <ide> } <ide> $deprecated = $config['sortWhitelist'] ?? null; <ide> if ($deprecated !== null) { <del> deprecationWarning('The `sortWhitelist` option is deprecated. Use `allowedSort` instead.'); <add> deprecationWarning('The `sortWhitelist` option is deprecated. Use `sortableFields` instead.'); <ide> } <ide> <ide> return $deprecated; <ide> public function getDefaults(string $alias, array $settings): array <ide> * result sets on un-indexed values. <ide> * <ide> * If you need to sort on associated columns or synthetic properties you <del> * will need to use the `allowedSort` option. <add> * will need to use the `sortableFields` option. <ide> * <ide> * Any columns listed in the allowed sort fields will be implicitly trusted. <ide> * You can use this to sort on synthetic columns, or columns added in custom <ide> public function validateSort(RepositoryInterface $object, array $options): array <ide> $sortAllowed = false; <ide> $allowed = $this->getAllowedSort($options); <ide> if ($allowed !== null) { <del> $options['allowedSort'] = $options['sortWhitelist'] = $allowed; <add> $options['sortableFields'] = $options['sortWhitelist'] = $allowed; <ide> <ide> $field = key($options['order']); <ide> $sortAllowed = in_array($field, $allowed, true); <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function testOutOfVeryBigPageNumberGetsClamped(): void <ide> } <ide> <ide> /** <del> * test that fields not in allowedSort won't be part of order conditions. <add> * test that fields not in sortableFields won't be part of order conditions. <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortFailure(): void <ide> $options = [ <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'allowedSort' => ['title', 'id'], <add> 'sortableFields' => ['title', 'id'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> $this->assertEquals([], $result['order']); <ide> } <ide> <ide> /** <del> * test that fields in the allowedSort are not validated <add> * test that fields in the sortableFields are not validated <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortTrusted(): void <ide> $options = [ <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'allowedSort' => ['body'], <add> 'sortableFields' => ['body'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateAllowedSortTrusted(): void <ide> } <ide> <ide> /** <del> * test that allowedSort as empty array does not allow any sorting <add> * test that sortableFields as empty array does not allow any sorting <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortEmpty(): void <ide> ], <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'allowedSort' => [], <add> 'sortableFields' => [], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> $this->assertSame([], $result['order'], 'No sort should be applied'); <ide> } <ide> <ide> /** <del> * test that fields in the allowedSort are not validated <add> * test that fields in the sortableFields are not validated <ide> * <ide> * @return void <ide> */ <ide> public function testValidateSortNotInSchema(): void <ide> $options = [ <ide> 'sort' => 'score', <ide> 'direction' => 'asc', <del> 'allowedSort' => ['score'], <add> 'sortableFields' => ['score'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortNotInSchema(): void <ide> } <ide> <ide> /** <del> * test that multiple fields in the allowedSort are not validated and properly aliased. <add> * test that multiple fields in the sortableFields are not validated and properly aliased. <ide> * <ide> * @return void <ide> */ <ide> public function testValidateSortAllowMultiple(): void <ide> 'body' => 'asc', <ide> 'foo.bar' => 'asc', <ide> ], <del> 'allowedSort' => ['body', 'foo.bar'], <add> 'sortableFields' => ['body', 'foo.bar'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortNoSort(): void <ide> <ide> $options = [ <ide> 'direction' => 'asc', <del> 'allowedSort' => ['title', 'id'], <add> 'sortableFields' => ['title', 'id'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> $this->assertEquals([], $result['order']); <ide><path>tests/TestCase/Datasource/PaginatorTestTrait.php <ide> public function testValidaSortInitialSortAndDirection() <ide> 'sort' => 'id', <ide> 'scope' => null, <ide> 'sortWhitelist' => ['id'], <del> 'allowedSort' => ['id'], <add> 'sortableFields' => ['id'], <ide> ]); <ide> <ide> $options = [ <ide> 'order' => [ <ide> 'id' => 'asc', <ide> ], <del> 'allowedSort' => ['id'], <add> 'sortableFields' => ['id'], <ide> ]; <ide> $this->Paginator->paginate($table, [], $options); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> public function testValidateSortRetainsOriginalSortValue() <ide> 'allowedParameters' => ['limit', 'sort', 'page', 'direction'], <ide> 'scope' => null, <ide> 'sortWhitelist' => ['id'], <del> 'allowedSort' => ['id'], <add> 'sortableFields' => ['id'], <ide> 'sort' => 'id', <ide> ]); <ide> <ide> public function testValidateSortRetainsOriginalSortValue() <ide> 'direction' => 'herp', <ide> ]; <ide> $options = [ <del> 'allowedSort' => ['id'], <add> 'sortableFields' => ['id'], <ide> ]; <ide> $this->Paginator->paginate($table, $params, $options); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> public function testOutOfVeryBigPageNumberGetsClamped() <ide> } <ide> <ide> /** <del> * test that fields not in allowedSort won't be part of order conditions. <add> * test that fields not in sortableFields won't be part of order conditions. <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortFailure() <ide> $options = [ <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'allowedSort' => ['title', 'id'], <add> 'sortableFields' => ['title', 'id'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWhitelistFailure() <ide> } <ide> <ide> /** <del> * test that fields in the allowedSort are not validated <add> * test that fields in the sortableFields are not validated <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortTrusted() <ide> } <ide> <ide> /** <del> * test that allowedSort as empty array does not allow any sorting <add> * test that sortableFields as empty array does not allow any sorting <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortEmpty() <ide> ], <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'allowedSort' => [], <add> 'sortableFields' => [], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> $this->assertSame([], $result['order'], 'No sort should be applied'); <ide> } <ide> <ide> /** <del> * test that fields in the allowedSort are not validated <add> * test that fields in the sortableFields are not validated <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortNotInSchema() <ide> $options = [ <ide> 'sort' => 'score', <ide> 'direction' => 'asc', <del> 'allowedSort' => ['score'], <add> 'sortableFields' => ['score'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateAllowedSortNotInSchema() <ide> } <ide> <ide> /** <del> * test that multiple fields in the allowedSort are not validated and properly aliased. <add> * test that multiple fields in the sortableFields are not validated and properly aliased. <ide> * <ide> * @return void <ide> */ <ide> public function testValidateAllowedSortMultiple() <ide> 'body' => 'asc', <ide> 'foo.bar' => 'asc', <ide> ], <del> 'allowedSort' => ['body', 'foo.bar'], <add> 'sortableFields' => ['body', 'foo.bar'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortNoSort() <ide> <ide> $options = [ <ide> 'direction' => 'asc', <del> 'allowedSort' => ['title', 'id'], <add> 'sortableFields' => ['title', 'id'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> $this->assertEquals([], $result['order']);
4
Python
Python
remove bad security advice about send_file
29f7c10a5dea499f64188e29a4e08161dbf14eff
<ide><path>flask/helpers.py <ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False, <ide> guessing requires a `filename` or an `attachment_filename` to be <ide> provided. <ide> <del> Please never pass filenames to this function from user sources without <del> checking them first. Something like this is usually sufficient to <del> avoid security problems:: <del> <del> if '..' in filename or filename.startswith('/'): <del> abort(404) <add> Please never pass filenames to this function from user sources; <add> you should use :func:`send_from_directory` instead. <ide> <ide> .. versionadded:: 0.2 <ide>
1
Text
Text
add energy solutions to inthewild.md
fd62f603028319bb4ae7d857d9d70feddb6633bd
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Elai Data](https://www.elaidata.com/) [[@lgov](https://github.com/lgov)] <ide> 1. [EllisDon](http://www.ellisdon.com/) [[@d2kalra](https://github.com/d2kalra) & [@zbasama](https://github.com/zbasama)] <ide> 1. [Endesa](https://www.endesa.com) [[@drexpp](https://github.com/drexpp)] <add>1. [Energy Solutions](https://www.energy-solution.com) [[@energy-solution](https://github.com/energy-solution/)] <ide> 1. [Enigma](https://www.enigma.com) [[@hydrosquall](https://github.com/hydrosquall)] <ide> 1. [Etsy](https://www.etsy.com) [[@mchalek](https://github.com/mchalek)] <ide> 1. [Everis](https://www.everis.com) [[@diegobenedicto](https://github.com/diegobenedicto)]
1
Go
Go
keep parser.directive internal to parser
64c4c1c3d5e0fe364d83db5a8dc99a24fd121754
<ide><path>builder/dockerfile/builder.go <ide> type Builder struct { <ide> disableCommit bool <ide> cacheBusted bool <ide> buildArgs *buildArgs <del> directive *parser.Directive <add> escapeToken rune <ide> <ide> imageCache builder.ImageCache <ide> from builder.Image <ide> func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, back <ide> runConfig: new(container.Config), <ide> tmpContainers: map[string]struct{}{}, <ide> buildArgs: newBuildArgs(config.BuildArgs), <del> directive: parser.NewDefaultDirective(), <add> escapeToken: parser.DefaultEscapeToken, <ide> } <ide> b.imageContexts = &imageContexts{b: b} <ide> return b, nil <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> return "", err <ide> } <ide> <del> addNodesForLabelOption(dockerfile, b.options.Labels) <add> addNodesForLabelOption(dockerfile.AST, b.options.Labels) <ide> <del> if err := checkDispatchDockerfile(dockerfile); err != nil { <add> if err := checkDispatchDockerfile(dockerfile.AST); err != nil { <ide> return "", err <ide> } <ide> <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> return b.image, nil <ide> } <ide> <del>func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Node) (string, error) { <del> total := len(dockerfile.Children) <add>func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Result) (string, error) { <add> // TODO: pass this to dispatchRequest instead <add> b.escapeToken = dockerfile.EscapeToken <add> <add> total := len(dockerfile.AST.Children) <ide> var shortImgID string <del> for i, n := range dockerfile.Children { <add> for i, n := range dockerfile.AST.Children { <ide> select { <ide> case <-b.clientCtx.Done(): <ide> logrus.Debug("Builder: build cancelled!") <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> return nil, err <ide> } <ide> <del> ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")), b.directive) <add> result, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n"))) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> // ensure that the commands are valid <del> for _, n := range ast.Children { <add> for _, n := range result.AST.Children { <ide> if !validCommitCommands[n.Value] { <ide> return nil, fmt.Errorf("%s is not a valid change command", n.Value) <ide> } <ide> func BuildFromConfig(config *container.Config, changes []string) (*container.Con <ide> b.Stderr = ioutil.Discard <ide> b.disableCommit = true <ide> <del> if err := checkDispatchDockerfile(ast); err != nil { <add> if err := checkDispatchDockerfile(result.AST); err != nil { <ide> return nil, err <ide> } <ide> <del> if err := dispatchFromDockerfile(b, ast); err != nil { <add> if err := dispatchFromDockerfile(b, result); err != nil { <ide> return nil, err <ide> } <ide> return b.runConfig, nil <ide> func checkDispatchDockerfile(dockerfile *parser.Node) error { <ide> return nil <ide> } <ide> <del>func dispatchFromDockerfile(b *Builder, ast *parser.Node) error { <add>func dispatchFromDockerfile(b *Builder, result *parser.Result) error { <add> // TODO: pass this to dispatchRequest instead <add> b.escapeToken = result.EscapeToken <add> ast := result.AST <ide> total := len(ast.Children) <add> <ide> for i, n := range ast.Children { <ide> if err := b.dispatch(i, total, n); err != nil { <ide> return err <ide><path>builder/dockerfile/builder_test.go <ide> import ( <ide> <ide> func TestAddNodesForLabelOption(t *testing.T) { <ide> dockerfile := "FROM scratch" <del> d := parser.NewDefaultDirective() <del> nodes, err := parser.Parse(strings.NewReader(dockerfile), d) <add> result, err := parser.Parse(strings.NewReader(dockerfile)) <ide> assert.NilError(t, err) <ide> <ide> labels := map[string]string{ <ide> func TestAddNodesForLabelOption(t *testing.T) { <ide> "org.b": "cli-b", <ide> "org.a": "cli-a", <ide> } <add> nodes := result.AST <ide> addNodesForLabelOption(nodes, labels) <ide> <ide> expected := []string{ <ide><path>builder/dockerfile/dispatchers.go <ide> func from(b *Builder, args []string, attributes map[string]bool, original string <ide> substituionArgs = append(substituionArgs, key+"="+value) <ide> } <ide> <del> name, err := ProcessWord(args[0], substituionArgs, b.directive.EscapeToken()) <add> name, err := ProcessWord(args[0], substituionArgs, b.escapeToken) <ide> if err != nil { <ide> return err <ide> } <ide><path>builder/dockerfile/dispatchers_test.go <ide> import ( <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/strslice" <ide> "github.com/docker/docker/builder" <del> "github.com/docker/docker/builder/dockerfile/parser" <ide> "github.com/docker/docker/pkg/testutil/assert" <ide> "github.com/docker/go-connections/nat" <ide> ) <ide> func newBuilderWithMockBackend() *Builder { <ide> options: &types.ImageBuildOptions{}, <ide> docker: &MockBackend{}, <ide> buildArgs: newBuildArgs(make(map[string]*string)), <del> directive: parser.NewDefaultDirective(), <ide> } <ide> b.imageContexts = &imageContexts{b: b} <ide> return b <ide><path>builder/dockerfile/evaluator.go <ide> func (b *Builder) evaluateEnv(cmd string, str string, envs []string) ([]string, <ide> return []string{word}, err <ide> } <ide> } <del> return processFunc(str, envs, b.directive.EscapeToken()) <add> return processFunc(str, envs, b.escapeToken) <ide> } <ide> <ide> // buildArgsWithoutConfigEnv returns a list of key=value pairs for all the build <ide><path>builder/dockerfile/evaluator_test.go <ide> func executeTestCase(t *testing.T, testCase dispatchTestCase) { <ide> }() <ide> <ide> r := strings.NewReader(testCase.dockerfile) <del> n, err := parser.Parse(r, parser.NewDefaultDirective()) <add> result, err := parser.Parse(r) <ide> <ide> if err != nil { <ide> t.Fatalf("Error when parsing Dockerfile: %s", err) <ide> func executeTestCase(t *testing.T, testCase dispatchTestCase) { <ide> Stdout: ioutil.Discard, <ide> context: context, <ide> buildArgs: newBuildArgs(options.BuildArgs), <del> directive: parser.NewDefaultDirective(), <ide> } <ide> <add> n := result.AST <ide> err = b.dispatch(0, len(n.Children), n.Children[0]) <ide> <ide> if err == nil { <ide><path>builder/dockerfile/internals.go <ide> func (b *Builder) processImageFrom(img builder.Image) error { <ide> <ide> // parse the ONBUILD triggers by invoking the parser <ide> for _, step := range onBuildTriggers { <del> ast, err := parser.Parse(strings.NewReader(step), b.directive) <add> result, err := parser.Parse(strings.NewReader(step)) <ide> if err != nil { <ide> return err <ide> } <ide> <del> for _, n := range ast.Children { <add> for _, n := range result.AST.Children { <ide> if err := checkDispatch(n); err != nil { <ide> return err <ide> } <ide> func (b *Builder) processImageFrom(img builder.Image) error { <ide> } <ide> } <ide> <del> if err := dispatchFromDockerfile(b, ast); err != nil { <add> if err := dispatchFromDockerfile(b, result); err != nil { <ide> return err <ide> } <ide> } <ide> func (b *Builder) clearTmp() { <ide> } <ide> <ide> // readAndParseDockerfile reads a Dockerfile from the current context. <del>func (b *Builder) readAndParseDockerfile() (*parser.Node, error) { <add>func (b *Builder) readAndParseDockerfile() (*parser.Result, error) { <ide> // If no -f was specified then look for 'Dockerfile'. If we can't find <ide> // that then look for 'dockerfile'. If neither are found then default <ide> // back to 'Dockerfile' and use that in the error message. <ide> func (b *Builder) readAndParseDockerfile() (*parser.Node, error) { <ide> } <ide> } <ide> <del> nodes, err := b.parseDockerfile() <add> result, err := b.parseDockerfile() <ide> if err != nil { <del> return nodes, err <add> return nil, err <ide> } <ide> <ide> // After the Dockerfile has been parsed, we need to check the .dockerignore <ide> func (b *Builder) readAndParseDockerfile() (*parser.Node, error) { <ide> if dockerIgnore, ok := b.context.(builder.DockerIgnoreContext); ok { <ide> dockerIgnore.Process([]string{b.options.Dockerfile}) <ide> } <del> return nodes, nil <add> return result, nil <ide> } <ide> <del>func (b *Builder) parseDockerfile() (*parser.Node, error) { <add>func (b *Builder) parseDockerfile() (*parser.Result, error) { <ide> f, err := b.context.Open(b.options.Dockerfile) <ide> if err != nil { <ide> if os.IsNotExist(err) { <ide> func (b *Builder) parseDockerfile() (*parser.Node, error) { <ide> return nil, fmt.Errorf("The Dockerfile (%s) cannot be empty", b.options.Dockerfile) <ide> } <ide> } <del> return parser.Parse(f, b.directive) <add> return parser.Parse(f) <ide> } <ide><path>builder/dockerfile/parser/dumper/main.go <ide> import ( <ide> "os" <ide> <ide> "github.com/docker/docker/builder/dockerfile/parser" <add> "go/ast" <ide> ) <ide> <ide> func main() { <ide> func main() { <ide> } <ide> defer f.Close() <ide> <del> d := parser.NewDefaultDirective() <del> ast, err := parser.Parse(f, d) <add> result, err := parser.Parse(f) <ide> if err != nil { <ide> panic(err) <del> } else { <del> fmt.Println(ast.Dump()) <ide> } <add> fmt.Println(result.AST.Dump()) <ide> } <ide> } <ide><path>builder/dockerfile/parser/json_test.go <ide> var validJSONArraysOfStrings = map[string][]string{ <ide> <ide> func TestJSONArraysOfStrings(t *testing.T) { <ide> for json, expected := range validJSONArraysOfStrings { <del> d := Directive{} <del> d.SetEscapeToken(DefaultEscapeToken) <add> d := NewDefaultDirective() <ide> <del> if node, _, err := parseJSON(json, &d); err != nil { <add> if node, _, err := parseJSON(json, d); err != nil { <ide> t.Fatalf("%q should be a valid JSON array of strings, but wasn't! (err: %q)", json, err) <ide> } else { <ide> i := 0 <ide> func TestJSONArraysOfStrings(t *testing.T) { <ide> } <ide> } <ide> for _, json := range invalidJSONArraysOfStrings { <del> d := Directive{} <del> d.SetEscapeToken(DefaultEscapeToken) <add> d := NewDefaultDirective() <ide> <del> if _, _, err := parseJSON(json, &d); err != errDockerfileNotStringArray { <add> if _, _, err := parseJSON(json, d); err != errDockerfileNotStringArray { <ide> t.Fatalf("%q should be an invalid JSON array of strings, but wasn't!", json) <ide> } <ide> } <ide><path>builder/dockerfile/parser/parser.go <ide> type Node struct { <ide> Original string // original line used before parsing <ide> Flags []string // only top Node should have this set <ide> StartLine int // the line in the original dockerfile where the node begins <del> EndLine int // the line in the original dockerfile where the node ends <add> endLine int // the line in the original dockerfile where the node ends <ide> } <ide> <ide> // Dump dumps the AST defined by `node` as a list of sexps. <ide> var ( <ide> ) <ide> <ide> // DefaultEscapeToken is the default escape token <del>const DefaultEscapeToken = "\\" <add>const DefaultEscapeToken = '\\' <ide> <ide> // Directive is the structure used during a build run to hold the state of <ide> // parsing directives. <ide> type Directive struct { <ide> escapeSeen bool // Whether the escape directive has been seen <ide> } <ide> <del>// SetEscapeToken sets the default token for escaping characters in a Dockerfile. <del>func (d *Directive) SetEscapeToken(s string) error { <add>// setEscapeToken sets the default token for escaping characters in a Dockerfile. <add>func (d *Directive) setEscapeToken(s string) error { <ide> if s != "`" && s != "\\" { <ide> return fmt.Errorf("invalid ESCAPE '%s'. Must be ` or \\", s) <ide> } <ide> func (d *Directive) SetEscapeToken(s string) error { <ide> return nil <ide> } <ide> <del>// EscapeToken returns the escape token <del>func (d *Directive) EscapeToken() rune { <del> return d.escapeToken <del>} <del> <ide> // NewDefaultDirective returns a new Directive with the default escapeToken token <ide> func NewDefaultDirective() *Directive { <ide> directive := Directive{ <ide> escapeSeen: false, <ide> lookingForDirectives: true, <ide> } <del> directive.SetEscapeToken(DefaultEscapeToken) <add> directive.setEscapeToken(string(DefaultEscapeToken)) <ide> return &directive <ide> } <ide> <ide> func handleParserDirective(line string, d *Directive) (bool, error) { <ide> } <ide> for i, n := range tokenEscapeCommand.SubexpNames() { <ide> if n == "escapechar" { <del> if err := d.SetEscapeToken(tecMatch[i]); err != nil { <add> if err := d.setEscapeToken(tecMatch[i]); err != nil { <ide> return false, err <ide> } <ide> return true, nil <ide> func handleParserDirective(line string, d *Directive) (bool, error) { <ide> return false, nil <ide> } <ide> <del>// Parse is the main parse routine. <del>// It handles an io.ReadWriteCloser and returns the root of the AST. <del>func Parse(rwc io.Reader, d *Directive) (*Node, error) { <add>// Result is the result of parsing a Dockerfile <add>type Result struct { <add> AST *Node <add> EscapeToken rune <add>} <add> <add>// Parse reads lines from a Reader, parses the lines into an AST and returns <add>// the AST and escape token <add>func Parse(rwc io.Reader) (*Result, error) { <add> d := NewDefaultDirective() <ide> currentLine := 0 <ide> root := &Node{} <ide> root.StartLine = -1 <ide> func Parse(rwc io.Reader, d *Directive) (*Node, error) { <ide> if child != nil { <ide> // Update the line information for the current child. <ide> child.StartLine = startLine <del> child.EndLine = currentLine <add> child.endLine = currentLine <ide> // Update the line information for the root. The starting line of the root is always the <ide> // starting line of the first child and the ending line is the ending line of the last child. <ide> if root.StartLine < 0 { <ide> root.StartLine = currentLine <ide> } <del> root.EndLine = currentLine <add> root.endLine = currentLine <ide> root.Children = append(root.Children, child) <ide> } <ide> } <ide> <del> return root, nil <add> return &Result{AST: root, EscapeToken: d.escapeToken}, nil <ide> } <ide> <ide> // covers comments and empty lines. Lines should be trimmed before passing to <ide><path>builder/dockerfile/parser/parser_test.go <ide> import ( <ide> "path/filepath" <ide> "runtime" <ide> "testing" <add> <add> "github.com/docker/docker/pkg/testutil/assert" <ide> ) <ide> <ide> const testDir = "testfiles" <ide> const testFileLineInfo = "testfile-line/Dockerfile" <ide> <ide> func getDirs(t *testing.T, dir string) []string { <ide> f, err := os.Open(dir) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <add> assert.NilError(t, err) <ide> defer f.Close() <ide> <ide> dirs, err := f.Readdirnames(0) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <add> assert.NilError(t, err) <ide> return dirs <ide> } <ide> <ide> func TestTestNegative(t *testing.T) { <ide> dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile") <ide> <ide> df, err := os.Open(dockerfile) <del> if err != nil { <del> t.Fatalf("Dockerfile missing for %s: %v", dir, err) <del> } <add> assert.NilError(t, err) <ide> defer df.Close() <ide> <del> _, err = Parse(df, NewDefaultDirective()) <del> if err == nil { <del> t.Fatalf("No error parsing broken dockerfile for %s", dir) <del> } <add> _, err = Parse(df) <add> assert.Error(t, err, "") <ide> } <ide> } <ide> <ide> func TestTestData(t *testing.T) { <ide> resultfile := filepath.Join(testDir, dir, "result") <ide> <ide> df, err := os.Open(dockerfile) <del> if err != nil { <del> t.Fatalf("Dockerfile missing for %s: %v", dir, err) <del> } <add> assert.NilError(t, err) <ide> defer df.Close() <ide> <del> ast, err := Parse(df, NewDefaultDirective()) <del> if err != nil { <del> t.Fatalf("Error parsing %s's dockerfile: %v", dir, err) <del> } <add> result, err := Parse(df) <add> assert.NilError(t, err) <ide> <ide> content, err := ioutil.ReadFile(resultfile) <del> if err != nil { <del> t.Fatalf("Error reading %s's result file: %v", dir, err) <del> } <add> assert.NilError(t, err) <ide> <ide> if runtime.GOOS == "windows" { <ide> // CRLF --> CR to match Unix behavior <ide> content = bytes.Replace(content, []byte{'\x0d', '\x0a'}, []byte{'\x0a'}, -1) <ide> } <ide> <del> if ast.Dump()+"\n" != string(content) { <del> fmt.Fprintln(os.Stderr, "Result:\n"+ast.Dump()) <del> fmt.Fprintln(os.Stderr, "Expected:\n"+string(content)) <del> t.Fatalf("%s: AST dump of dockerfile does not match result", dir) <del> } <add> assert.Equal(t, result.AST.Dump()+"\n", string(content)) <ide> } <ide> } <ide> <ide> func TestParseWords(t *testing.T) { <ide> <ide> for _, test := range tests { <ide> words := parseWords(test["input"][0], NewDefaultDirective()) <del> if len(words) != len(test["expect"]) { <del> t.Fatalf("length check failed. input: %v, expect: %q, output: %q", test["input"][0], test["expect"], words) <del> } <del> for i, word := range words { <del> if word != test["expect"][i] { <del> t.Fatalf("word check failed for word: %q. input: %q, expect: %q, output: %q", word, test["input"][0], test["expect"], words) <del> } <del> } <add> assert.DeepEqual(t, words, test["expect"]) <ide> } <ide> } <ide> <ide> func TestLineInformation(t *testing.T) { <ide> df, err := os.Open(testFileLineInfo) <del> if err != nil { <del> t.Fatalf("Dockerfile missing for %s: %v", testFileLineInfo, err) <del> } <add> assert.NilError(t, err) <ide> defer df.Close() <ide> <del> ast, err := Parse(df, NewDefaultDirective()) <del> if err != nil { <del> t.Fatalf("Error parsing dockerfile %s: %v", testFileLineInfo, err) <del> } <add> result, err := Parse(df) <add> assert.NilError(t, err) <ide> <del> if ast.StartLine != 5 || ast.EndLine != 31 { <del> fmt.Fprintf(os.Stderr, "Wrong root line information: expected(%d-%d), actual(%d-%d)\n", 5, 31, ast.StartLine, ast.EndLine) <add> ast := result.AST <add> if ast.StartLine != 5 || ast.endLine != 31 { <add> fmt.Fprintf(os.Stderr, "Wrong root line information: expected(%d-%d), actual(%d-%d)\n", 5, 31, ast.StartLine, ast.endLine) <ide> t.Fatal("Root line information doesn't match result.") <ide> } <del> if len(ast.Children) != 3 { <del> fmt.Fprintf(os.Stderr, "Wrong number of child: expected(%d), actual(%d)\n", 3, len(ast.Children)) <del> t.Fatalf("Root line information doesn't match result for %s", testFileLineInfo) <del> } <add> assert.Equal(t, len(ast.Children), 3) <ide> expected := [][]int{ <ide> {5, 5}, <ide> {11, 12}, <ide> {17, 31}, <ide> } <ide> for i, child := range ast.Children { <del> if child.StartLine != expected[i][0] || child.EndLine != expected[i][1] { <add> if child.StartLine != expected[i][0] || child.endLine != expected[i][1] { <ide> t.Logf("Wrong line information for child %d: expected(%d-%d), actual(%d-%d)\n", <del> i, expected[i][0], expected[i][1], child.StartLine, child.EndLine) <add> i, expected[i][0], expected[i][1], child.StartLine, child.endLine) <ide> t.Fatal("Root line information doesn't match result.") <ide> } <ide> }
11
Ruby
Ruby
add migrate command for migrating renamed
abf6b6f6cf31277ec1350fc7f7d16a7d23de882a
<ide><path>Library/Homebrew/cmd/migrate.rb <add>require "migrator" <add>require "formula_renames" <add> <add>module Homebrew <add> def migrate <add> raise FormulaUnspecifiedError if ARGV.named.empty? <add> <add> ARGV.resolved_formulae.each do |f| <add> if f.oldname <add> unless (rack = HOMEBREW_CELLAR/f.oldname).exist? && !rack.subdirs.empty? <add> raise NoSuchKegError, f.oldname <add> end <add> raise "#{rack} is a symlink" if rack.symlink? <add> end <add> <add> migrator = Migrator.new(f) <add> migrator.migrate <add> end <add> end <add>end
1
Python
Python
implement batch shuffle
48ea8dfb4748a57c90801f1cfd570b26996e365a
<ide><path>keras/models.py <ide> def standardize_y(y): <ide> y = np.expand_dims(y, 1) <ide> return y <ide> <add>def batch_shuffle(index_array, batch_size): <add> batch_count = int(len(index_array)/batch_size) <add> # to reshape we need to be cleanly divisible by batch size <add> # we stash extra items and reappend them after shuffling <add> last_batch = index_array[batch_count*batch_size:] <add> index_array = index_array[:batch_count*batch_size] <add> index_array = index_array.reshape((batch_count, batch_size)) <add> np.random.shuffle(index_array) <add> index_array = index_array.flatten() <add> return np.append(index_array, last_batch) <add> <ide> <ide> def make_batches(size, batch_size): <ide> nb_batch = int(np.ceil(size/float(batch_size))) <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, c <ide> self.stop_training = False <ide> for epoch in range(nb_epoch): <ide> callbacks.on_epoch_begin(epoch) <del> if shuffle: <add> if shuffle == 'batch': <add> index_array = batch_shuffle(index_array, batch_size) <add> elif shuffle: <ide> np.random.shuffle(index_array) <ide> <ide> batches = make_batches(nb_train_sample, batch_size)
1
Go
Go
remove old struct
da1a77defd765b5caf3336825292e1ecd8a7d320
<ide><path>daemon/inspect.go <ide> import ( <ide> "fmt" <ide> <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/runconfig" <ide> ) <ide> <del>type ContainerJSONRaw struct { <del> *Container <del> HostConfig *runconfig.HostConfig <del> <del> // Unused fields for backward compatibility with API versions < 1.12. <del> Volumes map[string]string <del> VolumesRW map[string]bool <del>} <del> <ide> func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error) { <ide> container, err := daemon.Get(name) <ide> if err != nil {
1
Javascript
Javascript
remove settimeout in test-net-connect-unref
586a7a4b1326dbc0603593edbc12aaec43dbe682
<ide><path>test/internet/test-net-connect-unref.js <ide> const common = require('../common'); <ide> const net = require('net'); <ide> <del>const TIMEOUT = 10 * 1000; <del> <ide> const client = net.createConnection(53, '8.8.8.8', function() { <ide> client.unref(); <ide> }); <ide> <ide> client.on('close', common.mustNotCall()); <del> <del>setTimeout(common.mustNotCall(), TIMEOUT).unref();
1
Ruby
Ruby
add fuzzy search results
d455ca937784aa4e1b282579064202cafb780c34
<ide><path>Library/Homebrew/search.rb <ide> def search_formulae(string_or_regex) <ide> .search(string_or_regex) <ide> .sort <ide> <add> results += Formula.fuzzy_search(string_or_regex) <add> <ide> results.map do |name| <ide> formula, canonical_full_name = begin <ide> f = Formulary.factory(name)
1
Javascript
Javascript
load all babel libs dynamically
21833ab508194ed27a5b2fb8cb782a41a6e789dd
<ide><path>client/src/templates/Challenges/rechallenge/transformers.js <ide> import { <ide> stubTrue <ide> } from 'lodash'; <ide> <del>import * as Babel from '@babel/standalone'; <del>import presetEnv from '@babel/preset-env'; <del>import presetReact from '@babel/preset-react'; <ide> import protect from '@freecodecamp/loop-protect'; <ide> <ide> import * as vinyl from '../utils/polyvinyl.js'; <ide> function testLoopProtectCB(line) { <ide> ); <ide> } <ide> <del>Babel.registerPlugin('loopProtection', protect(protectTimeout, loopProtectCB)); <del>Babel.registerPlugin( <del> 'testLoopProtection', <del> protect(testProtectTimeout, testLoopProtectCB, loopsPerTimeoutCheck) <del>); <add>// hold Babel, presets and options so we don't try to import them multiple times <ide> <del>const babelOptionsJSBase = { <del> presets: [presetEnv] <del>}; <del> <del>const babelOptionsJSX = { <del> plugins: ['loopProtection'], <del> presets: [presetEnv, presetReact] <del>}; <del> <del>const babelOptionsJS = { <del> ...babelOptionsJSBase, <del> plugins: ['testLoopProtection'] <del>}; <add>let Babel; <add>let presetEnv, presetReact; <add>let babelOptionsJSBase, babelOptionsJS, babelOptionsJSX, babelOptionsJSPreview; <ide> <del>const babelOptionsJSPreview = { <del> ...babelOptionsJSBase, <del> plugins: ['loopProtection'] <del>}; <add>async function loadBabel() { <add> if (Babel) return; <add> /* eslint-disable no-inline-comments */ <add> Babel = await import( <add> /* webpackChunkName: "@babel/standalone" */ '@babel/standalone' <add> ); <add> presetEnv = await import( <add> /* webpackChunkName: "@babel/preset-env" */ '@babel/preset-env' <add> ); <add> presetReact = await import( <add> /* webpackChunkName: "@babel/preset-react" */ '@babel/preset-react' <add> ); <add> /* eslint-enable no-inline-comments */ <add> Babel.registerPlugin( <add> 'loopProtection', <add> protect(protectTimeout, loopProtectCB) <add> ); <add> Babel.registerPlugin( <add> 'testLoopProtection', <add> protect(testProtectTimeout, testLoopProtectCB, loopsPerTimeoutCheck) <add> ); <add> babelOptionsJSBase = { <add> presets: [presetEnv] <add> }; <add> babelOptionsJSX = { <add> plugins: ['loopProtection'], <add> presets: [presetEnv, presetReact] <add> }; <add> babelOptionsJS = { <add> ...babelOptionsJSBase, <add> plugins: ['testLoopProtection'] <add> }; <add> babelOptionsJSPreview = { <add> ...babelOptionsJSBase, <add> plugins: ['loopProtection'] <add> }; <add>} <ide> <ide> const babelTransformCode = options => code => <ide> Babel.transform(code, options).code; <ide> const babelTransformer = ({ preview = false, protect = true }) => { <ide> return cond([ <ide> [ <ide> testJS, <del> flow( <del> partial( <add> async code => { <add> await loadBabel(); <add> return partial( <ide> vinyl.transformHeadTailAndContents, <ide> tryTransform(babelTransformCode(options)) <del> ) <del> ) <add> )(code); <add> } <ide> ], <ide> [ <ide> testJSX, <del> flow( <del> partial( <del> vinyl.transformHeadTailAndContents, <del> tryTransform(babelTransformCode(babelOptionsJSX)) <del> ), <del> partial(vinyl.setExt, 'js') <del> ) <add> async code => { <add> await loadBabel(); <add> return flow( <add> partial( <add> vinyl.transformHeadTailAndContents, <add> tryTransform(babelTransformCode(babelOptionsJSX)) <add> ), <add> partial(vinyl.setExt, 'js') <add> )(code); <add> } <ide> ], <ide> [stubTrue, identity] <ide> ]); <ide> async function transformSASS(element) { <ide> ); <ide> } <ide> <del>function transformScript(element) { <add>async function transformScript(element) { <add> await loadBabel(); <ide> const scriptTags = element.querySelectorAll('script'); <ide> scriptTags.forEach(script => { <ide> script.innerHTML = tryTransform(babelTransformCode(babelOptionsJSX))(
1
Text
Text
fix createportal link in api docs
e3d710e60a691b4d7dddbf90e33b0d624e89dd7a
<ide><path>docs/docs/reference-react-dom.md <ide> The `react-dom` package provides DOM-specific methods that can be used at the to <ide> - [`hydrate()`](#hydrate) <ide> - [`unmountComponentAtNode()`](#unmountcomponentatnode) <ide> - [`findDOMNode()`](#finddomnode) <del>- [`createPortal()`](#createPortal) <add>- [`createPortal()`](#createportal) <ide> <ide> ### Browser Support <ide> <ide> If this component has been mounted into the DOM, this returns the corresponding <ide> ReactDOM.createPortal(child, container) <ide> ``` <ide> <del>Creates a portal. Portals provide a way to [render children into a DOM node that exists outside the hierarchy of the DOM component](/docs/portals.html). <ide>\ No newline at end of file <add>Creates a portal. Portals provide a way to [render children into a DOM node that exists outside the hierarchy of the DOM component](/docs/portals.html).
1
Javascript
Javascript
move generate() to construct()
40de5a9c99eea7f1952e13c4aaf18f9cf8d96abc
<ide><path>examples/jsm/nodes/utils/MatcapUVNode.js <ide> class MatcapUVNode extends TempNode { <ide> <ide> } <ide> <del> generate( builder ) { <add> construct() { <ide> <ide> const x = normalize( vec3( positionViewDirection.z, 0, negate( positionViewDirection.x ) ) ); <ide> const y = cross( positionViewDirection, x ); <ide> <del> const uv = add( mul( vec2( dot( x, transformedNormalView ), dot( y, transformedNormalView ) ), 0.495 ), 0.5 ); <del> <del> return uv.build( builder, this.getNodeType( builder ) ); <add> return add( mul( vec2( dot( x, transformedNormalView ), dot( y, transformedNormalView ) ), 0.495 ), 0.5 ); <ide> <ide> } <ide> <ide><path>examples/jsm/nodes/utils/SpriteSheetUVNode.js <ide> class SpriteSheetUVNode extends Node { <ide> <ide> } <ide> <del> generate( builder ) { <add> construct() { <ide> <del> const count = this.countNode; <del> const uv = this.uvNode; <del> const frame = this.frameNode; <add> const { frameNode, uvNode, countNode } = this; <ide> <ide> const one = new ConstNode( 1 ); <ide> <del> const width = new SplitNode( count, 'x' ); <del> const height = new SplitNode( count, 'y' ); <add> const width = new SplitNode( countNode, 'x' ); <add> const height = new SplitNode( countNode, 'y' ); <ide> <ide> const total = new OperatorNode( '*', width, height ); <ide> <del> const roundFrame = new MathNode( MathNode.FLOOR, new MathNode( MathNode.MOD, frame, total ) ); <add> const roundFrame = new MathNode( MathNode.FLOOR, new MathNode( MathNode.MOD, frameNode, total ) ); <ide> <ide> const frameNum = new OperatorNode( '+', roundFrame, one ); <ide> <ide> const cell = new MathNode( MathNode.MOD, roundFrame, width ); <ide> const row = new MathNode( MathNode.CEIL, new OperatorNode( '/', frameNum, width ) ); <ide> const rowInv = new OperatorNode( '-', height, row ); <ide> <del> const scale = new OperatorNode( '/', one, count ); <add> const scale = new OperatorNode( '/', one, countNode ); <ide> <ide> const uvFrameOffset = new JoinNode( [ <ide> new OperatorNode( '*', cell, new SplitNode( scale, 'x' ) ), <ide> new OperatorNode( '*', rowInv, new SplitNode( scale, 'y' ) ) <ide> ] ); <ide> <del> const uvScale = new OperatorNode( '*', uv, scale ); <add> const uvScale = new OperatorNode( '*', uvNode, scale ); <ide> const uvFrame = new OperatorNode( '+', uvScale, uvFrameOffset ); <ide> <del> return uvFrame.build( builder, this.getNodeType( builder ) ); <add> return uvFrame; <ide> <ide> } <ide>
2
Ruby
Ruby
add new module
35e2209c10ffcf6a666ac4a8051a1f20801895ea
<ide><path>Library/Homebrew/os/mac/architecture_list.rb <add>module ArchitectureListExtension <add> # @private <add> def fat? <add> length > 1 <add> end <add> <add> # @private <add> def intel_universal? <add> intersects_all?(Hardware::CPU::INTEL_32BIT_ARCHS, Hardware::CPU::INTEL_64BIT_ARCHS) <add> end <add> <add> # @private <add> def ppc_universal? <add> intersects_all?(Hardware::CPU::PPC_32BIT_ARCHS, Hardware::CPU::PPC_64BIT_ARCHS) <add> end <add> <add> # Old-style 32-bit PPC/Intel universal, e.g. ppc7400 and i386 <add> # @private <add> def cross_universal? <add> intersects_all?(Hardware::CPU::PPC_32BIT_ARCHS, Hardware::CPU::INTEL_32BIT_ARCHS) <add> end <add> <add> # @private <add> def universal? <add> intel_universal? || ppc_universal? || cross_universal? <add> end <add> <add> def ppc? <add> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? { |a| self.include? a } <add> end <add> <add> # @private <add> def remove_ppc! <add> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).each { |a| delete a } <add> end <add> <add> def as_arch_flags <add> collect { |a| "-arch #{a}" }.join(" ") <add> end <add> <add> def as_cmake_arch_flags <add> join(";") <add> end <add> <add> protected <add> <add> def intersects_all?(*set) <add> set.all? do |archset| <add> archset.any? { |a| self.include? a } <add> end <add> end <add>end <add><path>Library/Homebrew/os/mac/cctools_mach.rb <del><path>Library/Homebrew/os/mac/mach.rb <del>module ArchitectureListExtension <del> # @private <del> def fat? <del> length > 1 <del> end <del> <del> # @private <del> def intel_universal? <del> intersects_all?(Hardware::CPU::INTEL_32BIT_ARCHS, Hardware::CPU::INTEL_64BIT_ARCHS) <del> end <del> <del> # @private <del> def ppc_universal? <del> intersects_all?(Hardware::CPU::PPC_32BIT_ARCHS, Hardware::CPU::PPC_64BIT_ARCHS) <del> end <del> <del> # Old-style 32-bit PPC/Intel universal, e.g. ppc7400 and i386 <del> # @private <del> def cross_universal? <del> intersects_all?(Hardware::CPU::PPC_32BIT_ARCHS, Hardware::CPU::INTEL_32BIT_ARCHS) <del> end <del> <del> # @private <del> def universal? <del> intel_universal? || ppc_universal? || cross_universal? <del> end <del> <del> def ppc? <del> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? { |a| self.include? a } <del> end <del> <del> # @private <del> def remove_ppc! <del> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).each { |a| delete a } <del> end <del> <del> def as_arch_flags <del> collect { |a| "-arch #{a}" }.join(" ") <del> end <del> <del> def as_cmake_arch_flags <del> join(";") <del> end <del> <del> protected <del> <del> def intersects_all?(*set) <del> set.all? do |archset| <del> archset.any? { |a| self.include? a } <del> end <del> end <del>end <add>require "os/mac/architecture_list" <ide> <del>module MachO <add>module CctoolsMachO <ide> # @private <ide> OTOOL_RX = /\t(.*) \(compatibility version (?:\d+\.)*\d+, current version (?:\d+\.)*\d+\)/ <ide> <ide> def mach_data <ide> end <ide> when 0xcefaedfe, 0xcffaedfe, 0xfeedface, 0xfeedfacf # Single arch <ide> offsets << 0 <del> when 0x7f454c46 # ELF <del> mach_data << { :arch => :x86_64, :type => :executable } <ide> else <ide> raise "Not a Mach-O binary." <ide> end
2
Javascript
Javascript
remove socket ondata/onend in parser cleanup
bce68134b647e6f102acf8e8f8ab3b153858d32c
<ide><path>lib/http.js <ide> ClientRequest.prototype.onSocket = function(socket) { <ide> var freeParser = function() { <ide> if (parser) { <ide> parsers.free(parser); <add> parser.socket.onend = null; <add> parser.socket.ondata = null; <add> parser.socket = null; <ide> parser = null; <ide> } <ide> };
1
Python
Python
divide commands into "actions"/"groups" sections
22d6dcfe55b11eea7b734188dfeb012725984d3c
<ide><path>airflow/cli/cli_parser.py <ide> import json <ide> import os <ide> import textwrap <del>from argparse import ArgumentError, RawTextHelpFormatter <add>from argparse import Action, ArgumentError, RawTextHelpFormatter <ide> from typing import Callable, Dict, Iterable, List, NamedTuple, Set, Union <ide> <ide> from tabulate import tabulate_formats <ide> class GroupCommand(NamedTuple): <ide> } <ide> <ide> <add>class AirflowHelpFormatter(argparse.HelpFormatter): <add> """ <add> Custom help formatter to display help message. <add> <add> It displays simple commands and groups of commands in separate sections. <add> """ <add> def _format_action(self, action: Action): <add> if isinstance(action, argparse._SubParsersAction): # pylint: disable=protected-access <add> parts = [] <add> subactions = action._get_subactions() # pylint: disable=protected-access <add> action_subcommnads, group_subcommnands = partition( <add> lambda d: isinstance(ALL_COMMANDS_DICT[d.dest], GroupCommand), subactions <add> ) <add> parts.append("\n") <add> parts.append('%*s%s:\n' % (self._current_indent, '', "Groups")) <add> self._indent() <add> for subaction in group_subcommnands: <add> parts.append(self._format_action(subaction)) <add> self._dedent() <add> <add> parts.append("\n") <add> parts.append('%*s%s:\n' % (self._current_indent, '', "Commands")) <add> self._indent() <add> <add> for subaction in action_subcommnads: <add> parts.append(self._format_action(subaction)) <add> self._dedent() <add> <add> # return a single string <add> return self._join_parts(parts) <add> <add> return super()._format_action(action) <add> <add> <ide> def get_parser(dag_parser: bool = False) -> argparse.ArgumentParser: <ide> """Creates and returns command line argument parser""" <del> parser = DefaultHelpParser(prog="airflow") <del> subparsers = parser.add_subparsers( <del> help='sub-command help', dest='subcommand') <add> parser = DefaultHelpParser(prog="airflow", formatter_class=AirflowHelpFormatter) <add> subparsers = parser.add_subparsers(dest='subcommand') <ide> subparsers.required = True <ide> <ide> subparser_list = DAG_CLI_COMMANDS if dag_parser else ALL_COMMANDS_DICT.keys() <ide><path>tests/cli/test_cli_parser.py <ide> # under the License. <ide> <ide> import argparse <add>import contextlib <add>import io <ide> import re <ide> from collections import Counter <ide> from unittest import TestCase <ide> def test_falsy_default_value(self): <ide> <ide> args = parser.parse_args([]) <ide> self.assertEqual(args.test, 0) <add> <add> def test_commands_and_command_group_sections(self): <add> parser = cli_parser.get_parser() <add> <add> with contextlib.redirect_stdout(io.StringIO()) as stdout: <add> with self.assertRaises(SystemExit): <add> parser.parse_args(['--help']) <add> stdout = stdout.getvalue() <add> self.assertIn("Commands", stdout) <add> self.assertIn("Groups", stdout)
2
Ruby
Ruby
add tests for simple match with namespace
5a5760828b998997048dc04ce3e83ecf50ae6e7b
<ide><path>actionpack/test/dispatch/routing_test.rb <ide> def self.matches?(request) <ide> match 'articles/:year/:month/:day/:title', :to => "articles#show", :as => :article <ide> <ide> namespace :account do <add> match 'description', :to => "account#description", :as => "description" <ide> resource :subscription, :credit, :credit_card <ide> <ide> namespace :admin do <ide> def test_redirect_with_port <ide> self.host = previous_host <ide> end <ide> <add> def test_normalize_namespaced_matches <add> with_test_routes do <add> assert_equal '/account/description', account_description_path <add> <add> get '/account/description' <add> assert_equal 'account#description', @response.body <add> end <add> end <add> <ide> def test_optional_scoped_path <ide> with_test_routes do <ide> assert_equal '/en/descriptions', descriptions_path("en")
1
Javascript
Javascript
add child_process customfds test
d0ed173d6d3e1ee394901da167cb836ce1c83772
<ide><path>test/parallel/test-child-process-custom-fds.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>// Verify that customFds is used if stdio is not provided. <add>{ <add> const msg = 'child_process: options.customFds option is deprecated. ' + <add> 'Use options.stdio instead.'; <add> common.expectWarning('DeprecationWarning', msg); <add> <add> const customFds = [-1, process.stdout.fd, process.stderr.fd]; <add> const child = common.spawnSyncPwd({ customFds }); <add> <add> assert.deepStrictEqual(child.options.customFds, customFds); <add> assert.deepStrictEqual(child.options.stdio, [ <add> { type: 'pipe', readable: true, writable: false }, <add> { type: 'fd', fd: process.stdout.fd }, <add> { type: 'fd', fd: process.stderr.fd } <add> ]); <add>} <add> <add>// Verify that customFds is ignored when stdio is present. <add>{ <add> const customFds = [0, 1, 2]; <add> const child = common.spawnSyncPwd({ customFds, stdio: 'pipe' }); <add> <add> assert.deepStrictEqual(child.options.customFds, customFds); <add> assert.deepStrictEqual(child.options.stdio, [ <add> { type: 'pipe', readable: true, writable: false }, <add> { type: 'pipe', readable: false, writable: true }, <add> { type: 'pipe', readable: false, writable: true } <add> ]); <add>}
1
Ruby
Ruby
update list_spec.rb for cask full_name
65d5c11f15644bc0103e5cb87011d4ba7a61b586
<ide><path>Library/Homebrew/test/cask/cmd/list_spec.rb <ide> let(:casks) { ["local-caffeine", "local-transmission", "third-party/tap/third-party-cask"] } <ide> let(:expected_output) { <ide> <<~EOS <del> [{"token":"local-caffeine","full_token":"homebrew/cask/local-caffeine","tap":"homebrew/cask","name":[],"desc":null,"homepage":"https://brew.sh/","url":"file:///usr/local/Homebrew/Library/Homebrew/test/support/fixtures/cask/caffeine.zip","appcast":null,"version":"1.2.3","installed":"1.2.3","outdated":false,"sha256":"67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94","artifacts":[["Caffeine.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null},{"token":"local-transmission","full_token":"homebrew/cask/local-transmission","tap":"homebrew/cask","name":["Transmission"],"desc":"BitTorrent client","homepage":"https://transmissionbt.com/","url":"file:///usr/local/Homebrew/Library/Homebrew/test/support/fixtures/cask/transmission-2.61.dmg","appcast":null,"version":"2.61","installed":"2.61","outdated":false,"sha256":"e44ffa103fbf83f55c8d0b1bea309a43b2880798dae8620b1ee8da5e1095ec68","artifacts":[["Transmission.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null},{"token":"third-party-cask","full_token":"third-party/tap/third-party-cask","tap":"third-party/tap","name":[],"desc":null,"homepage":"https://brew.sh/","url":"https://brew.sh/ThirdParty.dmg","appcast":null,"version":"1.2.3","installed":"1.2.3","outdated":false,"sha256":"8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b","artifacts":[["ThirdParty.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null}] <add> [{"token":"local-caffeine","full_token":"local-caffeine","tap":"homebrew/cask","name":[],"desc":null,"homepage":"https://brew.sh/","url":"file:///usr/local/Homebrew/Library/Homebrew/test/support/fixtures/cask/caffeine.zip","appcast":null,"version":"1.2.3","installed":"1.2.3","outdated":false,"sha256":"67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94","artifacts":[["Caffeine.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null},{"token":"local-transmission","full_token":"local-transmission","tap":"homebrew/cask","name":["Transmission"],"desc":"BitTorrent client","homepage":"https://transmissionbt.com/","url":"file:///usr/local/Homebrew/Library/Homebrew/test/support/fixtures/cask/transmission-2.61.dmg","appcast":null,"version":"2.61","installed":"2.61","outdated":false,"sha256":"e44ffa103fbf83f55c8d0b1bea309a43b2880798dae8620b1ee8da5e1095ec68","artifacts":[["Transmission.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null},{"token":"third-party-cask","full_token":"third-party/tap/third-party-cask","tap":"third-party/tap","name":[],"desc":null,"homepage":"https://brew.sh/","url":"https://brew.sh/ThirdParty.dmg","appcast":null,"version":"1.2.3","installed":"1.2.3","outdated":false,"sha256":"8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b","artifacts":[["ThirdParty.app"]],"caveats":null,"depends_on":{},"conflicts_with":null,"container":null,"auto_updates":null}] <ide> EOS <ide> } <ide>
1
Text
Text
fix nits in tools/doc/readme.md
d28edf97fa5cb863b5497cc3964c103f782d8b62
<ide><path>tools/doc/README.md <ide> Here's how the node docs work. <ide> <del>1:1 relationship from `lib/<module>.js` to `doc/api/<module>.md` <add>1:1 relationship from `lib/<module>.js` to `doc/api/<module>.md`. <ide> <ide> Each type of heading has a description block. <ide> <ide> ```md <del>## module <del><!-- YAML <del>added: v0.10.0 <del>--> <add># module <add> <add><!--introduced_in=v0.10.0--> <ide> <del>> Stability: 3 - Stable <add>> Stability: 2 - Stable <ide> <del>description and examples. <add>A description and examples. <ide> <del>### module.property <add>## module.property <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* Type <add>* {type} <ide> <del>description of the property. <add>A description of the property. <ide> <del>### module.someFunction(x, y, [z=100]) <add>## module.someFunction(x, y, [z=100]) <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* `x` {String} the description of the string <del>* `y` {Boolean} Should I stay or should I go? <del>* `z` {Number} How many zebras to bring. <add>* `x` {string} The description of the string. <add>* `y` {boolean} Should I stay or should I go? <add>* `z` {number} How many zebras to bring. <ide> <ide> A description of the function. <ide> <del>### module.someNewFunction(x) <add>## module.someNewFunction(x) <ide> <!-- YAML <ide> added: REPLACEME <ide> --> <ide> <del>* `x` {String} the description of the string <add>* `x` {string} The description of the string. <ide> <ide> This feature is not in a release yet. <ide> <del>### Event: 'blerg' <add>## Event: 'blerg' <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* Argument: SomeClass object. <add>* `anArg` {type} A description of the listener argument. <ide> <del>Modules don't usually raise events on themselves. `cluster` is the <add>Modules don't usually raise events on themselves. `cluster` is the <ide> only exception. <ide> <ide> ## Class: SomeClass <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>description of the class. <add>A description of the class. <ide> <del>### Class Method: SomeClass.classMethod(anArg) <add>### SomeClass.classMethod(anArg) <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* `anArg` {Object} Just an argument <del> * `field` {String} anArg can have this field. <del> * `field2` {Boolean} Another field. Default: `false`. <del>* Return: {Boolean} `true` if it worked. <add>* `anArg` {Object} Just an argument. <add> * `field` {string} `anArg` can have this field. <add> * `field2` {boolean} Another field. Default: `false`. <add>* Returns: {boolean} `true` if it worked. <ide> <del>Description of the method for humans. <add>A description of the method for humans. <ide> <del>### someClass.nextSibling() <add>### SomeClass.nextSibling() <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* Return: {SomeClass object | null} The next someClass in line. <add>* Returns: {SomeClass | null} The next `SomeClass` in line. <ide> <del>### someClass.someProperty <add>### SomeClass.someProperty <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* String <add>* {string} <ide> <del>The indication of what someProperty is. <add>The indication of what `someProperty` is. <ide> <ide> ### Event: 'grelb' <ide> <!-- YAML <ide> added: v0.10.0 <ide> --> <ide> <del>* `isBlerg` {Boolean} <add>* `isBlerg` {boolean} <ide> <del>This event is emitted on instances of SomeClass, not on the module itself. <add>This event is emitted on instances of `SomeClass`, not on the module itself. <ide> ``` <ide> <ide> <del>* Classes have (description, Properties, Methods, Events) <del>* Events have (list of arguments, description) <del>* Functions have (list of arguments, description) <del>* Methods have (list of arguments, description) <del>* Modules have (description, Properties, Functions, Classes, Examples) <del>* Properties have (type, description) <add>* Classes have (description, Properties, Methods, Events). <add>* Events have (list of arguments, description). <add>* Functions have (list of arguments, description). <add>* Methods have (list of arguments, description). <add>* Modules have (description, Properties, Functions, Classes, Examples). <add>* Properties have (type, description).
1
Python
Python
add missing entries in mappings
3b1bbefc476cdd710273c79f55f521a6d91083c3
<ide><path>src/transformers/models/auto/feature_extraction_auto.py <ide> ("regnet", "ConvNextFeatureExtractor"), <ide> ("poolformer", "PoolFormerFeatureExtractor"), <ide> ("maskformer", "MaskFormerFeatureExtractor"), <add> ("data2vec-audio", "Wav2Vec2FeatureExtractor"), <add> ("data2vec-vision", "BeitFeatureExtractor"), <add> ("dpt", "DPTFeatureExtractor"), <add> ("glpn", "GLPNFeatureExtractor"), <ide> ] <ide> ) <ide> <ide><path>src/transformers/models/auto/processing_auto.py <ide> ("wav2vec2", "Wav2Vec2Processor"), <ide> ("wav2vec2_with_lm", "Wav2Vec2ProcessorWithLM"), <ide> ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"), <add> ("unispeech", "Wav2Vec2Processor"), <add> ("unispeech-sat", "Wav2Vec2Processor"), <add> ("sew", "Wav2Vec2Processor"), <add> ("sew-d", "Wav2Vec2Processor"), <add> ("vilt", "ViltProcessor"), <add> ("wavlm", "Wav2Vec2Processor"), <ide> ] <ide> ) <ide> <ide><path>src/transformers/models/auto/tokenization_auto.py <ide> "XGLMTokenizerFast" if is_tokenizers_available() else None, <ide> ), <ide> ), <add> ("visual_bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), <add> ("megatron-bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)), <add> ( <add> "nystromformer", <add> ( <add> "AlbertTokenizer" if is_sentencepiece_available() else None, <add> "AlbertTokenizerFast" if is_tokenizers_available() else None, <add> ), <add> ), <add> ("xlm-roberta-xl", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), <add> ( <add> "yoso", <add> ( <add> "AlbertTokenizer" if is_sentencepiece_available() else None, <add> "AlbertTokenizerFast" if is_tokenizers_available() else None, <add> ), <add> ), <add> ("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)), <ide> ] <ide> ) <ide>
3
Ruby
Ruby
allow retrieving tabs from arbitrary kegs
dc1be896d8edb63cf1afd168a331a86b6fe2f289
<ide><path>Library/Homebrew/tab.rb <ide> def self.from_file path <ide> return tab <ide> end <ide> <add> def self.for_keg keg <add> path = keg+'INSTALL_RECEIPT.json' <add> <add> if path.exist? <add> self.from_file path <add> else <add> self.dummy_tab Formula.factory(keg.parent.basename) <add> end <add> end <add> <ide> def self.for_formula f <ide> f = Formula.factory f unless f.kind_of? Formula <ide> path = HOMEBREW_REPOSITORY + 'Library' + 'LinkedKegs' + f.name + 'INSTALL_RECEIPT.json' <ide> def self.for_formula f <ide> # TODO: <ide> # This isn't the best behavior---perhaps a future version of Homebrew can <ide> # treat missing Tabs as errors. <del> Tab.new :used_options => [], <del> :unused_options => f.options.map { |o, _| o} <add> self.dummy_tab f <ide> end <ide> end <ide> <add> def self.dummy_tab f <add> Tab.new :used_options => [], <add> :unused_options => f.options.map { |o, _| o} <add> end <add> <ide> def installed_with? opt <ide> used_options.include? opt <ide> end
1
Go
Go
fix import path
5af8cfd3b16b6bc1754537fb5424365839ad2fc4
<ide><path>volume/local/local_unix.go <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> <del> "src/github.com/pkg/errors" <add> "github.com/pkg/errors" <ide> <ide> "github.com/docker/docker/pkg/mount" <ide> )
1
PHP
PHP
improve api documentation for typeinterface
83c3a682993c921301af4f45465fc7fd027346de
<ide><path>src/Database/TypeInterface.php <ide> namespace Cake\Database; <ide> <ide> /** <del> * Encapsulates all conversion functions for values coming from database into PHP and <del> * going from PHP into database. <add> * Encapsulates all conversion functions for values coming from a database into PHP and <add> * going from PHP into a database. <ide> */ <ide> interface TypeInterface <ide> { <ide> <ide> /** <del> * Casts given value from a PHP type to one acceptable by database <add> * Casts given value from a PHP type to one acceptable by a database. <ide> * <del> * @param mixed $value value to be converted to database equivalent <del> * @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted <del> * @return mixed <add> * @param mixed $value Value to be converted to a database equivalent. <add> * @param \Cake\Database\Driver $driver Object from which database preferences and configuration will be extracted. <add> * @return mixed Given PHP type casted to one acceptable by a database. <ide> */ <ide> public function toDatabase($value, Driver $driver); <ide> <ide> /** <del> * Casts given value from a database type to PHP equivalent <add> * Casts given value from a database type to a PHP equivalent. <ide> * <del> * @param mixed $value value to be converted to PHP equivalent <del> * @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted <del> * @return mixed <add> * @param mixed $value Value to be converted to PHP equivalent <add> * @param \Cake\Database\Driver $driver Object from which database preferences and configuration will be extracted <add> * @return mixed Given value casted from a database to a PHP equivalent. <ide> */ <ide> public function toPHP($value, Driver $driver); <ide> <ide> /** <del> * Casts given value to Statement equivalent <add> * Casts given value to its Statement equivalent. <ide> * <del> * @param mixed $value value to be converted to PDO statement <del> * @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted <del> * @return mixed <add> * @param mixed $value Value to be converted to PDO statement. <add> * @param \Cake\Database\Driver $driver Object from which database preferences and configuration will be extracted. <add> * @return mixed Given value casted to its Statement equivalent. <ide> */ <ide> public function toStatement($value, Driver $driver); <ide> <ide> /** <ide> * Marshalls flat data into PHP objects. <ide> * <del> * Most useful for converting request data into PHP objects <add> * Most useful for converting request data into PHP objects, <ide> * that make sense for the rest of the ORM/Database layers. <ide> * <ide> * @param mixed $value The value to convert. <ide> public function marshal($value); <ide> <ide> /** <ide> * Returns the base type name that this class is inheriting. <del> * This is useful when extending base type for adding extra functionality <add> * <add> * This is useful when extending base type for adding extra functionality, <ide> * but still want the rest of the framework to use the same assumptions it would <ide> * do about the base type it inherits from. <ide> * <del> * @return string <add> * @return string The base type name that this class is inheriting. <ide> */ <ide> public function getBaseType(); <ide> <ide> /** <del> * Returns type identifier name for this object <add> * Returns type identifier name for this object. <ide> * <del> * @return string <add> * @return string The type identifier name for this object. <ide> */ <ide> public function getName(); <ide>
1
PHP
PHP
change default red to use the high intensity code
38ed099e265f685b0682573e2ee752a0601a5d9f
<ide><path>src/Console/ConsoleOutput.php <ide> class ConsoleOutput <ide> */ <ide> protected static $_foregroundColors = [ <ide> 'black' => 30, <del> 'red' => 31, <add> 'red' => 91, <ide> 'green' => 32, <ide> 'yellow' => 33, <ide> 'blue' => 34, <ide><path>tests/TestCase/Console/ConsoleOutputTest.php <ide> public function testStylesAdding() <ide> public function testFormattingSimple() <ide> { <ide> $this->output->expects($this->once())->method('_write') <del> ->with("\033[31mError:\033[0m Something bad"); <add> ->with("\033[91mError:\033[0m Something bad"); <ide> <ide> $this->output->write('<error>Error:</error> Something bad', false); <ide> } <ide> public function testFormattingMissingStyleName() <ide> public function testFormattingMultipleStylesName() <ide> { <ide> $this->output->expects($this->once())->method('_write') <del> ->with("\033[31mBad\033[0m \033[33mWarning\033[0m Regular"); <add> ->with("\033[91mBad\033[0m \033[33mWarning\033[0m Regular"); <ide> <ide> $this->output->write('<error>Bad</error> <warning>Warning</warning> Regular', false); <ide> } <ide> public function testFormattingMultipleStylesName() <ide> public function testFormattingMultipleSameTags() <ide> { <ide> $this->output->expects($this->once())->method('_write') <del> ->with("\033[31mBad\033[0m \033[31mWarning\033[0m Regular"); <add> ->with("\033[91mBad\033[0m \033[91mWarning\033[0m Regular"); <ide> <ide> $this->output->write('<error>Bad</error> <error>Warning</error> Regular', false); <ide> }
2
Python
Python
add solution for project euler problem 72
d8f5b31fab57cc009e87a8d62c8d03075f66e9bd
<ide><path>project_euler/problem_072/sol2.py <add>""" <add>Project Euler Problem 72: https://projecteuler.net/problem=72 <add> <add>Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, <add>it is called a reduced proper fraction. <add> <add>If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, <add>we get: <add> <add>1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, <add>4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 <add> <add>It can be seen that there are 21 elements in this set. <add> <add>How many elements would be contained in the set of reduced proper fractions <add>for d ≤ 1,000,000? <add>""" <add> <add> <add>def solution(limit: int = 1000000) -> int: <add> """ <add> Return the number of reduced proper fractions with denominator less than limit. <add> >>> solution(8) <add> 21 <add> >>> solution(1000) <add> 304191 <add> """ <add> primes = set(range(3, limit, 2)) <add> primes.add(2) <add> for p in range(3, limit, 2): <add> if p not in primes: <add> continue <add> primes.difference_update(set(range(p * p, limit, p))) <add> <add> phi = [float(n) for n in range(limit + 1)] <add> <add> for p in primes: <add> for n in range(p, limit + 1, p): <add> phi[n] *= 1 - 1 / p <add> <add> return int(sum(phi[2:])) <add> <add> <add>if __name__ == "__main__": <add> print(f"{solution() = }")
1
PHP
PHP
limit repeated queries when token is not valid
3f0269f97344deed0b7b5279d368a099837c7483
<ide><path>src/Illuminate/Auth/Guard.php <ide> class Guard { <ide> */ <ide> protected $loggedOut = false; <ide> <add> /** <add> * Indicates if a token user retrieval has been attempted. <add> * <add> * @var bool <add> */ <add> protected $tokenRetrievalAttempted = false; <add> <ide> /** <ide> * Create a new authentication guard. <ide> * <ide> public function id() <ide> */ <ide> protected function getUserByRecaller($recaller) <ide> { <del> if ($this->validRecaller($recaller)) <add> if ($this->validRecaller($recaller) && ! $this->tokenRetrievalAttempted) <ide> { <add> $this->tokenRetrievalAttempted = true; <add> <ide> list($id, $token) = explode('|', $recaller, 2); <ide> <ide> $this->viaRemember = ! is_null($user = $this->provider->retrieveByToken($id, $token));
1
Python
Python
fix decoding errors
5652b078516bb33520e9e7db5c21802bcec17003
<ide><path>numpy/distutils/exec_command.py <ide> import os <ide> import sys <ide> import subprocess <add>import locale <ide> <ide> from numpy.distutils.misc_util import is_sequence, make_temp_file <ide> from numpy.distutils import log <ide> def _exec_command(command, use_shell=None, use_tee = None, **env): <ide> # Inherit environment by default <ide> env = env or None <ide> try: <add> # universal_newlines is set to False so that communicate() <add> # will return bytes. We need to decode the output ourselves <add> # so that Python will not raise a UnicodeDecodeError when <add> # it encounters an invalid character; rather, we simply replace it <ide> proc = subprocess.Popen(command, shell=use_shell, env=env, <ide> stdout=subprocess.PIPE, <ide> stderr=subprocess.STDOUT, <del> universal_newlines=True) <add> universal_newlines=False) <ide> except EnvironmentError: <ide> # Return 127, as os.spawn*() and /bin/sh do <ide> return 127, '' <add> <ide> text, err = proc.communicate() <add> text = text.decode(locale.getpreferredencoding(False), <add> errors='replace') <add> <add> text = text.replace('\r\n', '\n') <ide> # Another historical oddity <ide> if text[-1:] == '\n': <ide> text = text[:-1] <add> <add> # stdio uses bytes in python 2, so to avoid issues, we simply <add> # remove all non-ascii characters <add> if sys.version_info < (3, 0): <add> text = text.encode('ascii', errors='replace') <add> <ide> if use_tee and text: <ide> print(text) <ide> return proc.returncode, text
1
Javascript
Javascript
fix experiments loading npm wasm
616e0d7ee88dd33d3fda793b790adee92468fee0
<ide><path>examples/with-webassembly/next.config.js <ide> module.exports = { <ide> config.output.webassemblyModuleFilename = 'static/wasm/[modulehash].wasm' <ide> <ide> // Since Webpack 5 doesn't enable WebAssembly by default, we should do it manually <del> config.experiments = { asyncWebAssembly: true } <add> config.experiments = { ...config.experiments, asyncWebAssembly: true } <ide> <ide> return config <ide> },
1
Python
Python
add check for token_type_ids before tensorizing
c76c3cebed3c707178d9f721349c5abd5206a57f
<ide><path>src/transformers/tokenization_utils.py <ide> def prepare_for_model( <ide> # Prepare inputs as tensors if asked <ide> if return_tensors == "tf" and is_tf_available(): <ide> encoded_inputs["input_ids"] = tf.constant([encoded_inputs["input_ids"]]) <del> encoded_inputs["token_type_ids"] = tf.constant([encoded_inputs["token_type_ids"]]) <add> <add> if "token_type_ids" in encoded_inputs: <add> encoded_inputs["token_type_ids"] = tf.constant([encoded_inputs["token_type_ids"]]) <ide> <ide> if "attention_mask" in encoded_inputs: <ide> encoded_inputs["attention_mask"] = tf.constant([encoded_inputs["attention_mask"]]) <ide> <ide> elif return_tensors == "pt" and is_torch_available(): <ide> encoded_inputs["input_ids"] = torch.tensor([encoded_inputs["input_ids"]]) <del> encoded_inputs["token_type_ids"] = torch.tensor([encoded_inputs["token_type_ids"]]) <add> <add> if "token_type_ids" in encoded_inputs: <add> encoded_inputs["token_type_ids"] = torch.tensor([encoded_inputs["token_type_ids"]]) <ide> <ide> if "attention_mask" in encoded_inputs: <ide> encoded_inputs["attention_mask"] = torch.tensor([encoded_inputs["attention_mask"]])
1
Go
Go
remove api, as it's no longer used
c425188bc07b3f6fe5826021cdd99cf72bf310ed
<ide><path>libnetwork/api/api.go <del>package api <del> <del>import ( <del> "encoding/json" <del> "fmt" <del> "io" <del> "net/http" <del> "strconv" <del> "strings" <del> <del> "github.com/docker/docker/libnetwork" <del> "github.com/docker/docker/libnetwork/netlabel" <del> "github.com/docker/docker/libnetwork/netutils" <del> "github.com/docker/docker/libnetwork/types" <del> "github.com/gorilla/mux" <del>) <del> <del>var ( <del> successResponse = responseStatus{Status: "Success", StatusCode: http.StatusOK} <del> createdResponse = responseStatus{Status: "Created", StatusCode: http.StatusCreated} <del> badQueryResponse = responseStatus{Status: "Unsupported query", StatusCode: http.StatusBadRequest} <del>) <del> <del>const ( <del> // Resource name regex <del> // Gorilla mux encloses the passed pattern with '^' and '$'. So we need to do some tricks <del> // to have mux eventually build a query regex which matches empty or word string (`^$|[\w]+`) <del> regex = "[a-zA-Z_0-9-]+" <del> qregx = "$|" + regex <del> // Router URL variable definition <del> nwNameQr = "{" + urlNwName + ":" + qregx + "}" <del> nwID = "{" + urlNwID + ":" + regex + "}" <del> nwPIDQr = "{" + urlNwPID + ":" + qregx + "}" <del> epNameQr = "{" + urlEpName + ":" + qregx + "}" <del> epID = "{" + urlEpID + ":" + regex + "}" <del> epPIDQr = "{" + urlEpPID + ":" + qregx + "}" <del> sbID = "{" + urlSbID + ":" + regex + "}" <del> sbPIDQr = "{" + urlSbPID + ":" + qregx + "}" <del> cnIDQr = "{" + urlCnID + ":" + qregx + "}" <del> cnPIDQr = "{" + urlCnPID + ":" + qregx + "}" <del> <del> // Internal URL variable name.They can be anything as <del> // long as they do not collide with query fields. <del> urlNwName = "network-name" <del> urlNwID = "network-id" <del> urlNwPID = "network-partial-id" <del> urlEpName = "endpoint-name" <del> urlEpID = "endpoint-id" <del> urlEpPID = "endpoint-partial-id" <del> urlSbID = "sandbox-id" <del> urlSbPID = "sandbox-partial-id" <del> urlCnID = "container-id" <del> urlCnPID = "container-partial-id" <del>) <del> <del>// NewHTTPHandler creates and initialize the HTTP handler to serve the requests for libnetwork <del>func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request) { <del> h := &httpHandler{c: c} <del> h.initRouter() <del> return h.handleRequest <del>} <del> <del>type responseStatus struct { <del> Status string <del> StatusCode int <del>} <del> <del>func (r *responseStatus) isOK() bool { <del> return r.StatusCode == http.StatusOK || r.StatusCode == http.StatusCreated <del>} <del> <del>type processor func(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) <del> <del>type httpHandler struct { <del> c libnetwork.NetworkController <del> r *mux.Router <del>} <del> <del>func (h *httpHandler) handleRequest(w http.ResponseWriter, req *http.Request) { <del> // Make sure the service is there <del> if h.c == nil { <del> http.Error(w, "NetworkController is not available", http.StatusServiceUnavailable) <del> return <del> } <del> <del> // Get handler from router and execute it <del> h.r.ServeHTTP(w, req) <del>} <del> <del>func (h *httpHandler) initRouter() { <del> m := map[string][]struct { <del> url string <del> qrs []string <del> fct processor <del> }{ <del> "GET": { <del> // Order matters <del> {"/networks", []string{"name", nwNameQr}, procGetNetworks}, <del> {"/networks", []string{"partial-id", nwPIDQr}, procGetNetworks}, <del> {"/networks", nil, procGetNetworks}, <del> {"/networks/" + nwID, nil, procGetNetwork}, <del> {"/networks/" + nwID + "/endpoints", []string{"name", epNameQr}, procGetEndpoints}, <del> {"/networks/" + nwID + "/endpoints", []string{"partial-id", epPIDQr}, procGetEndpoints}, <del> {"/networks/" + nwID + "/endpoints", nil, procGetEndpoints}, <del> {"/networks/" + nwID + "/endpoints/" + epID, nil, procGetEndpoint}, <del> {"/services", []string{"network", nwNameQr}, procGetServices}, <del> {"/services", []string{"name", epNameQr}, procGetServices}, <del> {"/services", []string{"partial-id", epPIDQr}, procGetServices}, <del> {"/services", nil, procGetServices}, <del> {"/services/" + epID, nil, procGetService}, <del> {"/services/" + epID + "/backend", nil, procGetSandbox}, <del> {"/sandboxes", []string{"partial-container-id", cnPIDQr}, procGetSandboxes}, <del> {"/sandboxes", []string{"container-id", cnIDQr}, procGetSandboxes}, <del> {"/sandboxes", []string{"partial-id", sbPIDQr}, procGetSandboxes}, <del> {"/sandboxes", nil, procGetSandboxes}, <del> {"/sandboxes/" + sbID, nil, procGetSandbox}, <del> }, <del> "POST": { <del> {"/networks", nil, procCreateNetwork}, <del> {"/networks/" + nwID + "/endpoints", nil, procCreateEndpoint}, <del> {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes", nil, procJoinEndpoint}, <del> {"/services", nil, procPublishService}, <del> {"/services/" + epID + "/backend", nil, procAttachBackend}, <del> {"/sandboxes", nil, procCreateSandbox}, <del> }, <del> "DELETE": { <del> {"/networks/" + nwID, nil, procDeleteNetwork}, <del> {"/networks/" + nwID + "/endpoints/" + epID, nil, procDeleteEndpoint}, <del> {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes/" + sbID, nil, procLeaveEndpoint}, <del> {"/services/" + epID, nil, procUnpublishService}, <del> {"/services/" + epID + "/backend/" + sbID, nil, procDetachBackend}, <del> {"/sandboxes/" + sbID, nil, procDeleteSandbox}, <del> }, <del> } <del> <del> h.r = mux.NewRouter() <del> for method, routes := range m { <del> for _, route := range routes { <del> r := h.r.Path("/{.*}" + route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct)) <del> if route.qrs != nil { <del> r.Queries(route.qrs...) <del> } <del> <del> r = h.r.Path(route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct)) <del> if route.qrs != nil { <del> r.Queries(route.qrs...) <del> } <del> } <del> } <del>} <del> <del>func makeHandler(ctrl libnetwork.NetworkController, fct processor) http.HandlerFunc { <del> return func(w http.ResponseWriter, req *http.Request) { <del> var ( <del> body []byte <del> err error <del> ) <del> if req.Body != nil { <del> body, err = io.ReadAll(req.Body) <del> if err != nil { <del> http.Error(w, "Invalid body: "+err.Error(), http.StatusBadRequest) <del> return <del> } <del> } <del> <del> res, rsp := fct(ctrl, mux.Vars(req), body) <del> if !rsp.isOK() { <del> http.Error(w, rsp.Status, rsp.StatusCode) <del> return <del> } <del> if res != nil { <del> writeJSON(w, rsp.StatusCode, res) <del> } <del> } <del>} <del> <del>/***************** <del> Resource Builders <del>******************/ <del> <del>func buildNetworkResource(nw libnetwork.Network) *networkResource { <del> r := &networkResource{} <del> if nw != nil { <del> r.Name = nw.Name() <del> r.ID = nw.ID() <del> r.Type = nw.Type() <del> epl := nw.Endpoints() <del> r.Endpoints = make([]*endpointResource, 0, len(epl)) <del> for _, e := range epl { <del> epr := buildEndpointResource(e) <del> r.Endpoints = append(r.Endpoints, epr) <del> } <del> } <del> return r <del>} <del> <del>func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource { <del> r := &endpointResource{} <del> if ep != nil { <del> r.Name = ep.Name() <del> r.ID = ep.ID() <del> r.Network = ep.Network() <del> } <del> return r <del>} <del> <del>func buildSandboxResource(sb libnetwork.Sandbox) *sandboxResource { <del> r := &sandboxResource{} <del> if sb != nil { <del> r.ID = sb.ID() <del> r.Key = sb.Key() <del> r.ContainerID = sb.ContainerID() <del> } <del> return r <del>} <del> <del>/**************** <del> Options Parsers <del>*****************/ <del> <del>func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption { <del> var setFctList []libnetwork.SandboxOption <del> if sc.HostName != "" { <del> setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName)) <del> } <del> if sc.DomainName != "" { <del> setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName)) <del> } <del> if sc.HostsPath != "" { <del> setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath)) <del> } <del> if sc.ResolvConfPath != "" { <del> setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath)) <del> } <del> if sc.UseDefaultSandbox { <del> setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox()) <del> } <del> if sc.UseExternalKey { <del> setFctList = append(setFctList, libnetwork.OptionUseExternalKey()) <del> } <del> if sc.DNS != nil { <del> for _, d := range sc.DNS { <del> setFctList = append(setFctList, libnetwork.OptionDNS(d)) <del> } <del> } <del> if sc.ExtraHosts != nil { <del> for _, e := range sc.ExtraHosts { <del> setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address)) <del> } <del> } <del> if sc.ExposedPorts != nil { <del> setFctList = append(setFctList, libnetwork.OptionExposedPorts(sc.ExposedPorts)) <del> } <del> if sc.PortMapping != nil { <del> setFctList = append(setFctList, libnetwork.OptionPortMapping(sc.PortMapping)) <del> } <del> return setFctList <del>} <del> <del>/****************** <del> Process functions <del>*******************/ <del> <del>func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate) { <del> if nc.NetworkType == "" { <del> nc.NetworkType = c.Config().Daemon.DefaultDriver <del> } <del>} <del> <del>/*************************** <del> NetworkController interface <del>****************************/ <del>func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var create networkCreate <del> <del> err := json.Unmarshal(body, &create) <del> if err != nil { <del> return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> processCreateDefaults(c, &create) <del> <del> options := []libnetwork.NetworkOption{} <del> if val, ok := create.NetworkOpts[netlabel.Internal]; ok { <del> internal, err := strconv.ParseBool(val) <del> if err != nil { <del> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> if internal { <del> options = append(options, libnetwork.NetworkOptionInternalNetwork()) <del> } <del> } <del> if val, ok := create.NetworkOpts[netlabel.EnableIPv6]; ok { <del> enableIPv6, err := strconv.ParseBool(val) <del> if err != nil { <del> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> options = append(options, libnetwork.NetworkOptionEnableIPv6(enableIPv6)) <del> } <del> if len(create.DriverOpts) > 0 { <del> options = append(options, libnetwork.NetworkOptionDriverOpts(create.DriverOpts)) <del> } <del> <del> if len(create.IPv4Conf) > 0 { <del> ipamV4Conf := &libnetwork.IpamConf{ <del> PreferredPool: create.IPv4Conf[0].PreferredPool, <del> SubPool: create.IPv4Conf[0].SubPool, <del> } <del> <del> options = append(options, libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil)) <del> } <del> <del> nw, err := c.NewNetwork(create.NetworkType, create.Name, create.ID, options...) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nw.ID(), &createdResponse <del>} <del> <del>func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> t, by := detectNetworkTarget(vars) <del> nw, errRsp := findNetwork(c, t, by) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> return buildNetworkResource(nw), &successResponse <del>} <del> <del>func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var list []*networkResource <del> <del> // Look for query filters and validate <del> name, queryByName := vars[urlNwName] <del> shortID, queryByPid := vars[urlNwPID] <del> if queryByName && queryByPid { <del> return nil, &badQueryResponse <del> } <del> <del> if queryByName { <del> if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() { <del> list = append(list, buildNetworkResource(nw)) <del> } <del> } else if queryByPid { <del> // Return all the prefix-matching networks <del> l := func(nw libnetwork.Network) bool { <del> if strings.HasPrefix(nw.ID(), shortID) { <del> list = append(list, buildNetworkResource(nw)) <del> } <del> return false <del> } <del> c.WalkNetworks(l) <del> } else { <del> for _, nw := range c.Networks() { <del> list = append(list, buildNetworkResource(nw)) <del> } <del> } <del> <del> return list, &successResponse <del>} <del> <del>func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var create sandboxCreate <del> <del> err := json.Unmarshal(body, &create) <del> if err != nil { <del> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> <del> sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...) <del> if err != nil { <del> return "", convertNetworkError(err) <del> } <del> <del> return sb.ID(), &createdResponse <del>} <del> <del>/****************** <del> Network interface <del>*******************/ <del>func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var ec endpointCreate <del> <del> err := json.Unmarshal(body, &ec) <del> if err != nil { <del> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> <del> nwT, nwBy := detectNetworkTarget(vars) <del> n, errRsp := findNetwork(c, nwT, nwBy) <del> if !errRsp.isOK() { <del> return "", errRsp <del> } <del> <del> var setFctList []libnetwork.EndpointOption <del> for _, str := range ec.MyAliases { <del> setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str)) <del> } <del> <del> ep, err := n.CreateEndpoint(ec.Name, setFctList...) <del> if err != nil { <del> return "", convertNetworkError(err) <del> } <del> <del> return ep.ID(), &createdResponse <del>} <del> <del>func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> nwT, nwBy := detectNetworkTarget(vars) <del> epT, epBy := detectEndpointTarget(vars) <del> <del> ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> return buildEndpointResource(ep), &successResponse <del>} <del> <del>func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> // Look for query filters and validate <del> name, queryByName := vars[urlEpName] <del> shortID, queryByPid := vars[urlEpPID] <del> if queryByName && queryByPid { <del> return nil, &badQueryResponse <del> } <del> <del> nwT, nwBy := detectNetworkTarget(vars) <del> nw, errRsp := findNetwork(c, nwT, nwBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> var list []*endpointResource <del> <del> // If query parameter is specified, return a filtered collection <del> if queryByName { <del> if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() { <del> list = append(list, buildEndpointResource(ep)) <del> } <del> } else if queryByPid { <del> // Return all the prefix-matching endpoints <del> l := func(ep libnetwork.Endpoint) bool { <del> if strings.HasPrefix(ep.ID(), shortID) { <del> list = append(list, buildEndpointResource(ep)) <del> } <del> return false <del> } <del> nw.WalkEndpoints(l) <del> } else { <del> for _, ep := range nw.Endpoints() { <del> epr := buildEndpointResource(ep) <del> list = append(list, epr) <del> } <del> } <del> <del> return list, &successResponse <del>} <del> <del>func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> target, by := detectNetworkTarget(vars) <del> <del> nw, errRsp := findNetwork(c, target, by) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> err := nw.Delete() <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nil, &successResponse <del>} <del> <del>/****************** <del> Endpoint interface <del>*******************/ <del>func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var ej endpointJoin <del> var setFctList []libnetwork.EndpointOption <del> err := json.Unmarshal(body, &ej) <del> if err != nil { <del> return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> <del> nwT, nwBy := detectNetworkTarget(vars) <del> epT, epBy := detectEndpointTarget(vars) <del> <del> ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> sb, errRsp := findSandbox(c, ej.SandboxID, byID) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> for _, str := range ej.Aliases { <del> name, alias, err := netutils.ParseAlias(str) <del> if err != nil { <del> return "", convertNetworkError(err) <del> } <del> setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias)) <del> } <del> <del> err = ep.Join(sb, setFctList...) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> return sb.Key(), &successResponse <del>} <del> <del>func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> nwT, nwBy := detectNetworkTarget(vars) <del> epT, epBy := detectEndpointTarget(vars) <del> <del> ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> sb, errRsp := findSandbox(c, vars[urlSbID], byID) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> err := ep.Leave(sb) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nil, &successResponse <del>} <del> <del>func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> nwT, nwBy := detectNetworkTarget(vars) <del> epT, epBy := detectEndpointTarget(vars) <del> <del> ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> err := ep.Delete(false) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nil, &successResponse <del>} <del> <del>/****************** <del> Service interface <del>*******************/ <del>func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> // Look for query filters and validate <del> nwName, filterByNwName := vars[urlNwName] <del> svName, queryBySvName := vars[urlEpName] <del> shortID, queryBySvPID := vars[urlEpPID] <del> <del> if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID { <del> return nil, &badQueryResponse <del> } <del> <del> var list []*endpointResource <del> <del> switch { <del> case filterByNwName: <del> // return all service present on the specified network <del> nw, errRsp := findNetwork(c, nwName, byName) <del> if !errRsp.isOK() { <del> return list, &successResponse <del> } <del> for _, ep := range nw.Endpoints() { <del> epr := buildEndpointResource(ep) <del> list = append(list, epr) <del> } <del> case queryBySvName: <del> // Look in each network for the service with the specified name <del> l := func(ep libnetwork.Endpoint) bool { <del> if ep.Name() == svName { <del> list = append(list, buildEndpointResource(ep)) <del> return true <del> } <del> return false <del> } <del> for _, nw := range c.Networks() { <del> nw.WalkEndpoints(l) <del> } <del> case queryBySvPID: <del> // Return all the prefix-matching services <del> l := func(ep libnetwork.Endpoint) bool { <del> if strings.HasPrefix(ep.ID(), shortID) { <del> list = append(list, buildEndpointResource(ep)) <del> } <del> return false <del> } <del> for _, nw := range c.Networks() { <del> nw.WalkEndpoints(l) <del> } <del> default: <del> for _, nw := range c.Networks() { <del> for _, ep := range nw.Endpoints() { <del> epr := buildEndpointResource(ep) <del> list = append(list, epr) <del> } <del> } <del> } <del> <del> return list, &successResponse <del>} <del> <del>func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> epT, epBy := detectEndpointTarget(vars) <del> sv, errRsp := findService(c, epT, epBy) <del> if !errRsp.isOK() { <del> return nil, endpointToService(errRsp) <del> } <del> return buildEndpointResource(sv), &successResponse <del>} <del> <del>func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var sp servicePublish <del> <del> err := json.Unmarshal(body, &sp) <del> if err != nil { <del> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> <del> n, errRsp := findNetwork(c, sp.Network, byName) <del> if !errRsp.isOK() { <del> return "", errRsp <del> } <del> <del> var setFctList []libnetwork.EndpointOption <del> for _, str := range sp.MyAliases { <del> setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str)) <del> } <del> <del> ep, err := n.CreateEndpoint(sp.Name, setFctList...) <del> if err != nil { <del> return "", endpointToService(convertNetworkError(err)) <del> } <del> <del> return ep.ID(), &createdResponse <del>} <del> <del>func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var sd serviceDelete <del> <del> if body != nil { <del> err := json.Unmarshal(body, &sd) <del> if err != nil { <del> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> } <del> <del> epT, epBy := detectEndpointTarget(vars) <del> sv, errRsp := findService(c, epT, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> if err := sv.Delete(sd.Force); err != nil { <del> return nil, endpointToService(convertNetworkError(err)) <del> } <del> return nil, &successResponse <del>} <del> <del>func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var bk endpointJoin <del> var setFctList []libnetwork.EndpointOption <del> err := json.Unmarshal(body, &bk) <del> if err != nil { <del> return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> <del> epT, epBy := detectEndpointTarget(vars) <del> sv, errRsp := findService(c, epT, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> sb, errRsp := findSandbox(c, bk.SandboxID, byID) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> for _, str := range bk.Aliases { <del> name, alias, err := netutils.ParseAlias(str) <del> if err != nil { <del> return "", convertNetworkError(err) <del> } <del> setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias)) <del> } <del> <del> err = sv.Join(sb, setFctList...) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return sb.Key(), &successResponse <del>} <del> <del>func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> epT, epBy := detectEndpointTarget(vars) <del> sv, errRsp := findService(c, epT, epBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> sb, errRsp := findSandbox(c, vars[urlSbID], byID) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> err := sv.Leave(sb) <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nil, &successResponse <del>} <del> <del>/****************** <del> Sandbox interface <del>*******************/ <del>func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> if epT, ok := vars[urlEpID]; ok { <del> sv, errRsp := findService(c, epT, byID) <del> if !errRsp.isOK() { <del> return nil, endpointToService(errRsp) <del> } <del> return buildSandboxResource(sv.Info().Sandbox()), &successResponse <del> } <del> <del> sbT, by := detectSandboxTarget(vars) <del> sb, errRsp := findSandbox(c, sbT, by) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> return buildSandboxResource(sb), &successResponse <del>} <del> <del>type cndFnMkr func(string) cndFn <del>type cndFn func(libnetwork.Sandbox) bool <del> <del>// list of (query type, condition function makers) couples <del>var cndMkrList = []struct { <del> identifier string <del> maker cndFnMkr <del>}{ <del> {urlSbPID, func(id string) cndFn { <del> return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) } <del> }}, <del> {urlCnID, func(id string) cndFn { <del> return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id } <del> }}, <del> {urlCnPID, func(id string) cndFn { <del> return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) } <del> }}, <del>} <del> <del>func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool { <del> for _, im := range cndMkrList { <del> if val, ok := vars[im.identifier]; ok { <del> return im.maker(val) <del> } <del> } <del> return func(sb libnetwork.Sandbox) bool { return true } <del>} <del> <del>func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker { <del> return func(sb libnetwork.Sandbox) bool { <del> if condition(sb) { <del> *list = append(*list, buildSandboxResource(sb)) <del> } <del> return false <del> } <del>} <del> <del>func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> var list []*sandboxResource <del> <del> cnd := getQueryCondition(vars) <del> c.WalkSandboxes(sandboxWalker(cnd, &list)) <del> <del> return list, &successResponse <del>} <del> <del>func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <del> sbT, by := detectSandboxTarget(vars) <del> <del> sb, errRsp := findSandbox(c, sbT, by) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> <del> err := sb.Delete() <del> if err != nil { <del> return nil, convertNetworkError(err) <del> } <del> <del> return nil, &successResponse <del>} <del> <del>/*********** <del> Utilities <del>************/ <del>const ( <del> byID = iota <del> byName <del>) <del> <del>func detectNetworkTarget(vars map[string]string) (string, int) { <del> if target, ok := vars[urlNwName]; ok { <del> return target, byName <del> } <del> if target, ok := vars[urlNwID]; ok { <del> return target, byID <del> } <del> // vars are populated from the URL, following cannot happen <del> panic("Missing URL variable parameter for network") <del>} <del> <del>func detectSandboxTarget(vars map[string]string) (string, int) { <del> if target, ok := vars[urlSbID]; ok { <del> return target, byID <del> } <del> // vars are populated from the URL, following cannot happen <del> panic("Missing URL variable parameter for sandbox") <del>} <del> <del>func detectEndpointTarget(vars map[string]string) (string, int) { <del> if target, ok := vars[urlEpName]; ok { <del> return target, byName <del> } <del> if target, ok := vars[urlEpID]; ok { <del> return target, byID <del> } <del> // vars are populated from the URL, following cannot happen <del> panic("Missing URL variable parameter for endpoint") <del>} <del> <del>func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) { <del> var ( <del> nw libnetwork.Network <del> err error <del> ) <del> switch by { <del> case byID: <del> nw, err = c.NetworkByID(s) <del> case byName: <del> if s == "" { <del> s = c.Config().Daemon.DefaultNetwork <del> } <del> nw, err = c.NetworkByName(s) <del> default: <del> panic(fmt.Sprintf("unexpected selector for network search: %d", by)) <del> } <del> if err != nil { <del> if _, ok := err.(types.NotFoundError); ok { <del> return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound} <del> } <del> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> return nw, &successResponse <del>} <del> <del>func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) { <del> var ( <del> sb libnetwork.Sandbox <del> err error <del> ) <del> <del> switch by { <del> case byID: <del> sb, err = c.SandboxByID(s) <del> default: <del> panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by)) <del> } <del> if err != nil { <del> if _, ok := err.(types.NotFoundError); ok { <del> return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound} <del> } <del> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> return sb, &successResponse <del>} <del> <del>func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) { <del> nw, errRsp := findNetwork(c, ns, nwBy) <del> if !errRsp.isOK() { <del> return nil, errRsp <del> } <del> var ( <del> err error <del> ep libnetwork.Endpoint <del> ) <del> switch epBy { <del> case byID: <del> ep, err = nw.EndpointByID(es) <del> case byName: <del> ep, err = nw.EndpointByName(es) <del> default: <del> panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy)) <del> } <del> if err != nil { <del> if _, ok := err.(types.NotFoundError); ok { <del> return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound} <del> } <del> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <del> } <del> return ep, &successResponse <del>} <del> <del>func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) { <del> for _, nw := range c.Networks() { <del> var ( <del> ep libnetwork.Endpoint <del> err error <del> ) <del> switch svBy { <del> case byID: <del> ep, err = nw.EndpointByID(svs) <del> case byName: <del> ep, err = nw.EndpointByName(svs) <del> default: <del> panic(fmt.Sprintf("unexpected selector for service search: %d", svBy)) <del> } <del> if err == nil { <del> return ep, &successResponse <del> } else if _, ok := err.(types.NotFoundError); !ok { <del> return nil, convertNetworkError(err) <del> } <del> } <del> return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound} <del>} <del> <del>func endpointToService(rsp *responseStatus) *responseStatus { <del> rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1) <del> return rsp <del>} <del> <del>func convertNetworkError(err error) *responseStatus { <del> var code int <del> switch err.(type) { <del> case types.BadRequestError: <del> code = http.StatusBadRequest <del> case types.ForbiddenError: <del> code = http.StatusForbidden <del> case types.NotFoundError: <del> code = http.StatusNotFound <del> case types.TimeoutError: <del> code = http.StatusRequestTimeout <del> case types.NotImplementedError: <del> code = http.StatusNotImplemented <del> case types.NoServiceError: <del> code = http.StatusServiceUnavailable <del> case types.InternalError: <del> code = http.StatusInternalServerError <del> default: <del> code = http.StatusInternalServerError <del> } <del> return &responseStatus{Status: err.Error(), StatusCode: code} <del>} <del> <del>func writeJSON(w http.ResponseWriter, code int, v interface{}) error { <del> w.Header().Set("Content-Type", "application/json") <del> w.WriteHeader(code) <del> return json.NewEncoder(w).Encode(v) <del>} <ide><path>libnetwork/api/api_linux_test.go <del>package api <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "errors" <del> "fmt" <del> "io" <del> "net/http" <del> "os" <del> "regexp" <del> "runtime" <del> "testing" <del> <del> "github.com/docker/docker/libnetwork" <del> "github.com/docker/docker/libnetwork/datastore" <del> "github.com/docker/docker/libnetwork/drivers/bridge" <del> "github.com/docker/docker/libnetwork/netlabel" <del> "github.com/docker/docker/libnetwork/options" <del> "github.com/docker/docker/libnetwork/testutils" <del> "github.com/docker/docker/libnetwork/types" <del> "github.com/docker/docker/pkg/reexec" <del>) <del> <del>const ( <del> bridgeNetType = "bridge" <del>) <del> <del>func i2s(i interface{}) string { <del> s, ok := i.(string) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2s for %v", i)) <del> } <del> return s <del>} <del> <del>func i2e(i interface{}) *endpointResource { <del> s, ok := i.(*endpointResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2e for %v", i)) <del> } <del> return s <del>} <del> <del>func i2eL(i interface{}) []*endpointResource { <del> s, ok := i.([]*endpointResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2eL for %v", i)) <del> } <del> return s <del>} <del> <del>func i2n(i interface{}) *networkResource { <del> s, ok := i.(*networkResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2n for %v", i)) <del> } <del> return s <del>} <del> <del>func i2nL(i interface{}) []*networkResource { <del> s, ok := i.([]*networkResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2nL for %v", i)) <del> } <del> return s <del>} <del> <del>func i2sb(i interface{}) *sandboxResource { <del> s, ok := i.(*sandboxResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2sb for %v", i)) <del> } <del> return s <del>} <del> <del>func i2sbL(i interface{}) []*sandboxResource { <del> s, ok := i.([]*sandboxResource) <del> if !ok { <del> panic(fmt.Sprintf("Failed i2sbL for %v", i)) <del> } <del> return s <del>} <del> <del>func createTestNetwork(t *testing.T, network string) (libnetwork.NetworkController, libnetwork.Network) { <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> netOption := options.Generic{ <del> netlabel.GenericData: options.Generic{ <del> "BridgeName": network, <del> }, <del> } <del> netGeneric := libnetwork.NetworkOptionGeneric(netOption) <del> nw, err := c.NewNetwork(bridgeNetType, network, "", netGeneric) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> return c, nw <del>} <del> <del>func GetOpsMap(bridgeName, defaultMTU string) map[string]string { <del> if defaultMTU == "" { <del> return map[string]string{ <del> bridge.BridgeName: bridgeName, <del> } <del> } <del> return map[string]string{ <del> bridge.BridgeName: bridgeName, <del> netlabel.DriverMTU: defaultMTU, <del> } <del>} <del> <del>func getExposedPorts() []types.TransportPort { <del> return []types.TransportPort{ <del> {Proto: types.TCP, Port: uint16(5000)}, <del> {Proto: types.UDP, Port: uint16(400)}, <del> {Proto: types.TCP, Port: uint16(600)}, <del> } <del>} <del> <del>func getPortMapping() []types.PortBinding { <del> return []types.PortBinding{ <del> {Proto: types.TCP, Port: uint16(230), HostPort: uint16(23000)}, <del> {Proto: types.UDP, Port: uint16(200), HostPort: uint16(22000)}, <del> {Proto: types.TCP, Port: uint16(120), HostPort: uint16(12000)}, <del> } <del>} <del> <del>func TestMain(m *testing.M) { <del> if reexec.Init() { <del> return <del> } <del> os.Exit(m.Run()) <del>} <del> <del>func TestSandboxOptionParser(t *testing.T) { <del> hn := "host1" <del> dn := "docker.com" <del> hp := "/etc/hosts" <del> rc := "/etc/resolv.conf" <del> dnss := []string{"8.8.8.8", "172.28.34.5"} <del> ehs := []extraHost{{Name: "extra1", Address: "172.28.9.1"}, {Name: "extra2", Address: "172.28.9.2"}} <del> <del> sb := sandboxCreate{ <del> HostName: hn, <del> DomainName: dn, <del> HostsPath: hp, <del> ResolvConfPath: rc, <del> DNS: dnss, <del> ExtraHosts: ehs, <del> UseDefaultSandbox: true, <del> } <del> <del> if len(sb.parseOptions()) != 9 { <del> t.Fatal("Failed to generate all libnetwork.SandboxOption methods") <del> } <del>} <del> <del>func TestJson(t *testing.T) { <del> nc := networkCreate{NetworkType: bridgeNetType} <del> b, err := json.Marshal(nc) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> var ncp networkCreate <del> err = json.Unmarshal(b, &ncp) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> if nc.NetworkType != ncp.NetworkType { <del> t.Fatalf("Incorrect networkCreate after json encoding/deconding: %v", ncp) <del> } <del> <del> jl := endpointJoin{SandboxID: "abcdef456789"} <del> b, err = json.Marshal(jl) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> var jld endpointJoin <del> err = json.Unmarshal(b, &jld) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> if jl.SandboxID != jld.SandboxID { <del> t.Fatalf("Incorrect endpointJoin after json encoding/deconding: %v", jld) <del> } <del>} <del> <del>func TestCreateDeleteNetwork(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> badBody, err := json.Marshal("bad body") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := make(map[string]string) <del> _, errRsp := procCreateNetwork(c, nil, badBody) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp) <del> } <del> <del> incompleteBody, err := json.Marshal(networkCreate{}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> _, errRsp = procCreateNetwork(c, vars, incompleteBody) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp) <del> } <del> <del> dops := GetOpsMap("abc", "") <del> nops := map[string]string{} <del> nc := networkCreate{Name: "network_1", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops} <del> goodBody, err := json.Marshal(nc) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> _, errRsp = procCreateNetwork(c, vars, goodBody) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> vars[urlNwName] = "" <del> _, errRsp = procDeleteNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> <del> vars[urlNwName] = "abc" <del> _, errRsp = procDeleteNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> <del> vars[urlNwName] = "network_1" <del> _, errRsp = procDeleteNetwork(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del>} <del> <del>func TestGetNetworksAndEndpoints(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> ops := GetOpsMap("api_test_nw", "") <del> nc := networkCreate{Name: "sh", NetworkType: bridgeNetType, DriverOpts: ops} <del> body, err := json.Marshal(nc) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := make(map[string]string) <del> inid, errRsp := procCreateNetwork(c, vars, body) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> nid, ok := inid.(string) <del> if !ok { <del> t.FailNow() <del> } <del> <del> ec1 := endpointCreate{ <del> Name: "ep1", <del> } <del> b1, err := json.Marshal(ec1) <del> if err != nil { <del> t.Fatal(err) <del> } <del> ec2 := endpointCreate{Name: "ep2"} <del> b2, err := json.Marshal(ec2) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars[urlNwName] = "sh" <del> vars[urlEpName] = "ep1" <del> ieid1, errRsp := procCreateEndpoint(c, vars, b1) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> eid1 := i2s(ieid1) <del> vars[urlEpName] = "ep2" <del> ieid2, errRsp := procCreateEndpoint(c, vars, b2) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> eid2 := i2s(ieid2) <del> <del> vars[urlNwName] = "" <del> vars[urlEpName] = "ep1" <del> _, errRsp = procGetEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure but succeeded: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode) <del> } <del> <del> vars = make(map[string]string) <del> vars[urlNwName] = "sh" <del> vars[urlEpID] = "" <del> _, errRsp = procGetEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure but succeeded: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode) <del> } <del> <del> vars = make(map[string]string) <del> vars[urlNwID] = "" <del> vars[urlEpID] = eid1 <del> _, errRsp = procGetEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure but succeeded: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode) <del> } <del> <del> // nw by name and ep by id <del> vars[urlNwName] = "sh" <del> i1, errRsp := procGetEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> // nw by name and ep by name <del> delete(vars, urlEpID) <del> vars[urlEpName] = "ep1" <del> i2, errRsp := procGetEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> // nw by id and ep by name <del> delete(vars, urlNwName) <del> vars[urlNwID] = nid <del> i3, errRsp := procGetEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> // nw by id and ep by id <del> delete(vars, urlEpName) <del> vars[urlEpID] = eid1 <del> i4, errRsp := procGetEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> id1 := i2e(i1).ID <del> if id1 != i2e(i2).ID || id1 != i2e(i3).ID || id1 != i2e(i4).ID { <del> t.Fatalf("Endpoints retrieved via different query parameters differ: %v, %v, %v, %v", i1, i2, i3, i4) <del> } <del> <del> vars[urlNwName] = "" <del> _, errRsp = procGetEndpoints(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> delete(vars, urlNwName) <del> vars[urlNwID] = "fakeID" <del> _, errRsp = procGetEndpoints(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlNwID] = nid <del> _, errRsp = procGetEndpoints(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> vars[urlNwName] = "sh" <del> iepList, errRsp := procGetEndpoints(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> epList := i2eL(iepList) <del> if len(epList) != 2 { <del> t.Fatalf("Did not return the expected number (2) of endpoint resources: %d", len(epList)) <del> } <del> if "sh" != epList[0].Network || "sh" != epList[1].Network { <del> t.Fatal("Did not find expected network name in endpoint resources") <del> } <del> <del> vars = make(map[string]string) <del> vars[urlNwName] = "" <del> _, errRsp = procGetNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars[urlNwName] = "shhhhh" <del> _, errRsp = procGetNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars[urlNwName] = "sh" <del> inr1, errRsp := procGetNetwork(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> nr1 := i2n(inr1) <del> <del> delete(vars, urlNwName) <del> vars[urlNwID] = "acacac" <del> _, errRsp = procGetNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure. Got: %v", errRsp) <del> } <del> vars[urlNwID] = nid <del> inr2, errRsp := procGetNetwork(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("procgetNetworkByName() != procgetNetworkById(), %v vs %v", inr1, inr2) <del> } <del> nr2 := i2n(inr2) <del> if nr1.Name != nr2.Name || nr1.Type != nr2.Type || nr1.ID != nr2.ID || len(nr1.Endpoints) != len(nr2.Endpoints) { <del> t.Fatalf("Get by name and Get failure: %v", errRsp) <del> } <del> <del> if len(nr1.Endpoints) != 2 { <del> t.Fatalf("Did not find the expected number (2) of endpoint resources in the network resource: %d", len(nr1.Endpoints)) <del> } <del> for _, er := range nr1.Endpoints { <del> if er.ID != eid1 && er.ID != eid2 { <del> t.Fatalf("Did not find the expected endpoint resources in the network resource: %v", nr1.Endpoints) <del> } <del> } <del> <del> iList, errRsp := procGetNetworks(c, nil, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> netList := i2nL(iList) <del> if len(netList) != 1 { <del> t.Fatal("Did not return the expected number of network resources") <del> } <del> if nid != netList[0].ID { <del> t.Fatalf("Did not find expected network %s: %v", nid, netList) <del> } <del> <del> _, errRsp = procDeleteNetwork(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "ep1" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> delete(vars, urlEpName) <del> iepList, errRsp = procGetEndpoints(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> epList = i2eL(iepList) <del> if len(epList) != 1 { <del> t.Fatalf("Did not return the expected number (1) of endpoint resources: %d", len(epList)) <del> } <del> <del> vars[urlEpName] = "ep2" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> iepList, errRsp = procGetEndpoints(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> epList = i2eL(iepList) <del> if len(epList) != 0 { <del> t.Fatalf("Did not return the expected number (0) of endpoint resources: %d", len(epList)) <del> } <del> <del> _, errRsp = procDeleteNetwork(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> iList, errRsp = procGetNetworks(c, nil, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> netList = i2nL(iList) <del> if len(netList) != 0 { <del> t.Fatal("Did not return the expected number of network resources") <del> } <del>} <del> <del>func TestProcGetServices(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> // Create 2 networks <del> netName1 := "production" <del> netOption := options.Generic{ <del> netlabel.GenericData: options.Generic{ <del> "BridgeName": netName1, <del> }, <del> } <del> nw1, err := c.NewNetwork(bridgeNetType, netName1, "", libnetwork.NetworkOptionGeneric(netOption)) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> netName2 := "workdev" <del> netOption = options.Generic{ <del> netlabel.GenericData: options.Generic{ <del> "BridgeName": netName2, <del> }, <del> } <del> nw2, err := c.NewNetwork(bridgeNetType, netName2, "", libnetwork.NetworkOptionGeneric(netOption)) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := make(map[string]string) <del> li, errRsp := procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list := i2eL(li) <del> if len(list) != 0 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> // Add a couple of services on one network and one on the other network <del> ep11, err := nw1.CreateEndpoint("db-prod") <del> if err != nil { <del> t.Fatal(err) <del> } <del> ep12, err := nw1.CreateEndpoint("web-prod") <del> if err != nil { <del> t.Fatal(err) <del> } <del> ep21, err := nw2.CreateEndpoint("db-dev") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 3 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> // Filter by network <del> vars[urlNwName] = netName1 <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 2 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> vars[urlNwName] = netName2 <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 1 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> vars[urlNwName] = "unknown-network" <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 0 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> // Query by name <del> delete(vars, urlNwName) <del> vars[urlEpName] = "db-prod" <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 1 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> vars[urlEpName] = "no-service" <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 0 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> // Query by id or partial id <del> delete(vars, urlEpName) <del> vars[urlEpPID] = ep12.ID() <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 1 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> if list[0].ID != ep12.ID() { <del> t.Fatalf("Unexpected element in response: %v", list) <del> } <del> <del> vars[urlEpPID] = "non-id" <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 0 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del> <del> delete(vars, urlEpPID) <del> err = ep11.Delete(false) <del> if err != nil { <del> t.Fatal(err) <del> } <del> err = ep12.Delete(false) <del> if err != nil { <del> t.Fatal(err) <del> } <del> err = ep21.Delete(false) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> li, errRsp = procGetServices(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> list = i2eL(li) <del> if len(list) != 0 { <del> t.Fatalf("Unexpected services in response: %v", list) <del> } <del>} <del> <del>func TestProcGetService(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, nw := createTestNetwork(t, "network") <del> defer c.Stop() <del> ep1, err := nw.CreateEndpoint("db") <del> if err != nil { <del> t.Fatal(err) <del> } <del> ep2, err := nw.CreateEndpoint("web") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := map[string]string{urlEpID: ""} <del> _, errRsp := procGetService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure, but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <del> } <del> <del> vars[urlEpID] = "unknown-service-id" <del> _, errRsp = procGetService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure, but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <del> } <del> <del> vars[urlEpID] = ep1.ID() <del> si, errRsp := procGetService(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> sv := i2e(si) <del> if sv.ID != ep1.ID() { <del> t.Fatalf("Unexpected service resource returned: %v", sv) <del> } <del> <del> vars[urlEpID] = ep2.ID() <del> si, errRsp = procGetService(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> sv = i2e(si) <del> if sv.ID != ep2.ID() { <del> t.Fatalf("Unexpected service resource returned: %v", sv) <del> } <del>} <del> <del>func TestProcPublishUnpublishService(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, _ := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> vars := make(map[string]string) <del> <del> vbad, err := json.Marshal("bad service create data") <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp := procPublishService(c, vars, vbad) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> b, err := json.Marshal(servicePublish{Name: ""}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procPublishService(c, vars, b) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> b, err = json.Marshal(servicePublish{Name: "db"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procPublishService(c, vars, b) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> b, err = json.Marshal(servicePublish{Name: "db", Network: "unknown-network"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procPublishService(c, vars, b) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <del> } <del> <del> b, err = json.Marshal(servicePublish{Name: "", Network: "network"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procPublishService(c, vars, b) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> b, err = json.Marshal(servicePublish{Name: "db", Network: "network"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procPublishService(c, vars, b) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> sp := servicePublish{ <del> Name: "web", <del> Network: "network", <del> } <del> b, err = json.Marshal(sp) <del> if err != nil { <del> t.Fatal(err) <del> } <del> si, errRsp := procPublishService(c, vars, b) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> sid := i2s(si) <del> <del> vars[urlEpID] = "" <del> _, errRsp = procUnpublishService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> vars[urlEpID] = "unknown-service-id" <del> _, errRsp = procUnpublishService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <del> } <del> <del> vars[urlEpID] = sid <del> _, errRsp = procUnpublishService(c, vars, nil) <del> if !errRsp.isOK() { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> _, errRsp = procGetService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure, but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <del> } <del>} <del> <del>func TestAttachDetachBackend(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, nw := createTestNetwork(t, "network") <del> defer c.Stop() <del> ep1, err := nw.CreateEndpoint("db") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := make(map[string]string) <del> <del> vbad, err := json.Marshal("bad data") <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp := procAttachBackend(c, vars, vbad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "endpoint" <del> bad, err := json.Marshal(endpointJoin{}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procAttachBackend(c, vars, bad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <del> } <del> <del> vars[urlEpID] = "db" <del> _, errRsp = procGetSandbox(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatalf("Expected failure. Got %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <del> } <del> <del> vars[urlEpName] = "db" <del> _, errRsp = procAttachBackend(c, vars, bad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> cid := "abcdefghi" <del> sbox, err := c.NewSandbox(cid) <del> if err != nil { <del> t.Fatal(err) <del> } <del> sid := sbox.ID() <del> defer sbox.Delete() <del> <del> jl := endpointJoin{SandboxID: sid} <del> jlb, err := json.Marshal(jl) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> _, errRsp = procAttachBackend(c, vars, jlb) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure, got: %v", errRsp) <del> } <del> <del> sli, errRsp := procGetSandboxes(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure, got: %v", errRsp) <del> } <del> sl := i2sbL(sli) <del> if len(sl) != 1 { <del> t.Fatalf("Did not find expected number of sandboxes attached to the service: %d", len(sl)) <del> } <del> if sl[0].ContainerID != cid { <del> t.Fatalf("Did not find expected sandbox attached to the service: %v", sl[0]) <del> } <del> <del> _, errRsp = procUnpublishService(c, vars, nil) <del> if errRsp.isOK() { <del> t.Fatal("Expected failure but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusForbidden { <del> t.Fatalf("Expected %d. Got: %v", http.StatusForbidden, errRsp) <del> } <del> <del> vars[urlEpName] = "endpoint" <del> _, errRsp = procDetachBackend(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <del> } <del> <del> vars[urlEpName] = "db" <del> _, errRsp = procDetachBackend(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del> <del> vars[urlSbID] = sid <del> _, errRsp = procDetachBackend(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure, got: %v", errRsp) <del> } <del> <del> delete(vars, urlEpID) <del> si, errRsp := procGetSandbox(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure, got: %v", errRsp) <del> } <del> sb := i2sb(si) <del> if sb.ContainerID != cid { <del> t.Fatalf("Did not find expected sandbox. Got %v", sb) <del> } <del> <del> err = ep1.Delete(false) <del> if err != nil { <del> t.Fatal(err) <del> } <del>} <del> <del>func TestDetectGetNetworksInvalidQueryComposition(t *testing.T) { <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> vars := map[string]string{urlNwName: "x", urlNwPID: "y"} <del> _, errRsp := procGetNetworks(c, vars, nil) <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del>} <del> <del>func TestDetectGetEndpointsInvalidQueryComposition(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, _ := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"} <del> _, errRsp := procGetEndpoints(c, vars, nil) <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del>} <del> <del>func TestDetectGetServicesInvalidQueryComposition(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, _ := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"} <del> _, errRsp := procGetServices(c, vars, nil) <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <del> } <del>} <del> <del>func TestFindNetworkUtilPanic(t *testing.T) { <del> defer checkPanic(t) <del> findNetwork(nil, "", -1) <del>} <del> <del>func TestFindNetworkUtil(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, nw := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> nid := nw.ID() <del> <del> _, errRsp := findNetwork(c, "", byName) <del> if errRsp == &successResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <del> } <del> <del> n, errRsp := findNetwork(c, nid, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> if n == nil { <del> t.Fatal("Unexpected nil libnetwork.Network") <del> } <del> if nid != n.ID() { <del> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n) <del> } <del> if "network" != n.Name() { <del> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n) <del> } <del> <del> n, errRsp = findNetwork(c, "network", byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> if n == nil { <del> t.Fatal("Unexpected nil libnetwork.Network") <del> } <del> if nid != n.ID() { <del> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n) <del> } <del> if "network" != n.Name() { <del> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n) <del> } <del> <del> if err := n.Delete(); err != nil { <del> t.Fatalf("Failed to delete the network: %s", err.Error()) <del> } <del> <del> _, errRsp = findNetwork(c, nid, byID) <del> if errRsp == &successResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findNetwork(c, "network", byName) <del> if errRsp == &successResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del>} <del> <del>func TestCreateDeleteEndpoints(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> nc := networkCreate{Name: "firstNet", NetworkType: bridgeNetType} <del> body, err := json.Marshal(nc) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars := make(map[string]string) <del> i, errRsp := procCreateNetwork(c, vars, body) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> nid := i2s(i) <del> <del> vbad, err := json.Marshal("bad endpoint create data") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars[urlNwName] = "firstNet" <del> _, errRsp = procCreateEndpoint(c, vars, vbad) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> <del> b, err := json.Marshal(endpointCreate{Name: ""}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars[urlNwName] = "secondNet" <del> _, errRsp = procCreateEndpoint(c, vars, b) <del> if errRsp == &createdResponse { <del> t.Fatal("Expected to fail but succeeded") <del> } <del> <del> vars[urlNwName] = "firstNet" <del> _, errRsp = procCreateEndpoint(c, vars, b) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure but succeeded: %v", errRsp) <del> } <del> <del> b, err = json.Marshal(endpointCreate{Name: "firstEp"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> i, errRsp = procCreateEndpoint(c, vars, b) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> eid := i2s(i) <del> <del> _, errRsp = findEndpoint(c, "myNet", "firstEp", byName, byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure but succeeded: %v", errRsp) <del> } <del> <del> ep0, errRsp := findEndpoint(c, nid, "firstEp", byID, byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep1, errRsp := findEndpoint(c, "firstNet", "firstEp", byName, byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep3, errRsp := findEndpoint(c, "firstNet", eid, byName, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() || ep0.ID() != ep3.ID() { <del> t.Fatalf("Different queries returned different endpoints: \nep0: %v\nep1: %v\nep2: %v\nep3: %v", ep0, ep1, ep2, ep3) <del> } <del> <del> vars = make(map[string]string) <del> vars[urlNwName] = "" <del> vars[urlEpName] = "ep1" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlNwName] = "firstNet" <del> vars[urlEpName] = "" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "ep2" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "firstEp" <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> _, errRsp = findEndpoint(c, "firstNet", "firstEp", byName, byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del>} <del> <del>func TestJoinLeave(t *testing.T) { <del> if runtime.GOARCH == "arm64" { <del> t.Skip("This test fails on arm64 foor some reason... this need to be fixed") <del> } <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> nb, err := json.Marshal(networkCreate{Name: "network", NetworkType: bridgeNetType}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> vars := make(map[string]string) <del> _, errRsp := procCreateNetwork(c, vars, nb) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> eb, err := json.Marshal(endpointCreate{Name: "endpoint"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> vars[urlNwName] = "network" <del> _, errRsp = procCreateEndpoint(c, vars, eb) <del> if errRsp != &createdResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> vbad, err := json.Marshal("bad data") <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procJoinEndpoint(c, vars, vbad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "endpoint" <del> bad, err := json.Marshal(endpointJoin{}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> _, errRsp = procJoinEndpoint(c, vars, bad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> cid := "abcdefghi" <del> sb, err := c.NewSandbox(cid) <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer sb.Delete() <del> <del> jl := endpointJoin{SandboxID: sb.ID()} <del> jlb, err := json.Marshal(jl) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> vars = make(map[string]string) <del> vars[urlNwName] = "" <del> vars[urlEpName] = "" <del> _, errRsp = procJoinEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlNwName] = "network" <del> vars[urlEpName] = "" <del> _, errRsp = procJoinEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlEpName] = "epoint" <del> _, errRsp = procJoinEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> // bad labels <del> vars[urlEpName] = "endpoint" <del> key, errRsp := procJoinEndpoint(c, vars, jlb) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure, got: %v", errRsp) <del> } <del> <del> keyStr := i2s(key) <del> if keyStr == "" { <del> t.Fatal("Empty sandbox key") <del> } <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlNwName] = "network2" <del> _, errRsp = procLeaveEndpoint(c, vars, vbad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> _, errRsp = procLeaveEndpoint(c, vars, bad) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars = make(map[string]string) <del> vars[urlNwName] = "" <del> vars[urlEpName] = "" <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars[urlNwName] = "network" <del> vars[urlEpName] = "" <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars[urlEpName] = "2epoint" <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> vars[urlEpName] = "epoint" <del> vars[urlCnID] = "who" <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> delete(vars, urlCnID) <del> vars[urlEpName] = "endpoint" <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> vars[urlSbID] = sb.ID() <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> _, errRsp = procLeaveEndpoint(c, vars, jlb) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, got: %v", errRsp) <del> } <del> <del> _, errRsp = procDeleteEndpoint(c, vars, nil) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del>} <del> <del>func TestFindEndpointUtilPanic(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> defer checkPanic(t) <del> c, nw := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> nid := nw.ID() <del> findEndpoint(c, nid, "", byID, -1) <del>} <del> <del>func TestFindServiceUtilPanic(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> defer checkPanic(t) <del> c, _ := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> findService(c, "random_service", -1) <del>} <del> <del>func TestFindEndpointUtil(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> c, nw := createTestNetwork(t, "network") <del> defer c.Stop() <del> <del> nid := nw.ID() <del> <del> ep, err := nw.CreateEndpoint("secondEp", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> eid := ep.ID() <del> <del> _, errRsp := findEndpoint(c, nid, "", byID, byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusBadRequest { <del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <del> } <del> <del> ep0, errRsp := findEndpoint(c, nid, "secondEp", byID, byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep1, errRsp := findEndpoint(c, "network", "secondEp", byName, byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep3, errRsp := findEndpoint(c, "network", eid, byName, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep4, errRsp := findService(c, "secondEp", byName) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> ep5, errRsp := findService(c, eid, byID) <del> if errRsp != &successResponse { <del> t.Fatalf("Unexpected failure: %v", errRsp) <del> } <del> <del> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() || <del> ep0.ID() != ep3.ID() || ep0.ID() != ep4.ID() || ep0.ID() != ep5.ID() { <del> t.Fatal("Different queries returned different endpoints") <del> } <del> <del> ep.Delete(false) <del> <del> _, errRsp = findEndpoint(c, nid, "secondEp", byID, byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findEndpoint(c, "network", "secondEp", byName, byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findEndpoint(c, nid, eid, byID, byID) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findEndpoint(c, "network", eid, byName, byID) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findService(c, "secondEp", byName) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del> <del> _, errRsp = findService(c, eid, byID) <del> if errRsp == &successResponse { <del> t.Fatalf("Expected failure, but got: %v", errRsp) <del> } <del> if errRsp.StatusCode != http.StatusNotFound { <del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <del> } <del>} <del> <del>func TestEndpointToService(t *testing.T) { <del> r := &responseStatus{Status: "this is one endpoint", StatusCode: http.StatusOK} <del> r = endpointToService(r) <del> if r.Status != "this is one service" { <del> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status) <del> } <del> <del> r = &responseStatus{Status: "this is one network", StatusCode: http.StatusOK} <del> r = endpointToService(r) <del> if r.Status != "this is one network" { <del> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status) <del> } <del>} <del> <del>func checkPanic(t *testing.T) { <del> if r := recover(); r != nil { <del> if _, ok := r.(runtime.Error); ok { <del> panic(r) <del> } <del> } else { <del> t.Fatal("Expected to panic, but succeeded") <del> } <del>} <del> <del>func TestDetectNetworkTargetPanic(t *testing.T) { <del> defer checkPanic(t) <del> vars := make(map[string]string) <del> detectNetworkTarget(vars) <del>} <del> <del>func TestDetectEndpointTargetPanic(t *testing.T) { <del> defer checkPanic(t) <del> vars := make(map[string]string) <del> detectEndpointTarget(vars) <del>} <del> <del>func TestResponseStatus(t *testing.T) { <del> list := []int{ <del> http.StatusBadGateway, <del> http.StatusBadRequest, <del> http.StatusConflict, <del> http.StatusContinue, <del> http.StatusExpectationFailed, <del> http.StatusForbidden, <del> http.StatusFound, <del> http.StatusGatewayTimeout, <del> http.StatusGone, <del> http.StatusHTTPVersionNotSupported, <del> http.StatusInternalServerError, <del> http.StatusLengthRequired, <del> http.StatusMethodNotAllowed, <del> http.StatusMovedPermanently, <del> http.StatusMultipleChoices, <del> http.StatusNoContent, <del> http.StatusNonAuthoritativeInfo, <del> http.StatusNotAcceptable, <del> http.StatusNotFound, <del> http.StatusNotModified, <del> http.StatusPartialContent, <del> http.StatusPaymentRequired, <del> http.StatusPreconditionFailed, <del> http.StatusProxyAuthRequired, <del> http.StatusRequestEntityTooLarge, <del> http.StatusRequestTimeout, <del> http.StatusRequestURITooLong, <del> http.StatusRequestedRangeNotSatisfiable, <del> http.StatusResetContent, <del> http.StatusServiceUnavailable, <del> http.StatusSwitchingProtocols, <del> http.StatusTemporaryRedirect, <del> http.StatusUnauthorized, <del> http.StatusUnsupportedMediaType, <del> http.StatusUseProxy, <del> } <del> for _, c := range list { <del> r := responseStatus{StatusCode: c} <del> if r.isOK() { <del> t.Fatalf("isOK() returned true for code% d", c) <del> } <del> } <del> <del> r := responseStatus{StatusCode: http.StatusOK} <del> if !r.isOK() { <del> t.Fatal("isOK() failed") <del> } <del> <del> r = responseStatus{StatusCode: http.StatusCreated} <del> if !r.isOK() { <del> t.Fatal("isOK() failed") <del> } <del>} <del> <del>// Local structs for end to end testing of api.go <del>type localReader struct { <del> data []byte <del> beBad bool <del>} <del> <del>func newLocalReader(data []byte) *localReader { <del> lr := &localReader{data: make([]byte, len(data))} <del> copy(lr.data, data) <del> return lr <del>} <del> <del>func (l *localReader) Read(p []byte) (n int, err error) { <del> if l.beBad { <del> return 0, errors.New("I am a bad reader") <del> } <del> if p == nil { <del> return -1, errors.New("nil buffer passed") <del> } <del> if l.data == nil || len(l.data) == 0 { <del> return 0, io.EOF <del> } <del> copy(p[:], l.data[:]) <del> return len(l.data), io.EOF <del>} <del> <del>type localResponseWriter struct { <del> body []byte <del> statusCode int <del>} <del> <del>func newWriter() *localResponseWriter { <del> return &localResponseWriter{} <del>} <del> <del>func (f *localResponseWriter) Header() http.Header { <del> return make(map[string][]string) <del>} <del> <del>func (f *localResponseWriter) Write(data []byte) (int, error) { <del> if data == nil { <del> return -1, errors.New("nil data passed") <del> } <del> <del> f.body = make([]byte, len(data)) <del> copy(f.body, data) <del> <del> return len(f.body), nil <del>} <del> <del>func (f *localResponseWriter) WriteHeader(c int) { <del> f.statusCode = c <del>} <del> <del>func testWriteJSON(t *testing.T, testCode int, testData interface{}) { <del> testDataMarshalled, err := json.Marshal(testData) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> rsp := newWriter() <del> writeJSON(rsp, testCode, testData) <del> if rsp.statusCode != testCode { <del> t.Fatalf("writeJSON() failed to set the status code. Expected %d. Got %d", testCode, rsp.statusCode) <del> } <del> // writeJSON calls json.Encode and it appends '\n' to the result, <del> // while json.Marshal not <del> expected := append(testDataMarshalled, byte('\n')) <del> if !bytes.Equal(expected, rsp.body) { <del> t.Fatalf("writeJSON() failed to set the body. Expected %q. Got %q", expected, rsp.body) <del> } <del>} <del> <del>func TestWriteJSON(t *testing.T) { <del> testWriteJSON(t, 55, "test data as string") <del> testWriteJSON(t, 55, []byte("test data as bytes")) <del>} <del> <del>func TestHttpHandlerUninit(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> h := &httpHandler{c: c} <del> h.initRouter() <del> if h.r == nil { <del> t.Fatal("initRouter() did not initialize the router") <del> } <del> <del> rsp := newWriter() <del> req, err := http.NewRequest("GET", "/v1.19/networks", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> handleRequest := NewHTTPHandler(nil) <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusServiceUnavailable { <del> t.Fatalf("Expected (%d). Got (%d): %s", http.StatusServiceUnavailable, rsp.statusCode, rsp.body) <del> } <del> <del> handleRequest = NewHTTPHandler(c) <del> <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected (%d). Got: (%d): %s", http.StatusOK, rsp.statusCode, rsp.body) <del> } <del> <del> var list []*networkResource <del> err = json.Unmarshal(rsp.body, &list) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(list) != 0 { <del> t.Fatalf("Expected empty list. Got %v", list) <del> } <del> <del> n, err := c.NewNetwork(bridgeNetType, "didietro", "", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> nwr := buildNetworkResource(n) <del> expected, err := json.Marshal([]*networkResource{nwr}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty list of networks") <del> } <del> if bytes.Equal(rsp.body, expected) { <del> t.Fatal("Incorrect list of networks in response's body") <del> } <del>} <del> <del>func TestHttpHandlerBadBody(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> rsp := newWriter() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> handleRequest := NewHTTPHandler(c) <del> <del> req, err := http.NewRequest("POST", "/v1.19/networks", &localReader{beBad: true}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusBadRequest { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body)) <del> } <del> <del> body := []byte{} <del> lr := newLocalReader(body) <del> req, err = http.NewRequest("POST", "/v1.19/networks", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusBadRequest { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body)) <del> } <del>} <del> <del>func TestEndToEnd(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> rsp := newWriter() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> <del> handleRequest := NewHTTPHandler(c) <del> <del> dops := GetOpsMap("cdef", "1460") <del> nops := map[string]string{} <del> <del> // Create network <del> nc := networkCreate{Name: "network-fiftyfive", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops} <del> body, err := json.Marshal(nc) <del> if err != nil { <del> t.Fatal(err) <del> } <del> lr := newLocalReader(body) <del> req, err := http.NewRequest("POST", "/v1.19/networks", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusCreated { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <del> } <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty response body") <del> } <del> <del> var nid string <del> err = json.Unmarshal(rsp.body, &nid) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> // Query networks collection <del> req, err = http.NewRequest("GET", "/v1.19/networks?name=", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> var list []*networkResource <del> err = json.Unmarshal(rsp.body, &list) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(list) != 0 { <del> t.Fatalf("Expected empty list. Got %v", list) <del> } <del> <del> req, err = http.NewRequest("GET", "/v1.19/networks", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> b0 := make([]byte, len(rsp.body)) <del> copy(b0, rsp.body) <del> <del> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> if !bytes.Equal(b0, rsp.body) { <del> t.Fatal("Expected same body from GET /networks and GET /networks?name=<nw> when only network <nw> exist.") <del> } <del> <del> // Query network by name <del> req, err = http.NewRequest("GET", "/v1.19/networks?name=culo", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &list) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(list) != 0 { <del> t.Fatalf("Expected empty list. Got %v", list) <del> } <del> <del> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &list) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(list) == 0 { <del> t.Fatal("Expected non empty list") <del> } <del> if list[0].Name != "network-fiftyfive" || nid != list[0].ID { <del> t.Fatalf("Incongruent resource found: %v", list[0]) <del> } <del> <del> // Query network by partial id <del> chars := []byte(nid) <del> partial := string(chars[0 : len(chars)/2]) <del> req, err = http.NewRequest("GET", "/v1.19/networks?partial-id="+partial, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &list) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(list) == 0 { <del> t.Fatal("Expected non empty list") <del> } <del> if list[0].Name != "network-fiftyfive" || nid != list[0].ID { <del> t.Fatalf("Incongruent resource found: %v", list[0]) <del> } <del> <del> // Get network by id <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> var nwr networkResource <del> err = json.Unmarshal(rsp.body, &nwr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if nwr.Name != "network-fiftyfive" || nid != nwr.ID { <del> t.Fatalf("Incongruent resource found: %v", nwr) <del> } <del> <del> // Create endpoint <del> eb, err := json.Marshal(endpointCreate{Name: "ep-TwentyTwo"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> lr = newLocalReader(eb) <del> req, err = http.NewRequest("POST", "/v1.19/networks/"+nid+"/endpoints", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusCreated { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <del> } <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty response body") <del> } <del> <del> var eid string <del> err = json.Unmarshal(rsp.body, &eid) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> // Query endpoint(s) <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=bla", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> var epList []*endpointResource <del> err = json.Unmarshal(rsp.body, &epList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(epList) != 0 { <del> t.Fatalf("Expected empty list. Got %v", epList) <del> } <del> <del> // Query endpoint by name <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=ep-TwentyTwo", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &epList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(epList) == 0 { <del> t.Fatal("Empty response body") <del> } <del> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID { <del> t.Fatalf("Incongruent resource found: %v", epList[0]) <del> } <del> <del> // Query endpoint by partial id <del> chars = []byte(eid) <del> partial = string(chars[0 : len(chars)/2]) <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?partial-id="+partial, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &epList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(epList) == 0 { <del> t.Fatal("Empty response body") <del> } <del> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID { <del> t.Fatalf("Incongruent resource found: %v", epList[0]) <del> } <del> <del> // Get endpoint by id <del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints/"+eid, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> var epr endpointResource <del> err = json.Unmarshal(rsp.body, &epr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if epr.Name != "ep-TwentyTwo" || epr.ID != eid { <del> t.Fatalf("Incongruent resource found: %v", epr) <del> } <del> <del> // Store two container ids and one partial ids <del> cid1 := "container10010000000" <del> cid2 := "container20010000000" <del> chars = []byte(cid1) <del> cpid1 := string(chars[0 : len(chars)/2]) <del> <del> // Create sandboxes <del> sb1, err := json.Marshal(sandboxCreate{ <del> ContainerID: cid1, <del> PortMapping: getPortMapping(), <del> }) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> lr = newLocalReader(sb1) <del> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusCreated { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <del> } <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty response body") <del> } <del> // Get sandbox id and partial id <del> var sid1 string <del> err = json.Unmarshal(rsp.body, &sid1) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> sb2, err := json.Marshal(sandboxCreate{ <del> ContainerID: cid2, <del> ExposedPorts: getExposedPorts(), <del> }) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> lr = newLocalReader(sb2) <del> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusCreated { <del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <del> } <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty response body") <del> } <del> // Get sandbox id and partial id <del> var sid2 string <del> err = json.Unmarshal(rsp.body, &sid2) <del> if err != nil { <del> t.Fatal(err) <del> } <del> chars = []byte(sid2) <del> spid2 := string(chars[0 : len(chars)/2]) <del> <del> // Query sandboxes <del> req, err = http.NewRequest("GET", "/sandboxes", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> var sbList []*sandboxResource <del> err = json.Unmarshal(rsp.body, &sbList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(sbList) != 2 { <del> t.Fatalf("Expected 2 elements in list. Got %v", sbList) <del> } <del> <del> // Get sandbox by id <del> req, err = http.NewRequest("GET", "/sandboxes/"+sid1, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> var sbr sandboxResource <del> err = json.Unmarshal(rsp.body, &sbr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if sbr.ContainerID != cid1 { <del> t.Fatalf("Incongruent resource found: %v", sbr) <del> } <del> <del> // Query sandbox by partial sandbox id <del> req, err = http.NewRequest("GET", "/sandboxes?partial-id="+spid2, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &sbList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(sbList) == 0 { <del> t.Fatal("Empty response body") <del> } <del> if sbList[0].ID != sid2 { <del> t.Fatalf("Incongruent resource found: %v", sbList[0]) <del> } <del> <del> // Query sandbox by container id <del> req, err = http.NewRequest("GET", "/sandboxes?container-id="+cid2, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &sbList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(sbList) == 0 { <del> t.Fatal("Empty response body") <del> } <del> if sbList[0].ContainerID != cid2 { <del> t.Fatalf("Incongruent resource found: %v", sbList[0]) <del> } <del> <del> // Query sandbox by partial container id <del> req, err = http.NewRequest("GET", "/sandboxes?partial-container-id="+cpid1, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> if rsp.statusCode != http.StatusOK { <del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body) <del> } <del> <del> err = json.Unmarshal(rsp.body, &sbList) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(sbList) == 0 { <del> t.Fatal("Empty response body") <del> } <del> if sbList[0].ContainerID != cid1 { <del> t.Fatalf("Incongruent resource found: %v", sbList[0]) <del> } <del>} <del> <del>func TestEndToEndErrorMessage(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <del> <del> rsp := newWriter() <del> <del> // Cleanup local datastore file <del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address) <del> <del> c, err := libnetwork.New() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer c.Stop() <del> handleRequest := NewHTTPHandler(c) <del> <del> body := []byte{} <del> lr := newLocalReader(body) <del> req, err := http.NewRequest("POST", "/v1.19/networks", lr) <del> if err != nil { <del> t.Fatal(err) <del> } <del> handleRequest(rsp, req) <del> <del> if len(rsp.body) == 0 { <del> t.Fatal("Empty response body.") <del> } <del> empty := []byte("\"\"") <del> if bytes.Equal(empty, bytes.TrimSpace(rsp.body)) { <del> t.Fatal("Empty response error message.") <del> } <del>} <del> <del>type bre struct{} <del> <del>func (b *bre) Error() string { <del> return "I am a bad request error" <del>} <del>func (b *bre) BadRequest() {} <del> <del>type nfe struct{} <del> <del>func (n *nfe) Error() string { <del> return "I am a not found error" <del>} <del>func (n *nfe) NotFound() {} <del> <del>type forb struct{} <del> <del>func (f *forb) Error() string { <del> return "I am a bad request error" <del>} <del>func (f *forb) Forbidden() {} <del> <del>type notimpl struct{} <del> <del>func (nip *notimpl) Error() string { <del> return "I am a not implemented error" <del>} <del>func (nip *notimpl) NotImplemented() {} <del> <del>type inter struct{} <del> <del>func (it *inter) Error() string { <del> return "I am an internal error" <del>} <del>func (it *inter) Internal() {} <del> <del>type tout struct{} <del> <del>func (to *tout) Error() string { <del> return "I am a timeout error" <del>} <del>func (to *tout) Timeout() {} <del> <del>type noserv struct{} <del> <del>func (nos *noserv) Error() string { <del> return "I am a no service error" <del>} <del>func (nos *noserv) NoService() {} <del> <del>type notclassified struct{} <del> <del>func (noc *notclassified) Error() string { <del> return "I am a non classified error" <del>} <del> <del>func TestErrorConversion(t *testing.T) { <del> if convertNetworkError(new(bre)).StatusCode != http.StatusBadRequest { <del> t.Fatal("Failed to recognize BadRequest error") <del> } <del> <del> if convertNetworkError(new(nfe)).StatusCode != http.StatusNotFound { <del> t.Fatal("Failed to recognize NotFound error") <del> } <del> <del> if convertNetworkError(new(forb)).StatusCode != http.StatusForbidden { <del> t.Fatal("Failed to recognize Forbidden error") <del> } <del> <del> if convertNetworkError(new(notimpl)).StatusCode != http.StatusNotImplemented { <del> t.Fatal("Failed to recognize NotImplemented error") <del> } <del> <del> if convertNetworkError(new(inter)).StatusCode != http.StatusInternalServerError { <del> t.Fatal("Failed to recognize Internal error") <del> } <del> <del> if convertNetworkError(new(tout)).StatusCode != http.StatusRequestTimeout { <del> t.Fatal("Failed to recognize Timeout error") <del> } <del> <del> if convertNetworkError(new(noserv)).StatusCode != http.StatusServiceUnavailable { <del> t.Fatal("Failed to recognize No Service error") <del> } <del> <del> if convertNetworkError(new(notclassified)).StatusCode != http.StatusInternalServerError { <del> t.Fatal("Failed to recognize not classified error as Internal error") <del> } <del>} <del> <del>func TestFieldRegex(t *testing.T) { <del> pr := regexp.MustCompile(regex) <del> qr := regexp.MustCompile(`^` + qregx + `$`) // mux compiles it like this <del> <del> if pr.MatchString("") { <del> t.Fatal("Unexpected match") <del> } <del> if !qr.MatchString("") { <del> t.Fatal("Unexpected match failure") <del> } <del> <del> if pr.MatchString(":") { <del> t.Fatal("Unexpected match") <del> } <del> if qr.MatchString(":") { <del> t.Fatal("Unexpected match") <del> } <del> <del> if pr.MatchString(".") { <del> t.Fatal("Unexpected match") <del> } <del> if qr.MatchString(".") { <del> t.Fatal("Unexpected match") <del> } <del>} <ide><path>libnetwork/api/types.go <del>package api <del> <del>import "github.com/docker/docker/libnetwork/types" <del> <del>/*********** <del> Resources <del>************/ <del> <del>// networkResource is the body of the "get network" http response message <del>type networkResource struct { <del> Name string `json:"name"` <del> ID string `json:"id"` <del> Type string `json:"type"` <del> Endpoints []*endpointResource `json:"endpoints"` <del>} <del> <del>// endpointResource is the body of the "get endpoint" http response message <del>type endpointResource struct { <del> Name string `json:"name"` <del> ID string `json:"id"` <del> Network string `json:"network"` <del>} <del> <del>// sandboxResource is the body of "get service backend" response message <del>type sandboxResource struct { <del> ID string `json:"id"` <del> Key string `json:"key"` <del> ContainerID string `json:"container_id"` <del>} <del> <del>/*********** <del> Body types <del> ************/ <del> <del>type ipamConf struct { <del> PreferredPool string <del> SubPool string <del> Gateway string <del> AuxAddresses map[string]string <del>} <del> <del>// networkCreate is the expected body of the "create network" http request message <del>type networkCreate struct { <del> Name string `json:"name"` <del> ID string `json:"id"` <del> NetworkType string `json:"network_type"` <del> IPv4Conf []ipamConf `json:"ipv4_configuration"` <del> DriverOpts map[string]string `json:"driver_opts"` <del> NetworkOpts map[string]string `json:"network_opts"` <del>} <del> <del>// endpointCreate represents the body of the "create endpoint" http request message <del>type endpointCreate struct { <del> Name string `json:"name"` <del> MyAliases []string `json:"my_aliases"` <del>} <del> <del>// sandboxCreate is the expected body of the "create sandbox" http request message <del>type sandboxCreate struct { <del> ContainerID string `json:"container_id"` <del> HostName string `json:"host_name"` <del> DomainName string `json:"domain_name"` <del> HostsPath string `json:"hosts_path"` <del> ResolvConfPath string `json:"resolv_conf_path"` <del> DNS []string `json:"dns"` <del> ExtraHosts []extraHost `json:"extra_hosts"` <del> UseDefaultSandbox bool `json:"use_default_sandbox"` <del> UseExternalKey bool `json:"use_external_key"` <del> ExposedPorts []types.TransportPort `json:"exposed_ports"` <del> PortMapping []types.PortBinding `json:"port_mapping"` <del>} <del> <del>// endpointJoin represents the expected body of the "join endpoint" or "leave endpoint" http request messages <del>type endpointJoin struct { <del> SandboxID string `json:"sandbox_id"` <del> Aliases []string `json:"aliases"` <del>} <del> <del>// servicePublish represents the body of the "publish service" http request message <del>type servicePublish struct { <del> Name string `json:"name"` <del> MyAliases []string `json:"my_aliases"` <del> Network string `json:"network_name"` <del>} <del> <del>// serviceDelete represents the body of the "unpublish service" http request message <del>type serviceDelete struct { <del> Name string `json:"name"` <del> Force bool `json:"force"` <del>} <del> <del>// extraHost represents the extra host object <del>type extraHost struct { <del> Name string `json:"name"` <del> Address string `json:"address"` <del>}
3
Text
Text
add a section on decentralized apps
31ff1b08ea28304a124ed150be438f48622a5c55
<ide><path>guide/english/blockchain/smart-contracts/index.md <ide> First conceived in [1994](http://www.fon.hum.uva.nl/rob/Courses/InformationInSp <ide> <ide> A smart contract is a computer code running on top of a blockchain containing a set of rules under which the parties to that smart contract agree to interact with each other. If and when the pre-defined rules are met, the agreement is automatically enforced. The smart contract code facilitates, verifies, and enforces the negotiation or performance of an agreement or transaction. It is the simplest form of decentralized automation. <ide> <del>Deployed contracts can be viewed on platforms such as [Etherscan](www.etherscan.io). <del> <add>Smart contracts can be used to create Decentralized Apps or Dapps that live on a host blockchain. <add>The most famous Dapp is perhaps the game CryptoKitties which exploded in popularity towards the end of 2017. <add>The network that CryptoKitties lives on, Ethereum, faced heavy congestion as a result. <ide> <ide> ## Applications of Smart Contacts <ide> Smart Contracts allows the transfer of goods and services without the need for a independent third party. Logic and rules are built into the smart contract that define the permissions and processes associated with a particular agreement and enforce the obligations attached to it. This provides an opportunity to remove middlemen that are traditionally required to interact with physical property or financial service instruments.
1
Go
Go
remove unused parameter in download
12180948be8040a4cdf99a0e660098cd33e32832
<ide><path>api.go <ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ <ide> } <ide> context = c <ide> } else if utils.IsURL(remoteURL) { <del> f, err := utils.Download(remoteURL, ioutil.Discard) <add> f, err := utils.Download(remoteURL) <ide> if err != nil { <ide> return err <ide> } <ide><path>buildfile.go <ide> func (b *buildFile) CmdVolume(args string) error { <ide> } <ide> <ide> func (b *buildFile) addRemote(container *Container, orig, dest string) error { <del> file, err := utils.Download(orig, ioutil.Discard) <add> file, err := utils.Download(orig) <ide> if err != nil { <ide> return err <ide> } <ide><path>server.go <ide> func (srv *Server) ImageInsert(name, url, path string, out io.Writer, sf *utils. <ide> return err <ide> } <ide> <del> file, err := utils.Download(url, out) <add> file, err := utils.Download(url) <ide> if err != nil { <ide> return err <ide> } <ide> func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Write <ide> out.Write(sf.FormatStatus("", "Downloading from %s", u)) <ide> // Download with curl (pretty progress bar) <ide> // If curl is not available, fallback to http.Get() <del> resp, err = utils.Download(u.String(), out) <add> resp, err = utils.Download(u.String()) <ide> if err != nil { <ide> return err <ide> } <ide><path>utils/utils.go <ide> func Go(f func() error) chan error { <ide> } <ide> <ide> // Request a given URL and return an io.Reader <del>func Download(url string, stderr io.Writer) (*http.Response, error) { <add>func Download(url string) (*http.Response, error) { <ide> var resp *http.Response <ide> var err error <ide> if resp, err = http.Get(url); err != nil {
4
Text
Text
fix typo in nativemodulesios.md
d1f42a82d235af405bd0bb4fcbaf4f4f27075f09
<ide><path>docs/NativeModulesIOS.md <ide> This is a more advanced guide that shows how to build a native module. It assume <ide> <ide> This guide will use [iOS Calendar API](https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html) example. Let's say we would like to be able to access the iOS calendar from JavaScript. <ide> <del>Native module is just an Objectve-C class that implements `RCTBridgeModule` protocol. If you are wondering, RCT is a shorthand for ReaCT. <add>Native module is just an Objective-C class that implements `RCTBridgeModule` protocol. If you are wondering, RCT is a shorthand for ReaCT. <ide> <ide> ```objective-c <ide> // CalendarManager.h
1
Text
Text
add redux-analytics to ecosystem
0d9b44c7c7a5bc1be00f9ce6a18541a16eef8610
<ide><path>docs/introduction/Ecosystem.md <ide> On this page we will only feature a few of them that the Redux maintainers have <ide> * [redux-rx](https://github.com/acdlite/redux-rx) — RxJS utilities for Redux, including a middleware for Observable <ide> * [redux-logger](https://github.com/fcomb/redux-logger) — Log every Redux action and the next state <ide> * [redux-immutable-state-invariant](https://github.com/leoasis/redux-immutable-state-invariant) — Warns about state mutations in development <add>* [redux-analytics](https://github.com/markdalgleish/redux-analytics) — Analytics middleware for Redux <ide> <ide> ## Components <ide>
1
Javascript
Javascript
add tests for daysinmonth overflow behavior
dfd7bcedfbd360a6f012faf4f90d78bb6f6044cc
<ide><path>src/test/moment/days_in_month.js <ide> import { module, test } from '../qunit'; <ide> import moment from '../../moment'; <ide> import each from '../helpers/each'; <add>import { daysInMonth } from '../../lib/units/month'; <ide> <ide> module('days in month'); <ide> <ide> test('days in month leap years', function (assert) { <ide> assert.equal(moment([2008, 1]).daysInMonth(), 29, 'Feb 2008 should have 29 days'); <ide> assert.equal(moment([2000, 1]).daysInMonth(), 29, 'Feb 2000 should have 29 days'); <ide> }); <add> <add>test('days in month with NaN inputs', function (assert) { <add> assert.ok(isNaN(daysInMonth(2, NaN)), 'month NaN inputs should return NaN'); <add> assert.ok(isNaN(daysInMonth(NaN, 0)), 'year NaN inputs should return NaN'); <add> assert.ok(!moment([2010, null, null]).isValid(), 'Invalid date because month is NaN'); <add>}); <add> <add>test('days in month with overflow', function (assert) { <add> assert.equal(daysInMonth(14, 22), daysInMonth(15, 10), 'positive overflow by 1'); <add> assert.equal(daysInMonth(14, 122), daysInMonth(24, 2), 'positive overflow by 10'); <add> assert.equal(daysInMonth(8, -2), daysInMonth(7, 10), 'negative overflow by 1'); <add> assert.equal(daysInMonth(-2380, -25), daysInMonth(-2383, 11), 'negative overflow by 3'); <add>}); <add> <add>test('days in month consistent with Date()', function (assert) { <add> var oldMethod = function (year, month) { <add> return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); <add> }; <add> assert.equal(daysInMonth(14, 22), oldMethod(14, 22), 'positive overflow by 1'); <add> assert.equal(daysInMonth(14, 122), oldMethod(14, 122), 'positive overflow by 10'); <add> assert.equal(daysInMonth(8, -2), oldMethod(8, -2), 'negative overflow by 1'); <add> assert.equal(daysInMonth(-2380, -25), oldMethod(-2380, -25), 'negative overflow by 3'); <add>});
1
Python
Python
update the codes due to recent change in deeplab.
f0899f18e178afb4b57c50ec32a7e8952e6f6a99
<ide><path>research/feelvos/common.py <ide> def __new__(cls, <ide> self.classification_loss = FLAGS.classification_loss <ide> <ide> return self <add> <add> <add>def parse_decoder_output_stride(): <add> """Parses decoder output stride. <add> <add> FEELVOS assumes decoder_output_stride = 4. Thus, this function is created for <add> this particular purpose. <add> <add> Returns: <add> An integer specifying the decoder_output_stride. <add> <add> Raises: <add> ValueError: If decoder_output_stride is None or contains more than one <add> element. <add> """ <add> if FLAGS.decoder_output_stride: <add> decoder_output_stride = [ <add> int(x) for x in FLAGS.decoder_output_stride] <add> if len(decoder_output_stride) != 1: <add> raise ValueError('Expect decoder output stride has only one element.') <add> decoder_output_stride = decoder_output_stride[0] <add> else: <add> raise ValueError('Expect flag decoder output stride not to be None.') <add> return decoder_output_stride <ide><path>research/feelvos/model.py <ide> def multi_scale_logits_with_nearest_neighbor_matching( <ide> if model_options.crop_size else tf.shape(images)[2]) <ide> <ide> # Compute the height, width for the output logits. <del> logits_output_stride = ( <del> model_options.decoder_output_stride or model_options.output_stride) <del> <add> if model_options.decoder_output_stride: <add> logits_output_stride = min(model_options.decoder_output_stride) <add> else: <add> logits_output_stride = model_options.output_stride <ide> logits_height = scale_dimension( <ide> crop_height, <ide> max(1.0, max(image_pyramid)) / logits_output_stride) <ide><path>research/feelvos/train.py <ide> def _build_deeplab(inputs_queue_or_samples, outputs_to_num_classes, <ide> preceding_frame_label[n, tf.newaxis], <ide> samples[common.LABEL][n * FLAGS.train_num_frames_per_video, <ide> tf.newaxis], <del> FLAGS.decoder_output_stride, <add> common.parse_decoder_output_stride(), <ide> reduce_labels=True) <ide> init_softmax_n = tf.squeeze(init_softmax_n, axis=0) <ide> init_softmax.append(init_softmax_n) <ide> def _get_dataset_and_samples(config, train_crop_size, dataset_name, <ide> is_training=True, <ide> model_variant=FLAGS.model_variant, <ide> batch_capacity_factor=FLAGS.batch_capacity_factor, <del> decoder_output_stride=FLAGS.decoder_output_stride, <add> decoder_output_stride=common.parse_decoder_output_stride(), <ide> first_frame_finetuning=first_frame_finetuning, <ide> sample_only_first_frame_for_finetuning= <ide> FLAGS.sample_only_first_frame_for_finetuning, <ide><path>research/feelvos/utils/embedding_utils.py <ide> def get_embeddings(images, model_options, embedding_dimension): <ide> is_training=False) <ide> <ide> if model_options.decoder_output_stride is not None: <add> decoder_output_stride = min(model_options.decoder_output_stride) <ide> if model_options.crop_size is None: <ide> height = tf.shape(images)[1] <ide> width = tf.shape(images)[2] <ide> else: <ide> height, width = model_options.crop_size <del> decoder_height = model.scale_dimension( <del> height, 1.0 / model_options.decoder_output_stride) <del> decoder_width = model.scale_dimension( <del> width, 1.0 / model_options.decoder_output_stride) <ide> features = model.refine_by_decoder( <ide> features, <ide> end_points, <del> decoder_height=decoder_height, <del> decoder_width=decoder_width, <add> crop_size=[height, width], <add> decoder_output_stride=[decoder_output_stride], <ide> decoder_use_separable_conv=model_options.decoder_use_separable_conv, <ide> model_variant=model_options.model_variant, <ide> is_training=False) <ide> def get_logits_with_matching(images, <ide> is_training=is_training, <ide> fine_tune_batch_norm=fine_tune_batch_norm) <ide> <del> if model_options.decoder_output_stride is not None: <add> if model_options.decoder_output_stride: <add> decoder_output_stride = min(model_options.decoder_output_stride) <ide> if model_options.crop_size is None: <ide> height = tf.shape(images)[1] <ide> width = tf.shape(images)[2] <ide> else: <ide> height, width = model_options.crop_size <del> decoder_height = model.scale_dimension( <del> height, 1.0 / model_options.decoder_output_stride) <del> decoder_width = model.scale_dimension( <del> width, 1.0 / model_options.decoder_output_stride) <add> decoder_height = model.scale_dimension(height, 1.0 / decoder_output_stride) <add> decoder_width = model.scale_dimension(width, 1.0 / decoder_output_stride) <ide> features = model.refine_by_decoder( <ide> features, <ide> end_points, <del> decoder_height=decoder_height, <del> decoder_width=decoder_width, <add> crop_size=[height, width], <add> decoder_output_stride=[decoder_output_stride], <ide> decoder_use_separable_conv=model_options.decoder_use_separable_conv, <ide> model_variant=model_options.model_variant, <ide> weight_decay=weight_decay, <ide><path>research/feelvos/vis_video.py <ide> def predict(args, imgs): <ide> <ide> init_labels = tf.squeeze(reference_labels, axis=-1) <ide> init_softmax = embedding_utils.create_initial_softmax_from_labels( <del> reference_labels, reference_labels, FLAGS.decoder_output_stride, <add> reference_labels, reference_labels, common.parse_decoder_output_stride(), <ide> reduce_labels=False) <ide> if FLAGS.save_embeddings: <ide> decoder_height = tf.shape(init_softmax)[1] <ide> def create_predictions_fast(samples, reference_labels, first_frame_img, <ide> first_frame_img[tf.newaxis], model_options, FLAGS.embedding_dimension) <ide> init_labels = tf.squeeze(reference_labels, axis=-1) <ide> init_softmax = embedding_utils.create_initial_softmax_from_labels( <del> reference_labels, reference_labels, FLAGS.decoder_output_stride, <add> reference_labels, reference_labels, common.parse_decoder_output_stride(), <ide> reduce_labels=False) <ide> init = (init_labels, init_softmax, first_frame_embeddings) <ide>
5
Python
Python
add type hints for convbert model
41bfc1e2620b56219bab5ea4d8f4cf2769479461
<ide><path>src/transformers/models/convbert/modeling_convbert.py <ide> import math <ide> import os <ide> from operator import attrgetter <add>from typing import Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> def set_output_embeddings(self, word_embeddings): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> position_ids: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MaskedLMOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> position_ids: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, SequenceClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> position_ids: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MultipleChoiceModelOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> position_ids: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, TokenClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> start_positions=None, <del> end_positions=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> position_ids: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> start_positions: Optional[torch.LongTensor] = None, <add> end_positions: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, QuestionAnsweringModelOutput]: <ide> r""" <ide> start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss. <ide><path>src/transformers/models/convbert/modeling_tf_convbert.py <ide> """ TF 2.0 ConvBERT model.""" <ide> <ide> <add>from typing import Optional, Tuple, Union <add> <add>import numpy as np <ide> import tensorflow as tf <ide> <ide> from ...activations_tf import get_tf_activation <ide> ) <ide> from ...modeling_tf_utils import ( <ide> TFMaskedLanguageModelingLoss, <add> TFModelInputType, <ide> TFMultipleChoiceLoss, <ide> TFPreTrainedModel, <ide> TFQuestionAnsweringLoss, <ide> def get_prefix_bias_name(self): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: Optional[bool] = False, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, TFMaskedLMOutput]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: Optional[bool] = False, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, TFSequenceClassifierOutput]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def dummy_inputs(self): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: Optional[bool] = False, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, TFMultipleChoiceModelOutput]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]` <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: Optional[bool] = False, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, TFTokenClassifierOutput]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> start_positions=None, <del> end_positions=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> start_positions: Optional[tf.Tensor] = None, <add> end_positions: Optional[tf.Tensor] = None, <add> training: Optional[bool] = False, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, TFQuestionAnsweringModelOutput]: <ide> r""" <ide> start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss.
2
Go
Go
remove unneeded sleep and imagelist call
f9fedf1308cc2730edb6cf650c0655946f008b29
<ide><path>integration/build/build_test.go <ide> import ( <ide> "io/ioutil" <ide> "strings" <ide> "testing" <del> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> func TestBuildMultiStageParentConfig(t *testing.T) { <ide> resp.Body.Close() <ide> assert.NilError(t, err) <ide> <del> time.Sleep(30 * time.Second) <del> <del> imgs, err := apiclient.ImageList(ctx, types.ImageListOptions{}) <del> assert.NilError(t, err) <del> t.Log(imgs) <del> <ide> image, _, err := apiclient.ImageInspectWithRaw(ctx, "build1") <ide> assert.NilError(t, err) <ide>
1
Java
Java
fix javadoc for maybe.tosingle
ea6c7de9bbac58bec6cc286d31255febc6c74ed8
<ide><path>src/main/java/io/reactivex/Maybe.java <ide> public final Observable<T> toObservable() { <ide> <ide> /** <ide> * Converts this Maybe into a Single instance composing cancellation <del> * through and turning an empty Maybe into a signal of NoSuchElementException. <add> * through and turning an empty Maybe into a Single that emits the given <add> * value through onSuccess. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd>
1
Text
Text
add a new solution using reduce
9d30fe70279d5e82e1bd15e89771060b67b94442
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number/index.md <ide> factorialize(5); <ide> <ide> * <a href='https://www.geeksforgeeks.org/tail-recursion/' target='_blank' rel='nofollow'>Tail Recursion</a> <ide> </details> <add> <add><details><summary>Solution 4 (Click to Show/Hide)</summary> <add> <add>```js <add>function factorialize(num, factorial = 1) { <add> return num < 0 ? 1 : ( <add> new Array(num).fill(undefined) <add> .reduce((product,val, index) => product * (index + 1), 1) <add> ); <add>} <add> <add>factorialize(5); <add>``` <add> <add>#### Code Explanation <add>* In this solution, we used "reduce" function to find the factorial value of the number. This is an intermadiate example. <add> <add>* We have created an array which has length `num`. And we filled all elements of the array as `undefined`. In this case, we have to do this because empty arrays couldn't reducible. You can fill the array as your wish by the way. This depends on your engineering sight completely. <add> <add>* In `reduce` function's accumulator is calling `product` this is also our final value. We are multiplying our index value with the product to find `factorial` value. <add> <add>* We're setting product's initial value to 1 because if it was zero products gets zero always. <add> <add>* Also the factorial value can't calculate for negative numbers, first of all, we're testing this. <add></details>
1
Python
Python
fallback celery_timezone to django's time_zone
43de06a2d24746802e4a5231e8a580fa3d0f015b
<ide><path>celery/app/utils.py <ide> def BROKER_HOST(self): <ide> return (os.environ.get('CELERY_BROKER_URL') or <ide> self.first('BROKER_URL', 'BROKER_HOST')) <ide> <add> @property <add> def CELERY_TIMEZONE(self): <add> # this way we also support django's time zone. <add> return self.first('CELERY_TIMEZONE', 'TIME_ZONE') <add> <ide> def without_defaults(self): <ide> """Returns the current configuration, but without defaults.""" <ide> # the last stash is the default settings, so just skip that
1
Ruby
Ruby
add raises for invalid input
90e830c19e1b37215b19af10c7d131f4c209c10d
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info <ide> <ide> if args.json <ide> raise UsageError, "Invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <add> raise UsageError, "This command's option requires a formula argument" if ARGV.named.empty? <ide> <ide> print_json <ide> elsif args.github? <add> raise UsageError, "This command's option requires a formula argument" if ARGV.named.empty? <add> <ide> exec_browser(*Homebrew.args.formulae.map { |f| github_info(f) }) <ide> else <ide> print_info <ide><path>Library/Homebrew/cmd/postinstall.rb <ide> def postinstall_args <ide> def postinstall <ide> postinstall_args.parse <ide> <add> raise KegUnspecifiedError if args.remaining.empty? <add> <ide> ARGV.resolved_formulae.each do |f| <ide> ohai "Postinstalling #{f}" <ide> fi = FormulaInstaller.new(f) <ide><path>Library/Homebrew/cmd/reinstall.rb <ide> def reinstall_args <ide> def reinstall <ide> reinstall_args.parse <ide> <add> raise FormulaUnspecifiedError if args.remaining.empty? <add> <ide> FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed? <ide> <ide> Install.perform_preinstall_checks <ide><path>Library/Homebrew/cmd/switch.rb <ide> def switch_args <ide> <ide> Symlink all of the specified <version> of <formula>'s installation into Homebrew's prefix. <ide> EOS <del> switch_option :verbose <del> switch_option :debug <add> switch :verbose <add> switch :debug <ide> end <ide> end <ide> <ide> def switch <ide> switch_args.parse <del> name = args.remaining.first <del> <del> usage = "Usage: brew switch <formula> <version>" <ide> <del> unless name <del> onoe usage <del> exit 1 <del> end <add> raise FormulaUnspecifiedError if args.remaining.empty? <ide> <add> name = args.remaining.first <ide> rack = Formulary.to_rack(name) <ide> <del> unless rack.directory? <del> onoe "#{name} not found in the Cellar." <del> exit 2 <del> end <add> odie "#{name} not found in the Cellar." unless rack.directory? <ide> <ide> versions = rack.subdirs <ide> .map { |d| Keg.new(d).version } <ide> .sort <ide> .join(", ") <ide> version = args.remaining.second <add> raise UsageError, "Specify one of #{name}'s installed versions: #{versions}" unless version <ide> <del> if !version || args.remaining.length > 2 <del> onoe usage <del> puts "#{name} installed versions: #{versions}" <del> exit 1 <del> end <del> <del> unless (rack/version).directory? <del> onoe "#{name} does not have a version \"#{version}\" in the Cellar." <del> puts "#{name} installed versions: #{versions}" <del> exit 3 <del> end <add> odie <<~EOS unless (rack/version).directory? <add> #{name} does not have a version \"#{version}\" in the Cellar. <add> #{name}'s installed versions: #{versions} <add> EOS <ide> <ide> # Unlink all existing versions <ide> rack.subdirs.each do |v| <ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle <ide> bottle_args.parse <ide> <ide> return merge if args.merge? <add> raise KegUnspecifiedError if args.remaining.empty? <ide> <ide> ensure_relocation_formulae_installed! unless args.skip_relocation? <ide> ARGV.resolved_formulae.each do |f| <ide> def bottle_formula(f) <ide> <ide> def merge <ide> write = args.write? <add> raise UsageError, "--merge requires a JSON file path argument" if ARGV.named.empty? <ide> <ide> bottles_hash = ARGV.named.reduce({}) do |hash, json_file| <ide> hash.deep_merge(JSON.parse(IO.read(json_file)))
5
Javascript
Javascript
add delimiter to regex for trackname
bc0696718d5fc2ee4c83acd0906559a83a547983
<ide><path>src/animation/PropertyBinding.js <ide> PropertyBinding.parseTrackName = function( trackName ) { <ide> // uuid.objectName[objectIndex].propertyName[propertyIndex] <ide> // parentName/nodeName.property <ide> // parentName/parentName/nodeName.property[index] <del> // .bone[Armature.DEF_cog].position <add> // .bone[Armature.DEF_cog].position <add> // scene:helium_balloon_model:helium_balloon_model.position <ide> // created and tested via https://regex101.com/#javascript <ide> <del> var re = /^((?:\w+\/)*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/; <add> var re = /^((?:\w+[\/:])*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/; <ide> var matches = re.exec( trackName ); <ide> <ide> if ( ! matches ) {
1
Javascript
Javascript
add classid property for <object/> tag
a185f09943a2488cd4ea6dc99288da4cdd7d4cad
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> cellSpacing: null, <ide> charSet: MUST_USE_ATTRIBUTE, <ide> checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <add> classID: MUST_USE_ATTRIBUTE, <ide> // To set className on SVG elements, it's necessary to use .setAttribute; <ide> // this works on HTML elements too in all browsers except IE8. Conveniently, <ide> // IE8 doesn't support SVG and so we can simply use the attribute in <ide> var HTMLDOMPropertyConfig = { <ide> property: null // Supports OG in meta tags <ide> }, <ide> DOMAttributeNames: { <add> classID: 'classid', <ide> className: 'class', <ide> htmlFor: 'for', <ide> httpEquiv: 'http-equiv'
1
Javascript
Javascript
avoid unnecessary buffer allocations
ebedf6b653ac2a5cb49f5c9d3e6ac6fffedbf369
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(config) { <ide> }); <ide> <ide> stream.on('end', function handleStreamEnd() { <del> var responseData = Buffer.concat(responseBuffer); <add> var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); <ide> if (config.responseType !== 'arraybuffer') { <ide> responseData = responseData.toString(config.responseEncoding); <ide> if (!config.responseEncoding || config.responseEncoding === 'utf8') {
1