content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Text | Text | stop support building addons with vs 2013 | 2062a69879986985ff272e20aac8314515444bf2 | <ide><path>BUILDING.md
<ide> Depending on host platform, the selection of toolchains may vary.
<ide>
<ide> #### Windows
<ide>
<del>* Building Node: Visual Studio 2015 or Visual C++ Build Tools 2015 or newer
<del>* Building native add-ons: Visual Studio 2013 or Visual C++ Build Tools 2015
<del> or newer
<add>* Visual Studio 2015 or Visual C++ Build Tools 2015 or newer
<ide>
<ide> ## Building Node.js on supported platforms
<ide> | 1 |
Python | Python | add divmod support to ndarrayoperatorsmixin | d51b538ba80d36841cc57911d77ea61cd1d3fb25 | <ide><path>numpy/lib/mixins.py
<ide> class NDArrayOperatorsMixin(object):
<ide> implement.
<ide>
<ide> This class does not yet implement the special operators corresponding
<del> to ``divmod`` or ``matmul`` (``@``), because these operation do not yet
<del> have corresponding NumPy ufuncs.
<add> to ``matmul`` (``@``), because ``np.matmul`` is not yet a NumPy ufunc.
<ide>
<ide> It is useful for writing classes that do not inherit from `numpy.ndarray`,
<ide> but that should support arithmetic and numpy universal functions like
<ide> def __repr__(self):
<ide> um.true_divide, 'truediv')
<ide> __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
<ide> um.floor_divide, 'floordiv')
<del> __mod__, __rmod__, __imod__ = _numeric_methods(um.mod, 'mod')
<add> __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod')
<add> __divmod__ = _binary_method(um.divmod, 'divmod')
<add> __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod')
<add> # __idivmod__ does not exist
<ide> # TODO: handle the optional third argument for __pow__?
<ide> __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
<ide> __lshift__, __rlshift__, __ilshift__ = _numeric_methods(
<ide><path>numpy/lib/tests/test_mixins.py
<ide> def __repr__(self):
<ide> return '%s(%r)' % (type(self).__name__, self.value)
<ide>
<ide>
<add>def wrap_array_like(result):
<add> if type(result) is tuple:
<add> return tuple(ArrayLike(r) for r in result)
<add> else:
<add> return ArrayLike(result)
<add>
<add>
<ide> def _assert_equal_type_and_value(result, expected, err_msg=None):
<ide> assert_equal(type(result), type(expected), err_msg=err_msg)
<del> assert_equal(result.value, expected.value, err_msg=err_msg)
<del> assert_equal(getattr(result.value, 'dtype', None),
<del> getattr(expected.value, 'dtype', None), err_msg=err_msg)
<add> if isinstance(result, tuple):
<add> assert_equal(len(result), len(expected), err_msg=err_msg)
<add> for result_item, expected_item in zip(result, expected):
<add> _assert_equal_type_and_value(result_item, expected_item, err_msg)
<add> else:
<add> assert_equal(result.value, expected.value, err_msg=err_msg)
<add> assert_equal(getattr(result.value, 'dtype', None),
<add> getattr(expected.value, 'dtype', None), err_msg=err_msg)
<add>
<add>
<add>_ALL_BINARY_OPERATORS = [
<add> operator.lt,
<add> operator.le,
<add> operator.eq,
<add> operator.ne,
<add> operator.gt,
<add> operator.ge,
<add> operator.add,
<add> operator.sub,
<add> operator.mul,
<add> operator.truediv,
<add> operator.floordiv,
<add> # TODO: test div on Python 2, only
<add> operator.mod,
<add> divmod,
<add> pow,
<add> operator.lshift,
<add> operator.rshift,
<add> operator.and_,
<add> operator.xor,
<add> operator.or_,
<add>]
<ide>
<ide>
<ide> class TestNDArrayOperatorsMixin(TestCase):
<ide> def test_unary_methods(self):
<ide> operator.invert]:
<ide> _assert_equal_type_and_value(op(array_like), ArrayLike(op(array)))
<ide>
<del> def test_binary_methods(self):
<add> def test_forward_binary_methods(self):
<ide> array = np.array([-1, 0, 1, 2])
<ide> array_like = ArrayLike(array)
<del> operators = [
<del> operator.lt,
<del> operator.le,
<del> operator.eq,
<del> operator.ne,
<del> operator.gt,
<del> operator.ge,
<del> operator.add,
<del> operator.sub,
<del> operator.mul,
<del> operator.truediv,
<del> operator.floordiv,
<del> # TODO: test div on Python 2, only
<del> operator.mod,
<del> # divmod is not yet implemented
<del> pow,
<del> operator.lshift,
<del> operator.rshift,
<del> operator.and_,
<del> operator.xor,
<del> operator.or_,
<del> ]
<del> for op in operators:
<del> expected = ArrayLike(op(array, 1))
<add> for op in _ALL_BINARY_OPERATORS:
<add> expected = wrap_array_like(op(array, 1))
<ide> actual = op(array_like, 1)
<ide> err_msg = 'failed for operator {}'.format(op)
<ide> _assert_equal_type_and_value(expected, actual, err_msg=err_msg)
<ide>
<add> def test_reflected_binary_methods(self):
<add> for op in _ALL_BINARY_OPERATORS:
<add> expected = wrap_array_like(op(2, 1))
<add> actual = op(2, ArrayLike(1))
<add> err_msg = 'failed for operator {}'.format(op)
<add> _assert_equal_type_and_value(expected, actual, err_msg=err_msg)
<add>
<ide> def test_ufunc_at(self):
<ide> array = ArrayLike(np.array([1, 2, 3, 4]))
<ide> assert_(np.negative.at(array, np.array([0, 1])) is None)
<ide> _assert_equal_type_and_value(array, ArrayLike([-1, -2, 3, 4]))
<ide>
<ide> def test_ufunc_two_outputs(self):
<del> def check(result):
<del> assert_(type(result) is tuple)
<del> assert_equal(len(result), 2)
<del> mantissa, exponent = np.frexp(2 ** -3)
<del> _assert_equal_type_and_value(result[0], ArrayLike(mantissa))
<del> _assert_equal_type_and_value(result[1], ArrayLike(exponent))
<del>
<del> check(np.frexp(ArrayLike(2 ** -3)))
<del> check(np.frexp(ArrayLike(np.array(2 ** -3))))
<add> mantissa, exponent = np.frexp(2 ** -3)
<add> expected = (ArrayLike(mantissa), ArrayLike(exponent))
<add> _assert_equal_type_and_value(
<add> np.frexp(ArrayLike(2 ** -3)), expected)
<add> _assert_equal_type_and_value(
<add> np.frexp(ArrayLike(np.array(2 ** -3))), expected)
<ide>
<ide>
<ide> if __name__ == "__main__": | 2 |
PHP | PHP | fix docblock param | 0ab5a6250fc627e8a619772dba0b2372f18283bd | <ide><path>src/Collection/CollectionTrait.php
<ide> trait CollectionTrait
<ide> * Allows classes which use this trait to determine their own
<ide> * type of returned collection interface
<ide> *
<del> * @param mixed ...$args
<add> * @param mixed $args,.. Constructor arguments.
<ide> * @return CollectionInterface
<ide> */
<ide> protected function newCollection(...$args) | 1 |
Javascript | Javascript | improve error handling in route generation script | 1b5b5d9c5b365af1c8ff3b2be8b08ee2e0dd06b3 | <ide><path>Libraries/JavaScriptAppEngine/Initialization/SourceMapsUtils.js
<ide> var SourceMapsUtils = {
<ide> return Promise.reject(new Error('RCTNetworking module is not available'));
<ide> }
<ide>
<del> return RCTSourceCode.getScriptText()
<add> const scriptText = RCTSourceCode.getScriptText();
<add> if (scriptText) {
<add> scriptText
<ide> .then(SourceMapsUtils.extractSourceMapURL)
<ide> .then((url) => {
<ide> if (url === null) {
<ide> return Promise.reject(new Error('No source map URL found. May be running from bundled file.'));
<ide> }
<ide> return Promise.resolve(url);
<ide> });
<add> }
<add> else {
<add> // Running in mock-config mode
<add> return Promise.reject(new Error('Couldn\'t fetch script text'));
<add> }
<ide> },
<ide> };
<ide> | 1 |
PHP | PHP | simplify global scopes | 59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> class Builder
<ide> 'exists', 'count', 'min', 'max', 'avg', 'sum',
<ide> ];
<ide>
<add> /**
<add> * Applied global scopes.
<add> *
<add> * @var array
<add> */
<add> protected $scopes = [];
<add>
<ide> /**
<ide> * Create a new Eloquent query builder instance.
<ide> *
<ide> public function __construct(QueryBuilder $query)
<ide> $this->query = $query;
<ide> }
<ide>
<add> /**
<add> * Register a new global scope.
<add> *
<add> * @param string $identifier
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|\Closure $scope
<add> * @return $this
<add> */
<add> public function applyGlobalScope($identifier, $scope)
<add> {
<add> $this->scopes[$identifier] = $scope;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Remove a registered global scope.
<add> *
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope
<add> * @return $this
<add> */
<add> public function removeGlobalScope($scope)
<add> {
<add> if (is_string($scope)) {
<add> unset($this->scopes[$scope]);
<add>
<add> return $this;
<add> }
<add>
<add> foreach ($this->scopes as $key => $value) {
<add> if ($scope instanceof $value) {
<add> unset($this->scopes[$key]);
<add> }
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Remove all registered global scopes.
<add> *
<add> * @return $this
<add> */
<add> public function removeGlobalScopes()
<add> {
<add> $this->scopes = [];
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Find a model by its primary key.
<ide> *
<ide> public function onDelete(Closure $callback)
<ide> */
<ide> public function getModels($columns = ['*'])
<ide> {
<del> $results = $this->query->get($columns);
<add> $results = $this->getQueryWithScopes()->get($columns);
<ide>
<ide> $connection = $this->model->getConnectionName();
<ide>
<ide> protected function callScope($scope, $parameters)
<ide> return call_user_func_array([$this->model, $scope], $parameters) ?: $this;
<ide> }
<ide>
<add> /**
<add> * Get the underlying query builder instance with applied global scopes.
<add> *
<add> * @return \Illuminate\Database\Query\Builder|static
<add> */
<add> public function getQueryWithScopes()
<add> {
<add> if (! $this->scopes) {
<add> return $this->getQuery();
<add> }
<add>
<add> $builder = clone $this;
<add>
<add> foreach ($this->scopes as $scope) {
<add> if ($scope instanceof Closure) {
<add> $scope($builder);
<add> }
<add>
<add> if ($scope instanceof ScopeInterface) {
<add> $scope->apply($builder, $this->getModel());
<add> }
<add> }
<add>
<add> return $builder->getQuery();
<add> }
<add>
<ide> /**
<ide> * Get the underlying query builder instance.
<ide> *
<ide> public function __call($method, $parameters)
<ide> array_unshift($parameters, $this);
<ide>
<ide> return call_user_func_array($this->macros[$method], $parameters);
<del> } elseif (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
<add> }
<add>
<add> if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
<ide> return $this->callScope($scope, $parameters);
<ide> }
<ide>
<del> $result = call_user_func_array([$this->query, $method], $parameters);
<add> if (in_array($method, $this->passthru)) {
<add> return call_user_func_array([$this->getQueryWithScopes(), $method], $parameters);
<add> }
<add>
<add> call_user_func_array([$this->query, $method], $parameters);
<ide>
<del> return in_array($method, $this->passthru) ? $result : $this;
<add> return $this;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide>
<ide> namespace Illuminate\Database\Eloquent;
<ide>
<add>use Closure;
<ide> use DateTime;
<ide> use Exception;
<ide> use ArrayAccess;
<ide> use JsonSerializable;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<add>use InvalidArgumentException;
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> public static function clearBootedModels()
<ide> /**
<ide> * Register a new global scope on the model.
<ide> *
<del> * @param \Illuminate\Database\Eloquent\ScopeInterface $scope
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|\Closure|string $scope
<add> * @param \Closure|null $implementation
<ide> * @return void
<ide> */
<del> public static function addGlobalScope(ScopeInterface $scope)
<add> public static function addGlobalScope($scope, Closure $implementation = null)
<ide> {
<del> static::$globalScopes[get_called_class()][get_class($scope)] = $scope;
<add> if (is_string($scope) && $implementation) {
<add> return static::$globalScopes[get_called_class()][$scope] = $implementation;
<add> }
<add>
<add> if ($scope instanceof Closure) {
<add> return static::$globalScopes[get_called_class()][uniqid('scope')] = $scope;
<add> }
<add>
<add> if ($scope instanceof ScopeInterface) {
<add> return static::$globalScopes[get_called_class()][get_class($scope)] = $scope;
<add> }
<add>
<add> throw new InvalidArgumentException('Global scope must be an instance of Closure or ScopeInterface');
<ide> }
<ide>
<ide> /**
<ide> * Determine if a model has a global scope.
<ide> *
<del> * @param \Illuminate\Database\Eloquent\ScopeInterface $scope
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope
<ide> * @return bool
<ide> */
<ide> public static function hasGlobalScope($scope)
<ide> public static function hasGlobalScope($scope)
<ide> /**
<ide> * Get a global scope registered with the model.
<ide> *
<del> * @param \Illuminate\Database\Eloquent\ScopeInterface $scope
<del> * @return \Illuminate\Database\Eloquent\ScopeInterface|null
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope
<add> * @return \Illuminate\Database\Eloquent\ScopeInterface|\Closure|null
<ide> */
<ide> public static function getGlobalScope($scope)
<ide> {
<del> return Arr::first(static::$globalScopes[get_called_class()], function ($key, $value) use ($scope) {
<add> $modelScopes = static::$globalScopes[get_called_class()];
<add>
<add> if (is_string($scope)) {
<add> return isset($modelScopes[$scope]) ? $modelScopes[$scope] : null;
<add> }
<add>
<add> return Arr::first($modelScopes, function ($key, $value) use ($scope) {
<ide> return $scope instanceof $value;
<ide> });
<ide> }
<ide> public function newQuery()
<ide> /**
<ide> * Get a new query instance without a given scope.
<ide> *
<del> * @param \Illuminate\Database\Eloquent\ScopeInterface $scope
<add> * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope
<ide> * @return \Illuminate\Database\Eloquent\Builder
<ide> */
<ide> public function newQueryWithoutScope($scope)
<ide> {
<del> $this->getGlobalScope($scope)->remove($builder = $this->newQuery(), $this);
<add> $builder = $this->newQuery();
<ide>
<del> return $builder;
<add> return $builder->removeGlobalScope($scope);
<ide> }
<ide>
<ide> /**
<ide> public function newQueryWithoutScopes()
<ide> */
<ide> public function applyGlobalScopes($builder)
<ide> {
<del> foreach ($this->getGlobalScopes() as $scope) {
<del> $scope->apply($builder, $this);
<add> foreach ($this->getGlobalScopes() as $identifier => $scope) {
<add> $builder->applyGlobalScope($identifier, $scope);
<ide> }
<ide>
<ide> return $builder;
<ide> public function applyGlobalScopes($builder)
<ide> */
<ide> public function removeGlobalScopes($builder)
<ide> {
<del> foreach ($this->getGlobalScopes() as $scope) {
<del> $scope->remove($builder, $this);
<del> }
<del>
<del> return $builder;
<add> return $builder->removeGlobalScopes();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/ScopeInterface.php
<ide> interface ScopeInterface
<ide> * @return void
<ide> */
<ide> public function apply(Builder $builder, Model $model);
<del>
<del> /**
<del> * Remove the scope from the given Eloquent query builder.
<del> *
<del> * @param \Illuminate\Database\Eloquent\Builder $builder
<del> * @param \Illuminate\Database\Eloquent\Model $model
<del> *
<del> * @return void
<del> */
<del> public function remove(Builder $builder, Model $model);
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/SoftDeletingScope.php
<ide> public function apply(Builder $builder, Model $model)
<ide> $this->extend($builder);
<ide> }
<ide>
<del> /**
<del> * Remove the scope from the given Eloquent query builder.
<del> *
<del> * @param \Illuminate\Database\Eloquent\Builder $builder
<del> * @param \Illuminate\Database\Eloquent\Model $model
<del> * @return void
<del> */
<del> public function remove(Builder $builder, Model $model)
<del> {
<del> $column = $model->getQualifiedDeletedAtColumn();
<del>
<del> $query = $builder->getQuery();
<del>
<del> $query->wheres = collect($query->wheres)->reject(function ($where) use ($column) {
<del> return $this->isSoftDeleteConstraint($where, $column);
<del> })->values()->all();
<del> }
<del>
<ide> /**
<ide> * Extend the query builder with the needed functions.
<ide> *
<ide> protected function addRestore(Builder $builder)
<ide> protected function addWithTrashed(Builder $builder)
<ide> {
<ide> $builder->macro('withTrashed', function (Builder $builder) {
<del> $this->remove($builder, $builder->getModel());
<del>
<del> return $builder;
<add> return $builder->removeGlobalScope($this);
<ide> });
<ide> }
<ide>
<ide> protected function addOnlyTrashed(Builder $builder)
<ide> $builder->macro('onlyTrashed', function (Builder $builder) {
<ide> $model = $builder->getModel();
<ide>
<del> $this->remove($builder, $model);
<del>
<del> $builder->getQuery()->whereNotNull($model->getQualifiedDeletedAtColumn());
<add> $builder->removeGlobalScope($this)->getQuery()->whereNotNull($model->getQualifiedDeletedAtColumn());
<ide>
<ide> return $builder;
<ide> });
<ide> }
<del>
<del> /**
<del> * Determine if the given where clause is a soft delete constraint.
<del> *
<del> * @param array $where
<del> * @param string $column
<del> * @return bool
<del> */
<del> protected function isSoftDeleteConstraint(array $where, $column)
<del> {
<del> return $where['type'] == 'Null' && $where['column'] == $column;
<del> }
<ide> }
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testRealNestedWhereWithScopes()
<ide> $model = new EloquentBuilderTestNestedStub;
<ide> $this->mockConnectionForModel($model, 'SQLite');
<ide> $query = $model->newQuery()->where('foo', '=', 'bar')->where(function ($query) { $query->where('baz', '>', 9000); });
<del> $this->assertEquals('select * from "table" where "table"."deleted_at" is null and "foo" = ? and ("baz" > ?)', $query->toSql());
<add> $this->assertEquals('select * from "table" where "foo" = ? and ("baz" > ?) and "table"."deleted_at" is null', $query->toSql());
<ide> $this->assertEquals(['bar', 9000], $query->getBindings());
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentGlobalScopesTest.php
<add><?php
<add>
<add>use Mockery as m;
<add>
<add>class DatabaseEloquentGlobalScopesTest extends PHPUnit_Framework_TestCase
<add>{
<add> public function tearDown()
<add> {
<add> m::close();
<add> }
<add>
<add> public function testGlobalScopeIsApplied()
<add> {
<add> $model = new EloquentGlobalScopesTestModel();
<add> $query = $model->newQuery();
<add> $this->assertEquals('select * from "table" where "active" = ?', $query->toSql());
<add> $this->assertEquals([1], $query->getBindings());
<add> }
<add>
<add> public function testGlobalScopeCanBeRemoved()
<add> {
<add> $model = new EloquentGlobalScopesTestModel();
<add> $query = $model->newQuery()->removeGlobalScope(ActiveScope::class);
<add> $this->assertEquals('select * from "table"', $query->toSql());
<add> $this->assertEquals([], $query->getBindings());
<add> }
<add>
<add> public function testClosureGlobalScopeIsApplied()
<add> {
<add> $model = new EloquentClosureGlobalScopesTestModel();
<add> $query = $model->newQuery();
<add> $this->assertEquals('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
<add> $this->assertEquals([1], $query->getBindings());
<add> }
<add>
<add> public function testClosureGlobalScopeCanBeRemoved()
<add> {
<add> $model = new EloquentClosureGlobalScopesTestModel();
<add> $query = $model->newQuery()->removeGlobalScope('active_scope');
<add> $this->assertEquals('select * from "table" order by "name" asc', $query->toSql());
<add> $this->assertEquals([], $query->getBindings());
<add> }
<add>
<add> public function testGlobalScopeCanBeRemovedAfterTheQueryIsExecuted()
<add> {
<add> $model = new EloquentClosureGlobalScopesTestModel();
<add> $query = $model->newQuery();
<add> $this->assertEquals('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
<add> $this->assertEquals([1], $query->getBindings());
<add>
<add> $query->removeGlobalScope('active_scope');
<add> $this->assertEquals('select * from "table" order by "name" asc', $query->toSql());
<add> $this->assertEquals([], $query->getBindings());
<add> }
<add>
<add> public function testAllGlobalScopesCanBeRemoved()
<add> {
<add> $model = new EloquentClosureGlobalScopesTestModel();
<add> $query = $model->newQuery()->removeGlobalScopes();
<add> $this->assertEquals('select * from "table"', $query->toSql());
<add> $this->assertEquals([], $query->getBindings());
<add>
<add> $model = new EloquentClosureGlobalScopesTestModel();
<add> $query = $model->newQuery();
<add> $model->removeGlobalScopes($query);
<add> $this->assertEquals('select * from "table"', $query->toSql());
<add> $this->assertEquals([], $query->getBindings());
<add> }
<add>}
<add>
<add>class EloquentClosureGlobalScopesTestModel extends Illuminate\Database\Eloquent\Model
<add>{
<add> protected $table = 'table';
<add>
<add> public static function boot()
<add> {
<add> static::addGlobalScope('active_scope', function ($query) {
<add> $query->where('active', 1);
<add> });
<add>
<add> static::addGlobalScope(function ($query) {
<add> $query->orderBy('name');
<add> });
<add>
<add> parent::boot();
<add> }
<add>}
<add>
<add>class EloquentGlobalScopesTestModel extends Illuminate\Database\Eloquent\Model
<add>{
<add> protected $table = 'table';
<add>
<add> public static function boot()
<add> {
<add> static::addGlobalScope(new ActiveScope);
<add>
<add> parent::boot();
<add> }
<add>}
<add>
<add>class ActiveScope implements \Illuminate\Database\Eloquent\ScopeInterface
<add>{
<add> public function apply(\Illuminate\Database\Eloquent\Builder $builder, \Illuminate\Database\Eloquent\Model $model)
<add> {
<add> return $builder->where('active', 1);
<add> }
<add>}
<ide><path>tests/Database/DatabaseSoftDeletingScopeTest.php
<ide> public function testApplyingScopeToABuilder()
<ide> $scope->apply($builder, $model);
<ide> }
<ide>
<del> public function testScopeCanRemoveDeletedAtConstraints()
<del> {
<del> $scope = new Illuminate\Database\Eloquent\SoftDeletingScope;
<del> $builder = m::mock('Illuminate\Database\Eloquent\Builder');
<del> $model = m::mock('Illuminate\Database\Eloquent\Model');
<del> $builder->shouldReceive('getModel')->andReturn($model);
<del> $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at');
<del> $builder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass'));
<del> $query->wheres = [['type' => 'Null', 'column' => 'foo'], ['type' => 'Null', 'column' => 'table.deleted_at']];
<del> $scope->remove($builder, $model);
<del>
<del> $this->assertEquals($query->wheres, [['type' => 'Null', 'column' => 'foo']]);
<del> }
<del>
<ide> public function testForceDeleteExtension()
<ide> {
<ide> $builder = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> public function testWithTrashedExtension()
<ide> $callback = $builder->getMacro('withTrashed');
<ide> $givenBuilder = m::mock('Illuminate\Database\Eloquent\Builder');
<ide> $givenBuilder->shouldReceive('getModel')->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
<del> $scope->shouldReceive('remove')->once()->with($givenBuilder, $model);
<add> $givenBuilder->shouldReceive('removeGlobalScope')->with($scope)->andReturn($givenBuilder);
<ide> $result = $callback($givenBuilder);
<ide>
<ide> $this->assertEquals($givenBuilder, $result);
<ide> public function testOnlyTrashedExtension()
<ide> $scope->extend($builder);
<ide> $callback = $builder->getMacro('onlyTrashed');
<ide> $givenBuilder = m::mock('Illuminate\Database\Eloquent\Builder');
<del> $scope->shouldReceive('remove')->once()->with($givenBuilder, $model);
<ide> $givenBuilder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass'));
<ide> $givenBuilder->shouldReceive('getModel')->andReturn($model);
<add> $givenBuilder->shouldReceive('removeGlobalScope')->with($scope)->andReturn($givenBuilder);
<ide> $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at');
<ide> $query->shouldReceive('whereNotNull')->once()->with('table.deleted_at');
<ide> $result = $callback($givenBuilder); | 7 |
Python | Python | remove obsolete conversion to set | 7ec2e1bac72afcdc68cf8256879afbc4cb14a907 | <ide><path>tools/refguide_check.py
<ide> def check_items(all_dict, names, deprecated, others, module_name, dots=True):
<ide> output += "Objects in refguide: %i\n\n" % num_ref
<ide>
<ide> only_all, only_ref, missing = compare(all_dict, others, names, module_name)
<del> dep_in_ref = set(only_ref).intersection(deprecated)
<del> only_ref = set(only_ref).difference(deprecated)
<add> dep_in_ref = only_ref.intersection(deprecated)
<add> only_ref = only_ref.difference(deprecated)
<ide>
<ide> if len(dep_in_ref) > 0:
<ide> output += "Deprecated objects in refguide::\n\n" | 1 |
Ruby | Ruby | delegate everything to the generator | 0904e8256864239f673bf91fce1cfffb9345ee61 | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def initialize(generator)
<ide> @options = generator.options
<ide> end
<ide>
<del> private
<del> %w(template copy_file directory empty_directory inside
<del> empty_directory_with_gitkeep create_file chmod shebang).each do |method|
<del> class_eval <<-RUBY, __FILE__, __LINE__ + 1
<del> def #{method}(*args, &block)
<del> @generator.send(:#{method}, *args, &block)
<del> end
<del> RUBY
<del> end
<add> private
<ide>
<del> # TODO: Remove once this is fully in place
<del> def method_missing(meth, *args, &block)
<del> STDERR.puts "Calling #{meth} with #{args.inspect} with #{block}"
<del> @generator.send(meth, *args, &block)
<del> end
<add> def method_missing(meth, *args, &block)
<add> @generator.send(meth, *args, &block)
<add> end
<ide> end
<ide>
<ide> class AppBuilder | 1 |
Text | Text | change submit button value from submit to send | ed86dfec10c26eaab621f711c41c5953fddcecca | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145f685797bd30df9784e8c.md
<ide> You should give the submit a `type` of `submit`.
<ide> assert.exists(document.querySelector('button[type="submit"]') || document.querySelector('form > input[type="submit"]'));
<ide> ```
<ide>
<del>The submit should display the text `Submit`.
<add>The submit should display the text `Send`.
<ide>
<ide> ```js
<del>assert.equal(document.querySelector('button[type="submit"]')?.textContent ?? document.querySelector('input[type="submit"]')?.value, 'Submit');
<add>assert.equal(document.querySelector('button[type="submit"]')?.textContent ?? document.querySelector('input[type="submit"]')?.value, 'Send');
<ide> ```
<ide>
<ide> # --seed--
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145f829ac6a920ebf5797d7.md
<ide> assert.exists(document.querySelector('footer > address'));
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> --fcc-editable-region--
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145f8f8bcd4370f6509078e.md
<ide> assert.equal(document.querySelector('address')?.innerText, 'freeCodeCamp\nSan Fr
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> --fcc-editable-region--
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145fb5018cb5b100cb2a88c.md
<ide> assert.equal(document.querySelector('address')?.innerHTML?.match(/freeCodeCamp/g
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> --fcc-editable-region--
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6145fc3707fc3310c277f5c8.md
<ide> assert.equal(display, 'block');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/614796cb8086be482d60e0ac.md
<ide> for (let elem of document.querySelectorAll('li > a')) {
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6147a14ef5668b5881ef2297.md
<ide> assert.equal(cursor, 'pointer');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/614878f7a412310647873015.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('header')?.top, '0px');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/61487b77d4a37707073a64e5.md
<ide> assert.isEmpty(new __helpers.CSSHelp(document).getStyle('main')?.paddingRight);
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/61487da611a65307e78d2c20.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('nav > ul')?.height, '100%
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/61487f703571b60899055cf9.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('section')?.maxWidth, '600
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/614880dc16070e093e29bc56.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('h2')?.paddingTop, '60px')
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/614883b6fa720e09fb167de9.md
<ide> assert.isAtLeast(Number(new __helpers.CSSHelp(document).getStyle('.info')?.paddi
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/614884c1f5d6f30ab3d78cde.md
<ide> assert.isAtLeast(valInPx, 13);
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/61488ecfd05e290b5712e6da.md
<ide> assert.equal(textAlign, 'left');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148d99cdc7acd0c519862cb.md
<ide> assert.equal(minWidth, '55px');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148da157cc0bd0d06df5c0a.md
<ide> document.querySelectorAll('.info label').forEach(el => {
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148dc095264000dce348bf5.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.question-block')?.textAl
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148dcaaf2e8750e6cb4501a.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('p')?.fontSize, '20px');
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148dd31d210990f0fb140f8.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.question')?.paddingBotto
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148defa9c01520fb9d178a0.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('.answers-list')?.padding,
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148dfab9b54c110577de165.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('button')?.border, '3px so
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e0bcc13efd10f7d7a6a9.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('footer')?.justifyContent,
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e161ecec9511941f8833.md
<ide> assert.isAtLeast(contrast(backgroundColour, aColour), 7);
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e28706b34912340fd042.md
<ide> assert.isAtLeast(Number(window.getComputedStyle(document.querySelector('address'
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e335c1edd512d00e4691.md
<ide> assert.equal(new __helpers.CSSHelp(document).getStyle('*')?.scrollBehavior, 'smo
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e41c728f65138addf9cc.md
<ide> assert.notExists(new __helpers.CSSHelp(document).getStyle('*'));
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-accessibility-by-building-a-quiz/6148e5aeb102e3142de026a2.md
<ide> assert.equal(document.querySelectorAll('a')?.[2]?.getAttribute('accesskey')?.len
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer>
<ide> address {
<ide> </div>
<ide> </div>
<ide> </section>
<del> <button type="submit">Submit</button>
<add> <button type="submit">Send</button>
<ide> </form>
<ide> </main>
<ide> <footer> | 28 |
PHP | PHP | use getremembertokenname() in usertrait | 8fb5c0a01f757ec3345c1e570ffafc8b04fd3e98 | <ide><path>src/Illuminate/Auth/UserTrait.php
<ide> public function getAuthPassword()
<ide> */
<ide> public function getRememberToken()
<ide> {
<del> return $this->remember_token;
<add> return $this->{$this->getRememberTokenName()};
<ide> }
<ide>
<ide> /**
<ide> public function getRememberToken()
<ide> */
<ide> public function setRememberToken($value)
<ide> {
<del> $this->remember_token = $value;
<add> $this->{$this->getRememberTokenName()} = $value;
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | add homebrew-x11 to default taps | d57fe3ededa2d438bc9134b17f4bd082fde53610 | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search
<ide> %w{Homebrew binary},
<ide> %w{Homebrew python},
<ide> %w{Homebrew php},
<add> %w{Homebrew x11},
<ide> %w{Caskroom cask},
<ide> ]
<ide> | 1 |
Javascript | Javascript | use url query param on search page | 84c46750e8a06d942f65579ec07d37975ba1392e | <ide><path>client/src/components/layouts/Default.js
<ide> class DefaultLayout extends Component {
<ide> isSignedIn,
<ide> landingPage,
<ide> navigationMenu,
<del> pathname,
<ide> removeFlashMessage,
<ide> showFooter = true
<ide> } = this.props;
<ide> class DefaultLayout extends Component {
<ide> >
<ide> <style>{fontawesome.dom.css()}</style>
<ide> </Helmet>
<del> <WithInstantSearch pathname={pathname}>
<add> <WithInstantSearch>
<ide> <Header
<ide> disableSettings={landingPage}
<ide> navigationMenu={navigationMenu}
<ide><path>client/src/components/search/WithInstantSearch.js
<ide> import React, { Component } from 'react';
<add>import { Location } from '@reach/router';
<ide> import PropTypes from 'prop-types';
<ide> import { connect } from 'react-redux';
<ide> import { InstantSearch, Configure } from 'react-instantsearch-dom';
<add>import qs from 'query-string';
<ide>
<ide> import {
<ide> isSearchDropdownEnabledSelector,
<ide> import { createSelector } from 'reselect';
<ide> const propTypes = {
<ide> children: PropTypes.any,
<ide> isDropdownEnabled: PropTypes.bool,
<del> pathname: PropTypes.string.isRequired,
<add> location: PropTypes.object.isRequired,
<ide> query: PropTypes.string,
<ide> toggleSearchDropdown: PropTypes.func.isRequired,
<ide> updateSearchQuery: PropTypes.func.isRequired
<ide> const mapDispatchToProps = {
<ide> updateSearchQuery
<ide> };
<ide>
<del>class WithInstantSearch extends Component {
<add>const searchStateToUrl = ({ pathname }, query) =>
<add> `${pathname}${query ? `?${qs.stringify({ query })}` : ''}`;
<add>
<add>const urlToSearchState = ({ search }) => qs.parse(search.slice(1));
<add>
<add>class InstantSearchRoot extends Component {
<ide> componentDidMount() {
<ide> const { toggleSearchDropdown } = this.props;
<del> toggleSearchDropdown(this.getSearchEnableDropdown());
<add> toggleSearchDropdown(!this.isSearchPage());
<add> this.setQueryFromURL();
<ide> }
<ide>
<ide> componentDidUpdate(prevProps) {
<del> const { pathname, toggleSearchDropdown, isDropdownEnabled } = this.props;
<del> const { pathname: prevPathname } = prevProps;
<del> const enableDropdown = this.getSearchEnableDropdown();
<del> if (pathname !== prevPathname || isDropdownEnabled !== enableDropdown) {
<add> const { location, toggleSearchDropdown, isDropdownEnabled } = this.props;
<add>
<add> const enableDropdown = !this.isSearchPage();
<add> if (isDropdownEnabled !== enableDropdown) {
<ide> toggleSearchDropdown(enableDropdown);
<ide> }
<del> const { query, updateSearchQuery } = this.props;
<del> if (query && pathname !== prevPathname && enableDropdown) {
<del> updateSearchQuery('');
<add>
<add> if (location !== prevProps.location) {
<add> const { query, updateSearchQuery } = this.props;
<add> if (this.isSearchPage()) {
<add> this.setQueryFromURL();
<add> } else if (query) {
<add> updateSearchQuery('');
<add> }
<ide> }
<ide> }
<ide>
<del> getSearchEnableDropdown = () => !this.props.pathname.startsWith('/search');
<add> isSearchPage = () => this.props.location.pathname.startsWith('/search');
<add>
<add> setQueryFromURL = () => {
<add> if (this.isSearchPage()) {
<add> const { updateSearchQuery, location, query } = this.props;
<add> const { query: queryFromURL } = urlToSearchState(location);
<add> if (query !== queryFromURL) {
<add> updateSearchQuery(queryFromURL);
<add> }
<add> }
<add> };
<ide>
<ide> onSearchStateChange = ({ query }) => {
<ide> const { updateSearchQuery, query: propsQuery } = this.props;
<ide> if (propsQuery === query || typeof query === 'undefined') {
<del> return null;
<add> return;
<add> }
<add> updateSearchQuery(query);
<add> this.updateBrowserHistory(query);
<add> };
<add>
<add> updateBrowserHistory = query => {
<add> if (this.isSearchPage()) {
<add> clearTimeout(this.debouncedSetState);
<add>
<add> this.debouncedSetState = setTimeout(() => {
<add> if (this.isSearchPage()) {
<add> window.history.pushState(
<add> { query },
<add> null,
<add> searchStateToUrl(this.props.location, query)
<add> );
<add> }
<add> }, 400);
<ide> }
<del> return updateSearchQuery(query);
<ide> };
<ide>
<ide> render() {
<ide> class WithInstantSearch extends Component {
<ide> }
<ide> }
<ide>
<del>WithInstantSearch.displayName = 'WithInstantSearch';
<del>WithInstantSearch.propTypes = propTypes;
<add>InstantSearchRoot.displayName = 'InstantSearchRoot';
<add>InstantSearchRoot.propTypes = propTypes;
<ide>
<del>export default connect(
<add>const InstantSearchRootConnected = connect(
<ide> mapStateToProps,
<ide> mapDispatchToProps
<del>)(WithInstantSearch);
<add>)(InstantSearchRoot);
<add>
<add>const WithInstantSearch = ({ children }) => (
<add> <Location>
<add> {({ location }) => (
<add> <InstantSearchRootConnected location={location}>
<add> {children}
<add> </InstantSearchRootConnected>
<add> )}
<add> </Location>
<add>);
<add>
<add>WithInstantSearch.displayName = 'WithInstantSearch';
<add>WithInstantSearch.propTypes = { children: PropTypes.any };
<add>
<add>export default WithInstantSearch;
<ide><path>client/src/components/search/searchBar/SearchBar.js
<ide> class SearchBar extends Component {
<ide> if (query) {
<ide> updateSearchQuery(query);
<ide> }
<del> return navigate('/search');
<add> return navigate(`/search${query ? `?query=${query}` : ''}`);
<ide> }
<ide>
<ide> render() {
<ide><path>client/src/pages/search.js
<ide> import React, { Fragment, Component } from 'react';
<ide> import PropTypes from 'prop-types';
<add>import Helmet from 'react-helmet';
<ide> import { connect } from 'react-redux';
<ide> import { Index, PoweredBy } from 'react-instantsearch-dom';
<ide> import { Grid, Row, Col } from '@freecodecamp/react-bootstrap';
<ide> class SearchPage extends Component {
<ide> render() {
<ide> return (
<ide> <Fragment>
<add> <Helmet title='Search | freeCodeCamp.org' />
<ide> <Index indexName='challenges' />
<ide> <Index indexName='guides' />
<ide> <Index indexName='youtube' /> | 4 |
Python | Python | allow model conversion in the pipeline allocator | 1ca52567a4059e7ee1707de6a855bb5e7fb3fac3 | <ide><path>transformers/pipelines.py
<ide> def pipeline(task: str, model, config: Optional[PretrainedConfig] = None, tokeni
<ide> targeted_task = SUPPORTED_TASKS[task]
<ide> task, allocator = targeted_task['impl'], targeted_task['tf'] if is_tf_available() else targeted_task['pt']
<ide>
<del> model = allocator.from_pretrained(model)
<add> # Special handling for model conversion
<add> from_tf = model.endswith('.h5') and not is_tf_available()
<add> from_pt = model.endswith('.bin') and not is_torch_available()
<add>
<add> if from_tf:
<add> logger.warning('Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. Trying to load the model with PyTorch.')
<add> elif from_pt:
<add> logger.warning('Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. Trying to load the model with Tensorflow.')
<add>
<add> if allocator.__name__.startswith('TF'):
<add> model = allocator.from_pretrained(model, config=config, from_pt=from_pt)
<add> else:
<add> model = allocator.from_pretrained(model, config=config, from_tf=from_tf)
<ide> return task(model, tokenizer, **kwargs) | 1 |
Ruby | Ruby | remove redundant code | 5cc789930f323d2c1a5aa3506d64ab50123f862c | <ide><path>actionpack/test/controller/render_test.rb
<ide> def test_last_modified_works_with_less_than_too
<ide> class EtagRenderTest < ActionController::TestCase
<ide> tests TestControllerWithExtraEtags
<ide>
<del> def setup
<del> super
<del> end
<del>
<ide> def test_multiple_etags
<ide> @request.if_none_match = etag(["123", 'ab', :cde, [:f]])
<ide> get :fresh | 1 |
Python | Python | add --abort-on-timeout option to test.py | 3b488eccc14dc966949b103b1469221eed40719e | <ide><path>tools/test.py
<ide> def HasFailed(self):
<ide> return execution_failed
<ide>
<ide>
<del>def KillProcessWithID(pid):
<add>def KillProcessWithID(pid, signal_to_send=signal.SIGTERM):
<ide> if utils.IsWindows():
<ide> os.popen('taskkill /T /F /PID %d' % pid)
<ide> else:
<del> os.kill(pid, signal.SIGTERM)
<add> os.kill(pid, signal_to_send)
<ide>
<ide>
<ide> MAX_SLEEP_TIME = 0.1
<ide> def Win32SetErrorMode(mode):
<ide> pass
<ide> return prev_error_mode
<ide>
<add>
<add>def KillTimedOutProcess(context, pid):
<add> signal_to_send = signal.SIGTERM
<add> if context.abort_on_timeout:
<add> # Using SIGABRT here allows the OS to generate a core dump that can be
<add> # looked at post-mortem, which helps for investigating failures that are
<add> # difficult to reproduce.
<add> signal_to_send = signal.SIGABRT
<add> KillProcessWithID(pid, signal_to_send)
<add>
<add>
<ide> def RunProcess(context, timeout, args, **rest):
<ide> if context.verbose: print "#", " ".join(args)
<ide> popen_args = args
<ide> def RunProcess(context, timeout, args, **rest):
<ide> while True:
<ide> if time.time() >= end_time:
<ide> # Kill the process and wait for it to exit.
<del> KillProcessWithID(process.pid)
<add> KillTimedOutProcess(context, process.pid)
<ide> exit_code = process.wait()
<ide> timed_out = True
<ide> break
<ide> def RunProcess(context, timeout, args, **rest):
<ide> while exit_code is None:
<ide> if (not end_time is None) and (time.time() >= end_time):
<ide> # Kill the process and wait for it to exit.
<del> KillProcessWithID(process.pid)
<add> KillTimedOutProcess(context, process.pid)
<ide> exit_code = process.wait()
<ide> timed_out = True
<ide> else:
<ide> class Context(object):
<ide>
<ide> def __init__(self, workspace, buildspace, verbose, vm, args, expect_fail,
<ide> timeout, processor, suppress_dialogs,
<del> store_unexpected_output, repeat):
<add> store_unexpected_output, repeat, abort_on_timeout):
<ide> self.workspace = workspace
<ide> self.buildspace = buildspace
<ide> self.verbose = verbose
<ide> def __init__(self, workspace, buildspace, verbose, vm, args, expect_fail,
<ide> self.suppress_dialogs = suppress_dialogs
<ide> self.store_unexpected_output = store_unexpected_output
<ide> self.repeat = repeat
<add> self.abort_on_timeout = abort_on_timeout
<ide>
<ide> def GetVm(self, arch, mode):
<ide> if arch == 'none':
<ide> def BuildOptions():
<ide> result.add_option('--repeat',
<ide> help='Number of times to repeat given tests',
<ide> default=1, type="int")
<add> result.add_option('--abort-on-timeout',
<add> help='Send SIGABRT instead of SIGTERM to kill processes that time out',
<add> default=False, dest="abort_on_timeout")
<ide> return result
<ide>
<ide>
<ide> def Main():
<ide> processor,
<ide> options.suppress_dialogs,
<ide> options.store_unexpected_output,
<del> options.repeat)
<add> options.repeat,
<add> options.abort_on_timeout)
<ide>
<ide> # Get status for tests
<ide> sections = [ ] | 1 |
Javascript | Javascript | fix broken stringifyprimitive | c9aec2b7167a08dc88141fbe3be1c498f8c5b061 | <ide><path>lib/querystring.js
<ide> QueryString.escape = function(str) {
<ide> };
<ide>
<ide> var stringifyPrimitive = function(v) {
<del> if (typeof v === 'string' || (typeof v === 'number' && isFinite(v)))
<add> if (typeof v === 'string')
<ide> return v;
<add> if (typeof v === 'number' && isFinite(v))
<add> return '' + v;
<ide> if (typeof v === 'boolean')
<ide> return v ? 'true' : 'false';
<ide> return ''; | 1 |
Go | Go | make term function consistent with each other | 672d3a6c6cd0494a0b8eaa13674c3cb87cba029c | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide> return readStringOnRawTerminal(stdin, stdout, false)
<ide> }
<ide>
<del> oldState, err := term.SetRawTerminal()
<add> oldState, err := term.SetRawTerminal(os.Stdin.Fd())
<ide> if err != nil {
<ide> return err
<ide> }
<del> defer term.RestoreTerminal(oldState)
<add> defer term.RestoreTerminal(os.Stdin.Fd(), oldState)
<ide>
<ide> cmd := Subcmd("login", "", "Register or Login to the docker registry server")
<ide> if err := cmd.Parse(args); err != nil {
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide> password = cli.authConfig.Password
<ide> email = cli.authConfig.Email
<ide> }
<del> term.RestoreTerminal(oldState)
<add> term.RestoreTerminal(os.Stdin.Fd(), oldState)
<ide>
<ide> cli.authConfig.Username = username
<ide> cli.authConfig.Password = password
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> }
<ide>
<ide> //start the container
<del> _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", nil)
<del> if err != nil {
<add> if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", nil); err != nil {
<ide> return err
<ide> }
<ide>
<ide> if !config.AttachStdout && !config.AttachStderr {
<del> fmt.Fprintf(cli.out, "%s\b", runResult.ID)
<add> fmt.Fprintf(cli.out, "%s\n", runResult.ID)
<ide> }
<ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr {
<ide> if config.Tty {
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in *os.Fi
<ide> })
<ide>
<ide> if in != nil && setRawTerminal && term.IsTerminal(in.Fd()) && os.Getenv("NORAW") == "" {
<del> oldState, err := term.SetRawTerminal()
<add> oldState, err := term.SetRawTerminal(os.Stdin.Fd())
<ide> if err != nil {
<ide> return err
<ide> }
<del> defer term.RestoreTerminal(oldState)
<add> defer term.RestoreTerminal(os.Stdin.Fd(), oldState)
<ide> }
<ide> sendStdin := utils.Go(func() error {
<ide> io.Copy(rwc, in)
<ide><path>term/term.go
<ide> func IsTerminal(fd uintptr) bool {
<ide>
<ide> // Restore restores the terminal connected to the given file descriptor to a
<ide> // previous state.
<del>func Restore(fd uintptr, state *State) error {
<add>func RestoreTerminal(fd uintptr, state *State) error {
<ide> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&state.termios)))
<ide> return err
<ide> }
<ide>
<del>func SetRawTerminal() (*State, error) {
<del> oldState, err := MakeRaw(os.Stdin.Fd())
<add>func SetRawTerminal(fd uintptr) (*State, error) {
<add> oldState, err := MakeRaw(fd)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> c := make(chan os.Signal, 1)
<ide> signal.Notify(c, os.Interrupt)
<ide> go func() {
<ide> _ = <-c
<del> Restore(os.Stdin.Fd(), oldState)
<add> RestoreTerminal(fd, oldState)
<ide> os.Exit(0)
<ide> }()
<ide> return oldState, err
<ide> }
<del>
<del>func RestoreTerminal(state *State) {
<del> Restore(os.Stdin.Fd(), state)
<del>} | 2 |
Javascript | Javascript | add triagemustache as a known helper | df91fd23b505b2eda250e0d91697aef31c8faaa4 | <ide><path>packages/ember-handlebars/lib/ext.js
<ide> Ember.Handlebars.precompile = function(string) {
<ide> unbound: true,
<ide> bindAttr: true,
<ide> template: true,
<del> view: true
<add> view: true,
<add> _triageMustache: true
<ide> },
<ide> data: true,
<ide> stringParams: true | 1 |
Javascript | Javascript | pass context to the constructor | 9abd1133c94288c09512f7cf0b8a0b8136df6da7 | <ide><path>src/classic/class/ReactClass.js
<ide> var ReactClass = {
<ide> * @public
<ide> */
<ide> createClass: function(spec) {
<del> var Constructor = function(props) {
<add> var Constructor = function(props, context) {
<ide> // This constructor is overridden by mocks. The argument is used
<ide> // by mocks to assert on what gets mounted.
<ide>
<ide> var ReactClass = {
<ide> }
<ide>
<ide> this.props = props;
<add> this.context = context;
<ide> this.state = null;
<ide>
<ide> // ReactClasses doesn't have constructors. Instead, they use the
<ide><path>src/classic/class/__tests__/ReactClass-test.js
<ide> describe('ReactClass-spec', function() {
<ide> expect(instance.state.occupation).toEqual('clown');
<ide> });
<ide>
<add> it('renders based on context getInitialState', function() {
<add> var Foo = React.createClass({
<add> contextTypes: {
<add> className: React.PropTypes.string
<add> },
<add> getInitialState() {
<add> return { className: this.context.className };
<add> },
<add> render() {
<add> return <span className={this.state.className} />;
<add> }
<add> });
<add>
<add> var Outer = React.createClass({
<add> childContextTypes: {
<add> className: React.PropTypes.string
<add> },
<add> getChildContext() {
<add> return { className: 'foo' };
<add> },
<add> render() {
<add> return <Foo />;
<add> }
<add> });
<add>
<add> var container = document.createElement('div');
<add> React.render(<Outer />, container);
<add> expect(container.firstChild.className).toBe('foo');
<add> });
<add>
<ide> it('should throw with non-object getInitialState() return values', function() {
<ide> [['an array'], 'a string', 1234].forEach(function(state) {
<ide> var Component = React.createClass({
<ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = assign({},
<ide> );
<ide>
<ide> // Initialize the public class
<del> var inst = new Component(publicProps);
<add> var inst = new Component(publicProps, publicContext);
<ide> // These should be set up in the constructor, but as a convenience for
<ide> // simpler class abstractions, we set them up after the fact.
<ide> inst.props = publicProps;
<ide><path>src/modern/class/ReactComponentBase.js
<ide> var warning = require('warning');
<ide> /**
<ide> * Base class helpers for the updating state of a component.
<ide> */
<del>function ReactComponentBase(props) {
<add>function ReactComponentBase(props, context) {
<ide> this.props = props;
<add> this.context = context;
<ide> }
<ide>
<ide> /**
<ide><path>src/modern/class/__tests__/ReactES6Class-test.js
<ide> describe('ReactES6Class', function() {
<ide> test(<Foo />, 'SPAN', 'bar');
<ide> });
<ide>
<add> it('renders based on context in the constructor', function() {
<add> class Foo extends React.Component {
<add> constructor(props, context) {
<add> super(props, context);
<add> this.state = { tag: context.tag, className: this.context.className };
<add> }
<add> render() {
<add> var Tag = this.state.tag;
<add> return <Tag className={this.state.className} />;
<add> }
<add> }
<add> Foo.contextTypes = {
<add> tag: React.PropTypes.string,
<add> className: React.PropTypes.string
<add> };
<add>
<add> class Outer extends React.Component {
<add> getChildContext() {
<add> return { tag: 'span', className: 'foo' };
<add> }
<add> render() {
<add> return <Foo />;
<add> }
<add> }
<add> Outer.childContextTypes = {
<add> tag: React.PropTypes.string,
<add> className: React.PropTypes.string
<add> };
<add> test(<Outer />, 'SPAN', 'foo');
<add> });
<add>
<ide> it('renders only once when setting state in componentWillMount', function() {
<ide> var renderCount = 0;
<ide> class Foo extends React.Component { | 5 |
Javascript | Javascript | remove debugger, test focus, and lint fixes | 45ab5488ae6be7659a905481efec8a716bb8736c | <ide><path>spec/tree-sitter-language-mode-spec.js
<ide> describe('TreeSitterLanguageMode', () => {
<ide> })
<ide>
<ide> describe('.getSyntaxNodeAtPosition(position, where?)', () => {
<del> fit('returns the range of the smallest matching node at position', async () => {
<add> it('returns the range of the smallest matching node at position', async () => {
<ide> const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
<ide> id: 'javascript',
<ide> parser: 'tree-sitter-javascript'
<ide><path>src/selectors.js
<ide> const {isSubset} = require('underscore-plus')
<ide>
<ide> // Private: Parse a selector into parts.
<ide> // If already parsed, returns the selector unmodified.
<del>//
<add>//
<ide> // * `selector` a {String|Array<String>} specifying what to match
<ide> // Returns selector parts, an {Array<String>}.
<ide> function parse (selector) {
<ide><path>src/tree-sitter-language-mode.js
<ide> class TreeSitterLanguageMode {
<ide>
<ide> let smallestNode
<ide> this._forEachTreeWithRange(range, tree => {
<del> if (typeof selector === 'function') debugger
<ide> let node = tree.rootNode.descendantForIndex(startIndex, searchEndIndex)
<ide> while (node) {
<ide> if (nodeContainsIndices(node, startIndex, endIndex) && where(node)) {
<ide> if (nodeIsSmaller(node, smallestNode)) smallestNode = node
<ide> break
<ide> }
<del> node = node.parent
<add> node = node.parent
<ide> }
<ide> })
<ide> | 3 |
Text | Text | consertei a palavra "definição" | 053bdc334476afada9dc8ce154b839b037f23d20 | <ide><path>guide/portuguese/robotics/index.md
<ide> localeTitle: Robótica
<ide> ---
<ide> ## Robótica
<ide>
<del>Robótica é sobre os sistemas que compõem os robôs. Não há deificação universal de um robô. Uma definição geralmente aceita é: _Um robô é uma máquina física programável que segue o paradigma do sentido, pensamento e ação_ . Mais especificamente, um robô precisa sentir seu ambiente, usar essa informação como uma entrada para tomar decisões e agir de acordo. Cada sistema neste paradigma é frequentemente um estudo em si. Há uma infinidade de variedades de tipos de robôs e sistemas de componentes. Cada robô geralmente é dedicado a um conjunto de processos com objetivos claros.
<add>Robótica é sobre os sistemas que compõem os robôs. Não há definicação universal de um robô. Uma definição geralmente aceita é: _Um robô é uma máquina física programável que segue o paradigma do sentido, pensamento e ação_ . Mais especificamente, um robô precisa sentir seu ambiente, usar essa informação como uma entrada para tomar decisões e agir de acordo. Cada sistema neste paradigma é frequentemente um estudo em si. Há uma infinidade de variedades de tipos de robôs e sistemas de componentes. Cada robô geralmente é dedicado a um conjunto de processos com objetivos claros.
<ide>
<ide> ### Sentido
<ide>
<ide> Juntando, esses recursos são bons o suficiente para iniciar sua jornada com a R
<ide>
<ide> [Sensores (electronicshub.org)](https://www.electronicshub.org/different-types-sensors/)
<ide>
<del>[Atuador (Wikipedia.org)](https://en.wikipedia.org/wiki/Actuator)
<ide>\ No newline at end of file
<add>[Atuador (Wikipedia.org)](https://en.wikipedia.org/wiki/Actuator) | 1 |
Javascript | Javascript | use const for non reassignable identifier | 3b3449c2e802997543c1b3e49766086607e9e323 | <ide><path>lib/RuleSet.js
<ide> module.exports = class RuleSet {
<ide> if(typeof rule !== "object")
<ide> throw new Error("Unexcepted " + typeof rule + " when object was expected as rule (" + rule + ")");
<ide>
<del> let newRule = {};
<add> const newRule = {};
<ide> let useSource;
<ide> let resourceSource;
<ide> let condition;
<ide> module.exports = class RuleSet {
<ide> return RuleSet.normalizeUseItemString(item);
<ide> }
<ide>
<del> let newItem = {};
<add> const newItem = {};
<ide>
<ide> if(item.options && item.query)
<ide> throw new Error("Provided options and query in use");
<ide> module.exports = class RuleSet {
<ide> if(typeof condition !== "object")
<ide> throw Error("Unexcepted " + typeof condition + " when condition was expected (" + condition + ")");
<ide>
<del> let matchers = [];
<add> const matchers = [];
<ide> Object.keys(condition).forEach(key => {
<ide> const value = condition[key];
<ide> switch(key) { | 1 |
Javascript | Javascript | move setting of controller data to single location | 83a6b150201a5dc9ff13d0bc4164ea093c348718 | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> }
<ide> }
<ide>
<del> // Initialize bindToController bindings
<add> // Initialize controllers
<ide> for (var name in elementControllers) {
<ide> var controllerDirective = controllerDirectives[name];
<ide> var controller = elementControllers[name];
<ide> var bindings = controllerDirective.$$bindings.bindToController;
<ide>
<add> // Initialize bindToController bindings
<ide> if (controller.identifier && bindings) {
<ide> controller.bindingInfo =
<ide> initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> // If the controller constructor has a return value, overwrite the instance
<ide> // from setupControllers
<ide> controller.instance = controllerResult;
<del> $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
<ide> controller.bindingInfo.removeWatches && controller.bindingInfo.removeWatches();
<ide> controller.bindingInfo =
<ide> initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
<ide> }
<add>
<add> // Store controllers on the $element data
<add> // For transclude comment nodes this will be a noop and will be done at transclusion time
<add> $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
<ide> }
<ide>
<ide> // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> controller = attrs[directive.name];
<ide> }
<ide>
<del> var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
<del>
<del> // For directives with element transclusion the element is a comment.
<del> // In this case .data will not attach any data.
<del> // Instead, we save the controllers for the element in a local hash and attach to .data
<del> // later, once we have the actual element.
<del> elementControllers[directive.name] = controllerInstance;
<del> $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
<add> elementControllers[directive.name] = $controller(controller, locals, true, directive.controllerAs);
<ide> }
<ide> return elementControllers;
<ide> } | 1 |
Python | Python | support dataset for model.fit + psstrategy | aaa022c622f583482e7502725272de201495fe52 | <ide><path>keras/distribute/dataset_creator_model_fit_ps_only_test.py
<ide> # ==============================================================================
<ide> """Tests for `DatasetCreator` with `Model.fit` across usages and strategies."""
<ide>
<del>import tensorflow.compat.v2 as tf
<ide> from keras import callbacks as callbacks_lib
<ide> from keras.distribute import dataset_creator_model_fit_test_base as test_base
<ide> from keras.distribute import strategy_combinations
<add>import tensorflow.compat.v2 as tf
<ide>
<ide>
<ide> @tf.__internal__.distribute.combinations.generate(
<ide> tf.__internal__.test.combinations.combine(
<ide> strategy=strategy_combinations.parameter_server_strategies_multi_worker,
<add> use_dataset_creator=[True, False],
<ide> mode="eager"))
<ide> class DatasetCreatorModelFitParameterServerStrategyOnlyTest(
<ide> test_base.DatasetCreatorModelFitTestBase):
<ide>
<del> def testModelFitWithRunEagerly(self, strategy):
<add> def testModelFitWithRunEagerly(self, strategy, use_dataset_creator):
<ide> with self.assertRaisesRegex(
<ide> ValueError, "When using `Model` with `ParameterServerStrategy`, "
<ide> "`run_eagerly` is not supported."):
<del> self._model_fit(strategy, run_eagerly=True)
<del>
<del> def testModelFitWithDatasetInstance(self, strategy):
<del> with self.assertRaisesRegex(
<del> NotImplementedError,
<del> "Only `tf.keras.utils.experimental.DatasetCreator`, `tf.Tensor`, "
<del> "numpy arrays and pandas dataframes are supported types at this "
<del> "time."):
<ide> self._model_fit(
<del> strategy, x=tf.data.Dataset.from_tensor_slices([1, 1]))
<add> strategy, run_eagerly=True, use_dataset_creator=use_dataset_creator)
<ide>
<del> def testModelPredict(self, strategy):
<add> def testModelPredict(self, strategy, use_dataset_creator):
<add> if use_dataset_creator:
<add> self.skipTest("Unused option.")
<ide> model, _ = self._model_compile(strategy)
<ide> test_data = tf.data.Dataset.from_tensor_slices(
<ide> [1., 2., 3., 1., 5., 1.]).repeat().batch(2)
<ide> model.predict(x=test_data, steps=3)
<ide>
<del> def testClusterCoordinatorSingleInstance(self, strategy):
<del> model = self._model_fit(strategy)
<add> def testClusterCoordinatorSingleInstance(self, strategy, use_dataset_creator):
<add> model = self._model_fit(strategy, use_dataset_creator=use_dataset_creator)
<ide> strategy = model.distribute_strategy
<del> self.assertIs(strategy._cluster_coordinator,
<del> tf.distribute.experimental.coordinator.ClusterCoordinator(strategy))
<add> self.assertIs(
<add> strategy._cluster_coordinator,
<add> tf.distribute.experimental.coordinator.ClusterCoordinator(strategy))
<ide>
<del> def testModelFitErrorOnBatchLevelCallbacks(self, strategy):
<add> def testModelFitErrorOnBatchLevelCallbacks(self, strategy,
<add> use_dataset_creator):
<ide>
<ide> class BatchLevelCallback(callbacks_lib.Callback):
<ide>
<ide> def on_train_batch_end(self, batch, logs=None):
<ide> with self.assertRaisesRegex(ValueError,
<ide> "Batch-level `Callback`s are not supported"):
<ide> callbacks = [BatchLevelCallback()]
<del> self._model_fit(strategy, callbacks=callbacks)
<add> self._model_fit(
<add> strategy,
<add> callbacks=callbacks,
<add> use_dataset_creator=use_dataset_creator)
<ide>
<del> def testModelFitCallbackSupportsTFLogs(self, strategy):
<add> def testModelFitCallbackSupportsTFLogs(self, strategy, use_dataset_creator):
<ide>
<ide> class MyCallback(callbacks_lib.Callback):
<ide>
<ide> def on_train_batch_end(self, batch, logs=None):
<ide>
<ide> my_callback = MyCallback()
<ide> callbacks = [my_callback]
<del> self._model_fit(strategy, callbacks=callbacks)
<add> self._model_fit(
<add> strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator)
<ide>
<del> def testModelFitVerbosity(self, strategy):
<add> def testModelFitVerbosity(self, strategy, use_dataset_creator):
<ide>
<ide> class MyCallback(callbacks_lib.Callback):
<ide> pass
<ide>
<ide> my_callback = MyCallback()
<ide> callbacks = [my_callback]
<del> self._model_fit(strategy, callbacks=callbacks)
<add> self._model_fit(
<add> strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator)
<ide> # PSStrategy should default to epoch-level logging.
<ide> self.assertEqual(my_callback.params["verbose"], 2)
<ide>
<del> def testModelFitTensorBoardEpochLevel(self, strategy):
<add> def testModelFitTensorBoardEpochLevel(self, strategy, use_dataset_creator):
<ide> log_dir = self.get_temp_dir()
<ide> callbacks = [callbacks_lib.TensorBoard(log_dir)]
<del> self._model_fit(strategy, callbacks=callbacks)
<add> self._model_fit(
<add> strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator)
<ide> self.assertTrue(tf.compat.v1.gfile.Exists(log_dir))
<ide> files = tf.compat.v1.gfile.ListDirectory(log_dir)
<ide> self.assertGreaterEqual(len(files), 1)
<ide>
<del> def testModelEvaluateWithDatasetInstance(self, strategy):
<del> with self.assertRaisesRegex(
<del> NotImplementedError,
<del> "Only `tf.keras.utils.experimental.DatasetCreator`, `tf.Tensor`, "
<del> "numpy arrays and pandas dataframes are supported types at this "
<del> "time."):
<del> self._model_evaluate(
<del> strategy, x=tf.data.Dataset.from_tensor_slices([1, 1]))
<del>
<del> def testModelEvaluateErrorOnBatchLevelCallbacks(self, strategy):
<add> def testModelEvaluateErrorOnBatchLevelCallbacks(self, strategy,
<add> use_dataset_creator):
<ide>
<ide> class BatchLevelCallback(callbacks_lib.Callback):
<ide>
<ide> def on_train_batch_end(self, batch, logs=None):
<ide> with self.assertRaisesRegex(ValueError,
<ide> "Batch-level `Callback`s are not supported"):
<ide> callbacks = [BatchLevelCallback()]
<del> self._model_evaluate(strategy, callbacks=callbacks)
<add> self._model_evaluate(
<add> strategy,
<add> callbacks=callbacks,
<add> use_dataset_creator=use_dataset_creator)
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>keras/distribute/dataset_creator_model_fit_test_base.py
<ide> def _model_fit(self,
<ide> run_eagerly=False,
<ide> with_normalization_layer=False,
<ide> callbacks=None,
<del> use_lookup_layer=False):
<add> use_lookup_layer=False,
<add> use_dataset_creator=True):
<ide> if callbacks is None:
<ide> callbacks = []
<ide>
<ide> def _model_fit(self,
<ide> callbacks += default_callbacks
<ide>
<ide> if x is None:
<del> x = dataset_creator.DatasetCreator(self._get_dataset_fn(use_lookup_layer))
<add> if use_dataset_creator:
<add> x = dataset_creator.DatasetCreator(
<add> self._get_dataset_fn(use_lookup_layer))
<add> else:
<add> x = self._get_dataset_fn(use_lookup_layer)(None)
<ide>
<ide> if validation_data is None:
<del> validation_data = dataset_creator.DatasetCreator(
<del> self._get_dataset_fn(use_lookup_layer))
<add> if use_dataset_creator:
<add> validation_data = dataset_creator.DatasetCreator(
<add> self._get_dataset_fn(use_lookup_layer))
<add> else:
<add> validation_data = self._get_dataset_fn(use_lookup_layer)(None)
<ide>
<ide> model.fit(
<ide> x,
<ide> def _model_evaluate(self,
<ide> steps=10,
<ide> run_eagerly=False,
<ide> with_normalization_layer=False,
<del> callbacks=None):
<add> callbacks=None,
<add> use_dataset_creator=True):
<ide> if callbacks is None:
<ide> callbacks = []
<ide>
<ide> def dataset_fn(input_context):
<ide> (x, y)).shuffle(10).repeat().batch(8)
<ide>
<ide> if x is None:
<del> x = dataset_creator.DatasetCreator(dataset_fn)
<add> if use_dataset_creator:
<add> x = dataset_creator.DatasetCreator(dataset_fn)
<add> else:
<add> x = dataset_fn(None)
<ide>
<ide> model.evaluate(
<ide> x=x, y=y, steps=steps, callbacks=callbacks, batch_size=batch_size)
<ide><path>keras/engine/data_adapter.py
<ide> class _ClusterCoordinatorDataHandler(DataHandler):
<ide> """A `DataHandler` that is compatible with `ClusterCoordinator`."""
<ide>
<ide> def __init__(self, x, y=None, **kwargs):
<del> if not isinstance(x, dataset_creator.DatasetCreator):
<add> if (not _is_distributed_dataset(x) and
<add> not isinstance(x, (dataset_creator.DatasetCreator, tf.data.Dataset))):
<ide> x = self._convert_to_dataset_creator(x, y, **kwargs)
<ide>
<ide> super().__init__(x=x, **kwargs)
<ide> def _dataset_fn(input_context):
<ide>
<ide> def _configure_dataset_and_inferred_steps(self, strategy, x, steps_per_epoch,
<ide> class_weight, distribute):
<del> if not isinstance(x, dataset_creator.DatasetCreator):
<del> raise TypeError("When using `ParameterServerStrategy`, `x` must be a "
<del> "`DatasetCreator`.")
<add> if isinstance(x, dataset_creator.DatasetCreator):
<ide>
<del> def per_worker_dataset_fn():
<add> def per_worker_dataset_fn():
<ide>
<del> return strategy.distribute_datasets_from_function(
<del> x, options=x.input_options)
<add> return strategy.distribute_datasets_from_function(
<add> x, options=x.input_options)
<add>
<add> self._dataset = self._model._cluster_coordinator.create_per_worker_dataset( # pylint: disable=protected-access
<add> per_worker_dataset_fn)
<add> else:
<add> assert distribute
<add> if not _is_distributed_dataset(x):
<add> x = strategy.experimental_distribute_dataset(x)
<ide>
<del> self._dataset = self._model._cluster_coordinator.create_per_worker_dataset( # pylint: disable=protected-access
<del> per_worker_dataset_fn)
<add> self._dataset = self._model._cluster_coordinator.create_per_worker_dataset( # pylint: disable=protected-access
<add> x)
<ide>
<ide> if steps_per_epoch == -1:
<ide> self._inferred_steps = None | 3 |
Python | Python | add quotes to paths in mecab arguments | e29c3f1b1104694889afcce4f13f8c842d6e0d6b | <ide><path>src/transformers/tokenization_bert_japanese.py
<ide> def __init__(
<ide> raise ValueError("Invalid mecab_dic is specified.")
<ide>
<ide> mecabrc = os.path.join(dic_dir, "mecabrc")
<del> mecab_option = "-d {} -r {} ".format(dic_dir, mecabrc) + mecab_option
<add> mecab_option = '-d "{}" -r "{}" '.format(dic_dir, mecabrc) + mecab_option
<ide>
<ide> self.mecab = fugashi.GenericTagger(mecab_option)
<ide> | 1 |
PHP | PHP | remove deprecated code in validation | f09f2f38f6953412059a72d2349746587580b7d5 | <ide><path>src/Validation/Validation.php
<ide> public static function lengthBetween($check, $min, $max)
<ide> return ($length >= $min && $length <= $max);
<ide> }
<ide>
<del> /**
<del> * Returns true if field is left blank -OR- only whitespace characters are present in its value
<del> * Whitespace characters include Space, Tab, Carriage Return, Newline
<del> *
<del> * @param string $check Value to check
<del> * @return bool Success
<del> * @deprecated 3.0.2 Validation::blank() is deprecated.
<del> */
<del> public static function blank($check)
<del> {
<del> deprecationWarning(
<del> 'Validation::blank() is deprecated.'
<del> );
<del>
<del> return !static::_check($check, '/[^\\s]/');
<del> }
<del>
<ide> /**
<ide> * Validation of credit card numbers.
<ide> * Returns true if $check is in the proper credit card format.
<ide> public static function inList($check, array $list, $caseInsensitive = false)
<ide> return in_array((string)$check, $list, true);
<ide> }
<ide>
<del> /**
<del> * Runs an user-defined validation.
<del> *
<del> * @param string|array $check value that will be validated in user-defined methods.
<del> * @param object $object class that holds validation method
<del> * @param string $method class method name for validation to run
<del> * @param array|null $args arguments to send to method
<del> * @return mixed user-defined class class method returns
<del> * @deprecated 3.0.2 You can just set a callable for `rule` key when adding validators.
<del> */
<del> public static function userDefined($check, $object, $method, $args = null)
<del> {
<del> deprecationWarning(
<del> 'Validation::userDefined() is deprecated. ' .
<del> 'You can just set a callable for `rule` key when adding validators.'
<del> );
<del>
<del> return $object->$method($check, $args);
<del> }
<del>
<ide> /**
<ide> * Checks that a value is a valid UUID - https://tools.ietf.org/html/rfc4122
<ide> *
<ide><path>src/Validation/ValidationSet.php
<ide> class ValidationSet implements ArrayAccess, IteratorAggregate, Countable
<ide> protected $_allowEmpty = false;
<ide>
<ide> /**
<del> * Sets whether a field is required to be present in data array.
<del> *
<del> * If no argument is passed the currently set `validatePresent` value will be returned.
<add> * Returns whether or not a field can be left out.
<ide> *
<del> * @param bool|string|callable|null $validatePresent Deprecated since 3.6.0 ValidationSet::isPresenceRequired() is deprecated as a setter
<del> * Use ValidationSet::requirePresence() instead.
<ide> * @return bool|string|callable
<ide> */
<del> public function isPresenceRequired($validatePresent = null)
<add> public function isPresenceRequired()
<ide> {
<del> if ($validatePresent === null) {
<del> return $this->_validatePresent;
<del> }
<del>
<del> deprecationWarning(
<del> 'ValidationSet::isPresenceRequired() is deprecated as a setter. ' .
<del> 'Use ValidationSet::requirePresence() instead.'
<del> );
<del>
<del> return $this->requirePresence($validatePresent);
<add> return $this->_validatePresent;
<ide> }
<ide>
<ide> /**
<ide> public function requirePresence($validatePresent)
<ide> }
<ide>
<ide> /**
<del> * Sets whether a field value is allowed to be empty.
<del> *
<del> * If no argument is passed the currently set `allowEmpty` value will be returned.
<add> * Returns whether or not a field can be left empty.
<ide> *
<del> * @param bool|string|callable|null $allowEmpty Deprecated since 3.6.0 ValidationSet::isEmptyAllowed() is deprecated as a setter.
<del> * Use ValidationSet::allowEmpty() instead.
<ide> * @return bool|string|callable
<ide> */
<del> public function isEmptyAllowed($allowEmpty = null)
<add> public function isEmptyAllowed()
<ide> {
<del> if ($allowEmpty === null) {
<del> return $this->_allowEmpty;
<del> }
<del>
<del> deprecationWarning(
<del> 'ValidationSet::isEmptyAllowed() is deprecated as a setter. ' .
<del> 'Use ValidationSet::allowEmpty() instead.'
<del> );
<del>
<del> return $this->allowEmpty($allowEmpty);
<add> return $this->_allowEmpty;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Validation/ValidationSetTest.php
<ide> public function testRequirePresence()
<ide> $this->assertFalse($set->isPresenceRequired());
<ide> }
<ide>
<del> /**
<del> * Test isPresenceRequired deprecated setter
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testRequirePresenceDeprecated()
<del> {
<del> $this->deprecated(function () {
<del> $set = new ValidationSet();
<del>
<del> $this->assertFalse($set->isPresenceRequired());
<del>
<del> $set->isPresenceRequired(true);
<del> $this->assertTrue($set->isPresenceRequired());
<del>
<del> $set->isPresenceRequired(false);
<del> $this->assertFalse($set->isPresenceRequired());
<del> });
<del> }
<del>
<del> /**
<del> * Test isPresenceRequired method deprecation
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testIsPresenceRequiredDeprecation()
<del> {
<del> $this->expectException(Deprecated::class);
<del> $this->expectExceptionMessage('ValidationSet::isPresenceRequired() is deprecated as a setter. Use ValidationSet::requirePresence() instead.');
<del>
<del> $set = new ValidationSet();
<del> $set->isPresenceRequired(true);
<del> }
<del>
<ide> /**
<ide> * Test allowEmpty and isEmptyAllowed methods
<ide> *
<ide> public function testAllowEmpty()
<ide> $set->allowEmpty(false);
<ide> $this->assertFalse($set->isEmptyAllowed());
<ide> }
<del>
<del> /**
<del> * Test isEmptyAllowed deprecated setter
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testAllowEmptyDeprecated()
<del> {
<del> $this->deprecated(function () {
<del> $set = new ValidationSet();
<del>
<del> $this->assertFalse($set->isEmptyAllowed());
<del>
<del> $set->isEmptyAllowed(true);
<del> $this->assertTrue($set->isEmptyAllowed());
<del>
<del> $set->isEmptyAllowed(false);
<del> $this->assertFalse($set->isEmptyAllowed());
<del> });
<del> }
<del>
<del> /**
<del> * Test isEmptyAllowed method deprecation
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testIsEmptyAllowedDeprecation()
<del> {
<del> $this->expectException(Deprecated::class);
<del> $this->expectExceptionMessage('ValidationSet::isEmptyAllowed() is deprecated as a setter. Use ValidationSet::allowEmpty() instead.');
<del>
<del> $set = new ValidationSet();
<del> $set->isEmptyAllowed(true);
<del> }
<ide> } | 3 |
Text | Text | fix html to jsx converter to work with https | 89b17330acc36b0aedc13693de39de1c65da86e5 | <ide><path>docs/html-jsx.md
<ide> id: html-jsx
<ide> <div class="jsxCompiler">
<ide> <h1>HTML to JSX Compiler</h1>
<ide> <div id="jsxCompiler"></div>
<del> <script src="http://reactjs.github.io/react-magic/htmltojsx.min.js"></script>
<add> <script src="https://reactjs.github.io/react-magic/htmltojsx.min.js"></script>
<ide> <script src="js/html-jsx.js"></script>
<ide> </div> | 1 |
Python | Python | fix python 2 test failure | 2ac69facc6da342c38c9d851f1ec53a3be0b820a | <ide><path>spacy/tests/regression/test_issue2800.py
<ide> '''Test issue that arises when too many labels are added to NER model.'''
<add>from __future__ import unicode_literals
<add>
<ide> import random
<ide> from ...lang.en import English
<ide> | 1 |
Python | Python | change exception message | d3cd1bb35c3d92c55d6643ba3d232902c09632b5 | <ide><path>libcloud/common/openstack.py
<ide> def add_default_headers(self, headers):
<ide> service_type = "compute"
<ide> microversion = microversion[0]
<ide> else:
<del> raise LibcloudError("Invalid microversion format.")
<add> raise LibcloudError("Invalid microversion format: servicename X.XX")
<ide>
<ide> if self.service_type and self.service_type.startswith(service_type):
<ide> headers["OpenStack-API-Version"] = "%s %s" % ( | 1 |
Text | Text | remove unneeded `export` | a04b4890a9185088af9d1664ba044d91e05697c7 | <ide><path>docs/Shell-Completion.md
<ide> This must be done before `compinit` is called. Note that if you are using Oh My
<ide>
<ide> ```diff
<ide> eval $(/opt/homebrew/bin/brew shellenv)
<del>+ export FPATH=$(brew --prefix)/share/zsh/site-functions:$FPATH
<add>+ FPATH=$(brew --prefix)/share/zsh/site-functions:$FPATH
<ide> ```
<ide>
<ide> You may also need to forcibly rebuild `zcompdump`: | 1 |
Go | Go | add tracking to elided layer pulls | d5482089bfd0348ed886be9f89c4d6b177cc6dce | <ide><path>distribution/xfer/download.go
<ide> func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS ima
<ide> topLayer = l
<ide> missingLayer = false
<ide> rootFS.Append(diffID)
<add> // Register this repository as a source of this layer.
<add> withRegistered, hasRegistered := descriptor.(DownloadDescriptorWithRegistered)
<add> if hasRegistered {
<add> withRegistered.Registered(diffID)
<add> }
<ide> continue
<ide> }
<ide> } | 1 |
Go | Go | use spf13/cobra for docker version | bc82e51d7755e54dc6d0dcb93e6250bbff0bbd59 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) Command(name string) func(...string) error {
<ide> "stats": cli.CmdStats,
<ide> "tag": cli.CmdTag,
<ide> "update": cli.CmdUpdate,
<del> "version": cli.CmdVersion,
<ide> }[name]
<ide> }
<add><path>api/client/system/version.go
<del><path>api/client/version.go
<del>package client
<add>package system
<ide>
<ide> import (
<ide> "runtime"
<del> "text/template"
<ide> "time"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<del> Cli "github.com/docker/docker/cli"
<add> "github.com/docker/docker/api/client"
<add> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/dockerversion"
<del> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/docker/utils/templates"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/spf13/cobra"
<ide> )
<ide>
<ide> var versionTemplate = `Client:
<ide> Server:
<ide> OS/Arch: {{.Server.Os}}/{{.Server.Arch}}{{if .Server.Experimental}}
<ide> Experimental: {{.Server.Experimental}}{{end}}{{end}}`
<ide>
<del>// CmdVersion shows Docker version information.
<del>//
<del>// Available version information is shown for: client Docker version, client API version, client Go version, client Git commit, client OS/Arch, server Docker version, server API version, server Go version, server Git commit, and server OS/Arch.
<del>//
<del>// Usage: docker version
<del>func (cli *DockerCli) CmdVersion(args ...string) (err error) {
<del> cmd := Cli.Subcmd("version", nil, Cli.DockerCommands["version"].Description, true)
<del> tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template")
<del> cmd.Require(flag.Exact, 0)
<add>type versionOptions struct {
<add> format string
<add>}
<add>
<add>// NewVersionCommand creats a new cobra.Command for `docker version`
<add>func NewVersionCommand(dockerCli *client.DockerCli) *cobra.Command {
<add> var opts versionOptions
<add>
<add> cmd := &cobra.Command{
<add> Use: "version [OPTIONS]",
<add> Short: "Show the Docker version information",
<add> Args: cli.ExactArgs(0),
<add> RunE: func(cmd *cobra.Command, args []string) error {
<add> return runVersion(dockerCli, &opts)
<add> },
<add> }
<add>
<add> flags := cmd.Flags()
<add>
<add> flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given go template")
<add>
<add> return cmd
<add>}
<ide>
<del> cmd.ParseFlags(args, true)
<add>func runVersion(dockerCli *client.DockerCli, opts *versionOptions) error {
<add> ctx := context.Background()
<ide>
<ide> templateFormat := versionTemplate
<del> if *tmplStr != "" {
<del> templateFormat = *tmplStr
<add> if opts.format != "" {
<add> templateFormat = opts.format
<ide> }
<ide>
<del> var tmpl *template.Template
<del> if tmpl, err = templates.Parse(templateFormat); err != nil {
<del> return Cli.StatusError{StatusCode: 64,
<add> tmpl, err := templates.Parse(templateFormat)
<add> if err != nil {
<add> return cli.StatusError{StatusCode: 64,
<ide> Status: "Template parsing error: " + err.Error()}
<ide> }
<ide>
<ide> vd := types.VersionResponse{
<ide> Client: &types.Version{
<ide> Version: dockerversion.Version,
<del> APIVersion: cli.client.ClientVersion(),
<add> APIVersion: dockerCli.Client().ClientVersion(),
<ide> GoVersion: runtime.Version(),
<ide> GitCommit: dockerversion.GitCommit,
<ide> BuildTime: dockerversion.BuildTime,
<ide> func (cli *DockerCli) CmdVersion(args ...string) (err error) {
<ide> },
<ide> }
<ide>
<del> serverVersion, err := cli.client.ServerVersion(context.Background())
<add> serverVersion, err := dockerCli.Client().ServerVersion(ctx)
<ide> if err == nil {
<ide> vd.Server = &serverVersion
<ide> }
<ide> func (cli *DockerCli) CmdVersion(args ...string) (err error) {
<ide> }
<ide> }
<ide>
<del> if err2 := tmpl.Execute(cli.out, vd); err2 != nil && err == nil {
<add> if err2 := tmpl.Execute(dockerCli.Out(), vd); err2 != nil && err == nil {
<ide> err = err2
<ide> }
<del> cli.out.Write([]byte{'\n'})
<add> dockerCli.Out().Write([]byte{'\n'})
<ide> return err
<ide> }
<ide><path>cli/cobraadaptor/adaptor.go
<ide> import (
<ide> "github.com/docker/docker/api/client/container"
<ide> "github.com/docker/docker/api/client/image"
<ide> "github.com/docker/docker/api/client/network"
<add> "github.com/docker/docker/api/client/system"
<ide> "github.com/docker/docker/api/client/volume"
<ide> "github.com/docker/docker/cli"
<ide> cliflags "github.com/docker/docker/cli/flags"
<ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor {
<ide> image.NewSearchCommand(dockerCli),
<ide> image.NewImportCommand(dockerCli),
<ide> network.NewNetworkCommand(dockerCli),
<add> system.NewVersionCommand(dockerCli),
<ide> volume.NewVolumeCommand(dockerCli),
<ide> )
<ide>
<ide><path>cli/usage.go
<ide> var DockerCommandUsage = []Command{
<ide> {"stats", "Display a live stream of container(s) resource usage statistics"},
<ide> {"tag", "Tag an image into a repository"},
<ide> {"update", "Update configuration of one or more containers"},
<del> {"version", "Show the Docker version information"},
<ide> }
<ide>
<ide> // DockerCommands stores all the docker command | 4 |
Text | Text | fix eventemitter examples | 9e5a27a9d310ba64289a326777d9a86e4b9a3928 | <ide><path>doc/api/events.md
<ide> but important side effect: any *additional* listeners registered to the same
<ide> listener that is in the process of being added.
<ide>
<ide> ```js
<add>class MyEmitter extends EventEmitter {}
<add>
<ide> const myEmitter = new MyEmitter();
<ide> // Only do this once so we don't loop forever
<ide> myEmitter.once('newListener', (event, listener) => {
<ide> A class method that returns the number of listeners for the given `eventName`
<ide> registered on the given `emitter`.
<ide>
<ide> ```js
<del>const myEmitter = new MyEmitter();
<add>const myEmitter = new EventEmitter();
<ide> myEmitter.on('event', () => {});
<ide> myEmitter.on('event', () => {});
<ide> console.log(EventEmitter.listenerCount(myEmitter, 'event')); | 1 |
Python | Python | mark the typing tests as slow | 5d8d296e9b7694c1254792dac564be14d47a46a9 | <ide><path>numpy/typing/tests/test_typing.py
<ide> def get_test_cases(directory):
<ide> )
<ide>
<ide>
<add>@pytest.mark.slow
<ide> @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
<ide> @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
<ide> def test_success(path):
<ide> def test_success(path):
<ide> assert re.match(r"Success: no issues found in \d+ source files?", stdout.strip())
<ide>
<ide>
<add>@pytest.mark.slow
<ide> @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
<ide> @pytest.mark.parametrize("path", get_test_cases(FAIL_DIR))
<ide> def test_fail(path):
<ide> def test_fail(path):
<ide> pytest.fail(f"Error {repr(errors[lineno])} not found")
<ide>
<ide>
<add>@pytest.mark.slow
<ide> @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
<ide> @pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
<ide> def test_reveal(path):
<ide> def test_reveal(path):
<ide> assert marker in error_line
<ide>
<ide>
<add>@pytest.mark.slow
<ide> @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
<ide> @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
<ide> def test_code_runs(path): | 1 |
Java | Java | simplify some redundant code | c5fb7b9fb70d0a711a963b2a160c3af5cc4be3a7 | <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java
<ide> public void testAddingConstructorResolvers() {
<ide> ctx.addConstructorResolver(dummy);
<ide> assertThat(ctx.getConstructorResolvers().size()).isEqualTo(2);
<ide>
<del> List<ConstructorResolver> copy = new ArrayList<>();
<del> copy.addAll(ctx.getConstructorResolvers());
<add> List<ConstructorResolver> copy = new ArrayList<>(ctx.getConstructorResolvers());
<ide> assertThat(ctx.removeConstructorResolver(dummy)).isTrue();
<ide> assertThat(ctx.removeConstructorResolver(dummy)).isFalse();
<ide> assertThat(ctx.getConstructorResolvers().size()).isEqualTo(1);
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java
<ide> public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() th
<ide> // Use the standard evaluation context
<ide> StandardEvaluationContext ctx = new StandardEvaluationContext();
<ide> ctx.setVariable("favouriteColour","blue");
<del> List<Integer> primes = new ArrayList<>();
<del> primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
<add> List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17);
<ide> ctx.setVariable("primes",primes);
<ide>
<ide> Expression expr = parser.parseRaw("#favouriteColour");
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java
<ide> public void testAddingMethodResolvers() {
<ide> ctx.addMethodResolver(dummy);
<ide> assertThat(ctx.getMethodResolvers().size()).isEqualTo(2);
<ide>
<del> List<MethodResolver> copy = new ArrayList<>();
<del> copy.addAll(ctx.getMethodResolvers());
<add> List<MethodResolver> copy = new ArrayList<>(ctx.getMethodResolvers());
<ide> assertThat(ctx.removeMethodResolver(dummy)).isTrue();
<ide> assertThat(ctx.removeMethodResolver(dummy)).isFalse();
<ide> assertThat(ctx.getMethodResolvers().size()).isEqualTo(1);
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java
<ide> public void testAddingRemovingAccessors() {
<ide> ctx.addPropertyAccessor(spa);
<ide> assertThat(ctx.getPropertyAccessors().size()).isEqualTo(2);
<ide>
<del> List<PropertyAccessor> copy = new ArrayList<>();
<del> copy.addAll(ctx.getPropertyAccessors());
<add> List<PropertyAccessor> copy = new ArrayList<>(ctx.getPropertyAccessors());
<ide> assertThat(ctx.removePropertyAccessor(spa)).isTrue();
<ide> assertThat(ctx.removePropertyAccessor(spa)).isFalse();
<ide> assertThat(ctx.getPropertyAccessors().size()).isEqualTo(1);
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java
<ide> public void testVariables() throws Exception {
<ide> @Test
<ide> public void testSpecialVariables() throws Exception {
<ide> // create an array of integers
<del> List<Integer> primes = new ArrayList<>();
<del> primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
<add> List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17);
<ide>
<ide> // create parser and set variable 'primes' as the array of integers
<ide> ExpressionParser parser = new SpelExpressionParser();
<ide> public static String reverseString(String input) {
<ide> }
<ide>
<ide> }
<del>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java
<ide> protected List<? extends HandlerMethodArgumentResolver> initArgumentResolvers()
<ide>
<ide> @Override
<ide> protected List<? extends HandlerMethodReturnValueHandler> initReturnValueHandlers() {
<del> List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>();
<del> handlers.addAll(getCustomReturnValueHandlers());
<add> List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(getCustomReturnValueHandlers());
<ide> return handlers;
<ide> }
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/ExtendedEntityManagerCreator.java
<ide> private static EntityManager createProxy(
<ide> }
<ide> else {
<ide> interfaces = cachedEntityManagerInterfaces.computeIfAbsent(rawEm.getClass(), key -> {
<del> Set<Class<?>> ifcs = new LinkedHashSet<>();
<del> ifcs.addAll(ClassUtils
<add> Set<Class<?>> ifcs = new LinkedHashSet<>(ClassUtils
<ide> .getAllInterfacesForClassAsSet(key, cl));
<ide> ifcs.add(EntityManagerProxy.class);
<ide> return ClassUtils.toClassArray(ifcs);
<ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufDecoder.java
<ide> public Iterable<? extends Message> apply(DataBuffer input) {
<ide> this.output = input.factory().allocateBuffer(this.messageBytesToRead);
<ide> }
<ide>
<del> chunkBytesToRead = this.messageBytesToRead >= input.readableByteCount() ?
<del> input.readableByteCount() : this.messageBytesToRead;
<add> chunkBytesToRead = Math.min(this.messageBytesToRead, input.readableByteCount());
<ide> remainingBytesToRead = input.readableByteCount() - chunkBytesToRead;
<ide>
<ide> byte[] bytesToWrite = new byte[chunkBytesToRead];
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
<ide> public void methodNotAllowed() throws Exception {
<ide> assertThat(response.getStatus()).as("Invalid response status").isEqualTo(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
<ide> String allowHeader = response.getHeader("Allow");
<ide> assertThat(allowHeader).as("No Allow header").isNotNull();
<del> Set<String> allowedMethods = new HashSet<>();
<del> allowedMethods.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", ")));
<add> Set<String> allowedMethods = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", ")));
<ide> assertThat(allowedMethods.size()).as("Invalid amount of supported methods").isEqualTo(6);
<ide> assertThat(allowedMethods.contains("PUT")).as("PUT not allowed").isTrue();
<ide> assertThat(allowedMethods.contains("DELETE")).as("DELETE not allowed").isTrue(); | 9 |
Javascript | Javascript | fix debugger keyword | 5e19bfa7e3b739e8913631cfb2e075a23bc65233 | <ide><path>packages/ember-htmlbars/lib/keywords/debugger.js
<ide> import Logger from "ember-metal/logger";
<ide> @param {String} property
<ide> */
<ide> export default function debuggerKeyword(morph, env, scope) {
<add> /* jshint unused: false, debug: true */
<ide>
<del> /* jshint unused: false */
<del> var view = scope.locals.view;
<add> var view = env.hooks.getValue(scope.locals.view);
<add> var context = env.hooks.getValue(scope.self);
<ide>
<del> /* jshint unused: false */
<del> var context = scope.self;
<del>
<del> /* jshint unused: false */
<ide> function get(path) {
<del> return env.hooks.getValue(env.hooks.get(path));
<add> return env.hooks.getValue(env.hooks.get(env, scope, path));
<ide> }
<ide>
<ide> Logger.info('Use `view`, `context`, and `get(<path>)` to debug this template.'); | 1 |
Ruby | Ruby | prefer json.encode(value) to value.to_json | 5b256ac36922b4dfa4ab7aa639757c4817d06680 | <ide><path>activeresource/lib/active_resource/formats/json_format.rb
<ide> def mime_type
<ide> "application/json"
<ide> end
<ide>
<del> def encode(hash, options={})
<del> hash.to_json(options)
<add> def encode(hash, options = nil)
<add> ActiveSupport::JSON.encode(hash, options)
<ide> end
<ide>
<ide> def decode(json) | 1 |
Mixed | Javascript | fix undefined http2 and tls errors | 3950a3e0b1319c6cae49f674b7f82a491ea09093 | <ide><path>doc/api/errors.md
<ide> provided.
<ide>
<ide> The `Http2Session` closed with a non-zero error code.
<ide>
<add><a id="ERR_HTTP2_SETTINGS_CANCEL"></a>
<add>### ERR_HTTP2_SETTINGS_CANCEL
<add>
<add>The `Http2Session` settings canceled.
<add>
<ide> <a id="ERR_HTTP2_SOCKET_BOUND"></a>
<ide> ### ERR_HTTP2_SOCKET_BOUND
<ide>
<ide> recommended to use 2048 bits or larger for stronger security.
<ide> A TLS/SSL handshake timed out. In this case, the server must also abort the
<ide> connection.
<ide>
<add><a id="ERR_TLS_RENEGOTIATE"></a>
<add>### ERR_TLS_RENEGOTIATE
<add>
<add>An attempt to renegotiate the TLS session failed.
<add>
<ide> <a id="ERR_TLS_RENEGOTIATION_DISABLED"></a>
<ide> ### ERR_TLS_RENEGOTIATION_DISABLED
<ide>
<ide><path>lib/internal/errors.js
<ide> E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error);
<ide> E('ERR_HTTP2_SEND_FILE_NOSEEK',
<ide> 'Offset or length can only be specified for regular files', Error);
<ide> E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error);
<add>E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error);
<ide> E('ERR_HTTP2_SOCKET_BOUND',
<ide> 'The socket is already bound to an Http2Session', Error);
<ide> E('ERR_HTTP2_STATUS_101',
<ide> E('ERR_TLS_CERT_ALTNAME_INVALID',
<ide> 'Hostname/IP does not match certificate\'s altnames: %s', Error);
<ide> E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048', Error);
<ide> E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout', Error);
<add>E('ERR_TLS_RENEGOTIATE', 'Attempt to renegotiate TLS session failed', Error);
<ide> E('ERR_TLS_RENEGOTIATION_DISABLED',
<ide> 'TLS session renegotiation disabled for this socket', Error);
<ide> | 2 |
Ruby | Ruby | remove erroneous form_tag option docs | 0387591c0528307cc664ad75697e683f2a3d9e80 | <ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb
<ide> module FormTagHelper
<ide> # This is helpful when you're fragment-caching the form. Remote forms get the
<ide> # authenticity token from the <tt>meta</tt> tag, so embedding is unnecessary unless you
<ide> # support browsers without JavaScript.
<del> # * A list of parameters to feed to the URL the form will be posted to.
<ide> # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
<ide> # submit behavior. By default this behavior is an ajax submit.
<ide> # * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name utf8 is not output. | 1 |
Javascript | Javascript | remove module argument from asyncdepblock | f23ce490403b6cc1961ecb0c1c97f7c4ec056cee | <ide><path>lib/AsyncDependenciesBlock.js
<ide> const DependenciesBlock = require("./DependenciesBlock");
<ide> class AsyncDependenciesBlock extends DependenciesBlock {
<ide> /**
<ide> * @param {GroupOptions} groupOptions options for the group
<del> * @param {Module} module the Module object
<ide> * @param {DependencyLocation=} loc the line of code
<ide> * @param {string=} request the request
<ide> */
<del> constructor(groupOptions, module, loc, request) {
<add> constructor(groupOptions, loc, request) {
<ide> super();
<ide> if (typeof groupOptions === "string") {
<ide> groupOptions = { name: groupOptions };
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> const block = new AsyncDependenciesBlock(
<ide> Object.assign({}, this.options.groupOptions, {
<ide> name: this.options.chunkName
<del> }),
<del> this
<add> })
<ide> );
<ide> for (const dep of dependencies) {
<ide> block.addDependency(dep);
<ide> class ContextModule extends Module {
<ide> Object.assign({}, this.options.groupOptions, {
<ide> name: chunkName
<ide> }),
<del> compilation.moduleGraph.getModule(dep),
<ide> dep.loc,
<ide> dep.userRequest
<ide> );
<ide><path>lib/dependencies/AMDRequireDependenciesBlock.js
<ide> module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBloc
<ide> arrayRange,
<ide> functionRange,
<ide> errorCallbackRange,
<del> module,
<ide> loc,
<ide> request
<ide> ) {
<del> super(null, module, loc, request);
<add> super(null, loc, request);
<ide> this.expr = expr;
<ide> this.outerRange = expr.range;
<ide> this.arrayRange = arrayRange;
<ide><path>lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
<ide> class AMDRequireDependenciesBlockParserPlugin {
<ide> param.range,
<ide> expr.arguments.length > 1 ? expr.arguments[1].range : null,
<ide> expr.arguments.length > 2 ? expr.arguments[2].range : null,
<del> parser.state.module,
<ide> expr.loc,
<ide> this.processArrayForRequestString(param)
<ide> );
<ide> class AMDRequireDependenciesBlockParserPlugin {
<ide> arrayRange,
<ide> functionRange,
<ide> errorCallbackRange,
<del> module,
<ide> loc,
<ide> request
<ide> ) {
<ide> class AMDRequireDependenciesBlockParserPlugin {
<ide> arrayRange,
<ide> functionRange,
<ide> errorCallbackRange,
<del> module,
<ide> loc,
<ide> request
<ide> );
<ide><path>lib/dependencies/ImportDependenciesBlock.js
<ide> const ImportDependency = require("./ImportDependency");
<ide>
<ide> module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock {
<ide> // TODO webpack 5 reorganize arguments
<del> constructor(request, range, groupOptions, module, loc, originModule) {
<del> super(groupOptions, module, loc, request);
<add> constructor(groupOptions, loc, request, range) {
<add> super(groupOptions, loc, request);
<ide> this.range = range;
<ide> const dep = new ImportDependency(request, this);
<ide> dep.loc = loc;
<ide><path>lib/dependencies/ImportParserPlugin.js
<ide> class ImportParserPlugin {
<ide> parser.state.current.addDependency(dep);
<ide> } else {
<ide> const depBlock = new ImportDependenciesBlock(
<del> param.string,
<del> expr.range,
<ide> Object.assign(groupOptions, {
<ide> name: chunkName
<ide> }),
<del> parser.state.module,
<ide> expr.loc,
<del> parser.state.module
<add> param.string,
<add> expr.range
<ide> );
<ide> parser.state.current.addBlock(depBlock);
<ide> }
<ide><path>lib/dependencies/RequireEnsureDependenciesBlock.js
<ide> module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesB
<ide> errorExpression,
<ide> chunkName,
<ide> chunkNameRange,
<del> module,
<ide> loc
<ide> ) {
<del> super(chunkName, module, loc, null);
<add> super(chunkName, loc, null);
<ide> this.expr = expr;
<ide> /** @type {[number, number] | undefined} */
<ide> const successBodyRange =
<ide><path>lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
<ide> module.exports = class RequireEnsureDependenciesBlockParserPlugin {
<ide> errorExpression ? errorExpression.fn : errorExpressionArg,
<ide> chunkName,
<ide> chunkNameRange,
<del> parser.state.module,
<ide> expr.loc
<ide> );
<ide> const old = parser.state.current; | 8 |
Java | Java | add reset logic for rn perf counters | 8e79a74bc21cc11926713f5dcf93f62ce4f738d6 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java
<ide> public void initializeWithInstance(CatalystInstance catalystInstance) {
<ide> mJSMessageQueueThread = queueConfig.getJSQueueThread();
<ide> }
<ide>
<add> public void resetPerfStats() {
<add> if (mNativeModulesMessageQueueThread != null) {
<add> mNativeModulesMessageQueueThread.resetPerfStats();
<add> }
<add> if (mJSMessageQueueThread != null) {
<add> mJSMessageQueueThread.resetPerfStats();
<add> }
<add> }
<add>
<ide> public void setNativeModuleCallExceptionHandler(
<ide> @Nullable NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler) {
<ide> mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThread.java
<ide> public interface MessageQueueThread {
<ide> void quitSynchronous();
<ide>
<ide> /**
<del> * Returns the time in milliseconds at which this thread was started. This
<add> * Returns the perf counters taken when the framework was started. This
<ide> * method is intended to be used for instrumentation purposes.
<ide> */
<ide> @DoNotStrip
<del> long getStartTimeMillis();
<add> MessageQueueThreadPerfStats getPerfStats();
<add>
<add> /**
<add> * Resets the perf counters. This is useful if the RN threads are being re-used.
<add> * This method is intended to be used for instrumentation purposes.
<add> */
<add> @DoNotStrip
<add> void resetPerfStats();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java
<ide> public class MessageQueueThreadImpl implements MessageQueueThread {
<ide> private final Looper mLooper;
<ide> private final MessageQueueThreadHandler mHandler;
<ide> private final String mAssertionErrorMessage;
<del> private long mStartTimeMillis;
<add> private MessageQueueThreadPerfStats mPerfStats;
<ide> private volatile boolean mIsFinished = false;
<ide>
<ide> private MessageQueueThreadImpl(
<ide> String name,
<ide> Looper looper,
<ide> QueueThreadExceptionHandler exceptionHandler) {
<del> this(name, looper, exceptionHandler, -1);
<add> this(name, looper, exceptionHandler, null);
<ide> }
<ide>
<ide> private MessageQueueThreadImpl(
<ide> String name,
<ide> Looper looper,
<ide> QueueThreadExceptionHandler exceptionHandler,
<del> long startTimeMillis) {
<add> MessageQueueThreadPerfStats stats) {
<ide> mName = name;
<ide> mLooper = looper;
<ide> mHandler = new MessageQueueThreadHandler(looper, exceptionHandler);
<del> mStartTimeMillis = startTimeMillis;
<add> mPerfStats = stats;
<ide> mAssertionErrorMessage = "Expected to be called from the '" + getName() + "' thread!";
<ide> }
<ide>
<ide> public void quitSynchronous() {
<ide>
<ide> @DoNotStrip
<ide> @Override
<del> public long getStartTimeMillis() {
<del> return mStartTimeMillis;
<add> public MessageQueueThreadPerfStats getPerfStats() {
<add> return mPerfStats;
<add> }
<add>
<add> @DoNotStrip
<add> @Override
<add> public void resetPerfStats() {
<add> assignToPerfStats(mPerfStats, -1, -1);
<add> runOnQueue(new Runnable() {
<add> @Override
<add> public void run() {
<add> long wallTime = SystemClock.uptimeMillis();
<add> long cpuTime = SystemClock.currentThreadTimeMillis();
<add> assignToPerfStats(mPerfStats, wallTime, cpuTime);
<add> }
<add> });
<add> }
<add>
<add> private static void assignToPerfStats(MessageQueueThreadPerfStats stats, long wall, long cpu) {
<add> stats.wallTime = wall;
<add> stats.cpuTime = cpu;
<ide> }
<ide>
<ide> public Looper getLooper() {
<ide> private static MessageQueueThreadImpl startNewBackgroundThread(
<ide> final String name,
<ide> long stackSize,
<ide> QueueThreadExceptionHandler exceptionHandler) {
<del> final SimpleSettableFuture<Pair<Looper, Long>> dataFuture = new SimpleSettableFuture<>();
<add> final SimpleSettableFuture<Pair<Looper, MessageQueueThreadPerfStats>> dataFuture = new SimpleSettableFuture<>();
<ide> long startTimeMillis;
<ide> Thread bgThread = new Thread(null,
<ide> new Runnable() {
<ide> @Override
<ide> public void run() {
<ide> Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
<ide> Looper.prepare();
<del> dataFuture.set(new Pair<>(Looper.myLooper(), SystemClock.uptimeMillis()));
<add> MessageQueueThreadPerfStats stats = new MessageQueueThreadPerfStats();
<add> long wallTime = SystemClock.uptimeMillis();
<add> long cpuTime = SystemClock.currentThreadTimeMillis();
<add> assignToPerfStats(stats, wallTime, cpuTime);
<add> dataFuture.set(new Pair<>(Looper.myLooper(), stats));
<ide> Looper.loop();
<ide> }
<ide> }, "mqt_" + name, stackSize);
<ide> bgThread.start();
<ide>
<del> Pair<Looper, Long> pair = dataFuture.getOrThrow();
<add> Pair<Looper, MessageQueueThreadPerfStats> pair = dataFuture.getOrThrow();
<ide> return new MessageQueueThreadImpl(name, pair.first, exceptionHandler, pair.second);
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadPerfStats.java
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.bridge.queue;
<add>
<add>/**
<add> * This class holds perf counters' values at the beginning of an RN startup.
<add> */
<add>public class MessageQueueThreadPerfStats {
<add> public long wallTime;
<add> public long cpuTime;
<add>} | 4 |
PHP | PHP | make pendingrequest conditionable | 442b6d0e7e086a5775c97ccd61111c75cd2d2037 | <ide><path>src/Illuminate/Http/Client/PendingRequest.php
<ide> use Illuminate\Http\Client\Events\ResponseReceived;
<ide> use Illuminate\Support\Collection;
<ide> use Illuminate\Support\Str;
<add>use Illuminate\Support\Traits\Conditionable;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Psr\Http\Message\MessageInterface;
<ide> use Symfony\Component\VarDumper\VarDumper;
<ide>
<ide> class PendingRequest
<ide> {
<del> use Macroable;
<add> use Conditionable, Macroable;
<ide>
<ide> /**
<ide> * The factory instance. | 1 |
Javascript | Javascript | update fast refresh full reload warning | dfee55221c6a85398b41db0ca9f5cae9d078c945 | <ide><path>packages/next/client/dev/error-overlay/hot-dev-client.js
<ide> function tryApplyUpdates(onHotUpdateSuccess) {
<ide> if (err) {
<ide> console.warn(
<ide> '[Fast Refresh] performing full reload\n\n' +
<del> "Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React tree.\n" +
<del> 'You might have a file which renders a React component but also exports a value that is imported by a non-React component.\n' +
<add> "Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
<add> 'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
<ide> 'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
<del> 'It is also possible you are using class components at the top-level of your application, which disables Fast Refresh.\n' +
<del> 'Fast Refresh requires at least one function component in your React tree.'
<add> 'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
<add> 'Fast Refresh requires at least one parent function component in your React tree.'
<ide> )
<ide> } else if (hadRuntimeError) {
<ide> console.warn( | 1 |
Python | Python | hide symbols for builtin js files in binary | 7b39503b4a620f2703564fcefb82d98df78dd039 | <ide><path>tools/js2c.py
<ide> def ReadMacros(lines):
<ide>
<ide> namespace node {{
<ide>
<add>namespace {{
<add>
<ide> {definitions}
<ide>
<add>}} // anonymous namespace
<add>
<ide> v8::Local<v8::String> LoadersBootstrapperSource(Environment* env) {{
<ide> return internal_bootstrap_loaders_value.ToStringChecked(env->isolate());
<ide> }} | 1 |
Ruby | Ruby | fix misspelling of 'lambda'. closes #987 | 86491476d5ff346e46cc024a890bf1e71530bdd5 | <ide><path>activesupport/test/option_merger_test.rb
<ide> def test_nested_method_with_options_containing_hashes_going_deep
<ide> end
<ide> end
<ide>
<del> def test_nested_method_with_options_using_lamdba
<del> local_lamdba = lambda { { :lambda => true } }
<add> def test_nested_method_with_options_using_lambda
<add> local_lambda = lambda { { :lambda => true } }
<ide> with_options(@options) do |o|
<del> assert_equal @options.merge(local_lamdba.call),
<del> o.method_with_options(local_lamdba).call
<add> assert_equal @options.merge(local_lambda.call),
<add> o.method_with_options(local_lambda).call
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | add test for csv.format | 3db7fd1b65e1a4aad1149044b037484fbb4a54e0 | <ide><path>test/csv/format-test.js
<add>require("../env");
<add>require("../../d3");
<add>require("../../d3.csv");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("d3.csv.format");
<add>
<add>suite.addBatch({
<add> "format": {
<add> topic: function() {
<add> return d3.csv.format;
<add> },
<add> "takes an array of arrays as input": function(format) {
<add> assert.equal(format([["a", "b", "c"], ["1", "2", "3"]]), "a,b,c\n1,2,3");
<add> },
<add> "separates lines using unix newline": function(format) {
<add> assert.equal(format([[], []]), "\n");
<add> },
<add> "does not strip whitespace": function(format) {
<add> assert.equal(format([["a ", " b", "c"], ["1", "2", "3 "]]), "a , b,c\n1,2,3 ");
<add> },
<add> "does not quote simple values": function(format) {
<add> assert.equal(format([["a"], [1]]), "a\n1");
<add> },
<add> "escapes double quotes": function(format) {
<add> assert.equal(format([["\"fish\""]]), "\"\"\"fish\"\"\"");
<add> },
<add> "escapes unix newlines": function(format) {
<add> assert.equal(format([["new\nline"]]), "\"new\nline\"");
<add> },
<add> "escapes commas": function(format) {
<add> assert.equal(format([["oxford,comma"]]), "\"oxford,comma\"");
<add> }
<add> }
<add>});
<add>
<add>suite.export(module);
<ide><path>test/csv/parse-test.js
<ide> require("../../d3.csv");
<ide> var vows = require("vows"),
<ide> assert = require("assert");
<ide>
<del>var suite = vows.describe("d3.csv");
<add>var suite = vows.describe("d3.csv.parse");
<ide>
<ide> suite.addBatch({
<ide> "parse": { | 2 |
PHP | PHP | remove urlparser from database | eee81be200cb4aed8b43d4d7f6e3469a0bcd5a69 | <ide><path>src/Illuminate/Database/ConfigurationUrlParser.php
<del><?php
<del>
<del>namespace Illuminate\Database;
<del>
<del>use Illuminate\Support\Arr;
<del>use InvalidArgumentException;
<del>
<del>class ConfigurationUrlParser
<del>{
<del> /**
<del> * The drivers aliases map.
<del> *
<del> * @var array
<del> */
<del> protected static $driverAliases = [
<del> 'mssql' => 'sqlsrv',
<del> 'mysql2' => 'mysql', // RDS
<del> 'postgres' => 'pgsql',
<del> 'postgresql' => 'pgsql',
<del> 'sqlite3' => 'sqlite',
<del> ];
<del>
<del> /**
<del> * Parse the database configuration, hydrating options using a database configuration URL if possible.
<del> *
<del> * @param array|string $config
<del> * @return array
<del> */
<del> public function parseConfiguration($config)
<del> {
<del> if (is_string($config)) {
<del> $config = ['url' => $config];
<del> }
<del>
<del> $url = $config['url'] ?? null;
<del>
<del> $config = Arr::except($config, 'url');
<del>
<del> if (! $url) {
<del> return $config;
<del> }
<del>
<del> $parsedUrl = $this->parseUrl($url);
<del>
<del> return array_merge(
<del> $config,
<del> $this->getPrimaryOptions($parsedUrl),
<del> $this->getQueryOptions($parsedUrl)
<del> );
<del> }
<del>
<del> /**
<del> * Get the primary database connection options.
<del> *
<del> * @param array $url
<del> * @return array
<del> */
<del> protected function getPrimaryOptions($url)
<del> {
<del> return array_filter([
<del> 'driver' => $this->getDriver($url),
<del> 'database' => $this->getDatabase($url),
<del> 'host' => $url['host'] ?? null,
<del> 'port' => $url['port'] ?? null,
<del> 'username' => $url['user'] ?? null,
<del> 'password' => $url['pass'] ?? null,
<del> ], function ($value) {
<del> return ! is_null($value);
<del> });
<del> }
<del>
<del> /**
<del> * Get the database driver from the URL.
<del> *
<del> * @param array $url
<del> * @return string|null
<del> */
<del> protected function getDriver($url)
<del> {
<del> $alias = $url['scheme'] ?? null;
<del>
<del> if (! $alias) {
<del> return;
<del> }
<del>
<del> return static::$driverAliases[$alias] ?? $alias;
<del> }
<del>
<del> /**
<del> * Get the database name from the URL.
<del> *
<del> * @param array $url
<del> * @return string|null
<del> */
<del> protected function getDatabase($url)
<del> {
<del> $path = $url['path'] ?? null;
<del>
<del> return $path ? substr($path, 1) : null;
<del> }
<del>
<del> /**
<del> * Get all of the additional database options from the query string.
<del> *
<del> * @param array $url
<del> * @return array
<del> */
<del> protected function getQueryOptions($url)
<del> {
<del> $queryString = $url['query'] ?? null;
<del>
<del> if (! $queryString) {
<del> return [];
<del> }
<del>
<del> $query = [];
<del>
<del> parse_str($queryString, $query);
<del>
<del> return $this->parseStringsToNativeTypes($query);
<del> }
<del>
<del> /**
<del> * Parse the string URL to an array of components.
<del> *
<del> * @param string $url
<del> * @return array
<del> */
<del> protected function parseUrl($url)
<del> {
<del> $url = preg_replace('#^(sqlite3?):///#', '$1://null/', $url);
<del>
<del> $parsedUrl = parse_url($url);
<del>
<del> if ($parsedUrl === false) {
<del> throw new InvalidArgumentException('The database configuration URL is malformed.');
<del> }
<del>
<del> return $this->parseStringsToNativeTypes(
<del> array_map('rawurldecode', $parsedUrl)
<del> );
<del> }
<del>
<del> /**
<del> * Convert string casted values to their native types.
<del> *
<del> * @param mixed $value
<del> * @return mixed
<del> */
<del> protected function parseStringsToNativeTypes($value)
<del> {
<del> if (is_array($value)) {
<del> return array_map([$this, 'parseStringsToNativeTypes'], $value);
<del> }
<del>
<del> if (! is_string($value)) {
<del> return $value;
<del> }
<del>
<del> $parsedValue = json_decode($value, true);
<del>
<del> if (json_last_error() === JSON_ERROR_NONE) {
<del> return $parsedValue;
<del> }
<del>
<del> return $value;
<del> }
<del>
<del> /**
<del> * Get all of the current drivers aliases.
<del> *
<del> * @return array
<del> */
<del> public static function getDriverAliases()
<del> {
<del> return static::$driverAliases;
<del> }
<del>
<del> /**
<del> * Add the given driver alias to the driver aliases array.
<del> *
<del> * @param string $alias
<del> * @param string $driver
<del> * @return void
<del> */
<del> public static function addDriverAlias($alias, $driver)
<del> {
<del> static::$driverAliases[$alias] = $driver;
<del> }
<del>}
<ide><path>tests/Database/DatabaseUrlParserTest.php
<del><?php
<del>
<del>namespace Illuminate\Tests\Database;
<del>
<del>use PHPUnit\Framework\TestCase;
<del>use Illuminate\Database\ConfigurationUrlParser;
<del>
<del>class DatabaseUrlParserTest extends TestCase
<del>{
<del> /**
<del> * @dataProvider databaseUrls
<del> */
<del> public function testDatabaseUrlsAreParsed($config, $expectedOutput)
<del> {
<del> $this->assertEquals($expectedOutput, (new ConfigurationUrlParser)->parseConfiguration($config));
<del> }
<del>
<del> public function testDriversAliases()
<del> {
<del> $this->assertEquals([
<del> 'mssql' => 'sqlsrv',
<del> 'mysql2' => 'mysql',
<del> 'postgres' => 'pgsql',
<del> 'postgresql' => 'pgsql',
<del> 'sqlite3' => 'sqlite',
<del> ], ConfigurationUrlParser::getDriverAliases());
<del>
<del> ConfigurationUrlParser::addDriverAlias('some-particular-alias', 'mysql');
<del>
<del> $this->assertEquals([
<del> 'mssql' => 'sqlsrv',
<del> 'mysql2' => 'mysql',
<del> 'postgres' => 'pgsql',
<del> 'postgresql' => 'pgsql',
<del> 'sqlite3' => 'sqlite',
<del> 'some-particular-alias' => 'mysql',
<del> ], ConfigurationUrlParser::getDriverAliases());
<del>
<del> $this->assertEquals([
<del> 'driver' => 'mysql',
<del> ], (new ConfigurationUrlParser)->parseConfiguration('some-particular-alias://null'));
<del> }
<del>
<del> public function databaseUrls()
<del> {
<del> return [
<del> 'simple URL' => [
<del> 'mysql://foo:bar@localhost/baz',
<del> [
<del> 'driver' => 'mysql',
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'host' => 'localhost',
<del> 'database' => 'baz',
<del> ],
<del> ],
<del> 'simple URL with port' => [
<del> 'mysql://foo:bar@localhost:134/baz',
<del> [
<del> 'driver' => 'mysql',
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'host' => 'localhost',
<del> 'port' => 134,
<del> 'database' => 'baz',
<del> ],
<del> ],
<del> 'sqlite relative URL with host' => [
<del> 'sqlite://localhost/foo/database.sqlite',
<del> [
<del> 'database' => 'foo/database.sqlite',
<del> 'driver' => 'sqlite',
<del> 'host' => 'localhost',
<del> ],
<del> ],
<del> 'sqlite absolute URL with host' => [
<del> 'sqlite://localhost//tmp/database.sqlite',
<del> [
<del> 'database' => '/tmp/database.sqlite',
<del> 'driver' => 'sqlite',
<del> 'host' => 'localhost',
<del> ],
<del> ],
<del> 'sqlite relative URL without host' => [
<del> 'sqlite:///foo/database.sqlite',
<del> [
<del> 'database' => 'foo/database.sqlite',
<del> 'driver' => 'sqlite',
<del> ],
<del> ],
<del> 'sqlite absolute URL without host' => [
<del> 'sqlite:////tmp/database.sqlite',
<del> [
<del> 'database' => '/tmp/database.sqlite',
<del> 'driver' => 'sqlite',
<del> ],
<del> ],
<del> 'sqlite memory' => [
<del> 'sqlite:///:memory:',
<del> [
<del> 'database' => ':memory:',
<del> 'driver' => 'sqlite',
<del> ],
<del> ],
<del> 'params parsed from URL override individual params' => [
<del> [
<del> 'url' => 'mysql://foo:bar@localhost/baz',
<del> 'password' => 'lulz',
<del> 'driver' => 'sqlite',
<del> ],
<del> [
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'host' => 'localhost',
<del> 'database' => 'baz',
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'params not parsed from URL but individual params are preserved' => [
<del> [
<del> 'url' => 'mysql://foo:bar@localhost/baz',
<del> 'port' => 134,
<del> ],
<del> [
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'host' => 'localhost',
<del> 'port' => 134,
<del> 'database' => 'baz',
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'query params from URL are used as extra params' => [
<del> 'url' => 'mysql://foo:bar@localhost/database?charset=UTF-8',
<del> [
<del> 'driver' => 'mysql',
<del> 'database' => 'database',
<del> 'host' => 'localhost',
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'charset' => 'UTF-8',
<del> ],
<del> ],
<del> 'simple URL with driver set apart' => [
<del> [
<del> 'url' => '//foo:bar@localhost/baz',
<del> 'driver' => 'sqlsrv',
<del> ],
<del> [
<del> 'username' => 'foo',
<del> 'password' => 'bar',
<del> 'host' => 'localhost',
<del> 'database' => 'baz',
<del> 'driver' => 'sqlsrv',
<del> ],
<del> ],
<del> 'simple URL with percent encoding' => [
<del> 'mysql://foo%3A:bar%2F@localhost/baz+baz%40',
<del> [
<del> 'username' => 'foo:',
<del> 'password' => 'bar/',
<del> 'host' => 'localhost',
<del> 'database' => 'baz+baz@',
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'simple URL with percent sign in password' => [
<del> 'mysql://foo:bar%25bar@localhost/baz',
<del> [
<del> 'username' => 'foo',
<del> 'password' => 'bar%bar',
<del> 'host' => 'localhost',
<del> 'database' => 'baz',
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'URL with mssql alias driver' => [
<del> 'mssql://null',
<del> [
<del> 'driver' => 'sqlsrv',
<del> ],
<del> ],
<del> 'URL with sqlsrv alias driver' => [
<del> 'sqlsrv://null',
<del> [
<del> 'driver' => 'sqlsrv',
<del> ],
<del> ],
<del> 'URL with mysql alias driver' => [
<del> 'mysql://null',
<del> [
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'URL with mysql2 alias driver' => [
<del> 'mysql2://null',
<del> [
<del> 'driver' => 'mysql',
<del> ],
<del> ],
<del> 'URL with postgres alias driver' => [
<del> 'postgres://null',
<del> [
<del> 'driver' => 'pgsql',
<del> ],
<del> ],
<del> 'URL with postgresql alias driver' => [
<del> 'postgresql://null',
<del> [
<del> 'driver' => 'pgsql',
<del> ],
<del> ],
<del> 'URL with pgsql alias driver' => [
<del> 'pgsql://null',
<del> [
<del> 'driver' => 'pgsql',
<del> ],
<del> ],
<del> 'URL with sqlite alias driver' => [
<del> 'sqlite://null',
<del> [
<del> 'driver' => 'sqlite',
<del> ],
<del> ],
<del> 'URL with sqlite3 alias driver' => [
<del> 'sqlite3://null',
<del> [
<del> 'driver' => 'sqlite',
<del> ],
<del> ],
<del>
<del> 'URL with unknown driver' => [
<del> 'foo://null',
<del> [
<del> 'driver' => 'foo',
<del> ],
<del> ],
<del> 'Sqlite with foreign_key_constraints' => [
<del> 'sqlite:////absolute/path/to/database.sqlite?foreign_key_constraints=true',
<del> [
<del> 'driver' => 'sqlite',
<del> 'database' => '/absolute/path/to/database.sqlite',
<del> 'foreign_key_constraints' => true,
<del> ],
<del> ],
<del>
<del> 'Most complex example with read and write subarrays all in string' => [
<del> 'mysql://root:@null/database?read[host][]=192.168.1.1&write[host][]=196.168.1.2&sticky=true&charset=utf8mb4&collation=utf8mb4_unicode_ci&prefix=',
<del> [
<del> 'read' => [
<del> 'host' => ['192.168.1.1'],
<del> ],
<del> 'write' => [
<del> 'host' => ['196.168.1.2'],
<del> ],
<del> 'sticky' => true,
<del> 'driver' => 'mysql',
<del> 'database' => 'database',
<del> 'username' => 'root',
<del> 'password' => '',
<del> 'charset' => 'utf8mb4',
<del> 'collation' => 'utf8mb4_unicode_ci',
<del> 'prefix' => '',
<del> ],
<del> ],
<del>
<del> 'Full example from doc that prove that there isn\'t any Breaking Change' => [
<del> [
<del> 'driver' => 'mysql',
<del> 'host' => '127.0.0.1',
<del> 'port' => '3306',
<del> 'database' => 'forge',
<del> 'username' => 'forge',
<del> 'password' => '',
<del> 'unix_socket' => '',
<del> 'charset' => 'utf8mb4',
<del> 'collation' => 'utf8mb4_unicode_ci',
<del> 'prefix' => '',
<del> 'prefix_indexes' => true,
<del> 'strict' => true,
<del> 'engine' => null,
<del> 'options' => ['foo' => 'bar'],
<del> ],
<del> [
<del> 'driver' => 'mysql',
<del> 'host' => '127.0.0.1',
<del> 'port' => '3306',
<del> 'database' => 'forge',
<del> 'username' => 'forge',
<del> 'password' => '',
<del> 'unix_socket' => '',
<del> 'charset' => 'utf8mb4',
<del> 'collation' => 'utf8mb4_unicode_ci',
<del> 'prefix' => '',
<del> 'prefix_indexes' => true,
<del> 'strict' => true,
<del> 'engine' => null,
<del> 'options' => ['foo' => 'bar'],
<del> ],
<del> ],
<del>
<del> 'Full example from doc with url overwriting parameters' => [
<del> [
<del> 'url' => 'mysql://root:pass@db/local',
<del> 'driver' => 'mysql',
<del> 'host' => '127.0.0.1',
<del> 'port' => '3306',
<del> 'database' => 'forge',
<del> 'username' => 'forge',
<del> 'password' => '',
<del> 'unix_socket' => '',
<del> 'charset' => 'utf8mb4',
<del> 'collation' => 'utf8mb4_unicode_ci',
<del> 'prefix' => '',
<del> 'prefix_indexes' => true,
<del> 'strict' => true,
<del> 'engine' => null,
<del> 'options' => ['foo' => 'bar'],
<del> ],
<del> [
<del> 'driver' => 'mysql',
<del> 'host' => 'db',
<del> 'port' => '3306',
<del> 'database' => 'local',
<del> 'username' => 'root',
<del> 'password' => 'pass',
<del> 'unix_socket' => '',
<del> 'charset' => 'utf8mb4',
<del> 'collation' => 'utf8mb4_unicode_ci',
<del> 'prefix' => '',
<del> 'prefix_indexes' => true,
<del> 'strict' => true,
<del> 'engine' => null,
<del> 'options' => ['foo' => 'bar'],
<del> ],
<del> ],
<del> ];
<del> }
<del>} | 2 |
Javascript | Javascript | use fixtures.readkey instead of fixturesdir | c4c63812822fc973cb3d4bb4040729213dcaa620 | <ide><path>test/parallel/test-tls-delayed-attach.js
<ide> const common = require('../common');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<ide> const net = require('net');
<ide>
<ide> const sent = 'hello world';
<ide> let received = '';
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<ide> };
<ide>
<ide> const server = net.createServer(function(c) { | 1 |
Javascript | Javascript | stop animations when destroying a chart | 66f7f96d4b0f8a03b67a45c43f20c1155935f792 | <ide><path>src/Chart.Core.js
<ide> return template(this.options.legendTemplate,this);
<ide> },
<ide> destroy : function(){
<add> this.stop();
<ide> this.clear();
<ide> unbindEvents(this, this.events);
<ide> var canvas = this.chart.canvas; | 1 |
Text | Text | fix typo in test/ttx/readme.md | 7d5bf83ce879a2a937ff1a5cf6c1b65e008beaa5 | <ide><path>test/ttx/README.md
<del>If `git clone --recursive` was not used, please run `git submodile init; git submodule update` to pull fonttools code.
<add>If `git clone --recursive` was not used, please run `git submodule init; git submodule update` to pull fonttools code.
<ide>
<del>Note: python 2.6 for 32-bit is required to run ttx.
<ide>\ No newline at end of file
<add>Note: python 2.6 for 32-bit is required to run ttx. | 1 |
Go | Go | use userprofile path on windows as home directory | d4dbb708320e59efa91b077303c87f9e9513cd91 | <ide><path>docker/flags.go
<ide> import (
<ide> "fmt"
<ide> "os"
<ide> "path/filepath"
<add> "runtime"
<ide>
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> var (
<ide>
<ide> func init() {
<ide> if dockerCertPath == "" {
<del> dockerCertPath = filepath.Join(os.Getenv("HOME"), ".docker")
<add> dockerCertPath = filepath.Join(getHomeDir(), ".docker")
<ide> }
<ide> }
<ide>
<add>func getHomeDir() string {
<add> if runtime.GOOS == "windows" {
<add> return os.Getenv("USERPROFILE")
<add> }
<add> return os.Getenv("HOME")
<add>}
<add>
<ide> var (
<ide> flVersion = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
<ide> flDaemon = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode") | 1 |
Javascript | Javascript | add callback to dgramsocket.send() | cbf2a2233eb2ef17b7a341b7e88c4309f80457e0 | <ide><path>lib/dgram.js
<ide> Socket.prototype.address = function () {
<ide> Socket.prototype.send = function(port, addr, buffer, offset, length) {
<ide> var self = this;
<ide>
<add> var lastArg = arguments[arguments.length - 1];
<add> var callback = typeof lastArg === 'function' ? lastArg : null;
<add>
<ide> if (!isPort(arguments[0])) {
<del> if (!self.fd) {
<del> self.type = 'unix_dgram';
<del> self.fd = socket(self.type);
<add> try {
<add> if (!self.fd) {
<add> self.type = 'unix_dgram';
<add> self.fd = socket(self.type);
<add> }
<add> var bytes = sendto(self.fd, buffer, offset, length, 0, port, addr);
<add> } catch (e) {
<add> if (callback) callback(e);
<add> return;
<ide> }
<del> sendto(self.fd, buffer, offset, length, 0, port, addr);
<add>
<add> if (callback) callback(null, bytes);
<add>
<ide> } else {
<ide> dns.lookup(arguments[1], function (err, ip, addressType) {
<add> // DNS error
<ide> if (err) {
<add> if (callback) callback(err);
<ide> self.emit('error', err);
<del> } else {
<add> return;
<add> }
<add>
<add> try {
<ide> if (!self.fd) {
<ide> self.type = addressType == 4 ? 'udp4' : 'udp6';
<ide> self.fd = socket(self.type);
<ide> Socket.prototype.send = function(port, addr, buffer, offset, length) {
<ide> self._startWatcher();
<ide> });
<ide> }
<del> sendto(self.fd, buffer, offset, length, 0, port, ip);
<add> var bytes = sendto(self.fd, buffer, offset, length, 0, port, ip);
<add> } catch (err) {
<add> // socket creation, or sendto error.
<add> if (callback) callback(err);
<add> return;
<ide> }
<add>
<add> if (callback) callback(null, bytes);
<ide> });
<ide> }
<ide> };
<ide><path>test/simple/test-dgram-pingpong.js
<ide> var dgram = require("dgram");
<ide>
<ide> var tests_run = 0;
<ide>
<add>
<ide> function pingPongTest (port, host) {
<add> var callbacks = 0;
<ide> var N = 500;
<ide> var count = 0;
<ide> var sent_final_ping = false;
<ide> function pingPongTest (port, host) {
<ide> if (/PING/.exec(msg)) {
<ide> var buf = new Buffer(4);
<ide> buf.write('PONG');
<del> server.send(rinfo.port, rinfo.address, buf, 0, buf.length);
<add> server.send(rinfo.port, rinfo.address, buf, 0, buf.length, function (err, sent) {
<add> callbacks++;
<add> });
<ide> }
<ide>
<ide> });
<ide> function pingPongTest (port, host) {
<ide> assert.equal(N, count);
<ide> tests_run += 1;
<ide> server.close();
<add> assert.equal(N-1, callbacks);
<ide> });
<ide>
<ide> client.addListener("error", function (e) { | 2 |
Javascript | Javascript | use runinnewcontext instead of process.compile | a16b3c3148554ec07ba3dd5581a6b1d2e4d62752 | <ide><path>src/node.js
<ide> process.assert = function (x, msg) {
<ide> };
<ide>
<ide> var writeError = process.binding('stdio').writeError;
<del>
<add>var evals = process.binding('evals');
<ide>
<ide> // lazy loaded.
<ide> var constants;
<ide> var module = (function () {
<ide> return replModule.exports;
<ide> }
<ide>
<del> var fn = process.compile(
<add> var fn = evals.Script.runInThisContext(
<ide> "(function (exports, require) {" + natives[id] + "\n})",
<ide> id + '.js');
<ide> var m = new Module(id);
<ide> var module = (function () {
<ide> var dirname = path.dirname(filename);
<ide>
<ide> if (contextLoad) {
<del> if (!Script) Script = process.binding('evals').Script;
<del>
<ide> if (self.id !== ".") {
<ide> debug('load submodule');
<ide> // not root module
<ide> var module = (function () {
<ide> sandbox.global = sandbox;
<ide> sandbox.root = root;
<ide>
<del> Script.runInNewContext(content, sandbox, filename);
<add> evals.Script.runInNewContext(content, sandbox, filename);
<ide>
<ide> } else {
<ide> debug('load root module');
<ide> var module = (function () {
<ide> global.__filename = filename;
<ide> global.__dirname = dirname;
<ide> global.module = self;
<del> Script.runInThisContext(content, filename);
<add> evals.Script.runInThisContext(content, filename);
<ide> }
<ide>
<ide> } else {
<ide> var module = (function () {
<ide> + content
<ide> + "\n});";
<ide>
<del> var compiledWrapper = process.compile(wrapper, filename);
<add> var compiledWrapper = evals.Script.runInThisContext(wrapper, filename);
<ide> if (filename === process.argv[1] && global.v8debug) {
<ide> global.v8debug.Debug.setBreakPoint(compiledWrapper, 0, 0);
<ide> } | 1 |
Python | Python | move exception handler out of main view | b430503fa657330b606a9c632ea0decc4254163e | <ide><path>rest_framework/views.py
<ide> from rest_framework.utils import formatting
<ide>
<ide>
<del>def get_view_name(cls, suffix=None):
<del> name = cls.__name__
<add>def get_view_name(view_cls, suffix=None):
<add> """
<add> Given a view class, return a textual name to represent the view.
<add> This name is used in the browsable API, and in OPTIONS responses.
<add>
<add> This function is the default for the `VIEW_NAME_FUNCTION` setting.
<add> """
<add> name = view_cls.__name__
<ide> name = formatting.remove_trailing_string(name, 'View')
<ide> name = formatting.remove_trailing_string(name, 'ViewSet')
<ide> name = formatting.camelcase_to_spaces(name)
<ide> def get_view_name(cls, suffix=None):
<ide>
<ide> return name
<ide>
<del>def get_view_description(cls, html=False):
<del> description = cls.__doc__ or ''
<add>def get_view_description(view_cls, html=False):
<add> """
<add> Given a view class, return a textual description to represent the view.
<add> This name is used in the browsable API, and in OPTIONS responses.
<add>
<add> This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
<add> """
<add> description = view_cls.__doc__ or ''
<ide> description = formatting.dedent(smart_text(description))
<ide> if html:
<ide> return formatting.markup_description(description)
<ide> return description
<ide>
<ide>
<add>def exception_handler(exc):
<add> """
<add> Returns the response that should be used for any given exception.
<add>
<add> By default we handle the REST framework `APIException`, and also
<add> Django's builtin `Http404` and `PermissionDenied` exceptions.
<add>
<add> Any unhandled exceptions may return `None`, which will cause a 500 error
<add> to be raised.
<add> """
<add> if isinstance(exc, exceptions.APIException):
<add> headers = {}
<add> if getattr(exc, 'auth_header', None):
<add> headers['WWW-Authenticate'] = exc.auth_header
<add> if getattr(exc, 'wait', None):
<add> headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait
<add>
<add> return Response({'detail': exc.detail},
<add> status=exc.status_code,
<add> headers=headers)
<add>
<add> elif isinstance(exc, Http404):
<add> return Response({'detail': 'Not found'},
<add> status=status.HTTP_404_NOT_FOUND)
<add>
<add> elif isinstance(exc, PermissionDenied):
<add> return Response({'detail': 'Permission denied'},
<add> status=status.HTTP_403_FORBIDDEN)
<add>
<add> # Note: Unhandled exceptions will raise a 500 error.
<add> return None
<add>
<add>
<ide> class APIView(View):
<ide> settings = api_settings
<ide>
<ide> def handle_exception(self, exc):
<ide> Handle any exception that occurs, by returning an appropriate response,
<ide> or re-raising the error.
<ide> """
<del> if isinstance(exc, exceptions.Throttled) and exc.wait is not None:
<del> # Throttle wait header
<del> self.headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait
<del>
<ide> if isinstance(exc, (exceptions.NotAuthenticated,
<ide> exceptions.AuthenticationFailed)):
<ide> # WWW-Authenticate header for 401 responses, else coerce to 403
<ide> auth_header = self.get_authenticate_header(self.request)
<ide>
<ide> if auth_header:
<del> self.headers['WWW-Authenticate'] = auth_header
<add> exc.auth_header = auth_header
<ide> else:
<ide> exc.status_code = status.HTTP_403_FORBIDDEN
<ide>
<del> if isinstance(exc, exceptions.APIException):
<del> return Response({'detail': exc.detail},
<del> status=exc.status_code,
<del> exception=True)
<del> elif isinstance(exc, Http404):
<del> return Response({'detail': 'Not found'},
<del> status=status.HTTP_404_NOT_FOUND,
<del> exception=True)
<del> elif isinstance(exc, PermissionDenied):
<del> return Response({'detail': 'Permission denied'},
<del> status=status.HTTP_403_FORBIDDEN,
<del> exception=True)
<del> raise
<add> response = exception_handler(exc)
<add>
<add> if response is None:
<add> raise
<add>
<add> response.exception = True
<add> return response
<ide>
<ide> # Note: session based authentication is explicitly CSRF validated,
<ide> # all other authentication is CSRF exempt. | 1 |
Mixed | Ruby | set precision 6 by default for datetime | c2a6f618d22cca4d9b7be7fa7652e7aac509350c | <ide><path>activerecord/CHANGELOG.md
<add>* Set precision 6 by default for `datetime` columns
<add>
<add> By default, datetime columns will have microseconds precision instead of seconds precision.
<add>
<add> *Roberto Miranda*
<add>
<ide> * Allow preloading of associations with instance dependent scopes
<ide>
<ide> *John Hawthorn*, *John Crepezzi*, *Adam Hess*, *Eileen M. Uchitelle*, *Dinah Shi*
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def column(name, type, index: nil, **options)
<ide> end
<ide> end
<ide>
<add> if @conn.supports_datetime_with_precision?
<add> if type == :datetime && !options.key?(:precision)
<add> options[:precision] = 6
<add> end
<add> end
<add>
<ide> @columns_hash[name] = new_column_definition(name, type, **options)
<ide>
<ide> if index
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def drop_table(table_name, **options)
<ide> def add_column(table_name, column_name, type, **options)
<ide> return if options[:if_not_exists] == true && column_exists?(table_name, column_name)
<ide>
<add> if supports_datetime_with_precision?
<add> if type == :datetime && !options.key?(:precision)
<add> options[:precision] = 6
<add> end
<add> end
<add>
<ide> at = create_alter_table table_name
<ide> at.add_column(column_name, type, **options)
<ide> execute schema_creation.accept at
<ide><path>activerecord/lib/active_record/migration/compatibility.rb
<ide> def timestamps(**options)
<ide> options[:null] = true if options[:null].nil?
<ide> super
<ide> end
<add>
<add> def column(name, type, index: nil, **options)
<add> options[:precision] ||= nil
<add> super
<add> end
<ide> end
<ide>
<ide> def add_reference(table_name, ref_name, **options)
<ide> def remove_index(table_name, column_name = nil, **options)
<ide> super
<ide> end
<ide>
<add> def add_column(table_name, column_name, type, **options)
<add> if type == :datetime
<add> options[:precision] ||= nil
<add> end
<add>
<add> super
<add> end
<add>
<ide> private
<ide> def compatible_table_definition(t)
<ide> class << t
<ide><path>activerecord/test/cases/adapters/postgresql/timestamp_test.rb
<ide> def test_adds_column_as_custom_type
<ide>
<ide> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:datetimes_as_enum] = { name: "custom_time_format" }
<ide> with_postgresql_datetime_type(:datetimes_as_enum) do
<del> ActiveRecord::Migration.new.add_column :postgresql_timestamp_with_zones, :times, :datetime
<add> ActiveRecord::Migration.new.add_column :postgresql_timestamp_with_zones, :times, :datetime, precision: nil
<ide>
<ide> assert_equal({ "data_type" => "USER-DEFINED", "udt_name" => "custom_time_format" },
<ide> PostgresqlTimestampWithZone.connection.execute("select data_type, udt_name from information_schema.columns where column_name = 'times'").to_a.first)
<ide><path>activerecord/test/cases/date_time_precision_test.rb
<ide> def test_datetime_precision_is_truncated_on_assignment
<ide> unless current_adapter?(:Mysql2Adapter)
<ide> def test_no_datetime_precision_isnt_truncated_on_assignment
<ide> @connection.create_table(:foos, force: true)
<del> @connection.add_column :foos, :created_at, :datetime
<del> @connection.add_column :foos, :updated_at, :datetime, precision: 6
<add> @connection.add_column :foos, :created_at, :datetime, precision: nil
<add> @connection.add_column :foos, :updated_at, :datetime
<ide>
<ide> time = ::Time.now.change(nsec: 123)
<ide> foo = Foo.new(created_at: time, updated_at: time)
<ide><path>activerecord/test/cases/defaults_test.rb
<ide> class PostgresqlDefaultExpressionTest < ActiveRecord::TestCase
<ide> output = dump_table_schema("defaults")
<ide> if ActiveRecord::Base.connection.database_version >= 100000
<ide> assert_match %r/t\.date\s+"modified_date",\s+default: -> { "CURRENT_DATE" }/, output
<del> assert_match %r/t\.datetime\s+"modified_time",\s+default: -> { "CURRENT_TIMESTAMP" }/, output
<add> assert_match %r/t\.datetime\s+"modified_time",\s+precision: 6,\s+default: -> { "CURRENT_TIMESTAMP" }/, output
<ide> else
<ide> assert_match %r/t\.date\s+"modified_date",\s+default: -> { "\('now'::text\)::date" }/, output
<del> assert_match %r/t\.datetime\s+"modified_time",\s+default: -> { "now\(\)" }/, output
<add> assert_match %r/t\.datetime\s+"modified_time",\s+precision: 6,\s+default: -> { "now\(\)" }/, output
<ide> end
<ide> assert_match %r/t\.date\s+"modified_date_function",\s+default: -> { "now\(\)" }/, output
<del> assert_match %r/t\.datetime\s+"modified_time_function",\s+default: -> { "now\(\)" }/, output
<add> assert_match %r/t\.datetime\s+"modified_time_function",\s+precision: 6,\s+default: -> { "now\(\)" }/, output
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/migration/change_schema_test.rb
<ide> def test_add_column_with_postgresql_datetime_type
<ide> assert_equal :datetime, column.type
<ide>
<ide> if current_adapter?(:PostgreSQLAdapter)
<del> assert_equal "timestamp without time zone", column.sql_type
<add> assert_equal "timestamp(6) without time zone", column.sql_type
<ide> elsif current_adapter?(:Mysql2Adapter)
<del> assert_equal "datetime", column.sql_type
<add> assert_equal "datetime(6)", column.sql_type
<ide> else
<del> assert_equal connection.type_to_sql("datetime"), column.sql_type
<add> assert_equal connection.type_to_sql("datetime(6)"), column.sql_type
<ide> end
<ide> end
<ide>
<ide> def test_add_column_with_datetime_in_timestamptz_mode
<ide> column = connection.columns(:testings).find { |c| c.name == "foo" }
<ide>
<ide> assert_equal :datetime, column.type
<del> assert_equal "timestamp with time zone", column.sql_type
<add> assert_equal "timestamp(6) with time zone", column.sql_type
<ide> end
<ide> end
<ide> end
<ide> def test_change_column_with_timestamp_type
<ide> elsif current_adapter?(:OracleAdapter)
<ide> assert_equal "TIMESTAMP(6)", column.sql_type
<ide> else
<del> assert_equal connection.type_to_sql("datetime"), column.sql_type
<add> assert_equal connection.type_to_sql("datetime(6)"), column.sql_type
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/compatibility_test.rb
<ide> def migrate(x)
<ide> assert connection.index_exists?(:testings, [:gizmo_type, :gizmo_id], name: :index_testings_on_gizmo_type_and_gizmo_id)
<ide> end
<ide>
<add> def test_datetime_doesnt_set_precision_on_create_table
<add> migration = Class.new(ActiveRecord::Migration[4.2]) {
<add> def migrate(x)
<add> create_table :more_testings do |t|
<add> t.datetime :published_at
<add> end
<add> end
<add> }.new
<add>
<add> ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate
<add>
<add> assert connection.column_exists?(:more_testings, :published_at, **precision_implicit_default)
<add> ensure
<add> connection.drop_table :more_testings rescue nil
<add> end
<add>
<add> def test_datetime_doesnt_set_precision_on_change_table
<add> create_migration = Class.new(ActiveRecord::Migration[4.2]) {
<add> def migrate(x)
<add> create_table :more_testings do |t|
<add> t.datetime :published_at
<add> end
<add> end
<add> }.new
<add>
<add> change_migration = Class.new(ActiveRecord::Migration[4.2]) {
<add> def migrate(x)
<add> change_table :more_testings do |t|
<add> t.datetime :published_at, default: Time.now
<add> end
<add> end
<add> }.new
<add>
<add> ActiveRecord::Migrator.new(:up, [create_migration, change_migration], @schema_migration).migrate
<add>
<add> assert connection.column_exists?(:more_testings, :published_at, **precision_implicit_default)
<add> ensure
<add> connection.drop_table :more_testings rescue nil
<add> end
<add>
<add> def test_datetime_doesnt_set_precision_on_add_column
<add> migration = Class.new(ActiveRecord::Migration[4.2]) {
<add> def migrate(x)
<add> add_column :testings, :published_at, :datetime, default: Time.now
<add> end
<add> }.new
<add>
<add> ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate
<add>
<add> assert connection.column_exists?(:testings, :published_at, **precision_implicit_default)
<add> end
<add>
<ide> private
<ide> def precision_implicit_default
<ide> if current_adapter?(:Mysql2Adapter)
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def test_schema_dump_defaults_with_universally_supported_types
<ide>
<ide> assert_match %r{t\.string\s+"string_with_default",.*?default: "Hello!"}, output
<ide> assert_match %r{t\.date\s+"date_with_default",\s+default: "2014-06-05"}, output
<del> assert_match %r{t\.datetime\s+"datetime_with_default",\s+default: "2014-06-05 07:17:04"}, output
<add> assert_match %r{t\.datetime\s+"datetime_with_default",\s+precision: 6,\s+default: "2014-06-05 07:17:04"}, output
<ide> assert_match %r{t\.time\s+"time_with_default",\s+default: "2000-01-01 07:17:04"}, output
<ide> assert_match %r{t\.decimal\s+"decimal_with_default",\s+precision: 20,\s+scale: 10,\s+default: "1234567890.0123456789"}, output
<ide> end
<ide> def test_schema_dump_with_column_infinity_default
<ide> output = dump_table_schema("infinity_defaults")
<ide> assert_match %r{t\.float\s+"float_with_inf_default",\s+default: ::Float::INFINITY}, output
<ide> assert_match %r{t\.float\s+"float_with_nan_default",\s+default: ::Float::NAN}, output
<del> assert_match %r{t\.datetime\s+"beginning_of_time",\s+default: -::Float::INFINITY}, output
<del> assert_match %r{t\.datetime\s+"end_of_time",\s+default: ::Float::INFINITY}, output
<add> assert_match %r{t\.datetime\s+"beginning_of_time",\s+precision: 6,\s+default: -::Float::INFINITY}, output
<add> assert_match %r{t\.datetime\s+"end_of_time",\s+precision: 6,\s+default: ::Float::INFINITY}, output
<ide> assert_match %r{t\.date\s+"date_with_neg_inf_default",\s+default: -::Float::INFINITY}, output
<ide> assert_match %r{t\.date\s+"date_with_pos_inf_default",\s+default: ::Float::INFINITY}, output
<ide> end
<ide><path>activerecord/test/schema/mysql2_specific_schema.rb
<ide> ActiveRecord::Schema.define do
<ide> if supports_datetime_with_precision?
<ide> create_table :datetime_defaults, force: true do |t|
<del> t.datetime :modified_datetime, default: -> { "CURRENT_TIMESTAMP" }
<del> t.datetime :precise_datetime, precision: 6, default: -> { "CURRENT_TIMESTAMP(6)" }
<add> t.datetime :modified_datetime, precision: nil, default: -> { "CURRENT_TIMESTAMP" }
<add> t.datetime :precise_datetime, default: -> { "CURRENT_TIMESTAMP(6)" }
<ide> end
<ide>
<ide> create_table :timestamp_defaults, force: true do |t|
<ide> t.timestamp :nullable_timestamp
<del> t.timestamp :modified_timestamp, default: -> { "CURRENT_TIMESTAMP" }
<add> t.timestamp :modified_timestamp, precision: nil, default: -> { "CURRENT_TIMESTAMP" }
<ide> t.timestamp :precise_timestamp, precision: 6, default: -> { "CURRENT_TIMESTAMP(6)" }
<ide> end
<ide> end | 11 |
Python | Python | add warning if neither pt nor tf are found | 4a21c4d88d13a966ebfdbd20c73a5a9a07be0a6a | <ide><path>examples/run_tf_glue.py
<ide>
<ide> # Compile tf.keras model for training
<ide> learning_rate = tf.keras.optimizers.schedules.PolynomialDecay(2e-5, 345, end_learning_rate=0)
<add>optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=1e-08, clipnorm=1.0)
<ide> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
<del>tf_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=1e-08, clipnorm=1.0),
<del> loss=loss, metrics=['sparse_categorical_accuracy'])
<add>tf_model.compile(optimizer=optimizer, loss=loss, metrics=['sparse_categorical_accuracy'])
<ide>
<ide> # Train and evaluate using tf.keras.Model.fit()
<del>tf_model.fit(train_dataset, epochs=3, steps_per_epoch=115, validation_data=valid_dataset, validation_steps=7)
<add>tf_model.fit(train_dataset, epochs=1, steps_per_epoch=115, validation_data=valid_dataset, validation_steps=7)
<ide>
<ide> # Save the model and load it in PyTorch
<ide> tf_model.save_pretrained('./runs/')
<ide><path>pytorch_transformers/__init__.py
<ide> load_tf2_checkpoint_in_pytorch_model,
<ide> load_tf2_weights_in_pytorch_model,
<ide> load_tf2_model_in_pytorch_model)
<add>
<add>if not is_tf_available() and not is_torch_available():
<add> logger.warning("Neither PyTorch nor TensorFlow >= 2.0 have been found."
<add> "Models won't be available and only tokenizers, configuration"
<add> "and file/data utilities can be used.") | 2 |
Python | Python | remove duplicate key 'c' in dictionary | 7f902d3f5b8279f247a70b78d40fb1110d6cae7c | <ide><path>glances/outputs/glances_curses.py
<ide> class _GlancesCurses(object):
<ide> 'm': {'auto_sort': False, 'sort_key': 'memory_percent'},
<ide> 'p': {'auto_sort': False, 'sort_key': 'name'},
<ide> 't': {'auto_sort': False, 'sort_key': 'cpu_times'},
<del> 'u': {'auto_sort': False, 'sort_key': 'username'},
<del> 'c': {'auto_sort': False, 'sort_key': 'cpu_percent'}
<add> 'u': {'auto_sort': False, 'sort_key': 'username'}
<ide> }
<ide>
<ide> def __init__(self, config=None, args=None): | 1 |
PHP | PHP | refactor the route finder | b25edfaf9bddb652d2bce07927a316d29a244653 | <ide><path>system/routing/finder.php
<ide> class Finder {
<ide> */
<ide> public static function find($name, $routes)
<ide> {
<del> if (array_key_exists($name, static::$names))
<del> {
<del> return static::$names[$name];
<del> }
<add> if (array_key_exists($name, static::$names)) return static::$names[$name];
<ide>
<ide> $arrayIterator = new \RecursiveArrayIterator($routes);
<ide> | 1 |
Javascript | Javascript | move latest firefox before firefox 60 test results | bc8aedf04210db9af519cdc1e947ee14f36934d6 | <ide><path>test/unit/support.js
<ide> testIframe(
<ide> "reliableMarginLeft": true,
<ide> "scrollboxSize": true
<ide> },
<del> firefox_60: {
<add> firefox: {
<ide> "ajax": true,
<ide> "boxSizingReliable": true,
<ide> "checkClone": true,
<ide> testIframe(
<ide> "pixelBoxStyles": true,
<ide> "pixelPosition": true,
<ide> "radioValue": true,
<del> "reliableMarginLeft": false,
<add> "reliableMarginLeft": true,
<ide> "scrollboxSize": true
<ide> },
<del> firefox: {
<add> firefox_60: {
<ide> "ajax": true,
<ide> "boxSizingReliable": true,
<ide> "checkClone": true,
<ide> testIframe(
<ide> "pixelBoxStyles": true,
<ide> "pixelPosition": true,
<ide> "radioValue": true,
<del> "reliableMarginLeft": true,
<add> "reliableMarginLeft": false,
<ide> "scrollboxSize": true
<ide> },
<ide> ios_11: { | 1 |
Java | Java | update copyright date for staxeventxmlreader | ff9b68c1b6b668e9da90dfff126149a53a052979 | <ide><path>spring-core/src/main/java/org/springframework/util/xml/StaxEventXMLReader.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. | 1 |
PHP | PHP | fix psalm error | e71fcd2787a139abd614813ffc6eaeb08c6bbb9a | <ide><path>src/Error/ExceptionRenderer.php
<ide> public function render(): ResponseInterface
<ide>
<ide> $isDebug = Configure::read('debug');
<ide> if ($isDebug) {
<del> $trace = Debugger::formatTrace($exception->getTrace(), [
<add> $trace = (array)Debugger::formatTrace($exception->getTrace(), [
<ide> 'format' => 'array',
<ide> 'args' => false,
<ide> ]); | 1 |
Go | Go | fix apparmor profile docker-default /proc/sys rule | 66f14e4ae9173f6fb7d1e4a7e13632297bdb8d29 | <ide><path>profiles/apparmor/template.go
<ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
<ide>
<ide> deny @{PROC}/* w, # deny write for all files directly in /proc (not in a subdir)
<ide> # deny write to files not in /proc/<number>/** or /proc/sys/**
<del> deny @{PROC}/{[^1-9],[^1-9][^0-9],[^1-9s][^0-9y][^0-9s],[^1-9][^0-9][^0-9][^0-9]*}/** w,
<add> deny @{PROC}/{[^1-9],[^1-9][^0-9],[^1-9s][^0-9y][^0-9s],[^1-9][^0-9][^0-9][^0-9/]*}/** w,
<ide> deny @{PROC}/sys/[^k]** w, # deny /proc/sys except /proc/sys/k* (effectively /proc/sys/kernel)
<ide> deny @{PROC}/sys/kernel/{?,??,[^s][^h][^m]**} w, # deny everything except shm* in /proc/sys/kernel/
<ide> deny @{PROC}/sysrq-trigger rwklx, | 1 |
PHP | PHP | add test for app folder for libraries support | 1454ea54a2a1c7789ce3e4853776ad529cbce1f2 | <ide><path>cake/tests/cases/libs/configure.test.php
<ide> function testClassLoading() {
<ide> }
<ide>
<ide> App::build(array(
<add> 'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
<ide> 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
<ide> ));
<ide>
<ide> function testClassLoading() {
<ide> $result = App::import('Lib', 'TestPlugin.TestPluginLibrary');
<ide> $this->assertTrue($result);
<ide> $this->assertTrue(class_exists('TestPluginLibrary'));
<del>
<add>
<add> $result = App::import('Lib', 'Library');
<add> $this->assertTrue($result);
<add> $this->assertTrue(class_exists('Library'));
<add>
<ide> $result = App::import('Helper', 'TestPlugin.OtherHelper');
<ide> $this->assertTrue($result);
<ide> $this->assertTrue(class_exists('OtherHelperHelper')); | 1 |
Go | Go | prefer netlink calls over ioctl | 6901ea51dc9f99b916bc189308543567cc72e1cb | <ide><path>libnetwork/drivers/bridge/bridge.go
<ide> func (d *driver) DeleteNetwork(nid types.UUID) error {
<ide> }
<ide>
<ide> func addToBridge(ifaceName, bridgeName string) error {
<del> iface, err := net.InterfaceByName(ifaceName)
<add> link, err := netlink.LinkByName(ifaceName)
<ide> if err != nil {
<ide> return fmt.Errorf("could not find interface %s: %v", ifaceName, err)
<ide> }
<add> if err = netlink.LinkSetMaster(link,
<add> &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: bridgeName}}); err != nil {
<add> logrus.Debugf("Failed to add %s to bridge via netlink.Trying ioctl: %v", ifaceName, err)
<add> iface, err := net.InterfaceByName(ifaceName)
<add> if err != nil {
<add> return fmt.Errorf("could not find network interface %s: %v", ifaceName, err)
<add> }
<ide>
<del> master, err := net.InterfaceByName(bridgeName)
<del> if err != nil {
<del> return fmt.Errorf("could not find bridge %s: %v", bridgeName, err)
<del> }
<add> master, err := net.InterfaceByName(bridgeName)
<add> if err != nil {
<add> return fmt.Errorf("could not find bridge %s: %v", bridgeName, err)
<add> }
<ide>
<del> return ioctlAddToBridge(iface, master)
<add> return ioctlAddToBridge(iface, master)
<add> }
<add> return nil
<ide> }
<ide>
<ide> func setHairpinMode(link netlink.Link, enable bool) error {
<ide><path>libnetwork/drivers/bridge/setup_device.go
<ide> package bridge
<ide>
<ide> import (
<add> "fmt"
<add>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<add> "github.com/docker/libnetwork/netutils"
<ide> "github.com/vishvananda/netlink"
<ide> )
<ide>
<ide> func setupDevice(config *networkConfiguration, i *bridgeInterface) error {
<ide> setMac = kv.Kernel > 3 || (kv.Kernel == 3 && kv.Major >= 3)
<ide> }
<ide>
<del> return ioctlCreateBridge(config.BridgeName, setMac)
<add> if err = netlink.LinkAdd(i.Link); err != nil {
<add> logrus.Debugf("Failed to create bridge %s via netlink. Trying ioctl", config.BridgeName)
<add> return ioctlCreateBridge(config.BridgeName, setMac)
<add> }
<add>
<add> if setMac {
<add> hwAddr := netutils.GenerateRandomMAC()
<add> if err = netlink.LinkSetHardwareAddr(i.Link, hwAddr); err != nil {
<add> return fmt.Errorf("failed to set bridge mac-address %s : %s", hwAddr, err.Error())
<add> }
<add> logrus.Debugf("Setting bridge mac address to %s", hwAddr)
<add> }
<add> return err
<ide> }
<ide>
<ide> // SetupDeviceUp ups the given bridge interface. | 2 |
Java | Java | remove outdated references to contextloaderservlet | 69998e3d507bcdc5c0b132cddeb4772e46cf8296 | <ide><path>spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java
<ide> *
<ide> * <p>Looks up the SessionFactory in Spring's root web application context.
<ide> * Supports a "sessionFactoryBeanName" filter init-param in {@code web.xml};
<del> * the default bean name is "sessionFactory". Looks up the SessionFactory on each
<del> * request, to avoid initialization order issues (when using ContextLoaderServlet,
<del> * the root application context will get initialized <i>after</i> this filter).
<add> * the default bean name is "sessionFactory".
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 3.1
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
<ide> *
<ide> * <p>Looks up the SessionFactory in Spring's root web application context.
<ide> * Supports a "sessionFactoryBeanName" filter init-param in {@code web.xml};
<del> * the default bean name is "sessionFactory". Looks up the SessionFactory on each
<del> * request, to avoid initialization order issues (when using ContextLoaderServlet,
<del> * the root application context will get initialized <i>after</i> this filter).
<add> * the default bean name is "sessionFactory".
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 1.2
<ide><path>spring-orm/src/main/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewFilter.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 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> *
<ide> * <p>Looks up the PersistenceManagerFactory in Spring's root web application context.
<ide> * Supports a "persistenceManagerFactoryBeanName" filter init-param in {@code web.xml};
<del> * the default bean name is "persistenceManagerFactory". Looks up the PersistenceManagerFactory
<del> * on each request, to avoid initialization order issues (when using ContextLoaderServlet,
<del> * the root application context will get initialized <i>after</i> this filter).
<add> * the default bean name is "persistenceManagerFactory".
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @since 1.1
<ide><path>spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java
<ide> public abstract class WebApplicationContextUtils {
<ide>
<ide>
<ide> /**
<del> * Find the root WebApplicationContext for this web application, which is
<del> * typically loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param sc ServletContext to find the web application context for
<ide> * @return the root WebApplicationContext for this web app
<ide> * @throws IllegalStateException if the root WebApplicationContext could not be found
<ide> * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
<ide> */
<del> public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
<del> throws IllegalStateException {
<del>
<add> public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc) throws IllegalStateException {
<ide> WebApplicationContext wac = getWebApplicationContext(sc);
<ide> if (wac == null) {
<ide> throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
<ide> public static WebApplicationContext getRequiredWebApplicationContext(ServletCont
<ide> }
<ide>
<ide> /**
<del> * Find the root WebApplicationContext for this web application, which is
<del> * typically loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param sc ServletContext to find the web application context for
<ide> public static WebApplicationContext getWebApplicationContext(ServletContext sc)
<ide> }
<ide>
<ide> /**
<del> * Find a custom WebApplicationContext for this web application.
<add> * Find a custom {@link WebApplicationContext} for this web app.
<ide> * @param sc ServletContext to find the web application context for
<ide> * @param attrName the name of the ServletContext attribute to look for
<ide> * @return the desired WebApplicationContext for this web app, or {@code null} if none
<ide> public static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf,
<ide> * Register web-specific environment beans ("contextParameters", "contextAttributes")
<ide> * with the given BeanFactory, as used by the WebApplicationContext.
<ide> * @param bf the BeanFactory to configure
<del> * @param sc the ServletContext that we're running within
<del> * @param config the ServletConfig of the containing Portlet
<add> * @param servletContext the ServletContext that we're running within
<add> * @param servletConfig the ServletConfig of the containing Portlet
<ide> */
<ide> public static void registerEnvironmentBeans(
<del> ConfigurableListableBeanFactory bf, ServletContext sc, ServletConfig config) {
<add> ConfigurableListableBeanFactory bf, ServletContext servletContext, ServletConfig servletConfig) {
<ide>
<del> if (sc != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
<del> bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, sc);
<add> if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
<add> bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext);
<ide> }
<ide>
<del> if (config != null && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) {
<del> bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, config);
<add> if (servletConfig != null && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) {
<add> bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, servletConfig);
<ide> }
<ide>
<ide> if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) {
<ide> Map<String, String> parameterMap = new HashMap<String, String>();
<del> if (sc != null) {
<del> Enumeration<?> paramNameEnum = sc.getInitParameterNames();
<add> if (servletContext != null) {
<add> Enumeration<?> paramNameEnum = servletContext.getInitParameterNames();
<ide> while (paramNameEnum.hasMoreElements()) {
<ide> String paramName = (String) paramNameEnum.nextElement();
<del> parameterMap.put(paramName, sc.getInitParameter(paramName));
<add> parameterMap.put(paramName, servletContext.getInitParameter(paramName));
<ide> }
<ide> }
<del> if (config != null) {
<del> Enumeration<?> paramNameEnum = config.getInitParameterNames();
<add> if (servletConfig != null) {
<add> Enumeration<?> paramNameEnum = servletConfig.getInitParameterNames();
<ide> while (paramNameEnum.hasMoreElements()) {
<ide> String paramName = (String) paramNameEnum.nextElement();
<del> parameterMap.put(paramName, config.getInitParameter(paramName));
<add> parameterMap.put(paramName, servletConfig.getInitParameter(paramName));
<ide> }
<ide> }
<ide> bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME,
<ide> public static void registerEnvironmentBeans(
<ide>
<ide> if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) {
<ide> Map<String, Object> attributeMap = new HashMap<String, Object>();
<del> if (sc != null) {
<del> Enumeration<?> attrNameEnum = sc.getAttributeNames();
<add> if (servletContext != null) {
<add> Enumeration<?> attrNameEnum = servletContext.getAttributeNames();
<ide> while (attrNameEnum.hasMoreElements()) {
<ide> String attrName = (String) attrNameEnum.nextElement();
<del> attributeMap.put(attrName, sc.getAttribute(attrName));
<add> attributeMap.put(attrName, servletContext.getAttribute(attrName));
<ide> }
<ide> }
<ide> bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME,
<ide> public static void registerEnvironmentBeans(
<ide> * {@link ServletConfig} parameter.
<ide> * @see #initServletPropertySources(MutablePropertySources, ServletContext, ServletConfig)
<ide> */
<del> public static void initServletPropertySources(
<del> MutablePropertySources propertySources, ServletContext servletContext) {
<del>
<add> public static void initServletPropertySources(MutablePropertySources propertySources, ServletContext servletContext) {
<ide> initServletPropertySources(propertySources, servletContext, null);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/jsf/FacesContextUtils.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 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> public abstract class FacesContextUtils {
<ide>
<ide> /**
<del> * Find the root {@link WebApplicationContext} for this web app,
<del> * typically loaded via ContextLoaderListener.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param fc the FacesContext to find the web application context for
<ide> public static WebApplicationContext getWebApplicationContext(FacesContext fc) {
<ide> }
<ide>
<ide> /**
<del> * Find the root {@link WebApplicationContext} for this web app,
<del> * typically loaded via ContextLoaderListener.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param fc the FacesContext to find the web application context for
<ide> * @return the root WebApplicationContext for this web app
<ide> * @throws IllegalStateException if the root WebApplicationContext could not be found
<ide> * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
<ide> */
<del> public static WebApplicationContext getRequiredWebApplicationContext(FacesContext fc)
<del> throws IllegalStateException {
<del>
<add> public static WebApplicationContext getRequiredWebApplicationContext(FacesContext fc) throws IllegalStateException {
<ide> WebApplicationContext wac = getWebApplicationContext(fc);
<ide> if (wac == null) {
<ide> throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/MultipartFilter.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 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> *
<ide> * <p>Looks up the MultipartResolver in Spring's root web application context.
<ide> * Supports a "multipartResolverBeanName" filter init-param in {@code web.xml};
<del> * the default bean name is "filterMultipartResolver". Looks up the MultipartResolver
<del> * on each request, to avoid initialization order issues (when using ContextLoaderServlet,
<del> * the root application context will get initialized <i>after</i> this filter).
<add> * the default bean name is "filterMultipartResolver".
<ide> *
<ide> * <p>If no MultipartResolver bean is found, this filter falls back to a default
<ide> * MultipartResolver: {@link StandardServletMultipartResolver} for Servlet 3.0,
<ide> protected void doFilterInternal(
<ide> processedRequest = multipartResolver.resolveMultipart(processedRequest);
<ide> }
<ide> else {
<add> // A regular request...
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Request [" + processedRequest.getRequestURI() + "] is not a multipart request");
<ide> }
<ide><path>spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java
<ide> public abstract class PortletApplicationContextUtils {
<ide>
<ide> /**
<del> * Find the root WebApplicationContext for this portlet application, which is
<del> * typically loaded via ContextLoaderListener or ContextLoaderServlet.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param pc PortletContext to find the web application context for
<ide> public static ApplicationContext getWebApplicationContext(PortletContext pc) {
<ide> }
<ide>
<ide> /**
<del> * Find the root WebApplicationContext for this portlet application, which is
<del> * typically loaded via ContextLoaderListener or ContextLoaderServlet.
<add> * Find the root {@link WebApplicationContext} for this web app, typically
<add> * loaded via {@link org.springframework.web.context.ContextLoaderListener}.
<ide> * <p>Will rethrow an exception that happened on root context startup,
<ide> * to differentiate between a failed context startup and no context at all.
<ide> * @param pc PortletContext to find the web application context for
<ide> public static ApplicationContext getWebApplicationContext(PortletContext pc) {
<ide> * @throws IllegalStateException if the root WebApplicationContext could not be found
<ide> * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
<ide> */
<del> public static ApplicationContext getRequiredWebApplicationContext(PortletContext pc)
<del> throws IllegalStateException {
<del>
<add> public static ApplicationContext getRequiredWebApplicationContext(PortletContext pc) throws IllegalStateException {
<ide> ApplicationContext wac = getWebApplicationContext(pc);
<ide> if (wac == null) {
<ide> throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
<ide> public static ApplicationContext getRequiredWebApplicationContext(PortletContext
<ide> /**
<ide> * Register web-specific scopes ("request", "session", "globalSession")
<ide> * with the given BeanFactory, as used by the Portlet ApplicationContext.
<del> * @param beanFactory the BeanFactory to configure
<add> * @param bf the BeanFactory to configure
<ide> * @param pc the PortletContext that we're running within
<ide> */
<del> static void registerPortletApplicationScopes(ConfigurableListableBeanFactory beanFactory, PortletContext pc) {
<del> beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
<del> beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false));
<del> beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true));
<add> static void registerPortletApplicationScopes(ConfigurableListableBeanFactory bf, PortletContext pc) {
<add> bf.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
<add> bf.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false));
<add> bf.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true));
<ide> if (pc != null) {
<ide> PortletContextScope appScope = new PortletContextScope(pc);
<del> beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
<add> bf.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
<ide> // Register as PortletContext attribute, for ContextCleanupListener to detect it.
<ide> pc.setAttribute(PortletContextScope.class.getName(), appScope);
<ide> }
<ide>
<del> beanFactory.registerResolvableDependency(PortletRequest.class, new RequestObjectFactory());
<del> beanFactory.registerResolvableDependency(PortletResponse.class, new ResponseObjectFactory());
<del> beanFactory.registerResolvableDependency(PortletSession.class, new SessionObjectFactory());
<del> beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
<add> bf.registerResolvableDependency(PortletRequest.class, new RequestObjectFactory());
<add> bf.registerResolvableDependency(PortletResponse.class, new ResponseObjectFactory());
<add> bf.registerResolvableDependency(PortletSession.class, new SessionObjectFactory());
<add> bf.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
<ide> }
<ide>
<ide> /**
<ide> * Register web-specific environment beans ("contextParameters", "contextAttributes")
<ide> * with the given BeanFactory, as used by the Portlet ApplicationContext.
<ide> * @param bf the BeanFactory to configure
<del> * @param sc the ServletContext that we're running within
<del> * @param pc the PortletContext that we're running within
<del> * @param config the PortletConfig of the containing Portlet
<add> * @param servletContext the ServletContext that we're running within
<add> * @param portletContext the PortletContext that we're running within
<add> * @param portletConfig the PortletConfig of the containing Portlet
<ide> */
<del> static void registerEnvironmentBeans(
<del> ConfigurableListableBeanFactory bf, ServletContext sc, PortletContext pc, PortletConfig config) {
<add> static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, ServletContext servletContext,
<add> PortletContext portletContext, PortletConfig portletConfig) {
<ide>
<del> if (sc != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
<del> bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, sc);
<add> if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
<add> bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext);
<ide> }
<ide>
<del> if (pc != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME)) {
<del> bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME, pc);
<add> if (portletContext != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME)) {
<add> bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME, portletContext);
<ide> }
<ide>
<del> if (config != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME)) {
<del> bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME, config);
<add> if (portletConfig != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME)) {
<add> bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME, portletConfig);
<ide> }
<ide>
<ide> if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) {
<ide> Map<String, String> parameterMap = new HashMap<String, String>();
<del> if (pc != null) {
<del> Enumeration<String> paramNameEnum = pc.getInitParameterNames();
<add> if (portletContext != null) {
<add> Enumeration<String> paramNameEnum = portletContext.getInitParameterNames();
<ide> while (paramNameEnum.hasMoreElements()) {
<ide> String paramName = paramNameEnum.nextElement();
<del> parameterMap.put(paramName, pc.getInitParameter(paramName));
<add> parameterMap.put(paramName, portletContext.getInitParameter(paramName));
<ide> }
<ide> }
<del> if (config != null) {
<del> Enumeration<String> paramNameEnum = config.getInitParameterNames();
<add> if (portletConfig != null) {
<add> Enumeration<String> paramNameEnum = portletConfig.getInitParameterNames();
<ide> while (paramNameEnum.hasMoreElements()) {
<ide> String paramName = paramNameEnum.nextElement();
<del> parameterMap.put(paramName, config.getInitParameter(paramName));
<add> parameterMap.put(paramName, portletConfig.getInitParameter(paramName));
<ide> }
<ide> }
<ide> bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME,
<ide> static void registerEnvironmentBeans(
<ide>
<ide> if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) {
<ide> Map<String, Object> attributeMap = new HashMap<String, Object>();
<del> if (pc != null) {
<del> Enumeration<String> attrNameEnum = pc.getAttributeNames();
<add> if (portletContext != null) {
<add> Enumeration<String> attrNameEnum = portletContext.getAttributeNames();
<ide> while (attrNameEnum.hasMoreElements()) {
<ide> String attrName = attrNameEnum.nextElement();
<del> attributeMap.put(attrName, pc.getAttribute(attrName));
<add> attributeMap.put(attrName, portletContext.getAttribute(attrName));
<ide> }
<ide> }
<ide> bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, | 7 |
Javascript | Javascript | use services where possible | 4994faa3c103a9672cdd48c7838d5073ddc86a48 | <ide><path>extensions/firefox/components/PdfStreamConverter.js
<ide> Cu.import('resource://gre/modules/Services.jsm');
<ide>
<ide> function log(aMsg) {
<ide> let msg = 'PdfStreamConverter.js: ' + (aMsg.join ? aMsg.join('') : aMsg);
<del> Cc['@mozilla.org/consoleservice;1'].getService(Ci.nsIConsoleService)
<del> .logStringMessage(msg);
<add> Services.console.logStringMessage(msg);
<ide> dump(msg + '\n');
<ide> }
<ide> let application = Cc['@mozilla.org/fuel/application;1']
<ide> PdfStreamConverter.prototype = {
<ide> aRequest.cancel(Cr.NS_BINDING_ABORTED);
<ide>
<ide> // Create a new channel that is viewer loaded as a resource.
<del> var ioService = Cc['@mozilla.org/network/io-service;1']
<del> .getService(Ci.nsIIOService);
<add> var ioService = Services.io;
<ide> var channel = ioService.newChannel(
<ide> 'resource://pdf.js/web/viewer.html', null, null);
<ide> | 1 |
Javascript | Javascript | use branchpattern to check tag | 9e4d42cafb2070530a8f4ee96fce5f3b5f869f96 | <ide><path>lib/versions/version-info.js
<ide> function getBuild() {
<ide> return 'sha.' + hash;
<ide> }
<ide>
<add>function checkBranchPattern(version, branchPattern) {
<add> // check that the version starts with the branch pattern minus its asterisk
<add> // e.g. branchPattern = '1.6.*'; version = '1.6.0-rc.0' => '1.6.' === '1.6.'
<add> return version.slice(0, branchPattern.length - 1) === branchPattern.replace('*', '');
<add>}
<ide>
<ide> /**
<ide> * If the current commit is tagged as a version get that version
<ide> var getTaggedVersion = function() {
<ide> var tag = gitTagResult.output.trim();
<ide> var version = semver.parse(tag);
<ide>
<del> if (version && semver.satisfies(version, currentPackage.branchVersion)) {
<add> if (version && checkBranchPattern(version, currentPackage.branchPattern)) {
<ide> version.codeName = getCodeName(tag);
<ide> version.full = version.version;
<ide> version.branch = 'v' + currentPackage.branchPattern.replace('*', 'x'); | 1 |
Javascript | Javascript | enforce nodecache validity | d93761af6253aa994660eb04be9313cddc920844 | <ide><path>src/core/ReactID.js
<ide>
<ide> "use strict";
<ide>
<add>var invariant = require('invariant');
<ide> var ReactMount = require('ReactMount');
<ide> var ATTR_NAME = 'id';
<ide> var nodeCache = {};
<ide> var nodeCache = {};
<ide> * @return {string} ID of the supplied `domNode`.
<ide> */
<ide> function getID(node) {
<del> if (node && node.getAttributeNode) {
<del> var attributeNode = node.getAttributeNode(ATTR_NAME);
<del> if (attributeNode) {
<del> var id = attributeNode.value;
<del> if (id) {
<del> // Assume that any node previously cached with this ID has since
<del> // become invalid and should be replaced. TODO Enforce this.
<del> nodeCache[id] = node;
<add> var id = internalGetID(node);
<add> if (id) {
<add> if (nodeCache.hasOwnProperty(id)) {
<add> var cached = nodeCache[id];
<add> if (cached !== node) {
<add> invariant(
<add> !isValid(cached, id),
<add> 'ReactID: Two valid but unequal nodes with the same `%s`: %s',
<add> ATTR_NAME, id
<add> );
<ide>
<del> return id;
<add> nodeCache[id] = node;
<ide> }
<add> } else {
<add> nodeCache[id] = node;
<ide> }
<ide> }
<ide>
<add> return id;
<add>}
<add>
<add>function internalGetID(node) {
<add> if (node && node.getAttributeNode) {
<add> var attributeNode = node.getAttributeNode(ATTR_NAME);
<add> if (attributeNode) {
<add> return attributeNode.value || '';
<add> }
<add> }
<ide> return '';
<ide> }
<ide>
<ide> function getID(node) {
<ide> * @param {string} id The value of the ID attribute.
<ide> */
<ide> function setID(node, id) {
<del> var oldID = getID(node);
<add> var oldID = internalGetID(node);
<ide> if (oldID !== id) {
<ide> delete nodeCache[oldID];
<ide> }
<ide> function setID(node, id) {
<ide> * @internal
<ide> */
<ide> function getNode(id) {
<del> if (!nodeCache[id]) {
<del> nodeCache[id] =
<del> document.getElementById(id) || // TODO Quit using getElementById.
<del> ReactMount.findReactRenderedDOMNodeSlow(id);
<add> if (nodeCache.hasOwnProperty(id)) {
<add> var node = nodeCache[id];
<add> if (isValid(node, id)) {
<add> return node;
<add> }
<add> }
<add>
<add> return nodeCache[id] =
<add> document.getElementById(id) || // TODO Quit using getElementById.
<add> ReactMount.findReactRenderedDOMNodeSlow(id);
<add>}
<add>
<add>/**
<add> * A node is "valid" if it is contained by a currently mounted container.
<add> *
<add> * This means that the node does not have to be contained by a document in
<add> * order to be considered valid.
<add> *
<add> * @param {?DOMElement} node The candidate DOM node.
<add> * @param {string} id The expected ID of the node.
<add> * @return {boolean} Whether the node is contained by a mounted container.
<add> */
<add>function isValid(node, id) {
<add> if (node) {
<add> invariant(
<add> internalGetID(node) === id,
<add> 'ReactID: Unexpected modification of `%s`',
<add> ATTR_NAME
<add> );
<add>
<add> var container = ReactMount.findReactContainerForID(id);
<add> if (container && contains(container, node)) {
<add> return true;
<add> }
<add> }
<add>
<add> return false;
<add>}
<add>
<add>function contains(ancestor, descendant) {
<add> if (ancestor.contains) {
<add> // Supported natively in virtually all browsers, but not in jsdom.
<add> return ancestor.contains(descendant);
<add> }
<add>
<add> if (descendant === ancestor) {
<add> return true;
<add> }
<add>
<add> if (descendant.nodeType === 3) {
<add> // If descendant is a text node, start from descendant.parentNode
<add> // instead, so that we can assume all ancestors worth considering are
<add> // element nodes with nodeType === 1.
<add> descendant = descendant.parentNode;
<ide> }
<ide>
<del> var node = nodeCache[id];
<del> if (getID(node) === id) {
<del> return node;
<add> while (descendant && descendant.nodeType === 1) {
<add> if (descendant === ancestor) {
<add> return true;
<add> }
<add> descendant = descendant.parentNode;
<ide> }
<ide>
<del> return null;
<add> return false;
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix resource path | aaf6d5b393beffacadd0dc1951c952c7bf116c8e | <ide><path>src/Illuminate/Exception/ExceptionServiceProvider.php
<ide> protected function shouldReturnJson()
<ide> protected function registerPrettyWhoopsHandler()
<ide> {
<ide> $me = $this;
<del>
<add>
<ide> $this->app['whoops.handler'] = $this->app->share(function() use ($me)
<ide> {
<ide> with($handler = new PrettyPageHandler)->setEditor('sublime');
<ide> public function resourcePath()
<ide> */
<ide> protected function getResourcePath()
<ide> {
<del> return __DIR__.'/resources';
<add> $base = $this->app['path.base'];
<add>
<add> return $base.'/vendor/laravel/framework/src/Illuminate/Exception/resources';
<ide> }
<ide>
<ide> } | 1 |
Python | Python | use list to be safe | a5973c71c989c20c75c123896bef33b3eeefc327 | <ide><path>airflow/operators/hive_stats_operator.py
<ide> def execute(self, context=None):
<ide> exprs = {
<ide> ('', 'count'): 'COUNT(*)'
<ide> }
<del> for col, col_type in field_types.items():
<add> for col, col_type in list(field_types.items()):
<ide> d = {}
<ide> if self.assignment_func:
<ide> d = self.assignment_func(col, col_type) | 1 |
Ruby | Ruby | fix typo in documentation examples | b2ed0b768d4e753cf756df6361986ee823b99054 | <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb
<ide> def image_tag(source, options = {})
<ide> # Active Storage blobs (videos that are uploaded by the users of your app):
<ide> #
<ide> # video_tag(user.intro_video)
<del> # # => <img src="/rails/active_storage/blobs/.../intro_video.mp4" />
<add> # # => <video src="/rails/active_storage/blobs/.../intro_video.mp4"></video>
<ide> def video_tag(*sources)
<ide> options = sources.extract_options!.symbolize_keys
<ide> public_poster_folder = options.delete(:poster_skip_pipeline)
<ide> def video_tag(*sources)
<ide> # Active Storage blobs (audios that are uploaded by the users of your app):
<ide> #
<ide> # audio_tag(user.name_pronunciation_audio)
<del> # # => <img src="/rails/active_storage/blobs/.../name_pronunciation_audio.mp4" />
<add> # # => <audio src="/rails/active_storage/blobs/.../name_pronunciation_audio.mp3"></audio>
<ide> def audio_tag(*sources)
<ide> multiple_sources_tag_builder("audio", sources)
<ide> end | 1 |
Javascript | Javascript | add separator example | cc8ea72f3a9375deab4182eb35d615dd9a6eec7f | <ide><path>src/ng/directive/ngSwitch.js
<ide> <hr/>
<ide> <div class="animate-switch-container"
<ide> ng-switch on="selection">
<del> <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<add> <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
<ide> <div class="animate-switch" ng-switch-when="home">Home Span</div>
<ide> <div class="animate-switch" ng-switch-default>default</div>
<ide> </div>
<ide> <file name="script.js">
<ide> angular.module('switchExample', ['ngAnimate'])
<ide> .controller('ExampleController', ['$scope', function($scope) {
<del> $scope.items = ['settings', 'home', 'other'];
<add> $scope.items = ['settings', 'home', 'options', 'other'];
<ide> $scope.selection = $scope.items[0];
<ide> }]);
<ide> </file>
<ide> select.all(by.css('option')).get(1).click();
<ide> expect(switchElem.getText()).toMatch(/Home Span/);
<ide> });
<del> it('should select default', function() {
<add> it('should change to settings via "options"', function() {
<ide> select.all(by.css('option')).get(2).click();
<add> expect(switchElem.getText()).toMatch(/Settings Div/);
<add> });
<add> it('should select default', function() {
<add> select.all(by.css('option')).get(3).click();
<ide> expect(switchElem.getText()).toMatch(/default/);
<ide> });
<ide> </file> | 1 |
Ruby | Ruby | eliminate unnecessary flatten | 887434f75fc0a207ac7184debcd3074802758952 | <ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> def transfer_time_values_to_utc_constructor(time)
<ide> end
<ide>
<ide> def duration_of_variable_length?(obj)
<del> ActiveSupport::Duration === obj && obj.parts.flatten.any? {|p| [:years, :months, :days].include? p }
<add> ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include? p[0] }
<ide> end
<ide> end
<ide> end | 1 |
Go | Go | update secret inspect to support ids | 70d2cefd51e853ca4f3bbf8eb0386360809e026b | <ide><path>cli/command/secret/inspect.go
<ide> import (
<ide> )
<ide>
<ide> type inspectOptions struct {
<del> name string
<add> names []string
<ide> format string
<ide> }
<ide>
<ide> func newSecretInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> opts := inspectOptions{}
<ide> cmd := &cobra.Command{
<del> Use: "inspect [name]",
<add> Use: "inspect SECRET [SECRET]",
<ide> Short: "Inspect a secret",
<del> Args: cli.ExactArgs(1),
<add> Args: cli.RequiresMinArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<del> opts.name = args[0]
<add> opts.names = args
<ide> return runSecretInspect(dockerCli, opts)
<ide> },
<ide> }
<ide> func runSecretInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
<ide> client := dockerCli.Client()
<ide> ctx := context.Background()
<ide>
<del> // attempt to lookup secret by name
<del> secrets, err := getSecretsByName(ctx, client, []string{opts.name})
<add> ids, err := getCliRequestedSecretIDs(ctx, client, opts.names)
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<del> id := opts.name
<del> for _, s := range secrets {
<del> if s.Spec.Annotations.Name == opts.name {
<del> id = s.ID
<del> break
<del> }
<del> }
<del>
<del> getRef := func(name string) (interface{}, []byte, error) {
<add> getRef := func(id string) (interface{}, []byte, error) {
<ide> return client.SecretInspectWithRaw(ctx, id)
<ide> }
<ide>
<del> return inspect.Inspect(dockerCli.Out(), []string{id}, opts.format, getRef)
<add> return inspect.Inspect(dockerCli.Out(), ids, opts.format, getRef)
<ide> }
<ide><path>cli/command/secret/remove.go
<ide> import (
<ide> )
<ide>
<ide> type removeOptions struct {
<del> ids []string
<add> names []string
<ide> }
<ide>
<ide> func newSecretRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> return &cobra.Command{
<del> Use: "rm [id]",
<add> Use: "rm SECRET [SECRET]",
<ide> Short: "Remove a secret",
<ide> Args: cli.RequiresMinArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide> opts := removeOptions{
<del> ids: args,
<add> names: args,
<ide> }
<ide> return runSecretRemove(dockerCli, opts)
<ide> },
<ide> func runSecretRemove(dockerCli *command.DockerCli, opts removeOptions) error {
<ide> client := dockerCli.Client()
<ide> ctx := context.Background()
<ide>
<del> // attempt to lookup secret by name
<del> secrets, err := getSecretsByName(ctx, client, opts.ids)
<add> ids, err := getCliRequestedSecretIDs(ctx, client, opts.names)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> ids := opts.ids
<del>
<del> names := make(map[string]int)
<del> for _, id := range ids {
<del> names[id] = 1
<del> }
<del>
<del> if len(secrets) > 0 {
<del> ids = []string{}
<del>
<del> for _, s := range secrets {
<del> if _, ok := names[s.Spec.Annotations.Name]; ok {
<del> ids = append(ids, s.ID)
<del> }
<del> }
<del> }
<del>
<ide> for _, id := range ids {
<ide> if err := client.SecretRemove(ctx, id); err != nil {
<del> return err
<add> fmt.Fprintf(dockerCli.Out(), "WARN: %s\n", err)
<ide> }
<ide>
<ide> fmt.Fprintln(dockerCli.Out(), id)
<ide><path>cli/command/secret/utils.go
<ide> func getSecretsByName(ctx context.Context, client client.APIClient, names []stri
<ide> Filters: args,
<ide> })
<ide> }
<add>
<add>func getCliRequestedSecretIDs(ctx context.Context, client client.APIClient, names []string) ([]string, error) {
<add> ids := names
<add>
<add> // attempt to lookup secret by name
<add> secrets, err := getSecretsByName(ctx, client, ids)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> lookup := make(map[string]struct{})
<add> for _, id := range ids {
<add> lookup[id] = struct{}{}
<add> }
<add>
<add> if len(secrets) > 0 {
<add> ids = []string{}
<add>
<add> for _, s := range secrets {
<add> if _, ok := lookup[s.Spec.Annotations.Name]; ok {
<add> ids = append(ids, s.ID)
<add> }
<add> }
<add> }
<add>
<add> return ids, nil
<add>}
<ide><path>integration-cli/docker_cli_secret_inspect_test.go
<add>// +build !windows
<add>
<add>package main
<add>
<add>import (
<add> "encoding/json"
<add>
<add> "github.com/docker/docker/api/types/swarm"
<add> "github.com/docker/docker/pkg/integration/checker"
<add> "github.com/go-check/check"
<add>)
<add>
<add>func (s *DockerSwarmSuite) TestSecretInspect(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> testName := "test_secret"
<add> id := d.createSecret(c, swarm.SecretSpec{
<add> swarm.Annotations{
<add> Name: testName,
<add> },
<add> []byte("TESTINGDATA"),
<add> })
<add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<add>
<add> secret := d.getSecret(c, id)
<add> c.Assert(secret.Spec.Name, checker.Equals, testName)
<add>
<add> out, err := d.Cmd("secret", "inspect", testName)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> var secrets []swarm.Secret
<add> c.Assert(json.Unmarshal([]byte(out), &secrets), checker.IsNil)
<add> c.Assert(secrets, checker.HasLen, 1)
<add>}
<add>
<add>func (s *DockerSwarmSuite) TestSecretInspectMultiple(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> testNames := []string{
<add> "test0",
<add> "test1",
<add> }
<add> for _, n := range testNames {
<add> id := d.createSecret(c, swarm.SecretSpec{
<add> swarm.Annotations{
<add> Name: n,
<add> },
<add> []byte("TESTINGDATA"),
<add> })
<add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<add>
<add> secret := d.getSecret(c, id)
<add> c.Assert(secret.Spec.Name, checker.Equals, n)
<add>
<add> }
<add>
<add> args := []string{
<add> "secret",
<add> "inspect",
<add> }
<add> args = append(args, testNames...)
<add> out, err := d.Cmd(args...)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> var secrets []swarm.Secret
<add> c.Assert(json.Unmarshal([]byte(out), &secrets), checker.IsNil)
<add> c.Assert(secrets, checker.HasLen, 2)
<add>} | 4 |
Javascript | Javascript | improve jsonp tests | cd546aba748aeac09886921ebc1a5fcaa3778bf8 | <ide><path>test/unit/ajax.js
<ide> module( "ajax", {
<ide> jsonpCallback: "functionToCleanUp",
<ide> success: function( data ) {
<ide> ok( data["data"], "JSON results returned (GET, custom callback name to be cleaned up)" );
<del> strictEqual( window["functionToCleanUp"], undefined, "Callback was removed (GET, custom callback name to be cleaned up)" );
<add> strictEqual( window["functionToCleanUp"], true, "Callback was removed (GET, custom callback name to be cleaned up)" );
<ide> var xhr;
<ide> jQuery.ajax({
<ide> url: "data/jsonp.php",
<ide> module( "ajax", {
<ide> });
<ide> xhr.fail(function() {
<ide> ok( true, "Ajax error JSON (GET, custom callback name to be cleaned up)" );
<del> strictEqual( window["functionToCleanUp"], undefined, "Callback was removed after early abort (GET, custom callback name to be cleaned up)" );
<add> strictEqual( window["functionToCleanUp"], true, "Callback was removed after early abort (GET, custom callback name to be cleaned up)" );
<ide> });
<ide> }
<ide> }, { | 1 |
Go | Go | remove channel close | 010951083060e1267e4dd726f5322d7309a8fd62 | <ide><path>integration-cli/events_utils.go
<ide> func matchEventLine(id, eventType string, actions map[string]chan bool) eventMat
<ide> func processEventMatch(actions map[string]chan bool) eventMatchProcessor {
<ide> return func(matches map[string]string) {
<ide> if ch, ok := actions[matches["action"]]; ok {
<del> close(ch)
<add> ch <- true
<ide> }
<ide> }
<ide> } | 1 |
Ruby | Ruby | use parser to parse args | 39a6f7f83f7c33d4b0367fb3d1cd2d71801167e0 | <ide><path>Library/Homebrew/dev-cmd/linkage.rb
<ide>
<ide> require "cache_store"
<ide> require "linkage_checker"
<add>require "cli_parser"
<ide>
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def linkage
<add> Homebrew::CLI::Parser.parse do
<add> switch "--test"
<add> switch "--reverse"
<add> switch "--cached"
<add> switch :verbose
<add> switch :debug
<add> end
<add>
<ide> CacheStoreDatabase.use(:linkage) do |db|
<ide> ARGV.kegs.each do |keg|
<ide> ohai "Checking #{keg.name} linkage" if ARGV.kegs.size > 1
<ide>
<del> use_cache = ARGV.include?("--cached") || ENV["HOMEBREW_LINKAGE_CACHE"]
<add> use_cache = args.cached? || ENV["HOMEBREW_LINKAGE_CACHE"]
<ide> result = LinkageChecker.new(keg, use_cache: use_cache, cache_db: db)
<ide>
<del> if ARGV.include?("--test")
<add> if args.test?
<ide> result.display_test_output
<ide> Homebrew.failed = true if result.broken_library_linkage?
<del> elsif ARGV.include?("--reverse")
<add> elsif args.reverse?
<ide> result.display_reverse_output
<ide> else
<ide> result.display_normal_output | 1 |
PHP | PHP | update builder.php | 40104bac79e74aeea5b2b5479de3d9430198899a | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function where($column, $operator = null, $value = null, $boolean = 'and'
<ide> * @param mixed $operator
<ide> * @param mixed $value
<ide> * @param string $boolean
<del> * @return \Illuminate\Database\Eloquent\Model|static
<add> * @return \Illuminate\Database\Eloquent\Model|static|null
<ide> */
<ide> public function firstWhere($column, $operator = null, $value = null, $boolean = 'and')
<ide> { | 1 |
Java | Java | reimplement the elementat operator | 25555b4f6f9e83acaf6e0f169b6041975718e7d3 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.operators.OperationDematerialize;
<ide> import rx.operators.OperationDistinct;
<ide> import rx.operators.OperationDistinctUntilChanged;
<del>import rx.operators.OperationElementAt;
<add>import rx.operators.OperatorElementAt;
<ide> import rx.operators.OperationFinally;
<ide> import rx.operators.OperationFlatMap;
<ide> import rx.operators.OperationGroupByUntil;
<ide> public final void onNext(T args) {
<ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementat">RxJava Wiki: elementAt()</a>
<ide> */
<ide> public final Observable<T> elementAt(int index) {
<del> return create(OperationElementAt.elementAt(this, index));
<add> return create(new OperatorElementAt<T>(this, index));
<ide> }
<ide>
<ide> /**
<ide> public final Observable<T> elementAt(int index) {
<ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementatordefault">RxJava Wiki: elementAtOrDefault()</a>
<ide> */
<ide> public final Observable<T> elementAtOrDefault(int index, T defaultValue) {
<del> return create(OperationElementAt.elementAtOrDefault(this, index, defaultValue));
<add> return create(new OperatorElementAt<T>(this, index, defaultValue));
<ide> }
<ide>
<ide> /**
<ide><path>rxjava-core/src/main/java/rx/operators/OperationElementAt.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx.operators;
<del>
<del>import java.util.concurrent.atomic.AtomicInteger;
<del>
<del>import rx.Observable;
<del>import rx.Observable.OnSubscribeFunc;
<del>import rx.Observer;
<del>import rx.Subscription;
<del>
<del>/**
<del> * Returns the element at a specified index in a sequence.
<del> */
<del>public class OperationElementAt {
<del>
<del> /**
<del> * Returns the element at a specified index in a sequence.
<del> *
<del> * @param source
<del> * Observable sequence to return the element from.
<del> * @param index
<del> * The zero-based index of the element to retrieve.
<del> *
<del> * @return An observable sequence that produces the element at the specified
<del> * position in the source sequence.
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * Index is greater than or equal to the number of elements in
<del> * the source sequence.
<del> * @throws IndexOutOfBoundsException
<del> * Index is less than 0.
<del> */
<del> public static <T> OnSubscribeFunc<T> elementAt(Observable<? extends T> source, int index) {
<del> return new ElementAt<T>(source, index, null, false);
<del> }
<del>
<del> /**
<del> * Returns the element at a specified index in a sequence or the default
<del> * value if the index is out of range.
<del> *
<del> * @param source
<del> * Observable sequence to return the element from.
<del> * @param index
<del> * The zero-based index of the element to retrieve.
<del> * @param defaultValue
<del> * The default value.
<del> *
<del> * @return An observable sequence that produces the element at the specified
<del> * position in the source sequence, or the default value if the
<del> * index is outside the bounds of the source sequence.
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * Index is less than 0.
<del> */
<del> public static <T> OnSubscribeFunc<T> elementAtOrDefault(Observable<? extends T> source, int index, T defaultValue) {
<del> return new ElementAt<T>(source, index, defaultValue, true);
<del> }
<del>
<del> private static class ElementAt<T> implements OnSubscribeFunc<T> {
<del>
<del> private final Observable<? extends T> source;
<del> private final int index;
<del> private final boolean hasDefault;
<del> private final T defaultValue;
<del>
<del> private ElementAt(Observable<? extends T> source, int index,
<del> T defaultValue, boolean hasDefault) {
<del> this.source = source;
<del> this.index = index;
<del> this.defaultValue = defaultValue;
<del> this.hasDefault = hasDefault;
<del> }
<del>
<del> @Override
<del> public Subscription onSubscribe(final Observer<? super T> observer) {
<del> final SafeObservableSubscription subscription = new SafeObservableSubscription();
<del> return subscription.wrap(source.subscribe(new Observer<T>() {
<del>
<del> private AtomicInteger counter = new AtomicInteger();
<del>
<del> @Override
<del> public void onNext(T value) {
<del> try {
<del> int currentIndex = counter.getAndIncrement();
<del> if (currentIndex == index) {
<del> observer.onNext(value);
<del> observer.onCompleted();
<del> } else if (currentIndex > index) {
<del> // this will work if the sequence is asynchronous,
<del> // it will have no effect on a synchronous observable
<del> subscription.unsubscribe();
<del> }
<del> } catch (Throwable ex) {
<del> observer.onError(ex);
<del> // this will work if the sequence is asynchronous, it
<del> // will have no effect on a synchronous observable
<del> subscription.unsubscribe();
<del> }
<del>
<del> }
<del>
<del> @Override
<del> public void onError(Throwable ex) {
<del> observer.onError(ex);
<del> }
<del>
<del> @Override
<del> public void onCompleted() {
<del> if (index < 0) {
<del> observer.onError(new IndexOutOfBoundsException(index + " is out of bounds"));
<del> } else if (counter.get() <= index) {
<del> if (hasDefault) {
<del> observer.onNext(defaultValue);
<del> observer.onCompleted();
<del> } else {
<del> observer.onError(new IndexOutOfBoundsException(index + " is out of bounds"));
<del> }
<del> }
<del> }
<del> }));
<del> }
<del> }
<del>}
<ide><path>rxjava-core/src/main/java/rx/operators/OperatorElementAt.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.operators;
<add>
<add>import rx.Observable;
<add>import rx.Observable.OnSubscribe;
<add>import rx.Subscriber;
<add>
<add>/**
<add> * Returns the element at a specified index in a sequence.
<add> */
<add>public final class OperatorElementAt<T> implements OnSubscribe<T> {
<add>
<add> private final Observable<? extends T> source;
<add> private final int index;
<add> private final boolean hasDefault;
<add> private final T defaultValue;
<add>
<add> public OperatorElementAt(Observable<? extends T> source, int index) {
<add> this(source, index, null, false);
<add> }
<add>
<add> public OperatorElementAt(Observable<? extends T> source, int index, T defaultValue) {
<add> this(source, index, defaultValue, true);
<add> }
<add>
<add> private OperatorElementAt(Observable<? extends T> source, int index, T defaultValue, boolean hasDefault) {
<add> if (index < 0) {
<add> throw new IndexOutOfBoundsException(index + " is out of bounds");
<add> }
<add> this.source = source;
<add> this.index = index;
<add> this.defaultValue = defaultValue;
<add> this.hasDefault = hasDefault;
<add> }
<add>
<add> @Override
<add> public void call(final Subscriber<? super T> subscriber) {
<add> source.subscribe(new Subscriber<T>(subscriber) {
<add>
<add> private int currentIndex = 0;
<add>
<add> @Override
<add> public void onNext(T value) {
<add> if (currentIndex == index) {
<add> subscriber.onNext(value);
<add> subscriber.onCompleted();
<add> }
<add> currentIndex++;
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> subscriber.onError(e);
<add> }
<add>
<add> @Override
<add> public void onCompleted() {
<add> if (currentIndex <= index) {
<add> // If "subscriber.onNext(value)" is called, currentIndex must be greater than index
<add> if (hasDefault) {
<add> subscriber.onNext(defaultValue);
<add> subscriber.onCompleted();
<add> } else {
<add> subscriber.onError(new IndexOutOfBoundsException(index + " is out of bounds"));
<add> }
<add> }
<add> }
<add> });
<add> }
<add>}
<ide><path>rxjava-core/src/test/java/rx/operators/OperationElementAtTest.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx.operators;
<del>
<del>import static org.junit.Assert.*;
<del>import static org.mockito.Matchers.*;
<del>import static org.mockito.Mockito.*;
<del>import static rx.operators.OperationElementAt.*;
<del>
<del>import java.util.Iterator;
<del>import java.util.concurrent.ExecutionException;
<del>
<del>import org.junit.Test;
<del>
<del>import rx.Observable;
<del>import rx.Observer;
<del>
<del>public class OperationElementAtTest {
<del>
<del> @Test
<del> public void testElementAt() {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable.create(elementAt(w, 1));
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> observer = mock(Observer.class);
<del> observable.subscribe(observer);
<del> verify(observer, never()).onNext(1);
<del> verify(observer, times(1)).onNext(2);
<del> verify(observer, never()).onError(
<del> any(Throwable.class));
<del> verify(observer, times(1)).onCompleted();
<del> }
<del>
<del> @Test
<del> public void testElementAtWithMinusIndex() {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable
<del> .create(elementAt(w, -1));
<del>
<del> try {
<del> Iterator<Integer> iter = OperationToIterator
<del> .toIterator(observable);
<del> assertTrue(iter.hasNext());
<del> iter.next();
<del> fail("expect an IndexOutOfBoundsException when index is out of bounds");
<del> } catch (IndexOutOfBoundsException e) {
<del> }
<del> }
<del>
<del> @Test
<del> public void testElementAtWithIndexOutOfBounds()
<del> throws InterruptedException, ExecutionException {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable.create(elementAt(w, 2));
<del> try {
<del> Iterator<Integer> iter = OperationToIterator
<del> .toIterator(observable);
<del> assertTrue(iter.hasNext());
<del> iter.next();
<del> fail("expect an IndexOutOfBoundsException when index is out of bounds");
<del> } catch (IndexOutOfBoundsException e) {
<del> }
<del> }
<del>
<del> @Test
<del> public void testElementAtOrDefault() throws InterruptedException,
<del> ExecutionException {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable
<del> .create(elementAtOrDefault(w, 1, 0));
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> observer = mock(Observer.class);
<del> observable.subscribe(observer);
<del> verify(observer, never()).onNext(1);
<del> verify(observer, times(1)).onNext(2);
<del> verify(observer, never()).onError(any(Throwable.class));
<del> verify(observer, times(1)).onCompleted();
<del> }
<del>
<del> @Test
<del> public void testElementAtOrDefaultWithIndexOutOfBounds()
<del> throws InterruptedException, ExecutionException {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable
<del> .create(elementAtOrDefault(w, 2, 0));
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Integer> observer = mock(Observer.class);
<del> observable.subscribe(observer);
<del> verify(observer, never()).onNext(1);
<del> verify(observer, never()).onNext(2);
<del> verify(observer, times(1)).onNext(0);
<del> verify(observer, never()).onError(any(Throwable.class));
<del> verify(observer, times(1)).onCompleted();
<del> }
<del>
<del> @Test
<del> public void testElementAtOrDefaultWithMinusIndex() {
<del> Observable<Integer> w = Observable.from(1, 2);
<del> Observable<Integer> observable = Observable
<del> .create(elementAtOrDefault(w, -1, 0));
<del>
<del> try {
<del> Iterator<Integer> iter = OperationToIterator
<del> .toIterator(observable);
<del> assertTrue(iter.hasNext());
<del> iter.next();
<del> fail("expect an IndexOutOfBoundsException when index is out of bounds");
<del> } catch (IndexOutOfBoundsException e) {
<del> }
<del> }
<del>}
<ide><path>rxjava-core/src/test/java/rx/operators/OperatorElementAtTest.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.operators;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>
<add>import java.util.Arrays;
<add>
<add>import org.junit.Test;
<add>
<add>import rx.Observable;
<add>
<add>public class OperatorElementAtTest {
<add>
<add> @Test
<add> public void testElementAt() {
<add> assertEquals(2, Observable.from(Arrays.asList(1, 2)).elementAt(1).toBlockingObservable().single()
<add> .intValue());
<add> }
<add>
<add> @Test(expected = IndexOutOfBoundsException.class)
<add> public void testElementAtWithMinusIndex() {
<add> Observable.from(Arrays.asList(1, 2)).elementAt(-1);
<add> }
<add>
<add> @Test(expected = IndexOutOfBoundsException.class)
<add> public void testElementAtWithIndexOutOfBounds() {
<add> Observable.from(Arrays.asList(1, 2)).elementAt(2).toBlockingObservable().single();
<add> }
<add>
<add> @Test
<add> public void testElementAtOrDefault() {
<add> assertEquals(2, Observable.from(Arrays.asList(1, 2)).elementAtOrDefault(1, 0).toBlockingObservable()
<add> .single().intValue());
<add> }
<add>
<add> @Test
<add> public void testElementAtOrDefaultWithIndexOutOfBounds() {
<add> assertEquals(0, Observable.from(Arrays.asList(1, 2)).elementAtOrDefault(2, 0).toBlockingObservable()
<add> .single().intValue());
<add> }
<add>
<add> @Test(expected = IndexOutOfBoundsException.class)
<add> public void testElementAtOrDefaultWithMinusIndex() {
<add> Observable.from(Arrays.asList(1, 2)).elementAtOrDefault(-1, 0);
<add> }
<add>} | 5 |
Javascript | Javascript | pass vector to lookat function | b788d8d73a2891aac08d52a27cd4d54abcaef837 | <ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> } else { // Cameras and other Object3Ds
<ide>
<del> model.lookAt( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
<add> model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
<ide>
<ide> }
<ide> | 1 |
Python | Python | fix failing tests | d1b28ad955f3cb4cba3a7eb99e46fc15dcbacc63 | <ide><path>libcloud/test/compute/test_kubevirt.py
<ide>
<ide> from libcloud.test import unittest
<ide> from libcloud.test import MockHttp
<del>from libcloud.test.compute import TestCaseMixin
<ide> from libcloud.test.file_fixtures import ComputeFileFixtures
<ide>
<ide>
<del>class KubeVirtTest(unittest.TestCase, TestCaseMixin):
<add>class KubeVirtTest(unittest.TestCase):
<ide>
<ide> fixtures = ComputeFileFixtures('kubevirt')
<ide>
<ide> def setUp(self):
<ide> KubeVirtNodeDriver.connectionCls.conn_class = KubeVirtMockHttp
<del> self.driver = KubeVirtNodeDriver(key='user',secret='pass',
<add> self.driver = KubeVirtNodeDriver(key='user',
<add> secret='pass',
<ide> secure=True,
<del> host='foo',port=6443)
<add> host='foo',
<add> port=6443)
<ide>
<ide> def test_list_locations(self):
<ide> locations = self.driver.list_locations()
<ide> def test_destroy_node(self):
<ide> resp = self.driver.destroy_node(to_destroy)
<ide> self.assertTrue(resp)
<ide>
<del>
<ide> def test_start_node(self):
<ide> nodes = self.driver.list_nodes()
<del> r1 = self.driver.ex_start_node(nodes[0])
<add> r1 = self.driver.start_node(nodes[0])
<ide> self.assertTrue(r1)
<ide>
<ide> def test_stop_node(self):
<ide> nodes = self.driver.list_nodes()
<del> r1 = self.driver.ex_stop_node(nodes[0])
<add> r1 = self.driver.stop_node(nodes[0])
<ide> self.assertTrue(r1)
<ide>
<ide> def test_reboot_node(self):
<ide> def test_reboot_node(self):
<ide> self.assertTrue(resp)
<ide>
<ide>
<del>
<ide> class KubeVirtMockHttp(MockHttp):
<ide>
<ide> fixtures = ComputeFileFixtures('kubevirt')
<ide>
<del>
<ide> def _api_v1_namespaces(self, method, url, body, headers):
<ide> if method == "GET":
<ide> body = self.fixtures.load('_api_v1_namespaces.json')
<ide> def _apis_kubevirt_io_v1alpha3_namespaces_kube_public_virtualmachines(self,
<ide> else:
<ide> AssertionError('Unsupported method')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<add>
<ide> def _apis_kubevirt_io_v1alpha3_namespaces_kube_system_virtualmachines(self,
<ide> method, url, body, headers):
<ide> if method == "GET":
<ide> def _apis_kubevirt_io_v1alpha3_namespaces_kubevirt_virtualmachines(self,
<ide> else:
<ide> AssertionError('Unsupported method')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<add>
<ide> def _apis_kubevirt_io_v1alpha3_namespaces_default_virtualmachines_testvm(self,
<ide> method, url, body, headers):
<ide> header = "application/merge-patch+json" | 1 |
Javascript | Javascript | fix headers with empty value | 70a8fb3763c92337bbc6a6138dd0c320134b847c | <ide><path>lib/http.js
<ide> var parsers = new FreeList('parsers', 1000, function () {
<ide>
<ide> parser.onHeaderField = function (b, start, len) {
<ide> var slice = b.toString('ascii', start, start+len).toLowerCase();
<del> if (parser.value) {
<add> if (parser.value != undefined) {
<ide> parser.incoming._addHeaderLine(parser.field, parser.value);
<ide> parser.field = null;
<ide> parser.value = null;
<ide> var parsers = new FreeList('parsers', 1000, function () {
<ide> };
<ide>
<ide> parser.onHeadersComplete = function (info) {
<del> if (parser.field && parser.value) {
<add> if (parser.field && (parser.value != undefined)) {
<ide> parser.incoming._addHeaderLine(parser.field, parser.value);
<ide> }
<ide>
<ide><path>test/simple/test-http-blank-header.js
<add>require('../common');
<add>
<add>http = require('http');
<add>net = require('net');
<add>
<add>gotReq = false;
<add>
<add>server = http.createServer(function (req, res) {
<add> error('got req');
<add> gotReq = true;
<add> assert.equal('GET', req.method);
<add> assert.equal('/blah', req.url);
<add> assert.deepEqual({
<add> host: "mapdevel.trolologames.ru:443",
<add> origin: "http://mapdevel.trolologames.ru",
<add> cookie: "",
<add> }, req.headers);
<add>});
<add>
<add>
<add>server.listen(PORT, function () {
<add> var c = net.createConnection(PORT);
<add>
<add> c.addListener('connect', function () {
<add> error('client wrote message');
<add> c.write( "GET /blah HTTP/1.1\r\n"
<add> + "Host: mapdevel.trolologames.ru:443\r\n"
<add> + "Cookie:\r\n"
<add> + "Origin: http://mapdevel.trolologames.ru\r\n"
<add> + "\r\n\r\nhello world"
<add> );
<add> });
<add>
<add> c.addListener('end', function () {
<add> c.end();
<add> });
<add>
<add> c.addListener('close', function () {
<add> error('client close');
<add> server.close();
<add> });
<add>});
<add>
<add>
<add>process.addListener('exit', function () {
<add> assert.ok(gotReq);
<add>}); | 2 |
Ruby | Ruby | remove implementation of unchecked_serialize | 6833bf4d108be3821f7818cf0e60419c80eafd0d | <ide><path>activemodel/lib/active_model/type/helpers/numeric.rb
<ide> module Numeric
<ide> def serialize(value)
<ide> cast(value)
<ide> end
<del> alias :unchecked_serialize :serialize
<ide>
<ide> def cast(value)
<ide> # Checks whether the value is numeric. Spaceship operator
<ide><path>activemodel/lib/active_model/type/value.rb
<ide> def cast(value)
<ide> def serialize(value)
<ide> value
<ide> end
<del> alias :unchecked_serialize :serialize
<ide>
<ide> # Type casts a value for schema dumping. This method is private, as we are
<ide> # hoping to remove it entirely.
<ide><path>activerecord/lib/active_record/enum.rb
<ide> def serializable?(value)
<ide> def serialize(value)
<ide> mapping.fetch(value, value)
<ide> end
<del> alias :unchecked_serialize :serialize
<ide>
<ide> def assert_valid_value(value)
<ide> unless serializable?(value)
<ide><path>activerecord/lib/arel/nodes/homogeneous_in.rb
<ide> def casted_values
<ide> type = attribute.type_caster
<ide>
<ide> casted_values = values.map do |raw_value|
<del> type.unchecked_serialize(raw_value) if type.serializable?(raw_value)
<add> type.serialize(raw_value) if type.serializable?(raw_value)
<ide> end
<ide>
<ide> casted_values.compact!
<ide><path>activerecord/lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_HomogeneousIn(o, collector)
<ide> collector << quote_table_name(o.table_name) << "." << quote_column_name(o.column_name)
<ide>
<ide> if o.type == :in
<del> collector << "IN ("
<add> collector << " IN ("
<ide> else
<del> collector << "NOT IN ("
<add> collector << " NOT IN ("
<ide> end
<ide>
<ide> values = o.casted_values.map { |v| @connection.quote(v) }
<ide><path>activerecord/test/cases/relation/where_test.rb
<ide> def test_where_with_integer_for_binary_column
<ide> assert_equal 0, count
<ide> end
<ide>
<add> def test_where_with_emoji_for_binary_column
<add> Binary.create!(data: "🥦")
<add> assert Binary.where(data: ["🥦", "🍦"]).to_sql.include?("f09fa5a6")
<add> assert Binary.where(data: ["🥦", "🍦"]).to_sql.include?("f09f8da6")
<add> end
<add>
<ide> def test_where_on_association_with_custom_primary_key
<ide> author = authors(:david)
<ide> essay = Essay.where(writer: author).first | 6 |
PHP | PHP | fix the broken test | 0cb1d3194294fd6ba317ce3ea05cd47801e10d4b | <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php
<ide> class FakeConnection
<ide> *
<ide> * @param array $config configuration for connecting to database
<ide> */
<del> public function __construct($config)
<add> public function __construct($config = [])
<ide> {
<ide> $this->_config = $config;
<ide> } | 1 |
Text | Text | add manual instructions on upgrading 0.13 -> 0.14 | 28ef2316da479245a358cf01735e20e33a503000 | <ide><path>docs/Images.md
<ide> var icon = this.props.active ? require('./my-icon-active.png') : require('./my-i
<ide> <Image source={icon} />
<ide> ```
<ide>
<del>NOTE: This system relies on build hooks for [Xcode](https://github.com/facebook/react-native/pull/3523) and [Gradle](https://github.com/facebook/react-native/commit/9dc036d2b99e6233297c55a3490bfc308e34e75f) that are included in new projects generated with `react-native init`. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system.
<add>**Available React Native 0.14+**. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for [Xcode](https://github.com/facebook/react-native/pull/3523) and [Gradle](https://github.com/facebook/react-native/commit/9dc036d2b99e6233297c55a3490bfc308e34e75f) that are included in new projects generated with `react-native init`. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See [Upgrading](/react-native/docs/upgrading.html) for instructions on how to do this.
<ide>
<ide> ## Images From Hybrid App's Resources
<ide>
<ide><path>docs/Upgrading.md
<ide> This will check your files against the latest template and perform the following
<ide> * If a file is different in your project than the template, you will be prompted; you have options
<ide> to view a diff between your file and the template file, keep your file or overwrite it with the
<ide> template version. If you are unsure, press `h` to get a list of possible commands.
<add>
<add>
<add># Manual Upgrades
<add>
<add>Xcode project format is pretty complex and sometimes it's tricky to upgrade and merge new changes.
<add>
<add>### From 0.13 to 0.14
<add>
<add>The major change in this version happened to the CLI ([see changelog](https://github.com/facebook/react-native/releases/tag/v0.14.0-rc)) and static images ([see docs](http://facebook.github.io/react-native/docs/images.html)). To use the new asset system in existing Xcode project, do the following:
<add>
<add>Add new "Run Script" step to your project's build phases:
<add>
<add>
<add>
<add>Set the script to
<add>```sh
<add>../node_modules/react-native/packager/react-native-xcode.sh
<add>```
<add>
<add>
<add>
<add>Move main.jsbundle to Trash (it will be generated automatically by Xcode using the script above)
<add>
<add>
<add>
<add>If you installed Node via nvm, you might experience "react-native: command not found". See [issues/3974](https://github.com/facebook/react-native/issues/3974) for workaround and [pull/4015](https://github.com/facebook/react-native/pull/4015) for the fix. | 2 |
Text | Text | add history info for `global.performance` | 8baf372313a435722783e248ec7a02f02de3f332 | <ide><path>doc/api/globals.md
<ide> This variable may appear to be global but is not. See [`module`][].
<ide>
<ide> ## `performance`
<ide>
<add><!-- YAML
<add>added: v16.0.0
<add>-->
<add>
<ide> The [`perf_hooks.performance`][] object.
<ide>
<ide> ## `process` | 1 |
Ruby | Ruby | fix typo in the documentation | 39a25ba57ee893bd4e4596076cc56cb4953cc169 | <ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def text_area(object_name, method, options = {})
<ide> # wouldn't update the flag.
<ide> #
<ide> # To prevent this the helper generates an auxiliary hidden field before
<del> # the very check box. The hidden field has the same name and its
<add> # every check box. The hidden field has the same name and its
<ide> # attributes mimic an unchecked check box.
<ide> #
<ide> # This way, the client either sends only the hidden field (representing
<ide> def label(method, text = nil, options = {}, &block)
<ide> # wouldn't update the flag.
<ide> #
<ide> # To prevent this the helper generates an auxiliary hidden field before
<del> # the very check box. The hidden field has the same name and its
<add> # every check box. The hidden field has the same name and its
<ide> # attributes mimic an unchecked check box.
<ide> #
<ide> # This way, the client either sends only the hidden field (representing | 1 |
PHP | PHP | add more tests | e7153b533392548a9b3ee90719dc2f88827b0e07 | <ide><path>lib/Cake/Configure/IniReader.php
<ide> protected function _parseNestedValues($values) {
<ide> if ($value === '') {
<ide> $value = false;
<ide> }
<add> unset($values[$key]);
<ide> if (strpos($key, '.') !== false) {
<ide> $values = Hash::insert($values, $key, $value);
<ide> } else {
<ide> public function dump($filename, $data) {
<ide> if (is_array($value)) {
<ide> $keyValues = Hash::flatten($value, '.');
<ide> foreach ($keyValues as $k => $v) {
<del> $result[] = "$k = " . trim(var_export($v, true), "'");
<add> $result[] = "$k = " . $this->_value($v);
<ide> }
<ide> }
<ide> }
<ide> $contents = join("\n", $result);
<ide> return file_put_contents($this->_path . $filename, $contents);
<ide> }
<add>
<add>/**
<add> * Converts a value into the ini equivalent
<add> *
<add> * @param mixed $value to export.
<add> * @return string String value for ini file.
<add> */
<add> protected function _value($val) {
<add> if ($val === null) {
<add> return 'null';
<add> }
<add> if ($val === true) {
<add> return 'true';
<add> }
<add> if ($val === false) {
<add> return 'false';
<add> }
<add> return (string)$val;
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/Case/Configure/IniReaderTest.php
<ide> class IniReaderTest extends CakeTestCase {
<ide>
<ide> /**
<del> * The test file that will be read.
<add> * Test data to serialize and unserialize.
<ide> *
<del> * @var string
<add> * @var array
<ide> */
<del> public $file;
<add> public $testData = array(
<add> 'One' => array(
<add> 'two' => 'value',
<add> 'three' => array(
<add> 'four' => 'value four'
<add> ),
<add> 'is_null' => null,
<add> 'bool_false' => false,
<add> 'bool_true' => true,
<add> ),
<add> 'Asset' => array(
<add> 'timestamp' => 'force'
<add> ),
<add> );
<ide>
<ide> /**
<ide> * setup
<ide> public function testReadingValuesWithDots() {
<ide> $this->assertTrue(isset($config['database']['db']['username']));
<ide> $this->assertEquals('mark', $config['database']['db']['username']);
<ide> $this->assertEquals(3, $config['nesting']['one']['two']['three']);
<add> $this->assertFalse(isset($config['database.db.username']));
<add> $this->assertFalse(isset($config['database']['db.username']));
<ide> }
<ide>
<ide> /**
<ide> public function testReadingWithoutExtension() {
<ide> * @return void
<ide> */
<ide> public function testDump() {
<del> $reader = new IniReader($this->path);
<del> $data = array(
<del> 'One' => array(
<del> 'two' => 'value',
<del> 'three' => array(
<del> 'four' => 'value four'
<del> )
<del> ),
<del> 'Asset' => array(
<del> 'timestamp' => 'force'
<del> ),
<del> );
<del> $result = $reader->dump('test.ini', $data);
<add> $reader = new IniReader(TMP);
<add> $result = $reader->dump('test.ini', $this->testData);
<ide> $this->assertTrue($result > 0);
<ide>
<ide> $expected = <<<INI
<ide> [One]
<ide> two = value
<ide> three.four = value four
<add>is_null = null
<add>bool_false = false
<add>bool_true = true
<ide> [Asset]
<ide> timestamp = force
<ide> INI;
<del> $file = $this->path . 'test.ini';
<add> $file = TMP . 'test.ini';
<ide> $result = file_get_contents($file);
<ide> unlink($file);
<ide>
<add> $this->assertTextEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * Test that dump() makes files read() can read.
<add> *
<add> * @return void
<add> */
<add> public function testDumpRead() {
<add> $reader = new IniReader(TMP);
<add> $reader->dump('test.ini', $this->testData);
<add> $result = $reader->read('test.ini');
<add> unlink(TMP . 'test.ini');
<add>
<add> $expected = $this->testData;
<add> $expected['One']['is_null'] = false;
<add>
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Configure/PhpReaderTest.php
<ide>
<ide> class PhpReaderTest extends CakeTestCase {
<ide>
<add>/**
<add> * Test data to serialize and unserialize.
<add> *
<add> * @var array
<add> */
<add> public $testData = array(
<add> 'One' => array(
<add> 'two' => 'value',
<add> 'three' => array(
<add> 'four' => 'value four'
<add> ),
<add> 'is_null' => null,
<add> 'bool_false' => false,
<add> 'bool_true' => true,
<add> ),
<add> 'Asset' => array(
<add> 'timestamp' => 'force'
<add> ),
<add> );
<add>
<ide> /**
<ide> * setup
<ide> *
<ide> public function testReadPluginValue() {
<ide> * @return void
<ide> */
<ide> public function testDump() {
<del> $reader = new PhpReader($this->path);
<del> $data = array(
<del> 'One' => array(
<del> 'two' => 'value',
<del> 'three' => array(
<del> 'four' => 'value four'
<del> ),
<del> 'null' => null
<del> ),
<del> 'Asset' => array(
<del> 'timestamp' => 'force'
<del> ),
<del> );
<del> $result = $reader->dump('test.php', $data);
<add> $reader = new PhpReader(TMP);
<add> $result = $reader->dump('test.php', $this->testData);
<ide> $this->assertTrue($result > 0);
<ide> $expected = <<<PHP
<ide> <?php
<ide> public function testDump() {
<ide> array (
<ide> 'four' => 'value four',
<ide> ),
<del> 'null' => NULL,
<add> 'is_null' => NULL,
<add> 'bool_false' => false,
<add> 'bool_true' => true,
<ide> ),
<ide> 'Asset' =>
<ide> array (
<ide> 'timestamp' => 'force',
<ide> ),
<ide> );
<ide> PHP;
<del> $file = $this->path . 'test.php';
<add> $file = TMP . 'test.php';
<ide> $contents = file_get_contents($file);
<ide>
<ide> unlink($file);
<del> $this->assertEquals($expected, $contents);
<add> $this->assertTextEquals($expected, $contents);
<add> }
<add>
<add>/**
<add> * Test that dump() makes files read() can read.
<add> *
<add> * @return void
<add> */
<add> public function testDumpRead() {
<add> $reader = new PhpReader(TMP);
<add> $reader->dump('test.php', $this->testData);
<add> $result = $reader->read('test.php');
<add> unlink(TMP . 'test.php');
<add>
<add> $this->assertTextEquals($this->testData, $result);
<ide> }
<ide>
<ide> } | 3 |
Text | Text | add v3.16.0 to changelog | f8fc3e9bfe3ef8928e00127e148bd248124e7f80 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.16.0-beta.1 (December 9, 2019)
<add>### v3.16.0 (January 20, 2020)
<ide>
<ide> - [#18436](https://github.com/emberjs/ember.js/pull/18436) [DEPRECATION] Deprecate globals resolver per [RFC #331](https://github.com/emberjs/rfcs/blob/master/text/0331-deprecate-globals-resolver.md).
<add>- [#18668](https://github.com/emberjs/ember.js/pull/18668) [BUGFIX] Fix some scenarios where the "backtracking assertion" would be thrown by consuming tags after fully getting values
<add>- [#18651](https://github.com/emberjs/ember.js/pull/18651) [BUGFIX] Async functions were incorrectly treated as falsey in template conditionals
<ide>
<ide> ### v3.15.0 (December 9, 2019)
<ide> | 1 |
Ruby | Ruby | utilize symbol#start_with? and #end_with? | a2ca8f062c38fd6546040e18b42cb97b0c40ce3e | <ide><path>actionview/lib/action_view/helpers/atom_feed_helper.rb
<ide> def atom_feed(options = {}, &block)
<ide> end
<ide>
<ide> feed_opts = { "xml:lang" => options[:language] || "en-US", "xmlns" => "http://www.w3.org/2005/Atom" }
<del> feed_opts.merge!(options).reject! { |k, v| !k.to_s.start_with?("xml") }
<add> feed_opts.merge!(options).reject! { |k, v| !k.start_with?("xml") }
<ide>
<ide> xml.feed(feed_opts) do
<ide> xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def initialize(object_name, object, template, options)
<ide>
<ide> convert_to_legacy_options(@options)
<ide>
<del> if @object_name.to_s.end_with?("[]")
<add> if @object_name&.end_with?("[]")
<ide> if (object ||= @template.instance_variable_get("@#{@object_name.to_s.delete_suffix("[]")}")) && object.respond_to?(:to_param)
<ide> @auto_index = object.to_param
<ide> else
<ide><path>railties/lib/rails/application/configuration.rb
<ide> def initialize
<ide> end
<ide>
<ide> def method_missing(method, *args)
<del> if method.to_s.end_with?("=")
<add> if method.end_with?("=")
<ide> @configurations[method.to_s.delete_suffix("=").to_sym] = args.first
<ide> else
<ide> @configurations.fetch(method) {
<ide><path>railties/lib/rails/railtie/configuration.rb
<ide> def respond_to?(name, include_private = false)
<ide>
<ide> private
<ide> def method_missing(name, *args, &blk)
<del> if name.to_s.end_with?("=")
<add> if name.end_with?("=")
<ide> @@options[name.to_s.delete_suffix("=").to_sym] = args.first
<ide> elsif @@options.key?(name)
<ide> @@options[name] | 4 |
Python | Python | convert regularizers to keras backend | 368df8ef04dfc289e3c6d5a177336f97bb233ae7 | <ide><path>keras/regularizers.py
<ide> from __future__ import absolute_import
<del>import theano.tensor as T
<add>from . import backend as K
<ide>
<ide>
<ide> class Regularizer(object):
<ide> def set_param(self, p):
<ide> self.p = p
<ide>
<ide> def __call__(self, loss):
<del> loss += T.sum(abs(self.p)) * self.l1
<del> loss += T.sum(self.p ** 2) * self.l2
<add> loss += K.sum(K.abs(self.p)) * self.l1
<add> loss += K.sum(self.p ** 2) * self.l2
<ide> return loss
<ide>
<ide> def get_config(self):
<ide> def set_layer(self, layer):
<ide> self.layer = layer
<ide>
<ide> def __call__(self, loss):
<del> loss += self.l1 * T.sum(T.mean(abs(self.layer.get_output(True)), axis=0))
<del> loss += self.l2 * T.sum(T.mean(self.layer.get_output(True) ** 2, axis=0))
<add> output = self.layer.get_output(True)
<add> loss += self.l1 * K.sum(K.mean(K.abs(output), axis=0))
<add> loss += self.l2 * K.sum(K.mean(output ** 2, axis=0))
<ide> return loss
<ide>
<ide> def get_config(self):
<ide> def activity_l1l2(l1=0.01, l2=0.01):
<ide>
<ide> from .utils.generic_utils import get_from_module
<ide> def get(identifier, kwargs=None):
<del> return get_from_module(identifier, globals(), 'regularizer', instantiate=True, kwargs=kwargs)
<add> return get_from_module(identifier, globals(), 'regularizer',
<add> instantiate=True, kwargs=kwargs) | 1 |
Python | Python | improve error message | 49a5cdf76dafce69834db2737b84c1e10011877d | <ide><path>keras/engine/topology.py
<ide> def output(self):
<ide> the layer has exactly one inbound node, i.e. if it is connected
<ide> to one incoming layer).
<ide> '''
<del> if len(self.inbound_nodes) != 1:
<add> if len(self.inbound_nodes) == 0:
<add> raise Exception('Layer ' + self.name +
<add> ' has no inbound nodes.')
<add> if len(self.inbound_nodes) > 1:
<ide> raise Exception('Layer ' + self.name +
<ide> ' has multiple inbound nodes, ' +
<ide> 'hence the notion of "layer output" ' | 1 |
Text | Text | add missing step of installing next@latest | 7c8b504252f94079f39304f5023818e84b7cff7e | <ide><path>docs/upgrading.md
<ide> description: Learn how to upgrade Next.js.
<ide>
<ide> ## Upgrading from version 10 to 11
<ide>
<del>## Upgrade React version to latest
<add>### Upgrade React version to latest
<ide>
<ide> Most applications already use the latest version of React, with Next.js 11 the minimum React version has been updated to 17.0.2.
<ide>
<ide> Or using `yarn`:
<ide> yarn add react@latest react-dom@latest
<ide> ```
<ide>
<add>### Upgrade Next.js version to latest
<add>
<add>To upgrade you can run the following command in the terminal:
<add>
<add>```
<add>npm install next@latest
<add>```
<add>
<add>or
<add>
<add>```
<add>yarn add next@latest
<add>```
<add>
<ide> ### Webpack 5
<ide>
<ide> Webpack 5 is now the default for all Next.js applications. If you did not have custom webpack configuration your application is already using webpack 5. If you do have custom webpack configuration you can refer to the [Next.js webpack 5 documentation](https://nextjs.org/docs/messages/webpack5) for upgrading guidance. | 1 |
Text | Text | add a section about "collection caching" [ci skip] | f6e48148be5325462ab1cdd9280bd36f26ce3111 | <ide><path>guides/source/caching_with_rails.md
<ide> If you want to cache a fragment under certain conditions, you can use
<ide> <% end %>
<ide> ```
<ide>
<add>#### Collection caching
<add>
<add>The `render` helper can also cache individual templates rendered for a collection.
<add>It can even one up the previous example with `each` by reading all cache
<add>templates at once instead of one by one. This is done automatically if the template
<add>rendered by the collection includes a `cache` call. Take a collection that renders
<add>a `products/_product.html.erb` partial for each element:
<add>
<add>```ruby
<add>render products
<add>```
<add>
<add>If `products/_product.html.erb` starts with a `cache` call like so:
<add>
<add>```html+erb
<add><% cache product do %>
<add> <%= product.name %>
<add><% end %>
<add>
<add>All the cached templates from previous renders will be fetched at once with much
<add>greater speed. There's more info on how to make your templates [eligible for
<add>collection caching](http://api.rubyonrails.org/classes/ActionView/Template/Handlers/ERB.html#method-i-resource_cache_call_pattern).
<add>
<ide> ### Russian Doll Caching
<ide>
<ide> You may want to nest cached fragments inside other cached fragments. This is | 1 |
Mixed | Go | fix some mistakes in dockerd.md | f53902aa776d2aa795e7eb217478abdf98e22ddf | <ide><path>daemon/config.go
<ide> type CommonConfig struct {
<ide> Root string `json:"graph,omitempty"`
<ide> SocketGroup string `json:"group,omitempty"`
<ide> TrustKeyPath string `json:"-"`
<del> CorsHeaders string `json:"api-cors-headers,omitempty"`
<add> CorsHeaders string `json:"api-cors-header,omitempty"`
<ide> EnableCors bool `json:"api-enable-cors,omitempty"`
<ide>
<ide> // ClusterStore is the storage backend used for the cluster information. It is used by both
<ide><path>daemon/config_unix.go
<ide> type bridgeConfig struct {
<ide> EnableIPv6 bool `json:"ipv6,omitempty"`
<ide> EnableIPTables bool `json:"iptables,omitempty"`
<ide> EnableIPForward bool `json:"ip-forward,omitempty"`
<del> EnableIPMasq bool `json:"ip-mask,omitempty"`
<add> EnableIPMasq bool `json:"ip-masq,omitempty"`
<ide> EnableUserlandProxy bool `json:"userland-proxy,omitempty"`
<ide> DefaultIP net.IP `json:"ip,omitempty"`
<ide> IP string `json:"bip,omitempty"`
<ide><path>docs/reference/commandline/dockerd.md
<ide> This is a full example of the allowed configuration options in the file:
<ide> "tlscacert": "",
<ide> "tlscert": "",
<ide> "tlskey": "",
<del> "api-cors-headers": "",
<add> "api-cors-header": "",
<ide> "selinux-enabled": false,
<ide> "userns-remap": "",
<ide> "group": "",
<ide> This is a full example of the allowed configuration options in the file:
<ide> "ipv6": false,
<ide> "iptables": false,
<ide> "ip-forward": false,
<del> "ip-mask": false,
<add> "ip-masq": false,
<ide> "userland-proxy": false,
<ide> "ip": "0.0.0.0",
<ide> "bridge": "", | 3 |
Python | Python | fix failing test | f83775a9241c7b95a8ec08d19dee7d65a8dbce8a | <ide><path>libcloud/test/compute/test_packet.py
<ide> def _plans(self, method, url, body, headers):
<ide> body = self.fixtures.load('plans.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<add> def _projects_3d27fd13_0466_4878_be22_9a4b5595a3df_plans(self, method, url, body, headers):
<add> body = self.fixtures.load('plans.json')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<ide> def _projects(self, method, url, body, headers):
<ide> body = self.fixtures.load('projects.json')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) | 1 |
Javascript | Javascript | use `concat()` rather than duplicating code | 14ff529fbbff46413c0cb451a2f0abbd16b05d5e | <ide><path>src/Angular.js
<ide> function bind(self, fn) {
<ide> return curryArgs.length
<ide> ? function() {
<ide> return arguments.length
<del> ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
<add> ? fn.apply(self, concat(curryArgs, arguments, 0))
<ide> : fn.apply(self, curryArgs);
<ide> }
<ide> : function() { | 1 |
Javascript | Javascript | remove usage of require('util') | 553c876a24e237b745ae7f8d47e2c9c9eae1263f | <ide><path>lib/internal/error-serdes.js
<ide> function GetName(object) {
<ide> return desc && desc.value;
<ide> }
<ide>
<del>let util;
<del>function lazyUtil() {
<del> if (!util)
<del> util = require('util');
<del> return util;
<add>let internalUtilInspect;
<add>function inspect(...args) {
<add> if (!internalUtilInspect) {
<add> internalUtilInspect = require('internal/util/inspect');
<add> }
<add> return internalUtilInspect.inspect(...args);
<ide> }
<ide>
<ide> let serialize;
<ide> function serializeError(error) {
<ide> return Buffer.concat([Buffer.from([kSerializedObject]), serialized]);
<ide> } catch {}
<ide> return Buffer.concat([Buffer.from([kInspectedError]),
<del> Buffer.from(lazyUtil().inspect(error), 'utf8')]);
<add> Buffer.from(inspect(error), 'utf8')]);
<ide> }
<ide>
<ide> let deserialize; | 1 |
Text | Text | update the version history in the middleware page | 882f3380eef219432543e98393550f2ed65624dc | <ide><path>docs/advanced-features/middleware.md
<ide> description: Learn how to use Middleware to run code before a request is complet
<ide>
<ide> | Version | Changes |
<ide> | --------- | ------------------------------------------------------------------------------------------ |
<add>| `v13.0.0` | Support overriding request headers. |
<ide> | `v12.2.0` | Middleware is stable |
<ide> | `v12.0.9` | Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) |
<ide> | `v12.0.0` | Middleware (Beta) added |
<ide> export function middleware(request: NextRequest) {
<ide>
<ide> ## Setting Headers
<ide>
<del>You can set request and response headers using the `NextResponse` API.
<add>You can set request and response headers using the `NextResponse` API (setting _request_ headers is available since Next.js v13.0.0).
<ide>
<ide> ```ts
<ide> // middleware.ts | 1 |
Javascript | Javascript | change var to let in stream_base_commons | 12a21aee1896dffcaf9b598c50908ee554d3abec | <ide><path>lib/internal/stream_base_commons.js
<ide> function createWriteWrap(handle) {
<ide> function writevGeneric(self, data, cb) {
<ide> const req = createWriteWrap(self[kHandle]);
<ide> const allBuffers = data.allBuffers;
<del> var chunks;
<del> var i;
<add> let chunks;
<ide> if (allBuffers) {
<ide> chunks = data;
<del> for (i = 0; i < data.length; i++)
<add> for (let i = 0; i < data.length; i++)
<ide> data[i] = data[i].chunk;
<ide> } else {
<ide> chunks = new Array(data.length << 1);
<del> for (i = 0; i < data.length; i++) {
<del> var entry = data[i];
<add> for (let i = 0; i < data.length; i++) {
<add> const entry = data[i];
<ide> chunks[i * 2] = entry.chunk;
<ide> chunks[i * 2 + 1] = entry.encoding;
<ide> } | 1 |
Javascript | Javascript | add devtools tests for copying complex values | 9ad35905fae96036a130d9dec24b47132dfe4076 | <ide><path>packages/react-devtools-shared/src/__tests__/inspectedElementContext-test.js
<ide> describe('InspectedElementContext', () => {
<ide>
<ide> done();
<ide> });
<add>
<add> it('should enable complex values to be copied to the clipboard', async done => {
<add> const Immutable = require('immutable');
<add>
<add> const Example = () => null;
<add>
<add> const set = new Set(['abc', 123]);
<add> const map = new Map([
<add> ['name', 'Brian'],
<add> ['food', 'sushi'],
<add> ]);
<add> const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
<add> const mapOfMaps = new Map([
<add> ['first', map],
<add> ['second', map],
<add> ]);
<add> const typedArray = Int8Array.from([100, -100, 0]);
<add> const arrayBuffer = typedArray.buffer;
<add> const dataView = new DataView(arrayBuffer);
<add> const immutable = Immutable.fromJS({
<add> a: [{hello: 'there'}, 'fixed', true],
<add> b: 123,
<add> c: {
<add> '1': 'xyz',
<add> xyz: 1,
<add> },
<add> });
<add> // $FlowFixMe
<add> const bigInt = BigInt(123); // eslint-disable-line no-undef
<add>
<add> await utils.actAsync(() =>
<add> ReactDOM.render(
<add> <Example
<add> arrayBuffer={arrayBuffer}
<add> dataView={dataView}
<add> map={map}
<add> set={set}
<add> mapOfMaps={mapOfMaps}
<add> setOfSets={setOfSets}
<add> typedArray={typedArray}
<add> immutable={immutable}
<add> bigInt={bigInt}
<add> />,
<add> document.createElement('div'),
<add> ),
<add> );
<add>
<add> const id = ((store.getElementIDAtIndex(0): any): number);
<add>
<add> let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath);
<add>
<add> function Suspender({target}) {
<add> const context = React.useContext(InspectedElementContext);
<add> copyPath = context.copyInspectedElementPath;
<add> return null;
<add> }
<add>
<add> await utils.actAsync(
<add> () =>
<add> TestRenderer.create(
<add> <Contexts
<add> defaultSelectedElementID={id}
<add> defaultSelectedElementIndex={0}>
<add> <React.Suspense fallback={null}>
<add> <Suspender target={id} />
<add> </React.Suspense>
<add> </Contexts>,
<add> ),
<add> false,
<add> );
<add> expect(copyPath).not.toBeNull();
<add>
<add> // Should copy the whole value (not just the hydrated parts)
<add> copyPath(id, ['props']);
<add> jest.runOnlyPendingTimers();
<add> // Should not error despite lots of unserialized values.
<add>
<add> global.mockClipboardCopy.mockReset();
<add>
<add> // Should copy the nested property specified (not just the outer value)
<add> copyPath(id, ['props', 'bigInt']);
<add> jest.runOnlyPendingTimers();
<add> expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
<add> expect(global.mockClipboardCopy).toHaveBeenCalledWith(
<add> JSON.stringify('123n'),
<add> );
<add>
<add> global.mockClipboardCopy.mockReset();
<add>
<add> // Should copy the nested property specified (not just the outer value)
<add> copyPath(id, ['props', 'typedArray']);
<add> jest.runOnlyPendingTimers();
<add> expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
<add> expect(global.mockClipboardCopy).toHaveBeenCalledWith(
<add> JSON.stringify({0: 100, 1: -100, 2: 0}),
<add> );
<add>
<add> done();
<add> });
<ide> });
<ide><path>packages/react-devtools-shared/src/__tests__/legacy/inspectElement-test.js
<ide> describe('InspectedElementContext', () => {
<ide> JSON.stringify(nestedObject.a.b),
<ide> );
<ide> });
<add>
<add> it('should enable complex values to be copied to the clipboard', () => {
<add> const Immutable = require('immutable');
<add>
<add> const Example = () => null;
<add>
<add> const set = new Set(['abc', 123]);
<add> const map = new Map([
<add> ['name', 'Brian'],
<add> ['food', 'sushi'],
<add> ]);
<add> const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
<add> const mapOfMaps = new Map([
<add> ['first', map],
<add> ['second', map],
<add> ]);
<add> const typedArray = Int8Array.from([100, -100, 0]);
<add> const arrayBuffer = typedArray.buffer;
<add> const dataView = new DataView(arrayBuffer);
<add> const immutable = Immutable.fromJS({
<add> a: [{hello: 'there'}, 'fixed', true],
<add> b: 123,
<add> c: {
<add> '1': 'xyz',
<add> xyz: 1,
<add> },
<add> });
<add> // $FlowFixMe
<add> const bigInt = BigInt(123); // eslint-disable-line no-undef
<add>
<add> act(() =>
<add> ReactDOM.render(
<add> <Example
<add> arrayBuffer={arrayBuffer}
<add> dataView={dataView}
<add> map={map}
<add> set={set}
<add> mapOfMaps={mapOfMaps}
<add> setOfSets={setOfSets}
<add> typedArray={typedArray}
<add> immutable={immutable}
<add> bigInt={bigInt}
<add> />,
<add> document.createElement('div'),
<add> ),
<add> );
<add>
<add> const id = ((store.getElementIDAtIndex(0): any): number);
<add> const rendererID = ((store.getRendererIDForElement(id): any): number);
<add>
<add> // Should copy the whole value (not just the hydrated parts)
<add> bridge.send('copyElementPath', {
<add> id,
<add> path: ['props'],
<add> rendererID,
<add> });
<add> jest.runOnlyPendingTimers();
<add> // Should not error despite lots of unserialized values.
<add>
<add> global.mockClipboardCopy.mockReset();
<add>
<add> // Should copy the nested property specified (not just the outer value)
<add> bridge.send('copyElementPath', {
<add> id,
<add> path: ['props', 'bigInt'],
<add> rendererID,
<add> });
<add> jest.runOnlyPendingTimers();
<add> expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
<add> expect(global.mockClipboardCopy).toHaveBeenCalledWith(
<add> JSON.stringify('123n'),
<add> );
<add>
<add> global.mockClipboardCopy.mockReset();
<add>
<add> // Should copy the nested property specified (not just the outer value)
<add> bridge.send('copyElementPath', {
<add> id,
<add> path: ['props', 'typedArray'],
<add> rendererID,
<add> });
<add> jest.runOnlyPendingTimers();
<add> expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
<add> expect(global.mockClipboardCopy).toHaveBeenCalledWith(
<add> JSON.stringify({0: 100, 1: -100, 2: 0}),
<add> );
<add> });
<ide> }); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.