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
make explicit reverting node_version.h changes
0b3caadad378e4ed9352a6ec5aba3dc080889467
<ide><path>doc/guides/releases.md <ide> $ git cherry-pick v1.x^ <ide> ``` <ide> <ide> Git should stop to let you fix conflicts. Revert all changes that were made to <del>`src/node_version.h`. If there are conflicts in `doc` due to updated `REPLACEME` <add>`src/node_version.h`: <add> <add>```console <add>$ git checkout --ours HEAD -- src/node_version.h <add>``` <add> <add>If there are conflicts in `doc` due to updated `REPLACEME` <ide> placeholders (that happens when a change previously landed on another release <ide> branch), keep both version numbers. Convert the YAML field to an array if it is <ide> not already one.
1
PHP
PHP
fix cs errors
4d434ec9f3b51ece238ddf2434b3d22979fe7c51
<ide><path>lib/Cake/Model/Model.php <ide> protected function _generateAssociation($type, $assocKey) { <ide> <ide> case 'joinTable': <ide> $tables = array($this->table, $this->{$class}->table); <del> sort ($tables); <add> sort($tables); <ide> $data = $tables[0] . '_' . $tables[1]; <ide> break; <ide> <ide><path>lib/Cake/Test/Case/Controller/Component/Acl/DbAclTest.php <ide> protected function _debug($printTreesToo = false) { <ide> foreach ($permissions as $key => $values) { <ide> array_unshift($values, $key); <ide> $values = array_map(array(&$this, '_pad'), $values); <del> $permissions[$key] = implode (' ', $values); <add> $permissions[$key] = implode(' ', $values); <ide> } <ide> $permissions = array_map(array(&$this, '_pad'), $permissions); <ide> array_unshift($permissions, 'Current Permissions :');
2
Javascript
Javascript
throw better error when js parse fails
3e5cffba0fb0bbbe2c62216463dcd295b7772311
<ide><path>curriculum/test/utils/extract-js-comments.js <ide> const parser = acorn.Parser; <ide> function extractComments(js) { <ide> let comments = []; <ide> const file = { data: {} }; <del> parser.parse(js, { onComment: comments, ecmaVersion: 2020 }); <add> try { <add> parser.parse(js, { onComment: comments, ecmaVersion: 2020 }); <add> } catch { <add> throw Error(`extract-js-comments could not parse the code below, this challenge have invalid syntax: <ide> <add>${js} <add>`); <add> } <ide> comments <ide> .map(({ value }) => value.trim()) <ide> .forEach(comment => commentToData(file, comment));
1
Javascript
Javascript
add missing semicolon in encodings
65adaab2e52f6d3e93106425c10db6f912386daa
<ide><path>examples/js/Encodings.js <ide> <ide> THREE.Encodings = function() { <ide> if( THREE.toHalf === undefined ) throw new Error("THREE.Encodings is required for HDRCubeMapLoader when loading half data."); <del>} <add>}; <ide> <ide> THREE.Encodings.RGBEByteToRGBFloat = function( sourceArray, sourceOffset, destArray, destOffset ) { <ide> var e = sourceArray[sourceOffset+3]; <ide> THREE.Encodings.RGBEByteToRGBFloat = function( sourceArray, sourceOffset, destAr <ide> destArray[destOffset+0] = sourceArray[sourceOffset+0] * scale; <ide> destArray[destOffset+1] = sourceArray[sourceOffset+1] * scale; <ide> destArray[destOffset+2] = sourceArray[sourceOffset+2] * scale; <del>} <add>}; <ide> <ide> THREE.Encodings.RGBEByteToRGBHalf = function( sourceArray, sourceOffset, destArray, destOffset ) { <ide> var e = sourceArray[sourceOffset+3]; <ide> THREE.Encodings.RGBEByteToRGBHalf = function( sourceArray, sourceOffset, destArr <ide> destArray[destOffset+0] = THREE.toHalf( sourceArray[sourceOffset+0] * scale ); <ide> destArray[destOffset+1] = THREE.toHalf( sourceArray[sourceOffset+1] * scale ); <ide> destArray[destOffset+2] = THREE.toHalf( sourceArray[sourceOffset+2] * scale ); <del>} <add>};
1
Mixed
Ruby
add support for inline images to mailer previews
60239f3e5a3303b4135e30469ba7dbf27890008d
<ide><path>actionmailer/CHANGELOG.md <add>* Add support for inline images in mailer previews by using an interceptor <add> class to convert cid: urls in image src attributes to data urls. <add> <add> *Andrew White* <add> <ide> * Mailer preview now uses `url_for` to fix links to emails for apps running on <ide> a subdirectory. <ide> <ide><path>actionmailer/lib/action_mailer/preview.rb <ide> require 'active_support/descendants_tracker' <add>require 'base64' <ide> <ide> module ActionMailer <ide> module Previews #:nodoc: <ide> extend ActiveSupport::Concern <ide> <add> class InlineAttachments #:nodoc: <add> PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i <add> <add> include Base64 <add> <add> attr_reader :message <add> <add> def self.previewing_email(message) <add> new(message).transform! <add> end <add> <add> def initialize(message) <add> @message = message <add> end <add> <add> def transform! <add> return message if html_part.blank? <add> <add> html_source.gsub!(PATTERN) do |match| <add> if part = find_part(match[9..-2]) <add> %[src="#{data_url(part)}"] <add> else <add> match <add> end <add> end <add> <add> message <add> end <add> <add> private <add> def html_part <add> @html_part ||= message.html_part <add> end <add> <add> def html_source <add> html_part.body.raw_source <add> end <add> <add> def data_url(part) <add> "data:#{part.mime_type};base64,#{urlsafe_encode64(part.body.raw_source)}" <add> end <add> <add> def find_part(cid) <add> message.all_parts.find{ |p| p.attachment? && p.cid == cid } <add> end <add> end <add> <ide> included do <ide> # Set the location of mailer previews through app configuration: <ide> # <ide> module Previews #:nodoc: <ide> <ide> # :nodoc: <ide> mattr_accessor :preview_interceptors, instance_writer: false <del> self.preview_interceptors = [] <add> self.preview_interceptors = [ActionMailer::Previews::InlineAttachments] <ide> end <ide> <ide> module ClassMethods <ide><path>railties/test/application/mailer_previews_test.rb <ide> def foo <ide> end <ide> <ide> test "plain text mailer preview with attachment" do <del> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioc\na/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==" <add> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca_JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" <ide> <ide> mailer 'notifier', <<-RUBY <ide> class Notifier < ActionMailer::Base <ide> default from: "from@example.com" <ide> <ide> def foo <add> attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') <ide> mail to: "to@example.org" <ide> end <ide> end <ide> def foo <ide> end <ide> <ide> test "multipart mailer preview with attachment" do <del> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioc\na/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==" <add> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca_JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" <ide> <ide> mailer 'notifier', <<-RUBY <ide> class Notifier < ActionMailer::Base <ide> default from: "from@example.com" <ide> <ide> def foo <del> attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png") <add> attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') <ide> mail to: "to@example.org" <ide> end <ide> end <ide> def foo <ide> end <ide> <ide> test "multipart mailer preview with inline attachment" do <del> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioc\na/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==" <add> image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca_JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" <ide> <ide> mailer 'notifier', <<-RUBY <ide> class Notifier < ActionMailer::Base <ide> default from: "from@example.com" <ide> <ide> def foo <del> attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png") <add> attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') <ide> mail to: "to@example.org" <ide> end <ide> end <ide> def foo <ide> get "/rails/mailers/notifier/foo?part=text/html" <ide> assert_equal 200, last_response.status <ide> assert_match %r[<p>Hello, World!</p>], last_response.body <add> assert_match %r[src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca_JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo="], last_response.body <ide> end <ide> <ide> test "multipart mailer preview with attached email" do <ide> def text_template(name, contents) <ide> end <ide> <ide> def image_file(name, contents) <del> app_file("public/images/#{name}", Base64.decode64(contents)) <add> app_file("public/images/#{name}", Base64.urlsafe_decode64(contents), 'wb') <ide> end <ide> end <ide> end <ide><path>railties/test/isolation/abstract_unit.rb <ide> def remove_from_config(str) <ide> File.open(file, "w+") { |f| f.puts contents } <ide> end <ide> <del> def app_file(path, contents) <add> def app_file(path, contents, mode = 'w') <ide> FileUtils.mkdir_p File.dirname("#{app_path}/#{path}") <del> File.open("#{app_path}/#{path}", 'w') do |f| <add> File.open("#{app_path}/#{path}", mode) do |f| <ide> f.puts contents <ide> end <ide> end
4
Ruby
Ruby
enforce https on [*.]archive.org
0d4da4234a1ee776114408f118cd1d683360a2cf
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_homepage <ide> %r{^http://[^/.]+\.tools\.ietf\.org}, <ide> %r{^http://www\.gnu\.org/}, <ide> %r{^http://code\.google\.com/}, <del> %r{^http://bitbucket\.org/} <add> %r{^http://bitbucket\.org/}, <add> %r{^http://(?:[^/]*\.)?archive\.org} <ide> problem "Please use https:// for #{homepage}" <ide> end <ide> <ide> def audit_urls <ide> %r{^http://code\.google\.com/}, <ide> %r{^http://fossies\.org/}, <ide> %r{^http://mirrors\.kernel\.org/}, <del> %r{^http://([^/]*\.|)bintray\.com/}, <add> %r{^http://(?:[^/]*\.)?bintray\.com/}, <ide> %r{^http://tools\.ietf\.org/}, <ide> %r{^http://www\.mirrorservice\.org/}, <ide> %r{^http://launchpad\.net/}, <del> %r{^http://bitbucket\.org/} <add> %r{^http://bitbucket\.org/}, <add> %r{^http://(?:[^/]*\.)?archive\.org} <ide> problem "Please use https:// for #{p}" <ide> when %r{^http://search\.mcpan\.org/CPAN/(.*)}i <ide> problem "#{p} should be `https://cpan.metacpan.org/#{$1}`"
1
Ruby
Ruby
fix rdoc for session_store documentation [ci-skip]
7118ebabbbe28c5bd37c43048c817f1be6af571b
<ide><path>railties/lib/rails/application/configuration.rb <ide> def colorize_logging=(val) <ide> end <ide> <ide> # Specifies what class to use to store the session. Possible values <del> # are `:cookie_store`, `:mem_cache_store`, a custom store, or <del> # `:disabled`. `:disabled` tells Rails not to deal with sessions. <add> # are +:cookie_store+, +:mem_cache_store+, a custom store, or <add> # +:disabled+. +:disabled+ tells Rails not to deal with sessions. <ide> # <ide> # Additional options will be set as +session_options+: <ide> #
1
Javascript
Javascript
fix create router from loopback
2b80cdbbdca9f99f847fa79409260b2a106f84f8
<ide><path>server/boot/a-react.js <ide> import debugFactory from 'debug'; <del>import { app$ } from '../common/app'; <add>import { app$ } from '../../common/app'; <ide> import { Cat } from 'thundercats'; <ide> <ide> const debug = debugFactory('freecc:servereact'); <ide> const routes = [ <ide> ]; <ide> <ide> export default function reactSubRouter(app) { <del> var router = app.Router(); <add> var router = app.loopback.Router(); <ide> <ide> routes.forEach(function(route) { <ide> router.get(route, serveReactApp);
1
Javascript
Javascript
allow multiple sensors, exclude phantom carboard
6a9b1ec65745d1bc10f9b89b5b4612fae92561b2
<ide><path>examples/js/controls/VRControls.js <ide> THREE.VRControls = function ( object, onError ) { <ide> <ide> var vrInputs = []; <ide> <add> function filterInvalidDevices( devices ) { <add> <add> var <add> OculusDeviceId = 'HMDInfo-dev-0x421e7eb800', <add> CardboardDeviceId = 'HMDInfo-dev-0x421e7ecc00'; <add> <add> <add> // Exclude Cardboard position sensor if Oculus exists. <add> var oculusDevices = devices.filter( function ( device ) { <add> <add> return device.deviceId === OculusDeviceId; <add> <add> } ); <add> <add> if ( oculusDevices.length >= 1 ) { <add> <add> return devices.filter( function ( device ) { <add> <add> return device.deviceId !== CardboardDeviceId; <add> <add> } ); <add> <add> } else { <add> <add> return devices; <add> <add> } <add> <add> } <add> <ide> function gotVRDevices( devices ) { <ide> <del> for ( var i = 0; i < devices.length; i ++ ) { <add> devices = filterInvalidDevices( devices ); <ide> <del> var device = devices[ i ]; <add> for ( var i = 0; i < devices.length; i ++ ) { <ide> <del> if ( device instanceof PositionSensorVRDevice ) { <add> if ( devices[ i ] instanceof PositionSensorVRDevice ) { <ide> <ide> vrInputs.push( devices[ i ] ); <ide> <del> break; // We keep the first we encounter <del> <ide> } <ide> <ide> }
1
PHP
PHP
remove unnecessary lcfirst call
a8130c7e4ff2888b3949751259b45f287bf518a0
<ide><path>src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php <ide> protected function normalizeGuessedAbilityName($ability) <ide> */ <ide> public function authorizeResource($model, $parameter = null, array $options = [], $request = null) <ide> { <del> $parameter = $parameter ?: Str::snake(lcfirst(class_basename($model))); <add> $parameter = $parameter ?: Str::snake(class_basename($model)); <ide> <ide> $middleware = []; <ide>
1
PHP
PHP
allow escaping placeholders
532c9b620556832bc0ca455d7b8644d162f76581
<ide><path>src/Log/Engine/BaseLog.php <ide> protected function _format(string $message, array $context = []): string <ide> return $message; <ide> } <ide> <del> preg_match_all('/\{([a-z][a-z0-9-_]*)\}/i', $message, $matches); <add> preg_match_all( <add> '/(?<!' . preg_quote('\\', '/') . ')\{([a-z][a-z0-9-_]*)\}/i', <add> $message, <add> $matches <add> ); <ide> if (empty($matches)) { <ide> return $message; <ide> } <ide><path>tests/TestCase/Log/Engine/BaseLogTest.php <ide> public function testPlaceHoldersInMessage() <ide> $context <ide> ); <ide> $this->assertSame('["my-type"]', $this->logger->getMessage()); <add> <add> $this->logger->log( <add> LogLevel::INFO, <add> '\{string}', <add> ['string' => 'a-string'] <add> ); <add> $this->assertSame('\{string}', $this->logger->getMessage()); <ide> } <ide> }
2
Javascript
Javascript
add validation to challenge completion
6642dd497f4c83b0146441e4294884de14a09bf7
<ide><path>client/commonFramework/bindings.js <ide> window.common = (function(global) { <ide> data = { <ide> id: common.challengeId, <ide> name: common.challengeName, <del> challengeType: common.challengeType <add> challengeType: +common.challengeType <ide> }; <del> $.post('/completed-challenge/', data) <add> $.ajax({ <add> url: '/completed-challenge/', <add> type: 'POST', <add> data: JSON.stringify(data), <add> contentType: 'application/json', <add> dataType: 'json' <add> }) <ide> .success(function(res) { <ide> if (!res) { <ide> return; <ide> window.common = (function(global) { <ide> common.challengeId; <ide> }) <ide> .fail(function() { <del> window.location.href = '/challenges'; <add> window.location.replace(window.location.href); <ide> }); <ide> <ide> break; <ide> window.common = (function(global) { <ide> githubLink <ide> }; <ide> <del> $.post('/completed-zipline-or-basejump/', data) <add> $.ajax({ <add> url: '/completed-zipline-or-basejump/', <add> type: 'POST', <add> data: JSON.stringify(data), <add> contentType: 'application/json', <add> dataType: 'json' <add> }) <ide> .success(function() { <ide> window.location.href = '/challenges/next-challenge?id=' + <ide> common.challengeId; <ide><path>client/commonFramework/show-completion.js <ide> window.common = (function(global) { <ide> `; <ide> console.error(err); <ide> } <del> const data = { <add> const data = JSON.stringify({ <ide> id: common.challengeId, <ide> name: common.challengeName, <ide> completedWith: didCompleteWith, <del> challengeType: common.challengeType, <add> challengeType: +common.challengeType, <ide> solution, <ide> timezone <del> }; <del> <del> $.post('/completed-challenge/', data, function(res) { <del> if (res) { <del> window.location = <del> '/challenges/next-challenge?id=' + common.challengeId; <del> } <ide> }); <add> <add> $.ajax({ <add> url: '/completed-challenge/', <add> type: 'POST', <add> data, <add> contentType: 'application/json', <add> dataType: 'json' <add> }) <add> .success(function(res) { <add> if (res) { <add> window.location = <add> '/challenges/next-challenge?id=' + common.challengeId; <add> } <add> }) <add> .fail(function() { <add> window.location.replace(window.location.href); <add> }); <ide> }); <ide> }; <ide> <ide><path>client/commonFramework/step-challenge.js <ide> window.common = (function({ $, common = { init: [] }}) { <ide> e.preventDefault(); <ide> <ide> $('#submit-challenge') <del> .attr('disabled', 'true') <del> .removeClass('btn-primary') <del> .addClass('btn-warning disabled'); <add> .attr('disabled', 'true') <add> .removeClass('btn-primary') <add> .addClass('btn-warning disabled'); <ide> <ide> var $checkmarkContainer = $('#checkmark-container'); <ide> $checkmarkContainer.css({ height: $checkmarkContainer.innerHeight() }); <ide> <ide> $('#challenge-checkmark') <del> .addClass('zoomOutUp') <del> .delay(1000) <del> .queue(function(next) { <del> $(this).replaceWith( <del> '<div id="challenge-spinner" ' + <del> 'class="animated zoomInUp inner-circles-loader">' + <del> 'submitting...</div>' <del> ); <del> next(); <del> }); <del> <del> $.post( <del> '/completed-challenge/', { <add> .addClass('zoomOutUp') <add> .delay(1000) <add> .queue(function(next) { <add> $(this).replaceWith( <add> '<div id="challenge-spinner" ' + <add> 'class="animated zoomInUp inner-circles-loader">' + <add> 'submitting...</div>' <add> ); <add> next(); <add> }); <add> <add> $.ajax({ <add> url: '/completed-challenge/', <add> type: 'POST', <add> data: JSON.stringify({ <ide> id: common.challengeId, <ide> name: common.challengeName, <del> challengeType: common.challengeType <del> }, <del> function(res) { <add> challengeType: +common.challengeType <add> }), <add> contentType: 'application/json', <add> dataType: 'json' <add> }) <add> .success(function(res) { <ide> if (res) { <ide> window.location = <ide> '/challenges/next-challenge?id=' + common.challengeId; <ide> } <del> } <del> ); <add> }) <add> .fail(function() { <add> window.location.replace(window.location.href); <add> }); <ide> } <ide> <ide> common.init.push(function($) { <ide><path>server/boot/challenge.js <ide> module.exports = function(app) { <ide> } <ide> <ide> function completedChallenge(req, res, next) { <add> req.checkBody('id', 'id must be a ObjectId').isMongoId(); <add> <add> req.checkBody('name', 'name must be at least 3 characters') <add> .isString() <add> .isLength({ min: 3 }); <add> <add> req.checkBody('challengeType', 'challengeType must be an integer') <add> .isNumber() <add> .isInt(); <ide> const type = accepts(req).type('html', 'json', 'text'); <ide> <add> const errors = req.validationErrors(true); <add> <add> if (errors) { <add> if (type === 'json') { <add> return res.status(403).send({ errors }); <add> } <add> <add> log('errors', errors); <add> return res.sendStatus(403); <add> } <add> <ide> const completedDate = Date.now(); <ide> const { <ide> id, <ide> module.exports = function(app) { <ide> const points = alreadyCompleted ? <ide> user.progressTimestamps.length : <ide> user.progressTimestamps.length + 1; <add> <ide> return user.update$(updateData) <ide> .doOnNext(({ count }) => log('%s documents updated', count)) <ide> .subscribe( <ide> module.exports = function(app) { <ide> } <ide> <ide> function completedZiplineOrBasejump(req, res, next) { <del> const { user, body = {} } = req; <del> <del> let completedChallenge; <del> // backwards compatibility <del> // please remove once in production <del> // to allow users to transition to new client code <del> if (body.challengeInfo) { <del> <del> if (!body.challengeInfo.challengeId) { <del> req.flash('error', { msg: 'No id returned during save' }); <del> return res.sendStatus(403); <add> const type = accepts(req).type('html', 'json', 'text'); <add> req.checkBody('id', 'id must be an ObjectId').isMongoId(); <add> req.checkBody('name', 'Name must be at least 3 characters') <add> .isString() <add> .isLength({ min: 3 }); <add> req.checkBody('challengeType', 'must be a number') <add> .isNumber() <add> .isInt(); <add> req.checkBody('solution', 'solution must be a url').isURL(); <add> <add> const errors = req.validationErrors(true); <add> <add> if (errors) { <add> if (type === 'json') { <add> return res.status(403).send({ errors }); <ide> } <add> log('errors', errors); <add> return res.sendStatus(403); <add> } <ide> <del> completedChallenge = { <del> id: body.challengeInfo.challengeId, <del> name: body.challengeInfo.challengeName || '', <del> completedDate: Date.now(), <del> <del> challengeType: +body.challengeInfo.challengeType === 4 ? 4 : 3, <add> const { user, body = {} } = req; <ide> <del> solution: body.challengeInfo.publicURL, <del> githubLink: body.challengeInfo.githubURL <del> }; <del> } else { <del> completedChallenge = _.pick( <del> body, <del> [ 'id', 'name', 'solution', 'githubLink', 'challengeType' ] <del> ); <del> completedChallenge.challengeType = +completedChallenge.challengeType; <del> completedChallenge.completedDate = Date.now(); <del> } <add> const completedChallenge = _.pick( <add> body, <add> [ 'id', 'name', 'solution', 'githubLink', 'challengeType' ] <add> ); <add> completedChallenge.challengeType = +completedChallenge.challengeType; <add> completedChallenge.completedDate = Date.now(); <ide> <ide> if ( <ide> !completedChallenge.solution || <ide> module.exports = function(app) { <ide> ) { <ide> req.flash('errors', { <ide> msg: 'You haven\'t supplied the necessary URLs for us to inspect ' + <del> 'your work.' <add> 'your work.' <ide> }); <ide> return res.sendStatus(403); <ide> } <ide> <ide> <ide> const { <add> alreadyCompleted, <ide> updateData <ide> } = buildUserUpdate(req.user, completedChallenge.id, completedChallenge); <ide> <del> return user.updateTo$(updateData) <del> .doOnNext(() => res.status(200).send(true)) <add> return user.update$(updateData) <add> .doOnNext(({ count }) => log('%s documents updated', count)) <add> .doOnNext(() => { <add> if (type === 'json') { <add> return res.send({ <add> alreadyCompleted, <add> points: alreadyCompleted ? <add> user.progressTimestamps.length : <add> user.progressTimestamps.length + 1 <add> }); <add> } <add> res.status(200).send(true); <add> }) <ide> .subscribe(() => {}, next); <ide> } <ide> <ide><path>server/middlewares/validator.js <ide> import validator from 'express-validator'; <ide> <del>export default validator.bind(validator, { <del> customValidators: { <del> matchRegex: function matchRegex(param, regex) { <del> return regex.test(param); <add>export default function() { <add> return validator({ <add> customValidators: { <add> matchRegex(param, regex) { <add> return regex.test(param); <add> }, <add> isString(value) { <add> return typeof value === 'string'; <add> }, <add> isNumber(value) { <add> return typeof value === 'number'; <add> } <ide> } <del> } <del>}); <add> }); <add>}
5
Text
Text
add flax examples and cloud tpu readme
77f9bd18afd4c39335e970abb8fc9a1d1c352d09
<ide><path>examples/flax/README.md <add><!--- <add>Copyright 2021 The HuggingFace Team. All rights reserved. <add>Licensed under the Apache License, Version 2.0 (the "License"); <add>you may not use this file except in compliance with the License. <add>You may obtain a copy of the License at <add> <add> http://www.apache.org/licenses/LICENSE-2.0 <add> <add>Unless required by applicable law or agreed to in writing, software <add>distributed under the License is distributed on an "AS IS" BASIS, <add>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add>See the License for the specific language governing permissions and <add>limitations under the License. <add>--> <add> <add># JAX/Flax Examples <add> <add>This folder contains actively maintained examples of 🤗 Transformers using the JAX/Flax backend. Porting models and examples to JAX/Flax is an ongoing effort, and more will be added in the coming months. In particular, these examples are all designed to run fast on Cloud TPUs, and we include step-by-step guides to getting started with Cloud TPU. <add> <add>*NOTE*: Currently, there is no "Trainer" abstraction for JAX/Flax -- all examples contain an explicit training loop. <add> <add>## Intro: JAX and Flax <add> <add>[JAX](https://github.com/google/jax) is a numerical computation library that exposes a NumPy-like API with tracing capabilities. With JAX's `jit`, you can <add>trace pure functions and compile them into efficient, fused accelerator code on both GPU and TPU. JAX <add>supports additional transformations such as `grad` (for arbitrary gradients), `pmap` (for parallelizing computation on multiple devices), `remat` (for gradient checkpointing), `vmap` (automatic <add>efficient vectorization), and `pjit` (for automatically sharded model parallelism). All JAX transformations compose arbitrarily with each other -- e.g., efficiently <add>computing per-example gradients is simply `vmap(grad(f))`. <add> <add>[Flax](https://github.com/google/flax) builds on top of JAX with an ergonomic <add>module abstraction using Python dataclasses that leads to concise and explicit code. Flax's "lifted" JAX transformations (e.g. `vmap`, `remat`) allow you to nest JAX transformation and modules in any way you wish. Flax is the most widely used JAX library, with [129 dependent projects](https://github.com/google/flax/network/dependents?package_id=UGFja2FnZS01MjEyMjA2MA%3D%3D) as of May 2021. It is also the library underlying all of the official Cloud TPU JAX examples. (TODO: Add link once it's there.) <add> <add>## Running on Cloud TPU <add> <add>All of our JAX/Flax models are designed to run efficiently on Google <add>Cloud TPUs. Here is a guide for running jobs on Google Cloud TPU. <add>(TODO: Add a link to the Cloud TPU JAX getting started guide once it's public) <add>Each example README contains more details on the specific model and training <add>procedure. <add> <add>## Supported models <add> <add>Porting models from PyTorch to JAX/Flax is an ongoing effort. <add>Feel free to reach out if you are interested in contributing a model in JAX/Flax -- we'll <add>be adding a guide for porting models from PyTorch in the upcoming few weeks. <add> <add>For a complete overview of models that are supported in JAX/Flax, please have a look at [this](https://huggingface.co/transformers/master/index.html#supported-frameworks) table. <add> <add>Over 3000 pretrained checkpoints are supported in JAX/Flax as of May 2021. <add>Click [here](https://huggingface.co/models?filter=jax) to see the full list on the 🤗 hub. <add> <add>## Examples <add> <add>The following table lists all of our examples on how to use 🤗 Transformers with the JAX/Flax backend: <add>- with information about the model and dataset used, <add>- whether or not they leverage the [🤗 Datasets](https://github.com/huggingface/datasets) library, <add>- links to **Colab notebooks** to walk through the scripts and run them easily. <add> <add>| Task | Example model | Example dataset | 🤗 Datasets | Colab <add>|---|---|---|:---:|:---:| <add>| [**`masked-language-modeling`**](https://github.com/huggingface/transformers/tree/master/examples/flax/language-modeling) | BERT | OSCAR | ✅ | [![Open In Colab (TODO: Patrick)](https://colab.research.google.com/assets/colab-badge.svg)]() <add>| [**`text-classification`**](https://github.com/huggingface/transformers/tree/master/examples/flax/text-classification) | BERT | GLUE | ✅ | [![Open In Colab (TODO: Patrick)](https://colab.research.google.com/assets/colab-badge.svg)]()
1
Javascript
Javascript
add support for appending multiple roots
b5790dc2e120415e6f08ccb8bb8c4ea367867fef
<ide><path>packages/ember-glimmer/lib/renderer.js <ide> if (isEnabled('ember-glimmer-detect-backtracking-rerender') || <ide> isEnabled('ember-glimmer-allow-backtracking-rerender')) { <ide> runInTransaction = _runInTransaction; <ide> } else { <del> runInTransaction = callback => { <del> callback(); <add> runInTransaction = (context, methodName) => { <add> context[methodName](); <ide> return false; <ide> }; <ide> } <ide> class DynamicScope { <ide> } <ide> } <ide> <del>let nextRootId = 0; <ide> class RootState { <del> constructor(env, root, template, self, parentElement, dynamicScope) { <del> this.id = ++nextRootId; <del> this.env = env; <add> constructor(root, env, template, self, parentElement, dynamicScope) { <add> assert(`You cannot render \`${self.value()}\` without a template.`, template); <add> <add> this.id = getViewId(root); <ide> this.root = root; <del> this.template = template; <del> this.self = self; <del> this.parentElement = parentElement; <del> this.dynamicScope = dynamicScope; <add> this.result = undefined; <add> this.shouldReflush = false; <ide> <del> this.options = { <add> let options = this.options = { <ide> alwaysRevalidate: false <ide> }; <del> this.render = this.initialRender; <del> this.lastRevision = undefined; <del> this.result = undefined; <del> } <ide> <del> isFor(possibleRoot) { <del> return this.root === possibleRoot; <del> } <add> this.render = () => { <add> let result = this.result = template.asEntryPoint().render(self, env, { <add> appendTo: parentElement, <add> dynamicScope <add> }); <ide> <del> initialRender() { <del> let { self, template, env, parentElement, dynamicScope } = this; <del> assert(`You cannot render \`${self.value()}\` without a template.`, template); <del> <del> this.result = this.template.asEntryPoint().render(self, env, { <del> appendTo: parentElement, <del> dynamicScope <del> }); <del> this.lastRevision = CURRENT_TAG.value(); <del> <del> // change next render to use `rerender` <del> this.render = this.rerender; <add> // override .render function after initial render <add> this.render = () => { <add> result.rerender(options); <add> }; <add> }; <ide> } <ide> <del> rerender() { <del> this.result.rerender(this.options); <del> this.lastRevision = CURRENT_TAG.value(); <add> isFor(possibleRoot) { <add> return this.root === possibleRoot; <ide> } <ide> <ide> destroy() { <ide> let { result } = this; <ide> <del> this.env = null; <ide> this.root = null; <del> this.template = null; <del> this.self = null; <del> this.parentElement = null; <del> this.dynamicScope = null; <del> this.lastRevision = null; <ide> this.result = null; <add> this.render = null; <ide> <ide> if (result) { <ide> result.destroy(); <ide> export class Renderer { <ide> this._viewRegistry = _viewRegistry; <ide> this._destinedForDOM = destinedForDOM; <ide> this._destroyed = false; <del> this._root = null; <del> this._transaction = null; <add> this._roots = []; <add> this._lastRevision = null; <ide> } <ide> <ide> // renderer HOOKS <ide> export class Renderer { <ide> let targetObject = view.outletState.render.controller; <ide> let ref = view.toReference(); <ide> let dynamicScope = new DynamicScope(null, ref, ref, true, targetObject); <del> let root = new RootState(this._env, view, view.template, self, target, dynamicScope); <add> let root = new RootState(view, this._env, view.template, self, target, dynamicScope); <ide> <ide> this._renderRoot(root); <ide> } <ide> export class Renderer { <ide> let rootDef = new RootComponentDefinition(view); <ide> let self = new RootReference(rootDef); <ide> let dynamicScope = new DynamicScope(null, UNDEFINED_REFERENCE, UNDEFINED_REFERENCE, true, null); <del> let root = new RootState(this._env, view, this._rootTemplate, self, target, dynamicScope); <add> let root = new RootState(view, this._env, this._rootTemplate, self, target, dynamicScope); <ide> <ide> this._renderRoot(root); <ide> } <ide> export class Renderer { <ide> view.trigger('willClearRender'); <ide> view._transitionTo('destroying'); <ide> <del> if (this._root && this._root.isFor(view)) { <del> this._clearRoot(); <add> let roots = this._roots; <add> <add> // traverse in reverse so we can remove items <add> // without mucking up the index <add> let i = this._roots.length; <add> while (i--) { <add> let root = roots[i]; <add> // check if the view being removed is a root view <add> if (root.isFor(view)) { <add> root.destroy(); <add> roots.splice(i, 1); <add> } <add> } <add> <add> if (this._roots.length === 0) { <add> deregister(this); <ide> } <ide> <ide> if (!view.isDestroying) { <ide> export class Renderer { <ide> return; <ide> } <ide> this._destroyed = true; <del> this._clearRoot(); <add> this._clearAllRoots(); <ide> } <ide> <ide> getBounds(view) { <ide> export class Renderer { <ide> } <ide> <ide> _renderRoot(root) { <del> assert('Cannot append multiple root views', !this._root); <add> let { _roots: roots } = this; <add> <add> roots.push(root); <ide> <del> let { _env: env } = this; <add> if (roots.length === 1) { <add> register(this); <add> } <add> <add> this._renderRootsTransaction(); <add> } <ide> <del> this._root = root; <add> _renderRoots() { <add> let { _roots: roots, _env: env } = this; <add> let globalShouldReflush; <ide> <del> register(this); <add> // ensure that for the first iteration of the loop <add> // each root is processed <add> let initial = true; <add> <add> do { <add> env.begin(); <add> globalShouldReflush = false; <add> <add> for (let i = 0; i < roots.length; i++) { <add> let root = roots[i]; <add> let { shouldReflush } = root; <add> <add> // when processing non-initial reflush loops, <add> // do not process more roots than needed <add> if (!initial && !shouldReflush) { <add> continue; <add> } <ide> <del> let transaction = () => { <del> let shouldReflush = false; <del> do { <del> env.begin(); <ide> root.options.alwaysRevalidate = shouldReflush; <del> shouldReflush = runInTransaction(root, 'render'); <del> env.commit(); <del> } while (shouldReflush); <del> }; <add> // track shouldReflush based on this roots render result <add> shouldReflush = root.shouldReflush = runInTransaction(root, 'render'); <ide> <del> this._transaction = () => { <del> try { <del> transaction(); <del> } catch (e) { <del> this.destroy(); <del> throw e; <add> // globalShouldReflush should be `true` if *any* of <add> // the roots need to reflush <add> globalShouldReflush = globalShouldReflush || shouldReflush; <ide> } <del> }; <ide> <del> this._transaction(); <add> this._lastRevision = CURRENT_TAG.value(); <add> env.commit(); <add> <add> initial = false; <add> } while (globalShouldReflush); <add> } <add> <add> _renderRootsTransaction() { <add> try { <add> this._renderRoots(); <add> } catch (e) { <add> this.destroy(); <add> throw e; <add> } <ide> } <ide> <del> _clearRoot() { <del> let root = this._root; <del> this._root = null; <del> this._transaction = null; <add> _clearAllRoots() { <add> let roots = this._roots; <add> for (let i = 0; i < roots.length; i++) { <add> let root = roots[i]; <add> root.destroy(); <add> } <add> this._roots = null; <ide> <del> if (root) { <add> if (roots.length) { <ide> deregister(this); <del> root.destroy(); <ide> } <ide> } <ide> <ide> export class Renderer { <ide> } <ide> <ide> _isValid() { <del> return !this._root || CURRENT_TAG.validate(this._root.lastRevision); <add> return this._destroyed || this._roots.length === 0 || CURRENT_TAG.validate(this._lastRevision); <ide> } <ide> <ide> _revalidate() { <ide> if (this._isValid()) { <ide> return; <ide> } <del> this._transaction(); <add> this._renderRootsTransaction(); <ide> } <ide> } <ide> <ide><path>packages/ember-glimmer/tests/integration/components/append-test.js <ide> class AbstractAppendTest extends RenderingTest { <ide> this.assert.equal(willDestroyCalled, 1); <ide> } <ide> <del> ['@skip appending, updating and destroying multiple components'](assert) { <add> ['@test appending, updating and destroying multiple components'](assert) { <ide> let willDestroyCalled = 0; <ide> <ide> this.registerComponent('x-first', {
2
PHP
PHP
add response trait to dry code
72964e278ae2e34c40ecc9c00614596ee960ed4c
<ide><path>src/Illuminate/Http/JsonResponse.php <ide> <ide> class JsonResponse extends \Symfony\Component\HttpFoundation\JsonResponse { <ide> <add> use ResponseTrait; <add> <ide> /** <ide> * Get the json_decoded data from the response <ide> * <ide> public function setData($data = array()) <ide> return $this->update(); <ide> } <ide> <del> /** <del> * Set a header on the Response. <del> * <del> * @param string $key <del> * @param string $value <del> * @param bool $replace <del> * @return \Illuminate\Http\Response <del> */ <del> public function header($key, $value, $replace = true) <del> { <del> $this->headers->set($key, $value, $replace); <del> <del> return $this; <del> } <del> <del> /** <del> * Add a cookie to the response. <del> * <del> * @param \Symfony\Component\HttpFoundation\Cookie $cookie <del> * @return \Illuminate\Http\Response <del> */ <del> public function withCookie(Cookie $cookie) <del> { <del> $this->headers->setCookie($cookie); <del> <del> return $this; <del> } <del> <ide> } <ide>\ No newline at end of file <ide><path>src/Illuminate/Http/Response.php <ide> <ide> class Response extends \Symfony\Component\HttpFoundation\Response { <ide> <add> use ResponseTrait; <add> <ide> /** <ide> * The original content of the response. <ide> * <ide> * @var mixed <ide> */ <ide> public $original; <ide> <del> /** <del> * Set a header on the Response. <del> * <del> * @param string $key <del> * @param string $value <del> * @param bool $replace <del> * @return \Illuminate\Http\Response <del> */ <del> public function header($key, $value, $replace = true) <del> { <del> $this->headers->set($key, $value, $replace); <del> <del> return $this; <del> } <del> <del> /** <del> * Add a cookie to the response. <del> * <del> * @param \Symfony\Component\HttpFoundation\Cookie $cookie <del> * @return \Illuminate\Http\Response <del> */ <del> public function withCookie(Cookie $cookie) <del> { <del> $this->headers->setCookie($cookie); <del> <del> return $this; <del> } <del> <ide> /** <ide> * Set the content on the response. <ide> * <ide><path>src/Illuminate/Http/ResponseTrait.php <add><?php namespace Illuminate\Http; <add> <add>trait ResponseTrait { <add> <add> /** <add> * Set a header on the Response. <add> * <add> * @param string $key <add> * @param string $value <add> * @param bool $replace <add> * @return \Illuminate\Http\Response <add> */ <add> public function header($key, $value, $replace = true) <add> { <add> $this->headers->set($key, $value, $replace); <add> <add> return $this; <add> } <add> <add> /** <add> * Add a cookie to the response. <add> * <add> * @param \Symfony\Component\HttpFoundation\Cookie $cookie <add> * @return \Illuminate\Http\Response <add> */ <add> public function withCookie(Cookie $cookie) <add> { <add> $this->headers->setCookie($cookie); <add> <add> return $this; <add> } <add> <add>} <ide>\ No newline at end of file
3
Text
Text
fix api descriptions for openssl-1.1.0
ae096ba27cd26479e11a6610873957910da0beb0
<ide><path>doc/api/crypto.md <ide> is a bit field taking one of or a mix of the following flags (defined in <ide> * `crypto.constants.ENGINE_METHOD_DSA` <ide> * `crypto.constants.ENGINE_METHOD_DH` <ide> * `crypto.constants.ENGINE_METHOD_RAND` <del>* `crypto.constants.ENGINE_METHOD_ECDH` <del>* `crypto.constants.ENGINE_METHOD_ECDSA` <add>* `crypto.constants.ENGINE_METHOD_EC` <ide> * `crypto.constants.ENGINE_METHOD_CIPHERS` <ide> * `crypto.constants.ENGINE_METHOD_DIGESTS` <del>* `crypto.constants.ENGINE_METHOD_STORE` <ide> * `crypto.constants.ENGINE_METHOD_PKEY_METHS` <ide> * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` <ide> * `crypto.constants.ENGINE_METHOD_ALL` <ide> * `crypto.constants.ENGINE_METHOD_NONE` <ide> <add>The flags below are deprecated in OpenSSL-1.1.0. <add> <add>* `crypto.constants.ENGINE_METHOD_ECDH` <add>* `crypto.constants.ENGINE_METHOD_ECDSA` <add>* `crypto.constants.ENGINE_METHOD_STORE` <add> <ide> ### crypto.setFips(bool) <ide> <!-- YAML <ide> added: REPLACEME <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> <td>Limit engine usage to RAND</td> <ide> </tr> <ide> <tr> <del> <td><code>ENGINE_METHOD_ECDH</code></td> <del> <td>Limit engine usage to ECDH</td> <del> </tr> <del> <tr> <del> <td><code>ENGINE_METHOD_ECDSA</code></td> <del> <td>Limit engine usage to ECDSA</td> <add> <td><code>ENGINE_METHOD_EC</code></td> <add> <td>Limit engine usage to EC</td> <ide> </tr> <ide> <tr> <ide> <td><code>ENGINE_METHOD_CIPHERS</code></td> <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> <td><code>ENGINE_METHOD_DIGESTS</code></td> <ide> <td>Limit engine usage to DIGESTS</td> <ide> </tr> <del> <tr> <del> <td><code>ENGINE_METHOD_STORE</code></td> <del> <td>Limit engine usage to STORE</td> <del> </tr> <ide> <tr> <ide> <td><code>ENGINE_METHOD_PKEY_METHS</code></td> <ide> <td>Limit engine usage to PKEY_METHDS</td> <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> <ide> <ide> [`Buffer`]: buffer.html <del>[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_BytesToKey.html <add>[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html <ide> [`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size <ide> [`cipher.final()`]: #crypto_cipher_final_outputencoding <ide> [`cipher.update()`]: #crypto_cipher_update_data_inputencoding_outputencoding <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> [NIST SP 800-132]: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf <ide> [NIST SP 800-38D]: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf <ide> [Nonce-Disrespecting Adversaries]: https://github.com/nonce-disrespect/nonce-disrespect <del>[OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/man1.0.2/apps/spkac.html <add>[OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html <ide> [RFC 2412]: https://www.rfc-editor.org/rfc/rfc2412.txt <ide> [RFC 3526]: https://www.rfc-editor.org/rfc/rfc3526.txt <ide> [RFC 3610]: https://www.rfc-editor.org/rfc/rfc3610.txt <ide><path>doc/api/tls.md <ide> field which always contains the value `'TLSv1/SSLv3'`. <ide> For example: `{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }` <ide> <ide> See `SSL_CIPHER_get_name()` in <del>https://www.openssl.org/docs/man1.0.2/ssl/SSL_CIPHER_get_name.html for more <add>https://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_name.html for more <ide> information. <ide> <ide> ### tlsSocket.getEphemeralKeyInfo() <ide> Example responses include: <ide> * `TLSv1.2` <ide> * `unknown` <ide> <del>See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more <add>See https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html for more <ide> information. <ide> <ide> ### tlsSocket.getSession() <ide> changes: <ide> [OpenSSL Options][]. <ide> * `secureProtocol` {string} Optional SSL method to use. The possible values <ide> are listed as [SSL_METHODS][], use the function names as strings. <del> For example, `'SSLv3_method'` to force SSL version 3. **Default:** <del> `'SSLv23_method'`. <add> For example, `'TLSv1_2_method'` to force TLS version 1.2. **Default:** <add> `'TLS_method'`. <ide> * `sessionIdContext` {string} Optional opaque identifier used by servers to <ide> ensure session state is not shared between applications. Unused by clients. <ide> <ide> where `secure_socket` has the same API as `pair.cleartext`. <ide> [Forward secrecy]: https://en.wikipedia.org/wiki/Perfect_forward_secrecy <ide> [OCSP request]: https://en.wikipedia.org/wiki/OCSP_stapling <ide> [OpenSSL Options]: crypto.html#crypto_openssl_options <del>[OpenSSL cipher list format documentation]: https://www.openssl.org/docs/man1.0.2/apps/ciphers.html#CIPHER-LIST-FORMAT <add>[OpenSSL cipher list format documentation]: https://www.openssl.org/docs/man1.1.0/apps/ciphers.html#CIPHER-LIST-FORMAT <ide> [Perfect Forward Secrecy]: #tls_perfect_forward_secrecy <del>[SSL_CTX_set_timeout]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_timeout.html <del>[SSL_METHODS]: https://www.openssl.org/docs/man1.0.2/ssl/ssl.html#DEALING-WITH-PROTOCOL-METHODS <add>[SSL_CTX_set_timeout]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_timeout.html <add>[SSL_METHODS]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html#Dealing-with-Protocol-Methods <ide> [Stream]: stream.html#stream_stream <ide> [TLS Session Tickets]: https://www.ietf.org/rfc/rfc5077.txt <ide> [TLS recommendations]: https://wiki.mozilla.org/Security/Server_Side_TLS
2
PHP
PHP
add testresponse to return type
7f0b1836a93b7b7ffe285bd8e46b5159fbc62b43
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> protected function extractFilesFromDataArray(&$data) <ide> * Follow a redirect chain until a non-redirect is received. <ide> * <ide> * @param \Illuminate\Http\Response $response <del> * @return \Illuminate\Http\Response <add> * @return \Illuminate\Http\Response|\Illuminate\Foundation\Testing\TestResponse <ide> */ <ide> protected function followRedirects($response) <ide> {
1
Javascript
Javascript
fix syntax error on older builds of ie11
f9ea222f1daf8460bff0722b6ad4b6554a85dc2f
<ide><path>src/loaders/BufferGeometryLoader.js <ide> Object.assign( BufferGeometryLoader.prototype, { <ide> var TYPED_ARRAYS = { <ide> Int8Array: Int8Array, <ide> Uint8Array: Uint8Array, <del> Uint8ClampedArray: Uint8ClampedArray, <add> Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, <ide> Int16Array: Int16Array, <ide> Uint16Array: Uint16Array, <ide> Int32Array: Int32Array,
1
PHP
PHP
remove double backslashes in memcachedengine
1824d3bfc8fabc644b516a5709a1a4e00cebadcf
<ide><path>src/Cache/Engine/MemcachedEngine.php <ide> */ <ide> class MemcachedEngine extends CacheEngine { <ide> <del>/** <del> * memcached wrapper. <del> * <del> * @var Memcache <del> */ <del> protected $_Memcached = null; <del> <del>/** <del> * The default config used unless overriden by runtime configuration <del> * <del> * - `compress` Whether to compress data <del> * - `duration` Specify how long items in this cache configuration last. <del> * - `groups` List of groups or 'tags' associated to every key stored in this config. <del> * handy for deleting a complete group from cache. <del> * - `login` Login to access the Memcache server <del> * - `password` Password to access the Memcache server <del> * - `persistent` The name of the persistent connection. All configurations using <del> * the same persistent value will share a single underlying connection. <del> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace <del> * with either another cache config or another application. <del> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable <del> * cache::gc from ever being called automatically. <del> * - `serialize` The serializer engine used to serialize data. Available engines are php, <del> * igbinary and json. Beside php, the memcached extension must be compiled with the <del> * appropriate serializer support. <del> * - `servers` String or array of memcached servers. If an array MemcacheEngine will use <del> * them as a pool. <del> * - `options` - Additional options for the memcached client. Should be an array of option => value. <del> * Use the \Memcached::OPT_* constants as keys. <del> * <del> * @var array <del> */ <del> protected $_defaultConfig = [ <del> 'compress' => false, <del> 'duration' => 3600, <del> 'groups' => [], <del> 'login' => null, <del> 'password' => null, <del> 'persistent' => false, <del> 'prefix' => 'cake_', <del> 'probability' => 100, <del> 'serialize' => 'php', <del> 'servers' => ['127.0.0.1'], <del> 'options' => [], <del> ]; <del> <del>/** <del> * List of available serializer engines <del> * <del> * Memcached must be compiled with json and igbinary support to use these engines <del> * <del> * @var array <del> */ <del> protected $_serializers = []; <del> <del>/** <del> * Initialize the Cache Engine <del> * <del> * Called automatically by the cache frontend <del> * <del> * @param array $config array of setting for the engine <del> * @return bool True if the engine has been successfully initialized, false if not <del> * @throws \Cake\Error\Exception when you try use authentication without Memcached compiled with SASL support <del> */ <del> public function init(array $config = []) { <del> if (!class_exists('\\Memcached')) { <del> return false; <del> } <del> <del> if (!isset($config['prefix'])) { <del> $config['prefix'] = Inflector::slug(APP_DIR) . '_'; <del> } <del> <del> $this->_serializers = [ <del> 'igbinary' => \Memcached::SERIALIZER_IGBINARY, <del> 'json' => \Memcached::SERIALIZER_JSON, <del> 'php' => \Memcached::SERIALIZER_PHP <del> ]; <del> if (defined('\\Memcached::HAVE_MSGPACK') && \Memcached::HAVE_MSGPACK) { <del> $this->_serializers['msgpack'] = \Memcached::SERIALIZER_MSGPACK; <del> } <del> <del> parent::init($config); <del> <del> if (isset($config['servers'])) { <del> $this->config('servers', $config['servers'], false); <del> } <del> <del> if (!is_array($this->_config['servers'])) { <del> $this->_config['servers'] = [$this->_config['servers']]; <del> } <del> <del> if (isset($this->_Memcached)) { <del> return true; <del> } <del> <del> $this->_Memcached = new \Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <del> $this->_setOptions(); <del> <del> if (count($this->_Memcached->getServerList())) { <del> return true; <del> } <del> <del> $servers = []; <del> foreach ($this->_config['servers'] as $server) { <del> $servers[] = $this->_parseServerString($server); <del> } <del> <del> if (!$this->_Memcached->addServers($servers)) { <del> return false; <del> } <del> <del> if (is_array($this->_config['options'])) { <del> foreach ($this->_config['options'] as $opt => $value) { <del> $this->_Memcached->setOption($opt, $value); <del> } <del> } <del> <del> if ($this->_config['login'] !== null && $this->_config['password'] !== null) { <del> if (!method_exists($this->_Memcached, 'setSaslAuthData')) { <del> throw new Error\Exception( <del> 'Memcached extension is not build with SASL support' <del> ); <del> } <del> $this->_Memcached->setSaslAuthData($this->_config['login'], $this->_config['password']); <del> } <del> <del> return true; <del> } <del> <del>/** <del> * Settings the memcached instance <del> * <del> * @return void <del> * @throws \Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine <del> */ <del> protected function _setOptions() { <del> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <del> <del> $serializer = strtolower($this->_config['serialize']); <del> if (!isset($this->_serializers[$serializer])) { <del> throw new Error\Exception( <del> sprintf('%s is not a valid serializer engine for Memcached', $serializer) <del> ); <del> } <del> <del> if ($serializer !== 'php' && !constant('\\Memcached::HAVE_' . strtoupper($serializer))) { <del> throw new Error\Exception( <del> sprintf('Memcached extension is not compiled with %s support', $serializer) <del> ); <del> } <del> <del> $this->_Memcached->setOption(\Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <del> <del> // Check for Amazon ElastiCache instance <del> if (defined('\\Memcached::OPT_CLIENT_MODE') && defined('\\Memcached::DYNAMIC_CLIENT_MODE')) { <del> $this->_Memcached->setOption(\Memcached::OPT_CLIENT_MODE, \Memcached::DYNAMIC_CLIENT_MODE); <del> } <del> <del> $this->_Memcached->setOption(\Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <del> } <del> <del>/** <del> * Parses the server address into the host/port. Handles both IPv6 and IPv4 <del> * addresses and Unix sockets <del> * <del> * @param string $server The server address string. <del> * @return array Array containing host, port <del> */ <del> protected function _parseServerString($server) { <del> if ($server[0] === 'u') { <del> return [$server, 0]; <del> } <del> if (substr($server, 0, 1) === '[') { <del> $position = strpos($server, ']:'); <del> if ($position !== false) { <del> $position++; <del> } <del> } else { <del> $position = strpos($server, ':'); <del> } <del> $port = 11211; <del> $host = $server; <del> if ($position !== false) { <del> $host = substr($server, 0, $position); <del> $port = substr($server, $position + 1); <del> } <del> return [$host, (int)$port]; <del> } <del> <del>/** <del> * Write data for key into cache. When using memcached as your cache engine <del> * remember that the Memcached pecl extension does not support cache expiry times greater <del> * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring. <del> * <del> * @param string $key Identifier for the data <del> * @param mixed $value Data to be cached <del> * @return bool True if the data was successfully cached, false on failure <del> * @see http://php.net/manual/en/memcache.set.php <del> */ <del> public function write($key, $value) { <del> $duration = $this->_config['duration']; <del> if ($duration > 30 * DAY) { <del> $duration = 0; <del> } <del> <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->set($key, $value, $duration); <del> } <del> <del>/** <del> * Write many cache entries to the cache at once <del> * <del> * @param array $data An array of data to be stored in the cache <del> * @return array of bools for each key provided, true if the data was successfully cached, false on failure <del> */ <del> public function writeMany($data) { <del> $cacheData = array(); <del> foreach ($data as $key => $value) { <del> $cacheData[$this->_key($key)] = $value; <del> } <del> <del> $success = $this->_Memcached->setMulti($cacheData); <del> <del> $return = array(); <del> foreach (array_keys($data) as $key) { <del> $return[$key] = $success; <del> } <del> return $return; <del> } <del> <del>/** <del> * Read a key from the cache <del> * <del> * @param string $key Identifier for the data <del> * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it <del> */ <del> public function read($key) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->get($key); <del> } <del> <del>/** <del> * Read many keys from the cache at once <del> * <del> * @param array $keys An array of identifiers for the data <del> * @return An array containing, for each of the given $keys, the cached data or false if cached data could not be <del> * retreived <del> */ <del> public function readMany($keys) { <del> $cacheKeys = array(); <del> foreach ($keys as $key) { <del> $cacheKeys[] = $this->_key($key); <del> } <del> <del> $values = $this->_Memcached->getMulti($cacheKeys); <del> $return = array(); <del> foreach ($keys as &$key) { <del> $return[$key] = array_key_exists($this->_key($key), $values) ? $values[$this->_key($key)] : false; <del> } <del> return $return; <del> } <del> <del>/** <del> * Increments the value of an integer cached key <del> * <del> * @param string $key Identifier for the data <del> * @param int $offset How much to increment <del> * @return bool|int New incremented value, false otherwise <del> * @throws \Cake\Error\Exception when you try to increment with compress = true <del> */ <del> public function increment($key, $offset = 1) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->increment($key, $offset); <del> } <del> <del>/** <del> * Decrements the value of an integer cached key <del> * <del> * @param string $key Identifier for the data <del> * @param int $offset How much to subtract <del> * @return bool|int New decremented value, false otherwise <del> * @throws \Cake\Error\Exception when you try to decrement with compress = true <del> */ <del> public function decrement($key, $offset = 1) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->decrement($key, $offset); <del> } <del> <del>/** <del> * Delete a key from the cache <del> * <del> * @param string $key Identifier for the data <del> * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed <del> */ <del> public function delete($key) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->delete($key); <del> } <del> <del>/** <del> * Delete many keys from the cache at once <del> * <del> * @param array $keys An array of identifiers for the data <del> * @return array of boolean values that are true if the key was successfully deleted, false if it didn't exist or <del> * couldn't be removed <del> */ <del> public function deleteMany($keys) { <del> $cacheKeys = array(); <del> foreach ($keys as $key) { <del> $cacheKeys[] = $this->_key($key); <del> } <del> <del> $success = $this->_Memcached->deleteMulti($cacheKeys); <del> <del> $return = array(); <del> foreach ($keys as $key) { <del> $return[$key] = $success; <del> } <del> return $return; <del> } <del> <del>/** <del> * Delete all keys from the cache <del> * <del> * @param bool $check If true will check expiration, otherwise delete all. <del> * @return bool True if the cache was successfully cleared, false otherwise <del> */ <del> public function clear($check) { <del> if ($check) { <del> return true; <del> } <del> <del> $keys = $this->_Memcached->getAllKeys(); <del> <del> foreach ($keys as $key) { <del> if (strpos($key, $this->_config['prefix']) === 0) { <del> $this->_Memcached->delete($key); <del> } <del> } <del> <del> return true; <del> } <del> <del>/** <del> * Returns the `group value` for each of the configured groups <del> * If the group initial value was not found, then it initializes <del> * the group accordingly. <del> * <del> * @return array <del> */ <del> public function groups() { <del> if (empty($this->_compiledGroupNames)) { <del> foreach ($this->_config['groups'] as $group) { <del> $this->_compiledGroupNames[] = $this->_config['prefix'] . $group; <del> } <del> } <del> <del> $groups = $this->_Memcached->getMulti($this->_compiledGroupNames); <del> if (count($groups) !== count($this->_config['groups'])) { <del> foreach ($this->_compiledGroupNames as $group) { <del> if (!isset($groups[$group])) { <del> $this->_Memcached->set($group, 1, 0); <del> $groups[$group] = 1; <del> } <del> } <del> ksort($groups); <del> } <del> <del> $result = []; <del> $groups = array_values($groups); <del> foreach ($this->_config['groups'] as $i => $group) { <del> $result[] = $group . $groups[$i]; <del> } <del> <del> return $result; <del> } <del> <del>/** <del> * Increments the group value to simulate deletion of all keys under a group <del> * old values will remain in storage until they expire. <del> * <del> * @param string $group name of the group to be cleared <del> * @return bool success <del> */ <del> public function clearGroup($group) { <del> return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group); <del> } <del>} <add> /** <add> * memcached wrapper. <add> * <add> * @var Memcache <add> */ <add> protected $_Memcached = null; <add> <add> /** <add> * The default config used unless overriden by runtime configuration <add> * <add> * - `compress` Whether to compress data <add> * - `duration` Specify how long items in this cache configuration last. <add> * - `groups` List of groups or 'tags' associated to every key stored in this config. <add> * handy for deleting a complete group from cache. <add> * - `login` Login to access the Memcache server <add> * - `password` Password to access the Memcache server <add> * - `persistent` The name of the persistent connection. All configurations using <add> * the same persistent value will share a single underlying connection. <add> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace <add> * with either another cache config or another application. <add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable <add> * cache::gc from ever being called automatically. <add> * - `serialize` The serializer engine used to serialize data. Available engines are php, <add> * igbinary and json. Beside php, the memcached extension must be compiled with the <add> * appropriate serializer support. <add> * - `servers` String or array of memcached servers. If an array MemcacheEngine will use <add> * them as a pool. <add> * - `options` - Additional options for the memcached client. Should be an array of option => value. <add> * Use the \Memcached::OPT_* constants as keys. <add> * <add> * @var array <add> */ <add> protected $_defaultConfig = [ <add> 'compress' => false, <add> 'duration' => 3600, <add> 'groups' => [], <add> 'login' => null, <add> 'password' => null, <add> 'persistent' => false, <add> 'prefix' => 'cake_', <add> 'probability' => 100, <add> 'serialize' => 'php', <add> 'servers' => ['127.0.0.1'], <add> 'options' => [], <add> ]; <add> <add> /** <add> * List of available serializer engines <add> * <add> * Memcached must be compiled with json and igbinary support to use these engines <add> * <add> * @var array <add> */ <add> protected $_serializers = []; <add> <add> /** <add> * Initialize the Cache Engine <add> * <add> * Called automatically by the cache frontend <add> * <add> * @param array $config array of setting for the engine <add> * @return bool True if the engine has been successfully initialized, false if not <add> * @throws \Cake\Error\Exception when you try use authentication without Memcached compiled with SASL support <add> */ <add> public function init(array $config = []) { <add> if (!class_exists('Memcached')) { <add> return false; <add> } <add> <add> if (!isset($config['prefix'])) { <add> $config['prefix'] = Inflector::slug(APP_DIR) . '_'; <add> } <add> <add> $this->_serializers = [ <add> 'igbinary' => \Memcached::SERIALIZER_IGBINARY, <add> 'json' => \Memcached::SERIALIZER_JSON, <add> 'php' => \Memcached::SERIALIZER_PHP <add> ]; <add> if (defined('Memcached::HAVE_MSGPACK') && \Memcached::HAVE_MSGPACK) { <add> $this->_serializers['msgpack'] = \Memcached::SERIALIZER_MSGPACK; <add> } <add> <add> parent::init($config); <add> <add> if (isset($config['servers'])) { <add> $this->config('servers', $config['servers'], false); <add> } <add> <add> if (!is_array($this->_config['servers'])) { <add> $this->_config['servers'] = [$this->_config['servers']]; <add> } <add> <add> if (isset($this->_Memcached)) { <add> return true; <add> } <add> <add> $this->_Memcached = new \Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <add> $this->_setOptions(); <add> <add> if (count($this->_Memcached->getServerList())) { <add> return true; <add> } <add> <add> $servers = []; <add> foreach ($this->_config['servers'] as $server) { <add> $servers[] = $this->_parseServerString($server); <add> } <add> <add> if (!$this->_Memcached->addServers($servers)) { <add> return false; <add> } <add> <add> if (is_array($this->_config['options'])) { <add> foreach ($this->_config['options'] as $opt => $value) { <add> $this->_Memcached->setOption($opt, $value); <add> } <add> } <add> <add> if ($this->_config['login'] !== null && $this->_config['password'] !== null) { <add> if (!method_exists($this->_Memcached, 'setSaslAuthData')) { <add> throw new Error\Exception( <add> 'Memcached extension is not build with SASL support' <add> ); <add> } <add> $this->_Memcached->setSaslAuthData($this->_config['login'], $this->_config['password']); <add> } <add> <add> return true; <add> } <add> <add> /** <add> * Settings the memcached instance <add> * <add> * @return void <add> * @throws \Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine <add> */ <add> protected function _setOptions() { <add> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <add> <add> $serializer = strtolower($this->_config['serialize']); <add> if (!isset($this->_serializers[$serializer])) { <add> throw new Error\Exception( <add> sprintf('%s is not a valid serializer engine for Memcached', $serializer) <add> ); <add> } <add> <add> if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) { <add> throw new Error\Exception( <add> sprintf('Memcached extension is not compiled with %s support', $serializer) <add> ); <add> } <add> <add> $this->_Memcached->setOption(\Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <add> <add> // Check for Amazon ElastiCache instance <add> if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) { <add> $this->_Memcached->setOption(\Memcached::OPT_CLIENT_MODE, \Memcached::DYNAMIC_CLIENT_MODE); <add> } <add> <add> $this->_Memcached->setOption(\Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <add> } <add> <add> /** <add> * Parses the server address into the host/port. Handles both IPv6 and IPv4 <add> * addresses and Unix sockets <add> * <add> * @param string $server The server address string. <add> * @return array Array containing host, port <add> */ <add> protected function _parseServerString($server) { <add> if ($server[0] === 'u') { <add> return [$server, 0]; <add> } <add> if (substr($server, 0, 1) === '[') { <add> $position = strpos($server, ']:'); <add> if ($position !== false) { <add> $position++; <add> } <add> } else { <add> $position = strpos($server, ':'); <add> } <add> $port = 11211; <add> $host = $server; <add> if ($position !== false) { <add> $host = substr($server, 0, $position); <add> $port = substr($server, $position + 1); <add> } <add> return [$host, (int)$port]; <add> } <add> <add> /** <add> * Write data for key into cache. When using memcached as your cache engine <add> * remember that the Memcached pecl extension does not support cache expiry times greater <add> * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring. <add> * <add> * @param string $key Identifier for the data <add> * @param mixed $value Data to be cached <add> * @return bool True if the data was successfully cached, false on failure <add> * @see http://php.net/manual/en/memcache.set.php <add> */ <add> public function write($key, $value) { <add> $duration = $this->_config['duration']; <add> if ($duration > 30 * DAY) { <add> $duration = 0; <add> } <add> <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->set($key, $value, $duration); <add> } <add> <add> /** <add> * Write many cache entries to the cache at once <add> * <add> * @param array $data An array of data to be stored in the cache <add> * @return array of bools for each key provided, true if the data was successfully cached, false on failure <add> */ <add> public function writeMany($data) { <add> $cacheData = array(); <add> foreach ($data as $key => $value) { <add> $cacheData[$this->_key($key)] = $value; <add> } <add> <add> $success = $this->_Memcached->setMulti($cacheData); <add> <add> $return = array(); <add> foreach (array_keys($data) as $key) { <add> $return[$key] = $success; <add> } <add> return $return; <add> } <add> <add> /** <add> * Read a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it <add> */ <add> public function read($key) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->get($key); <add> } <add> <add> /** <add> * Read many keys from the cache at once <add> * <add> * @param array $keys An array of identifiers for the data <add> * @return An array containing, for each of the given $keys, the cached data or false if cached data could not be <add> * retreived <add> */ <add> public function readMany($keys) { <add> $cacheKeys = array(); <add> foreach ($keys as $key) { <add> $cacheKeys[] = $this->_key($key); <add> } <add> <add> $values = $this->_Memcached->getMulti($cacheKeys); <add> $return = array(); <add> foreach ($keys as &$key) { <add> $return[$key] = array_key_exists($this->_key($key), $values) ? $values[$this->_key($key)] : false; <add> } <add> return $return; <add> } <add> <add> /** <add> * Increments the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to increment <add> * @return bool|int New incremented value, false otherwise <add> * @throws \Cake\Error\Exception when you try to increment with compress = true <add> */ <add> public function increment($key, $offset = 1) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->increment($key, $offset); <add> } <add> <add> /** <add> * Decrements the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to subtract <add> * @return bool|int New decremented value, false otherwise <add> * @throws \Cake\Error\Exception when you try to decrement with compress = true <add> */ <add> public function decrement($key, $offset = 1) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->decrement($key, $offset); <add> } <add> <add> /** <add> * Delete a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed <add> */ <add> public function delete($key) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->delete($key); <add> } <add> <add> /** <add> * Delete many keys from the cache at once <add> * <add> * @param array $keys An array of identifiers for the data <add> * @return array of boolean values that are true if the key was successfully deleted, false if it didn't exist or <add> * couldn't be removed <add> */ <add> public function deleteMany($keys) { <add> $cacheKeys = array(); <add> foreach ($keys as $key) { <add> $cacheKeys[] = $this->_key($key); <add> } <add> <add> $success = $this->_Memcached->deleteMulti($cacheKeys); <add> <add> $return = array(); <add> foreach ($keys as $key) { <add> $return[$key] = $success; <add> } <add> return $return; <add> } <add> <add> /** <add> * Delete all keys from the cache <add> * <add> * @param bool $check If true will check expiration, otherwise delete all. <add> * @return bool True if the cache was successfully cleared, false otherwise <add> */ <add> public function clear($check) { <add> if ($check) { <add> return true; <add> } <add> <add> $keys = $this->_Memcached->getAllKeys(); <add> <add> foreach ($keys as $key) { <add> if (strpos($key, $this->_config['prefix']) === 0) { <add> $this->_Memcached->delete($key); <add> } <add> } <add> <add> return true; <add> } <add> <add> /** <add> * Returns the `group value` for each of the configured groups <add> * If the group initial value was not found, then it initializes <add> * the group accordingly. <add> * <add> * @return array <add> */ <add> public function groups() { <add> if (empty($this->_compiledGroupNames)) { <add> foreach ($this->_config['groups'] as $group) { <add> $this->_compiledGroupNames[] = $this->_config['prefix'] . $group; <add> } <add> } <add> <add> $groups = $this->_Memcached->getMulti($this->_compiledGroupNames); <add> if (count($groups) !== count($this->_config['groups'])) { <add> foreach ($this->_compiledGroupNames as $group) { <add> if (!isset($groups[$group])) { <add> $this->_Memcached->set($group, 1, 0); <add> $groups[$group] = 1; <add> } <add> } <add> ksort($groups); <add> } <add> <add> $result = []; <add> $groups = array_values($groups); <add> foreach ($this->_config['groups'] as $i => $group) { <add> $result[] = $group . $groups[$i]; <add> } <add> <add> return $result; <add> } <add> <add> /** <add> * Increments the group value to simulate deletion of all keys under a group <add> * old values will remain in storage until they expire. <add> * <add> * @param string $group name of the group to be cleared <add> * @return bool success <add> */ <add> public function clearGroup($group) { <add> return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group); <add> } <add>} <ide>\ No newline at end of file
1
Javascript
Javascript
add a way to inject provided modules
f6a5053fb2bd0c5bd3ec56a44ccb8569a140fb75
<ide><path>lib/JavascriptParserHelpers.js <ide> exports.addParsedVariableToModule = (parser, name, expression) => { <ide> }; <ide> <ide> exports.requireFileAsExpression = (context, pathToModule) => { <add> const moduleJsPath = exports.getModulePath(context, pathToModule); <add> return `require(${JSON.stringify(moduleJsPath)})`; <add>}; <add> <add>exports.getModulePath = (context, pathToModule) => { <ide> let moduleJsPath = path.relative(context, pathToModule); <ide> if (!/^[A-Z]:/i.test(moduleJsPath)) { <ide> moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); <ide> } <del> return "require(" + JSON.stringify(moduleJsPath) + ")"; <add> return moduleJsPath; <ide> }; <ide> <ide> exports.toConstantDependency = (parser, value) => { <ide><path>lib/NodeStuffPlugin.js <ide> const { <ide> evaluateToIdentifier, <ide> evaluateToString, <ide> expressionIsUnsupported, <add> getModulePath, <ide> toConstantDependency, <ide> toConstantDependencyWithWebpackRequire <ide> } = require("./JavascriptParserHelpers"); <ide> class NodeStuffPlugin { <ide> parser.hooks.expression.for("module").tap("NodeStuffPlugin", () => { <ide> const module = parser.state.module; <ide> const isHarmony = module.buildMeta && module.buildMeta.exportsType; <del> let moduleJsPath = path.join( <del> __dirname, <del> "..", <del> "buildin", <del> isHarmony ? "harmony-module.js" : "module.js" <add> const moduleJsPath = getModulePath( <add> module.context, <add> require.resolve( <add> isHarmony <add> ? "../buildin/harmony-module.js" <add> : "../buildin/module.js" <add> ) <ide> ); <del> if (module.context) { <del> moduleJsPath = path.relative( <del> parser.state.module.context, <del> moduleJsPath <del> ); <del> if (!/^[A-Z]:/i.test(moduleJsPath)) { <del> moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; <del> } <del> } <ide> return addParsedVariableToModule( <ide> parser, <ide> "module", <ide><path>lib/dependencies/ProvidedDependency.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Florent Cailhol @ooflorent <add>*/ <add> <add>"use strict"; <add> <add>const InitFragment = require("../InitFragment"); <add>const Template = require("../Template"); <add>const ModuleDependency = require("./ModuleDependency"); <add> <add>class ProvidedDependency extends ModuleDependency { <add> constructor(request, originModule, name, specifier, range, loc) { <add> super(request); <add> this.originModule = originModule; <add> this.name = name; <add> this.specifier = specifier; <add> this.range = range; <add> this.loc = loc; <add> } <add> <add> get type() { <add> return "provided"; <add> } <add>} <add> <add>function getImportVarName(dep) { <add> return `${Template.toIdentifier(dep.name)}__WEBPACK_PROVIDED_MODULE__`; <add>} <add> <add>ProvidedDependency.Template = class ProvidedDependencyTemplate { <add> apply(dep, source, runtime) { <add> source.replace( <add> dep.range[0], <add> dep.range[1] - 1, <add> this.getContent(dep, runtime) <add> ); <add> } <add> <add> getContent(dep, runtime) { <add> return runtime.exportFromImport({ <add> module: dep.module, <add> originModule: dep.originModule, <add> request: dep.request, <add> importVar: getImportVarName(dep), <add> exportName: dep.specifier, <add> asiSafe: true, <add> isCall: false, <add> callContext: null <add> }); <add> } <add> <add> getInitFragments(dep, source, runtime) { <add> return [ <add> new InitFragment( <add> runtime.importStatement({ <add> update: false, <add> module: dep.module, <add> originModule: dep.originModule, <add> request: dep.request, <add> importVar: getImportVarName(dep) <add> }), <add> 0, <add> `provided ${dep.name}` <add> ) <add> ]; <add> } <add>}; <add> <add>module.exports = ProvidedDependency; <ide><path>lib/dependencies/SystemPlugin.js <ide> <ide> "use strict"; <ide> <add>const path = require("path"); <ide> const { <del> addParsedVariableToModule, <ide> evaluateToString, <ide> expressionIsUnsupported, <del> requireFileAsExpression, <add> getModulePath, <ide> toConstantDependency <ide> } = require("../JavascriptParserHelpers"); <ide> const WebpackError = require("../WebpackError"); <add>const ProvidedDependency = require("./ProvidedDependency"); <ide> <ide> class SystemPlugin { <ide> constructor(options) { <ide> class SystemPlugin { <ide> compiler.hooks.compilation.tap( <ide> "SystemPlugin", <ide> (compilation, { normalModuleFactory }) => { <add> compilation.dependencyFactories.set( <add> ProvidedDependency, <add> normalModuleFactory <add> ); <add> compilation.dependencyTemplates.set( <add> ProvidedDependency, <add> new ProvidedDependency.Template() <add> ); <add> <ide> const handler = (parser, parserOptions) => { <ide> if ( <ide> typeof parserOptions.system === "undefined" || <ide> class SystemPlugin { <ide> setNotSupported("System.get"); <ide> setNotSupported("System.register"); <ide> <del> parser.hooks.expression.for("System").tap("SystemPlugin", () => { <del> const systemPolyfillRequire = requireFileAsExpression( <del> parser.state.module.context, <del> require.resolve("../../buildin/system") <del> ); <del> return addParsedVariableToModule( <del> parser, <del> "System", <del> systemPolyfillRequire <add> parser.hooks.expression.for("System").tap("SystemPlugin", expr => { <add> parser.state.current.addDependency( <add> new ProvidedDependency( <add> getModulePath( <add> parser.state.module.context, <add> require.resolve("../../buildin/system") <add> ), <add> parser.state.module, <add> "System", <add> null, <add> expr.range, <add> expr.loc <add> ) <ide> ); <add> return true; <ide> }); <ide> <ide> parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { <ide><path>lib/node/NodeSourcePlugin.js <ide> <ide> const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin"); <ide> const nodeLibsBrowser = require("node-libs-browser"); <del>const { <del> addParsedVariableToModule, <del> requireFileAsExpression <del>} = require("../JavascriptParserHelpers"); <add>const { getModulePath } = require("../JavascriptParserHelpers"); <add>const ProvidedDependency = require("../dependencies/ProvidedDependency"); <ide> <ide> module.exports = class NodeSourcePlugin { <ide> constructor(options) { <ide> module.exports = class NodeSourcePlugin { <ide> }; <ide> <ide> const addExpression = (parser, name, module, type, suffix) => { <del> suffix = suffix || ""; <del> parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { <add> parser.hooks.expression.for(name).tap("NodeSourcePlugin", expr => { <ide> if ( <ide> parser.state.module && <ide> parser.state.module.resource === getPathToModule(module, type) <del> ) <add> ) { <ide> return; <del> const mockModule = requireFileAsExpression( <del> parser.state.module.context, <del> getPathToModule(module, type) <add> } <add> parser.state.current.addDependency( <add> new ProvidedDependency( <add> getModulePath( <add> parser.state.module.context, <add> getPathToModule(module, type) <add> ), <add> parser.state.module, <add> module, <add> suffix, <add> expr.range, <add> expr.loc <add> ) <ide> ); <del> return addParsedVariableToModule(parser, name, mockModule + suffix); <add> return true; <ide> }); <ide> }; <ide> <ide> compiler.hooks.compilation.tap( <ide> "NodeSourcePlugin", <ide> (compilation, { normalModuleFactory }) => { <add> compilation.dependencyFactories.set( <add> ProvidedDependency, <add> normalModuleFactory <add> ); <add> compilation.dependencyTemplates.set( <add> ProvidedDependency, <add> new ProvidedDependency.Template() <add> ); <add> <ide> const handler = (parser, parserOptions) => { <ide> if (parserOptions.node === false) return; <ide> <ide> module.exports = class NodeSourcePlugin { <ide> if (localOptions.global) { <ide> parser.hooks.expression <ide> .for("global") <del> .tap("NodeSourcePlugin", () => { <del> const retrieveGlobalModule = requireFileAsExpression( <del> parser.state.module.context, <del> require.resolve("../../buildin/global") <del> ); <del> return addParsedVariableToModule( <del> parser, <del> "global", <del> retrieveGlobalModule <add> .tap("NodeSourcePlugin", expr => { <add> parser.state.current.addDependency( <add> new ProvidedDependency( <add> getModulePath( <add> parser.state.module.context, <add> require.resolve("../../buildin/global") <add> ), <add> parser.state.module, <add> "global", <add> null, <add> expr.range, <add> expr.loc <add> ) <ide> ); <ide> }); <ide> } <ide> if (localOptions.process) { <ide> const processType = localOptions.process; <del> addExpression(parser, "process", "process", processType); <add> addExpression(parser, "process", "process", processType, null); <ide> } <ide> if (localOptions.console) { <ide> const consoleType = localOptions.console; <del> addExpression(parser, "console", "console", consoleType); <add> addExpression(parser, "console", "console", consoleType, null); <ide> } <ide> const bufferType = localOptions.Buffer; <ide> if (bufferType) { <del> addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); <add> addExpression(parser, "Buffer", "buffer", bufferType, "Buffer"); <ide> } <ide> if (localOptions.setImmediate) { <ide> const setImmediateType = localOptions.setImmediate; <ide> module.exports = class NodeSourcePlugin { <ide> "setImmediate", <ide> "timers", <ide> setImmediateType, <del> ".setImmediate" <add> "setImmediate" <ide> ); <ide> addExpression( <ide> parser, <ide> "clearImmediate", <ide> "timers", <ide> setImmediateType, <del> ".clearImmediate" <add> "clearImmediate" <ide> ); <ide> } <ide> };
5
Text
Text
fix tiny grammatical error
a7906c9b7c51d479b629f14d75819796b77b87c0
<ide><path>docs/GettingStarted.md <ide> next: android-setup <ide> - Install **nvm** with Homebrew or [its setup instructions here](https://github.com/creationix/nvm#installation). Then run `nvm install node && nvm alias default node`, which installs the latest version of Node.js and sets up your terminal so you can run it by typing `node`. With nvm you can install multiple versions of Node.js and easily switch between them. <ide> - New to [npm](https://docs.npmjs.com/)? <ide> 4. `brew install watchman`. We recommend installing [watchman](https://facebook.github.io/watchman/docs/install.html), otherwise you might hit a node file watching bug. <del>5. `brew install flow`. If you want to use [flow](http://www.flowtype.org). <add>5. `brew install flow`, if you want to use [flow](http://www.flowtype.org). <ide> <ide> We recommend periodically running `brew update && brew upgrade` to keep your programs up-to-date. <ide>
1
Javascript
Javascript
add invariant errors for bindactioncreator
22ca4beb9ad42e3c6e5eb70bc9a677c41c429751
<ide><path>src/utils/bindActionCreators.js <add>import invariant from 'invariant'; <ide> import mapValues from '../utils/mapValues'; <ide> <ide> function bindActionCreator(actionCreator, dispatch) { <ide> export default function bindActionCreators(actionCreators, dispatch) { <ide> return bindActionCreator(actionCreators, dispatch); <ide> } <ide> <add> invariant( <add> typeof actionCreators === 'object' && actionCreators != null, <add> 'bindActionCreators expected an object or a function, instead received %s. ' + <add> 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?', <add> typeof actionCreators <add> ); <add> <ide> return mapValues(actionCreators, actionCreator => <ide> bindActionCreator(actionCreator, dispatch) <ide> ); <ide> } <add> <ide><path>test/utils/bindActionCreators.spec.js <ide> describe('bindActionCreators', () => { <ide> { id: 1, text: 'Hello' } <ide> ]); <ide> }); <add> <add> it('should throw an invariant violation for an undefined actionCreator', () => { <add> expect(() => { <add> bindActionCreators(undefined, store.dispatch); <add> }).toThrow( <add> 'bindActionCreators expected an object or a function, instead received undefined. ' + <add> 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' <add> ); <add> }); <add> <add> it('should throw an invariant violation for a null actionCreator', () => { <add> expect(() => { <add> bindActionCreators(null, store.dispatch); <add> }).toThrow( <add> 'bindActionCreators expected an object or a function, instead received null. ' + <add> 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' <add> ); <add> }); <add> <add> it('should throw an invariant violation for a primitive actionCreator', () => { <add> expect(() => { <add> bindActionCreators('string', store.dispatch); <add> }).toThrow( <add> 'bindActionCreators expected an object or a function, instead received string. ' + <add> 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' <add> ); <add> }); <ide> });
2
Javascript
Javascript
improve performance caused by primordials
e5cbbe05ef8d2b9878f153cd0d7d898cd5d75fa8
<ide><path>lib/events.js <ide> <ide> 'use strict'; <ide> <del>const { Math, Object, Reflect } = primordials; <del>const apply = Reflect.apply; <add>const { <add> Math: { <add> min: MathMin <add> }, <add> Object: { <add> defineProperty: ObjectDefineProperty, <add> getPrototypeOf: ObjectGetPrototypeOf, <add> create: ObjectCreate, <add> keys: ObjectKeys, <add> }, <add> Reflect: { <add> apply: ReflectApply, <add> ownKeys: ReflectOwnKeys, <add> } <add>} = primordials; <ide> <ide> var spliceOne; <ide> <ide> function checkListener(listener) { <ide> } <ide> } <ide> <del>Object.defineProperty(EventEmitter, 'defaultMaxListeners', { <add>ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', { <ide> enumerable: true, <ide> get: function() { <ide> return defaultMaxListeners; <ide> Object.defineProperty(EventEmitter, 'defaultMaxListeners', { <ide> EventEmitter.init = function() { <ide> <ide> if (this._events === undefined || <del> this._events === Object.getPrototypeOf(this)._events) { <del> this._events = Object.create(null); <add> this._events === ObjectGetPrototypeOf(this)._events) { <add> this._events = ObjectCreate(null); <ide> this._eventsCount = 0; <ide> } <ide> <ide> function identicalSequenceRange(a, b) { <ide> const rest = b.length - pos; <ide> if (rest > 3) { <ide> let len = 1; <del> const maxLen = Math.min(a.length - i, rest); <add> const maxLen = MathMin(a.length - i, rest); <ide> // Count the number of consecutive entries. <ide> while (maxLen > len && a[i + len] === b[pos + len]) { <ide> len++; <ide> EventEmitter.prototype.emit = function emit(type, ...args) { <ide> const capture = {}; <ide> // eslint-disable-next-line no-restricted-syntax <ide> Error.captureStackTrace(capture, EventEmitter.prototype.emit); <del> Object.defineProperty(er, kEnhanceStackBeforeInspector, { <add> ObjectDefineProperty(er, kEnhanceStackBeforeInspector, { <ide> value: enhanceStackTrace.bind(this, er, capture), <ide> configurable: true <ide> }); <ide> EventEmitter.prototype.emit = function emit(type, ...args) { <ide> return false; <ide> <ide> if (typeof handler === 'function') { <del> apply(handler, this, args); <add> ReflectApply(handler, this, args); <ide> } else { <ide> const len = handler.length; <ide> const listeners = arrayClone(handler, len); <ide> for (var i = 0; i < len; ++i) <del> apply(listeners[i], this, args); <add> ReflectApply(listeners[i], this, args); <ide> } <ide> <ide> return true; <ide> function _addListener(target, type, listener, prepend) { <ide> <ide> events = target._events; <ide> if (events === undefined) { <del> events = target._events = Object.create(null); <add> events = target._events = ObjectCreate(null); <ide> target._eventsCount = 0; <ide> } else { <ide> // To avoid recursion in the case that type === "newListener"! Before <ide> EventEmitter.prototype.removeListener = <ide> <ide> if (list === listener || list.listener === listener) { <ide> if (--this._eventsCount === 0) <del> this._events = Object.create(null); <add> this._events = ObjectCreate(null); <ide> else { <ide> delete events[type]; <ide> if (events.removeListener) <ide> EventEmitter.prototype.removeAllListeners = <ide> // Not listening for removeListener, no need to emit <ide> if (events.removeListener === undefined) { <ide> if (arguments.length === 0) { <del> this._events = Object.create(null); <add> this._events = ObjectCreate(null); <ide> this._eventsCount = 0; <ide> } else if (events[type] !== undefined) { <ide> if (--this._eventsCount === 0) <del> this._events = Object.create(null); <add> this._events = ObjectCreate(null); <ide> else <ide> delete events[type]; <ide> } <ide> EventEmitter.prototype.removeAllListeners = <ide> <ide> // Emit removeListener for all listeners on all events <ide> if (arguments.length === 0) { <del> for (const key of Object.keys(events)) { <add> for (const key of ObjectKeys(events)) { <ide> if (key === 'removeListener') continue; <ide> this.removeAllListeners(key); <ide> } <ide> this.removeAllListeners('removeListener'); <del> this._events = Object.create(null); <add> this._events = ObjectCreate(null); <ide> this._eventsCount = 0; <ide> return this; <ide> } <ide> function listenerCount(type) { <ide> } <ide> <ide> EventEmitter.prototype.eventNames = function eventNames() { <del> return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; <add> return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; <ide> }; <ide> <ide> function arrayClone(arr, n) {
1
Text
Text
remove html tags to fix misalignment
9a863898f3c90b532df4221ecbd976f67290ae51
<ide><path>client/src/pages/learn/apis-and-microservices/managing-packages-with-npm/index.md <ide> superBlock: APIs and Microservices <ide> --- <ide> ## Introduction to the Managing Packages with npm Challenges <ide> <del>The Node Package Manager (npm) is a command-line tool used by developers to share and control modules (or packages) of JavaScript code written for use with Node.js.<br><br>When starting a new project, npm generates a <code>package.json</code> file. This file lists the package dependencies for your project. Since npm packages are regularly updated, the <code>package.json</code> file allows you to set specific version numbers for each dependency. This ensures that updates to a package don't break your project.<br><br>npm saves packages in a folder named <code>node\_modules</code>. These packages can be installed in two ways:<br><br><ol><li>globally in a root <code>node\_modules</code> folder, accessible by all projects.</li><li>locally within a project's own <code>node\_modules</code> folder, accessible only to that project.</li></ol><br>Most developers prefer to install packages local to each project to create a separation between the dependencies of different projects. <del>Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public Glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.<br>Start this project on Glitch using <a href='https://glitch.com/edit/#!/remix/clone-from-repo?REPO_URL=https://github.com/freeCodeCamp/boilerplate-npm/'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-npm/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe! <add>The Node Package Manager (npm) is a command-line tool used by developers to share and control modules (or packages) of JavaScript code written for use with Node.js.<br><br>When starting a new project, npm generates a <code>package.json</code> file. This file lists the package dependencies for your project. Since npm packages are regularly updated, the <code>package.json</code> file allows you to set specific version numbers for each dependency. This ensures that updates to a package don't break your project. <add> <add>npm saves packages in a folder named <code>node\_modules</code>. These packages can be installed in two ways: <add> <add> <add>1. globally in a root <code>node\_modules</code> folder, accessible by all projects. <add>2. locally within a project's own <code>node\_modules</code> folder, accessible only to that project. <add> <add>Most developers prefer to install packages local to each project to create a separation between the dependencies of different projects. <add>Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public Glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <add> <add>Start this project on Glitch using <a href='https://glitch.com/edit/#!/remix/clone-from-repo?REPO_URL=https://github.com/freeCodeCamp/boilerplate-npm/'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-npm/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe!
1
Javascript
Javascript
add test for child_process benchmark
3d7c82bd612ebb9190d54b80c90ceed3310161aa
<ide><path>benchmark/child_process/spawn-echo.js <ide> 'use strict'; <ide> var common = require('../common.js'); <ide> var bench = common.createBenchmark(main, { <del> thousands: [1] <add> n: [1000] <ide> }); <ide> <ide> var spawn = require('child_process').spawn; <ide> function main(conf) { <del> var len = +conf.thousands * 1000; <add> var n = +conf.n; <ide> <ide> bench.start(); <del> go(len, len); <add> go(n, n); <ide> } <ide> <ide> function go(n, left) { <ide><path>test/sequential/test-benchmark-child-process.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const assert = require('assert'); <add>const fork = require('child_process').fork; <add>const path = require('path'); <add> <add>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <add> <add>const child = fork(runjs, ['--set', 'dur=0.1', <add> '--set', 'n=1', <add> '--set', 'len=1', <add> 'child_process'], <add> {env: {NODEJS_BENCHMARK_ZERO_ALLOWED: 1}}); <add>child.on('exit', (code, signal) => { <add> assert.strictEqual(code, 0); <add> assert.strictEqual(signal, null); <add>});
2
Text
Text
update links to reference and api documentation
9c45acd43abefd5c7e004dfa51324b0c78ea2af9
<ide><path>README.md <ide> Instructions on <ide> via Maven and other build systems are available via the project wiki. <ide> <ide> ## Documentation <del>See the current [Javadoc](http://static.springsource.org/spring/docs/current/javadoc-api) <del>and [Reference docs](http://static.springsource.org/spring/docs/current/spring-framework-reference). <add>See the current [Javadoc](http://static.springsource.org/spring-framework/docs/current/api) <add>and [Reference docs](http://static.springsource.org/spring-framework/docs/current/reference). <ide> <ide> ## Getting support <ide> Check out the [Spring forums](http://forum.springsource.org) and the
1
Javascript
Javascript
add more error codes
ecfe32e3a0a4f6b62063a2b56fbb23599cfb51f1
<ide><path>lib/dns.js <ide> exports.resolve = function(domain, type_, callback_) { <ide> <ide> <ide> // ERROR CODES <del>exports.BADNAME = 'EBADNAME'; <del>exports.BADRESP = 'EBADRESP'; <del>exports.CONNREFUSED = 'ECONNREFUSED'; <del>exports.DESTRUCTION = 'EDESTRUCTION'; <del>exports.REFUSED = 'EREFUSED'; <del>exports.FORMERR = 'EFORMERR'; <ide> exports.NODATA = 'ENODATA'; <del>exports.NOMEM = 'ENOMEM'; <add>exports.FORMERR = 'EFORMERR'; <add>exports.SERVFAIL = 'ESERVFAIL'; <ide> exports.NOTFOUND = 'ENOTFOUND'; <ide> exports.NOTIMP = 'ENOTIMP'; <del>exports.SERVFAIL = 'ESERVFAIL'; <add>exports.REFUSED = 'EREFUSED'; <add>exports.BADQUERY = 'EBADQUERY'; <add>exports.ADNAME = 'EADNAME'; <add>exports.BADFAMILY = 'EBADFAMILY'; <add>exports.BADRESP = 'EBADRESP'; <add>exports.CONNREFUSED = 'ECONNREFUSED'; <ide> exports.TIMEOUT = 'ETIMEOUT'; <add>exports.EOF = 'EOF'; <add>exports.FILE = 'EFILE'; <add>exports.NOMEM = 'ENOMEM'; <add>exports.DESTRUCTION = 'EDESTRUCTION'; <add>exports.BADSTR = 'EBADSTR'; <add>exports.BADFLAGS = 'EBADFLAGS'; <add>exports.NONAME = 'ENONAME'; <add>exports.BADHINTS = 'EBADHINTS'; <add>exports.NOTINITIALIZED = 'ENOTINITIALIZED'; <add>exports.LOADIPHLPAPI = 'ELOADIPHLPAPI'; <add>exports.ADDRGETNETWORKPARAMS = 'EADDRGETNETWORKPARAMS'; <add>exports.CANCELLED = 'ECANCELLED';
1
Mixed
Go
send registry auth token for service deploy
a26bdd8607c62e6e736d06e9ec8f0908c4808d74
<ide><path>api/client/stack/deploy.go <ide> const ( <ide> ) <ide> <ide> type deployOptions struct { <del> bundlefile string <del> namespace string <add> bundlefile string <add> namespace string <add> sendRegistryAuth bool <ide> } <ide> <ide> func newDeployCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> func newDeployCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> <ide> flags := cmd.Flags() <ide> addBundlefileFlag(&opts.bundlefile, flags) <add> addRegistryAuthFlag(&opts.sendRegistryAuth, flags) <ide> return cmd <ide> } <ide> <ide> func runDeploy(dockerCli *client.DockerCli, opts deployOptions) error { <ide> if err := updateNetworks(ctx, dockerCli, networks, opts.namespace); err != nil { <ide> return err <ide> } <del> return deployServices(ctx, dockerCli, bundle.Services, opts.namespace) <add> return deployServices(ctx, dockerCli, bundle.Services, opts.namespace, opts.sendRegistryAuth) <ide> } <ide> <ide> func getUniqueNetworkNames(services map[string]bundlefile.Service) []string { <ide> func deployServices( <ide> dockerCli *client.DockerCli, <ide> services map[string]bundlefile.Service, <ide> namespace string, <add> sendAuth bool, <ide> ) error { <ide> apiClient := dockerCli.Client() <ide> out := dockerCli.Out() <ide> func deployServices( <ide> cspec.User = *service.User <ide> } <ide> <add> encodedAuth := "" <add> if sendAuth { <add> // Retrieve encoded auth token from the image reference <add> image := serviceSpec.TaskTemplate.ContainerSpec.Image <add> encodedAuth, err = dockerCli.RetrieveAuthTokenFromImage(ctx, image) <add> if err != nil { <add> return err <add> } <add> } <add> <ide> if service, exists := existingServiceMap[name]; exists { <ide> fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID) <ide> <del> // TODO(nishanttotla): Pass auth token <add> updateOpts := types.ServiceUpdateOptions{} <add> if sendAuth { <add> updateOpts.EncodedRegistryAuth = encodedAuth <add> } <ide> if err := apiClient.ServiceUpdate( <ide> ctx, <ide> service.ID, <ide> service.Version, <ide> serviceSpec, <del> types.ServiceUpdateOptions{}, <add> updateOpts, <ide> ); err != nil { <ide> return err <ide> } <ide> } else { <ide> fmt.Fprintf(out, "Creating service %s\n", name) <ide> <del> // TODO(nishanttotla): Pass headers with X-Registry-Auth <del> if _, err := apiClient.ServiceCreate(ctx, serviceSpec, types.ServiceCreateOptions{}); err != nil { <add> createOpts := types.ServiceCreateOptions{} <add> if sendAuth { <add> createOpts.EncodedRegistryAuth = encodedAuth <add> } <add> if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil { <ide> return err <ide> } <ide> } <ide><path>api/client/stack/opts.go <ide> func addBundlefileFlag(opt *string, flags *pflag.FlagSet) { <ide> "Path to a Distributed Application Bundle file (Default: STACK.dab)") <ide> } <ide> <add>func addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) { <add> flags.BoolVar(opt, "registry-auth", false, "Send registry authentication details to Swarm agents") <add>} <add> <ide> func loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) { <ide> defaultPath := fmt.Sprintf("%s.dab", namespace) <ide> <ide><path>docs/reference/commandline/deploy.md <ide> Create and update a stack from a Distributed Application Bundle (DAB) <ide> Options: <ide> --file string Path to a Distributed Application Bundle file (Default: STACK.dab) <ide> --help Print usage <add> --registry-auth Send registry authentication details to Swarm agents <ide> ``` <ide> <ide> Create and update a stack from a `dab` file. This command has to be <ide><path>experimental/docker-stacks-and-bundles.md <ide> Create and update a stack <ide> Options: <ide> --file string Path to a Distributed Application Bundle file (Default: STACK.dab) <ide> --help Print usage <add> --registry-auth Send registry authentication details to Swarm agents <ide> ``` <ide> <ide> Let's deploy the stack created before:
4
Python
Python
remove bare returns
9ee02b4551d860be4b10aec65d13d7aae45533c0
<ide><path>official/vision/beta/projects/yolo/common/registry_imports.py <ide> from official.vision.beta.projects.yolo.configs.darknet_classification import ImageClassificationTask <ide> <ide> from official.vision.beta.projects.yolo.tasks.image_classification import ImageClassificationTask <del> <del># task_factory.register_task_cls(ImageClassificationTask)(ImageClassificationTask) <del># print(task_factory._REGISTERED_TASK_CLS) <ide>\ No newline at end of file <ide><path>official/vision/beta/projects/yolo/modeling/backbones/Darknet.py <ide> def get_config(self): <ide> "use_sync_bn": self._use_sync_bn, <ide> "activation": self._activation <ide> } <del> #layer_config.update(super().get_config()) <ide> return layer_config <ide> <ide> @factory.register_backbone_builder('darknet') <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_CSPConnect.py <ide> def __init__( <ide> self._use_sync_bn = use_sync_bn <ide> self._norm_moment = norm_momentum <ide> self._norm_epsilon = norm_epsilon <del> return <ide> <ide> def build(self, input_shape): <ide> self._conv1 = DarkConv(filters=self._filters // self._filter_reduce, <ide> def build(self, input_shape): <ide> norm_momentum=self._norm_moment, <ide> norm_epsilon=self._norm_epsilon, <ide> activation=self._activation) <del> return <ide> <ide> def call(self, inputs): <ide> x_prev, x_csp = inputs <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_CSPDownSample.py <ide> def __init__( <ide> self._use_sync_bn = use_sync_bn <ide> self._norm_moment = norm_momentum <ide> self._norm_epsilon = norm_epsilon <del> return <ide> <ide> def build(self, input_shape): <ide> self._conv1 = DarkConv(filters=self._filters, <ide> def build(self, input_shape): <ide> norm_momentum=self._norm_moment, <ide> norm_epsilon=self._norm_epsilon, <ide> activation=self._activation) <del> return <ide> <ide> def call(self, inputs): <ide> x = self._conv1(inputs) <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_CSPTiny.py <ide> def __init__( <ide> self._leaky_alpha = leaky_alpha <ide> <ide> super().__init__(**kwargs) <del> return <ide> <ide> def build(self, input_shape): <ide> self._convlayer1 = DarkConv(filters=self._filters, <ide> def build(self, input_shape): <ide> data_format=None) <ide> <ide> super().build(input_shape) <del> return <ide> <ide> def call(self, inputs): <ide> x1 = self._convlayer1(inputs) <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_DarkConv.py <ide> def __init__( <ide> self._leaky_alpha = leaky_alpha <ide> <ide> super(DarkConv, self).__init__(**kwargs) <del> return <ide> <ide> def build(self, input_shape): <ide> kernel_size = self._kernel_size if type( <ide> def build(self, input_shape): <ide> self._activation_fn = mish() <ide> else: <ide> self._activation_fn = ks.layers.Activation(activation=self._activation) <del> return <ide> <ide> def call(self, inputs): <ide> x = self._zeropad(inputs) <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_DarkResidual.py <ide> def __init__(self, <ide> self._sc_activation = sc_activation <ide> <ide> super().__init__(**kwargs) <del> return <ide> <ide> def build(self, input_shape): <ide> if self._downsample: <ide> def build(self, input_shape): <ide> self._activation_fn = ks.layers.Activation(activation=self._sc_activation) <ide> <ide> super().build(input_shape) <del> return <ide> <ide> def call(self, inputs): <ide> shortcut = self._dconv(inputs) <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_DarkTiny.py <ide> def __init__( <ide> self._sc_activation = sc_activation <ide> <ide> super().__init__(**kwargs) <del> return <ide> <ide> def build(self, input_shape): <ide> self._maxpool = tf.keras.layers.MaxPool2D(pool_size=2, <ide> def build(self, input_shape): <ide> leaky_alpha=self._leaky_alpha) <ide> <ide> super().build(input_shape) <del> return <ide> <ide> def call(self, inputs): <ide> output = self._maxpool(inputs) <ide><path>official/vision/beta/projects/yolo/modeling/building_blocks/_Identity.py <ide> class Identity(ks.layers.Layer): <ide> def __init__(self, **kwargs): <ide> super().__init__(**kwargs) <del> return <ide> <ide> def call(self, input): <ide> return input <del> <ide><path>official/vision/beta/projects/yolo/modeling/functions/mish_activation.py <ide> class mish(ks.layers.Layer): <ide> def __init__(self, **kwargs): <ide> super().__init__(**kwargs) <del> return <ide> <ide> def call(self, x): <ide> return x * tf.math.tanh(ks.activations.softplus(x)) <ide><path>official/vision/beta/projects/yolo/modeling/tests/test_CSPConnect.py <ide> def test_pass_through(self, width, height, filters, mod): <ide> outx.shape.as_list(), <ide> [None, np.ceil(width // 2), <ide> np.ceil(height // 2), (filters)]) <del> return <ide> <ide> @parameterized.named_parameters(("same", 224, 224, 64, 1), <ide> ("downsample", 224, 224, 128, 2)) <ide> def test_gradient_pass_though(self, filters, width, height, mod): <ide> optimizer.apply_gradients(zip(grad, test_layer.trainable_variables)) <ide> <ide> self.assertNotIn(None, grad) <del> return <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/vision/beta/projects/yolo/modeling/tests/test_CSPDownSample.py <ide> def test_pass_through(self, width, height, filters, mod): <ide> outx.shape.as_list(), <ide> [None, np.ceil(width // 2), <ide> np.ceil(height // 2), (filters / mod)]) <del> return <ide> <ide> @parameterized.named_parameters(("same", 224, 224, 64, 1), <ide> ("downsample", 224, 224, 128, 2)) <ide> def test_gradient_pass_though(self, filters, width, height, mod): <ide> optimizer.apply_gradients(zip(grad, test_layer.trainable_variables)) <ide> <ide> self.assertNotIn(None, grad) <del> return <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/vision/beta/projects/yolo/modeling/tests/test_DarkConv.py <ide> def test_pass_through(self, kernel_size, padding, strides): <ide> ] <ide> print(test) <ide> self.assertAllEqual(outx.shape.as_list(), test) <del> return <ide> <ide> @parameterized.named_parameters(("filters", 3)) <ide> def test_gradient_pass_though(self, filters): <ide> def test_gradient_pass_though(self, filters): <ide> grad = tape.gradient(grad_loss, test_layer.trainable_variables) <ide> optimizer.apply_gradients(zip(grad, test_layer.trainable_variables)) <ide> self.assertNotIn(None, grad) <del> return <ide> <ide> if __name__ == "__main__": <ide> tf.test.main() <ide><path>official/vision/beta/projects/yolo/modeling/tests/test_DarkResidual.py <ide> def test_pass_through(self, width, height, filters, downsample): <ide> outx.shape.as_list(), <ide> [None, np.ceil(width / mod), <ide> np.ceil(height / mod), filters]) <del> return <ide> <ide> @parameterized.named_parameters(("same", 64, 224, 224, False), <ide> ("downsample", 32, 223, 223, True), <ide> def test_gradient_pass_though(self, filters, width, height, downsample): <ide> optimizer.apply_gradients(zip(grad, test_layer.trainable_variables)) <ide> <ide> self.assertNotIn(None, grad) <del> return <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/vision/beta/projects/yolo/modeling/tests/test_DarkTiny.py <ide> def test_pass_through(self, width, height, filters, strides): <ide> self.assertEqual(height % strides, 0, msg="height % strides != 0") <ide> self.assertAllEqual(outx.shape.as_list(), <ide> [None, width // strides, height // strides, filters]) <del> return <ide> <ide> @parameterized.named_parameters(("middle", 224, 224, 64, 2), <ide> ("last", 224, 224, 1024, 1)) <ide> def test_gradient_pass_though(self, width, height, filters, strides): <ide> optimizer.apply_gradients(zip(grad, test_layer.trainable_variables)) <ide> <ide> self.assertNotIn(None, grad) <del> return <ide> <ide> <ide> if __name__ == "__main__":
15
Text
Text
fix parent class of model test example
6ef90c40f21e68a327d25fe8b90613803303a7b9
<ide><path>guides/source/testing.md <ide> within a model: <ide> ```ruby <ide> require 'test_helper' <ide> <del>class ProductTest < ActiveJob::TestCase <add>class ProductTest < ActiveSupport::TestCase <add> include ActiveJob::TestHelper <add> <ide> test 'billing job scheduling' do <ide> assert_enqueued_with(job: BillingJob) do <ide> product.charge(account)
1
Javascript
Javascript
add comparison function to filter
ace54ff08c4593195b49eadb04d258e6409d969e
<ide><path>src/ng/filter/filter.js <ide> * called for each element of `array`. The final result is an array of those elements that <ide> * the predicate returned true for. <ide> * <add> * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in <add> * determining if the expected value (from the filter expression) and actual value (from <add> * the object in the array) should be considered a match. <add> * <add> * Can be one of: <add> * <add> * - `function(expected, actual)`: <add> * The function will be given the object value and the predicate value to compare and <add> * should return true if the item should be included in filtered result. <add> * <add> * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`. <add> * this is essentially strict comparison of expected and actual. <add> * <add> * - `false|undefined`: A short hand for a function which will look for a substring match in case <add> * insensitive way. <add> * <ide> * @example <ide> <doc:example> <ide> <doc:source> <ide> <div ng-init="friends = [{name:'John', phone:'555-1276'}, <ide> {name:'Mary', phone:'800-BIG-MARY'}, <ide> {name:'Mike', phone:'555-4321'}, <ide> {name:'Adam', phone:'555-5678'}, <del> {name:'Julie', phone:'555-8765'}]"></div> <add> {name:'Julie', phone:'555-8765'}, <add> {name:'Juliette', phone:'555-5678'}]"></div> <ide> <ide> Search: <input ng-model="searchText"> <ide> <table id="searchTextResults"> <ide> Any: <input ng-model="search.$"> <br> <ide> Name only <input ng-model="search.name"><br> <ide> Phone only <input ng-model="search.phone"å><br> <add> Equality <input type="checkbox" ng-model="strict"><br> <ide> <table id="searchObjResults"> <ide> <tr><th>Name</th><th>Phone</th><tr> <del> <tr ng-repeat="friend in friends | filter:search"> <add> <tr ng-repeat="friend in friends | filter:search:strict"> <ide> <td>{{friend.name}}</td> <ide> <td>{{friend.phone}}</td> <ide> <tr> <ide> it('should search in specific fields when filtering with a predicate object', function() { <ide> input('search.$').enter('i'); <ide> expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). <del> toEqual(['Mary', 'Mike', 'Julie']); <add> toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); <add> }); <add> it('should use a equal comparison when comparator is true', function() { <add> input('search.name').enter('Julie'); <add> input('strict').check(); <add> expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). <add> toEqual(['Julie']); <ide> }); <ide> </doc:scenario> <ide> </doc:example> <ide> */ <ide> function filterFilter() { <del> return function(array, expression) { <add> return function(array, expression, comperator) { <ide> if (!(array instanceof Array)) return array; <ide> var predicates = []; <ide> predicates.check = function(value) { <ide> function filterFilter() { <ide> } <ide> return true; <ide> }; <add> switch(typeof comperator) { <add> case "function": <add> break; <add> case "boolean": <add> if(comperator == true) { <add> comperator = function(obj, text) { <add> return angular.equals(obj, text); <add> } <add> break; <add> } <add> default: <add> comperator = function(obj, text) { <add> text = (''+text).toLowerCase(); <add> return (''+obj).toLowerCase().indexOf(text) > -1 <add> }; <add> } <ide> var search = function(obj, text){ <del> if (text.charAt(0) === '!') { <add> if (typeof text == 'string' && text.charAt(0) === '!') { <ide> return !search(obj, text.substr(1)); <ide> } <ide> switch (typeof obj) { <ide> case "boolean": <ide> case "number": <ide> case "string": <del> return ('' + obj).toLowerCase().indexOf(text) > -1; <add> return comperator(obj, text); <ide> case "object": <del> for ( var objKey in obj) { <del> if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { <del> return true; <del> } <add> switch (typeof text) { <add> case "object": <add> return comperator(obj, text); <add> break; <add> default: <add> for ( var objKey in obj) { <add> if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { <add> return true; <add> } <add> } <add> break; <ide> } <ide> return false; <ide> case "array": <ide> function filterFilter() { <ide> default: <ide> return false; <ide> } <del> }; <add> }; <ide> switch (typeof expression) { <ide> case "boolean": <ide> case "number": <ide> function filterFilter() { <ide> for (var key in expression) { <ide> if (key == '$') { <ide> (function() { <del> var text = (''+expression[key]).toLowerCase(); <del> if (!text) return; <add> if (!expression[key]) return; <add> var path = key <ide> predicates.push(function(value) { <del> return search(value, text); <add> return search(value, expression[path]); <ide> }); <ide> })(); <ide> } else { <ide> (function() { <add> if (!expression[key]) return; <ide> var path = key; <del> var text = (''+expression[key]).toLowerCase(); <del> if (!text) return; <ide> predicates.push(function(value) { <del> return search(getter(value, path), text); <add> return search(getter(value,path), expression[path]); <ide> }); <ide> })(); <ide> } <ide><path>test/ng/filter/filterSpec.js <ide> describe('Filter: filter', function() { <ide> expect(filter(items, '!isk').length).toBe(1); <ide> expect(filter(items, '!isk')[0]).toEqual(items[1]); <ide> }); <add> <add> describe('should support comparator', function() { <add> <add> it('as equality when true', function() { <add> var items = ['misko', 'adam', 'adamson']; <add> var expr = 'adam'; <add> expect(filter(items, expr, true)).toEqual([items[1]]); <add> expect(filter(items, expr, false)).toEqual([items[1], items[2]]); <add> <add> var items = [ <add> {key: 'value1', nonkey: 1}, <add> {key: 'value2', nonkey: 2}, <add> {key: 'value12', nonkey: 3}, <add> {key: 'value1', nonkey:4}, <add> {key: 'Value1', nonkey:5} <add> ]; <add> var expr = {key: 'value1'}; <add> expect(filter(items, expr, true)).toEqual([items[0], items[3]]); <add> <add> var items = [ <add> {key: 1, nonkey: 1}, <add> {key: 2, nonkey: 2}, <add> {key: 12, nonkey: 3}, <add> {key: 1, nonkey:4} <add> ]; <add> var expr = { key: 1 }; <add> expect(filter(items, expr, true)).toEqual([items[0], items[3]]); <add> <add> var expr = 12; <add> expect(filter(items, expr, true)).toEqual([items[2]]); <add> }); <add> <add> it('and use the function given to compare values', function() { <add> var items = [ <add> {key: 1, nonkey: 1}, <add> {key: 2, nonkey: 2}, <add> {key: 12, nonkey: 3}, <add> {key: 1, nonkey:14} <add> ]; <add> var expr = {key: 10}; <add> var comparator = function (obj,value) { <add> return obj > value; <add> } <add> expect(filter(items, expr, comparator)).toEqual([items[2]]); <add> <add> expr = 10; <add> expect(filter(items, expr, comparator)).toEqual([items[2], items[3]]); <add> <add> }); <add> <add> <add> }); <add> <ide> });
2
PHP
PHP
set container on controller
bb0200154e5945b2d1a6e53cb35b44e7d6e7ca34
<ide><path>src/Illuminate/Routing/Controller.php <ide> <?php namespace Illuminate\Routing; <ide> <ide> use Closure; <add>use Illuminate\Container\Container; <ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; <ide> <ide> abstract class Controller { <ide> abstract class Controller { <ide> protected $afterFilters = array(); <ide> <ide> /** <del> * The route filterer implementation. <add> * The container instance. <ide> * <del> * @var \Illuminate\Routing\RouteFiltererInterface <add> * @var \Illuminate\Container\Container <ide> */ <del> protected static $filterer; <add> protected $container; <ide> <ide> /** <del> * The layout used by the controller. <add> * The route filterer implementation. <ide> * <del> * @var \Illuminate\View\View <add> * @var \Illuminate\Routing\RouteFiltererInterface <ide> */ <del> protected $layout; <add> protected static $filterer; <ide> <ide> /** <ide> * Register a "before" filter on the controller. <ide> public static function setFilterer(RouteFiltererInterface $filterer) <ide> static::$filterer = $filterer; <ide> } <ide> <del> /** <del> * Create the layout used by the controller. <del> * <del> * @return void <del> */ <del> protected function setupLayout() {} <del> <ide> /** <ide> * Execute an action on the controller. <ide> * <ide> protected function setupLayout() {} <ide> */ <ide> public function callAction($method, $parameters) <ide> { <del> $this->setupLayout(); <del> <del> $response = call_user_func_array(array($this, $method), $parameters); <del> <del> // If no response is returned from the controller action and a layout is being <del> // used we will assume we want to just return the layout view as any nested <del> // views were probably bound on this view during this controller actions. <del> if (is_null($response) && ! is_null($this->layout)) <del> { <del> $response = $this->layout; <del> } <del> <del> return $response; <add> return call_user_func_array(array($this, $method), $parameters); <ide> } <ide> <ide> /** <ide> public function missingMethod($parameters = array()) <ide> throw new NotFoundHttpException("Controller method not found."); <ide> } <ide> <add> /** <add> * Set the container instance on the controller. <add> * <add> * @param \Illuminate\Container\Container $container <add> * @return $this <add> */ <add> public function setContainer(Container $container) <add> { <add> $this->container = $container; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Handle calls to missing methods on the controller. <ide> * <ide><path>src/Illuminate/Routing/ControllerDispatcher.php <ide> protected function makeController($controller) <ide> { <ide> Controller::setFilterer($this->filterer); <ide> <del> return $this->container->make($controller); <add> return $this->container->make($controller)->setContainer($this->container); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/helpers.php <ide> function class_uses_recursive($class) <ide> } <ide> } <ide> <add>if ( ! function_exists('config')) <add>{ <add> /** <add> * Get the specified configuration value. <add> * <add> * @param string $key <add> * @param mixed $default <add> * @return mixed <add> */ <add> function config($key, $default = null) <add> { <add> return app('config')->get($key, $default); <add> } <add>} <add> <ide> if ( ! function_exists('csrf_token')) <ide> { <ide> /** <ide><path>tests/Routing/RoutingControllerDispatcherTest.php <ide> public function testBasicDispatchToMethod() <ide> <ide> $response = $dispatcher->dispatch($route, $request, 'ControllerDispatcherTestControllerStub', 'getIndex'); <ide> $this->assertEquals('getIndex', $response); <del> $this->assertEquals('setupLayout', $_SERVER['ControllerDispatcherTestControllerStub']); <ide> } <ide> <ide> <ide> public function __construct() <ide> // construct shouldn't affect setupLayout. <ide> } <ide> <del> protected function setupLayout() <del> { <del> $_SERVER['ControllerDispatcherTestControllerStub'] = __FUNCTION__; <del> } <del> <del> <ide> public function getIndex() <ide> { <ide> return __FUNCTION__;
4
Python
Python
show line which caused the deprecationwarning
ba07f5bd81f66a40333cc619d0a8a7b3c17ec49f
<ide><path>flask/exthook.py <ide> def load_module(self, fullname): <ide> <ide> warnings.warn( <ide> "Importing flask.ext.{x} is deprecated, use flask_{x} instead." <del> .format(x=modname), ExtDeprecationWarning <add> .format(x=modname), ExtDeprecationWarning, stacklevel=2 <ide> ) <ide> <ide> for path in self.module_choices:
1
Text
Text
improve russian translation
0fcb2a971dbbab635e2d402ff327a1cc2e8e463f
<ide><path>guide/russian/python/powxy/index.md <ide> title: Python Powxy <ide> localeTitle: Python Powxy <ide> --- <del>`pow(x, y, z)` является встроенной функцией в Python 3 для вычисления `x` до степени `y` , а если `z` присутствует, возвращает `x` в силу `y` [по модулю](https://processing.org/reference/modulo.html) `z` . <add>`pow(x, y, z)` является встроенной в Python 3 функцией для возведения `x` в степень `y` . Если задано значение `z` , то функция возвращает `x` в степени `y` [деленное по модулю](https://processing.org/reference/modulo.html) `z` . <ide> <del>## аргументы <add>## Аргументы <ide> <del>Аргументы должны иметь числовые типы. Эта функция принимает два аргумента: `x` и `y` , а также три, `x` , `y` и `z` . Если `z` присутствует, `x` и `y` должны быть целочисленных типов, а y должно быть неотрицательным. <add>Аргументы должны иметь числовые типы. <add>Функция может принимать два аргумента: `x` и `y` , а также три: `x` , `y` и `z` . Если значение `z` задано, то значения `x` и `y` должны быть целочисленных типов, а значение `y` должно быть неотрицательным. <ide> <del>## Вернуть <add>## Возвращаемое значение <ide> <del>Если `z` присутствует, он возвращает `x` к мощности `y` по модулю `z` . Если присутствуют только `x` и `y` , он возвращает `x` в силу `y` (то же, что и `x**y` ). <add>Если `z` присутствует, функция возвращает `x` в степени `y`, деленное по модулю `z` . Если присутствуют только `x` и `y` , функция возвращает `x` в степени `y` (то же, что и `x**y` ). <ide> <del>## пример <add>## Пример <ide> <ide> ```python <del>print(pow(2,4)) # prints 16 <del> print(pow(10,-2)) # prints 0.01 <del> print(pow(4,3,5)) # prints 4 <add>print(pow(2,4)) # выводит 16 <add> print(pow(10,-2)) # выводит 0.01 <add> print(pow(4,3,5)) # выводит 4 <ide> ``` <ide> <del>[🚀Конкурс](https://repl.it/CTGi) <add>[🚀Выполнить код](https://repl.it/CTGi) <ide> <del>[Официальная документация](https://docs.python.org/3/library/functions.html#pow) <ide>\ No newline at end of file <add>[Официальная документация](https://docs.python.org/3/library/functions.html#pow)
1
Text
Text
update the userguide to fix user feedback
bf76b1d686018cebd043aa99152d68fbbe6bb977
<ide><path>docs/userguide/index.md <ide> <!--[metadata]> <ide> +++ <ide> title = "User guide" <del>description = "Welcome to the user guide" <del>keywords = ["docker, introduction, documentation, about, technology, docker.io, user, guide, user's, manual, platform, framework, home, intro"] <add>description = "How to use the Docker Engine user guide" <add>keywords = ["engine, introduction, documentation, about, technology, docker, user, guide, framework, home, intro"] <ide> [menu.main] <ide> parent="engine_use" <ide> identifier = "engine_guide" <ide> weight="-80" <ide> +++ <ide> <![end-metadata]--> <ide> <del># User guide <add># Docker Engine user guide <add> <add>This guide helps users learn how to use Docker Engine. <add> <add>- [Introduction to Engine user guide](intro.md) <add> <add>## Learn by example <add> <add>- [Hello world in a container](containers/dockerizing.md) <add>- [Build your own images](containers/dockerimages.md) <add>- [Network containers](containers/networkingcontainers.md) <add>- [Run a simple application](containers/usingdocker.md) <add>- [Manage data in containers](containers/dockervolumes.md) <add>- [Store images on Docker Hub](containers/dockerrepos.md) <add> <add>## Work with images <add> <add>- [Best practices for writing Dockerfiles](eng-image/dockerfile_best-practices.md) <add>- [Create a base image](eng-image/baseimages.md) <add>- [Image management](eng-image/image_management.md) <add> <add>## Manage storage drivers <add> <add>- [Understand images, containers, and storage drivers](storagedriver/imagesandcontainers.md) <add>- [Select a storage driver](storagedriver/selectadriver.md) <add>- [AUFS storage in practice](storagedriver/aufs-driver.md) <add>- [Btrfs storage in practice](storagedriver/btrfs-driver.md) <add>- [Device Mapper storage in practice](storagedriver/device-mapper-driver.md) <add>- [OverlayFS storage in practice](storagedriver/overlayfs-driver.md) <add>- [ZFS storage in practice](storagedriver/zfs-driver.md) <add> <add>## Configure networks <add> <add>- [Understand Docker container networks](networking/dockernetworks.md) <add>- [Embedded DNS server in user-defined networks](networking/configure-dns.md) <add>- [Get started with multi-host networking](networking/get-started-overlay.md) <add>- [Work with network commands](networking/work-with-networks.md) <add> <add>### Work with the default network <add> <add>- [Understand container communication](networking/default_network/container-communication.md) <add>- [Legacy container links](networking/default_network/dockerlinks.md) <add>- [Binding container ports to the host](networking/default_network/binding.md) <add>- [Build your own bridge](networking/default_network/build-bridges.md) <add>- [Configure container DNS](networking/default_network/configure-dns.md) <add>- [Customize the docker0 bridge](networking/default_network/custom-docker0.md) <add>- [IPv6 with Docker](networking/default_network/ipv6.md) <add> <add>## Misc <add> <add>- [Apply custom metadata](labels-custom-metadata.md) <ide><path>docs/userguide/networking/default_network/options.md <del><!--[metadata]> <del>+++ <del>draft=true <del>title = "Tools and Examples" <del>keywords = ["docker, bridge, docker0, network"] <del>[menu.main] <del>parent = "smn_networking_def" <del>+++ <del><![end-metadata]--> <del> <del><!--[metadata]> <del>We may want to add it back in later under another form. Labeled DRAFT for now. Won't be built. <del><![end-metadata]--> <del> <del># Quick guide to the options <del>Here is a quick list of the networking-related Docker command-line options, in case it helps you find the section below that you are looking for. <del> <del>Some networking command-line options can only be supplied to the Docker server when it starts up, and cannot be changed once it is running: <del>- `-b BRIDGE` or `--bridge=BRIDGE` -- see <del> <del> [Building your own bridge](#bridge-building) <del> <del>- `--bip=CIDR` -- see <del> <del> [Customizing docker0](#docker0) <del> <del>- `--default-gateway=IP_ADDRESS` -- see <del> <del> [How Docker networks a container](#container-networking) <del> <del>- `--default-gateway-v6=IP_ADDRESS` -- see <del> <del> [IPv6](#ipv6) <del> <del>- `--fixed-cidr` -- see <del> <del> [Customizing docker0](#docker0) <del> <del>- `--fixed-cidr-v6` -- see <del> <del> [IPv6](#ipv6) <del> <del>- `-H SOCKET...` or `--host=SOCKET...` -- <del> <del> This might sound like it would affect container networking, <del> <del> but it actually faces in the other direction: <del> <del> it tells the Docker server over what channels <del> <del> it should be willing to receive commands <del> <del> like "run container" and "stop container." <del> <del>- `--icc=true|false` -- see <del> <del> [Communication between containers](#between-containers) <del> <del>- `--ip=IP_ADDRESS` -- see <del> <del> [Binding container ports](#binding-ports) <del> <del>- `--ipv6=true|false` -- see <del> <del> [IPv6](#ipv6) <del> <del>- `--ip-forward=true|false` -- see <del> <del> [Communication between containers and the wider world](#the-world) <del> <del>- `--iptables=true|false` -- see <del> <del> [Communication between containers](#between-containers) <del> <del>- `--mtu=BYTES` -- see <del> <del> [Customizing docker0](#docker0) <del> <del>- `--userland-proxy=true|false` -- see <del> <del> [Binding container ports](#binding-ports) <del> <del>There are three networking options that can be supplied either at startup or when `docker run` is invoked. When provided at startup, set the default value that `docker run` will later use if the options are not specified: <del>- `--dns=IP_ADDRESS...` -- see <del> <del> [Configuring DNS](#dns) <del> <del>- `--dns-search=DOMAIN...` -- see <del> <del> [Configuring DNS](#dns) <del> <del>- `--dns-opt=OPTION...` -- see <del> <del> [Configuring DNS](#dns) <del> <del>Finally, several networking options can only be provided when calling `docker run` because they specify something specific to one container: <del>- `-h HOSTNAME` or `--hostname=HOSTNAME` -- see <del> <del> [Configuring DNS](#dns) and <del> <del> [How Docker networks a container](#container-networking) <del> <del>- `--link=CONTAINER_NAME_or_ID:ALIAS` -- see <del> <del> [Configuring DNS](#dns) and <del> <del> [Communication between containers](#between-containers) <del> <del>- `--net=bridge|none|container:NAME_or_ID|host` -- see <del> <del> [How Docker networks a container](#container-networking) <del> <del>- `--mac-address=MACADDRESS...` -- see <del> <del> [How Docker networks a container](#container-networking) <del> <del>- `-p SPEC` or `--publish=SPEC` -- see <del> <del> [Binding container ports](#binding-ports) <del> <del>- `-P` or `--publish-all=true|false` -- see <del> <del> [Binding container ports](#binding-ports) <del> <del>To supply networking options to the Docker server at startup, use the `DOCKER_OPTS` variable in the Docker upstart configuration file. For Ubuntu, edit the variable in `/etc/default/docker` or `/etc/sysconfig/docker` for CentOS. <del> <del>The following example illustrates how to configure Docker on Ubuntu to recognize a newly built bridge. <del> <del>Edit the `/etc/default/docker` file: <del> <del>``` <del>$ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker <del>``` <del> <del>Then restart the Docker server. <del> <del>``` <del>$ sudo service docker start <del>``` <del> <del>For additional information on bridges, see [building your own bridge](#building-your-own-bridge) later on this page. <ide><path>docs/userguide/networking/default_network/saveme.md <del><!--[metadata]> <del>+++ <del>draft=true <del>title = "Saved text" <del>keywords = ["docker, bridge, docker0, network"] <del>[menu.main] <del>parent = "smn_networking_def" <del>+++ <del><![end-metadata]--> <del> <del><!--[metadata]> <del>This content was extracted from the original introduction. We may want to add it back in later under another form. Labeled DRAFT for now. Won't be built. <del><![end-metadata]--> <del> <del> <del>## A Brief introduction to networking and docker <del>When Docker starts, it creates a virtual interface named `docker0` on the host machine. It randomly chooses an address and subnet from the private range defined by [RFC 1918](http://tools.ietf.org/html/rfc1918) that are not in use on the host machine, and assigns it to `docker0`. Docker made the choice `172.17.42.1/16` when I started it a few minutes ago, for example -- a 16-bit netmask providing 65,534 addresses for the host machine and its containers. The MAC address is generated using the IP address allocated to the container to avoid ARP collisions, using a range from `02:42:ac:11:00:00` to `02:42:ac:11:ff:ff`. <del> <del>> **Note:** This document discusses advanced networking configuration and options for Docker. In most cases you won't need this information. If you're looking to get started with a simpler explanation of Docker networking and an introduction to the concept of container linking see the [Docker User Guide](dockerlinks.md). <del> <del>But `docker0` is no ordinary interface. It is a virtual _Ethernet bridge_ that automatically forwards packets between any other network interfaces that are attached to it. This lets containers communicate both with the host machine and with each other. Every time Docker creates a container, it creates a pair of "peer" interfaces that are like opposite ends of a pipe -- a packet sent on one will be received on the other. It gives one of the peers to the container to become its `eth0` interface and keeps the other peer, with a unique name like `vethAQI2QT`, out in the namespace of the host machine. By binding every `veth*` interface to the `docker0` bridge, Docker creates a virtual subnet shared between the host machine and every Docker container. <del> <del>The remaining sections of this document explain all of the ways that you can use Docker options and -- in advanced cases -- raw Linux networking commands to tweak, supplement, or entirely replace Docker's default networking configuration. <del> <del>## Editing networking config files <del>Starting with Docker v.1.2.0, you can now edit `/etc/hosts`, `/etc/hostname` and `/etc/resolve.conf` in a running container. This is useful if you need to install bind or other services that might override one of those files. <del> <del>Note, however, that changes to these files will not be saved by `docker commit`, nor will they be saved during `docker run`. That means they won't be saved in the image, nor will they persist when a container is restarted; they will only "stick" in a running container. <ide><path>docs/userguide/networking/default_network/tools.md <del><!--[metadata]> <del>+++ <del>draft=true <del>title = "Tools and Examples" <del>keywords = ["docker, bridge, docker0, network"] <del>[menu.main] <del>parent = "smn_networking_def" <del>+++ <del><![end-metadata]--> <del> <del><!--[metadata]> <del>Dave Tucker instructed remove this. We may want to add it back in later under another form. Labeled DRAFT for now. Won't be built. <del><![end-metadata]--> <del> <del># Tools and examples <del>Before diving into the following sections on custom network topologies, you might be interested in glancing at a few external tools or examples of the same kinds of configuration. Here are two: <del>- Jérôme Petazzoni has created a `pipework` shell script to help you <del> <del> connect together containers in arbitrarily complex scenarios: <del> <del> [https://github.com/jpetazzo/pipework](https://github.com/jpetazzo/pipework) <del> <del>- Brandon Rhodes has created a whole network topology of Docker <del> <del> containers for the next edition of Foundations of Python Network <del> <del> Programming that includes routing, NAT'd firewalls, and servers that <del> <del> offer HTTP, SMTP, POP, IMAP, Telnet, SSH, and FTP: <del> <del> [https://github.com/brandon-rhodes/fopnp/tree/m/playground](https://github.com/brandon-rhodes/fopnp/tree/m/playground) <del> <del>Both tools use networking commands very much like the ones you saw in the previous section, and will see in the following sections. <del> <del># Building a point-to-point connection <del><a name="point-to-point"></a> <del> <del>By default, Docker attaches all containers to the virtual subnet implemented by `docker0`. You can create containers that are each connected to some different virtual subnet by creating your own bridge as shown in [Building your own bridge](#bridge-building), starting each container with `docker run --net=none`, and then attaching the containers to your bridge with the shell commands shown in [How Docker networks a container](#container-networking). <del> <del>But sometimes you want two particular containers to be able to communicate directly without the added complexity of both being bound to a host-wide Ethernet bridge. <del> <del>The solution is simple: when you create your pair of peer interfaces, simply throw _both_ of them into containers, and configure them as classic point-to-point links. The two containers will then be able to communicate directly (provided you manage to tell each container the other's IP address, of course). You might adjust the instructions of the previous section to go something like this: <del> <del>``` <del># Start up two containers in two terminal windows <del> <del>$ docker run -i -t --rm --net=none base /bin/bash <del>root@1f1f4c1f931a:/# <del> <del>$ docker run -i -t --rm --net=none base /bin/bash <del>root@12e343489d2f:/# <del> <del># Learn the container process IDs <del># and create their namespace entries <del> <del>$ docker inspect -f '{{.State.Pid}}' 1f1f4c1f931a <del>2989 <del>$ docker inspect -f '{{.State.Pid}}' 12e343489d2f <del>3004 <del>$ sudo mkdir -p /var/run/netns <del>$ sudo ln -s /proc/2989/ns/net /var/run/netns/2989 <del>$ sudo ln -s /proc/3004/ns/net /var/run/netns/3004 <del> <del># Create the "peer" interfaces and hand them out <del> <del>$ sudo ip link add A type veth peer name B <del> <del>$ sudo ip link set A netns 2989 <del>$ sudo ip netns exec 2989 ip addr add 10.1.1.1/32 dev A <del>$ sudo ip netns exec 2989 ip link set A up <del>$ sudo ip netns exec 2989 ip route add 10.1.1.2/32 dev A <del> <del>$ sudo ip link set B netns 3004 <del>$ sudo ip netns exec 3004 ip addr add 10.1.1.2/32 dev B <del>$ sudo ip netns exec 3004 ip link set B up <del>$ sudo ip netns exec 3004 ip route add 10.1.1.1/32 dev B <del>``` <del> <del>The two containers should now be able to ping each other and make connections successfully. Point-to-point links like this do not depend on a subnet nor a netmask, but on the bare assertion made by `ip route` that some other single IP address is connected to a particular network interface. <del> <del>Note that point-to-point links can be safely combined with other kinds of network connectivity -- there is no need to start the containers with `--net=none` if you want point-to-point links to be an addition to the container's normal networking instead of a replacement. <del> <del>A final permutation of this pattern is to create the point-to-point link between the Docker host and one container, which would allow the host to communicate with that one container on some single IP address and thus communicate "out-of-band" of the bridge that connects the other, more usual containers. But unless you have very specific networking needs that drive you to such a solution, it is probably far preferable to use `--icc=false` to lock down inter-container communication, as we explored earlier.
4
Text
Text
remove reference to "credentials object"
f11f1808785fee9741436dfb43a87e2050d8b3af
<ide><path>doc/api/tls.md <ide> to `true`, other APIs that create secure contexts leave it unset. <ide> from `process.argv` as the default value of the `sessionIdContext` option, other <ide> APIs that create secure contexts have no default value. <ide> <del>The `tls.createSecureContext()` method creates a credentials object. <add>The `tls.createSecureContext()` method creates a `SecureContext` object. It is <add>usable as an argument to several `tls` APIs, such as [`tls.createServer()`][] <add>and [`server.addContext()`][], but has no public methods. <ide> <ide> A key is *required* for ciphers that make use of certificates. Either `key` or <ide> `pfx` can be used to provide it. <ide> where `secureSocket` has the same API as `pair.cleartext`. <ide> [`net.Server.address()`]: net.html#net_server_address <ide> [`net.Server`]: net.html#net_class_net_server <ide> [`net.Socket`]: net.html#net_class_net_socket <add>[`server.addContext()`]: #tls_server_addcontext_hostname_context <ide> [`server.getConnections()`]: net.html#net_server_getconnections_callback <ide> [`server.getTicketKeys()`]: #tls_server_getticketkeys <ide> [`server.listen()`]: net.html#net_server_listen
1
Go
Go
improve interface order
67dbb048520513de23be771d5e677a4103e173ec
<ide><path>libnetwork/sandbox.go <ide> func OptionIngress() SandboxOption { <ide> } <ide> } <ide> <add>// <=> Returns true if a < b, false if a > b and advances to next level if a == b <add>// epi.prio <=> epj.prio # 2 < 1 <add>// epi.gw <=> epj.gw # non-gw < gw <add>// epi.internal <=> epj.internal # non-internal < internal <add>// epi.joininfo <=> epj.joininfo # ipv6 < ipv4 <add>// epi.name <=> epj.name # bar < foo <ide> func (epi *endpoint) Less(epj *endpoint) bool { <ide> var ( <del> cip, cjp int <del> ok bool <add> prioi, prioj int <ide> ) <ide> <del> ci, _ := epi.getSandbox() <del> cj, _ := epj.getSandbox() <add> sbi, _ := epi.getSandbox() <add> sbj, _ := epj.getSandbox() <ide> <del> if epi.endpointInGWNetwork() { <del> return false <add> // Prio defaults to 0 <add> if sbi != nil { <add> prioi = sbi.epPriority[epi.ID()] <add> } <add> if sbj != nil { <add> prioj = sbj.epPriority[epj.ID()] <ide> } <ide> <del> if epj.endpointInGWNetwork() { <del> return true <add> if prioi != prioj { <add> return prioi > prioj <ide> } <ide> <del> if epi.getNetwork().Internal() { <del> return false <add> gwi := epi.endpointInGWNetwork() <add> gwj := epj.endpointInGWNetwork() <add> if gwi != gwj { <add> return gwj <ide> } <ide> <del> if epj.getNetwork().Internal() { <del> return true <add> inti := epi.getNetwork().Internal() <add> intj := epj.getNetwork().Internal() <add> if inti != intj { <add> return intj <ide> } <ide> <del> if epi.joinInfo != nil && epj.joinInfo != nil { <del> if (epi.joinInfo.gw != nil && epi.joinInfo.gw6 != nil) && <del> (epj.joinInfo.gw == nil || epj.joinInfo.gw6 == nil) { <del> return true <add> jii := 0 <add> if epi.joinInfo != nil { <add> if epi.joinInfo.gw != nil { <add> jii = jii + 1 <ide> } <del> if (epj.joinInfo.gw != nil && epj.joinInfo.gw6 != nil) && <del> (epi.joinInfo.gw == nil || epi.joinInfo.gw6 == nil) { <del> return false <add> if epi.joinInfo.gw6 != nil { <add> jii = jii + 2 <ide> } <ide> } <ide> <del> if ci != nil { <del> cip, ok = ci.epPriority[epi.ID()] <del> if !ok { <del> cip = 0 <add> jij := 0 <add> if epj.joinInfo != nil { <add> if epj.joinInfo.gw != nil { <add> jij = jij + 1 <ide> } <del> } <del> <del> if cj != nil { <del> cjp, ok = cj.epPriority[epj.ID()] <del> if !ok { <del> cjp = 0 <add> if epj.joinInfo.gw6 != nil { <add> jij = jij + 2 <ide> } <ide> } <ide> <del> if cip == cjp { <del> return epi.network.Name() < epj.network.Name() <add> if jii != jij { <add> return jii > jij <ide> } <ide> <del> return cip > cjp <add> return epi.network.Name() < epj.network.Name() <ide> } <ide> <ide> func (sb *sandbox) NdotsSet() bool { <ide><path>libnetwork/sandbox_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/libnetwork/config" <add> "github.com/docker/libnetwork/ipamapi" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/options" <ide> "github.com/docker/libnetwork/osl" <ide> "github.com/docker/libnetwork/testutils" <ide> ) <ide> <del>func getTestEnv(t *testing.T, numNetworks int) (NetworkController, []Network) { <add>func getTestEnv(t *testing.T, opts ...[]NetworkOption) (NetworkController, []Network) { <ide> netType := "bridge" <ide> <ide> option := options.Generic{ <ide> func getTestEnv(t *testing.T, numNetworks int) (NetworkController, []Network) { <ide> t.Fatal(err) <ide> } <ide> <del> if numNetworks == 0 { <add> if len(opts) == 0 { <ide> return c, nil <ide> } <ide> <del> nwList := make([]Network, 0, numNetworks) <del> for i := 0; i < numNetworks; i++ { <add> nwList := make([]Network, 0, len(opts)) <add> for i, opt := range opts { <ide> name := fmt.Sprintf("test_nw_%d", i) <ide> netOption := options.Generic{ <ide> netlabel.GenericData: options.Generic{ <ide> "BridgeName": name, <ide> }, <ide> } <del> n, err := c.NewNetwork(netType, name, "", NetworkOptionGeneric(netOption)) <add> newOptions := make([]NetworkOption, 1, len(opt)+1) <add> newOptions[0] = NetworkOptionGeneric(netOption) <add> newOptions = append(newOptions, opt...) <add> n, err := c.NewNetwork(netType, name, "", newOptions...) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func getTestEnv(t *testing.T, numNetworks int) (NetworkController, []Network) { <ide> } <ide> <ide> func TestSandboxAddEmpty(t *testing.T) { <del> c, _ := getTestEnv(t, 0) <add> c, _ := getTestEnv(t) <ide> ctrlr := c.(*controller) <ide> <ide> sbx, err := ctrlr.NewSandbox("sandbox0") <ide> func TestSandboxAddEmpty(t *testing.T) { <ide> osl.GC() <ide> } <ide> <add>// // If different priorities are specified, internal option and ipv6 addresses mustn't influence endpoint order <ide> func TestSandboxAddMultiPrio(t *testing.T) { <ide> if !testutils.IsRunningInContainer() { <ide> defer testutils.SetupTestOSContext(t)() <ide> } <ide> <del> c, nws := getTestEnv(t, 3) <add> opts := [][]NetworkOption{ <add> {NetworkOptionEnableIPv6(true), NetworkOptionIpam(ipamapi.DefaultIPAM, "", nil, []*IpamConf{{PreferredPool: "fe90::/64"}}, nil)}, <add> {NetworkOptionInternalNetwork()}, <add> {}, <add> } <add> <add> c, nws := getTestEnv(t, opts...) <ide> ctrlr := c.(*controller) <ide> <ide> sbx, err := ctrlr.NewSandbox("sandbox1") <ide> func TestSandboxAddSamePrio(t *testing.T) { <ide> defer testutils.SetupTestOSContext(t)() <ide> } <ide> <del> c, nws := getTestEnv(t, 2) <add> opts := [][]NetworkOption{ <add> {}, <add> {}, <add> {NetworkOptionEnableIPv6(true), NetworkOptionIpam(ipamapi.DefaultIPAM, "", nil, []*IpamConf{{PreferredPool: "fe90::/64"}}, nil)}, <add> {NetworkOptionInternalNetwork()}, <add> } <add> <add> c, nws := getTestEnv(t, opts...) <ide> <ide> ctrlr := c.(*controller) <ide> <ide> func TestSandboxAddSamePrio(t *testing.T) { <ide> } <ide> sid := sbx.ID() <ide> <del> ep1, err := nws[0].CreateEndpoint("ep1") <add> epNw1, err := nws[1].CreateEndpoint("ep1") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> ep2, err := nws[1].CreateEndpoint("ep2") <add> epIPv6, err := nws[2].CreateEndpoint("ep2") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := ep1.Join(sbx); err != nil { <add> epInternal, err := nws[3].CreateEndpoint("ep3") <add> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := ep2.Join(sbx); err != nil { <add> epNw0, err := nws[0].CreateEndpoint("ep4") <add> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if ctrlr.sandboxes[sid].endpoints[0].ID() != ep1.ID() { <del> t.Fatal("Expected ep1 to be at the top of the heap. But did not find ep1 at the top of the heap") <add> if err := epNw1.Join(sbx); err != nil { <add> t.Fatal(err) <ide> } <ide> <del> if err := ep1.Leave(sbx); err != nil { <add> if err := epIPv6.Join(sbx); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if ctrlr.sandboxes[sid].endpoints[0].ID() != ep2.ID() { <del> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap") <add> if err := epInternal.Join(sbx); err != nil { <add> t.Fatal(err) <ide> } <ide> <del> if err := ep2.Leave(sbx); err != nil { <add> if err := epNw0.Join(sbx); err != nil { <add> t.Fatal(err) <add> } <add> <add> // order should now be: epIPv6, epNw0, epNw1, epInternal <add> if len(sbx.Endpoints()) != 4 { <add> t.Fatal("Expected 4 endpoints to be connected to the sandbox.") <add> } <add> <add> // IPv6 has precedence over IPv4 <add> if ctrlr.sandboxes[sid].endpoints[0].ID() != epIPv6.ID() { <add> t.Fatal("Expected epIPv6 to be at the top of the heap. But did not find epIPv6 at the top of the heap") <add> } <add> <add> // internal network has lowest precedence <add> if ctrlr.sandboxes[sid].endpoints[3].ID() != epInternal.ID() { <add> t.Fatal("Expected epInternal to be at the bottom of the heap. But did not find epInternal at the bottom of the heap") <add> } <add> <add> if err := epIPv6.Leave(sbx); err != nil { <add> t.Fatal(err) <add> } <add> <add> // 'test_nw_0' has precedence over 'test_nw_1' <add> if ctrlr.sandboxes[sid].endpoints[0].ID() != epNw0.ID() { <add> t.Fatal("Expected epNw0 to be at the top of the heap after removing epIPv6. But did not find epNw0 at the top of the heap") <add> } <add> <add> if err := epNw1.Leave(sbx); err != nil { <ide> t.Fatal(err) <ide> } <ide>
2
Javascript
Javascript
destructure primordials in lib/_http_server.js
0d285276f8028fdeb2c16ad47e09e9cd022f3a90
<ide><path>lib/_http_server.js <ide> <ide> 'use strict'; <ide> <del>const { Object } = primordials; <add>const { <add> Object: { <add> setPrototypeOf: ObjectSetPrototypeOf, <add> keys: ObjectKeys, <add> } <add>} = primordials; <ide> <ide> const net = require('net'); <ide> const assert = require('internal/assert'); <ide> function ServerResponse(req) { <ide> }; <ide> } <ide> } <del>Object.setPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype); <del>Object.setPrototypeOf(ServerResponse, OutgoingMessage); <add>ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype); <add>ObjectSetPrototypeOf(ServerResponse, OutgoingMessage); <ide> <ide> ServerResponse.prototype._finish = function _finish() { <ide> DTRACE_HTTP_SERVER_RESPONSE(this.socket); <ide> function writeHead(statusCode, reason, obj) { <ide> // Slow-case: when progressive API and header fields are passed. <ide> let k; <ide> if (obj) { <del> const keys = Object.keys(obj); <del> for (let i = 0; i < keys.length; i++) { <add> const keys = ObjectKeys(obj); <add> for (var i = 0; i < keys.length; i++) { <ide> k = keys[i]; <ide> if (k) this.setHeader(k, obj[k]); <ide> } <ide> function Server(options, requestListener) { <ide> this.maxHeadersCount = null; <ide> this.headersTimeout = 40 * 1000; // 40 seconds <ide> } <del>Object.setPrototypeOf(Server.prototype, net.Server.prototype); <del>Object.setPrototypeOf(Server, net.Server); <add>ObjectSetPrototypeOf(Server.prototype, net.Server.prototype); <add>ObjectSetPrototypeOf(Server, net.Server); <ide> <ide> <ide> Server.prototype.setTimeout = function setTimeout(msecs, callback) {
1
Ruby
Ruby
prepare the statement before we cache the key
1b4e0b654210d024989dd4b46311807e2c823bdb
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def initialize(connection, logger, connection_parameters, config) <ide> @local_tz = nil <ide> @table_alias_length = nil <ide> @postgresql_version = nil <del> @statements = Hash.new { |h,k| h[k] = "a#{h.length + 1}" } <add> @statements = {} <ide> <ide> connect <ide> @local_tz = execute('SHOW TIME ZONE').first["TimeZone"] <ide> def exec(sql, name = 'SQL', binds = []) <ide> def async_exec(sql, name, binds) <ide> log(sql, name) do <ide> unless @statements.key? sql <del> @connection.prepare @statements[sql], sql <add> nextkey = "a#{@statements.length + 1}" <add> @connection.prepare nextkey, sql <add> @statements[sql] = nextkey <ide> end <ide> <ide> key = @statements[sql]
1
Text
Text
add link to show k-means
56a42de7b109a001991d1abe55b1bb2c2d104129
<ide><path>guide/english/machine-learning/clustering-algorithms/index.md <ide> plt.show() <ide> <ide> Since the data points belong usually to a high-dimensional space, the similarity measure is often defined as a distance between two vectors (Euclidean, Manhathan, Cosine, Mahalanobis...) <ide> <add>Here's a visualization of K-means that allows you to change the number of clusters and centroids to show how k data points converge into clusters around the closest centroid: [Visualizing K-Means](http://stanford.edu/class/ee103/visualizations/kmeans/kmeans.html) <add> <ide> ### Mixture Density <ide> We can write *mixture density* as: <ide> ![mixture density](https://latex.codecogs.com/gif.latex?p%28x%29%20%3D%20%5Csum_%7Bi%3D1%7D%5E%7Bk%7Dp%28x%7CG_%7Bi%7D%29p%28G_%7Bi%7D%29)
1
PHP
PHP
fix typo in class name
c1e358dde5513bf64b38ae7375e2d119589ed07d
<ide><path>lib/Cake/Test/TestCase/Cache/Engine/RedisEngineTest.php <ide> * <ide> * @package Cake.Test.Case.Cache.Engine <ide> */ <del>class RegisEngineTest extends TestCase { <add>class RedisEngineTest extends TestCase { <ide> <ide> /** <ide> * setUp method
1
Javascript
Javascript
unpublish the function as it is not public
14183833f9106a3ab4c7621bcf964fc2b5cc96e6
<ide><path>src/Angular.js <ide> function reloadWithDebugInfo() { <ide> } <ide> <ide> /** <del> * @ngdoc function <ide> * @name angular.getTestability <ide> * @module ng <ide> * @description
1
Text
Text
add article for completing the square
43174378c995d17a8c24800a6ceb769c99e9ffff
<ide><path>client/src/pages/guide/english/mathematics/completing-the-square/index.md <ide> title: Completing the Square <ide> --- <ide> ## Completing the Square <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/completing-the-square/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>The completing the square method is one of the many methods for solving a <a href='https://guide.freecodecamp.org/mathematics/quadratic-equations' target='_blank'>quadratic eduation</a>. It involves changing the form of the equation so that the left side becomes a perfect square. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>A quadratic equation generally takes the form: <em>ax<sup>2</sup> + bx + c</em> = 0. In solving the above, follow the following steps: <add> <add>1. Move the constant value to the Right Hand Side of the equation so it becomes: <br> <add><pre><em>ax<sup>2</sup> + bx = -c</em></pre> <add> <add>2. Make the coefficient of x<sup>2</sup> equal to 1 by dividing both sides of the equation by <em>a</em> so that we now have: <br> <add><pre>x<sup>2</sup> + (<sup>b</sup>/<sub>a</sub>)x = - (<sup>c</sup>/<sub>a</sub>)</pre> <add> <add>3. Next, add the square of half of the coefficient of the <em>x</em>-term to both sides of the equation: <br> <add><pre>x<sup>2</sup> + (<sup>b</sup>/<sub>a</sub>)x + (<sup>b</sup>/<sub>2a</sub>)<sup>2</sup> = (<sup>b</sup>/<sub>2a</sub>)<sup>2</sup> - (<sup>c</sup>/<sub>a</sub>)</pre> <add> <add>4. Completing the square on the Left Hand Side and simplifying the Right Hand Side of the above equation, we have: <add><pre>(x<sup></sup> + <sup>b</sup>/<sub>2a</sub>)<sup>2</sup> = (<sup>b<sup>2</sup></sup>/<sub>4a<sup>2</sup></sub>) - (<sup>c</sup>/<sub>a</sub>)</pre> <add> <add>5. Further simplpfying the Right Hand Side, <add><pre>(x<sup></sup> + <sup>b</sup>/<sub>2a</sub>)<sup>2</sup> = (b<sup>2</sup> - 4ac)/4a<sup>2</sup> </pre> <add> <add>6. Finding the square root of both sides of the equation, <add><pre>x<sup></sup> + <sup>b</sup>/<sub>2a</sub> = &radic;(b<sup>2</sup> - 4ac) &divide; 2a </pre> <add> <add>7. By making x the subject of our formula, we are able to solve for its value completely: <add><pre>x<sup></sup> = -b &#177; &radic;(b<sup>2</sup> - 4ac) &divide; 2a </pre> <ide> <ide> #### More Information: <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <del> <add>* [Varsity Tutors](https://www.varsitytutors.com/hotmath/hotmath_help/topics/completing-the-square) <add>* [Maths is Fun](https://www.mathsisfun.com/algebra/completing-square.html) <ide>
1
Text
Text
remove bold typography from style_guide.md
a206bab4197509f8a46dbeebb8070522aeec10c1
<ide><path>doc/STYLE_GUIDE.md <ide> # Style Guide <ide> <del>* Documents are written in markdown files. <del>* Those files should be written in **`lowercase-with-dashes.md`**. <add>* Documentation is written in markdown files with names formatted as <add> `lowercase-with-dashes.md`. <ide> * Underscores in filenames are allowed only when they are present in the <ide> topic the document will describe (e.g., `child_process`). <del> * Filenames should be **lowercase**. <ide> * Some files, such as top-level markdown files, are exceptions. <ide> * Documents should be word-wrapped at 80 characters. <ide> * The formatting described in `.editorconfig` is preferred. <ide> * Generally avoid personal pronouns in reference documentation ("I", "you", <ide> "we"). <ide> * Pronouns are acceptable in more colloquial documentation, like guides. <del> * Use **gender-neutral pronouns** and **mass nouns**. Non-comprehensive <add> * Use gender-neutral pronouns and mass nouns. Non-comprehensive <ide> examples: <del> * **OK**: "they", "their", "them", "folks", "people", "developers", "cats" <del> * **NOT OK**: "his", "hers", "him", "her", "guys", "dudes" <add> * OK: "they", "their", "them", "folks", "people", "developers", "cats" <add> * NOT OK: "his", "hers", "him", "her", "guys", "dudes" <ide> * When combining wrapping elements (parentheses and quotes), terminal <ide> punctuation should be placed: <ide> * Inside the wrapping element if the wrapping element contains a complete <ide> is necessary, include it as an asset in `assets/code-examples` and link to <ide> it. <ide> * When using underscores, asterisks, and backticks, please use proper escaping <del> (**\\\_**, **\\\*** and **\\\`** instead of **\_**, **\*** and **\`**). <add> (`\_`, `\*` and ``\` `` instead of `_`, `*` and `` ` ``). <ide> * References to constructor functions should use PascalCase. <ide> * References to constructor instances should use camelCase. <ide> * References to methods should be used with parentheses: for example,
1
Python
Python
set version to v3.0.0a13
9341cbc013b4f471654d1fd5ad79a0827e572545
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy-nightly" <del>__version__ = "3.0.0a12" <add>__version__ = "3.0.0a13" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Ruby
Ruby
add install script for testing gems locally
f79f9a74a4b593e8c36d14c43a030b9a12c69255
<ide><path>install.rb <add>version = ARGV.pop <add> <add>%w( activesupport activemodel activerecord activeresource actionpack actionmailer railties ).each do |framework| <add> puts "Installing #{framework}..." <add> `cd #{framework} && gem build #{framework}.gemspec && gem install #{framework}-#{version}.gem --no-ri --no-rdoc && rm #{framework}-#{version}.gem` <add>end <add> <add>puts "Installing Rails..." <add>`gem build rails.gemspec` <add>`gem install rails-#{version}.gem --no-ri --no-rdoc ` <add>`rm rails-#{version}.gem` <ide>\ No newline at end of file
1
Javascript
Javascript
add note about recursive compilation in templates
7a7e9f4047812bf3317203c7fd618a8859a886a4
<ide><path>src/ng/compile.js <ide> * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration <ide> * should be done in a linking function rather than in a compile function. <ide> * </div> <add> <add> * <div class="alert alert-warning"> <add> * **Note:** The compile function cannot handle directives that recursively use themselves in their <add> * own templates or compile functions. Compiling these directives results in an infinite loop and a <add> * stack overflow errors. <add> * <add> * This can be avoided by manually using $compile in the postLink function to imperatively compile <add> * a directive's template instead of relying on automatic template compilation via `template` or <add> * `templateUrl` declaration or manual compilation inside the compile function. <add> * </div> <ide> * <ide> * <div class="alert alert-error"> <ide> * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
1
Javascript
Javascript
fix ie failures from 55313d32
f42e1e654f43e9207c5b2f651c410f344982c2b5
<ide><path>test/unit/core.js <ide> test("jQuery.proxy", function(){ <ide> }); <ide> <ide> test("jQuery.parseHTML", function() { <del> expect( 11 ); <add> expect( 12 ); <add> <add> var html, nodes; <ide> <ide> equal( jQuery.parseHTML(), null, "Nothing in, null out." ); <del> equal( jQuery.parseHTML( null ), null, "Nothing in, null out." ); <del> equal( jQuery.parseHTML( "" ), null, "Nothing in, null out." ); <add> equal( jQuery.parseHTML( null ), null, "Null in, null out." ); <add> equal( jQuery.parseHTML( "" ), null, "Empty string in, null out." ); <ide> raises(function() { <del> jQuery.parseHTML( "<div>", document.getElementById("form") ); <add> jQuery.parseHTML( "<div></div>", document.getElementById("form") ); <ide> }, "Passing an element as the context raises an exception (context should be a document)"); <ide> <del> var elems = jQuery.parseHTML( jQuery("body").html() ); <del> ok( elems.length > 10, "Parse a large html string" ); <del> equal( jQuery.type( elems ), "array", "parseHTML returns an array rather than a nodelist" ); <add> nodes = jQuery.parseHTML( jQuery("body")[0].innerHTML ); <add> ok( nodes.length > 4, "Parse a large html string" ); <add> equal( jQuery.type( nodes ), "array", "parseHTML returns an array rather than a nodelist" ); <ide> <del> var script = "<script>undefined()</script>"; <del> equal( jQuery.parseHTML( script ).length, 0, "Passing a script is not allowed by default" ); <del> raises(function() { <del> jQuery(jQuery.parseHTML( script, true )).appendTo("#qunit-fixture"); <del> }, "Passing a script is allowed if allowScripts is true"); <add> html = "<script>undefined()</script>"; <add> equal( jQuery.parseHTML( html ).length, 0, "Ignore scripts by default" ); <add> equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve scripts when requested" ); <ide> <del> var html = script + "<div></div>"; <del> equal( jQuery.parseHTML( html )[0].nodeName.toLowerCase(), "div", "Ignore scripts by default" ); <del> raises(function() { <del> jQuery(jQuery.parseHTML( html, true )).appendTo("#qunit-fixture"); <del> }, "Passing a script is allowed if allowScripts is true"); <add> html += "<div></div>"; <add> equal( jQuery.parseHTML( html )[0].nodeName.toLowerCase(), "div", "Preserve non-script nodes" ); <add> equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve script position"); <ide> <ide> equal( jQuery.parseHTML("text")[0].nodeType, 3, "Parsing text returns a text node" ); <add> equal( jQuery.parseHTML( "\t<div></div>" )[0].nodeValue, "\t", "Preserve leading whitespace" ); <ide> }); <ide> <ide> test("jQuery.parseJSON", function(){
1
Python
Python
support multiple outputs in lambda layer
692e8e2023046c683b2b66f80b32b0c525570c52
<ide><path>keras/layers/core.py <ide> def compute_output_shape(self, input_shape): <ide> else: <ide> shape = self._output_shape(input_shape) <ide> if not isinstance(shape, (list, tuple)): <del> raise ValueError('`output_shape` function must return a tuple.') <del> return tuple(shape) <add> raise ValueError('`output_shape` function must return a tuple or a list of tuples.') <add> if isinstance(shape, list): <add> if type(shape[0]) == int or shape[0] is None: <add> shape = tuple(shape) <add> return shape <ide> <ide> def call(self, inputs, mask=None): <ide> arguments = self.arguments <ide><path>tests/keras/layers/core_test.py <ide> import pytest <ide> import numpy as np <add>from numpy.testing import assert_allclose <ide> <ide> from keras import backend as K <ide> from keras import layers <ide> def antirectifier_output_shape(input_shape): <ide> 'output_shape': antirectifier_output_shape}, <ide> input_shape=(3, 2)) <ide> <add> # test layer with multiple outputs <add> def test_multiple_outputs(): <add> def func(x): <add> return [x * 0.2, x * 0.3] <add> <add> def output_shape(input_shape): <add> return [input_shape, input_shape] <add> <add> def mask(inputs, mask=None): <add> return [None, None] <add> <add> i = layers.Input(shape=(64, 64, 3)) <add> o = layers.Lambda(function=func, <add> output_shape=output_shape, <add> mask=mask)(i) <add> <add> o1, o2 = o <add> assert o1._keras_shape == (None, 64, 64, 3) <add> assert o2._keras_shape == (None, 64, 64, 3) <add> <add> model = Model(i, o) <add> <add> x = np.random.random((4, 64, 64, 3)) <add> out1, out2 = model.predict(x) <add> assert out1.shape == (4, 64, 64, 3) <add> assert out2.shape == (4, 64, 64, 3) <add> assert_allclose(out1, x * 0.2, atol=1e-4) <add> assert_allclose(out2, x * 0.3, atol=1e-4) <add> <add> test_multiple_outputs() <add> <ide> # test serialization with function <ide> def f(x): <ide> return x + 1
2
Ruby
Ruby
avoid duplicated logic
541459791351a69b7b70047ee5e0c2c05797de92
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_logs <ide> end <ide> <ide> def cleanup_cellar <del> Formula.racks.each do |rack| <del> begin <del> cleanup_formula Formulary.from_rack(rack) <del> rescue FormulaUnavailableError, TapFormulaAmbiguityError <del> # Don't complain about directories from DIY installs <del> end <add> Formula.installed.each do |formula| <add> cleanup_formula formula <ide> end <ide> end <ide>
1
Python
Python
get lxd image metadata defensively
375b8d82c8456290d21567df90666f93b4cbb1f5
<ide><path>libcloud/container/drivers/lxd.py <ide> def deploy_container(self, name, image, cluster=None, <ide> except Exception as e: <ide> raise LXDAPIException(message='Deploying ' <ide> 'container failed: ' <del> 'Image could not ' <del> 'be installed') <add> 'Image could not ' <add> 'be installed. %r' % e) <ide> <ide> # if the image was installed then we need to change <ide> # how parameters are structured <ide> parameters = {"source": {"type": "image", <ide> "fingerprint": <ide> image.extra['fingerprint']}} <ide> <del> parameters = json.loads(parameters) <del> <ide> cont_params = \ <ide> LXDContainerDriver._fix_cont_params(architecture=ex_architecture, <ide> profiles=ex_profiles, <ide> def destroy_container(self, container, ex_timeout=default_time_out): <ide> # something is wrong <ide> raise LXDAPIException(message=e.message) <ide> <del> <ide> response_dict = response.parse_body() <ide> assert_response(response_dict=response_dict, status_code=200) <ide> <ide> def _to_image(self, metadata): <ide> <ide> :rtype: :class:`.ContainerImage` <ide> """ <add> fingerprint = metadata.get('fingerprint') <ide> aliases = metadata.get('aliases', []) <ide> <ide> if aliases: <ide> name = metadata.get('aliases')[0].get('name') <ide> else: <del> name = metadata.get('fingerprint') <add> name = metadata.get('properties', {}).get('description') \ <add> or fingerprint <ide> <del> version = metadata.get('update_source').get('alias') <add> version = metadata.get('update_source', {}).get('alias') <ide> extra = metadata <ide> <del> return ContainerImage(id=name, name=name, path=None, <add> return ContainerImage(id=fingerprint, name=name, path=None, <ide> version=version, driver=self, extra=extra) <ide> <ide> def _to_storage_pool(self, data): <ide> def _deploy_container_from_image(self, name, image, parameters, <ide> :param name: the name of the container <ide> :param image: .ContainerImage <ide> <del> :param parameters: string describing the source attribute <del> :type parameters ``str`` <add> :param parameters: dictionary describing the source attribute <add> :type parameters ``dict`` <ide> <ide> :param cont_params: dictionary describing the container configuration <ide> :type cont_params: dict
1
Text
Text
update definition of division and more information
0b4cdb07e9f4ece74c9048e712feaddd71848ff2
<ide><path>guide/english/mathematics/division/index.md <ide> title: Division <ide> --- <ide> ## Division <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/division/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>Division is one of the four basic operations of arithmetic, the others being addition, subtraction, and multiplication. Division is the inverse of multiplication; if `a × b = c`, then `a = c ÷ b`, as long as b is not zero. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <del>Division is represented by the symbol '%'. To devide one number by antother is to find out how many times the second goes into the first. Therefore 7/2 = 3.5 because 2 goes into 7 3 and 1 half times. <del>#### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add>Division is represented by the symbol **/**, **÷**, or a fraction bar. Dividing is the process of calculating the number of times one number is contained within another one. For example, 15 apples are divided into three groups of five apples, meaning that fifteen divided by five gives three, or three is the result of division of fifteen by five. This is denoted as `15 / 5 = 3` or `15 ÷ 5 = 3`. <add> <ide> <ide> <add>#### More Information: <add>* <a href='https://en.wikipedia.org/wiki/Division_(mathematics) "Division"' target='_blank' rel='nofollow'>Division</a> <add>
1
Go
Go
add tests for create /etc volume
f3713010dd6355cc89944cc4185b4c5023fd95c5
<ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunReuseBindVolumeThatIsSymlink(t *testing.T) { <ide> logDone("run - can remount old bindmount volume") <ide> } <ide> <add>//test create /etc volume <add>func TestRunCreateVolumeEtc(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal("failed to run container: %v, output: %q", err, out) <add> } <add> if !strings.Contains(out, "nameserver 127.0.0.1") { <add> t.Fatal("failed: create /etc volume cover /etc/resolv.conf") <add> } <add> <add> cmd = exec.Command(dockerBinary, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") <add> out, _, err = runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal("failed to run container: %v, output: %q", err, out) <add> } <add> if !strings.Contains(out, "test123") { <add> t.Fatal("failed: create /etc volume cover /etc/hostname") <add> } <add> <add> cmd = exec.Command(dockerBinary, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") <add> out, _, err = runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal("failed to run container: %v, output: %q", err, out) <add> } <add> out = strings.Replace(out, "\n", " ", -1) <add> if !strings.Contains(out, "192.168.0.1"+"\t"+"test") || !strings.Contains(out, "127.0.0.1"+"\t"+"localhost") { <add> t.Fatal("failed: create /etc volume cover /etc/hosts", out) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("run - create /etc volume success") <add>} <add> <ide> func TestVolumesNoCopyData(t *testing.T) { <ide> defer deleteImages("dataimage") <ide> defer deleteAllContainers()
1
Java
Java
remove timeout in blocking iterator
00d33b70073920c72dfcb3149a89b231e69c39dd
<ide><path>rxjava-core/src/main/java/rx/internal/operators/BlockingOperatorToIterator.java <ide> public T next() { <ide> } <ide> <ide> private Notification<? extends T> take() { <del> try { <del> // TODO remove this timeout and logging before final release of 0.20 <del> Notification<? extends T> n = notifications.poll(10000, TimeUnit.MILLISECONDS); <del> if(n == null) { <del> System.err.println("Timed out waiting for value. File a bug at github.com/Netflix/RxJava"); <del> throw new RuntimeException("Timed out waiting for value. File a bug at github.com/Netflix/RxJava"); <del> } else { <del> return n; <del> } <del> } catch (InterruptedException e) { <del> throw Exceptions.propagate(e); <del> } <add> return notifications.poll(); <ide> } <ide> <ide> @Override
1
Javascript
Javascript
delete the gdocs.js file
01d86381141cda4a13ad6b29a4e81eb9a528e99d
<ide><path>gdocs.js <del>#!/usr/bin/env node <del> <del>'use strict'; <del> <del>var http = require('http'); <del>var https = require('https'); <del>var fs = require('fs'); <del> <del>var collections = { <del> 'guide': 'https://docs.google.com/feeds/default/private/full/folder%3A0B9PsajIPqzmANGUwMGVhZmYtMTk1ZC00NTdmLWIxMDAtZGI5YWNlZjQ2YjZl/contents', <del> 'api': 'https://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDYjMwYTc2YWUtZTgzYy00YjIxLThlZDYtYWJlOTFlNzE2NzEw/contents', <del> 'tutorial': 'https://docs.google.com/feeds/default/private/full/folder%3A0B9PsajIPqzmAYWMxYWE3MzYtYzdjYS00OGQxLWJhZjItYzZkMzJiZTRhZjFl/contents', <del> 'cookbook': 'https://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDNzkxZWM5ZTItN2M5NC00NWIxLTg2ZDMtMmYwNDY1NWM1MGU4/contents', <del> 'misc': 'https://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDZjVlNmZkYzQtMjZlOC00NmZhLWI5MjAtMGRjZjlkOGJkMDBi/contents' <del>}; <del> <del>console.log('Google Docs...'); <del> <del>var flag = process && process.argv[2]; <del>if (flag === '--login') { <del> var username = process.argv[3]; <del> if (username) { <del> askPassword(function(password) { <del> login(username, password); <del> }); <del> } else { <del> console.log('Missing username!'); <del> } <del>} else if (flag === '--fetch') { <del> var collection = process.argv[3]; <del> if (collection) { <del> fetch(collection, collections[collection]); <del> } else { <del> for (collection in collections) <del> fetch(collection, collections[collection]); <del> } <del>} else { <del> help(); <del>} <del> <del>function help() { <del> console.log('Synopsis'); <del> console.log('gdocs.js --login <username>'); <del> console.log('gdocs.js --fetch [<docs collection>]'); <del> process.exit(-1); <del>} <del> <del> <del>function fetch(collection, url) { <del> console.log('fetching a list of docs in collection ' + collection + '...'); <del> request('GET', url, { <del> headers: { <del> 'Gdata-Version': '3.0', <del> 'Authorization': 'GoogleLogin auth=' + getAuthToken() <del> } <del> }, <del> function(chunk) { <del> var entries = chunk.split('<entry'); <del> entries.shift(); <del> entries.forEach(function(entry) { <del> var title = entry.match(/<title>(.*?)<\/title>/)[1]; <del> if (title.match(/\.ngdoc$/)) { <del> var exportUrl = entry.match(/<content type='text\/html' src='(.*?)'\/>/)[1]; <del> download(collection, title, exportUrl); <del> } <del> }); <del> } <del> ); <del>} <del> <del>function download(collection, name, url) { <del> console.log('Downloading:', name, '...'); <del> request('GET', url + '&exportFormat=txt', <del> { <del> headers: { <del> 'Gdata-Version': '3.0', <del> 'Authorization': 'GoogleLogin auth=' + getAuthToken() <del> } <del> }, <del> function(data) { <del> data = data.replace('\ufeff', ''); <del> data = data.replace(/\r\n/mg, '\n'); <del> <del> // strip out all text annotations <del> data = data.replace(/\[[a-zA-Z]{1,2}\]/mg, ''); <del> <del> // strip out all docos comments <del> data = data.replace(/^[^\s_]+:\n\S+[\S\s]*$/m, ''); <del> <del> // fix smart-quotes <del> data = data.replace(/[“”]/g, '"'); <del> data = data.replace(/[‘’]/g, '\''); <del> <del> <del> data = data + '\n'; <del> <del> //this should be a bug in Google Doc API, hence need to remove this once the bug is fixed <del> data = data.replace(/\n\n/g, '\n'); <del> <del> fs.writeFileSync('docs/content/' + collection + '/' + name, reflow(data, 100)); <del> } <del> ); <del>} <del> <del>/** <del> * token=$(curl <del> * -s https://www.google.com/accounts/ClientLogin <del> * -d Email=...username... <del> * -d Passwd=...password... <del> * -d accountType=GOOGLE <del> * -d service=writely <del> * -d Gdata-version=3.0 | cut -d "=" -f 2) <del> */ <del>function login(username, password) { <del> request('POST', 'https://www.google.com/accounts/ClientLogin', <del> { <del> data: { <del> Email: username, <del> Passwd: password, <del> accountType: 'GOOGLE', <del> service: 'writely', <del> 'Gdata-version': '3.0' <del> }, <del> headers: { <del> 'Content-type': 'application/x-www-form-urlencoded' <del> } <del> }, <del> function(chunk) { <del> var token; <del> chunk.split('\n').forEach(function(line) { <del> var parts = line.split('='); <del> if (parts[0] === 'Auth') { <del> token = parts[1]; <del> } <del> }); <del> if (token) { <del> fs.writeFileSync('tmp/gdocs.auth', token); <del> console.log('logged in, token saved in \'tmp/gdocs.auth\''); <del> } else { <del> console.log('failed to log in'); <del> } <del> } <del> ); <del>} <del> <del>function getAuthToken() { <del> var pwdFile = 'tmp/gdocs.auth'; <del> try { <del> fs.statSync(pwdFile); <del> return fs.readFileSync(pwdFile); <del> } catch (e) { <del> console.log('Please log in first...'); <del> } <del>} <del> <del>function request(method, url, options, response) { <del> url = url.match(/http(s?):\/\/(.+?)(\/.*)/); <del> var isHttps = url[1]; <del> var req = (isHttps ? https : http).request({ <del> host: url[2], <del> port: (url[1] ? 443 : 80), <del> path: url[3], <del> method: method <del> }, function(res) { <del> var data; <del> switch (res.statusCode) { <del> case 200: <del> data = []; <del> res.setEncoding('utf8'); <del> res.on('end', function() { response(data.join('')); }); <del> res.on('close', function() { response(data.join('')); }); // https <del> res.on('data', function(chunk) { data.push(chunk); }); <del> res.on('error', function(e) { console.log(e); }); <del> break; <del> case 401: <del> console.log('Error: Login credentials expired! Please login.'); <del> break; <del> default: <del> data = []; <del> console.log('ERROR: ', res.statusCode); <del> console.log('REQUEST URL: ', url[0]); <del> console.log('REQUEST POST: ', options.data); <del> console.log('REQUEST HEADERS: ', options.headers); <del> console.log('RESPONSE HEADERS: ', res.headers); <del> res.on('end', function() { console.log('BODY: ', data.join('')); }); <del> res.on('close', function() { console.log('BODY: ', data.join('')); }); // https <del> res.on('data', function(chunk) { data.push(chunk); }); <del> res.on('error', function(e) { console.log(e); }); <del> } <del> }); <del> for (var header in options.headers) { <del> req.setHeader(header, options.headers[header]); <del> } <del> if (options.data) <del> req.write(encodeData(options.data)); <del> req.on('end', function() { <del> console.log('end'); <del> }); <del> req.end(); <del>} <del> <del>function encodeData(obj) { <del> var pairs = []; <del> for (var key in obj) { <del> pairs.push(key + '=' + obj[key]); <del> } <del> return pairs.join('&') + '\n'; <del>} <del> <del>function askPassword(callback) { <del> var stdin = process.openStdin(), <del> stdio = process.binding('stdio'); <del> <del> stdio.setRawMode(); <del> <del> console.log('Enter your password:'); <del> var password = ''; <del> stdin.on('data', function(c) { <del> c = c + ''; <del> switch (c) { <del> case '\n': <del> case '\r': <del> case '\u0004': <del> stdio.setRawMode(false); <del> stdin.pause(); <del> callback(password); <del> break; <del> case '\u0003': <del> process.exit(); <del> break; <del> default: <del> password += c; <del> break; <del> } <del> }); <del> <del>} <del> <del>function reflow(text, margin) { <del> var lines = []; <del> text.split(/\n/).forEach(function(line) { <del> var col = 0; <del> var reflowLine = ''; <del> function flush() { <del> reflowLine = reflowLine.replace(/\s*$/, ''); <del> lines.push(reflowLine); <del> reflowLine = ''; <del> col = 0; <del> } <del> line.replace(/\s*\S*\s*/g, function(chunk) { <del> if (col + chunk.length > margin) flush(); <del> reflowLine += chunk; <del> col += chunk.length; <del> }); <del> flush(); <del> }); <del> return lines.join('\n'); <del>}
1
Java
Java
fix race conditions in drawview
a848ce8efd7ef24041a4d5e0ae466dbb981f069a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawView.java <ide> /* package */ final class DrawView extends AbstractClippingDrawCommand { <ide> <ide> /* package */ final int reactTag; <del> /* package */ boolean isViewGroupClipped; <add> // Indicates if the DrawView is frozen. If it is frozen then any setting of the clip bounds <add> // should create a new DrawView. <add> private boolean mFrozen; <add> // Indicates whether this DrawView has been previously drawn. If it has been drawn, then we know <add> // that the bounds haven't changed, as a bounds change would trigger a new DrawView, which will <add> // set this to false for the new DrawView. Leaving this as package for direct access, but this <add> // should only be set from draw in DrawView, to avoid race conditions. <add> /* package */ boolean mPreviouslyDrawn; <ide> <del> public DrawView(int reactTag, float clipLeft, float clipTop, float clipRight, float clipBottom) { <add> public DrawView(int reactTag) { <ide> this.reactTag = reactTag; <del> setClipBounds(clipLeft, clipTop, clipRight, clipBottom); <add> } <add> <add> public DrawView collectDrawView( <add> float clipLeft, <add> float clipTop, <add> float clipRight, <add> float clipBottom) { <add> if (mFrozen) { <add> return clipBoundsMatch(clipLeft, clipTop, clipRight, clipBottom) ? <add> this : <add> new DrawView(reactTag).collectDrawView(clipLeft, clipTop, clipRight, clipBottom); <add> } else { <add> mFrozen = true; <add> setClipBounds(clipLeft, clipTop, clipRight, clipBottom); <add> return this; <add> } <ide> } <ide> <ide> @Override <ide> public void draw(FlatViewGroup parent, Canvas canvas) { <add> mPreviouslyDrawn = true; <ide> if (mNeedsClipping) { <ide> canvas.save(Canvas.CLIP_SAVE_FLAG); <ide> applyClipping(canvas); <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java <ide> private static final String PROP_REMOVE_CLIPPED_SUBVIEWS = <ide> ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS; <ide> private static final Rect LOGICAL_OFFSET_EMPTY = new Rect(); <add> // When we first initialize a backing view, we create a view we are going to throw away anyway, <add> // so instead initialize with a shared view. <add> private static final DrawView EMPTY_DRAW_VIEW = new DrawView(0); <ide> <ide> private DrawCommand[] mDrawCommands = DrawCommand.EMPTY_ARRAY; <ide> private AttachDetachListener[] mAttachDetachListeners = AttachDetachListener.EMPTY_ARRAY; <ide> protected final void setNodeRegion(NodeRegion nodeRegion) { <ide> } <ide> <ide> if (mDrawView == null) { <del> mDrawView = new DrawView(getReactTag(), 0, 0, 0, 0); <add> // Create a new DrawView, but we might not know our react tag yet, so set it to 0 in the <add> // meantime. <add> mDrawView = EMPTY_DRAW_VIEW; <ide> invalidate(); <ide> <ide> // reset NodeRegion to allow it getting garbage-collected <ide> protected final void setNodeRegion(NodeRegion nodeRegion) { <ide> } <ide> <ide> /* package */ final DrawView collectDrawView(float left, float top, float right, float bottom) { <del> if (!Assertions.assumeNotNull(mDrawView).clipBoundsMatch(left, top, right, bottom)) { <del> mDrawView = new DrawView(getReactTag(), left, top, right, bottom); <add> Assertions.assumeNotNull(mDrawView); <add> if (mDrawView.reactTag == 0) { <add> // This is the first time we have collected this DrawView, but we have to create a new <add> // DrawView anyway, as reactTag is final. <add> mDrawView = new DrawView(getReactTag()).collectDrawView(left, top, right, bottom); <add> } else { <add> // We have collected the DrawView before, so the react tag is correct, but we may need a new <add> // copy with updated bounds. If the bounds match, the same view is returned. <add> mDrawView = mDrawView.collectDrawView(left, top, right, bottom); <ide> } <del> <ide> return mDrawView; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatViewGroup.java <ide> protected void onDebugDraw(Canvas canvas) { <ide> mAndroidDebugDraw = true; <ide> } <ide> <add> private void clip(int id, View view) { <add> mClippedSubviews.put(id, view); <add> } <add> <add> private void unclip(int id) { <add> mClippedSubviews.remove(id); <add> } <add> <add> private boolean isClipped(int id) { <add> return mClippedSubviews.containsKey(id); <add> } <add> <ide> @Override <ide> public void dispatchDraw(Canvas canvas) { <ide> mAndroidDebugDraw = false; <ide> public void dispatchDraw(Canvas canvas) { <ide> if (mRemoveClippedSubviews) { <ide> for (DrawCommand drawCommand : mDrawCommands) { <ide> if (drawCommand instanceof DrawView) { <del> if (!((DrawView) drawCommand).isViewGroupClipped) { <add> if (!isClipped(((DrawView) drawCommand).reactTag)) { <ide> drawCommand.draw(this, canvas); <ide> } <ide> // else, don't draw, and don't increment index <ide> public void dispatchDraw(Canvas canvas) { <ide> private void debugDraw(Canvas canvas) { <ide> for (DrawCommand drawCommand : mDrawCommands) { <ide> if (drawCommand instanceof DrawView) { <del> if (!((DrawView) drawCommand).isViewGroupClipped) { <add> if (!isClipped(((DrawView) drawCommand).reactTag)) { <ide> drawCommand.debugDraw(this, canvas); <ide> } <ide> // else, don't draw, and don't increment index <ide> public void removeAllViewsInLayout() { <ide> mNodeRegions = nodeRegions; <ide> } <ide> <add> /** <add> * Mount a list of views to add, and dismount a list of views to detach. Ids will not appear in <add> * both lists, aka: <add> * set(viewsToAdd + viewsToDetach).size() == viewsToAdd.length + viewsToDetach.length <add> * <add> * Every time we get any change in the views in a FlatViewGroup, we detach all views first, then <add> * reattach / remove them as needed. viewsToAdd is odd in that the ids also specify whether <add> * the view is new to us, or if we were already the parent. If it is new to us, then the id has <add> * a positive value, otherwise we are already the parent, but it was previously detached, since we <add> * detach everything when anything changes. <add> * <add> * The reason we detach everything is that a single detach is on the order of O(n), as in the <add> * average case we have to move half of the views one position to the right, and a single add is <add> * the same. Removing all views is also on the order of O(n), as you delete everything backward <add> * from the end, while adding a new set of views is also on the order of O(n), as you just add <add> * them all back in order. ArrayLists are weird. <add> * <add> * @param viewResolver Resolves the views from their id. <add> * @param viewsToAdd id of views to add if they weren't just attached to us, or -id if they are <add> * just being reattached. <add> * @param viewsToDetach id of views that we don't own anymore. They either moved to a new parent, <add> * or are being removed entirely. <add> */ <ide> /* package */ void mountViews(ViewResolver viewResolver, int[] viewsToAdd, int[] viewsToDetach) { <ide> for (int viewToAdd : viewsToAdd) { <ide> if (viewToAdd > 0) { <ide> public void removeAllViewsInLayout() { <ide> View view = ensureViewHasNoParent(viewResolver.getView(-viewToAdd)); <ide> if (mRemoveClippedSubviews) { <ide> DrawView drawView = Assertions.assertNotNull(mDrawViewMap.get(-viewToAdd)); <del> // If the view is clipped, we don't need to attach it. <del> if (!drawView.isViewGroupClipped) { <add> if (!drawView.mPreviouslyDrawn) { <add> // The DrawView has not been drawn before, which means the bounds changed and triggered <add> // a new DrawView when it was collected from the shadow node. We have a view with the <add> // same id temporarily detached, but we no longer know the bounds. <add> unclip(drawView.reactTag); <add> attachViewToParent(view, -1, ensureLayoutParams(view.getLayoutParams())); <add> } else if (!isClipped(drawView.reactTag)) { <add> // The DrawView has been drawn before, and is not clipped. Attach it, and it will get <add> // removed if we update the clipping rect. <ide> attachViewToParent(view, -1, ensureLayoutParams(view.getLayoutParams())); <ide> } <add> // The DrawView has been previously drawn and is clipped, so don't attach it. <ide> } else { <add> // We aren't clipping, so attach all the things. <ide> attachViewToParent(view, -1, ensureLayoutParams(view.getLayoutParams())); <ide> } <ide> } <ide> public void removeAllViewsInLayout() { <ide> for (int viewToDetach : viewsToDetach) { <ide> View view = viewResolver.getView(viewToDetach); <ide> if (view.getParent() != null) { <del> removeViewInLayout(view); <add> throw new RuntimeException("Trying to remove view not owned by FlatViewGroup"); <ide> } else { <ide> removeDetachedView(view, false); <ide> } <ide> <ide> if (mRemoveClippedSubviews) { <del> mClippedSubviews.remove(viewToDetach); <add> unclip(viewToDetach); <ide> } <ide> } <ide> <ide> private ViewGroup.LayoutParams ensureLayoutParams(ViewGroup.LayoutParams lp) { <ide> } <ide> <ide> // Returns true if a view is currently animating. <del> static boolean animating(View view, Rect clippingRect) { <add> static boolean animating(View view) { <ide> Animation animation = view.getAnimation(); <ide> return animation != null && !animation.hasEnded(); <ide> } <ide> private void updateClippingToRect(Rect clippingRect) { <ide> if (view == null) { <ide> // Not clipped, visible <ide> view = getChildAt(index++); <del> if (!animating(view, clippingRect) && !withinBounds(view, clippingRect)) { <add> if (!animating(view) && !withinBounds(view, clippingRect)) { <ide> // Now off the screen. Don't invalidate in this case, as the canvas should not be <ide> // redrawn unless new elements are coming onscreen. <del> mClippedSubviews.put(view.getId(), view); <add> clip(drawView.reactTag, view); <ide> detachViewFromParent(--index); <del> drawView.isViewGroupClipped = true; <ide> } <ide> } else { <del> // Clipped, invisible. <add> // Clipped, invisible. We obviously aren't animating here, as if we were then we would not <add> // have clipped in the first place. <ide> if (withinBounds(view, clippingRect)) { <ide> // Now on the screen. Invalidate as we have a new element to draw. <del> attachViewToParent( <del> view, <del> index++, <del> ensureLayoutParams(view.getLayoutParams())); <del> mClippedSubviews.remove(view.getId()); <del> drawView.isViewGroupClipped = false; <add> unclip(drawView.reactTag); <add> attachViewToParent(view, index++, ensureLayoutParams(view.getLayoutParams())); <ide> needsInvalidate = true; <ide> } <ide> }
3
Python
Python
fix small issue detected by pylint
81c6bd802e7e3aad2e80b181d7c6d97e11eb8a46
<ide><path>libcloud/common/openstack_identity.py <ide> def __init__(self, auth_url, user_id, key, tenant_name=None, <ide> Tenant, domain and scope options are ignored as they are contained <ide> within the app credential itself and can't be changed. <ide> """ <del> super(OpenStackIdentity_3_0_Connection, <add> super(OpenStackIdentity_3_0_Connection_AppCred, <ide> self).__init__(auth_url=auth_url, <ide> user_id=user_id, <ide> key=key,
1
Java
Java
revise cache api
3699a037a55ed4fbe43d66ecc73876f2378e3507
<ide><path>org.springframework.context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.annotation; <add> <add>import java.io.Serializable; <add>import java.lang.reflect.AnnotatedElement; <add>import java.lang.reflect.Method; <add>import java.util.Collections; <add>import java.util.LinkedHashSet; <add>import java.util.Set; <add> <add>import org.springframework.cache.interceptor.AbstractFallbackCacheOperationSource; <add>import org.springframework.cache.interceptor.CacheOperation; <add>import org.springframework.util.Assert; <add> <add>/** <add> * <add> * Implementation of the {@link org.springframework.cache.interceptor.CacheOperationSource} <add> * interface for working with caching metadata in JDK 1.5+ annotation format. <add> * <add> * <p>This class reads Spring's JDK 1.5+ {@link Cacheable} and {@link CacheEvict} <add> * annotations and exposes corresponding caching operation definition to Spring's cache infrastructure. <add> * This class may also serve as base class for a custom CacheOperationSource. <add> * <add> * @author Costin Leau <add> */ <add>@SuppressWarnings("serial") <add>public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperationSource implements <add> Serializable { <add> <add> private final boolean publicMethodsOnly; <add> <add> private final Set<CacheAnnotationParser> annotationParsers; <add> <add> /** <add> * Create a default AnnotationCacheOperationSource, supporting <add> * public methods that carry the <code>Cacheable</code> and <code>CacheEvict</code> <add> * annotations. <add> */ <add> public AnnotationCacheOperationSource() { <add> this(true); <add> } <add> <add> /** <add> * Create a custom AnnotationCacheOperationSource, supporting <add> * public methods that carry the <code>Cacheable</code> and <add> * <code>CacheEvict</code> annotations. <add> * <add> * @param publicMethodsOnly whether to support only annotated public methods <add> * typically for use with proxy-based AOP), or protected/private methods as well <add> * (typically used with AspectJ class weaving) <add> */ <add> public AnnotationCacheOperationSource(boolean publicMethodsOnly) { <add> this.publicMethodsOnly = publicMethodsOnly; <add> this.annotationParsers = new LinkedHashSet<CacheAnnotationParser>(1); <add> this.annotationParsers.add(new SpringCachingAnnotationParser()); <add> } <add> <add> /** <add> * Create a custom AnnotationCacheOperationSource. <add> * @param annotationParsers the CacheAnnotationParser to use <add> */ <add> public AnnotationCacheOperationSource(CacheAnnotationParser... annotationParsers) { <add> this.publicMethodsOnly = true; <add> Assert.notEmpty(annotationParsers, "At least one CacheAnnotationParser needs to be specified"); <add> Set<CacheAnnotationParser> parsers = new LinkedHashSet<CacheAnnotationParser>(annotationParsers.length); <add> Collections.addAll(parsers, annotationParsers); <add> this.annotationParsers = parsers; <add> } <add> <add> @Override <add> protected CacheOperation findCacheOperation(Class<?> clazz) { <add> return determineCacheOperation(clazz); <add> } <add> <add> @Override <add> protected CacheOperation findCacheOperation(Method method) { <add> return determineCacheOperation(method); <add> } <add> <add> /** <add> * Determine the cache operation definition for the given method or class. <add> * <p>This implementation delegates to configured <add> * {@link CacheAnnotationParser CacheAnnotationParsers} <add> * for parsing known annotations into Spring's metadata attribute class. <add> * Returns <code>null</code> if it's not cacheable. <add> * <p>Can be overridden to support custom annotations that carry caching metadata. <add> * @param ae the annotated method or class <add> * @return CacheOperation the configured caching operation, <add> * or <code>null</code> if none was found <add> */ <add> protected CacheOperation determineCacheOperation(AnnotatedElement ae) { <add> for (CacheAnnotationParser annotationParser : this.annotationParsers) { <add> CacheOperation attr = annotationParser.parseCacheAnnotation(ae); <add> if (attr != null) { <add> return attr; <add> } <add> } <add> return null; <add> } <add> <add> /** <add> * By default, only public methods can be made cacheable. <add> */ <add> @Override <add> protected boolean allowPublicMethodsOnly() { <add> return this.publicMethodsOnly; <add> } <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/AbstractFallbackCacheOperationSource.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import java.lang.reflect.Method; <add>import java.lang.reflect.Modifier; <add>import java.util.Map; <add>import java.util.concurrent.ConcurrentHashMap; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.core.BridgeMethodResolver; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.util.ObjectUtils; <add> <add>/** <add> * Abstract implementation of {@link CacheOperation} that caches <add> * attributes for methods and implements a fallback policy: 1. specific target <add> * method; 2. target class; 3. declaring method; 4. declaring class/interface. <add> * <add> * <p>Defaults to using the target class's caching attribute if none is <add> * associated with the target method. Any caching attribute associated with <add> * the target method completely overrides a class caching attribute. <add> * If none found on the target class, the interface that the invoked method <add> * has been called through (in case of a JDK proxy) will be checked. <add> * <add> * <p>This implementation caches attributes by method after they are first used. <add> * If it is ever desirable to allow dynamic changing of cacheable attributes <add> * (which is very unlikely), caching could be made configurable. <add> <add> * @author Costin Leau <add> * @see org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource <add> */ <add>public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource { <add> <add> /** <add> * Canonical value held in cache to indicate no caching attribute was <add> * found for this method and we don't need to look again. <add> */ <add> private final static CacheOperation NULL_CACHING_ATTRIBUTE = new CacheUpdateOperation(); <add> <add> /** <add> * Logger available to subclasses. <add> * <p>As this base class is not marked Serializable, the logger will be recreated <add> * after serialization - provided that the concrete subclass is Serializable. <add> */ <add> protected final Log logger = LogFactory.getLog(getClass()); <add> <add> /** <add> * Cache of CacheOperationDefinitions, keyed by DefaultCacheKey (Method + target Class). <add> * <p>As this base class is not marked Serializable, the cache will be recreated <add> * after serialization - provided that the concrete subclass is Serializable. <add> */ <add> final Map<Object, CacheOperation> attributeCache = new ConcurrentHashMap<Object, CacheOperation>(); <add> <add> /** <add> * Determine the caching attribute for this method invocation. <add> * <p>Defaults to the class's caching attribute if no method attribute is found. <add> * @param method the method for the current invocation (never <code>null</code>) <add> * @param targetClass the target class for this invocation (may be <code>null</code>) <add> * @return {@link CacheOperation} for this method, or <code>null</code> if the method <add> * is not cacheable <add> */ <add> public CacheOperation getCacheOperation(Method method, Class<?> targetClass) { <add> // First, see if we have a cached value. <add> Object cacheKey = getCacheKey(method, targetClass); <add> CacheOperation cached = this.attributeCache.get(cacheKey); <add> if (cached != null) { <add> if (cached == NULL_CACHING_ATTRIBUTE) { <add> return null; <add> } <add> // Value will either be canonical value indicating there is no caching attribute, <add> // or an actual caching attribute. <add> return cached; <add> } <add> else { <add> // We need to work it out. <add> CacheOperation cacheDef = computeCacheOperationDefinition(method, targetClass); <add> // Put it in the cache. <add> if (cacheDef == null) { <add> this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE); <add> } <add> else { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheDef); <add> } <add> this.attributeCache.put(cacheKey, cacheDef); <add> } <add> return cacheDef; <add> } <add> } <add> <add> /** <add> * Determine a cache key for the given method and target class. <add> * <p>Must not produce same key for overloaded methods. <add> * Must produce same key for different instances of the same method. <add> * @param method the method (never <code>null</code>) <add> * @param targetClass the target class (may be <code>null</code>) <add> * @return the cache key (never <code>null</code>) <add> */ <add> protected Object getCacheKey(Method method, Class<?> targetClass) { <add> return new DefaultCacheKey(method, targetClass); <add> } <add> <add> /** <add> * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result. <add> * {@link #getTransactionAttribute} is effectively a caching decorator for this method. <add> * @see #getTransactionAttribute <add> */ <add> private CacheOperation computeCacheOperationDefinition(Method method, Class<?> targetClass) { <add> // Don't allow no-public methods as required. <add> if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) { <add> return null; <add> } <add> <add> // The method may be on an interface, but we need attributes from the target class. <add> // If the target class is null, the method will be unchanged. <add> Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); <add> // If we are dealing with method with generic parameters, find the original method. <add> specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); <add> <add> // First try is the method in the target class. <add> CacheOperation opDef = findCacheOperation(specificMethod); <add> if (opDef != null) { <add> return opDef; <add> } <add> <add> // Second try is the caching operation on the target class. <add> opDef = findCacheOperation(specificMethod.getDeclaringClass()); <add> if (opDef != null) { <add> return opDef; <add> } <add> <add> if (specificMethod != method) { <add> // Fall back is to look at the original method. <add> opDef = findCacheOperation(method); <add> if (opDef != null) { <add> return opDef; <add> } <add> // Last fall back is the class of the original method. <add> return findCacheOperation(method.getDeclaringClass()); <add> } <add> return null; <add> } <add> <add> /** <add> * Subclasses need to implement this to return the caching attribute <add> * for the given method, if any. <add> * @param method the method to retrieve the attribute for <add> * @return all caching attribute associated with this method <add> * (or <code>null</code> if none) <add> */ <add> protected abstract CacheOperation findCacheOperation(Method method); <add> <add> /** <add> * Subclasses need to implement this to return the caching attribute <add> * for the given class, if any. <add> * @param clazz the class to retrieve the attribute for <add> * @return all caching attribute associated with this class <add> * (or <code>null</code> if none) <add> */ <add> protected abstract CacheOperation findCacheOperation(Class<?> clazz); <add> <add> /** <add> * Should only public methods be allowed to have caching semantics? <add> * <p>The default implementation returns <code>false</code>. <add> */ <add> protected boolean allowPublicMethodsOnly() { <add> return false; <add> } <add> <add> /** <add> * Default cache key for the CacheOperationDefinition cache. <add> */ <add> private static class DefaultCacheKey { <add> <add> private final Method method; <add> <add> private final Class<?> targetClass; <add> <add> public DefaultCacheKey(Method method, Class<?> targetClass) { <add> this.method = method; <add> this.targetClass = targetClass; <add> } <add> <add> @Override <add> public boolean equals(Object other) { <add> if (this == other) { <add> return true; <add> } <add> if (!(other instanceof DefaultCacheKey)) { <add> return false; <add> } <add> DefaultCacheKey otherKey = (DefaultCacheKey) other; <add> return (this.method.equals(otherKey.method) && ObjectUtils.nullSafeEquals(this.targetClass, <add> otherKey.targetClass)); <add> } <add> <add> @Override <add> public int hashCode() { <add> return this.method.hashCode() * 29 + (this.targetClass != null ? this.targetClass.hashCode() : 0); <add> } <add> } <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/BeanFactoryCacheOperationSourceAdvisor.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import org.springframework.aop.ClassFilter; <add>import org.springframework.aop.Pointcut; <add>import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor; <add> <add>/** <add> * Advisor driven by a {@link CacheOperationSource}, used to include a <add> * cache advice bean for methods that are cacheable. <add> * <add> * @author Costin Leau <add> */ <add>@SuppressWarnings("serial") <add>public class BeanFactoryCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor { <add> <add> private CacheOperationSource cacheDefinitionSource; <add> <add> private final CacheOperationSourcePointcut pointcut = new CacheOperationSourcePointcut() { <add> @Override <add> protected CacheOperationSource getCacheOperationSource() { <add> return cacheDefinitionSource; <add> } <add> }; <add> <add> /** <add> * Set the cache operation attribute source which is used to find cache <add> * attributes. This should usually be identical to the source reference <add> * set on the cache interceptor itself. <add> * @see CacheInterceptor#setCacheAttributeSource <add> */ <add> public void setCacheDefinitionSource(CacheOperationSource cacheDefinitionSource) { <add> this.cacheDefinitionSource = cacheDefinitionSource; <add> } <add> <add> /** <add> * Set the {@link ClassFilter} to use for this pointcut. <add> * Default is {@link ClassFilter#TRUE}. <add> */ <add> public void setClassFilter(ClassFilter classFilter) { <add> this.pointcut.setClassFilter(classFilter); <add> } <add> <add> public Pointcut getPointcut() { <add> return this.pointcut; <add> } <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>/** <add> * Class describing an 'evict' operation. <add> * <add> * @author Costin Leau <add> */ <add>public class CacheEvictOperation extends CacheOperation { <add> <add> private boolean cacheWide = false; <add> <add> public boolean isCacheWide() { <add> return cacheWide; <add> } <add> <add> public void setCacheWide(boolean cacheWide) { <add> this.cacheWide = cacheWide; <add> } <add> <add> @Override <add> protected StringBuilder getOperationDescription() { <add> StringBuilder sb = super.getOperationDescription(); <add> sb.append(","); <add> sb.append(cacheWide); <add> return sb; <add> } <add>} <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import java.util.Collections; <add>import java.util.LinkedHashSet; <add>import java.util.Set; <add> <add>import org.springframework.util.Assert; <add> <add>/** <add> * Base class implementing {@link CacheOperation}. <add> * <add> * @author Costin Leau <add> */ <add>public abstract class CacheOperation { <add> <add> private Set<String> cacheNames = Collections.emptySet(); <add> private String condition = ""; <add> private String key = ""; <add> private String name = ""; <add> <add> <add> public Set<String> getCacheNames() { <add> return cacheNames; <add> } <add> <add> public String getCondition() { <add> return condition; <add> } <add> <add> public String getKey() { <add> return key; <add> } <add> <add> public String getName() { <add> return name; <add> } <add> <add> public void setCacheName(String cacheName) { <add> Assert.hasText(cacheName); <add> this.cacheNames = Collections.singleton(cacheName); <add> } <add> <add> public void setCacheNames(String[] cacheNames) { <add> Assert.notEmpty(cacheNames); <add> this.cacheNames = new LinkedHashSet<String>(cacheNames.length); <add> for (String string : cacheNames) { <add> this.cacheNames.add(string); <add> } <add> } <add> <add> public void setCondition(String condition) { <add> Assert.notNull(condition); <add> this.condition = condition; <add> } <add> <add> public void setKey(String key) { <add> Assert.notNull(key); <add> this.key = key; <add> } <add> <add> public void setName(String name) { <add> Assert.hasText(name); <add> this.name = name; <add> } <add> <add> /** <add> * This implementation compares the <code>toString()</code> results. <add> * @see #toString() <add> */ <add> @Override <add> public boolean equals(Object other) { <add> return (other instanceof CacheOperation && toString().equals(other.toString())); <add> } <add> <add> /** <add> * This implementation returns <code>toString()</code>'s hash code. <add> * @see #toString() <add> */ <add> @Override <add> public int hashCode() { <add> return toString().hashCode(); <add> } <add> <add> /** <add> * Return an identifying description for this cache operation. <add> * <p>Has to be overridden in subclasses for correct <code>equals</code> <add> * and <code>hashCode</code> behavior. Alternatively, {@link #equals} <add> * and {@link #hashCode} can be overridden themselves. <add> */ <add> @Override <add> public String toString() { <add> return getOperationDescription().toString(); <add> } <add> <add> /** <add> * Return an identifying description for this caching operation. <add> * <p>Available to subclasses, for inclusion in their <code>toString()</code> result. <add> */ <add> protected StringBuilder getOperationDescription() { <add> StringBuilder result = new StringBuilder(); <add> result.append("CacheDefinition["); <add> result.append(name); <add> result.append("] caches="); <add> result.append(cacheNames); <add> result.append(" | condition='"); <add> result.append(condition); <add> result.append("' | key='"); <add> result.append(key); <add> result.append("'"); <add> return result; <add> } <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperationSource.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import java.lang.reflect.Method; <add> <add> <add>/** <add> * Interface used by CacheInterceptor. Implementations know <add> * how to source cache operation attributes, whether from configuration, <add> * metadata attributes at source level, or anywhere else. <add> * <add> * @author Costin Leau <add> */ <add>public interface CacheOperationSource { <add> <add> /** <add> * Return the cache operation definition for this method. <add> * Return null if the method is not cacheable. <add> * @param method method <add> * @param targetClass target class. May be <code>null</code>, in which <add> * case the declaring class of the method must be used. <add> * @return {@link CacheOperation} the matching cache operation, <add> * or <code>null</code> if none found <add> */ <add> CacheOperation getCacheOperation(Method method, Class<?> targetClass); <add>} <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import java.io.Serializable; <add>import java.lang.reflect.Method; <add> <add>import org.springframework.aop.support.StaticMethodMatcherPointcut; <add>import org.springframework.util.ObjectUtils; <add> <add>/** <add> * Inner class that implements a Pointcut that matches if the underlying <add> * {@link CacheOperationSource} has an attribute for a given method. <add> * <add> * @author Costin Leau <add> */ <add>@SuppressWarnings("serial") <add>abstract class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implements Serializable { <add> <add> public boolean matches(Method method, Class<?> targetClass) { <add> CacheOperationSource cas = getCacheOperationSource(); <add> return (cas == null || cas.getCacheOperation(method, targetClass) != null); <add> } <add> <add> @Override <add> public boolean equals(Object other) { <add> if (this == other) { <add> return true; <add> } <add> if (!(other instanceof CacheOperationSourcePointcut)) { <add> return false; <add> } <add> CacheOperationSourcePointcut otherPc = (CacheOperationSourcePointcut) other; <add> return ObjectUtils.nullSafeEquals(getCacheOperationSource(), <add> otherPc.getCacheOperationSource()); <add> } <add> <add> @Override <add> public int hashCode() { <add> return CacheOperationSourcePointcut.class.hashCode(); <add> } <add> <add> @Override <add> public String toString() { <add> return getClass().getName() + ": " + getCacheOperationSource(); <add> } <add> <add> <add> /** <add> * Obtain the underlying CacheOperationDefinitionSource (may be <code>null</code>). <add> * To be implemented by subclasses. <add> */ <add> protected abstract CacheOperationSource getCacheOperationSource(); <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheUpdateOperation.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>/** <add> * Class describing an 'update' operation. <add> * <add> * @author Costin Leau <add> */ <add>public class CacheUpdateOperation extends CacheOperation { <add> <add>} <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/CompositeCacheOperationSource.java <add>/* <add> * Copyright 2010-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import java.io.Serializable; <add>import java.lang.reflect.Method; <add> <add>import org.springframework.util.Assert; <add> <add>/** <add> * Composite {@link CacheOperationSource} implementation that iterates <add> * over a given array of {@link CacheOperationSource} instances. <add> * <add> * @author Costin Leau <add> */ <add>@SuppressWarnings("serial") <add>public class CompositeCacheOperationSource implements CacheOperationSource, Serializable { <add> <add> private final CacheOperationSource[] cacheDefinitionSources; <add> <add> /** <add> * Create a new CompositeCachingDefinitionSource for the given sources. <add> * @param cacheDefinitionSourcess the CacheDefinitionSource instances to combine <add> */ <add> public CompositeCacheOperationSource(CacheOperationSource[] cacheDefinitionSources) { <add> Assert.notNull(cacheDefinitionSources, "cacheDefinitionSource array must not be null"); <add> this.cacheDefinitionSources = cacheDefinitionSources; <add> } <add> <add> /** <add> * Return the CacheDefinitionSource instances that this <add> * CompositeCachingDefinitionSource combines. <add> */ <add> public final CacheOperationSource[] getCacheDefinitionSources() { <add> return this.cacheDefinitionSources; <add> } <add> <add> <add> public CacheOperation getCacheOperation(Method method, Class<?> targetClass) { <add> for (CacheOperationSource source : cacheDefinitionSources) { <add> CacheOperation definition = source.getCacheOperation(method, targetClass); <add> if (definition != null) { <add> return definition; <add> } <add> } <add> <add> return null; <add> } <add>} <ide>\ No newline at end of file <ide><path>org.springframework.context/src/main/java/org/springframework/cache/interceptor/DefaultValue.java <add>/* <add> * Copyright 2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.cache.interceptor; <add> <add>import org.springframework.cache.Cache.ValueWrapper; <add> <add>/** <add> * Default implementation for {@link org.springframework.cache.Cache.ValueWrapper}. <add> * <add> * @author Costin Leau <add> */ <add>public class DefaultValue<V> implements ValueWrapper<V> { <add> <add> private final V value; <add> <add> public DefaultValue(V value) { <add> this.value = value; <add> } <add> <add> public V get() { <add> return value; <add> } <add>}
10
PHP
PHP
remove "fresh" command
37ebc7ecc693405a717239ca30e0586d0a71e4d3
<ide><path>src/Illuminate/Foundation/Console/FreshCommand.php <del><?php namespace Illuminate\Foundation\Console; <del> <del>use Illuminate\Console\Command; <del>use Illuminate\Filesystem\Filesystem; <del> <del>class FreshCommand extends Command { <del> <del> /** <del> * The console command name. <del> * <del> * @var string <del> */ <del> protected $name = 'fresh'; <del> <del> /** <del> * The console command description. <del> * <del> * @var string <del> */ <del> protected $description = "Remove some of Laravel's scaffolding"; <del> <del> /** <del> * The filesystem instance. <del> * <del> * @var \Illuminate\Filesystem\Filesystem <del> */ <del> protected $files; <del> <del> /** <del> * Create a new command instance. <del> * <del> * @param \Illuminate\Filesystem\Filesystem $files <del> * @return void <del> */ <del> public function __construct(Filesystem $files) <del> { <del> parent::__construct(); <del> <del> $this->files = $files; <del> } <del> <del> /** <del> * Execute the console command. <del> * <del> * @return void <del> */ <del> public function fire() <del> { <del> foreach ($this->getFiles() as $file) <del> { <del> $this->files->delete($file); <del> <del> $this->line('<info>Removed File:</info> '.$file); <del> } <del> <del> foreach ($this->getDirectories() as $directory) <del> { <del> $this->files->deleteDirectory($directory); <del> <del> $this->line('<comment>Removed Directory:</comment> '.$directory); <del> } <del> <del> foreach ($this->getStubs() as $stub => $path) <del> { <del> $this->files->put($path, $this->files->get(__DIR__.'/stubs/fresh/'.$stub)); <del> } <del> <del> $this->info('Scaffolding Removed!'); <del> } <del> <del> /** <del> * Get the files that should be deleted. <del> * <del> * @return array <del> */ <del> protected function getFiles() <del> { <del> return [ <del> base_path('.bowerrc'), <del> base_path('bower.json'), <del> base_path('gulpfile.js'), <del> base_path('package.json'), <del> base_path('views/dashboard.blade.php'), <del> app_path('Http/Controllers/HomeController.php'), <del> ]; <del> } <del> <del> /** <del> * Get the directories that should be deleted. <del> * <del> * @return array <del> */ <del> protected function getDirectories() <del> { <del> return [ <del> public_path('js'), <del> public_path('css'), <del> base_path('assets'), <del> base_path('views/auth'), <del> base_path('views/emails'), <del> base_path('views/layouts'), <del> base_path('views/partials'), <del> app_path('Http/Requests/Auth'), <del> app_path('Http/Controllers/Auth'), <del> ]; <del> } <del> <del> /** <del> * Get the stubs to copy. <del> * <del> * @return array <del> */ <del> protected function getStubs() <del> { <del> return [ <del> 'routes.stub' => app_path('Http/routes.php'), <del> 'view.stub' => base_path('views/welcome.blade.php'), <del> 'welcome.stub' => app_path('Http/Controllers/WelcomeController.php'), <del> ]; <del> } <del> <del>} <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Foundation\Console\UpCommand; <ide> use Illuminate\Foundation\Console\DownCommand; <del>use Illuminate\Foundation\Console\FreshCommand; <ide> use Illuminate\Foundation\Console\TinkerCommand; <ide> use Illuminate\Foundation\Console\AppNameCommand; <ide> use Illuminate\Foundation\Console\OptimizeCommand; <ide> class ArtisanServiceProvider extends ServiceProvider { <ide> 'Down' => 'command.down', <ide> 'Environment' => 'command.environment', <ide> 'EventScan' => 'command.event.scan', <del> 'Fresh' => 'command.fresh', <ide> 'KeyGenerate' => 'command.key.generate', <ide> 'Optimize' => 'command.optimize', <ide> 'ProviderMake' => 'command.provider.make', <ide> protected function registerEventScanCommand() <ide> }); <ide> } <ide> <del> /** <del> * Register the command. <del> * <del> * @return void <del> */ <del> protected function registerFreshCommand() <del> { <del> $this->app->singleton('command.fresh', function($app) <del> { <del> return new FreshCommand($app['files']); <del> }); <del> } <del> <ide> /** <ide> * Register the command. <ide> *
2
Javascript
Javascript
skip failing tests for osx mojave
eff869feccb7396715fd2d0b47b6a1cbb5b2d1c2
<ide><path>test/common/index.js <ide> const isOpenBSD = process.platform === 'openbsd'; <ide> const isLinux = process.platform === 'linux'; <ide> const isOSX = process.platform === 'darwin'; <ide> <add>const isOSXMojave = isOSX && (os.release().startsWith('18')); <add> <ide> const enoughTestMem = os.totalmem() > 0x70000000; /* 1.75 Gb */ <ide> const cpus = os.cpus(); <ide> const enoughTestCpu = Array.isArray(cpus) && <ide> module.exports = { <ide> isMainThread, <ide> isOpenBSD, <ide> isOSX, <add> isOSXMojave, <ide> isSunOS, <ide> isWindows, <ide> localIPv6Hosts, <ide><path>test/known_issues/test-cluster-bind-privileged-port.js <add>'use strict'; <add>const common = require('../common'); <add> <add>// This test should fail on macOS (10.14) due to an issue with privileged ports. <add> <add>const assert = require('assert'); <add>const cluster = require('cluster'); <add>const net = require('net'); <add> <add>if (!common.isOSXMojave) <add> assert.fail('Code should fail only on macOS Mojave.'); <add> <add> <add>if (cluster.isMaster) { <add> cluster.fork().on('exit', common.mustCall((exitCode) => { <add> assert.strictEqual(exitCode, 0); <add> })); <add>} else { <add> const s = net.createServer(common.mustNotCall()); <add> s.listen(42, common.mustNotCall('listen should have failed')); <add> s.on('error', common.mustCall((err) => { <add> assert.strictEqual(err.code, 'EACCES'); <add> process.disconnect(); <add> })); <add>} <ide><path>test/parallel/test-cluster-bind-privileged-port.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add> <add>// Skip on OS X Mojave. https://github.com/nodejs/node/issues/21679 <add>if (common.isOSXMojave) <add> common.skip('bypass test for Mojave due to OSX issue'); <add> <ide> if (common.isWindows) <ide> common.skip('not reliable on Windows.'); <ide> <ide><path>test/parallel/test-cluster-shared-handle-bind-privileged-port.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add> <add>// Skip on OS X Mojave. https://github.com/nodejs/node/issues/21679 <add>if (common.isOSXMojave) <add> common.skip('bypass test for Mojave due to OSX issue'); <add> <ide> if (common.isWindows) <ide> common.skip('not reliable on Windows'); <ide>
4
PHP
PHP
add support for commands to autodiscovery
1eb3dcbdac85bbf4bfe9cf9d94a180d476670708
<ide><path>src/Console/CommandScanner.php <ide> class CommandScanner <ide> public function scanAll() <ide> { <ide> $shellList = []; <del> <ide> $appNamespace = Configure::read('App.namespace'); <del> $shellList['app'] = $this->scanDir( <add> <add> $coreShells = $this->scanDir( <add> dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Shell' . DIRECTORY_SEPARATOR, <add> 'Cake\Shell\\', <add> '', <add> ['command_list'] <add> ); <add> $coreCommands = $this->scanDir( <add> dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Command' . DIRECTORY_SEPARATOR, <add> 'Cake\Command\\', <add> '', <add> ['command_list'] <add> ); <add> $shellList['CORE'] = array_merge($coreShells, $coreCommands); <add> <add> $appShells = $this->scanDir( <ide> App::path('Shell')[0], <ide> $appNamespace . '\Shell\\', <ide> '', <ide> ['app'] <ide> ); <del> <del> $shellList['CORE'] = $this->scanDir( <del> dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Shell' . DIRECTORY_SEPARATOR, <del> 'Cake\Shell\\', <add> $appCommands = $this->scanDir( <add> App::path('Command')[0], <add> $appNamespace . '\Command\\', <ide> '', <del> ['command_list'] <add> ['app'] <ide> ); <add> $shellList['app'] = array_merge($appShells, $appCommands); <ide> <ide> $plugins = []; <ide> foreach (Plugin::loaded() as $plugin) { <del> $plugins[$plugin] = $this->scanDir( <del> Plugin::classPath($plugin) . 'Shell', <del> str_replace('/', '\\', $plugin) . '\Shell\\', <del> Inflector::underscore($plugin) . '.', <del> [] <del> ); <add> $path = Plugin::classPath($plugin); <add> $namespace = str_replace('/', '\\', $plugin); <add> $prefix = Inflector::underscore($plugin) . '.'; <add> <add> $commands = $this->scanDir($path . 'Command', $namespace . '\Command\\', $prefix, []); <add> $shells = $this->scanDir($path . 'Shell', $namespace . '\Shell\\', $prefix, []); <add> <add> $plugins[$plugin] = array_merge($shells, $commands); <ide> } <ide> $shellList['plugins'] = $plugins; <ide> <ide> protected function scanDir($path, $namespace, $prefix, array $hide) <ide> return []; <ide> } <ide> <add> $classPattern = '/(Shell|Command)$/'; <ide> $shells = []; <ide> foreach ($contents[1] as $file) { <ide> if (substr($file, -4) !== '.php') { <ide> continue; <ide> } <del> <ide> $shell = substr($file, 0, -4); <del> $name = Inflector::underscore(str_replace('Shell', '', $shell)); <add> if (!preg_match($classPattern, $shell)) { <add> continue; <add> } <add> <add> $name = Inflector::underscore(preg_replace($classPattern, '', $shell)); <ide> if (in_array($name, $hide, true)) { <ide> continue; <ide> } <ide><path>tests/TestCase/Console/CommandCollectionTest.php <ide> public function testAutoDiscoverApp() <ide> $collection = new CommandCollection(); <ide> $collection->addMany($collection->autoDiscover()); <ide> <add> $this->assertTrue($collection->has('demo')); <ide> $this->assertTrue($collection->has('i18m')); <ide> $this->assertTrue($collection->has('sample')); <ide> $this->assertTrue($collection->has('testing_dispatch')); <ide> <add> $this->assertSame('TestApp\Command\DemoCommand', $collection->get('demo')); <ide> $this->assertSame('TestApp\Shell\I18mShell', $collection->get('i18m')); <ide> $this->assertSame('TestApp\Shell\SampleShell', $collection->get('sample')); <ide> } <ide> public function testAutoDiscoverCore() <ide> $collection = new CommandCollection(); <ide> $collection->addMany($collection->autoDiscover()); <ide> <add> $this->assertTrue($collection->has('version')); <ide> $this->assertTrue($collection->has('routes')); <ide> $this->assertTrue($collection->has('i18n')); <ide> $this->assertTrue($collection->has('orm_cache')); <ide> public function testAutoDiscoverCore() <ide> // These have to be strings as ::class uses the local namespace. <ide> $this->assertSame('Cake\Shell\RoutesShell', $collection->get('routes')); <ide> $this->assertSame('Cake\Shell\I18nShell', $collection->get('i18n')); <add> $this->assertSame('Cake\Command\VersionCommand', $collection->get('version')); <ide> } <ide> <ide> /**
2
Mixed
Javascript
add abortsignal support to interface
54c525ef0e6d59ee43852e6d5ab1dbe3ab32b4e1
<ide><path>doc/api/readline.md <ide> the current position of the cursor down. <ide> <!-- YAML <ide> added: v0.1.98 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37932 <add> description: The `signal` option is supported now. <ide> - version: v15.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/33662 <ide> description: The `history` option is supported now. <ide> changes: <ide> **Default:** `500`. <ide> * `tabSize` {integer} The number of spaces a tab is equal to (minimum 1). <ide> **Default:** `8`. <add> * `signal` {AbortSignal} Allows closing the interface using an AbortSignal. <add> Aborting the signal will internally call `close` on the interface. <ide> * Returns: {readline.Interface} <ide> <ide> The `readline.createInterface()` method creates a new `readline.Interface` <ide><path>lib/readline.js <ide> const { <ide> ERR_INVALID_CURSOR_POS, <ide> } = codes; <ide> const { <add> validateAbortSignal, <ide> validateArray, <ide> validateCallback, <ide> validateString, <ide> function Interface(input, output, completer, terminal) { <ide> let removeHistoryDuplicates = false; <ide> let crlfDelay; <ide> let prompt = '> '; <del> <add> let signal; <ide> if (input && input.input) { <ide> // An options object was given <ide> output = input.output; <ide> completer = input.completer; <ide> terminal = input.terminal; <ide> history = input.history; <ide> historySize = input.historySize; <add> signal = input.signal; <ide> if (input.tabSize !== undefined) { <ide> validateUint32(input.tabSize, 'tabSize', true); <ide> this.tabSize = input.tabSize; <ide> function Interface(input, output, completer, terminal) { <ide> ); <ide> } <ide> } <add> <add> if (signal) { <add> validateAbortSignal(signal, 'options.signal'); <add> } <add> <ide> crlfDelay = input.crlfDelay; <ide> input = input.input; <ide> } <ide> function Interface(input, output, completer, terminal) { <ide> self.once('close', onSelfCloseWithTerminal); <ide> } <ide> <add> if (signal) { <add> const onAborted = () => self.close(); <add> if (signal.aborted) { <add> process.nextTick(onAborted); <add> } else { <add> signal.addEventListener('abort', onAborted, { once: true }); <add> self.once('close', () => signal.removeEventListener('abort', onAborted)); <add> } <add> } <add> <ide> // Current line <ide> this.line = ''; <ide> <ide><path>test/parallel/test-readline-interface.js <ide> const { <ide> getStringWidth, <ide> stripVTControlCharacters <ide> } = require('internal/util/inspect'); <del>const EventEmitter = require('events').EventEmitter; <add>const { EventEmitter, getEventListeners } = require('events'); <ide> const { Writable, Readable } = require('stream'); <ide> <ide> class FakeInput extends EventEmitter { <ide> for (let i = 0; i < 12; i++) { <ide> rl.line = `a${' '.repeat(1e6)}a`; <ide> rl.cursor = rl.line.length; <ide> } <add> <add>{ <add> const fi = new FakeInput(); <add> const signal = AbortSignal.abort(); <add> <add> const rl = readline.createInterface({ <add> input: fi, <add> output: fi, <add> signal, <add> }); <add> rl.on('close', common.mustCall()); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <add>} <add> <add>{ <add> const fi = new FakeInput(); <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const rl = readline.createInterface({ <add> input: fi, <add> output: fi, <add> signal, <add> }); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <add> rl.on('close', common.mustCall()); <add> ac.abort(); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <add>} <add> <add>{ <add> const fi = new FakeInput(); <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const rl = readline.createInterface({ <add> input: fi, <add> output: fi, <add> signal, <add> }); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 1); <add> rl.close(); <add> assert.strictEqual(getEventListeners(signal, 'abort').length, 0); <add>} <add> <add>{ <add> // Constructor throws if signal is not an abort signal <add> assert.throws(() => { <add> readline.createInterface({ <add> input: new FakeInput(), <add> signal: {}, <add> }); <add> }, { <add> name: 'TypeError', <add> code: 'ERR_INVALID_ARG_TYPE' <add> }); <add>}
3
Python
Python
fix hybrid_to_proto2 with missing timelimit
47ca2b462f22a8d48ed8d80c2f9bf8b9dc4a4de6
<ide><path>celery/worker/strategy.py <ide> def hybrid_to_proto2(message, body): <ide> 'eta': body.get('eta'), <ide> 'expires': body.get('expires'), <ide> 'retries': body.get('retries'), <del> 'timelimit': body.get('timelimit'), <add> 'timelimit': body.get('timelimit', (None, None)), <ide> 'argsrepr': body.get('argsrepr'), <ide> 'kwargsrepr': body.get('kwargsrepr'), <ide> 'origin': body.get('origin'), <ide><path>t/unit/worker/test_request.py <ide> from celery.five import monotonic <ide> from celery.signals import task_revoked <ide> from celery.worker import request as module <add>from celery.worker import strategy <ide> from celery.worker.request import Request, create_request_cls <ide> from celery.worker.request import logger as req_logger <ide> from celery.worker.state import revoked <ide> def test_execute_using_pool(self): <ide> assert job._apply_result <ide> weakref_ref.assert_called_with(self.pool.apply_async()) <ide> assert job._apply_result is weakref_ref() <add> <add> def test_execute_using_pool__defaults_of_hybrid_to_proto2(self): <add> weakref_ref = Mock(name='weakref.ref') <add> headers = strategy.hybrid_to_proto2('', {'id': uuid(), <add> 'task': self.mytask.name})[1] <add> job = self.zRequest(revoked_tasks=set(), ref=weakref_ref, **headers) <add> job.execute_using_pool(self.pool) <add> assert job._apply_result <add> weakref_ref.assert_called_with(self.pool.apply_async()) <add> assert job._apply_result is weakref_ref()
2
Python
Python
add test for issue 2626
860f5bd91f80a107bea6178b852a6d4f0a187bd2
<ide><path>spacy/tests/regression/test_issue2626.py <add>from __future__ import unicode_literals <add>import spacy <add> <add>def test_issue2626(): <add> '''Check that this sentence doesn't cause an infinite loop in the tokenizer.''' <add> nlp = spacy.blank('en') <add> text = """ <add> ABLEItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume TABLE ItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume ItemColumn IAcceptance Limits of ErrorIn-Service Limits of ErrorColumn IIColumn IIIColumn IVColumn VComputed VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeUnder Registration of\xa0VolumeOver Registration of\xa0VolumeCubic FeetCubic FeetCubic FeetCubic FeetCubic Feet1Up to 10.0100.0050.0100.005220.0200.0100.0200.010350.0360.0180.0360.0184100.0500.0250.0500.0255Over 100.5% of computed volume0.25% of computed volume0.5% of computed volume0.25% of computed volume <add> """ <add> doc = nlp.make_doc(text) <add>
1
Go
Go
display id on run -s stdin
ac0e27699c0dd9306ae0edabeff5d462399c8e74
<ide><path>commands.go <ide> func CmdRun(args ...string) error { <ide> if err != nil { <ide> return err <ide> } <add> var status int <ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr { <ide> if err := hijack("POST", "/containers/"+out.Id+"/attach?"+v.Encode(), config.Tty); err != nil { <ide> return err <ide> func CmdRun(args ...string) error { <ide> if err != nil { <ide> return err <ide> } <del> os.Exit(out.StatusCode) <add> status = out.StatusCode <ide> } <add> } <ide> <del> } else { <add> if !config.AttachStdout && !config.AttachStderr { <ide> fmt.Println(out.Id) <ide> } <add> <add> if status != 0 { <add> os.Exit(status) <add> } <ide> return nil <ide> } <ide>
1
PHP
PHP
add assertdatabasecount assertion
bb3f0aa147cbcc495716ca710a1c86b255f2fd93
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php <ide> use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Database\Eloquent\SoftDeletes; <ide> use Illuminate\Support\Arr; <add>use Illuminate\Testing\Constraints\CountInDatabase; <ide> use Illuminate\Testing\Constraints\HasInDatabase; <ide> use Illuminate\Testing\Constraints\SoftDeletedInDatabase; <ide> use PHPUnit\Framework\Constraint\LogicalNot as ReverseConstraint; <ide> protected function assertDatabaseMissing($table, array $data, $connection = null <ide> return $this; <ide> } <ide> <add> /** <add> * Assert the count of table entries. <add> * <add> * @param string $table <add> * @param int $count <add> * @param string|null $connection <add> * @return $this <add> */ <add> protected function assertDatabaseCount($table, int $count, $connection = null) <add> { <add> $this->assertThat( <add> $table, new CountInDatabase($this->getConnection($connection), $count) <add> ); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Assert the given record has been deleted. <ide> * <ide><path>src/Illuminate/Testing/Constraints/CountInDatabase.php <add><?php <add> <add>namespace Illuminate\Testing\Constraints; <add> <add>use ReflectionClass; <add>use Illuminate\Database\Connection; <add>use PHPUnit\Framework\Constraint\Constraint; <add> <add>class CountInDatabase extends Constraint <add>{ <add> <add> /** <add> * The database connection. <add> * <add> * @var \Illuminate\Database\Connection <add> */ <add> protected $database; <add> <add> /** <add> * The expected table entries count that will be checked against the actual count. <add> * <add> * @var int <add> */ <add> protected $expectedCount; <add> <add> /** <add> * The actual table entries count that will be checked against the expected count. <add> * <add> * @var int <add> */ <add> protected $actualCount; <add> <add> /** <add> * Create a new constraint instance. <add> * <add> * @param \Illuminate\Database\Connection $database <add> * @param int $expectedCount <add> * <add> * @return void <add> */ <add> public function __construct(Connection $database, int $expectedCount) <add> { <add> $this->expectedCount = $expectedCount; <add> <add> $this->database = $database; <add> } <add> <add> /** <add> * Check if the expected and actual count are equal. <add> * <add> * @param string $table <add> * @return bool <add> */ <add> public function matches($table): bool <add> { <add> $this->actualCount = $this->database->table($table)->count(); <add> <add> return $this->actualCount === $this->expectedCount; <add> } <add> <add> /** <add> * Get the description of the failure. <add> * <add> * @param string $table <add> * @return string <add> */ <add> public function failureDescription($table): string <add> { <add> return sprintf( <add> "table [%s] matches expected entries count of %s. Entries found: %s.\n", <add> $table, $this->expectedCount, $this->actualCount <add> ); <add> } <add> <add> /** <add> * Get a string representation of the object. <add> * <add> * @param int $options <add> * @return string <add> */ <add> public function toString($options = 0): string <add> { <add> return (new ReflectionClass($this))->name; <add> } <add>} <ide><path>tests/Foundation/FoundationInteractsWithDatabaseTest.php <ide> public function testDontSeeInDatabaseFindsResults() <ide> $this->assertDatabaseMissing($this->table, $this->data); <ide> } <ide> <add> public function testAssertTableEntriesCount() <add> { <add> $this->mockCountBuilder(1); <add> <add> $this->assertDatabaseCount($this->table, 1); <add> } <add> <add> public function testAssertTableEntriesCountWrong() <add> { <add> $this->expectException(ExpectationFailedException::class); <add> $this->expectExceptionMessage('Failed asserting that table [products] matches expected entries count of 3. Entries found: 1.'); <add> $this->mockCountBuilder(1); <add> <add> $this->assertDatabaseCount($this->table, 3); <add> } <add> <ide> public function testAssertDeletedPassesWhenDoesNotFindResults() <ide> { <ide> $this->mockCountBuilder(0);
3
Python
Python
implement create_node for rackspace
f7cd9536e40fea4f0dfca2eac1f0cc0dc4b7267f
<ide><path>libcloud/drivers/rackspace.py <ide> <ide> class RackspaceResponse(Response): <ide> <add> def success(self): <add> i = int(self.status) <add> #print i <add> #print self.body <add> return i >= 200 and i <= 299 <add> <ide> def parse_body(self): <ide> if not self.body: <ide> return None <ide> class RackspaceConnection(ConnectionUserAndKey): <ide> <ide> responseCls = RackspaceResponse <ide> <del> def default_headers(self): <del> return {'X-Auth-Token': self.token, <del> 'Accept': 'application/xml' } <add> def add_default_headers(self, headers): <add> headers['X-Auth-Token'] = self.token; <add> headers['Accept'] = 'application/xml' <add> return headers <ide> <ide> def _authenticate(self): <ide> # TODO: Fixup for when our token expires (!!!) <ide> def connect(self, host=None, port=None): <ide> <ide> def request(self, action, params={}, data='', method='GET'): <ide> action = self.path + action <del> return super(RackspaceConnection, self).request(action=action, params=params, data=data, method=method) <add> headers = {} <add> if method == "POST": <add> headers = {'Content-Type': 'application/xml; charset=UTF-8'} <add> return super(RackspaceConnection, self).request(action=action, <add> params=params, data=data, <add> method=method, headers=headers) <ide> <ide> class RackspaceNodeDriver(NodeDriver): <ide> <ide> def list_images(self): <ide> return self.to_images(self.connection.request('/images/detail').object) <ide> <ide> def create_node(self, name, image, size): <del> raise NotImplemented <add> body = """<server xmlns="%s" <add> name="%s" <add> imageId="%s" <add> flavorId="%s"> <add> </server> <add> """ % (NAMESPACE, name, image.id, size.id) <add> resp = self.connection.request("/servers", method='POST', data=body, ) <add> return self._to_node(resp.object) <ide> <ide> def reboot_node(self, node): <ide> # TODO: Hard Reboots should be supported too! <ide> def _node_action(self, node, body): <ide> attr = ' '.join(['%s="%s"' % (item[0], item[1]) for item in body[1:]]) <ide> body = '<%s xmlns="%s" %s/>' % (body[0], NAMESPACE, attr) <ide> uri = '/servers/%s/action' % (node.id) <del> resp = self.connection.request(uri, method='POST', body=body) <add> resp = self.connection.request(uri, method='POST', data=body) <ide> return resp <ide> <ide> def to_nodes(self, object): <ide> def _findall(self, element, xpath): <ide> <ide> def _to_node(self, el): <ide> def get_ips(el): <del> return [ip.get('addr') for ip in el.children()] <add> return [ip.get('addr') for ip in el] <ide> <ide> public_ip = get_ips(self._findall(el, <ide> 'addresses/public'))
1
Mixed
Text
fix spelling, routing setup call and formatting
78a530282ee7b55ba39c76cf5c67d0d239bb5edc
<ide><path>README.md <ide> end <ide> Then setup a mailbox: <ide> <ide> ```ruby <del># Generate new maiblox <add># Generate new mailbox <ide> bin/rails generate mailbox forwards <ide> ``` <ide> <ide><path>lib/action_mailbox/base.rb <ide> # <ide> # class ApplicationMailbox < ActionMailbox::Base <ide> # # Any of the recipients of the mail (whether to, cc, bcc) are matched against the regexp. <del># route /^replies@/i => :replies <add># routing /^replies@/i => :replies <ide> # <ide> # # Any of the recipients of the mail (whether to, cc, bcc) needs to be an exact match for the string. <del># route "help@example.com" => :help <add># routing "help@example.com" => :help <ide> # <ide> # # Any callable (proc, lambda, etc) object is passed the inbound_email record and is a match if true. <del># route ->(inbound_email) { inbound_email.mail.to.size > 2 } => :multiple_recipients <add># routing ->(inbound_email) { inbound_email.mail.to.size > 2 } => :multiple_recipients <ide> # <ide> # # Any object responding to #match? is called with the inbound_email record as an argument. Match if true. <del># route CustomAddress.new => :custom <add># routing CustomAddress.new => :custom <ide> # <ide> # # Any inbound_email that has not been already matched will be sent to the BackstopMailbox. <del># route :all => :backstop <add># routing :all => :backstop <ide> # end <ide> # <ide> # Application mailboxes need to overwrite the `#process` method, which is invoked by the framework after <ide> # callbacks have been run. The callbacks available are: `before_processing`, `after_processing`, and <ide> # `around_processing`. The primary use case is ensure certain preconditions to processing are fulfilled <ide> # using `before_processing` callbacks. <ide> # <del># If a precondition fails to be met, you can halt the processing using the `#bounced!` method, <add># If a precondition fails to be met, you can halt the processing using the `#bounced!` method, <ide> # which will silently prevent any further processing, but not actually send out any bounce notice. You <ide> # can also pair this behavior with the invocation of an Action Mailer class responsible for sending out <ide> # an actual bounce email. This is done using the `#bounce_with` method, which takes the mail object returned <ide> # end <ide> # <ide> # During the processing of the inbound email, the status will be tracked. Before processing begins, <del># the email will normally have the `pending` status. Once processing begins, just before callbacks <add># the email will normally have the `pending` status. Once processing begins, just before callbacks <ide> # and the `#process` method is called, the status is changed to `processing`. If processing is allowed to <ide> # complete, the status is changed to `delivered`. If a bounce is triggered, then `bounced`. If an unhandled <ide> # exception is bubbled up, then `failed`. <ide> # <ide> # Exceptions can be handled at the class level using the familiar `Rescuable` approach: <ide> # <ide> # class ForwardsMailbox < ApplicationMailbox <del># rescue_from(ApplicationSpecificVerificationError) { bounced! } <add># rescue_from(ApplicationSpecificVerificationError) { bounced! } <ide> # end <ide> class ActionMailbox::Base <ide> include ActiveSupport::Rescuable
2
Javascript
Javascript
detect data modifications with equal values
50f2a1097a7db459adf38a9e9981e7aa26967c72
<ide><path>src/core/core.datasetController.js <ide> export default class DatasetController { <ide> this._parsing = false; <ide> this._data = undefined; <ide> this._dataCopy = undefined; <add> this._dataModified = false; <ide> this._objectData = undefined; <ide> this._labels = undefined; <ide> this._scaleStacked = {}; <ide> export default class DatasetController { <ide> me._data = convertObjectDataToArray(data); <ide> me._objectData = data; <ide> } else { <del> if (me._data === data && helpers.arrayEquals(data, me._dataCopy)) { <add> if (me._data === data && !me._dataModified && helpers.arrayEquals(data, me._dataCopy)) { <ide> return false; <ide> } <ide> <ide> export default class DatasetController { <ide> // Note: This is suboptimal, but better than always parsing the data <ide> me._dataCopy = data.slice(0); <ide> <add> me._dataModified = false; <add> <ide> if (data && Object.isExtensible(data)) { <ide> listenArrayEvents(data, me); <ide> } <ide> export default class DatasetController { <ide> _onDataPush() { <ide> const count = arguments.length; <ide> this._insertElements(this.getDataset().data.length - count, count); <add> this._dataModified = true; <ide> } <ide> <ide> /** <ide> * @private <ide> */ <ide> _onDataPop() { <ide> this._removeElements(this._cachedMeta.data.length - 1, 1); <add> this._dataModified = true; <ide> } <ide> <ide> /** <ide> * @private <ide> */ <ide> _onDataShift() { <ide> this._removeElements(0, 1); <add> this._dataModified = true; <ide> } <ide> <ide> /** <ide> export default class DatasetController { <ide> _onDataSplice(start, count) { <ide> this._removeElements(start, count); <ide> this._insertElements(start, arguments.length - 2); <add> this._dataModified = true; <ide> } <ide> <ide> /** <ide> * @private <ide> */ <ide> _onDataUnshift() { <ide> this._insertElements(0, arguments.length); <add> this._dataModified = true; <ide> } <ide> } <ide> <ide><path>test/specs/core.datasetController.tests.js <ide> describe('Chart.DatasetController', function() { <ide> expect(meta.data.length).toBe(42); <ide> }); <ide> <add> // https://github.com/chartjs/Chart.js/issues/7243 <add> it('should re-synchronize metadata when data is moved and values are equal', function() { <add> var data = [10, 10, 10, 10, 10, 10]; <add> var chart = acquireChart({ <add> type: 'line', <add> data: { <add> labels: ['a', 'b', 'c', 'd', 'e', 'f'], <add> datasets: [{ <add> data, <add> fill: true <add> }] <add> } <add> }); <add> <add> var meta = chart.getDatasetMeta(0); <add> <add> expect(meta.data.length).toBe(6); <add> const firstX = meta.data[0].x; <add> <add> data.push(data.shift()); <add> chart.update(); <add> <add> expect(meta.data.length).toBe(6); <add> expect(meta.data[0].x).toEqual(firstX); <add> }); <add> <ide> it('should re-synchronize metadata when scaleID changes', function() { <ide> var chart = acquireChart({ <ide> type: 'line',
2
Java
Java
fix javadoc links
0cff7eb32cb4123f72a8dfdccbccf7d4a3cf9a7e
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java <ide> public interface RSocketRequester { <ide> * <p>For requestChannel interactions, i.e. Flux-to-Flux the metadata is <ide> * attached to the first request payload. <ide> * @param route the routing destination <del> * @return a spec for further defining and executing the reuqest <add> * @return a spec for further defining and executing the request <ide> */ <ide> RequestSpec route(String route); <ide> <ide> <ide> /** <ide> * Obtain a builder for an {@link RSocketRequester} by connecting to an <ide> * RSocket server. The builder allows for customization of <del> * {@link RSocketFactory.ClientRSocketFactory ClientRSocketFactory} settings, <del> * {@link RSocketStrategies}, and for selecting the transport to use. <add> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory ClientRSocketFactory} <add> * settings, {@link RSocketStrategies}, and for selecting the transport to use. <ide> */ <ide> static RSocketRequester.Builder builder() { <ide> return new DefaultRSocketRequesterBuilder(); <ide> interface RequestSpec { <ide> * Provide request payload data. The given Object may be a synchronous <ide> * value, or a {@link Publisher} of values, or another async type that's <ide> * registered in the configured {@link ReactiveAdapterRegistry}. <del> * <p>For multivalued Publishers, prefer using <add> * <p>For multi-valued Publishers, prefer using <ide> * {@link #data(Publisher, Class)} or <ide> * {@link #data(Publisher, ParameterizedTypeReference)} since that makes <ide> * it possible to find a compatible {@code Encoder} up front vs looking <ide> interface RequestSpec { <ide> * <p>Publisher semantics determined through the configured <ide> * {@link ReactiveAdapterRegistry} influence which of the 4 RSocket <ide> * interactions to use. Publishers with unknown semantics are treated <del> * as multivalued. Consider registering a reactive type adapter, or <add> * as multi-valued. Consider registering a reactive type adapter, or <ide> * passing {@code Mono.from(publisher)}. <ide> * <p>If the publisher completes empty, possibly {@code Publisher<Void>}, <ide> * the request will have an empty data Payload. <ide> interface ResponseSpec { <ide> * expected data type is {@code Void.class}, the returned {@code Mono} <ide> * will complete after all data is consumed. <ide> * <p><strong>Note:</strong> Use of this method will raise an error if <del> * the request payload is a multivalued {@link Publisher} as <add> * the request payload is a multi-valued {@link Publisher} as <ide> * determined through the configured {@link ReactiveAdapterRegistry}. <ide> * @param dataType the expected data type for the response <ide> * @param <T> parameter for the expected data type <ide><path>spring-test/src/main/java/org/springframework/test/context/TestConstructor.java <ide> * <ide> * <p>If {@code @TestConstructor} is not <em>present</em> or <em>meta-present</em> <ide> * on a test class, the default <em>test constructor autowire</em> mode will be used. <del> * See {@link #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME} for details on how to change <add> * See {@link #TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME} for details on how to change <ide> * the default mode. Note, however, that a local declaration of <ide> * {@link org.springframework.beans.factory.annotation.Autowired @Autowired} on <ide> * a constructor takes precedence over both {@code @TestConstructor} and the default <ide> * Flag for setting the <em>test constructor autowire</em> mode for the <ide> * current test class. <ide> * <p>Setting this flag overrides the global default. See <del> * {@link #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME} for details on how to <add> * {@link #TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME} for details on how to <ide> * change the global default. <ide> * @return {@code true} if all test constructor arguments should be autowired <ide> * from the test's {@link org.springframework.context.ApplicationContext <ide> * ApplicationContext} <del> * @see #AUTOWIRE_TEST_CONSTRUCTOR_PROPERTY_NAME <add> * @see #TEST_CONSTRUCTOR_AUTOWIRE_PROPERTY_NAME <ide> * @see org.springframework.beans.factory.annotation.Autowired @Autowired <ide> */ <ide> boolean autowire();
2
Javascript
Javascript
add canadian i18n
46b451c89a49e4ba4a566330b9e92681e1aac3e7
<ide><path>lang/en-ca.js <ide> weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), <ide> longDateFormat : { <ide> LT : "h:mm A", <del> L : "DD/MM/YYYY", <del> LL : "D MMMM YYYY", <del> LLL : "D MMMM YYYY LT", <del> LLLL : "dddd, D MMMM YYYY LT" <add> L : "YYYY-MM-DD", <add> LL : "D MMMM, YYYY", <add> LLL : "D MMMM, YYYY LT", <add> LLLL : "dddd, D MMMM, YYYY LT" <ide> }, <ide> calendar : { <ide> sameDay : '[Today at] LT', <ide><path>lang/fr-ca.js <ide> weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), <ide> longDateFormat : { <ide> LT : "HH:mm", <del> L : "DD/MM/YYYY", <add> L : "YYYY-MM-DD", <ide> LL : "D MMMM YYYY", <ide> LLL : "D MMMM YYYY LT", <ide> LLLL : "dddd D MMMM YYYY LT"
2
Javascript
Javascript
make flaky test stricter
9949a2e1e3100c4ff1f228bac57c1af95cdc3e9d
<ide><path>test/parallel/test-http-destroyed-socket-write2.js <ide> server.listen(0, function() { <ide> } <ide> <ide> req.on('error', common.mustCall(function(er) { <add> assert.strictEqual(req.res, null); <ide> switch (er.code) { <ide> // This is the expected case <ide> case 'ECONNRESET': <ide> server.listen(0, function() { <ide> server.close(); <ide> })); <ide> <del> req.on('response', function(res) { <del> res.on('data', common.mustNotCall('Should not receive response data')); <del> res.on('end', common.mustNotCall('Should not receive response end')); <del> }); <add> req.on('response', common.mustNotCall()); <ide> <ide> write(); <ide> });
1
Ruby
Ruby
ask the scope for the action name
e4cb3819dfe36cc9a8396fb207b74980d7bd0cd5
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def name_for_action(as, action) #:nodoc: <ide> member_name = parent_resource.member_name <ide> end <ide> <del> name = case scope_level <del> when :nested <del> [name_prefix, prefix] <del> when :collection <del> [prefix, name_prefix, collection_name] <del> when :new <del> [prefix, :new, name_prefix, member_name] <del> when :member <del> [prefix, name_prefix, member_name] <del> when :root <del> [name_prefix, collection_name, prefix] <del> else <del> [name_prefix, member_name, prefix] <del> end <add> name = @scope.action_name(name_prefix, prefix, collection_name, member_name) <ide> <ide> if candidate = name.compact.join("_").presence <ide> # If a name was not explicitly given, we check if it is valid <ide> def resources? <ide> scope_level == :resources <ide> end <ide> <add> def action_name(name_prefix, prefix, collection_name, member_name) <add> case scope_level <add> when :nested <add> [name_prefix, prefix] <add> when :collection <add> [prefix, name_prefix, collection_name] <add> when :new <add> [prefix, :new, name_prefix, member_name] <add> when :member <add> [prefix, name_prefix, member_name] <add> when :root <add> [name_prefix, collection_name, prefix] <add> else <add> [name_prefix, member_name, prefix] <add> end <add> end <add> <ide> def resource_scope? <ide> RESOURCE_SCOPES.include? scope_level <ide> end
1
Python
Python
add newline to task failed log message
4bca120eef3a40eeaa9b2433c6bc78d937ef6767
<ide><path>celery/worker/job.py <ide> # says "trailing whitespace" ;) <ide> EMAIL_SIGNATURE_SEP = "-- " <ide> TASK_ERROR_EMAIL_BODY = """ <del>Task %%(name)s with id %%(id)s raised exception: %%(exc)s <add>Task %%(name)s with id %%(id)s raised exception:\n%%(exc)s <ide> <ide> <ide> Task was called with args: %%(args)s kwargs: %%(kwargs)s.
1
PHP
PHP
add test for array iterator issue
38e764671af844341d058ae6f23c68c2c8937bbe
<ide><path>tests/TestCase/Collection/CollectionTest.php <ide> public function __construct($items) <ide> } <ide> } <ide> <add>/** <add> * Special class to test that extending \ArrayIterator works as expected <add> */ <add>class TestIterator extends ArrayIterator <add>{ <add> use CollectionTrait; <add> <add> public $data = []; <add> <add> public function __construct($data) <add> { <add> $this->data = $data; <add> <add> parent::__construct($data); <add> } <add> <add> public function checkValues() <add> { <add> return true; <add> } <add>} <add> <ide> /** <ide> * CollectionTest <ide> */ <ide> protected function datePeriod($start, $end) <ide> { <ide> return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end)); <ide> } <add> <add> /** <add> * Tests to ensure that collection classes extending ArrayIterator work as expected. <add> * <add> * @return void <add> */ <add> public function testArrayIteratorExtend() <add> { <add> $iterator = new TestIterator(range(0, 10)); <add> <add> $this->assertTrue(method_exists($iterator, 'checkValues')); <add> $this->assertTrue($iterator->checkValues()); <add> <add> //We need to perform at least two collection operation to trigger the issue. <add> $newIterator = $iterator <add> ->filter(function ($item) { <add> return $item < 5; <add> }) <add> ->reject(function ($item) { <add> return $item > 2; <add> }); <add> <add> $this->assertTrue(method_exists($newIterator, 'checkValues'), 'Our method has gone missing!'); <add> $this->assertTrue($newIterator->checkValues()); <add> $this->assertCount(3, $newIterator->toArray()); <add> } <ide> }
1
Javascript
Javascript
move flag check into each switch case
3df7e8f5dcc3e379d8ce738da2a87029467bcf1d
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> function commitLayoutEffectOnFiber( <ide> finishedWork: Fiber, <ide> committedLanes: Lanes, <ide> ): void { <del> if ((finishedWork.flags & LayoutMask) !== NoFlags) { <del> switch (finishedWork.tag) { <del> case FunctionComponent: <del> case ForwardRef: <del> case SimpleMemoComponent: { <add> const flags = finishedWork.flags; <add> switch (finishedWork.tag) { <add> case FunctionComponent: <add> case ForwardRef: <add> case SimpleMemoComponent: { <add> if (flags & Update) { <ide> if (!offscreenSubtreeWasHidden) { <ide> // At this point layout effects have already been destroyed (during mutation phase). <ide> // This is done to prevent sibling component effects from interfering with each other, <ide> function commitLayoutEffectOnFiber( <ide> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork); <ide> } <ide> } <del> break; <ide> } <del> case ClassComponent: { <del> const instance = finishedWork.stateNode; <del> if (finishedWork.flags & Update) { <del> if (!offscreenSubtreeWasHidden) { <del> if (current === null) { <del> // We could update instance props and state here, <del> // but instead we rely on them being set during last render. <del> // TODO: revisit this when we implement resuming. <del> if (__DEV__) { <del> if ( <del> finishedWork.type === finishedWork.elementType && <del> !didWarnAboutReassigningProps <del> ) { <del> if (instance.props !== finishedWork.memoizedProps) { <del> console.error( <del> 'Expected %s props to match memoized props before ' + <del> 'componentDidMount. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.props`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> if (instance.state !== finishedWork.memoizedState) { <del> console.error( <del> 'Expected %s state to match memoized state before ' + <del> 'componentDidMount. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.state`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> } <del> } <add> break; <add> } <add> case ClassComponent: { <add> if (flags & Update) { <add> if (!offscreenSubtreeWasHidden) { <add> const instance = finishedWork.stateNode; <add> if (current === null) { <add> // We could update instance props and state here, <add> // but instead we rely on them being set during last render. <add> // TODO: revisit this when we implement resuming. <add> if (__DEV__) { <ide> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> finishedWork.mode & ProfileMode <add> finishedWork.type === finishedWork.elementType && <add> !didWarnAboutReassigningProps <ide> ) { <del> try { <del> startLayoutEffectTimer(); <del> instance.componentDidMount(); <del> } finally { <del> recordLayoutEffectDuration(finishedWork); <add> if (instance.props !== finishedWork.memoizedProps) { <add> console.error( <add> 'Expected %s props to match memoized props before ' + <add> 'componentDidMount. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.props`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <add> } <add> if (instance.state !== finishedWork.memoizedState) { <add> console.error( <add> 'Expected %s state to match memoized state before ' + <add> 'componentDidMount. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.state`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <ide> } <del> } else { <add> } <add> } <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> try { <add> startLayoutEffectTimer(); <ide> instance.componentDidMount(); <add> } finally { <add> recordLayoutEffectDuration(finishedWork); <ide> } <ide> } else { <del> const prevProps = <del> finishedWork.elementType === finishedWork.type <del> ? current.memoizedProps <del> : resolveDefaultProps( <del> finishedWork.type, <del> current.memoizedProps, <del> ); <del> const prevState = current.memoizedState; <del> // We could update instance props and state here, <del> // but instead we rely on them being set during last render. <del> // TODO: revisit this when we implement resuming. <del> if (__DEV__) { <del> if ( <del> finishedWork.type === finishedWork.elementType && <del> !didWarnAboutReassigningProps <del> ) { <del> if (instance.props !== finishedWork.memoizedProps) { <del> console.error( <del> 'Expected %s props to match memoized props before ' + <del> 'componentDidUpdate. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.props`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> if (instance.state !== finishedWork.memoizedState) { <del> console.error( <del> 'Expected %s state to match memoized state before ' + <del> 'componentDidUpdate. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.state`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> } <del> } <add> instance.componentDidMount(); <add> } <add> } else { <add> const prevProps = <add> finishedWork.elementType === finishedWork.type <add> ? current.memoizedProps <add> : resolveDefaultProps(finishedWork.type, current.memoizedProps); <add> const prevState = current.memoizedState; <add> // We could update instance props and state here, <add> // but instead we rely on them being set during last render. <add> // TODO: revisit this when we implement resuming. <add> if (__DEV__) { <ide> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> finishedWork.mode & ProfileMode <add> finishedWork.type === finishedWork.elementType && <add> !didWarnAboutReassigningProps <ide> ) { <del> try { <del> startLayoutEffectTimer(); <del> instance.componentDidUpdate( <del> prevProps, <del> prevState, <del> instance.__reactInternalSnapshotBeforeUpdate, <add> if (instance.props !== finishedWork.memoizedProps) { <add> console.error( <add> 'Expected %s props to match memoized props before ' + <add> 'componentDidUpdate. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.props`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <ide> ); <del> } finally { <del> recordLayoutEffectDuration(finishedWork); <ide> } <del> } else { <add> if (instance.state !== finishedWork.memoizedState) { <add> console.error( <add> 'Expected %s state to match memoized state before ' + <add> 'componentDidUpdate. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.state`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <add> } <add> } <add> } <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> try { <add> startLayoutEffectTimer(); <ide> instance.componentDidUpdate( <ide> prevProps, <ide> prevState, <ide> instance.__reactInternalSnapshotBeforeUpdate, <ide> ); <add> } finally { <add> recordLayoutEffectDuration(finishedWork); <ide> } <add> } else { <add> instance.componentDidUpdate( <add> prevProps, <add> prevState, <add> instance.__reactInternalSnapshotBeforeUpdate, <add> ); <ide> } <ide> } <ide> } <add> } <ide> <add> if (flags & Callback) { <ide> // TODO: I think this is now always non-null by the time it reaches the <ide> // commit phase. Consider removing the type check. <ide> const updateQueue: UpdateQueue< <ide> *, <ide> > | null = (finishedWork.updateQueue: any); <del> if (finishedWork.flags & Callback && updateQueue !== null) { <add> if (updateQueue !== null) { <add> const instance = finishedWork.stateNode; <ide> if (__DEV__) { <ide> if ( <ide> finishedWork.type === finishedWork.elementType && <ide> function commitLayoutEffectOnFiber( <ide> // TODO: revisit this when we implement resuming. <ide> commitCallbacks(updateQueue, instance); <ide> } <add> } <ide> <del> if (finishedWork.flags & Ref) { <del> if (!offscreenSubtreeWasHidden) { <del> commitAttachRef(finishedWork); <del> } <add> if (flags & Ref) { <add> if (!offscreenSubtreeWasHidden) { <add> commitAttachRef(finishedWork); <ide> } <del> break; <ide> } <del> case HostRoot: { <add> break; <add> } <add> case HostRoot: { <add> if (flags & Callback) { <ide> // TODO: I think this is now always non-null by the time it reaches the <ide> // commit phase. Consider removing the type check. <ide> const updateQueue: UpdateQueue< <ide> *, <ide> > | null = (finishedWork.updateQueue: any); <del> if (finishedWork.flags & Callback && updateQueue !== null) { <add> if (updateQueue !== null) { <ide> let instance = null; <ide> if (finishedWork.child !== null) { <ide> switch (finishedWork.child.tag) { <ide> function commitLayoutEffectOnFiber( <ide> } <ide> commitCallbacks(updateQueue, instance); <ide> } <del> break; <ide> } <del> case HostComponent: { <add> break; <add> } <add> case HostComponent: { <add> if (flags & Update) { <ide> const instance: Instance = finishedWork.stateNode; <ide> <ide> // Renderers may schedule work to be done after host components are mounted <ide> function commitLayoutEffectOnFiber( <ide> const props = finishedWork.memoizedProps; <ide> commitMount(instance, type, props, finishedWork); <ide> } <add> } <ide> <del> if (finishedWork.flags & Ref) { <del> if (!offscreenSubtreeWasHidden) { <del> commitAttachRef(finishedWork); <del> } <add> if (flags & Ref) { <add> if (!offscreenSubtreeWasHidden) { <add> commitAttachRef(finishedWork); <ide> } <del> break; <del> } <del> case HostText: { <del> // We have no life-cycles associated with text. <del> break; <ide> } <del> case HostPortal: { <del> // We have no life-cycles associated with portals. <del> break; <del> } <del> case Profiler: { <del> if (enableProfilerTimer) { <add> break; <add> } <add> case HostText: { <add> // We have no life-cycles associated with text. <add> break; <add> } <add> case HostPortal: { <add> // We have no life-cycles associated with portals. <add> break; <add> } <add> case Profiler: { <add> if (enableProfilerTimer) { <add> if (flags & Update) { <ide> const {onCommit, onRender} = finishedWork.memoizedProps; <ide> const {effectDuration} = finishedWork.stateNode; <ide> <ide> function commitLayoutEffectOnFiber( <ide> } <ide> } <ide> } <del> break; <ide> } <del> case SuspenseComponent: { <add> break; <add> } <add> case SuspenseComponent: { <add> if (flags & Update) { <ide> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); <del> break; <ide> } <del> case SuspenseListComponent: <del> case IncompleteClassComponent: <del> case ScopeComponent: <del> case OffscreenComponent: <del> case LegacyHiddenComponent: <del> case TracingMarkerComponent: { <del> break; <del> } <del> <del> default: <del> throw new Error( <del> 'This unit of work tag should not have side-effects. This error is ' + <del> 'likely caused by a bug in React. Please file an issue.', <del> ); <add> break; <add> } <add> case SuspenseListComponent: <add> case IncompleteClassComponent: <add> case ScopeComponent: <add> case OffscreenComponent: <add> case LegacyHiddenComponent: <add> case TracingMarkerComponent: { <add> break; <ide> } <add> <add> default: <add> throw new Error( <add> 'This unit of work tag should not have side-effects. This error is ' + <add> 'likely caused by a bug in React. Please file an issue.', <add> ); <ide> } <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> function commitLayoutEffectOnFiber( <ide> finishedWork: Fiber, <ide> committedLanes: Lanes, <ide> ): void { <del> if ((finishedWork.flags & LayoutMask) !== NoFlags) { <del> switch (finishedWork.tag) { <del> case FunctionComponent: <del> case ForwardRef: <del> case SimpleMemoComponent: { <add> const flags = finishedWork.flags; <add> switch (finishedWork.tag) { <add> case FunctionComponent: <add> case ForwardRef: <add> case SimpleMemoComponent: { <add> if (flags & Update) { <ide> if (!offscreenSubtreeWasHidden) { <ide> // At this point layout effects have already been destroyed (during mutation phase). <ide> // This is done to prevent sibling component effects from interfering with each other, <ide> function commitLayoutEffectOnFiber( <ide> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork); <ide> } <ide> } <del> break; <ide> } <del> case ClassComponent: { <del> const instance = finishedWork.stateNode; <del> if (finishedWork.flags & Update) { <del> if (!offscreenSubtreeWasHidden) { <del> if (current === null) { <del> // We could update instance props and state here, <del> // but instead we rely on them being set during last render. <del> // TODO: revisit this when we implement resuming. <del> if (__DEV__) { <del> if ( <del> finishedWork.type === finishedWork.elementType && <del> !didWarnAboutReassigningProps <del> ) { <del> if (instance.props !== finishedWork.memoizedProps) { <del> console.error( <del> 'Expected %s props to match memoized props before ' + <del> 'componentDidMount. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.props`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> if (instance.state !== finishedWork.memoizedState) { <del> console.error( <del> 'Expected %s state to match memoized state before ' + <del> 'componentDidMount. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.state`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> } <del> } <add> break; <add> } <add> case ClassComponent: { <add> if (flags & Update) { <add> if (!offscreenSubtreeWasHidden) { <add> const instance = finishedWork.stateNode; <add> if (current === null) { <add> // We could update instance props and state here, <add> // but instead we rely on them being set during last render. <add> // TODO: revisit this when we implement resuming. <add> if (__DEV__) { <ide> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> finishedWork.mode & ProfileMode <add> finishedWork.type === finishedWork.elementType && <add> !didWarnAboutReassigningProps <ide> ) { <del> try { <del> startLayoutEffectTimer(); <del> instance.componentDidMount(); <del> } finally { <del> recordLayoutEffectDuration(finishedWork); <add> if (instance.props !== finishedWork.memoizedProps) { <add> console.error( <add> 'Expected %s props to match memoized props before ' + <add> 'componentDidMount. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.props`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <add> } <add> if (instance.state !== finishedWork.memoizedState) { <add> console.error( <add> 'Expected %s state to match memoized state before ' + <add> 'componentDidMount. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.state`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <ide> } <del> } else { <add> } <add> } <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> try { <add> startLayoutEffectTimer(); <ide> instance.componentDidMount(); <add> } finally { <add> recordLayoutEffectDuration(finishedWork); <ide> } <ide> } else { <del> const prevProps = <del> finishedWork.elementType === finishedWork.type <del> ? current.memoizedProps <del> : resolveDefaultProps( <del> finishedWork.type, <del> current.memoizedProps, <del> ); <del> const prevState = current.memoizedState; <del> // We could update instance props and state here, <del> // but instead we rely on them being set during last render. <del> // TODO: revisit this when we implement resuming. <del> if (__DEV__) { <del> if ( <del> finishedWork.type === finishedWork.elementType && <del> !didWarnAboutReassigningProps <del> ) { <del> if (instance.props !== finishedWork.memoizedProps) { <del> console.error( <del> 'Expected %s props to match memoized props before ' + <del> 'componentDidUpdate. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.props`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> if (instance.state !== finishedWork.memoizedState) { <del> console.error( <del> 'Expected %s state to match memoized state before ' + <del> 'componentDidUpdate. ' + <del> 'This might either be because of a bug in React, or because ' + <del> 'a component reassigns its own `this.state`. ' + <del> 'Please file an issue.', <del> getComponentNameFromFiber(finishedWork) || 'instance', <del> ); <del> } <del> } <del> } <add> instance.componentDidMount(); <add> } <add> } else { <add> const prevProps = <add> finishedWork.elementType === finishedWork.type <add> ? current.memoizedProps <add> : resolveDefaultProps(finishedWork.type, current.memoizedProps); <add> const prevState = current.memoizedState; <add> // We could update instance props and state here, <add> // but instead we rely on them being set during last render. <add> // TODO: revisit this when we implement resuming. <add> if (__DEV__) { <ide> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> finishedWork.mode & ProfileMode <add> finishedWork.type === finishedWork.elementType && <add> !didWarnAboutReassigningProps <ide> ) { <del> try { <del> startLayoutEffectTimer(); <del> instance.componentDidUpdate( <del> prevProps, <del> prevState, <del> instance.__reactInternalSnapshotBeforeUpdate, <add> if (instance.props !== finishedWork.memoizedProps) { <add> console.error( <add> 'Expected %s props to match memoized props before ' + <add> 'componentDidUpdate. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.props`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <ide> ); <del> } finally { <del> recordLayoutEffectDuration(finishedWork); <ide> } <del> } else { <add> if (instance.state !== finishedWork.memoizedState) { <add> console.error( <add> 'Expected %s state to match memoized state before ' + <add> 'componentDidUpdate. ' + <add> 'This might either be because of a bug in React, or because ' + <add> 'a component reassigns its own `this.state`. ' + <add> 'Please file an issue.', <add> getComponentNameFromFiber(finishedWork) || 'instance', <add> ); <add> } <add> } <add> } <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> finishedWork.mode & ProfileMode <add> ) { <add> try { <add> startLayoutEffectTimer(); <ide> instance.componentDidUpdate( <ide> prevProps, <ide> prevState, <ide> instance.__reactInternalSnapshotBeforeUpdate, <ide> ); <add> } finally { <add> recordLayoutEffectDuration(finishedWork); <ide> } <add> } else { <add> instance.componentDidUpdate( <add> prevProps, <add> prevState, <add> instance.__reactInternalSnapshotBeforeUpdate, <add> ); <ide> } <ide> } <ide> } <add> } <ide> <add> if (flags & Callback) { <ide> // TODO: I think this is now always non-null by the time it reaches the <ide> // commit phase. Consider removing the type check. <ide> const updateQueue: UpdateQueue< <ide> *, <ide> > | null = (finishedWork.updateQueue: any); <del> if (finishedWork.flags & Callback && updateQueue !== null) { <add> if (updateQueue !== null) { <add> const instance = finishedWork.stateNode; <ide> if (__DEV__) { <ide> if ( <ide> finishedWork.type === finishedWork.elementType && <ide> function commitLayoutEffectOnFiber( <ide> // TODO: revisit this when we implement resuming. <ide> commitCallbacks(updateQueue, instance); <ide> } <add> } <ide> <del> if (finishedWork.flags & Ref) { <del> if (!offscreenSubtreeWasHidden) { <del> commitAttachRef(finishedWork); <del> } <add> if (flags & Ref) { <add> if (!offscreenSubtreeWasHidden) { <add> commitAttachRef(finishedWork); <ide> } <del> break; <ide> } <del> case HostRoot: { <add> break; <add> } <add> case HostRoot: { <add> if (flags & Callback) { <ide> // TODO: I think this is now always non-null by the time it reaches the <ide> // commit phase. Consider removing the type check. <ide> const updateQueue: UpdateQueue< <ide> *, <ide> > | null = (finishedWork.updateQueue: any); <del> if (finishedWork.flags & Callback && updateQueue !== null) { <add> if (updateQueue !== null) { <ide> let instance = null; <ide> if (finishedWork.child !== null) { <ide> switch (finishedWork.child.tag) { <ide> function commitLayoutEffectOnFiber( <ide> } <ide> commitCallbacks(updateQueue, instance); <ide> } <del> break; <ide> } <del> case HostComponent: { <add> break; <add> } <add> case HostComponent: { <add> if (flags & Update) { <ide> const instance: Instance = finishedWork.stateNode; <ide> <ide> // Renderers may schedule work to be done after host components are mounted <ide> function commitLayoutEffectOnFiber( <ide> const props = finishedWork.memoizedProps; <ide> commitMount(instance, type, props, finishedWork); <ide> } <add> } <ide> <del> if (finishedWork.flags & Ref) { <del> if (!offscreenSubtreeWasHidden) { <del> commitAttachRef(finishedWork); <del> } <add> if (flags & Ref) { <add> if (!offscreenSubtreeWasHidden) { <add> commitAttachRef(finishedWork); <ide> } <del> break; <del> } <del> case HostText: { <del> // We have no life-cycles associated with text. <del> break; <ide> } <del> case HostPortal: { <del> // We have no life-cycles associated with portals. <del> break; <del> } <del> case Profiler: { <del> if (enableProfilerTimer) { <add> break; <add> } <add> case HostText: { <add> // We have no life-cycles associated with text. <add> break; <add> } <add> case HostPortal: { <add> // We have no life-cycles associated with portals. <add> break; <add> } <add> case Profiler: { <add> if (enableProfilerTimer) { <add> if (flags & Update) { <ide> const {onCommit, onRender} = finishedWork.memoizedProps; <ide> const {effectDuration} = finishedWork.stateNode; <ide> <ide> function commitLayoutEffectOnFiber( <ide> } <ide> } <ide> } <del> break; <ide> } <del> case SuspenseComponent: { <add> break; <add> } <add> case SuspenseComponent: { <add> if (flags & Update) { <ide> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); <del> break; <ide> } <del> case SuspenseListComponent: <del> case IncompleteClassComponent: <del> case ScopeComponent: <del> case OffscreenComponent: <del> case LegacyHiddenComponent: <del> case TracingMarkerComponent: { <del> break; <del> } <del> <del> default: <del> throw new Error( <del> 'This unit of work tag should not have side-effects. This error is ' + <del> 'likely caused by a bug in React. Please file an issue.', <del> ); <add> break; <add> } <add> case SuspenseListComponent: <add> case IncompleteClassComponent: <add> case ScopeComponent: <add> case OffscreenComponent: <add> case LegacyHiddenComponent: <add> case TracingMarkerComponent: { <add> break; <ide> } <add> <add> default: <add> throw new Error( <add> 'This unit of work tag should not have side-effects. This error is ' + <add> 'likely caused by a bug in React. Please file an issue.', <add> ); <ide> } <ide> } <ide>
2
Java
Java
fix checkstyle issues
75fa9c4266a516039b1b797fe8ccd8b2614e7647
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/UnknownHttpStatusCodeException.java <add>/* <add> * Copyright 2002-2018 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <ide> package org.springframework.web.reactive.function.client; <ide> <ide> import java.nio.charset.Charset; <ide> public UnknownHttpStatusCodeException(int statusCode, HttpHeaders headers, <ide> super("Unknown status code [" + statusCode + "]", statusCode, "", <ide> headers, responseBody, responseCharset); <ide> } <del> <add> <ide> }
1
Javascript
Javascript
remove persistence from rntester app
33fb70f6b60cb3c332698a1c00ca1883caf576ba
<ide><path>RNTester/e2e/__tests__/Button-test.js <ide> * @format <ide> */ <ide> <del>/* global element, by, expect */ <add>/* global device, element, by, expect */ <ide> <ide> describe('Button', () => { <ide> beforeAll(async () => { <add> await device.reloadReactNative(); <ide> await element(by.id('explorer_search')).replaceText('<Button>'); <ide> await element( <ide> by.label('<Button> Simple React Native button component.'), <ide><path>RNTester/e2e/__tests__/Switch-test.js <ide> * @format <ide> */ <ide> <del>/* global element, by, expect */ <add>/* global device, element, by, expect */ <ide> <ide> const jestExpect = require('expect'); <ide> <ide> describe('Switch', () => { <ide> beforeAll(async () => { <add> await device.reloadReactNative(); <ide> await element(by.id('explorer_search')).replaceText('<Switch>'); <ide> await element(by.label('<Switch> Native boolean input')).tap(); <ide> }); <ide><path>RNTester/js/RNTesterApp.ios.js <ide> class RNTesterApp extends React.Component<Props, RNTesterNavigationState> { <ide> ); <ide> const urlAction = URIActionMap(url); <ide> const launchAction = exampleAction || urlAction; <del> if (err || !storedString) { <del> const initialAction = launchAction || {type: 'InitialAction'}; <del> this.setState(RNTesterNavigationReducer(undefined, initialAction)); <del> return; <del> } <del> const storedState = JSON.parse(storedString); <del> if (launchAction) { <del> this.setState(RNTesterNavigationReducer(storedState, launchAction)); <del> return; <del> } <del> this.setState(storedState); <add> const initialAction = launchAction || {type: 'InitialAction'}; <add> this.setState(RNTesterNavigationReducer(undefined, initialAction)); <ide> }); <ide> }); <ide> <ide><path>RNTester/js/RNTesterExampleList.js <ide> const Text = require('Text'); <ide> const TextInput = require('TextInput'); <ide> const TouchableHighlight = require('TouchableHighlight'); <ide> const RNTesterActions = require('./RNTesterActions'); <del>const RNTesterStatePersister = require('./RNTesterStatePersister'); <ide> const View = require('View'); <ide> <ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found when <ide> * making Flow check .android.js files. */ <ide> import type {RNTesterExample} from './RNTesterList.ios'; <del>import type {PassProps} from './RNTesterStatePersister'; <ide> import type {TextStyleProp, ViewStyleProp} from 'StyleSheet'; <ide> <ide> type Props = { <ide> type Props = { <ide> ComponentExamples: Array<RNTesterExample>, <ide> APIExamples: Array<RNTesterExample>, <ide> }, <del> persister: PassProps<*>, <del> searchTextInputStyle: TextStyleProp, <ide> style?: ?ViewStyleProp, <ide> }; <ide> <ide> const renderSectionHeader = ({section}) => ( <ide> ); <ide> <ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> { <add> state = {filter: ''}; <add> <ide> render() { <del> const filterText = this.props.persister.state.filter; <add> const filterText = this.state.filter; <ide> let filterRegex = /.*/; <ide> <ide> try { <ide> class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> { <ide> autoCorrect={false} <ide> clearButtonMode="always" <ide> onChangeText={text => { <del> this.props.persister.setState(() => ({filter: text})); <add> this.setState(() => ({filter: text})); <ide> }} <ide> placeholder="Search..." <ide> underlineColorAndroid="transparent" <del> style={[styles.searchTextInput, this.props.searchTextInputStyle]} <add> style={styles.searchTextInput} <ide> testID="explorer_search" <del> value={this.props.persister.state.filter} <add> value={this.state.filter} <ide> /> <ide> </View> <ide> ); <ide> const ItemSeparator = ({highlighted}) => ( <ide> <View style={highlighted ? styles.separatorHighlighted : styles.separator} /> <ide> ); <ide> <del>/* $FlowFixMe(>=0.85.0 site=react_native_fb) This comment suppresses an error <del> * found when Flow v0.85 was deployed. To see the error, delete this comment <del> * and run Flow. */ <del>RNTesterExampleList = RNTesterStatePersister.createContainer( <del> RNTesterExampleList, <del> { <del> cacheKeySuffix: () => 'mainList', <del> getInitialState: () => ({filter: ''}), <del> }, <del>); <del> <ide> const styles = StyleSheet.create({ <ide> listContainer: { <ide> flex: 1,
4
Javascript
Javascript
serialize json data as buffer and decode on demand
b42d94e42fa14e119b6d92d02cea5396190f762e
<ide><path>lib/json/JsonData.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add> <add>"use strict"; <add> <add>const { register } = require("../util/serialization"); <add> <add>class JsonData { <add> constructor(data) { <add> this._buffer = undefined; <add> this._data = undefined; <add> if (Buffer.isBuffer(data)) { <add> this._buffer = data; <add> } else { <add> this._data = data; <add> } <add> } <add> <add> get() { <add> if (this._data === undefined && this._buffer !== undefined) { <add> this._data = JSON.parse(this._buffer.toString()); <add> } <add> return this._data; <add> } <add>} <add> <add>register(JsonData, "webpack/lib/json/JsonData", null, { <add> serialize(obj, { write }) { <add> if (obj._buffer === undefined && obj._data !== undefined) { <add> obj._buffer = Buffer.from(JSON.stringify(obj._data)); <add> } <add> write(obj._buffer); <add> }, <add> deserialize({ read }) { <add> return new JsonData(read()); <add> } <add>}); <add> <add>module.exports = JsonData; <ide><path>lib/json/JsonGenerator.js <ide> class JsonGenerator extends Generator { <ide> * @returns {number} estimate size of the module <ide> */ <ide> getSize(module, type) { <del> let data = module.buildInfo && module.buildInfo.jsonData; <add> let data = <add> module.buildInfo && <add> module.buildInfo.jsonData && <add> module.buildInfo.jsonData.get(); <ide> if (!data) return 0; <ide> return stringifySafe(data).length + 10; <ide> } <ide> class JsonGenerator extends Generator { <ide> concatenationScope <ide> } <ide> ) { <del> const data = module.buildInfo && module.buildInfo.jsonData; <add> const data = <add> module.buildInfo && <add> module.buildInfo.jsonData && <add> module.buildInfo.jsonData.get(); <ide> if (data === undefined) { <ide> return new RawSource( <ide> runtimeTemplate.missingModuleStatement({ <ide><path>lib/json/JsonParser.js <ide> const parseJson = require("json-parse-better-errors"); <ide> const Parser = require("../Parser"); <ide> const JsonExportsDependency = require("../dependencies/JsonExportsDependency"); <add>const JsonData = require("./JsonData"); <ide> <ide> /** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ <ide> /** @typedef {import("../Parser").ParserState} ParserState */ <ide> class JsonParser extends Parser { <ide> ? source <ide> : parseFn(source[0] === "\ufeff" ? source.slice(1) : source); <ide> <del> state.module.buildInfo.jsonData = data; <add> state.module.buildInfo.jsonData = new JsonData(data); <ide> state.module.buildInfo.strict = true; <ide> state.module.buildMeta.exportsType = "default"; <ide> state.module.buildMeta.defaultObject = <ide><path>lib/util/internalSerializables.js <ide> module.exports = { <ide> require("../dependencies/WebpackIsIncludedDependency"), <ide> "dependencies/WorkerDependency": () => <ide> require("../dependencies/WorkerDependency"), <add> "json/JsonData": () => require("../json/JsonData"), <ide> "optimize/ConcatenatedModule": () => <ide> require("../optimize/ConcatenatedModule"), <ide> DelegatedModule: () => require("../DelegatedModule"),
4
Text
Text
translate 10.5 to korean
8838a6d9f928e2d4b66b7673a6e01a9c0332bb16
<ide><path>docs/docs/10.5-clone-with-props.ko-KR.md <add>--- <add>id: clone-with-props-ko-KR <add>title: ReactElement 클론하기 <add>permalink: clone-with-props-ko-KR.html <add>prev: test-utils-ko-KR.html <add>next: update-ko-KR.html <add>--- <add> <add>드문 경우긴 하지만 엘리먼트에서 소유하지 않은 엘리먼트의 props를 변경하고 싶을 때가 있습니다. (`this.props.children`로 전달된 엘리먼트의 `className` 변경 같은 경우) 아니면 전달된 엘리먼트의 복사본을 여럿 만들고 싶을 수도 있습니다. 이는 `cloneWithProps()`로 할 수 있습니다. <add> <add>#### `ReactElement React.addons.cloneWithProps(ReactElement element, object? extraProps)` <add> <add>`element`를 얕은 복사하고 `extraProps`로 넘긴 props를 머지합니다. `className`과 `style` props는 지능적으로 머지됩니다. <add> <add>> 주의: <add>> <add>> `cloneWithProps`는 `key`를 클론된 엘리먼트에 전송하지 않습니다. 키를 보존하고 싶으시면, `extraProps` 객체에 넣으세요. <add>> <add>> ```js <add>> var clonedElement = cloneWithProps(originalElement, { key : originalElement.key }); <add>> ``` <add>> <add>> 비슷하게 `ref`도 유지되지 않습니다.
1
Python
Python
adapt coercion-tests to the new situation
7012ef71f68c1dbd4bd746042722752ded7221f0
<ide><path>numpy/core/tests/test_array_coercion.py <ide> class TestStringDiscovery: <ide> [object(), 1.2, 10**43, None, "string"], <ide> ids=["object", "1.2", "10**43", "None", "string"]) <ide> def test_basic_stringlength(self, obj): <del> if not isinstance(obj, (str, int)): <del> pytest.xfail( <del> "The Single object (first assert) uses a different branch " <del> "and thus gives a different result (either wrong or longer" <del> "string than normally discovered).") <del> <ide> length = len(str(obj)) <ide> expected = np.dtype(f"S{length}") <ide> <ide> def test_basic_stringlength(self, obj): <ide> arr = np.array(obj, dtype="O") <ide> assert np.array(arr, dtype="S").dtype == expected <ide> <del> @pytest.mark.xfail(reason="Only single array unpacking is supported") <ide> @pytest.mark.parametrize("obj", <ide> [object(), 1.2, 10**43, None, "string"], <ide> ids=["object", "1.2", "10**43", "None", "string"]) <ide> def test_nested_arrays_stringlength(self, obj): <ide> arr = np.array(obj, dtype="O") <ide> assert np.array([arr, arr], dtype="S").dtype == expected <ide> <del> @pytest.mark.xfail(reason="Only single array unpacking is supported") <ide> @pytest.mark.parametrize("arraylike", arraylikes()) <ide> def test_unpack_first_level(self, arraylike): <ide> # We unpack exactly one level of array likes <ide> def test_scalar(self, scalar): <ide> assert arr.shape == () <ide> assert arr.dtype == scalar.dtype <ide> <del> if type(scalar) is np.bytes_: <del> pytest.xfail("Nested bytes use len(str(scalar)) currently.") <del> <ide> arr = np.array([[scalar, scalar]]) <ide> assert arr.shape == (1, 2) <ide> assert arr.dtype == scalar.dtype <ide> <ide> # Additionally to string this test also runs into a corner case <ide> # with datetime promotion (the difference is the promotion order). <del> @pytest.mark.xfail(reason="Coercion to string is not symmetric") <ide> def test_scalar_promotion(self): <ide> for sc1, sc2 in product(scalar_instances(), scalar_instances()): <ide> sc1, sc2 = sc1.values[0], sc2.values[0] <ide> # test all combinations: <del> arr = np.array([sc1, sc2]) <add> try: <add> arr = np.array([sc1, sc2]) <add> except (TypeError, ValueError): <add> # The promotion between two times can fail <add> # XFAIL (ValueError): Some object casts are currently undefined <add> continue <ide> assert arr.shape == (2,) <ide> try: <ide> dt1, dt2 = sc1.dtype, sc2.dtype <ide> def test_scalar_coercion(self, scalar): <ide> <ide> @pytest.mark.xfail(IS_PYPY, reason="`int(np.complex128(3))` fails on PyPy") <ide> @pytest.mark.filterwarnings("ignore::numpy.ComplexWarning") <del> # After change, can enable times here, and below and it will work, <del> # Right now times are too complex, so map out some details below. <del> @pytest.mark.parametrize("cast_to", scalar_instances(times=False)) <add> @pytest.mark.parametrize("cast_to", scalar_instances()) <ide> def test_scalar_coercion_same_as_cast_and_assignment(self, cast_to): <ide> """ <ide> Test that in most cases: <ide> def test_scalar_coercion_same_as_cast_and_assignment(self, cast_to): <ide> """ <ide> dtype = cast_to.dtype # use to parametrize only the target dtype <ide> <del> # XFAIL: Some extended precision tests fail, because assigning to <del> # complex256 will use float(float128). Rational fails currently. <del> for scalar in scalar_instances( <del> times=False, extended_precision=False, user_dtype=False): <add> for scalar in scalar_instances(times=False): <ide> scalar = scalar.values[0] <ide> <ide> if dtype.type == np.void: <ide> def test_scalar_coercion_same_as_cast_and_assignment(self, cast_to): <ide> # this, but has different rules than the cast. <ide> with pytest.raises(TypeError): <ide> np.array(scalar).astype(dtype) <del> # XFAIL: np.array(scalar, dtype=dtype) <add> np.array(scalar, dtype=dtype) <ide> np.array([scalar], dtype=dtype) <ide> continue <ide> <ide> class TestTimeScalars: <ide> param(np.timedelta64(123, "s"), id="timedelta64[s]"), <ide> param(np.datetime64("NaT", "generic"), id="datetime64[generic](NaT)"), <ide> param(np.datetime64(1, "D"), id="datetime64[D]")],) <del> @pytest.mark.xfail( <del> reason="This uses int(scalar) or float(scalar) to assign, which " <del> "fails. However, casting currently does not fail.") <ide> def test_coercion_basic(self, dtype, scalar): <ide> arr = np.array(scalar, dtype=dtype) <ide> cast = np.array(scalar).astype(dtype) <ide> def test_coercion_timedelta_convert_to_number(self, dtype, scalar): <ide> <ide> @pytest.mark.parametrize(["val", "unit"], <ide> [param(123, "s", id="[s]"), param(123, "D", id="[D]")]) <del> @pytest.mark.parametrize("scalar_type", [np.datetime64, np.timedelta64]) <del> @pytest.mark.xfail(reason="Error not raised for assignment") <del> def test_coercion_assignment_times(self, scalar_type, val, unit): <del> scalar = scalar_type(val, unit) <add> def test_coercion_assignment_datetime(self, val, unit): <add> scalar = np.datetime64(val, unit) <ide> <del> # The error type is not ideal, fails because string is too short: <add> # The error type is not ideal, fails because string is too short, <add> # This should possibly be allowed as an unsafe cast: <ide> with pytest.raises(RuntimeError): <ide> np.array(scalar, dtype="S6") <ide> with pytest.raises(RuntimeError): <del> cast = np.array(scalar).astype("S6") <add> np.array(scalar).astype("S6") <ide> ass = np.ones((), dtype="S6") <ide> with pytest.raises(RuntimeError): <ide> ass[()] = scalar <ide> <add> @pytest.mark.parametrize(["val", "unit"], <add> [param(123, "s", id="[s]"), param(123, "D", id="[D]")]) <add> def test_coercion_assignment_timedelta(self, val, unit): <add> scalar = np.timedelta64(val, unit) <add> <add> # Unlike datetime64, timedelta allows the unsafe cast: <add> np.array(scalar, dtype="S6") <add> cast = np.array(scalar).astype("S6") <add> ass = np.ones((), dtype="S6") <add> ass[()] = scalar <add> expected = scalar.astype("S")[:6] <add> assert cast[()] == expected <add> assert ass[()] == expected <ide> <ide> class TestNested: <del> @pytest.mark.xfail(reason="No deprecation warning given.") <ide> def test_nested_simple(self): <ide> initial = [1.2] <ide> nested = initial <ide> def test_pathological_self_containing(self): <ide> arr = np.array([l, [None], l], dtype=object) <ide> assert arr.shape == (3, 1) <ide> <del> @pytest.mark.xfail( <del> reason="For arrays and memoryview, this used to not complain " <del> "and assign to a too small array instead. For other " <del> "array-likes the error is different because fewer (only " <del> "MAXDIM-1) dimensions are found, failing the last test.") <ide> @pytest.mark.parametrize("arraylike", arraylikes()) <ide> def test_nested_arraylikes(self, arraylike): <ide> # We try storing an array like into an array, but the array-like <ide> def test_nested_arraylikes(self, arraylike): <ide> # assigned to it (which does work for object or if `float(arraylike)` <ide> # works). <ide> initial = arraylike(np.ones((1, 1))) <del> #if not isinstance(initial, (np.ndarray, memoryview)): <del> # pytest.xfail( <del> # "When coercing to object, these cases currently discover " <del> # "fewer dimensions than ndarray failing the second part.") <ide> <ide> nested = initial <ide> for i in range(np.MAXDIMS - 1): <ide> def test_uneven_depth_ragged(self, arraylike): <ide> assert out[0] is arr <ide> assert type(out[1]) is list <ide> <del> if not isinstance(arr, (np.ndarray, memoryview)): <del> pytest.xfail( <del> "does not raise ValueError below, because it discovers " <del> "the dimension as (2,) and not (2, 2, 2)") <del> <ide> # Array is ragged in the third dimension: <ide> with pytest.raises(ValueError): <ide> # This is a broadcast error during assignment, because <ide> def __len__(self): <ide> <ide> obj.append(mylist([1, 2])) <ide> <del> with pytest.raises(ValueError): # changes to RuntimeError <add> with pytest.raises(RuntimeError): <ide> np.array(obj) <ide> <ide> # Note: We do not test a shrinking list. These do very evil things <ide> def __len__(self): <ide> <ide> obj.append([2, 3]) <ide> obj.append(mylist([1, 2])) <del> #with pytest.raises(RuntimeError): # Will error in the future <del> np.array(obj) <add> with pytest.raises(RuntimeError): <add> np.array(obj) <ide> <ide> def test_replace_0d_array(self): <ide> # List to coerce, `mylist` will mutate the first element <ide> def __getitem__(self): <ide> # Runs into a corner case in the new code, the `array(2)` is cached <ide> # so replacing it invalidates the cache. <ide> obj.append([np.array(2), baditem()]) <del> # with pytest.raises(RuntimeError): # Will error in the future <del> np.array(obj) <add> with pytest.raises(RuntimeError): <add> np.array(obj) <ide> <ide> <ide> class TestArrayLikes:
1
Python
Python
adapt percentile test to changed promotion
9a5c5e886a4222e769e2f251ec7705c565d0cc4f
<ide><path>numpy/lib/tests/test_function_base.py <ide> def test_linear_nan_1D(self, dtype): <ide> <ide> H_F_TYPE_CODES = [(int_type, np.float64) <ide> for int_type in np.typecodes["AllInteger"] <del> ] + [(np.float16, np.float64), <del> (np.float32, np.float64), <add> ] + [(np.float16, np.float16), <add> (np.float32, np.float32), <ide> (np.float64, np.float64), <ide> (np.longdouble, np.longdouble), <del> (np.complex64, np.complex128), <add> (np.complex64, np.complex64), <ide> (np.complex128, np.complex128), <ide> (np.clongdouble, np.clongdouble), <ide> (np.dtype("O"), np.float64)] <ide> def test_linear_interpolation(self, <ide> expected, <ide> input_dtype, <ide> expected_dtype): <add> expected_dtype = np.dtype(expected_dtype) <add> if np.get_promotion_state() == "legacy": <add> expected_dtype = np.promote_types(expected_dtype, np.float64) <add> <ide> arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype) <ide> actual = np.percentile(arr, 40.0, method=method) <ide> <del> np.testing.assert_almost_equal(actual, expected, 14) <add> np.testing.assert_almost_equal( <add> actual, expected_dtype.type(expected), 14) <ide> <ide> if method in ["inverted_cdf", "closest_observation"]: <ide> if input_dtype == "O":
1
Javascript
Javascript
improve assertion in test-require-dot
d520059460fa4d610eff3a99e2527dab3033d2dd
<ide><path>test/parallel/test-require-dot.js <ide> process.env.NODE_PATH = fixtures.path('module-require', 'relative'); <ide> m._initPaths(); <ide> <ide> const c = require('.'); <del> <del>assert.strictEqual(c.value, 42, 'require(".") should honor NODE_PATH'); <add>assert.strictEqual( <add> c.value, <add> 42, <add> `require(".") should honor NODE_PATH; expected 42, found ${c.value}` <add>);
1
Text
Text
indicate n-api out params that may be null
4cf5563147cd562335ec02c4a78f9397a30e6701
<ide><path>doc/api/n-api.md <ide> Returns `napi_ok` if the API succeeded. <ide> <ide> This API returns various properties of a typed array. <ide> <add>Any of the out parameters may be `NULL` if that property is unneeded. <add> <ide> *Warning*: Use caution while using this API since the underlying data buffer <ide> is managed by the VM. <ide> <ide> napi_status napi_get_dataview_info(napi_env env, <ide> <ide> Returns `napi_ok` if the API succeeded. <ide> <add>Any of the out parameters may be `NULL` if that property is unneeded. <add> <ide> This API returns various properties of a `DataView`. <ide> <ide> #### napi_get_date_value
1
Text
Text
incorporate feedback from @danmaz74 in #463
0986a9f1fe015c1f8653052c814840ecd4b61a2d
<ide><path>docs/introduction/Examples.md <ide> npm install <ide> npm start <ide> ``` <ide> <add>See it running at [http://localhost:3000/](http://localhost:3000/). <add> <ide> Run the [TodoMVC](https://github.com/gaearon/redux/tree/master/examples/todomvc) example: <ide> <ide> ``` <ide> npm install <ide> npm start <ide> ``` <ide> <add>It will also run at [http://localhost:3000/](http://localhost:3000/). <add> <ide> >##### Important Note <del>>For examples to work outside the Redux folder, remove these lines from their `webpack.config.js`: <add>>If you copy Redux examples outside their folders, remove these lines from their `webpack.config.js`: <ide> > <ide> >```js <ide> >alias: {
1
Text
Text
add astronet directory and a temporary readme.md
130e04e518911a31488970a4f1c8c0d047eb809e
<ide><path>research/astronet/README.md <add># Coming Soon! <add> <add>This directory will soon be populated with TensorFlow models and data <add>processing code for identifying exoplanets in astrophysical light curves. <add> <add>For full details, see the following paper: <add> <add>*Identifying Exoplanets With Deep Learning: A Five Planet Resonant Chain Around <add>Kepler-80 And An Eighth Planet Around Kepler-90* <add> <add>Christopher J Shallue and Andrew Vanderburg <add> <add>To appear in the Astronomical Journal <add> <add>Preprint available at https://www.cfa.harvard.edu/~avanderb/kepler90i.pdf <add> <add>Contact: Chris Shallue (@cshallue)
1
Ruby
Ruby
remove unused return values
7c1671667f23e98b301647a2ad0e2d29b7da01e9
<ide><path>Library/Homebrew/extend/pathname.rb <ide> class Pathname <ide> BOTTLE_EXTNAME_RX = /(\.[a-z_]+(32)?\.bottle\.(\d+\.)?tar\.gz)$/ <ide> <ide> def install *sources <del> results = [] <ide> sources.each do |src| <ide> case src <ide> when Array <ide> if src.empty? <ide> opoo "tried to install empty array to #{self}" <del> return [] <add> return <ide> end <del> src.each {|s| results << install_p(s) } <add> src.each {|s| install_p(s) } <ide> when Hash <ide> if src.empty? <ide> opoo "tried to install empty hash to #{self}" <del> return [] <add> return <ide> end <del> src.each {|s, new_basename| results << install_p(s, new_basename) } <add> src.each {|s, new_basename| install_p(s, new_basename) } <ide> else <del> results << install_p(src) <add> install_p(src) <ide> end <ide> end <del> return results <ide> end <ide> <ide> def install_p src, new_basename = nil <ide> if new_basename <ide> new_basename = File.basename(new_basename) # rationale: see Pathname.+ <ide> dst = self+new_basename <del> return_value = Pathname.new(dst) <ide> else <ide> dst = self <del> return_value = self+File.basename(src) <ide> end <ide> <ide> src = src.to_s <ide> def install_p src, new_basename = nil <ide> # this function when installing from the temporary build directory <ide> FileUtils.mv src, dst <ide> end <del> <del> return return_value <ide> end <ide> protected :install_p <ide> <ide> # Creates symlinks to sources in this folder. <ide> def install_symlink *sources <del> results = [] <ide> sources.each do |src| <ide> case src <ide> when Array <del> src.each {|s| results << install_symlink_p(s) } <add> src.each {|s| install_symlink_p(s) } <ide> when Hash <del> src.each {|s, new_basename| results << install_symlink_p(s, new_basename) } <add> src.each {|s, new_basename| install_symlink_p(s, new_basename) } <ide> else <del> results << install_symlink_p(src) <add> install_symlink_p(src) <ide> end <ide> end <del> return results <ide> end <ide> <ide> def install_symlink_p src, new_basename = nil <ide> def install_symlink_p src, new_basename = nil <ide> else <ide> dst = self+File.basename(new_basename) <ide> end <del> <del> src = src.to_s <del> dst = dst.to_s <del> <ide> mkpath <del> FileUtils.ln_s src, dst <del> <del> return dst <add> FileUtils.ln_s src.to_s, dst.to_s <ide> end <ide> protected :install_symlink_p <ide> <ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_install_missing_file <ide> end <ide> <ide> def test_install_removes_original <del> orig_file = @file <ide> touch @file <add> @dst.install(@file) <ide> <del> @file, _ = @dst.install(@file) <del> <del> assert_equal orig_file.basename, @file.basename <del> assert @file.exist? <del> assert !orig_file.exist? <add> assert (@dst/@file.basename).exist? <add> assert !@file.exist? <ide> end <ide> <ide> def setup_install_test <ide> def test_install_symlink <ide> end <ide> end <ide> <del> def test_install_returns_installed_paths <del> foo, bar = @src+'foo', @src+'bar' <del> touch [foo, bar] <del> dirs = @dst.install(foo, bar) <del> assert_equal [@dst+'foo', @dst+'bar'], dirs <del> end <del> <ide> def test_install_creates_intermediate_directories <ide> touch @file <ide> assert !@dir.directory?
2
Python
Python
fix list_records method in the dummy dns driver
ac43cb8d28cb5fbd07c14d5e3164bbeb88cb6937
<ide><path>libcloud/dns/drivers/dummy.py <ide> def list_zones(self): <ide> return [zone['zone'] for zone in list(self._zones.values())] <ide> <ide> def list_records(self, zone): <del> return self.get_zone(zone_id=zone.id).records <add> """ <add> >>> driver = DummyDNSDriver('key', 'secret') <add> >>> zone = driver.create_zone(domain='apache.org', type='master', <add> ... ttl=100) <add> >>> list(zone.list_records()) <add> [] <add> >>> record = driver.create_record(name='libcloud', zone=zone, <add> ... type=RecordType.A, data='127.0.0.1') <add> >>> list(zone.list_records()) #doctest: +ELLIPSIS <add> [<Record: zone=id-apache.org, name=libcloud, type=A...>] <add> """ <add> return self._zones[zone.id]['records'].values() <ide> <ide> def get_zone(self, zone_id): <ide> """
1
Java
Java
update some marbles of observable
96b8d585c137b13e083afb5aba77eb772e3f8513
<ide><path>src/main/java/io/reactivex/Observable.java <ide> public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLates <ide> * the source ObservableSources each time an item is received from any of the source ObservableSources, where this <ide> * aggregation is defined by a specified function. <ide> * <p> <add> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.png" alt=""> <add> * <p> <ide> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the <ide> * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a <ide> * {@code Function<Integer[], R>} passed to the method would trigger a {@code ClassCastException}. <ide> public static <T, R> Observable<R> combineLatestDelayError(ObservableSource<? ex <ide> * aggregation is defined by a specified function and delays any error from the sources until <ide> * all source ObservableSources terminate. <ide> * <p> <add> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.png" alt=""> <add> * <p> <ide> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the <ide> * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a <ide> * {@code Function<Integer[], R>} passed to the method would trigger a {@code ClassCastException}. <ide> public static <T> Observable<T> concatArrayDelayError(ObservableSource<? extends <ide> * source ObservableSources. The operator buffers the values emitted by these ObservableSources and then drains them <ide> * in order, each one after the previous one completes. <ide> * <p> <del> * <img width="640" height="290" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArray.png" alt=""> <add> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> <ide> public static <T> Observable<T> empty() { <ide> * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the <ide> * Observer subscribes to it. <ide> * <p> <del> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.png" alt=""> <add> * <img width="640" height="220" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.supplier.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public static <T> Observable<T> error(Callable<? extends Throwable> errorSupplie <ide> * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the <ide> * Observer subscribes to it. <ide> * <p> <del> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.png" alt=""> <add> * <img width="640" height="220" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.item.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public static <T> Observable<T> fromCallable(Callable<? extends T> supplier) { <ide> /** <ide> * Converts a {@link Future} into an ObservableSource. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt=""> <add> * <img width="640" height="284" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.noarg.png" alt=""> <ide> * <p> <ide> * You can convert any object that supports the {@link Future} interface into an ObservableSource that emits the <ide> * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} <ide> public static <T> Observable<T> fromFuture(Future<? extends T> future) { <ide> /** <ide> * Converts a {@link Future} into an ObservableSource, with a timeout on the Future. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt=""> <add> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.timeout.png" alt=""> <ide> * <p> <ide> * You can convert any object that supports the {@link Future} interface into an ObservableSource that emits the <ide> * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} <ide> public static <T> Observable<T> fromFuture(Future<? extends T> future, long time <ide> /** <ide> * Converts a {@link Future} into an ObservableSource, with a timeout on the Future. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt=""> <add> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.timeout.scheduler.png" alt=""> <ide> * <p> <ide> * You can convert any object that supports the {@link Future} interface into an ObservableSource that emits the <ide> * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} <ide> public static <T> Observable<T> fromFuture(Future<? extends T> future, long time <ide> /** <ide> * Converts a {@link Future}, operating on a specified {@link Scheduler}, into an ObservableSource. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.s.png" alt=""> <add> * <img width="640" height="294" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.scheduler.png" alt=""> <ide> * <p> <ide> * You can convert any object that supports the {@link Future} interface into an ObservableSource that emits the <ide> * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} <ide> public static <T> Observable<T> fromFuture(Future<? extends T> future, Scheduler <ide> /** <ide> * Converts an {@link Iterable} sequence into an ObservableSource that emits the items in the sequence. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.png" alt=""> <add> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromIterable.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code fromIterable} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public final Single<T> single(T defaultItem) { <ide> * if this Observable completes without emitting any items or emits more than one item a <ide> * {@link NoSuchElementException} or {@code IllegalArgumentException} will be signalled respectively. <ide> * <p> <del> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/single.2.png" alt=""> <add> * <img width="640" height="228" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/singleOrError.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code singleOrError} does not operate by default on a particular {@link Scheduler}.</dd>
1
Java
Java
create art*viewmanager classes
1052d29fac68ae3475a05a248d58fdb9e55af16f
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTGroupViewManager.java <add>// Copyright 2004-present Facebook. All Rights Reserved. <add> <add>package com.facebook.react.views.art; <add> <add>import com.facebook.react.module.annotations.ReactModule; <add> <add>/** <add> * ViewManager for shadowed ART group views. <add> */ <add>@ReactModule(name = ARTRenderableViewManager.CLASS_GROUP) <add>public class ARTGroupViewManager extends ARTRenderableViewManager { <add> <add> /* package */ ARTGroupViewManager() { <add> super(CLASS_GROUP); <add> } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTRenderableViewManager.java <ide> <ide> import android.view.View; <ide> <del>import com.facebook.react.uimanager.ReactStylesDiffMap; <ide> import com.facebook.react.uimanager.ReactShadowNode; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> import com.facebook.react.uimanager.ViewManager; <ide> public class ARTRenderableViewManager extends ViewManager<View, ReactShadowNode> <ide> private final String mClassName; <ide> <ide> public static ARTRenderableViewManager createARTGroupViewManager() { <del> return new ARTRenderableViewManager(CLASS_GROUP); <add> return new ARTGroupViewManager(); <ide> } <ide> <ide> public static ARTRenderableViewManager createARTShapeViewManager() { <del> return new ARTRenderableViewManager(CLASS_SHAPE); <add> return new ARTShapeViewManager(); <ide> } <ide> <ide> public static ARTRenderableViewManager createARTTextViewManager() { <del> return new ARTRenderableViewManager(CLASS_TEXT); <add> return new ARTTextViewManager(); <ide> } <ide> <del> private ARTRenderableViewManager(String className) { <add> /* package */ ARTRenderableViewManager(String className) { <ide> mClassName = className; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTShapeViewManager.java <add>// Copyright 2004-present Facebook. All Rights Reserved. <add> <add>package com.facebook.react.views.art; <add> <add>import com.facebook.react.module.annotations.ReactModule; <add> <add>/** <add> * ViewManager for shadowed ART shape views. <add> */ <add>@ReactModule(name = ARTRenderableViewManager.CLASS_SHAPE) <add>public class ARTShapeViewManager extends ARTRenderableViewManager { <add> <add> /* package */ ARTShapeViewManager() { <add> super(CLASS_SHAPE); <add> } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTTextViewManager.java <add>// Copyright 2004-present Facebook. All Rights Reserved. <add> <add>package com.facebook.react.views.art; <add> <add>import com.facebook.react.module.annotations.ReactModule; <add> <add>/** <add> * ViewManager for shadowed ART text views. <add> */ <add>@ReactModule(name = ARTRenderableViewManager.CLASS_TEXT) <add>public class ARTTextViewManager extends ARTRenderableViewManager { <add> <add> /* package */ ARTTextViewManager() { <add> super(CLASS_TEXT); <add> } <add>}
4
Text
Text
add more guidelines
9db1feb3da20348828bf16280a8eafa010a80522
<ide><path>docs/Maintainer-Guidelines.md <ide> definitely not a beginner’s guide. <ide> <ide> Maybe you were looking for the [Formula Cookbook](Formula-Cookbook.md)? <ide> <add>This document is a work in progress. If you wish to change or discuss any of the below: open a PR to suggest a change. <add> <ide> ## Quick checklist <ide> <ide> This is all that really matters: <ide> is a good opportunity to do it) provided the line itself has some kind <ide> of modification that is not whitespace in it. But be careful about <ide> making changes to inline patches—make sure they still apply. <ide> <add>### Adding formulae <add>Only one maintainer is necessary to approve and merge the addition of a new formula which passes CI. However, if the formula addition <add>is controversial the maintainer who adds it will be expected to fix issues that arise with it in future. <add> <add>### Removing formulae <add>Formulae that: <add> <add>- work on at least 2/3 of our supported macOS versions in the default Homebrew prefix <add>- do not require patches rejected by upstream to work <add>- do not have known security vulnerabilities/CVEs for the version we package <add>- are shown to be still installed by users in our analytics with a `BuildError` rate of <25% <add> <add> <add>should not be removed from Homebrew. The exception to this rule are [versioned formulae](Versions.md) for which there are higher standards of usage and a maximum number of versions for a given formula. <add> <add>### Closing issues/PRs <add>Maintainers (including the lead maintainer) should not close issues or pull requests opened by other maintainers unless they are stale (i.e. have seen no updates for 28 days) in which case they can be closed by any maintainer. If the close is undesirable: no big deal, they can be reopened when additional work will be done. <add> <add>Any maintainer can merge any PR passing CI that has been opened by any other maintainer. If you do not wish to have other maintainers merge your PRs: please use the `do not merge` label to indicate that until you're ready to merge it yourself. <add> <add>## Reverting PRs <add>Any maintainer can revert a PR created by another maintainer after a user submitted issue or CI failure that results. The maintainer who created the original PR should be given an hour to fix the issue themselves or decide to revert the PR themselves if they would rather. <add> <ide> ## Communication <ide> Maintainers have a variety of ways to communicate with each other: <ide> <ide> This makes it easier for other maintainers, contributors and users to follow alo <ide> <ide> All maintainers (and lead maintainer) communication through any medium is bound by [Homebrew's Code of Conduct](CODE_OF_CONDUCT.md#code-of-conduct). Abusive behaviour towards other maintainers, contributors or users will not be tolerated; the maintainer will be given a warning and if their behaviour continues they will be removed as a maintainer. <ide> <add>Healthy, friendly, technical disagreement between maintainers is actively encouraged and should occur in public on the issue tracker. Off-topic discussions on the issue tracker, [bike-shedding](https://en.wikipedia.org/wiki/Law_of_triviality) and personal attacks are forbidden. <add> <ide> ## Lead maintainer guidelines <ide> There should be one lead maintainer for Homebrew. Decisions are determined by a consensus of the maintainers. When a consensus is not reached, the lead maintainer has the final say in determining the outcome of any decision (though this power should be used sparingly). They should also be seen as the product manager for Homebrew itself and ensuring that changes made to the entire Homebrew ecosystem are consistent and providing an increasingly positive experience for Homebrew's users. <ide> <ide> In the same way that Homebrew maintainers are expected to be spending more of their time reviewing and merging contributions from non-maintainer contributors than making their own contributions, the lead maintainer should be spending most of their time reviewing work from and mentoring other maintainers. <ide> <ide> Individual Homebrew repositories should not have formal lead maintainers (although those who do the most work will have the loudest voices). <add> <add>Maintainers should feel free to pleasantly disagree with the work and decisions of the lead maintainer. Constructive criticism is actively solicited and will be iterated upon to make the project better. Technical criticism should occur on the issue tracker and interpersonal criticism should be handled privately in Slack. If work or decisions are insufficiently documented or explained any maintainer or contributor should feel free to ask for clarification. The lead maintainer may never justify a decision with e.g. "because I say so" or "it was I who did X" alone.
1
Python
Python
fix minor error in "squeeze" docstring
016b21186b87c68a0aa09cca939187f6f29d1900
<ide><path>numpy/core/fromnumeric.py <ide> def squeeze(a, axis=None): <ide> Returns <ide> ------- <ide> squeezed : ndarray <del> The input array, but with with all or a subset of the <add> The input array, but with all or a subset of the <ide> dimensions of length 1 removed. This is always `a` itself <ide> or a view into `a`. <ide>
1
Text
Text
improve diff of code snippet example (#163)
573635944d31d6ae28554f18eade8e5c0f8b449e
<ide><path>threejs/lessons/threejs-scenegraph.md <ide> Continuing that same pattern let's add a moon. <ide> <ide> const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <ide> const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>-earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit" <ide> -solarSystem.add(earthMesh); <ide> +earthOrbit.add(earthMesh); <ide> objects.push(earthMesh);
1
Javascript
Javascript
add flow test for
275486e5be968c37ca5ab057a41e88295b073795
<ide><path>type-definitions/tests/immutable-flow.js <ide> stringToNumberOrString = Map({'a': 1}).mergeDeepWith((previous, next, key) => 1, <ide> // $ExpectError - the array [1] is not a valid argument <ide> stringToNumber = Map({'a': 1}).mergeDeepWith((previous, next, key) => 1, [1]) <ide> <add>// KeyedSeq can merge into Map <add>var stringToStringSeq: KeyedSeq<string, string> = Seq({'b': 'B'}); <add>stringToNumberOrString = Map({'a': 1}).merge(stringToStringSeq); <add> <ide> // $ExpectError <ide> stringToNumber = Map({'a': 1}).setIn([], 0) <ide> // $ExpectError
1
Ruby
Ruby
prevent extra `spawn` to make `klass.all` faster
eeaf9cf61c3cd14929583878785c31dab79e2196
<ide><path>activerecord/lib/active_record/core.rb <ide> def relation <ide> relation = Relation.create(self, arel_table, predicate_builder) <ide> <ide> if finder_needs_type_condition? && !ignore_default_scope? <del> relation.where(type_condition).create_with(inheritance_column.to_s => sti_name) <add> relation.where!(type_condition) <add> relation.create_with!(inheritance_column.to_s => sti_name) <ide> else <ide> relation <ide> end <ide><path>activerecord/lib/active_record/scoping/default.rb <ide> def build_default_scope(base_rel = nil) <ide> # The user has defined their own default scope method, so call that <ide> evaluate_default_scope do <ide> if scope = default_scope <del> (base_rel ||= relation).merge(scope) <add> (base_rel ||= relation).merge!(scope) <ide> end <ide> end <ide> elsif default_scopes.any? <ide> base_rel ||= relation <ide> evaluate_default_scope do <ide> default_scopes.inject(base_rel) do |default_scope, scope| <ide> scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call) <del> default_scope.merge(base_rel.instance_exec(&scope)) <add> default_scope.merge!(base_rel.instance_exec(&scope)) <ide> end <ide> end <ide> end
2
Go
Go
fix golint errors in api
c8ce0856b752cecb2f2a2149b79e6e96a63f03dc
<ide><path>api/client/image/build.go <ide> func replaceDockerfileTarWrapper(ctx context.Context, inputTarStream io.ReadClos <ide> return <ide> } <ide> <del> var content io.Reader = tarReader <add> content := io.Reader(tarReader) <ide> if hdr.Name == dockerfileName { <ide> // This entry is the Dockerfile. Since the tar archive was <ide> // generated from a directory on the local filesystem, the <ide><path>api/server/router/build/build_routes.go <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL) <ide> } <ide> <del> var out io.Writer = output <add> out := io.Writer(output) <ide> if buildOptions.SuppressOutput { <ide> out = notVerboseBuffer <ide> }
2
Javascript
Javascript
improve deepequal set and map worst case
5203bb0b1695f5cc2ea68c0c2e87b857c2c713f3
<ide><path>lib/assert.js <ide> const errors = require('internal/errors'); <ide> <ide> const assert = module.exports = ok; <ide> <del>// At present only the three keys mentioned above are used and <del>// understood by the spec. Implementations or sub modules can pass <del>// other keys to the AssertionError's constructor - they will be <del>// ignored. <del> <ide> // All of the following functions must throw an AssertionError <ide> // when a corresponding condition is not met, with a message that <ide> // may be undefined if not provided. All assertion methods provide <ide> function areSimilarRegExps(a, b) { <ide> return a.source === b.source && a.flags === b.flags; <ide> } <ide> <del>// For small buffers it's faster to compare the buffer in a loop. <del>// The c++ barrier takes the advantage of the faster compare otherwise. <del>// 300 was the number after which compare became faster. <add>// For small buffers it's faster to compare the buffer in a loop. The c++ <add>// barrier including the Buffer.from operation takes the advantage of the faster <add>// compare otherwise. 300 was the number after which compare became faster. <ide> function areSimilarTypedArrays(a, b) { <ide> const len = a.byteLength; <ide> if (len !== b.byteLength) { <ide> function looseDeepEqual(actual, expected) { <ide> return false; <ide> } <ide> if (util.isDate(actual) && util.isDate(expected)) { <del> if (actual.getTime() !== expected.getTime()) { <del> return false; <del> } <del> return true; <add> return actual.getTime() === expected.getTime(); <ide> } <ide> if (util.isRegExp(actual) && util.isRegExp(expected)) { <del> if (!areSimilarRegExps(actual, expected)) { <del> return false; <del> } <del> return true; <add> return areSimilarRegExps(actual, expected); <ide> } <ide> const actualTag = objectToString(actual); <ide> const expectedTag = objectToString(expected); <ide> if (actualTag === expectedTag) { <del> if (!isFloatTypedArrayTag(actualTag) && !isObjectOrArrayTag(actualTag) && <add> if (!isObjectOrArrayTag(actualTag) && !isFloatTypedArrayTag(actualTag) && <ide> ArrayBuffer.isView(actual)) { <ide> return areSimilarTypedArrays(actual, expected); <ide> } <ide> function innerDeepEqual(actual, expected, strict, memos) { <ide> return areEq; <ide> } <ide> <del>function setHasSimilarElement(set, val1, usedEntries, strict, memo) { <del> if (set.has(val1)) { <del> if (usedEntries !== null) <del> usedEntries.add(val1); <del> return true; <del> } <del> <del> // In strict mode the only things which can match a primitive or a function <del> // will already be detected by set.has(val1). <del> if (strict && (typeof val1 !== 'object' || val1 === null)) <del> return false; <del> <del> // Otherwise go looking. <add>function setHasEqualElement(set, val1, strict, memo) { <add> // Go looking. <ide> for (const val2 of set) { <del> if (!usedEntries.has(val2) && innerDeepEqual(val1, val2, strict, memo)) { <del> usedEntries.add(val2); <add> if (innerDeepEqual(val1, val2, strict, memo)) { <add> // Remove the matching element to make sure we do not check that again. <add> set.delete(val2); <ide> return true; <ide> } <ide> } <ide> <ide> return false; <ide> } <ide> <add>// Note: we actually run this multiple times for each loose key! <add>// This is done to prevent slowing down the average case. <add>function setHasLoosePrim(a, b, val) { <add> const altValues = findLooseMatchingPrimitives(val); <add> if (altValues === undefined) <add> return false; <add> <add> var matches = 1; <add> for (var i = 0; i < altValues.length; i++) { <add> if (b.has(altValues[i])) { <add> matches--; <add> } <add> if (a.has(altValues[i])) { <add> matches++; <add> } <add> } <add> return matches === 0; <add>} <add> <ide> function setEquiv(a, b, strict, memo) { <ide> // This code currently returns false for this pair of sets: <ide> // assert.deepEqual(new Set(['1', 1]), new Set([1])) <ide> function setEquiv(a, b, strict, memo) { <ide> if (a.size !== b.size) <ide> return false; <ide> <del> // This is a set of the entries in b which have been consumed in our pairwise <del> // comparison. <del> // <add> // This is a lazily initiated Set of entries which have to be compared <add> // pairwise. <add> var set = null; <ide> // When the sets contain only value types (eg, lots of numbers), and we're in <del> // strict mode, we don't need to match off the entries in a pairwise way. In <del> // that case this initialization is done lazily to avoid the allocation & <del> // bookkeeping cost. Unfortunately, we can't get away with that in non-strict <del> // mode. <del> let usedEntries = strict === true ? null : new Set(); <del> <del> for (const val1 of a) { <del> if (usedEntries === null && typeof val1 === 'object') <del> usedEntries = new Set(); <del> <del> // If the value doesn't exist in the second set by reference, and its an <del> // object or an array we'll need to go hunting for something thats <del> // deep-equal to it. Note that this is O(n^2) complexity, and will get <del> // slower if large, very similar sets / maps are nested inside. <del> // Unfortunately there's no real way around this. <del> if (!setHasSimilarElement(b, val1, usedEntries, strict, memo)) <add> // strict mode or if all entries strictly match, we don't need to match the <add> // entries in a pairwise way. In that case this initialization is done lazily <add> // to avoid the allocation & bookkeeping cost. <add> for (const val of a) { <add> // Note: Checking for the objects first improves the performance for object <add> // heavy sets but it is a minor slow down for primitives. As they are fast <add> // to check this improves the worst case scenario instead. <add> if (typeof val === 'object' && val !== null) { <add> if (set === null) { <add> set = new Set(); <add> } <add> // If the specified value doesn't exist in the second set its an not null <add> // object (or non strict only: a not matching primitive) we'll need to go <add> // hunting for something thats deep-(strict-)equal to it. To make this <add> // O(n log n) complexity we have to copy these values in a new set first. <add> set.add(val); <add> } else if (!b.has(val) && (strict || !setHasLoosePrim(a, b, val))) { <ide> return false; <add> } <add> } <add> <add> if (set !== null) { <add> for (const val of b) { <add> // In non-strict-mode we have to check if a primitive value is already <add> // matching and only if it's not, go hunting for it. <add> if (typeof val === 'object' && val !== null) { <add> if (!setHasEqualElement(set, val, strict, memo)) <add> return false; <add> } else if (!a.has(val) && (strict || !setHasLoosePrim(b, a, val))) { <add> return false; <add> } <add> } <ide> } <ide> <ide> return true; <ide> } <ide> <del>function mapHasSimilarEntry(map, key1, item1, usedEntries, strict, memo) { <del> // To be able to handle cases like: <del> // Map([[1, 'a'], ['1', 'b']]) vs Map([['1', 'a'], [1, 'b']]) <del> // or: <del> // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) <del> // ... we need to consider *all* matching keys, not just the first we find. <add>function findLooseMatchingPrimitives(prim) { <add> var values, number; <add> switch (typeof prim) { <add> case 'number': <add> values = ['' + prim]; <add> if (prim === 1 || prim === 0) <add> values.push(Boolean(prim)); <add> return values; <add> case 'string': <add> number = +prim; <add> if ('' + number === prim) { <add> values = [number]; <add> if (number === 1 || number === 0) <add> values.push(Boolean(number)); <add> } <add> return values; <add> case 'undefined': <add> return [null]; <add> case 'object': // Only pass in null as object! <add> return [undefined]; <add> case 'boolean': <add> number = +prim; <add> return [number, '' + number]; <add> } <add>} <ide> <del> // This check is not strictly necessary. The loop performs this check, but <del> // doing it here improves performance of the common case when reference-equal <del> // keys exist (which includes all primitive-valued keys). <del> if (map.has(key1) && innerDeepEqual(item1, map.get(key1), strict, memo)) { <del> if (usedEntries !== null) <del> usedEntries.add(key1); <del> return true; <add>// This is a ugly but relatively fast way to determine if a loose equal entry <add>// actually has a correspondent matching entry. Otherwise checking for such <add>// values would be way more expensive (O(n^2)). <add>// Note: we actually run this multiple times for each loose key! <add>// This is done to prevent slowing down the average case. <add>function mapHasLoosePrim(a, b, key1, memo, item1, item2) { <add> const altKeys = findLooseMatchingPrimitives(key1); <add> if (altKeys === undefined) <add> return false; <add> <add> const setA = new Set(); <add> const setB = new Set(); <add> <add> var keyCount = 1; <add> <add> setA.add(item1); <add> if (b.has(key1)) { <add> keyCount--; <add> setB.add(item2); <ide> } <ide> <del> if (strict && (typeof key1 !== 'object' || key1 === null)) <add> for (var i = 0; i < altKeys.length; i++) { <add> const key2 = altKeys[i]; <add> if (a.has(key2)) { <add> keyCount++; <add> setA.add(a.get(key2)); <add> } <add> if (b.has(key2)) { <add> keyCount--; <add> setB.add(b.get(key2)); <add> } <add> } <add> if (keyCount !== 0 || setA.size !== setB.size) <ide> return false; <ide> <del> for (const [key2, item2] of map) { <del> // The first part is checked above. <del> if (key2 === key1 || usedEntries.has(key2)) <del> continue; <add> for (const val of setA) { <add> if (!setHasEqualElement(setB, val, false, memo)) <add> return false; <add> } <add> <add> return true; <add>} <ide> <add>function mapHasEqualEntry(set, map, key1, item1, strict, memo) { <add> // To be able to handle cases like: <add> // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) <add> // ... we need to consider *all* matching keys, not just the first we find. <add> for (const key2 of set) { <ide> if (innerDeepEqual(key1, key2, strict, memo) && <del> innerDeepEqual(item1, item2, strict, memo)) { <del> usedEntries.add(key2); <add> innerDeepEqual(item1, map.get(key2), strict, memo)) { <add> set.delete(key2); <ide> return true; <ide> } <ide> } <ide> function mapHasSimilarEntry(map, key1, item1, usedEntries, strict, memo) { <ide> function mapEquiv(a, b, strict, memo) { <ide> // Caveat: In non-strict mode, this implementation does not handle cases <ide> // where maps contain two equivalent-but-not-reference-equal keys. <del> // <del> // For example, maps like this are currently considered not equivalent: <ide> if (a.size !== b.size) <ide> return false; <ide> <del> let usedEntries = strict === true ? null : new Set(); <del> <del> for (const [key, item] of a) { <del> if (usedEntries === null && typeof key === 'object') <del> usedEntries = new Set(); <del> <del> // Just like setEquiv above, this hunt makes this function O(n^2) when <del> // using objects and lists as keys <del> if (!mapHasSimilarEntry(b, key, item, usedEntries, strict, memo)) <add> var set = null; <add> <add> for (const [key, item1] of a) { <add> // By directly retrieving the value we prevent another b.has(key) check in <add> // almost all possible cases. <add> const item2 = b.get(key); <add> if (item2 === undefined) { <add> // Just like setEquiv above but in addition we have to make sure the <add> // values are also equal. <add> if (typeof key === 'object' && key !== null) { <add> if (set === null) { <add> set = new Set(); <add> } <add> set.add(key); <add> // Note: we do not have to pass memo in this case as at least one item <add> // is undefined. <add> } else if ((!innerDeepEqual(item1, item2, strict) || !b.has(key)) && <add> (strict || !mapHasLoosePrim(a, b, key, memo, item1))) { <add> return false; <add> } <add> } else if (!innerDeepEqual(item1, item2, strict, memo) && <add> (strict || !mapHasLoosePrim(a, b, key, memo, item1, item2))) { <ide> return false; <add> } <add> } <add> <add> if (set !== null) { <add> for (const [key, item] of b) { <add> if (typeof key === 'object' && key !== null) { <add> if (!mapHasEqualEntry(set, a, key, item, strict, memo)) <add> return false; <add> } else if (!a.has(key) && <add> (strict || !mapHasLoosePrim(b, a, key, memo, item))) { <add> return false; <add> } <add> } <ide> } <ide> <ide> return true; <ide> function objEquiv(a, b, strict, keys, memos) { <ide> if (isSet(a)) { <ide> if (!isSet(b) || !setEquiv(a, b, strict, memos)) <ide> return false; <del> } else if (isSet(b)) { <del> return false; <ide> } else if (isMap(a)) { <ide> if (!isMap(b) || !mapEquiv(a, b, strict, memos)) <ide> return false; <del> } else if (isMap(b)) { <add> } else if (isSet(b) || isMap(b)) { <ide> return false; <ide> } <ide> <ide><path>test/parallel/test-assert-deep.js <ide> assertDeepAndStrictEqual( <ide> assertDeepAndStrictEqual(new Map([[1, 1], [2, 2]]), new Map([[1, 1], [2, 2]])); <ide> assertDeepAndStrictEqual(new Map([[1, 1], [2, 2]]), new Map([[2, 2], [1, 1]])); <ide> assertNotDeepOrStrict(new Map([[1, 1], [2, 2]]), new Map([[1, 2], [2, 1]])); <add>assertNotDeepOrStrict( <add> new Map([[[1], 1], [{}, 2]]), <add> new Map([[[1], 2], [{}, 1]]) <add>); <ide> <ide> assertNotDeepOrStrict(new Set([1]), [1]); <ide> assertNotDeepOrStrict(new Set(), []); <ide> assertOnlyDeepEqual(new Set(['1']), new Set([1])); <ide> <ide> assertOnlyDeepEqual(new Map([['1', 'a']]), new Map([[1, 'a']])); <ide> assertOnlyDeepEqual(new Map([['a', '1']]), new Map([['a', 1]])); <add>assertNotDeepOrStrict(new Map([['a', '1']]), new Map([['a', 2]])); <ide> <ide> assertDeepAndStrictEqual(new Set([{}]), new Set([{}])); <ide> <ide> assertNotDeepOrStrict( <ide> new Set([{a: 1}, {a: 2}, {a: 2}]) <ide> ); <ide> <add>// Mixed primitive and object keys <add>assertDeepAndStrictEqual( <add> new Map([[1, 'a'], [{}, 'a']]), <add> new Map([[1, 'a'], [{}, 'a']]) <add>); <add>assertDeepAndStrictEqual( <add> new Set([1, 'a', [{}, 'a']]), <add> new Set([1, 'a', [{}, 'a']]) <add>); <add> <ide> // This is an awful case, where a map contains multiple equivalent keys: <ide> assertOnlyDeepEqual( <ide> new Map([[1, 'a'], ['1', 'b']]), <del> new Map([['1', 'a'], [1, 'b']]) <add> new Map([['1', 'a'], [true, 'b']]) <add>); <add>assertNotDeepOrStrict( <add> new Set(['a']), <add> new Set(['b']) <ide> ); <ide> assertDeepAndStrictEqual( <ide> new Map([[{}, 'a'], [{}, 'b']]), <ide> new Map([[{}, 'b'], [{}, 'a']]) <ide> ); <add>assertOnlyDeepEqual( <add> new Map([[true, 'a'], ['1', 'b'], [1, 'a']]), <add> new Map([['1', 'a'], [1, 'b'], [true, 'a']]) <add>); <add>assertNotDeepOrStrict( <add> new Map([[true, 'a'], ['1', 'b'], [1, 'c']]), <add> new Map([['1', 'a'], [1, 'b'], [true, 'a']]) <add>); <add> <add>// Similar object keys <add>assertNotDeepOrStrict( <add> new Set([{}, {}]), <add> new Set([{}, 1]) <add>); <add>assertNotDeepOrStrict( <add> new Set([[{}, 1], [{}, 1]]), <add> new Set([[{}, 1], [1, 1]]) <add>); <add>assertNotDeepOrStrict( <add> new Map([[{}, 1], [{}, 1]]), <add> new Map([[{}, 1], [1, 1]]) <add>); <add>assertOnlyDeepEqual( <add> new Map([[{}, 1], [true, 1]]), <add> new Map([[{}, 1], [1, 1]]) <add>); <add> <add>// Similar primitive key / values <add>assertNotDeepOrStrict( <add> new Set([1, true, false]), <add> new Set(['1', 0, '0']) <add>); <add>assertNotDeepOrStrict( <add> new Map([[1, 5], [true, 5], [false, 5]]), <add> new Map([['1', 5], [0, 5], ['0', 5]]) <add>); <add> <add>// undefined value in Map <add>assertDeepAndStrictEqual( <add> new Map([[1, undefined]]), <add> new Map([[1, undefined]]) <add>); <add>assertOnlyDeepEqual( <add> new Map([[1, null]]), <add> new Map([['1', undefined]]) <add>); <add>assertNotDeepOrStrict( <add> new Map([[1, undefined]]), <add> new Map([[2, undefined]]) <add>); <add> <add>// null as key <add>assertDeepAndStrictEqual( <add> new Map([[null, 3]]), <add> new Map([[null, 3]]) <add>); <add>assertOnlyDeepEqual( <add> new Map([[null, undefined]]), <add> new Map([[undefined, null]]) <add>); <add>assertOnlyDeepEqual( <add> new Set([null]), <add> new Set([undefined]) <add>); <ide> <ide> { <ide> const values = [
2
Python
Python
call on_train_end when trial is pruned
483a9450a040a910ad26fd8cdcbc2f8e773cb161
<ide><path>src/transformers/trainer.py <ide> def _report_to_hp_search( <ide> <ide> trial.report(self.objective, epoch) <ide> if trial.should_prune(): <add> self.callback_handler.on_train_end(self.args, self.state, self.control) <ide> raise optuna.TrialPruned() <ide> elif self.hp_search_backend == HPSearchBackend.RAY: <ide> from ray import tune
1
Text
Text
add dereknongeneric to collaborators
0be93eeb335d48636a4e338ef7a501cdb3beabd4
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Danielle Adams** &lt;adamzdanielle@gmail.com&gt; (she/her) <ide> * [davisjam](https://github.com/davisjam) - <ide> **Jamie Davis** &lt;davisjam@vt.edu&gt; (he/him) <add>* [DerekNonGeneric](https://github.com/DerekNonGeneric) - <add>**Derek Lewis** &lt;DerekNonGeneric@inf.is&gt; (he/him) <ide> * [devnexen](https://github.com/devnexen) - <ide> **David Carlier** &lt;devnexen@gmail.com&gt; <ide> * [devsnek](https://github.com/devsnek) -
1
Mixed
Javascript
add support for default datetime formats in en
3af1e7ca2ee8c2acd69e5bcbb3ffc1bf51239285
<ide><path>CHANGELOG.md <ide> <a name="0.9.18"><a/> <ide> # <angular/> 0.9.18 jiggling-armfat (in-progress) # <del> <add>### Breaking changes <add>- no longer support MMMMM in filter.date as we need to follow UNICODE LOCALE DATA formats. <ide> <ide> <ide> <ide><path>src/filters.js <ide> function dateStrGetter(name, shortForm) { <ide> }; <ide> } <ide> <add>function timeZoneGetter(numFormat) { <add> return function(date) { <add> var timeZone; <add> if (numFormat || !(timeZone = GET_TIME_ZONE.exec(date.toString()))) { <add> var offset = date.getTimezoneOffset(); <add> return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); <add> } <add> return timeZone[0]; <add> }; <add>} <add> <ide> var DAY = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','); <ide> <ide> var MONTH = 'January,February,March,April,May,June,July,August,September,October,November,December'. <ide> var MONTH = 'January,February,March,April,May,June,July,August,September,October <ide> var DATE_FORMATS = { <ide> yyyy: dateGetter('FullYear', 4), <ide> yy: dateGetter('FullYear', 2, 0, true), <del> MMMMM: dateStrGetter('Month'), <add> y: dateGetter('FullYear', 1), <add> MMMM: dateStrGetter('Month'), <ide> MMM: dateStrGetter('Month', true), <ide> MM: dateGetter('Month', 2, 1), <ide> M: dateGetter('Month', 1, 1), <ide> var DATE_FORMATS = { <ide> EEEE: dateStrGetter('Day'), <ide> EEE: dateStrGetter('Day', true), <ide> a: function(date){return date.getHours() < 12 ? 'am' : 'pm';}, <del> Z: function(date){ <del> var offset = date.getTimezoneOffset(); <del> return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); <del> } <add> z: timeZoneGetter(false), <add> Z: timeZoneGetter(true) <ide> }; <ide> <add>var DEFAULT_DATETIME_FORMATS = { <add> long: 'MMMM d, y h:mm:ss a z', <add> medium: 'MMM d, y h:mm:ss a', <add> short: 'M/d/yy h:mm a', <add> fullDate: 'EEEE, MMMM d, y', <add> longDate: 'MMMM d, y', <add> mediumDate: 'MMM d, y', <add> shortDate: 'M/d/yy', <add> longTime: 'h:mm:ss a z', <add> mediumTime: 'h:mm:ss a', <add> shortTime: 'h:mm a' <add>}; <ide> <del>var DATE_FORMATS_SPLIT = /([^yMdHhmsaZE]*)(E+|y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/; <add>var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/; <add>var DATE_FORMATS_SPLIT = /([^yMdHhmsazZE]*)(E+|y+|M+|d+|H+|h+|m+|s+|a|Z|z)(.*)/; <add>var OPERA_TOSTRING_PATTERN = /^[\d].*Z$/; <ide> var NUMBER_STRING = /^\d+$/; <ide> <ide> <ide> var NUMBER_STRING = /^\d+$/; <ide> * <ide> * `format` string can be composed of the following elements: <ide> * <del> * * `'yyyy'`: 4 digit representation of year e.g. 2010 <del> * * `'yy'`: 2 digit representation of year, padded (00-99) <del> * * `'MMMMM'`: Month in year (January‒December) <add> * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) <add> * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) <add> * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) <add> * * `'MMMM'`: Month in year (January‒December) <ide> * * `'MMM'`: Month in year (Jan - Dec) <ide> * * `'MM'`: Month in year, padded (01‒12) <ide> * * `'M'`: Month in year (1‒12) <ide> var NUMBER_STRING = /^\d+$/; <ide> * * `'s'`: Second in minute (0‒59) <ide> * * `'a'`: am/pm marker <ide> * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200‒1200) <add> * * `'z'`: short form of current timezone name (e.g. PDT) <add> * <add> * `format` string can also be the following default formats for `en_US` locale (support for other <add> * locales will be added in the future versions): <add> * <add> * * `'long'`: equivalent to `'MMMM d, y h:mm:ss a z'` for en_US locale <add> * (e.g. September 3, 2010 12:05:08 pm PDT) <add> * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale <add> * (e.g. Sep 3, 2010 12:05:08 pm) <add> * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) <add> * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale <add> * (e.g. Friday, September 3, 2010) <add> * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 <add> * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) <add> * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) <add> * * `'longTime'`: equivalent to `'h:mm:ss a z'` for en_US locale (e.g. 12:05:08 pm PDT) <add> * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) <add> * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) <ide> * <ide> * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or <ide> * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). <del> * @param {string=} format Formatting rules. If not specified, Date#toLocaleDateString is used. <add> * @param {string=} format Formatting rules (see Description). If not specified, <add> * Date#toLocaleDateString is used. <ide> * @returns {string} Formatted string or the input if input is not recognized as date/millis. <ide> * <ide> * @example <ide> <doc:example> <ide> <doc:source> <add> <span ng:non-bindable>{{1288323623006 | date:'medium'}}</span>: <add> {{1288323623006 | date:'medium'}}<br/> <ide> <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: <ide> {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <ide> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: <ide> {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> <ide> </doc:source> <ide> <doc:scenario> <ide> it('should format date', function(){ <add> expect(binding("1288323623006 | date:'medium'")). <add> toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} pm/); <ide> expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). <ide> toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); <ide> expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). <ide> var NUMBER_STRING = /^\d+$/; <ide> </doc:example> <ide> */ <ide> angularFilter.date = function(date, format) { <add> format = DEFAULT_DATETIME_FORMATS[format] || format; <ide> if (isString(date)) { <ide> if (NUMBER_STRING.test(date)) { <ide> date = parseInt(date, 10); <ide><path>test/FiltersSpec.js <ide> describe('filter', function() { <ide> }); <ide> <ide> it('should handle mailto:', function() { <del> expect(linky("mailto:me@example.com").html).toEqual('<a href="mailto:me@example.com">me@example.com</a>'); <del> expect(linky("me@example.com").html).toEqual('<a href="mailto:me@example.com">me@example.com</a>'); <add> expect(linky("mailto:me@example.com").html). <add> toEqual('<a href="mailto:me@example.com">me@example.com</a>'); <add> expect(linky("me@example.com").html). <add> toEqual('<a href="mailto:me@example.com">me@example.com</a>'); <ide> expect(linky("send email to me@example.com, but").html). <ide> toEqual('send email to <a href="mailto:me@example.com">me@example.com</a>, but'); <ide> }); <ide> describe('filter', function() { <ide> var morning = new TzDate(+5, '2010-09-03T12:05:08.000Z'); //7am <ide> var noon = new TzDate(+5, '2010-09-03T17:05:08.000Z'); //12pm <ide> var midnight = new TzDate(+5, '2010-09-03T05:05:08.000Z'); //12am <add> var earlyDate = new TzDate(+5, '0001-09-03T05:05:08.000Z'); <add> var timZoneDate = new TzDate(+5, '2010-09-03T05:05:08.000Z', <add> 'Mon Sep 3 2010 00:05:08 GMT+0500 (XYZ)'); //12am <ide> <ide> it('should ignore falsy inputs', function() { <ide> expect(filter.date(null)).toBeNull(); <ide> describe('filter', function() { <ide> <ide> it('should accept various format strings', function() { <ide> expect(filter.date(morning, "yy-MM-dd HH:mm:ss")). <del> toEqual('10-09-03 07:05:08'); <add> toEqual('10-09-03 07:05:08'); <ide> <ide> expect(filter.date(midnight, "yyyy-M-d h=H:m:saZ")). <del> toEqual('2010-9-3 12=0:5:8am0500'); <add> toEqual('2010-9-3 12=0:5:8am0500'); <ide> <ide> expect(filter.date(midnight, "yyyy-MM-dd hh=HH:mm:ssaZ")). <del> toEqual('2010-09-03 12=00:05:08am0500'); <add> toEqual('2010-09-03 12=00:05:08am0500'); <ide> <ide> expect(filter.date(noon, "yyyy-MM-dd hh=HH:mm:ssaZ")). <del> toEqual('2010-09-03 12=12:05:08pm0500'); <add> toEqual('2010-09-03 12=12:05:08pm0500'); <add> <add> expect(filter.date(timZoneDate, "yyyy-MM-dd hh=HH:mm:ss a z")). <add> toEqual('2010-09-03 12=00:05:08 am XYZ'); <ide> <ide> expect(filter.date(noon, "EEE, MMM d, yyyy")). <del> toEqual('Fri, Sep 3, 2010'); <add> toEqual('Fri, Sep 3, 2010'); <add> <add> expect(filter.date(noon, "EEEE, MMMM dd, yyyy")). <add> toEqual('Friday, September 03, 2010'); <add> <add> expect(filter.date(earlyDate, "MMMM dd, y")). <add> toEqual('September 03, 1'); <add> }); <add> <add> it('should accept default formats', function() { <add> <add> expect(filter.date(timZoneDate, "long")). <add> toEqual('September 3, 2010 12:05:08 am XYZ'); <add> <add> expect(filter.date(noon, "medium")). <add> toEqual('Sep 3, 2010 12:05:08 pm'); <add> <add> expect(filter.date(noon, "short")). <add> toEqual('9/3/10 12:05 pm'); <add> <add> expect(filter.date(noon, "fullDate")). <add> toEqual('Friday, September 3, 2010'); <add> <add> expect(filter.date(noon, "longDate")). <add> toEqual('September 3, 2010'); <ide> <del> expect(filter.date(noon, "EEEE, MMMMM dd, yyyy")). <del> toEqual('Friday, September 03, 2010'); <add> expect(filter.date(noon, "mediumDate")). <add> toEqual('Sep 3, 2010'); <add> <add> expect(filter.date(noon, "shortDate")). <add> toEqual('9/3/10'); <add> <add> expect(filter.date(timZoneDate, "longTime")). <add> toEqual('12:05:08 am XYZ'); <add> <add> expect(filter.date(noon, "mediumTime")). <add> toEqual('12:05:08 pm'); <add> <add> expect(filter.date(noon, "shortTime")). <add> toEqual('12:05 pm'); <add> }); <add> <add> <add> it('should parse timezone identifier from various toString values', function() { <add> //chrome and firefox format <add> expect(filter.date(new TzDate(+5, '2010-09-03T17:05:08.000Z', <add> 'Mon Sep 3 2010 17:05:08 GMT+0500 (XYZ)'), "z")).toBe('XYZ'); <add> <add> //opera format <add> expect(filter.date(new TzDate(+5, '2010-09-03T17:05:08.000Z', <add> '2010-09-03T17:05:08Z'), "z")).toBe('0500'); <add> <add> //ie 8 format <add> expect(filter.date(new TzDate(+5, '2010-09-03T17:05:08.000Z', <add> 'Mon Sep 3 17:05:08 XYZ 2010'), "z")).toBe('XYZ'); <ide> }); <ide> <add> <ide> it('should be able to parse ISO 8601 dates/times using', function() { <ide> var isoString = '2010-09-03T05:05:08.872Z'; <ide> expect(filter.date(isoString)). <ide><path>test/angular-mocksSpec.js <ide> describe('mocks', function(){ <ide> <ide> <ide> it('should throw error when no third param but toString called', function() { <del> var t = new TzDate(0, 0); <del> try { <del> t.toString(); <del> } catch(err) { <del> expect(err.name).toBe('MethodNotImplemented'); <del> } <del> }) <add> expect(function() { new TzDate(0,0).toString() }). <add> toThrow('Method \'toString\' is not implemented in the TzDate mock'); <add> }); <ide> }); <ide> <ide> describe('$log mock', function() {
4