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
Javascript
Javascript
fix race in simple/test-cluster-master-error
d8c4ecea0b03a4524eda172dfd7f08992c1538c8
<ide><path>test/simple/test-cluster-master-error.js <ide> if (cluster.isWorker) { <ide> // Check that the cluster died accidently <ide> existMaster = (code === 1); <ide> <del> // When master is dead all workers should be dead to <del> var alive = false; <del> workers.forEach(function(pid) { <del> if (isAlive(pid)) { <del> alive = true; <del> } <del> }); <add> // Give the workers time to shut down <add> setTimeout(checkWorkers, 200); <add> <add> function checkWorkers() { <add> // When master is dead all workers should be dead to <add> var alive = false; <add> workers.forEach(function(pid) { <add> if (isAlive(pid)) { <add> alive = true; <add> } <add> }); <ide> <del> // If a worker was alive this did not act as expected <del> existWorker = !alive; <add> // If a worker was alive this did not act as expected <add> existWorker = !alive; <add> } <ide> }); <ide> <ide> process.once('exit', function() {
1
Python
Python
fix autoscale when prefetch_multiplier is 1
163d09f20a72550fb86e1787978291278e90b58a
<ide><path>celery/worker/autoscale.py <ide> def update(self, max=None, min=None): <ide> if max is not None: <ide> if max < self.processes: <ide> self._shrink(self.processes - max) <add> self._update_consumer_prefetch_count(max) <ide> self.max_concurrency = max <ide> if min is not None: <ide> if min > self.processes: <ide> def force_scale_up(self, n): <ide> with self.mutex: <ide> new = self.processes + n <ide> if new > self.max_concurrency: <add> self._update_consumer_prefetch_count(new) <ide> self.max_concurrency = new <ide> self._grow(n) <ide> <ide> def scale_down(self, n): <ide> def _grow(self, n): <ide> info('Scaling up %s processes.', n) <ide> self.pool.grow(n) <del> self.worker.consumer._update_prefetch_count(n) <ide> <ide> def _shrink(self, n): <ide> info('Scaling down %s processes.', n) <ide> def _shrink(self, n): <ide> debug("Autoscaler won't scale down: all processes busy.") <ide> except Exception as exc: <ide> error('Autoscaler: scale_down: %r', exc, exc_info=True) <del> self.worker.consumer._update_prefetch_count(-n) <add> <add> def _update_consumer_prefetch_count(self, new_max): <add> diff = new_max - self.max_concurrency <add> if diff: <add> self.worker.consumer._update_prefetch_count( <add> diff * self.worker.consumer.prefetch_multiplier <add> ) <ide> <ide> def info(self): <ide> return { <ide><path>celery/worker/components.py <ide> class Consumer(bootsteps.StartStopStep): <ide> <ide> def create(self, w): <ide> if w.max_concurrency: <del> prefetch_count = max(w.min_concurrency, 1) * w.prefetch_multiplier <add> prefetch_count = max(w.max_concurrency, 1) * w.prefetch_multiplier <ide> else: <ide> prefetch_count = w.concurrency * w.prefetch_multiplier <ide> c = w.consumer = self.instantiate( <ide><path>t/unit/worker/test_autoscale.py <ide> def test_body(self): <ide> x.body() <ide> x.body() <ide> assert x.pool.num_processes == 10 <del> worker.consumer._update_prefetch_count.assert_called() <ide> state.reserved_requests.clear() <ide> x.body() <ide> assert x.pool.num_processes == 10 <ide> x._last_scale_up = monotonic() - 10000 <ide> x.body() <ide> assert x.pool.num_processes == 3 <del> worker.consumer._update_prefetch_count.assert_called() <ide> <ide> def test_run(self): <ide> <ide> def test_shrink_raises_ValueError(self, debug): <ide> def test_update_and_force(self): <ide> worker = Mock(name='worker') <ide> x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker) <add> x.worker.consumer.prefetch_multiplier = 1 <ide> assert x.processes == 3 <ide> x.force_scale_up(5) <ide> assert x.processes == 8 <ide> def test_update_and_force(self): <ide> x.update(max=300, min=2) <ide> x.update(max=None, min=None) <ide> <add> def test_prefetch_count_on_updates(self): <add> worker = Mock(name='worker') <add> x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker) <add> x.worker.consumer.prefetch_multiplier = 1 <add> x.update(5, None) <add> worker.consumer._update_prefetch_count.assert_called_with(-5) <add> x.update(15, 7) <add> worker.consumer._update_prefetch_count.assert_called_with(10) <add> <add> def test_prefetch_count_on_force_up(self): <add> worker = Mock(name='worker') <add> x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker) <add> x.worker.consumer.prefetch_multiplier = 1 <add> <add> x.force_scale_up(5) <add> worker.consumer._update_prefetch_count.assert_not_called() <add> x.force_scale_up(5) <add> worker.consumer._update_prefetch_count.assert_called_with(3) <add> <ide> def test_info(self): <ide> worker = Mock(name='worker') <ide> x = autoscale.Autoscaler(self.pool, 10, 3, worker=worker)
3
Javascript
Javascript
fix normalnode context
5dc078a9d60be4811a36d1408f5d8cab3737e383
<ide><path>examples/jsm/nodes/accessors/NormalNode.js <ide> NormalNode.prototype.getShared = function () { <ide> <ide> }; <ide> <add>NormalNode.prototype.build = function ( builder, output, uuid, ns ) { <add> <add> var contextNormal = builder.context[ this.scope + 'Normal' ]; <add> <add> if ( contextNormal ) { <add> <add> return contextNormal.build( builder, output, uuid, ns ); <add> <add> } <add> <add> return TempNode.prototype.build.call( this, builder, output, uuid ); <add> <add>} <add> <ide> NormalNode.prototype.generate = function ( builder, output ) { <ide> <ide> var result; <ide><path>examples/jsm/nodes/accessors/ReflectNode.js <ide> ReflectNode.prototype.generate = function ( builder, output ) { <ide> <ide> case ReflectNode.VECTOR: <ide> <del> var viewNormalNode = builder.context.viewNormal || new NormalNode( NormalNode.VIEW ); <add> var viewNormalNode = new NormalNode( NormalNode.VIEW ); <ide> var roughnessNode = builder.context.roughness; <ide> <ide> var viewNormal = viewNormalNode.build( builder, 'v3' ); <ide><path>examples/jsm/nodes/materials/nodes/StandardNode.js <ide> StandardNode.prototype.build = function ( builder ) { <ide> roughness: specularRoughness, <ide> bias: new SpecularMIPLevelNode( specularRoughness ), <ide> viewNormal: new ExpressionNode( 'normal', 'v3' ), <add> worldNormal: new ExpressionNode( 'inverseTransformDirection( geometry.normal, viewMatrix )', 'v3' ), <ide> gamma: true <ide> }; <ide> <ide> StandardNode.prototype.build = function ( builder ) { <ide> roughness: clearcoatRoughness, <ide> bias: new SpecularMIPLevelNode( clearcoatRoughness ), <ide> viewNormal: new ExpressionNode( 'clearcoatNormal', 'v3' ), <add> worldNormal: new ExpressionNode( 'inverseTransformDirection( geometry.clearcoatNormal, viewMatrix )', 'v3' ), <ide> gamma: true <ide> }; <ide> <ide><path>examples/jsm/nodes/misc/TextureCubeUVNode.js <ide> TextureCubeUVNode.Nodes = ( function () { <ide> <ide> var bilinearCubeUV = new FunctionNode( <ide> `TextureCubeUVData bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) { <add> <ide> float face = getFace(direction); <ide> float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0); <ide> mipInt = max(mipInt, cubeUV_minMipLevel); <ide> float faceSize = exp2(mipInt); <add> <ide> float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize); <add> <ide> vec2 uv = getUV(direction, face) * (faceSize - 1.0); <ide> vec2 f = fract(uv); <ide> uv += 0.5 - f; <ide> TextureCubeUVNode.Nodes = ( function () { <ide> uv.y += filterInt * 2.0 * cubeUV_minTileSize; <ide> uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize); <ide> uv *= texelSize; <add> <ide> vec4 tl = texture2D(envMap, uv); <ide> uv.x += texelSize; <ide> vec4 tr = texture2D(envMap, uv);
4
Python
Python
pass value for auto_name argument
315a12ac58d373640942cebe9b6ac6a314344c82
<ide><path>tests/auto/test_sequential_model.py <ide> def output_shape(previous): <ide> left = Sequential() <ide> left.add(Dense(nb_hidden, input_shape=(input_dim,))) <ide> left.add(Activation('relu')) <del> left.set_name('left') <ide> <ide> right = Sequential() <ide> right.add(Dense(nb_hidden, input_shape=(input_dim,))) <ide> right.add(Activation('relu')) <del> right.set_name('right') <ide> <ide> model = Sequential() <del> model.add(Merge([left, right], mode='join')) <add> model.add(Merge([left, right], mode='join', auto_name=True)) <ide> <ide> model.add(Lambda(function=func,output_shape=output_shape)) <ide>
1
Javascript
Javascript
remove oldie change and submit special-event code
1c4297816dc274754d399e9e66e0bbf39f4d008a
<ide><path>src/event.js <del>var rformElems = /^(?:input|select|textarea)$/i, <del> rkeyEvent = /^key/, <add>var rkeyEvent = /^key/, <ide> rmouseEvent = /^(?:mouse|contextmenu)|click/, <ide> rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, <ide> rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; <ide> jQuery.each({ <ide> }; <ide> }); <ide> <del>// IE submit delegation <del>if ( !jQuery.support.submitBubbles ) { <del> <del> jQuery.event.special.submit = { <del> setup: function() { <del> // Only need this for delegated form submit events <del> if ( jQuery.nodeName( this, "form" ) ) { <del> return false; <del> } <del> <del> // Lazy-add a submit handler when a descendant form may potentially be submitted <del> jQuery.event.add( this, "click._submit keypress._submit", function( e ) { <del> // Node name check avoids a VML-related crash in IE (#9807) <del> var elem = e.target, <del> form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; <del> if ( form && !jQuery._data( form, "_submit_attached" ) ) { <del> jQuery.event.add( form, "submit._submit", function( event ) { <del> event._submit_bubble = true; <del> }); <del> jQuery._data( form, "_submit_attached", true ); <del> } <del> }); <del> // return undefined since we don't need an event listener <del> }, <del> <del> postDispatch: function( event ) { <del> // If form was submitted by the user, bubble the event up the tree <del> if ( event._submit_bubble ) { <del> delete event._submit_bubble; <del> if ( this.parentNode && !event.isTrigger ) { <del> jQuery.event.simulate( "submit", this.parentNode, event, true ); <del> } <del> } <del> }, <del> <del> teardown: function() { <del> // Only need this for delegated form submit events <del> if ( jQuery.nodeName( this, "form" ) ) { <del> return false; <del> } <del> <del> // Remove delegated handlers; cleanData eventually reaps submit handlers attached above <del> jQuery.event.remove( this, "._submit" ); <del> } <del> }; <del>} <del> <del>// IE change delegation and checkbox/radio fix <del>if ( !jQuery.support.changeBubbles ) { <del> <del> jQuery.event.special.change = { <del> <del> setup: function() { <del> <del> if ( rformElems.test( this.nodeName ) ) { <del> // IE doesn't fire change on a check/radio until blur; trigger it on click <del> // after a propertychange. Eat the blur-change in special.change.handle. <del> // This still fires onchange a second time for check/radio after blur. <del> if ( this.type === "checkbox" || this.type === "radio" ) { <del> jQuery.event.add( this, "propertychange._change", function( event ) { <del> if ( event.originalEvent.propertyName === "checked" ) { <del> this._just_changed = true; <del> } <del> }); <del> jQuery.event.add( this, "click._change", function( event ) { <del> if ( this._just_changed && !event.isTrigger ) { <del> this._just_changed = false; <del> } <del> // Allow triggered, simulated change events (#11500) <del> jQuery.event.simulate( "change", this, event, true ); <del> }); <del> } <del> return false; <del> } <del> // Delegated event; lazy-add a change handler on descendant inputs <del> jQuery.event.add( this, "beforeactivate._change", function( e ) { <del> var elem = e.target; <del> <del> if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { <del> jQuery.event.add( elem, "change._change", function( event ) { <del> if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { <del> jQuery.event.simulate( "change", this.parentNode, event, true ); <del> } <del> }); <del> jQuery._data( elem, "_change_attached", true ); <del> } <del> }); <del> }, <del> <del> handle: function( event ) { <del> var elem = event.target; <del> <del> // Swallow native change events from checkbox/radio, we already triggered them above <del> if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { <del> return event.handleObj.handler.apply( this, arguments ); <del> } <del> }, <del> <del> teardown: function() { <del> jQuery.event.remove( this, "._change" ); <del> <del> return !rformElems.test( this.nodeName ); <del> } <del> }; <del>} <del> <ide> // Create "bubbling" focus and blur events <ide> if ( !jQuery.support.focusinBubbles ) { <ide> jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
1
Ruby
Ruby
install active storage extension lazily
1a4a582ddcf3dbacf37973f53e6dfacddd2fe2c3
<ide><path>lib/action_text/engine.rb <ide> class Engine < Rails::Engine <ide> end <ide> <ide> initializer "action_text.active_storage_extension" do <del> require "active_storage/blob" <del> <del> class ActiveStorage::Blob <add> ActiveSupport.on_load(:active_storage_blob) do <ide> include ActionText::Attachable <ide> <ide> def previewable_attachable?
1
PHP
PHP
improve code readility and optimize it a bit
c169d265525b6206770546997a062923b1ddf4cc
<ide><path>src/Console/ConsoleOptionParser.php <ide> protected function getCommandError($command) <ide> $subcommands = array_keys((array)$this->subcommands()); <ide> $bestGuess = $this->findClosestItem($command, $subcommands); <ide> <del> $out = []; <del> <del> $out[] = sprintf( <del> 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.', <del> $rootCommand, <del> $command, <del> $this->rootName, <del> $rootCommand <del> ); <del> $out[] = ''; <add> $out = [ <add> sprintf( <add> 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.', <add> $rootCommand, <add> $command, <add> $this->rootName, <add> $rootCommand <add> ), <add> '' <add> ]; <add> <ide> if ($bestGuess !== null) { <ide> $out[] = sprintf('Did you mean : `%s %s` ?', $rootCommand, $bestGuess); <ide> $out[] = ''; <ide> protected function getOptionError($option) <ide> { <ide> $availableOptions = array_keys($this->_options); <ide> $bestGuess = $this->findClosestItem($option, $availableOptions); <del> $out = []; <del> $out[] = sprintf('Unknown option `%s`.', $option); <del> $out[] = ''; <add> $out = [ <add> sprintf('Unknown option `%s`.', $option), <add> '' <add> ]; <ide> <ide> if ($bestGuess !== null) { <ide> $out[] = sprintf('Did you mean `%s` ?', $bestGuess); <ide> protected function findClosestItem($needle, $haystack) <ide> $score = levenshtein($needle, $item); <ide> <ide> if (!isset($bestScore) || $score < $bestScore) { <del> $bestScore = levenshtein($needle, $item); <add> $bestScore = $score; <ide> $bestGuess = $item; <ide> } <ide> } <ide><path>src/Console/Shell.php <ide> protected function _displayHelp($command) <ide> <ide> $subcommands = $this->OptionParser->subcommands(); <ide> $command = isset($subcommands[$command]) ? $command : null; <add> <ide> return $this->out($this->OptionParser->help($command, $format)); <ide> } <ide>
2
Javascript
Javascript
fix memory leak of promise callbacks
36389288e8c7f2538b5ae7dd6877e81a9a76c644
<ide><path>src/deferred.js <ide> jQuery.extend( { <ide> // fulfilled_callbacks.disable <ide> tuples[ 3 - i ][ 2 ].disable, <ide> <add> // rejected_handlers.disable <add> // fulfilled_handlers.disable <add> tuples[ 3 - i ][ 3 ].disable, <add> <ide> // progress_callbacks.lock <del> tuples[ 0 ][ 2 ].lock <add> tuples[ 0 ][ 2 ].lock, <add> <add> // progress_handlers.lock <add> tuples[ 0 ][ 3 ].lock <ide> ); <ide> } <ide>
1
Text
Text
add brewdler tap to documentation
eaba2607c4a2f58a9dab0bc910c571b477e2a762
<ide><path>share/doc/homebrew/Interesting-Taps-&-Branches.md <ide> Homebrew has the capability to add (and remove) multiple taps to your local inst <ide> - Formula are not deleted, they are moved here. <ide> <ide> * [homebrew/nginx](https://github.com/Homebrew/homebrew-nginx) <del> - Feature rich Nginx tap for modules <add> - Feature rich Nginx tap for modules. <ide> <ide> * [homebrew/binary](https://github.com/Homebrew/homebrew-binary) <ide> - Precompiled binary formulae. <ide> <add>* [homebrew/brewdler](https://github.com/Homebrew/homebrew-brewdler) <add> - A Bundler-equivalent for installing project dependencies from Homebrew. <add> <ide> <ide> `brew search` looks in these main taps and as well in [Homebrew/homebrew](https://github.com/Homebrew/homebrew). So don't worry about missing stuff. We will add other taps to the search as they become well maintained and popular. <ide>
1
Text
Text
move orangemocha to collaborator emeriti list
d88fcf3ef713193dea3402703cc93b755ebfddf3
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Teddy Katz** &lt;teddy.katz@gmail.com&gt; (he/him) <ide> * [ofrobots](https://github.com/ofrobots) - <ide> **Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; (he/him) <del>* [orangemocha](https://github.com/orangemocha) - <del>**Alexis Campailla** &lt;orangemocha@nodejs.org&gt; <ide> * [oyyd](https://github.com/oyyd) - <ide> **Ouyang Yadong** &lt;oyydoibh@gmail.com&gt; (he/him) <ide> * [pmq20](https://github.com/pmq20) - <ide> For information about the governance of the Node.js project, see <ide> **Christopher Monsanto** &lt;chris@monsan.to&gt; <ide> * [Olegas](https://github.com/Olegas) - <ide> **Oleg Elifantiev** &lt;oleg@elifantiev.ru&gt; <add>* [orangemocha](https://github.com/orangemocha) - <add>**Alexis Campailla** &lt;orangemocha@nodejs.org&gt; <ide> * [othiym23](https://github.com/othiym23) - <ide> **Forrest L Norvell** &lt;ogd@aoaioxxysz.net&gt; (he/him) <ide> * [petkaantonov](https://github.com/petkaantonov) -
1
Ruby
Ruby
use svn info --xml (#174)
90d3317d7dc9d809d7fc8da15e824161a0ce3008
<ide><path>Library/Homebrew/download_strategy.rb <ide> require "utils/json" <add>require "rexml/document" <ide> <ide> class AbstractDownloadStrategy <ide> include FileUtils <ide> def stage <ide> end <ide> <ide> def source_modified_time <del> Time.parse Utils.popen_read("svn", "info", cached_location.to_s).strip[/^Last Changed Date: (.+)$/, 1] <add> xml = REXML::Document.new(Utils.popen_read("svn", "info", "--xml", cached_location.to_s)) <add> Time.parse REXML::XPath.first(xml, "//date/text()").to_s <ide> end <ide> <ide> private
1
Javascript
Javascript
increase fibonacci argument to 40
0ab4a1ce90cd1cb33860a10388473ed7bb070713
<ide><path>test/fixtures/workload/fibonacci.js <ide> function fib(n) { <ide> return fib(n - 1) + fib(n - 2); <ide> } <ide> <del>// This is based on emperial values - in the CI, on Windows the program <del>// tend to finish too fast then we won't be able to see the profiled script <del>// in the samples, so we need to bump the values a bit. On slower platforms <del>// like the Pis it could take more time to complete, we need to use a <del>// smaller value so the test would not time out. <del>const FIB = process.platform === 'win32' ? 40 : 30; <del> <del>const n = parseInt(process.env.FIB) || FIB; <add>const n = parseInt(process.env.FIB, 10) || 40; <ide> process.stdout.write(`${fib(n)}\n`);
1
PHP
PHP
allow wildcard mime types
fe1ef6570d10c955da8e90c8be429d96ad5574ee
<ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> protected function validateMimetypes($attribute, $value, $parameters) <ide> return false; <ide> } <ide> <del> return $value->getPath() != '' && (in_array($value->getMimeType(), $parameters) || in_array(explode('/', $value->getMimeType())[0] . '/*', $parameters)); <add> return $value->getPath() != '' && <add> (in_array($value->getMimeType(), $parameters) || <add> in_array(explode('/', $value->getMimeType())[0].'/*', $parameters)); <ide> } <ide> <ide> /**
1
Javascript
Javascript
drop unused import
cc5b7fb9a9d0e146599be759ce52721d2078f465
<ide><path>src/lib/units/month.js <ide> import isArray from '../utils/is-array'; <ide> import indexOf from '../utils/index-of'; <ide> import { createUTC } from '../create/utc'; <ide> import getParsingFlags from '../create/parsing-flags'; <del>import isUndefined from '../utils/is-undefined'; <ide> <ide> export function daysInMonth(year, month) { <ide> return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
1
Ruby
Ruby
remove obsolete comment from generator gem method
09be6921590a7e4ded515deb8ce77566fa41fed5
<ide><path>railties/lib/rails/generators/actions.rb <ide> module Rails <ide> module Generators <ide> module Actions <ide> <del> # Adds an entry into Gemfile for the supplied gem. If env <del> # is specified, add the gem to the given environment. <add> # Adds an entry into Gemfile for the supplied gem. <ide> # <ide> # gem "rspec", :group => :test <ide> # gem "technoweenie-restful-authentication", :lib => "restful-authentication", :source => "http://gems.github.com/"
1
Python
Python
add an interface test
a05d1c2450074577f01eabe2e7e3a5ca8e64c847
<ide><path>numpy/core/tests/test_overrides.py <ide> def test_pickle(self): <ide> def test_docstring(self): <ide> assert_equal(dispatched_one_arg.__doc__, 'Docstring.') <ide> <add> def test_interface(self): <add> <add> class MyArray(object): <add> def __array_function__(self, func, types, args, kwargs): <add> return (self, func, types, args, kwargs) <add> <add> original = MyArray() <add> (obj, func, types, args, kwargs) = dispatched_one_arg(original) <add> assert_(obj is original) <add> assert_(func is dispatched_one_arg) <add> assert_equal(set(types), {MyArray}) <add> assert_equal(args, (original,)) <add> assert_equal(kwargs, {}) <add> <ide> <ide> def _new_duck_type_and_implements(): <ide> """Create a duck array type and implements functions."""
1
Ruby
Ruby
fix missing formula handling
9126a5cf8dbee31eae9df92d25c58c3337e55ed6
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> end <ide> end <ide> <del> begin <del> formulae = [] <del> <del> unless ARGV.casks.empty? <del> cask_args = [] <del> cask_args << "--force" if args.force? <del> cask_args << "--debug" if args.debug? <del> cask_args << "--verbose" if args.verbose? <del> <del> ARGV.casks.each do |c| <del> ohai "brew cask install #{c} #{cask_args.join " "}" <del> system("#{HOMEBREW_PREFIX}/bin/brew", "cask", "install", c, *cask_args) <del> end <del> end <add> formulae = [] <ide> <del> # if the user's flags will prevent bottle only-installations when no <del> # developer tools are available, we need to stop them early on <del> FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed? <add> unless ARGV.casks.empty? <add> cask_args = [] <add> cask_args << "--force" if args.force? <add> cask_args << "--debug" if args.debug? <add> cask_args << "--verbose" if args.verbose? <ide> <del> ARGV.formulae.each do |f| <del> # head-only without --HEAD is an error <del> if !Homebrew.args.HEAD? && f.stable.nil? && f.devel.nil? <del> raise <<~EOS <del> #{f.full_name} is a head-only formula <del> Install with `brew install --HEAD #{f.full_name}` <del> EOS <del> end <del> <del> # devel-only without --devel is an error <del> if !args.devel? && f.stable.nil? && f.head.nil? <del> raise <<~EOS <del> #{f.full_name} is a devel-only formula <del> Install with `brew install --devel #{f.full_name}` <del> EOS <del> end <add> ARGV.casks.each do |c| <add> ohai "brew cask install #{c} #{cask_args.join " "}" <add> system("#{HOMEBREW_PREFIX}/bin/brew", "cask", "install", c, *cask_args) <add> end <add> end <ide> <del> if !(args.HEAD? || args.devel?) && f.stable.nil? <del> raise "#{f.full_name} has no stable download, please choose --devel or --HEAD" <del> end <add> # if the user's flags will prevent bottle only-installations when no <add> # developer tools are available, we need to stop them early on <add> FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed? <add> <add> ARGV.formulae.each do |f| <add> # head-only without --HEAD is an error <add> if !Homebrew.args.HEAD? && f.stable.nil? && f.devel.nil? <add> raise <<~EOS <add> #{f.full_name} is a head-only formula <add> Install with `brew install --HEAD #{f.full_name}` <add> EOS <add> end <ide> <del> # --HEAD, fail with no head defined <del> if args.head? && f.head.nil? <del> raise "No head is defined for #{f.full_name}" <del> end <add> # devel-only without --devel is an error <add> if !args.devel? && f.stable.nil? && f.head.nil? <add> raise <<~EOS <add> #{f.full_name} is a devel-only formula <add> Install with `brew install --devel #{f.full_name}` <add> EOS <add> end <ide> <del> # --devel, fail with no devel defined <del> if args.devel? && f.devel.nil? <del> raise "No devel block is defined for #{f.full_name}" <del> end <add> if !(args.HEAD? || args.devel?) && f.stable.nil? <add> raise "#{f.full_name} has no stable download, please choose --devel or --HEAD" <add> end <ide> <del> installed_head_version = f.latest_head_version <del> new_head_installed = installed_head_version && <del> !f.head_version_outdated?(installed_head_version, fetch_head: args.fetch_HEAD?) <del> prefix_installed = f.prefix.exist? && !f.prefix.children.empty? <del> <del> if f.keg_only? && f.any_version_installed? && f.optlinked? && !args.force? <del> # keg-only install is only possible when no other version is <del> # linked to opt, because installing without any warnings can break <del> # dependencies. Therefore before performing other checks we need to be <del> # sure --force flag is passed. <del> if f.outdated? <del> optlinked_version = Keg.for(f.opt_prefix).version <del> onoe <<~EOS <del> #{f.full_name} #{optlinked_version} is already installed <del> To upgrade to #{f.version}, run `brew upgrade #{f.name}` <del> EOS <del> elsif args.only_dependencies? <del> formulae << f <del> else <del> opoo <<~EOS <del> #{f.full_name} #{f.pkg_version} is already installed and up-to-date <del> To reinstall #{f.pkg_version}, run `brew reinstall #{f.name}` <del> EOS <del> end <del> elsif (args.HEAD? && new_head_installed) || prefix_installed <del> # After we're sure that --force flag is passed for linked to opt <del> # keg-only we need to be sure that the version we're attempting to <del> # install is not already installed. <add> # --HEAD, fail with no head defined <add> if args.head? && f.head.nil? <add> raise "No head is defined for #{f.full_name}" <add> end <ide> <del> installed_version = if args.HEAD? <del> f.latest_head_version <del> else <del> f.pkg_version <del> end <add> # --devel, fail with no devel defined <add> if args.devel? && f.devel.nil? <add> raise "No devel block is defined for #{f.full_name}" <add> end <ide> <del> msg = "#{f.full_name} #{installed_version} is already installed" <del> linked_not_equals_installed = f.linked_version != installed_version <del> if f.linked? && linked_not_equals_installed <del> msg = <<~EOS <del> #{msg} <del> The currently linked version is #{f.linked_version} <del> You can use `brew switch #{f} #{installed_version}` to link this version. <del> EOS <del> elsif !f.linked? || f.keg_only? <del> msg = <<~EOS <del> #{msg}, it's just not linked <del> You can use `brew link #{f}` to link this version. <del> EOS <del> elsif args.only_dependencies? <del> msg = nil <del> formulae << f <del> else <del> msg = <<~EOS <del> #{msg} and up-to-date <del> To reinstall #{f.pkg_version}, run `brew reinstall #{f.name}` <del> EOS <del> end <del> opoo msg if msg <del> elsif !f.any_version_installed? && old_formula = f.old_installed_formulae.first <del> msg = "#{old_formula.full_name} #{old_formula.installed_version} already installed" <del> if !old_formula.linked? && !old_formula.keg_only? <del> msg = <<~EOS <del> #{msg}, it's just not linked. <del> You can use `brew link #{old_formula.full_name}` to link this version. <del> EOS <del> end <del> opoo msg <del> elsif f.migration_needed? && !args.force? <del> # Check if the formula we try to install is the same as installed <del> # but not migrated one. If --force passed then install anyway. <add> installed_head_version = f.latest_head_version <add> new_head_installed = installed_head_version && <add> !f.head_version_outdated?(installed_head_version, fetch_head: args.fetch_HEAD?) <add> prefix_installed = f.prefix.exist? && !f.prefix.children.empty? <add> <add> if f.keg_only? && f.any_version_installed? && f.optlinked? && !args.force? <add> # keg-only install is only possible when no other version is <add> # linked to opt, because installing without any warnings can break <add> # dependencies. Therefore before performing other checks we need to be <add> # sure --force flag is passed. <add> if f.outdated? <add> optlinked_version = Keg.for(f.opt_prefix).version <add> onoe <<~EOS <add> #{f.full_name} #{optlinked_version} is already installed <add> To upgrade to #{f.version}, run `brew upgrade #{f.name}` <add> EOS <add> elsif args.only_dependencies? <add> formulae << f <add> else <ide> opoo <<~EOS <del> #{f.oldname} already installed, it's just not migrated <del> You can migrate formula with `brew migrate #{f}` <del> Or you can force install it with `brew install #{f} --force` <add> #{f.full_name} #{f.pkg_version} is already installed and up-to-date <add> To reinstall #{f.pkg_version}, run `brew reinstall #{f.name}` <ide> EOS <add> end <add> elsif (args.HEAD? && new_head_installed) || prefix_installed <add> # After we're sure that --force flag is passed for linked to opt <add> # keg-only we need to be sure that the version we're attempting to <add> # install is not already installed. <add> <add> installed_version = if args.HEAD? <add> f.latest_head_version <ide> else <del> # If none of the above is true and the formula is linked, then <del> # FormulaInstaller will handle this case. <add> f.pkg_version <add> end <add> <add> msg = "#{f.full_name} #{installed_version} is already installed" <add> linked_not_equals_installed = f.linked_version != installed_version <add> if f.linked? && linked_not_equals_installed <add> msg = <<~EOS <add> #{msg} <add> The currently linked version is #{f.linked_version} <add> You can use `brew switch #{f} #{installed_version}` to link this version. <add> EOS <add> elsif !f.linked? || f.keg_only? <add> msg = <<~EOS <add> #{msg}, it's just not linked <add> You can use `brew link #{f}` to link this version. <add> EOS <add> elsif args.only_dependencies? <add> msg = nil <ide> formulae << f <add> else <add> msg = <<~EOS <add> #{msg} and up-to-date <add> To reinstall #{f.pkg_version}, run `brew reinstall #{f.name}` <add> EOS <add> end <add> opoo msg if msg <add> elsif !f.any_version_installed? && old_formula = f.old_installed_formulae.first <add> msg = "#{old_formula.full_name} #{old_formula.installed_version} already installed" <add> if !old_formula.linked? && !old_formula.keg_only? <add> msg = <<~EOS <add> #{msg}, it's just not linked. <add> You can use `brew link #{old_formula.full_name}` to link this version. <add> EOS <ide> end <add> opoo msg <add> elsif f.migration_needed? && !args.force? <add> # Check if the formula we try to install is the same as installed <add> # but not migrated one. If --force passed then install anyway. <add> opoo <<~EOS <add> #{f.oldname} already installed, it's just not migrated <add> You can migrate formula with `brew migrate #{f}` <add> Or you can force install it with `brew install #{f} --force` <add> EOS <add> else <add> # If none of the above is true and the formula is linked, then <add> # FormulaInstaller will handle this case. <add> formulae << f <add> end <ide> <del> # Even if we don't install this formula mark it as no longer just <del> # installed as a dependency. <del> next unless f.opt_prefix.directory? <add> # Even if we don't install this formula mark it as no longer just <add> # installed as a dependency. <add> next unless f.opt_prefix.directory? <ide> <del> keg = Keg.new(f.opt_prefix.resolved_path) <del> tab = Tab.for_keg(keg) <del> unless tab.installed_on_request <del> tab.installed_on_request = true <del> tab.write <del> end <add> keg = Keg.new(f.opt_prefix.resolved_path) <add> tab = Tab.for_keg(keg) <add> unless tab.installed_on_request <add> tab.installed_on_request = true <add> tab.write <ide> end <add> end <ide> <del> return if formulae.empty? <add> return if formulae.empty? <ide> <del> Install.perform_preinstall_checks <add> Install.perform_preinstall_checks <ide> <del> formulae.each do |f| <del> Migrator.migrate_if_needed(f) <del> install_formula(f) <del> Cleanup.install_formula_clean!(f) <del> end <del> Homebrew.messages.display_messages <del> rescue FormulaUnreadableError, FormulaClassUnavailableError, <del> TapFormulaUnreadableError, TapFormulaClassUnavailableError => e <del> # Need to rescue before `FormulaUnavailableError` (superclass of this) <del> # is handled, as searching for a formula doesn't make sense here (the <del> # formula was found, but there's a problem with its implementation). <del> ofail e.message <del> rescue FormulaUnavailableError => e <del> if e.name == "updog" <del> ofail "What's updog?" <del> return <del> end <add> formulae.each do |f| <add> Migrator.migrate_if_needed(f) <add> install_formula(f) <add> Cleanup.install_formula_clean!(f) <add> end <add> Homebrew.messages.display_messages <add> rescue FormulaUnreadableError, FormulaClassUnavailableError, <add> TapFormulaUnreadableError, TapFormulaClassUnavailableError => e <add> # Need to rescue before `FormulaUnavailableError` (superclass of this) <add> # is handled, as searching for a formula doesn't make sense here (the <add> # formula was found, but there's a problem with its implementation). <add> ofail e.message <add> rescue FormulaUnavailableError => e <add> if e.name == "updog" <add> ofail "What's updog?" <add> return <add> end <ide> <del> ofail e.message <del> if (reason = MissingFormula.reason(e.name)) <del> $stderr.puts reason <del> return <del> end <add> ofail e.message <add> if (reason = MissingFormula.reason(e.name)) <add> $stderr.puts reason <add> return <add> end <ide> <del> ohai "Searching for similarly named formulae..." <del> formulae_search_results = search_formulae(e.name) <del> case formulae_search_results.length <del> when 0 <del> ofail "No similarly named formulae found." <del> when 1 <del> puts "This similarly named formula was found:" <del> puts formulae_search_results <del> puts "To install it, run:\n brew install #{formulae_search_results.first}" <del> else <del> puts "These similarly named formulae were found:" <del> puts Formatter.columns(formulae_search_results) <del> puts "To install one of them, run (for example):\n brew install #{formulae_search_results.first}" <del> end <add> ohai "Searching for similarly named formulae..." <add> formulae_search_results = search_formulae(e.name) <add> case formulae_search_results.length <add> when 0 <add> ofail "No similarly named formulae found." <add> when 1 <add> puts "This similarly named formula was found:" <add> puts formulae_search_results <add> puts "To install it, run:\n brew install #{formulae_search_results.first}" <add> else <add> puts "These similarly named formulae were found:" <add> puts Formatter.columns(formulae_search_results) <add> puts "To install one of them, run (for example):\n brew install #{formulae_search_results.first}" <add> end <ide> <del> # Do not search taps if the formula name is qualified <del> return if e.name.include?("/") <del> <del> ohai "Searching taps..." <del> taps_search_results = search_taps(e.name)[:formulae] <del> case taps_search_results.length <del> when 0 <del> ofail "No formulae found in taps." <del> when 1 <del> puts "This formula was found in a tap:" <del> puts taps_search_results <del> puts "To install it, run:\n brew install #{taps_search_results.first}" <del> else <del> puts "These formulae were found in taps:" <del> puts Formatter.columns(taps_search_results) <del> puts "To install one of them, run (for example):\n brew install #{taps_search_results.first}" <del> end <add> # Do not search taps if the formula name is qualified <add> return if e.name.include?("/") <add> <add> ohai "Searching taps..." <add> taps_search_results = search_taps(e.name)[:formulae] <add> case taps_search_results.length <add> when 0 <add> ofail "No formulae found in taps." <add> when 1 <add> puts "This formula was found in a tap:" <add> puts taps_search_results <add> puts "To install it, run:\n brew install #{taps_search_results.first}" <add> else <add> puts "These formulae were found in taps:" <add> puts Formatter.columns(taps_search_results) <add> puts "To install one of them, run (for example):\n brew install #{taps_search_results.first}" <ide> end <ide> end <ide>
1
PHP
PHP
remove int cast from authentication adapters
3de72baeb1d911aecbea51006f815742696b3c9f
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php <ide> protected function _findUser($username, $password) { <ide> } <ide> $result = ClassRegistry::init($userModel)->find('first', array( <ide> 'conditions' => $conditions, <del> 'recursive' => (int)$this->settings['recursive'], <add> 'recursive' => $this->settings['recursive'], <ide> 'contain' => $this->settings['contain'], <ide> )); <ide> if (empty($result) || empty($result[$model])) { <ide><path>lib/Cake/Controller/Component/Auth/DigestAuthenticate.php <ide> protected function _findUser($username, $password) { <ide> } <ide> $result = ClassRegistry::init($userModel)->find('first', array( <ide> 'conditions' => $conditions, <del> 'recursive' => (int)$this->settings['recursive'] <add> 'recursive' => $this->settings['recursive'] <ide> )); <ide> if (empty($result) || empty($result[$model])) { <ide> return false;
2
Javascript
Javascript
bring population example up-to-date
aa575adb9840d86de421b153ae189f711d3a8d48
<ide><path>examples/population/population.js <del>var w = 960, <del> h = 500, <del> x = d3.scale.linear().range([0, w]), <del> y = d3.scale.linear().range([0, h - 40]); <add>var width = 960, <add> height = 500; <add> <add>var x = d3.scale.linear() <add> .range([0, width]); <add> <add>var y = d3.scale.linear() <add> .range([0, height - 40]); <ide> <ide> // An SVG element with a bottom-right origin. <ide> var svg = d3.select("#chart").append("svg") <del> .attr("width", w) <del> .attr("height", h) <add> .attr("width", width) <add> .attr("height", height) <ide> .style("padding-right", "30px") <ide> .append("g") <del> .attr("transform", "translate(" + x(1) + "," + (h - 20) + ")scale(-1,-1)"); <add> .attr("transform", "translate(" + x(1) + "," + (height - 20) + ")scale(-1,-1)"); <ide> <ide> // A sliding container to hold the bars. <ide> var body = svg.append("g") <ide> d3.csv("population.csv", function(data) { <ide> .attr("transform", function(d) { return "translate(0," + y(d) + ")"; }); <ide> <ide> rules.append("line") <del> .attr("x2", w); <add> .attr("x2", width); <ide> <ide> rules.append("text") <ide> .attr("x", 6)
1
Text
Text
improve korean translation and change wording
fb551cb23c32fc85e76041489c5896e5a650bdb1
<ide><path>docs/i18n-languages/korean/CONTRIBUTING.md <ide> <ide> # 기여 지침 <ide> <del>안녕하세요 👋! <add>안녕하세요. 👋 <ide> <ide> freeCodeCamp.org는 여러분과 같은 수천 명의 친절한 자원봉사자 덕분에 운영할 수 있습니다. 우리는 여러분의 기여를 환영하며 감사하고 기쁘게 생각합니다. <ide> <del>우리는 [행동 강령] (https://www.freecodecamp.org/code-of-conduct)을 엄격히 시행합니다. 잠시 시간을 내어 읽어주십시오. 단지 196 단어밖에 되지 않습니다. <add>우리는 [행동 강령](https://www.freecodecamp.org/code-of-conduct)을 엄격히 시행하고 있습니다. 잠시 시간을 내어 읽어주세요. 196단어밖에 되지 않습니다. <ide> <del>행복한 기여가 되길 바랍니다 🎉! <add>행복한 기여가 되길 바랍니다. <ide> <del>## 여러분이 도울 수 있는 몇 가지 재미있는 방법들 <add>## 기여할 수 있는 몇 가지 재미있는 방법들 <ide> <del>관심 분야에 기여할 수 있습니다: <add>여러분은 어느 방법으로도 기여할 수 있습니다. <ide> <del>1. [오픈소스 코드 베이스에 기여](#contribute-to-this-open-source-codebase). [가이드 문서](https://guide.freecodecamp.org/), [코딩 과제](https://learn.freecodecamp.org/) 편집, 학습 플랫폼의 버그 수정. <add>1. [오픈소스 코드 베이스에 기여](#contribute-to-this-open-source-codebase)할 수 있습니다. 코딩 챌린지를 편집하거나 학습 플랫폼의 버그를 수정해 도움을 주세요. <ide> <del>2. 우리의 [공개 포럼](https://www.freecodecamp.org/forum/)에서 사용자 돕기. [코딩 질문에 답변](https://www.freecodecamp.org/forum/?max_posts=1)하거나 [코딩 프로젝트에 대한 피드백을 제공](https://www.freecodecamp.org/forum/c/project-feedback?max_posts=1). <add>2. [공개 포럼](https://www.freecodecamp.org/forum/)에서 학습자들을 도와주세요. [코딩 질문에 답변](https://www.freecodecamp.org/forum/?max_posts=1)해주거나 [코딩 프로젝트에 대한 피드백을 제공](https://www.freecodecamp.org/forum/c/project-feedback?max_posts=1)할 수 있습니다. <ide> <del>3. [유튜브 채널 비디오](https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ/videos)에 자막이나 캡션을 추가. <add>3. [유튜브 채널 비디오](https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ/videos)에 자막 (숨겨진 캡션)을 추가할 수 있습니다. <ide> <del>## 오픈소스 코드 베이스에 기여 <add>## 오픈소스 코드 베이스에 기여하기 <ide> <del>우리는 수천 가지의 [코딩 과제](https://learn.freecodecamp.org)와 [가이드 문서](https://guide.freecodecamp.org)로 구성된 막대한 오픈소스 코드 베이스를 가지고 있습니다. <add>우리의 코드 베이스는 수천 개의 [코딩 챌린지](https://learn.freecodecamp.org)와 막대한 오픈소스 코드 베이스를 가지고 있습니다. <ide> <del>다음과 같은 방법으로 도울 수 있습니다: <add>### 코딩 챌린지 만들기, 업데이트하기, 버그 수정하기 <ide> <del>- [📝 연구, 가이드 문서 작성 및 업데이트](#research-write-and-update-our-guide-articles) <add>모든 코딩 챌린지는 커뮤니티가 엄선한 것이며, 여러분과 같은 자원봉사자들이 기여한 전문 지식입니다. <ide> <del>- [💻 창작, 코딩 과제 버그 업데이트 및 수정](#create-update-and-fix-bugs-in-our-coding-challenges) <add>여러분은 코딩 챌린지에 자세한 설명을 덧붙이거나 명확한 표현으로 바꿀 수도 있습니다. 개념을 더 잘 설명하기 위해 유저 스토리를 업데이트 할 수도 있고 중복되는 내용을 삭제할 수도 있습니다. 또한 챌린지 테스트의 정확성을 높여 테스트를 개선할 수도 있습니다. <ide> <del>- [🌐 가이드 문서 번역](#translate-guide-articles) <add>**이러한 코딩 챌린지를 개선하는 데 관심이 있으시다면, [코딩 챌린지 작업 방법](/docs/how-to-work-on-coding-challenges.md)를 참고해주세요.** <ide> <del>- [🛠 freeCodeCamp.org의 학습 플랫폼에서 버그 수정](#help-us-fix-bugs-in-freecodecamporgs-learning-platform) <add>### freeCodeCamp.org 학습 플랫폼의 버그 수정하기 <ide> <del>### 연구, 가이드 문서 작성 및 업데이트 <add>우리의 학습 플랫폼은 모던 자바스크립트 스택으로 운영됩니다. 플랫폼은 Node.js, MongoDB, LoopBack, OAuth 2.0, React, Gatsby, Webpack 외에도 다양한 컴포넌트, 도구, 라이브러리로 구성되어 있습니다. <ide> <del>**가이드 문서란 무엇인가?** <add>간단히 말해, 이렇게 이루어져 있습니다. <ide> <del>가이드 문서는 여러분이 기술 개념을 빨리 이해하도록 도와줍니다. 좀 더 심층적인 자료로 넘어가기 전에 읽을 수 있는 짧고 쉬운 설명을 뜻합니다. <add>- Node.js 기반 API 서버 <add>- 일련의 React 기반 클라이언트 애플리케이션 <add>- 프론트엔드 프로젝트를 평가하기 위해 사용하는 스크립트 <ide> <del>다음은 [HTML 앵커 요소에 대한 예시 문서](https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/html/elements/a-tag/index.md)입니다. <add>이러한 학습 플랫폼에 기여하기 위해서는 API와 ES6 문법에 대한 이해와 많은 호기심이 필요합니다. <ide> <del>**무엇에 관한 문서를 작성할 수 있을까?** <add>기본적으로 앞서 언급한 기술, 도구 및 라이브러리에 대한 기초 지식이 필요합니다. 말하자면, 여러분은 기여하기 위해 전문가가 될 필요가 없습니다. <ide> <del>우리는 여러분이 문서 작성을 돕는 것을 환영합니다. 문서를 작성하기 위해 어떤 분야의 전문가가 될 필요가 없습니다. 가이드 문서는 오픈소스이기 때문에 실수하더라도 다른 기여자가 정정해줄 것입니다. <add>**코드 베이스를 개선하는 데 도움을 주고 싶다면 [로컬에서 freeCodeCamp를 설치](/docs/how-to-setup-freecodecamp-locally.md)하거나 Gitpod이나 무료 온라인 개발 환경을 사용하면 됩니다.** <ide> <del>돕기 위해서 `stub article`을 [Guide website](https://guide.freecodecamp.org)에서 찾고, 문서를 작성한 다음, 풀 요청을 열어 `stub article`을 문서로 교체하십시오. [풀 요청](https://help.github.com/articles/about-pull-requests/)은 다른 사람들이 여러분의 변경 사항에 대해 알고, 검토하고, 채택할 수 있게 합니다. <add>[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/freeCodeCamp/freeCodeCamp) <ide> <del>쓰고 싶은 주제에 대한 `stub article`을 찾을 수 없다면 `stub article`을 만들고 초안 기사를 포함하는 풀 요청을 열 수 있습니다. <add>(여러분의 브라우저에서 freecodecamp의 개발 환경을 실행합니다.) <ide> <del>가이드 문서를 개선하고 싶다면 [가이드 문서를 작성하는 방법](/docs/how-to-work-on-guide-articles.md)을 참조하십시오. <del> <del>### 창작, 코딩 과제 버그 업데이트 및 수정 <del> <del>모든 코딩 과제는 커뮤니티가 처리하고, 여러분과 같은 자원봉사자들로부터 전문적인 지식을 가져옵니다. <del> <del>여러분은 프로그래밍을 확장하고 코딩 표현을 더 명확하게 하는데 도움을 줄 수 있습니다. 여러분은 개념을 더 잘 설명하기 위해 사용자 이야기를 업데이트할 수 있고 심지어 중복되는 것도 제거할 수 있습니다. 또한 도전 테스트를 개선하여 사람들의 코드를 더 정확하게 테스트할 수 있습니다. <del> <del>코딩 과제를 개선하는데 관심이 있는 경우, [코딩 과제를 해결하는 방법](/docs/how-to-work-on-coding-challenges.md)을 참조하십시오. <del> <del>### 가이드 문서 번역 <del> <del>여러분이 말하는 언어로 가이드 문서를 번역 할 수 있도록 도와주십시오. 현재 번역 버전은 다음과 같습니다: <del> <del>- [아랍어 (عربي)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/arabic) <del>- [중국어 (中文)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/chinese) <del>- [포르투갈어 (Português)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/portuguese) <del>- [러시아어 (русский)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/russian) <del>- [스페인어 (Español)](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/spanish) <del> <del>우리는 이러한 번역의 품질을 개선하는 데 여러분의 도움을 바랍니다. 수백만 명의 사람들이 freeCodeCamp.org의 영어 버전을 사용하고 있으며 수백만 명이이 번역된 버전을 더 많이 사용할 것으로 기대합니다. <del> <del>[FreeCodeCamp 커리큘럼 7.0 버전](https://www.freecodecamp.org/forum/t/help-us-build-version-7-0-of-the-freecodecamp-curriculum/263546)이 끝나면 번역할 계획입니다. <del> <del>### freeCodeCamp.org의 학습 플랫폼에서 버그 수정 <del> <del>당사의 학습 플랫폼은 최신 JavaScript 스택에서 실행되고 있습니다. Node.js, MongoDB, LoopBack, OAuth 2.0, React, Gatsby, Webpack 등을 포함하되 이에 국한되지 않는 다양한 구성요소, 도구 및 라이브러리를 갖추고 있습니다. <del> <del>대략적으로, <del> <del>- Node.js 기반 API 서버. <del>- React 기반 클라이언트 응용 프로그램 세트. <del>- 프론트엔드 프로젝트 평가 스크립트. <del> <del>이를 위해 API, ES6 구문에 대한 많은 호기심과 이해가 필요합니다. <add>## 자주 묻는 질문 <ide> <del>본질적으로 앞서 언급한 기술, 도구 및 라이브러리에 대한 기본적인 지식을 기대합니다. 여러분은 기여하기 위해 전문가가 될 필요가 없습니다. <add>**새로운 버그를 어떻게 신고할 수 있나요?** <ide> <del>관련 문제에 관해 질문 할 수 있으면 언제든지 알려주시기 바랍니다. 의심스러운 점이 있다면 우리의 개발자 팀인 Mrugesh Mohapatra [`@ raisedadead`] (https://github.com/raisedadead) 또는 Stuart Taylor [`@ bouncey`] (https://github.com/bouncey)가 도와줄 것입니다. <del>코드 베이스를 개선하는 데 도움을 주려면 [로컬에서 freeCodeCamp를 설치하는 방법] (/docs/ how-to-setup-freecodecamp-locally.md)을 참조하십시오. <add>만약 새로운 버그를 발견했다고 생각한다면, 먼저 ["Help I've Found a Bug"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) 문서를 읽고 지시를 따르세요. <ide> <del>## 자주 묻는 질문 <add>새로운 버그라고 확신이 든다면, 먼저 새로운 GitHub 이슈를 만드세요. 우리가 그 버그를 재현할 수 있도록 가능한 많은 정보를 포함해야 한다는 것을 명심하세요. 이때 도움이 될 수 있도록 미리 이슈 템플릿을 만들어 놓았습니다. <ide> <del>**새로운 버그를 어떻게 신고할 수 있는가?** <add>코딩 챌린지에 대한 도움을 요청하는 이슈는 닫힌다는 점을 유의하세요. 이슈 트래커는 코드베이스 관련 이슈와 논의만을 위한 것입니다. 잘 모르겠다면, 보고를 하기 전에 [포럼에서 도움을 요청](https://www.freecodecamp.org/forum)하세요. <ide> <del>만약 여러분이 새로운 버그를 발견했다고 생각한다면, 먼저 ["Help I've Found a Bug"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543)문서를 읽고 지시를 따르십시오. <add>**보안 이슈를 어떻게 신고할 수 있나요?** <ide> <del>새로운 버그라고 확신이 든다면, 계속하여 새로운 GitHub 이슈들을 만드십시오. 우리가 그 버그를 재현할 수 있도록 가능한 많은 정보를 포함해야 합니다. 이 문제를 해결하는 데 도움이 되는 미리 정의된 문제 템플릿이 있습니다, <add>보안 이슈로 GitHub 이슈를 만들지 말아 주세요. 대신 `security@freecodecamp.org`로 이메일을 보내주시면 즉시 확인하겠습니다. <ide> <del>도전에 대한 코딩 도움말을 찾는 모든 문제는 종결된다는 점에 유의하십시오. 이슈 추적기는 코드베이스 관련 이슈와 논의를 엄격히 하기 위한 것이다. 의심스러울 때마다 보고서를 작성하기 전, 포럼에서 도움을 구해야 합니다. <add>**이슈에 붙은 다양한 라벨은 무엇을 의미하나요?** <ide> <del>**보안 이슈를 어떻게 신고할 수 있는가?** <add>커뮤니티 중재자는 우선순위, 심각성 및 기타 요인에 따라 이슈를 [분류](https://en.wikipedia.org/wiki/Software_bug#Bug_management)하고 PR을 보냅니다. [여기서 모든 라벨의 의미를 찾아볼 수 있습니다](https://github.com/freecodecamp/freecodecamp/labels). <ide> <del>보안 문제에 대해 GitHub 문제를 만들지 마십시오. 대신 `security@freecodecamp.org`로 이메일을 보내주시면 즉시 살펴보겠습니다. <add>여러분이 작업할 수 있는 이슈를 빠르게 찾고 싶다면 [**`help wanted`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) 또는 [**`first timers welcome`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22first+timers+welcome%22) 라벨이 달린 이슈를 살펴보세요. 이 이슈들은 누구에게나 열려 있으며 작업하기 전에 허락을 구할 필요가 없습니다. <ide> <del>**문서에 포함되지 않은 문제가 있다면 어떻게 도움을 받을 수 있는가?** <add>만약 이슈의 설명이 불명확하다면 코멘트 란에 자유롭게 질문하세요. <ide> <del>도움을 요청하십시오: <add>**오타를 찾았는데 PR을 보내기 전에 이슈를 만들어야 하나요?** <ide> <del>- [The "Contributors" category of our public forum](https://www.freecodecamp.org/forum/c/contributors) <del>- [Our public contributors chat room on Gitter](https://gitter.im/FreeCodeCamp/Contributors) <add>오타나 단어 표현 변경과 관련해서는 이슈를 만들 필요 없이 바로 PR을 보내면 됩니다. 이슈는 커리큘럼의 코드나 구조적인 측면과 관련된 더 큰 문제들을 논의하기 위함입니다. <ide> <del>우리는 여러분이 작업하고 싶은 주제에 기여할 수 있도록 도와드립니다. 새 쿼리를 게시하기 전에 쿼리를 검색하십시오. 공손한 마음과 인내심을 가지세요. 자원봉사자 및 운영자 커뮤니티는 항상 여러분의 질문에 답변합니다. <add>**GitHub과 오픈소스가 처음이에요.** <ide> <del>**평소 GitHub와 오픈소스에 익숙하지 않다면:** <add>[오픈소스 가이드에 기여하는 방법](https://github.com/freeCodeCamp/how-to-contribute-to-open-source)을 읽어 보세요. <ide> <del>[오픈소스 가이드에 기여하는 방법](https://github.com/freeCodeCamp/how-to-contribute-to-open-source)을 읽으십시오. <add>**문서에 포함되지 않은 문제가 있다면 어떻게 도움을 받을 수 있나요?** <ide> <del>**이슈에 태그가 붙은 라벨들은 무엇을 의미하는가?** <add>자유롭게 도움을 요청하세요. <ide> <del>커뮤니티 중재자는 우선순위, 심각도 및 기타 요인에 따라 이슈를 [분류](https://en.wikipedia.org/wiki/Software_bug#Bug_management)하고 풀을 요청합니다. [여기에서 완전한 용어집을 찾아보십시오](https://github.com/freecodecamp/freecodecamp/labels). <add>- [공개 포럼의 "Contributors" 카테고리](https://www.freecodecamp.org/forum/c/contributors) <add>- [Gitter에 있는 컨트리뷰터들의 대화방](https://gitter.im/FreeCodeCamp/Contributors) <ide> <del>사용할 수 있는 작업에 대한 간략한 개요는 [**`help wanted`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) 또는 [**`first timers welcome`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22first+timers+welcome%22)를 거쳐야 합니다. 이에 대해 작업하기 전에 허락을 구할 필요가 없습니다.. <add>우리는 여러분이 관심 있는 분야에 기여할 수 있도록 도와드릴 수 있어 대단히 기쁩니다. 관련된 이슈 스레드에 자유롭게 질문하시면, 반갑게 설명해드리겠습니다. 다만 기존에 같은 질문이 있었는지 먼저 검색해주세요. 공손함과 인내심도 필요합니다. 자원봉사자와 중재자들로 이 커뮤니티는 여러분을 도와드리기 위해 항상 대기하고 있습니다. <ide> <del>If these issues lack clarity on what needs to be done, feel free to ask questions in the comments. <add>궁금한 사항이 있다면, 플랫폼 개발팀에 연락을 주세요. <ide> <del>**오타를 찾았는데 풀 요청하기 전에 문제를 보고해야 하는가?** <add>| Name | GitHub | Twitter | <add>|:----------------|:-------|:--------| <add>| Mrugesh Mohapatra | [`@raisedadead`](https://github.com/raisedadead) | [`@raisedadead`](https://twitter.com/raisedadead)| <add>| Ahmad Abdolsaheb | [`@ahmadabdolsaheb`](https://github.com/ahmadabdolsaheb) | [`@Abdolsaheb`](https://twitter.com/Abdolsaheb) | <add>| Kristofer Koishigawa | [`@scissorsneedfoodtoo`](https://github.com/scissorsneedfoodtoo) | [`@kriskoishigawa`](https://twitter.com/kriskoishigawa) | <ide> <del>오타 및 기타 단어 변경의 경우 먼저 문제를 만들지 않고 풀 요청을 직접 열 수 있다. 문제는 커리큘럼의 코드 또는 구조적인 측면과 관련된 더 큰 문제를 토론하는 데 더 많다. <add>> **Email: `dev@freecodecamp.org`**
1
Javascript
Javascript
change passive checker to use defineproperty
035e4cffbd16fd618ed1a5614838656a4a505936
<ide><path>packages/react-dom/src/events/checkPassiveEvents.js <ide> export let passiveBrowserEventsSupported = false; <ide> // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support <ide> if (enableEventAPI && canUseDOM) { <ide> try { <del> const options = { <del> get passive() { <add> const options = {}; <add> // $FlowFixMe: Ignore Flow complaining about needing a value <add> Object.defineProperty(options, 'passive', { <add> get: function() { <ide> passiveBrowserEventsSupported = true; <ide> }, <del> }; <add> }); <ide> window.addEventListener('test', options, options); <ide> window.removeEventListener('test', options, options); <ide> } catch (e) {
1
PHP
PHP
fix doc blocks and class name
7cb92b85b05c7c1ee7902ea7ac47cd5767d593fb
<ide><path>src/View/ViewBuilder.php <ide> public function templatePath($path = null) <ide> * Get/set path for layout files. <ide> * <ide> * @param string|null $path Path for layout files. If null returns current path. <del> * @return string|void <add> * @return string|$this <ide> */ <ide> public function layoutPath($path = null) <ide> { <ide> public function build($vars = [], Request $request = null, Response $response = <ide> $className = App::className($this->_className, 'View', 'View'); <ide> } <ide> if (!$className) { <del> throw new Exception\MissingViewException([$this->_className]); <add> throw new MissingViewException([$this->_className]); <ide> } <ide> $data = [ <ide> 'name' => $this->_name,
1
Javascript
Javascript
verify inspector help url works
dfea13a1688f8fda6a7132714019067e7da68d1b
<ide><path>test/internet/test-inspector-help-page.js <add>'use strict'; <add>const common = require('../common'); <add> <add>common.skipIfInspectorDisabled(); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const https = require('https'); <add>const { spawnSync } = require('child_process'); <add>const child = spawnSync(process.execPath, ['--inspect', '-e', '""']); <add>const stderr = child.stderr.toString(); <add>const helpUrl = stderr.match(/For help, see: (.+)/)[1]; <add> <add>function check(url, cb) { <add> https.get(url, common.mustCall((res) => { <add> assert(res.statusCode >= 200 && res.statusCode < 400); <add> <add> if (res.statusCode >= 300) <add> return check(res.headers.location, cb); <add> <add> let result = ''; <add> <add> res.setEncoding('utf8'); <add> res.on('data', (data) => { <add> result += data; <add> }); <add> <add> res.on('end', common.mustCall(() => { <add> assert(/>Debugging Guide</.test(result)); <add> cb(); <add> })); <add> })).on('error', common.mustNotCall); <add>} <add> <add>check(helpUrl, common.mustCall());
1
Ruby
Ruby
fix typo in the `touch_all` doc [ci skip]
ac1efe7a947ba04b276a7109f1a86e559a6ab683
<ide><path>activerecord/lib/active_record/relation.rb <ide> def update_all(updates) <ide> # === Examples <ide> # <ide> # # Touch all records <del> # Person.all.touch <add> # Person.all.touch_all <ide> # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670'" <ide> # <ide> # # Touch multiple records with a custom attribute <del> # Person.all.touch(:created_at) <add> # Person.all.touch_all(:created_at) <ide> # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670', \"created_at\" = '2018-01-04 22:55:23.132670'" <ide> # <ide> # # Touch multiple records with a specified time <del> # Person.all.touch(time: Time.new(2020, 5, 16, 0, 0, 0)) <add> # Person.all.touch_all(time: Time.new(2020, 5, 16, 0, 0, 0)) <ide> # # => "UPDATE \"people\" SET \"updated_at\" = '2020-05-16 00:00:00'" <ide> # <ide> # # Touch records with scope <del> # Person.where(name: 'David').touch <add> # Person.where(name: 'David').touch_all <ide> # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670' WHERE \"people\".\"name\" = 'David'" <ide> def touch_all(*names, time: nil) <ide> attributes = Array(names) + klass.timestamp_attributes_for_update_in_model
1
Javascript
Javascript
increase max buffer to 1mb
875e9c886c179d26bc0c7c106fee230d132eadd4
<ide><path>script/utils/child-process-wrapper.js <ide> exports.safeExec = function(command, options, callback) { <ide> callback = options; <ide> options = {}; <ide> } <add> if (!options) <add> options = {}; <add> <add> // This needed to be increase for `apm test` runs that generate tons of failures <add> // The default is 200KB. <add> options.maxBuffer = 1024 * 1024; <add> <ide> var child = childProcess.exec(command, options, function(error, stdout, stderr) { <ide> if (error) <ide> process.exit(error.code || 1);
1
PHP
PHP
change binary column type to varbinary(max)
050efd6eae2b244e92b2b3a5a67f9ca7eb79d170
<ide><path>src/Database/Schema/SqlserverSchema.php <ide> public function columnSql(Table $table, $name) { <ide> 'integer' => ' INTEGER', <ide> 'biginteger' => ' BIGINT', <ide> 'boolean' => ' BIT', <del> 'binary' => ' BINARY', <add> 'binary' => ' VARBINARY(MAX)', <ide> 'float' => ' FLOAT', <ide> 'decimal' => ' DECIMAL', <ide> 'text' => ' NVARCHAR(MAX)', <ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php <ide> public static function columnSqlProvider() { <ide> [ <ide> 'img', <ide> ['type' => 'binary'], <del> '[img] BINARY' <add> '[img] VARBINARY(MAX)' <ide> ], <ide> // Boolean <ide> [
2
Python
Python
tolerate missing soundfile module.
39d55d9a4b3e5b2d894e51e78d9fa35e6be4aa18
<ide><path>research/audioset/vggish/vggish_input.py <ide> import mel_features <ide> import vggish_params <ide> <del>import soundfile as sf <add>try: <add> import soundfile as sf <add> <add> def wav_read(wav_file): <add> wav_data, sr = sf.read(wav_file, dtype='int16') <add> return wav_data, sr <add> <add>except ImportError: <add> <add> def wav_read(wav_file): <add> raise NotImplementedError('WAV file reading requires soundfile package.') <ide> <ide> <ide> def waveform_to_examples(data, sample_rate): <ide> def wavfile_to_examples(wav_file): <ide> Returns: <ide> See waveform_to_examples. <ide> """ <del> wav_data, sr = sf.read(wav_file, dtype='int16') <add> wav_data, sr = wav_read(wav_file) <ide> assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype <ide> samples = wav_data / 32768.0 # Convert to [-1.0, +1.0] <ide> return waveform_to_examples(samples, sr)
1
Python
Python
yield none when there's nothing to schedule
89f429738eed210a6ce1471a4a3ad763364a0c7a
<ide><path>celery/worker/scheduler.py <ide> def __iter__(self): <ide> yield 0 <ide> else: <ide> heapq.heappush(q, event) <del> yield 1 <add> yield None <ide> <ide> def empty(self): <ide> return not self._queue
1
Ruby
Ruby
switch pkgversion to use composition
27092cabc4bda0904e1616bb2e5d4d949dbd3178
<ide><path>Library/Homebrew/pkg_version.rb <del>require 'version' <add>require "version" <ide> <del>class PkgVersion < Version <del> attr_reader :version, :revision <add>class PkgVersion <add> include Comparable <ide> <ide> RX = /\A(.+?)(?:_(\d+))?\z/ <ide> <ide> def self.parse(path) <ide> _, version, revision = *path.match(RX) <del> new(version, revision) <add> version = Version.new(version) <add> new(version, revision.to_i) <ide> end <ide> <ide> def initialize(version, revision) <del> super(version) <add> @version = version <add> @revision = version.head? ? 0 : revision <add> end <ide> <del> if head? <del> @revision = 0 <del> else <del> @revision = revision.to_i <del> end <add> def head? <add> version.head? <ide> end <ide> <ide> def to_s <ide> if revision > 0 <ide> "#{version}_#{revision}" <ide> else <del> version <add> version.to_s <ide> end <ide> end <ide> alias_method :to_str, :to_s <ide> <ide> def <=>(other) <del> return unless Version === other <del> super.nonzero? || revision <=> other.revision <add> return unless PkgVersion === other <add> (version <=> other.version).nonzero? || revision <=> other.revision <ide> end <add> alias_method :eql?, :== <add> <add> def hash <add> version.hash ^ revision.hash <add> end <add> <add> protected <add> <add> attr_reader :version, :revision <ide> end <ide><path>Library/Homebrew/test/test_pkg_version.rb <ide> def v(version) <ide> end <ide> <ide> def test_parse <del> assert_equal PkgVersion.new("1.0", 1), PkgVersion.parse("1.0_1") <del> assert_equal PkgVersion.new("1.0", 1), PkgVersion.parse("1.0_1") <del> assert_equal PkgVersion.new("1.0", 0), PkgVersion.parse("1.0") <del> assert_equal PkgVersion.new("1.0", 0), PkgVersion.parse("1.0_0") <del> assert_equal PkgVersion.new("2.1.4", 0), PkgVersion.parse("2.1.4_0") <del> assert_equal PkgVersion.new("2.1.4_1", 0), PkgVersion.parse("2.1.4_1_0") <del> assert_equal PkgVersion.new("1.0.1e", 1), PkgVersion.parse("1.0.1e_1") <add> assert_equal PkgVersion.new(Version.new("1.0"), 1), PkgVersion.parse("1.0_1") <add> assert_equal PkgVersion.new(Version.new("1.0"), 1), PkgVersion.parse("1.0_1") <add> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0") <add> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0_0") <add> assert_equal PkgVersion.new(Version.new("2.1.4"), 0), PkgVersion.parse("2.1.4_0") <add> assert_equal PkgVersion.new(Version.new("2.1.4_1"), 0), PkgVersion.parse("2.1.4_1_0") <add> assert_equal PkgVersion.new(Version.new("1.0.1e"), 1), PkgVersion.parse("1.0.1e_1") <ide> end <ide> <ide> def test_comparison <ide> def test_comparison <ide> assert_operator v("HEAD"), :>, v("1.0") <ide> assert_operator v("1.0"), :<, v("HEAD") <ide> <del> v = PkgVersion.new("1.0", 0) <add> v = PkgVersion.new(Version.new("1.0"), 0) <ide> assert_nil v <=> Object.new <ide> assert_raises(ArgumentError) { v > Object.new } <add> assert_raises(ArgumentError) { v > Version.new("1.0") } <ide> end <ide> <ide> def test_to_s <del> assert_equal "1.0", PkgVersion.new("1.0", 0).to_s <del> assert_equal "1.0_1", PkgVersion.new("1.0", 1).to_s <del> assert_equal "1.0", PkgVersion.new("1.0", 0).to_s <del> assert_equal "1.0", PkgVersion.new("1.0", 0).to_s <del> assert_equal "HEAD", PkgVersion.new("HEAD", 1).to_s <add> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <add> assert_equal "1.0_1", PkgVersion.new(Version.new("1.0"), 1).to_s <add> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <add> assert_equal "1.0", PkgVersion.new(Version.new("1.0"), 0).to_s <add> assert_equal "HEAD", PkgVersion.new(Version.new("HEAD"), 1).to_s <ide> end <ide> end
2
Python
Python
fix blank lines around docstrings
a101251a2adbe4c42d28a60732e2b4d505cc624b
<ide><path>rest_framework/decorators.py <ide> <ide> <ide> def api_view(http_method_names=None): <del> <ide> """ <ide> Decorator that converts a function-based view into an APIView subclass. <ide> Takes a list of allowed methods for the view as an argument. <ide><path>rest_framework/generics.py <ide> def get_paginated_response(self, data): <ide> <ide> class CreateAPIView(mixins.CreateModelMixin, <ide> GenericAPIView): <del> <ide> """ <ide> Concrete view for creating a model instance. <ide> """ <ide> def get(self, request, *args, **kwargs): <ide> <ide> class DestroyAPIView(mixins.DestroyModelMixin, <ide> GenericAPIView): <del> <ide> """ <ide> Concrete view for deleting a model instance. <ide> """ <ide> def delete(self, request, *args, **kwargs): <ide> <ide> class UpdateAPIView(mixins.UpdateModelMixin, <ide> GenericAPIView): <del> <ide> """ <ide> Concrete view for updating a model instance. <ide> """ <ide><path>rest_framework/parsers.py <ide> class BaseParser(object): <ide> All parsers should extend `BaseParser`, specifying a `media_type` <ide> attribute, and overriding the `.parse()` method. <ide> """ <del> <ide> media_type = None <ide> <ide> def parse(self, stream, media_type=None, parser_context=None): <ide> class JSONParser(BaseParser): <ide> """ <ide> Parses JSON-serialized data. <ide> """ <del> <ide> media_type = 'application/json' <ide> renderer_class = renderers.JSONRenderer <ide> <ide> class FormParser(BaseParser): <ide> """ <ide> Parser for form data. <ide> """ <del> <ide> media_type = 'application/x-www-form-urlencoded' <ide> <ide> def parse(self, stream, media_type=None, parser_context=None): <ide> class MultiPartParser(BaseParser): <ide> """ <ide> Parser for multipart form data, which may include file data. <ide> """ <del> <ide> media_type = 'multipart/form-data' <ide> <ide> def parse(self, stream, media_type=None, parser_context=None): <ide> def parse(self, stream, media_type=None, parser_context=None): <ide> `.data` will be None (we expect request body to be a file content). <ide> `.files` will be a `QueryDict` containing one 'file' element. <ide> """ <del> <ide> parser_context = parser_context or {} <ide> request = parser_context['request'] <ide> encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) <ide><path>rest_framework/permissions.py <ide> class AllowAny(BasePermission): <ide> permission_classes list, but it's useful because it makes the intention <ide> more explicit. <ide> """ <add> <ide> def has_permission(self, request, view): <ide> return True <ide> <ide> class DjangoObjectPermissions(DjangoModelPermissions): <ide> This permission can only be applied against view classes that <ide> provide a `.queryset` attribute. <ide> """ <del> <ide> perms_map = { <ide> 'GET': [], <ide> 'OPTIONS': [], <ide><path>rest_framework/relations.py <ide> class SlugRelatedField(RelatedField): <ide> A read-write field that represents the target of the relationship <ide> by a unique 'slug' attribute. <ide> """ <del> <ide> default_error_messages = { <ide> 'does_not_exist': _('Object with {slug_name}={value} does not exist.'), <ide> 'invalid': _('Invalid value.'), <ide><path>rest_framework/renderers.py <ide> class BaseRenderer(object): <ide> All renderers should extend this class, setting the `media_type` <ide> and `format` attributes, and override the `.render()` method. <ide> """ <del> <ide> media_type = None <ide> format = None <ide> charset = 'utf-8' <ide> class JSONRenderer(BaseRenderer): <ide> """ <ide> Renderer which serializes to JSON. <ide> """ <del> <ide> media_type = 'application/json' <ide> format = 'json' <ide> encoder_class = encoders.JSONEncoder <ide> class TemplateHTMLRenderer(BaseRenderer): <ide> <ide> For pre-rendered HTML, see StaticHTMLRenderer. <ide> """ <del> <ide> media_type = 'text/html' <ide> format = 'html' <ide> template_name = None <ide><path>rest_framework/request.py <ide> class override_method(object): <ide> with override_method(view, request, 'POST') as request: <ide> ... # Do stuff with `view` and `request` <ide> """ <add> <ide> def __init__(self, view, request, method): <ide> self.view = view <ide> self.request = request <ide> class Request(object): <ide> - authentication_classes(list/tuple). The authentications used to try <ide> authenticating the request's user. <ide> """ <add> <ide> def __init__(self, request, parsers=None, authenticators=None, <ide> negotiator=None, parser_context=None): <ide> self._request = request <ide><path>rest_framework/routers.py <ide> def get_routes(self, viewset): <ide> <ide> Returns a list of the Route namedtuple. <ide> """ <del> <ide> known_actions = flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)]) <ide> <ide> # Determine any `@detail_route` or `@list_route` decorated methods on the viewset <ide><path>rest_framework/throttling.py <ide> class BaseThrottle(object): <ide> """ <ide> Rate throttling of requests. <ide> """ <add> <ide> def allow_request(self, request, view): <ide> """ <ide> Return `True` if the request should be allowed, `False` otherwise. <ide> class SimpleRateThrottle(BaseThrottle): <ide> <ide> Previous request information used for throttling is stored in the cache. <ide> """ <del> <ide> cache = default_cache <ide> timer = time.time <ide> cache_format = 'throttle_%(scope)s_%(ident)s' <ide><path>rest_framework/utils/breadcrumbs.py <ide> def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): <ide> Add tuples of (name, url) to the breadcrumbs list, <ide> progressively chomping off parts of the url. <ide> """ <del> <ide> try: <ide> (view, unused_args, unused_kwargs) = resolve(url) <ide> except Exception:
10
Ruby
Ruby
prevent helper_method from calling to_hash
85f95b2f5806f2a34bfddd08d3002f74df556169
<ide><path>actionpack/lib/abstract_controller/helpers.rb <ide> def helper_method(*methods) <ide> <ide> methods.each do |method| <ide> _helpers.class_eval <<-ruby_eval, file, line <del> def #{method}(*args, **kwargs, &blk) # def current_user(*args, **kwargs, &blk) <del> if kwargs.empty? # if kwargs.empty? <del> controller.send(%(#{method}), *args, &blk) # controller.send(:current_user, *args, &blk) <del> else # else <del> controller.send(%(#{method}), *args, **kwargs, &blk) # controller.send(:current_user, *args, **kwargs, &blk) <del> end # end <del> end # end <add> def #{method}(*args, &blk) # def current_user(*args, &blk) <add> controller.send(%(#{method}), *args, &blk) # controller.send(:current_user, *args, &blk) <add> end # end <add> ruby2_keywords(%(#{method})) if respond_to?(:ruby2_keywords, true) <ide> ruby_eval <ide> end <ide> end <ide><path>actionpack/test/controller/helper_test.rb <ide> class HelperTest < ActiveSupport::TestCase <ide> class TestController < ActionController::Base <ide> attr_accessor :delegate_attr <ide> def delegate_method() end <add> def delegate_method_arg(arg); arg; end <add> def delegate_method_kwarg(hi:); hi; end <ide> end <ide> <ide> def setup <ide> # Increment symbol counter. <ide> @symbol = (@@counter ||= "A0").succ.dup <ide> <ide> # Generate new controller class. <del> controller_class_name = "Helper#{@symbol}Controller" <del> eval("class #{controller_class_name} < TestController; end") <del> @controller_class = self.class.const_get(controller_class_name) <add> @controller_class = Class.new(TestController) <ide> <ide> # Set default test helper. <ide> self.test_helper = LocalAbcHelper <ide> def test_helper_method <ide> assert_includes master_helper_methods, :delegate_method <ide> end <ide> <add> def test_helper_method_arg <add> assert_nothing_raised { @controller_class.helper_method :delegate_method_arg } <add> assert_equal({ hi: :there }, @controller_class.new.helpers.delegate_method_arg({ hi: :there })) <add> end <add> <add> def test_helper_method_arg_does_not_call_to_hash <add> assert_nothing_raised { @controller_class.helper_method :delegate_method_arg } <add> <add> my_class = Class.new do <add> def to_hash <add> { hi: :there } <add> end <add> end.new <add> <add> assert_equal(my_class, @controller_class.new.helpers.delegate_method_arg(my_class)) <add> end <add> <add> def test_helper_method_kwarg <add> assert_nothing_raised { @controller_class.helper_method :delegate_method_kwarg } <add> <add> assert_equal(:there, @controller_class.new.helpers.delegate_method_kwarg(hi: :there)) <add> end <add> <ide> def test_helper_attr <ide> assert_nothing_raised { @controller_class.helper_attr :delegate_attr } <ide> assert_includes master_helper_methods, :delegate_attr
2
PHP
PHP
add docs for new classes
7154b818af7e8d6c7e6f9a3f7d4ed8c5027c519f
<ide><path>src/Error/DumpFormatter/TextFormatter.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpFormatter; <ide> <ide> use Cake\Error\DumpNode\ArrayNode; <ide> use Cake\Error\DumpNode\SpecialNode; <ide> use RuntimeException; <ide> <add>/** <add> * A Debugger formatter for generating unstyled plain text output. <add> * <add> * Provides backwards compatible output with the historical output of <add> * `Debugger::exportVar()` <add> */ <ide> class TextFormatter <ide> { <add> /** <add> * Convert a tree of NodeInterface objects into a plain text string. <add> * <add> * @param \Cake\Error\DumpNode\NodeInterface $node The node tree to dump. <add> * @return string <add> */ <ide> public function dump(NodeInterface $node): string <ide> { <ide> $indent = 0; <add> <ide> return $this->_export($node, $indent); <ide> } <ide> <add> /** <add> * Convert a tree of NodeInterface objects into a plain text string. <add> * <add> * @param \Cake\Error\DumpNode\NodeInterface $node The node tree to dump. <add> * @param int $indent The current indentation level. <add> * @return string <add> */ <ide> protected function _export(NodeInterface $var, int $indent): string <ide> { <ide> if ($var instanceof ScalarNode) { <ide><path>src/Error/DumpNode/ArrayNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for Array values. <add> */ <ide> class ArrayNode implements NodeInterface <ide> { <ide> /** <ide> * @var \Cake\Error\DumpNode\ItemNode[] <ide> */ <ide> private $items; <ide> <add> /** <add> * Constructor <add> * <add> * @param \Cake\Error\DumpNode\ItemNode[] $items The items for the array <add> */ <ide> public function __construct(array $items = []) <ide> { <ide> $this->items = []; <ide> public function __construct(array $items = []) <ide> } <ide> } <ide> <add> /** <add> * Add an item <add> * <add> * @param \Cake\Error\DumpNode\ItemNode <add> * @return void <add> */ <ide> public function add(ItemNode $node): void <ide> { <ide> $this->items[] = $node; <ide> } <ide> <add> /** <add> * Get the contained items <add> * <add> * @return \Cake\Error\DumpNode\ItemNode[] <add> */ <ide> public function getValue(): array <ide> { <ide> return $this->items; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return $this->items; <ide><path>src/Error/DumpNode/ClassNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for objects/class instances. <add> */ <ide> class ClassNode implements NodeInterface <ide> { <ide> /** <ide> class ClassNode implements NodeInterface <ide> */ <ide> private $properties = []; <ide> <add> /** <add> * Constructor <add> * <add> * @param string $class The class name <add> * @param int $id The reference id of this object in the DumpContext <add> */ <ide> public function __construct(string $class, int $id) <ide> { <ide> $this->class = $class; <ide> $this->id = $id; <ide> } <ide> <del> public function addProperty(PropertyNode $node) <add> /** <add> * Add a property <add> * <add> * @param \Cake\Error\DumpNode\PropertyNode $node The property to add. <add> * @return void <add> */ <add> public function addProperty(PropertyNode $node): void <ide> { <ide> $this->properties[] = $node; <ide> } <ide> <add> /** <add> * Get the class name <add> * <add> * @return string <add> */ <ide> public function getValue(): string <ide> { <ide> return $this->class; <ide> } <ide> <add> /** <add> * Get the reference id <add> * <add> * @return int <add> */ <ide> public function getId(): int <ide> { <ide> return $this->id; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return $this->properties; <ide><path>src/Error/DumpNode/ItemNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for Array Items. <add> */ <ide> class ItemNode implements NodeInterface <ide> { <add> /** <add> * @var \Cake\Error\DumpNode\NodeInterface <add> */ <ide> private $key; <add> <add> /** <add> * @var \Cake\Error\DumpNode\NodeInterface <add> */ <ide> private $value; <ide> <add> /** <add> * Constructor <add> * <add> * @param \Cake\Error\DumpNode\NodeInterface $key The node for the item key <add> * @param \Cake\Error\DumpNode\NodeInterface $value The node for the array value <add> */ <ide> public function __construct(NodeInterface $key, NodeInterface $value) <ide> { <ide> $this->key = $key; <ide> $this->value = $value; <ide> } <ide> <add> /** <add> * Get the value <add> * <add> * @return \Cake\Error\DumpNode\NodeInterface <add> */ <ide> public function getValue() <ide> { <ide> return $this->value; <ide> } <ide> <add> /** <add> * Get the key <add> * <add> * @return \Cake\Error\DumpNode\NodeInterface <add> */ <ide> public function getKey() <ide> { <ide> return $this->key; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return [$this->value]; <ide><path>src/Error/DumpNode/NodeInterface.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Interface for DumpNodes <add> * <add> * Provides methods to look at contained value and iterate child nodes in the tree. <add> */ <ide> interface NodeInterface <ide> { <add> /** <add> * Get the child nodes of this node. <add> * <add> * @return \Cake\Error\DumpNode\NodeInterface[] <add> */ <ide> public function getChildren(): array; <ide> <add> /** <add> * Get the contained value. <add> * <add> * @return mixed <add> */ <ide> public function getValue(); <ide> } <ide><path>src/Error/DumpNode/PropertyNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for object properties. <add> */ <ide> class PropertyNode implements NodeInterface <ide> { <add> /** <add> * @var string <add> */ <ide> private $name; <add> <add> /** <add> * @var string <add> */ <ide> private $visibility; <add> <add> /** <add> * @var \Cake\Error\DumpNode\NodeInterface <add> */ <ide> private $value; <ide> <add> /** <add> * Constructor <add> * <add> * @param string $name The property name <add> * @param string $visibility The visibility of the property. <add> * @param \Cake\Error\DumpNode\NodeInterface $value The property value node. <add> */ <ide> public function __construct(string $name, ?string $visibility, NodeInterface $value) <ide> { <ide> $this->name = $name; <ide> $this->visibility = $visibility; <ide> $this->value = $value; <ide> } <ide> <add> /** <add> * Get the value <add> * <add> * @return \Cake\Error\DumpNode\NodeInterface <add> */ <ide> public function getValue(): NodeInterface <ide> { <ide> return $this->value; <ide> } <ide> <add> /** <add> * Get the property visibility <add> * <add> * @return string <add> */ <ide> public function getVisibility(): ?string <ide> { <ide> return $this->visibility; <ide> } <ide> <add> /** <add> * Get the property name <add> * <add> * @return string <add> */ <ide> public function getName(): string <ide> { <ide> return $this->name; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return [$this->value]; <ide><path>src/Error/DumpNode/ReferenceNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for class references. <add> * <add> * To prevent cyclic references from being output multiple times <add> * a reference node can be used after an object has been seen the <add> * first time. <add> */ <ide> class ReferenceNode implements NodeInterface <ide> { <add> /** <add> * @var string <add> */ <ide> private $class; <add> <add> /** <add> * @var int <add> */ <ide> private $id; <ide> <add> /** <add> * Constructor <add> * <add> * @param string $class The class name <add> * @param int $id The id of the referenced class. <add> */ <ide> public function __construct(string $class, int $id) <ide> { <ide> $this->class = $class; <ide> $this->id = $id; <ide> } <ide> <add> /** <add> * Get the class name/value <add> * <add> * @return string <add> */ <ide> public function getValue(): string <ide> { <ide> return $this->class; <ide> } <ide> <add> /** <add> * Get the reference id for this node. <add> * <add> * @return int <add> */ <ide> public function getId(): int <ide> { <ide> return $this->id; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return []; <ide><path>src/Error/DumpNode/ScalarNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for scalar values. <add> */ <ide> class ScalarNode implements NodeInterface <ide> { <ide> /** <ide> class ScalarNode implements NodeInterface <ide> */ <ide> private $value; <ide> <add> /** <add> * Constructor <add> * <add> * @param string $type The type of scalar value. <add> * @param string|int|float|bool|null $value The wrapped value. <add> */ <ide> public function __construct(string $type, $value) <ide> { <ide> $this->type = $type; <ide> $this->value = $value; <ide> } <ide> <add> /** <add> * Get the type of value <add> * <add> * @return string <add> */ <ide> public function getType(): string <ide> { <ide> return $this->type; <ide> } <ide> <add> /** <add> * Get the value <add> * <add> * @return string|int|float|bool|null <add> */ <ide> public function getValue() <ide> { <ide> return $this->value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return []; <ide><path>src/Error/DumpNode/SpecialNode.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <ide> namespace Cake\Error\DumpNode; <ide> <add>/** <add> * Dump node for special messages like errors or recursion warnings. <add> */ <ide> class SpecialNode implements NodeInterface <ide> { <ide> /** <ide> * @var string <ide> */ <ide> private $value; <ide> <add> /** <add> * Constructor <add> * <add> * @param string $value The message/value to include in dump results. <add> */ <ide> public function __construct(string $value) <ide> { <ide> $this->value = $value; <ide> } <ide> <add> /** <add> * Get the message/value <add> * <add> * @return string <add> */ <ide> public function getValue(): string <ide> { <ide> return $this->value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getChildren(): array <ide> { <ide> return [];
9
Text
Text
fix mkdir typo in dockerfile_best-practices.md
b95f9c10ff2bd05fc2d30b30bebb8174883c683a
<ide><path>docs/sources/articles/dockerfile_best-practices.md <ide> things like: <ide> <ide> And instead, do something like: <ide> <del> RUN mdkir -p /usr/src/things \ <add> RUN mkdir -p /usr/src/things \ <ide> && curl -SL http://example.com/big.tar.gz \ <ide> | tar -xJC /usr/src/things \ <ide> && make -C /usr/src/things all
1
PHP
PHP
add plugin. prefix for plugin files
72d0105e209bc1b40bbedc9bc9a99b33736a3ace
<ide><path>lib/Cake/Core/App.php <ide> public static function load($className) { <ide> return false; <ide> } <ide> <del> if ($file = self::_mapped($className)) { <del> return include $file; <del> } <del> <ide> $parts = explode('.', self::$_classMap[$className], 2); <ide> list($plugin, $package) = count($parts) > 1 ? $parts : array(null, current($parts)); <add> <add> if ($file = self::_mapped($className, $plugin)) { <add> return include $file; <add> } <ide> $paths = self::path($package, $plugin); <ide> <ide> if (empty($plugin)) { <ide> public static function load($className) { <ide> foreach ($paths as $path) { <ide> $file = $path . $className . '.php'; <ide> if (file_exists($file)) { <del> self::_map($file, $className); <add> self::_map($file, $className, $plugin); <ide> return include $file; <ide> } <ide> } <ide> public static function init() { <ide> * @return void <ide> */ <ide> protected static function _map($file, $name, $plugin = null) { <add> $key = $name; <ide> if ($plugin) { <del> self::$_map['Plugin'][$plugin][$name] = $file; <del> } else { <del> self::$_map[$name] = $file; <add> $key = 'plugin.' . $name; <add> } <add> if ($plugin && empty(self::$_map[$name])) { <add> self::$_map[$key] = $file; <add> } <add> if (!$plugin && empty(self::$_map['plugin.' . $name])) { <add> self::$_map[$key] = $file; <ide> } <ide> if (!self::$bootstrapping) { <ide> self::$_cacheChange = true; <ide> protected static function _map($file, $name, $plugin = null) { <ide> * @return mixed file path if found, false otherwise <ide> */ <ide> protected static function _mapped($name, $plugin = null) { <add> $key = $name; <ide> if ($plugin) { <del> if (isset(self::$_map['Plugin'][$plugin][$name])) { <del> return self::$_map['Plugin'][$plugin][$name]; <del> } <del> return false; <add> $key = 'plugin.' . $name; <ide> } <del> <del> if (isset(self::$_map[$name])) { <del> return self::$_map[$name]; <del> } <del> return false; <add> return isset(self::$_map[$key]) ? self::$_map[$name] : false; <ide> } <ide> <ide> /**
1
Javascript
Javascript
increase readstream buffersize to 64k
24ac87f5437e067e01fc10d71ba4ee58f9ca1994
<ide><path>lib/fs.js <ide> var binding = process.binding('fs'); <ide> var fs = exports; <ide> <ide> var kMinPoolSpace = 128; <del>var kPoolSize = 40*1024; <add>var kPoolSize = 40 * 1024; <ide> <ide> fs.Stats = binding.Stats; <ide> <ide> var ReadStream = fs.ReadStream = function(path, options) { <ide> <ide> this.flags = 'r'; <ide> this.mode = 0666; <del> this.bufferSize = 4 * 1024; <add> this.bufferSize = 64 * 1024; <ide> <ide> options = options || {}; <ide>
1
Text
Text
add note for hardware keyboard in simulator
64c11433a16935e89c1b568e5df222454189ba65
<ide><path>docs/GettingStarted.md <ide> In the newly created folder `AwesomeProject/` <ide> - Open `index.ios.js` in your text editor of choice and edit some lines <ide> - Hit cmd+R ([twice](http://openradar.appspot.com/19613391)) in your iOS simulator to reload the app and see your change! <ide> <add>If Cmd-R is not responding, enable iOS simulator's "Connect hardware keyboard" from menu Hardware > Keyboard menu. <add> <add>![keyboard menu](https://cloud.githubusercontent.com/assets/1388454/6863127/03837824-d409-11e4-9251-e05bd31d978f.png) <add> <ide> Congratulations! You've just successfully run and modified your first React Native app. <ide>
1
PHP
PHP
remove type hint
1b3f62aaeced2c9761a6052a7f0d3c1a046851c9
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php <ide> public static function fromRawAttributes(Model $parent, $attributes, $table, $ex <ide> * @param \Illuminate\Database\Eloquent\Builder $query <ide> * @return \Illuminate\Database\Eloquent\Builder <ide> */ <del> protected function setKeysForSaveQuery(Builder $query) <add> protected function setKeysForSaveQuery($query) <ide> { <ide> if (isset($this->attributes[$this->getKeyName()])) { <ide> return parent::setKeysForSaveQuery($query); <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphPivot.php <ide> class MorphPivot extends Pivot <ide> * @param \Illuminate\Database\Eloquent\Builder $query <ide> * @return \Illuminate\Database\Eloquent\Builder <ide> */ <del> protected function setKeysForSaveQuery(Builder $query) <add> protected function setKeysForSaveQuery($query) <ide> { <ide> $query->where($this->morphType, $this->morphClass); <ide>
2
Text
Text
release notes for 1.3.0-beta.8 accidental-haiku
be7c02c316dd1fbb8277851405e78a4cb1c283f1
<ide><path>CHANGELOG.md <add><a name="1.3.0-beta.8"></a> <add># 1.3.0-beta.8 accidental-haiku (2014-05-09) <add> <add> <add>## Bug Fixes <add> <add>- **$compile:** set $isolateScope correctly for sync template directives <add> ([562c4e42](https://github.com/angular/angular.js/commit/562c4e424b0ed5f8d4bffba0cd18e66db2059043), <add> [#6942](https://github.com/angular/angular.js/issues/6942)) <add>- **$httpBackend:** Add missing expectHEAD() method <add> ([e1d61784](https://github.com/angular/angular.js/commit/e1d6178457045e721872022f71227b277cb88726), <add> [#7320](https://github.com/angular/angular.js/issues/7320)) <add>- **$interpolate:** don't ReferenceError when context is undefined <add> ([924ee6db](https://github.com/angular/angular.js/commit/924ee6db06a2518224caada86769efedd21c0710), <add> [#7230](https://github.com/angular/angular.js/issues/7230), [#7237](https://github.com/angular/angular.js/issues/7237)) <add>- **grunt-utils:** ensure special inline CSS works when `angular` is not a global <add> ([af72f40a](https://github.com/angular/angular.js/commit/af72f40a5512daa97c1f175a59b547c33cff1dc0), <add> [#7176](https://github.com/angular/angular.js/issues/7176)) <add>- **injector:** invoke config blocks for module after all providers <add> ([c0b4e2db](https://github.com/angular/angular.js/commit/c0b4e2db9cbc8bc3164cedc4646145d3ab72536e), <add> [#7139](https://github.com/angular/angular.js/issues/7139), [#7147](https://github.com/angular/angular.js/issues/7147)) <add>- **ngModelOptions:** <add> - enable overriding the default with a debounce of zero <add> ([c56e32a7](https://github.com/angular/angular.js/commit/c56e32a7fa44e2edd2c70f663906720c7c9ad898), <add> [#7205](https://github.com/angular/angular.js/issues/7205)) <add> - initialize ngModelOptions in prelink <add> ([fbf5ab8f](https://github.com/angular/angular.js/commit/fbf5ab8f17d28efeadb492c5a252f0778643f072), <add> [#7281](https://github.com/angular/angular.js/issues/7281), [#7292](https://github.com/angular/angular.js/issues/7292)) <add>- **ngSanitize:** encode surrogate pair properly <add> ([627b0354](https://github.com/angular/angular.js/commit/627b0354ec35bef5c6dbfab6469168c2fadcbee5), <add> [#5088](https://github.com/angular/angular.js/issues/5088), [#6911](https://github.com/angular/angular.js/issues/6911)) <add>- **ngSrc, ngSrcset:** only interpolate if all expressions are defined <add> ([8d180383](https://github.com/angular/angular.js/commit/8d180383014cbe38d58ff3eab083f51cfcfb8dde), <add> [#6984](https://github.com/angular/angular.js/issues/6984)) <add>- **ngSwitch:** properly support case labels with different numbers of transclude fns <add> ([ac37915e](https://github.com/angular/angular.js/commit/ac37915ef64c60ec8f8d4e49e4d61d7baeb96ba0), <add> [#7372](https://github.com/angular/angular.js/issues/7372), [#7373](https://github.com/angular/angular.js/issues/7373)) <add> <add> <add>## Features <add> <add>- **$compile:** allow SVG and MathML templates via special `type` property <add> ([f0e12ea7](https://github.com/angular/angular.js/commit/f0e12ea7fea853192e4eead00b40d6041c5f914a), <add> [#7265](https://github.com/angular/angular.js/issues/7265)) <add>- **$interpolate:** add optional allOrNothing param <add> ([c2362e3f](https://github.com/angular/angular.js/commit/c2362e3f45e732a9defdb0ea59ce4ec5236fcd3a)) <add>- **FormController:** commit `$viewValue` of all child controls when form is submitted <add> ([a0ae07bd](https://github.com/angular/angular.js/commit/a0ae07bd4ee8d98654df4eb261d16ca55884e374), <add> [#7017](https://github.com/angular/angular.js/issues/7017)) <add>- **NgMessages:** introduce the NgMessages module and directives <add> ([0f4016c8](https://github.com/angular/angular.js/commit/0f4016c84a47e01a0fb993867dfd0a64828c089c)) <add> <add> <add>## Breaking Changes <add> <add>- **$http:** due to [ad4336f9](https://github.com/angular/angular.js/commit/ad4336f9359a073e272930f8f9bcd36587a8648f), <add> <add> <add>Previously, it was possible to register a response interceptor like so: <add> <add>```js <add>// register the interceptor as a service <add>$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { <add> return function(promise) { <add> return promise.then(function(response) { <add> // do something on success <add> return response; <add> }, function(response) { <add> // do something on error <add> if (canRecover(response)) { <add> return responseOrNewPromise <add> } <add> return $q.reject(response); <add> }); <add> } <add>}); <add> <add>$httpProvider.responseInterceptors.push('myHttpInterceptor'); <add>``` <add> <add>Now, one must use the newer API introduced in v1.1.4 (4ae46814), like so: <add> <add>```js <add>$provide.factory('myHttpInterceptor', function($q) { <add> return { <add> response: function(response) { <add> // do something on success <add> return response; <add> }, <add> responseError: function(response) { <add> // do something on error <add> if (canRecover(response)) { <add> return responseOrNewPromise <add> } <add> return $q.reject(response); <add> } <add> }; <add>}); <add> <add>$httpProvider.interceptors.push('myHttpInterceptor'); <add>``` <add> <add>More details on the new interceptors API (which has been around as of v1.1.4) can be found at <add>https://docs.angularjs.org/api/ng/service/$http#interceptors <add> <add> <add>- **injector:** due to [c0b4e2db](https://github.com/angular/angular.js/commit/c0b4e2db9cbc8bc3164cedc4646145d3ab72536e), <add> <add>Previously, config blocks would be able to control behaviour of provider registration, due to being <add>invoked prior to provider registration. Now, provider registration always occurs prior to configuration <add>for a given module, and therefore config blocks are not able to have any control over a providers <add>registration. <add> <add>**Example**: <add> <add>Previously, the following: <add> <add>```js <add>angular.module('foo', []) <add> .provider('$rootProvider', function() { <add> this.$get = function() { ... } <add> }) <add> .config(function($rootProvider) { <add> $rootProvider.dependentMode = "B"; <add> }) <add> .provider('$dependentProvider', function($rootProvider) { <add> if ($rootProvider.dependentMode === "A") { <add> this.$get = function() { <add> // Special mode! <add> } <add> } else { <add> this.$get = function() { <add> // something else <add> } <add> } <add> }); <add>``` <add> <add>would have "worked", meaning behaviour of the config block between the registration of "$rootProvider" <add>and "$dependentProvider" would have actually accomplished something and changed the behaviour of the <add>app. This is no longer possible within a single module. <add> <add> <add>- **ngModelOptions:** due to [adfc322b](https://github.com/angular/angular.js/commit/adfc322b04a58158fb9697e5b99aab9ca63c80bb), <add> <add> <add>This commit changes the API on `NgModelController`, both semantically and <add>in terms of adding and renaming methods. <add> <add>* `$setViewValue(value)` - <add>This method still changes the `$viewValue` but does not immediately commit this <add>change through to the `$modelValue` as it did previously. <add>Now the value is committed only when a trigger specified in an associated <add>`ngModelOptions` directive occurs. If `ngModelOptions` also has a `debounce` delay <add>specified for the trigger then the change will also be debounced before being <add>committed. <add>In most cases this should not have a significant impact on how `NgModelController` <add>is used: If `updateOn` includes `default` then `$setViewValue` will trigger <add>a (potentially debounced) commit immediately. <add>* `$cancelUpdate()` - is renamed to `$rollbackViewValue()` and has the same meaning, <add>which is to revert the current `$viewValue` back to the `$lastCommittedViewValue`, <add>to cancel any pending debounced updates and to re-render the input. <add> <add>To migrate code that used `$cancelUpdate()` follow the example below: <add> <add>Before: <add> <add>```js <add>$scope.resetWithCancel = function (e) { <add> if (e.keyCode == 27) { <add> $scope.myForm.myInput1.$cancelUpdate(); <add> $scope.myValue = ''; <add> } <add>}; <add>``` <add> <add>After: <add> <add>```js <add>$scope.resetWithCancel = function (e) { <add> if (e.keyCode == 27) { <add> $scope.myForm.myInput1.$rollbackViewValue(); <add> $scope.myValue = ''; <add> } <add>} <add>``` <add> <add> <ide> <a name="v1.3.0-beta.7"></a> <ide> # v1.3.0-beta.7 proper-attribution (2014-04-25) <ide>
1
Text
Text
add subheadings for these sections [ci skip]
cd01f9f9c5df06f74e1acdb55f0c6e5110ea0daf
<ide><path>guides/source/testing.md <ide> This will run all test methods from the test case. <ide> <ide> The `.` (dot) above indicates a passing test. When a test fails you see an `F`; when a test throws an error you see an `E` in its place. The last line of the output is the summary. <ide> <add>#### Your first failing test <add> <ide> To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case. <ide> <ide> ```ruby <ide> Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s. <ide> <ide> Now, if you noticed, we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). <ide> <add>#### What an error looks like <add> <ide> To see how an error gets reported, here's a test containing an error: <ide> <ide> ```ruby
1
Java
Java
deprecate unused method
706446a66018a2042bc1ba572f3f6b53dbfa253c
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketHttpHeaders.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.CollectionUtils; <add>import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> * An {@link org.springframework.http.HttpHeaders} variant that adds support for <ide> public class WebSocketHttpHeaders extends HttpHeaders { <ide> * Create a new instance. <ide> */ <ide> public WebSocketHttpHeaders() { <del> this(new HttpHeaders(), false); <add> this(new HttpHeaders()); <ide> } <ide> <ide> /** <ide> public WebSocketHttpHeaders() { <ide> * @param headers the HTTP headers to wrap <ide> */ <ide> public WebSocketHttpHeaders(HttpHeaders headers) { <del> this(headers, false); <del> } <del> <del> /** <del> * Private constructor that can create read-only {@code WebSocketHttpHeader} instances. <del> */ <del> private WebSocketHttpHeaders(HttpHeaders headers, boolean readOnly) { <del> this.headers = readOnly ? HttpHeaders.readOnlyHttpHeaders(headers) : headers; <add> this.headers = headers; <ide> } <ide> <ide> /** <ide> * Returns {@code WebSocketHttpHeaders} object that can only be read, not written to. <add> * @deprecated as of 5.2.7 in favor of {@link HttpHeaders#readOnlyHttpHeaders(MultiValueMap)} <ide> */ <add> @Deprecated <ide> public static WebSocketHttpHeaders readOnlyWebSocketHttpHeaders(WebSocketHttpHeaders headers) { <del> return new WebSocketHttpHeaders(headers, true); <add> return new WebSocketHttpHeaders(HttpHeaders.readOnlyHttpHeaders(headers)); <ide> } <ide> <ide>
1
Javascript
Javascript
allow webpack.config.js in watch test
0d0f7e0062fd9684dd1d96a3f7fcb4ab4cf613a3
<ide><path>test/WatchTestCases.test.js <ide> describe("WatchTestCases", function() { <ide> describe(testName, function() { <ide> var tempDirectory = path.join(__dirname, "js", "watch-src", category.name, testName); <ide> var testDirectory = path.join(casesPath, category.name, testName); <del> var runs = fs.readdirSync(testDirectory).sort().map(function(name) { <add> var runs = fs.readdirSync(testDirectory).sort().filter(function(name) { <add> return fs.statSync(path.join(testDirectory, name)).isDirectory(); <add> }).map(function(name) { <ide> return { <ide> name: name, <ide> suite: describe(name, function() {}) <ide> describe("WatchTestCases", function() { <ide> this.timeout(30000); <ide> var outputDirectory = path.join(__dirname, "js", "watch", category.name, testName); <ide> <del> var options = { <del> context: tempDirectory, <del> entry: "./index.js", <del> output: { <del> path: outputDirectory, <del> pathinfo: true, <del> filename: "bundle.js" <del> } <del> }; <add> var options = {}; <add> var configPath = path.join(testDirectory, "webpack.config.js"); <add> if(fs.existsSync(configPath)) <add> options = require(configPath); <add> if(!options.context) options.context = tempDirectory; <add> if(!options.entry) options.entry = "./index.js"; <add> if(!options.target) options.target = "async-node"; <add> if(!options.output) options.output = {}; <add> if(!options.output.path) options.output.path = outputDirectory; <add> if(typeof options.output.pathinfo === "undefined") options.output.pathinfo = true; <add> if(!options.output.filename) options.output.filename = "bundle.js"; <ide> <ide> var runIdx = 0; <ide> var run = runs[runIdx];
1
Ruby
Ruby
update some references to finder options [ci skip]
c5ee0ba6e2f130d89360af4ec10a5f48202f0f1e
<ide><path>activerecord/lib/active_record/errors.rb <ide> class ValueTooLong < StatementInvalid <ide> class RangeError < StatementInvalid <ide> end <ide> <del> # Raised when number of bind variables in statement given to +:condition+ key <del> # (for example, when using {ActiveRecord::Base.find}[rdoc-ref:FinderMethods#find] method) <del> # does not match number of expected values supplied. <add> # Raised when the number of placeholders in an SQL fragment passed to <add> # {ActiveRecord::Base.where}[rdoc-ref:QueryMethods#where] <add> # does not match the number of values supplied. <ide> # <ide> # For example, when there are two placeholders with only one value supplied: <ide> # <ide><path>activerecord/lib/active_record/relation/finder_methods.rb <ide> def second_to_last! <ide> # * Integer - Finds the record with this primary key. <ide> # * String - Finds the record with a primary key corresponding to this <ide> # string (such as <tt>'5'</tt>). <del> # * Array - Finds the record that matches these +find+-style conditions <add> # * Array - Finds the record that matches these +where+-style conditions <ide> # (such as <tt>['name LIKE ?', "%#{query}%"]</tt>). <del> # * Hash - Finds the record that matches these +find+-style conditions <add> # * Hash - Finds the record that matches these +where+-style conditions <ide> # (such as <tt>{name: 'David'}</tt>). <ide> # * +false+ - Returns always +false+. <ide> # * No args - Returns +false+ if the relation is empty, +true+ otherwise.
2
Ruby
Ruby
fix rubocop warnings
f421374af1c70880e8e3abf0362f3efb55f62baf
<ide><path>Library/Homebrew/os/mac/sdk.rb <ide> def sdk_for(v) <ide> def latest_sdk <ide> return if sdk_paths.empty? <ide> <del> v, path = sdk_paths.max {|a, b| OS::Mac::Version.new(a[0]) <=> OS::Mac::Version.new(b[0])} <add> v, path = sdk_paths.max { |a, b| OS::Mac::Version.new(a[0]) <=> OS::Mac::Version.new(b[0]) } <ide> SDK.new v, path <ide> end <ide>
1
Python
Python
remove polybase from np.polynomial.polyutils
7a9c663c2b6b1b636de56607485260e935ed6450
<ide><path>numpy/polynomial/polyutils.py <ide> This module provides: error and warning objects; a polynomial base class; <ide> and some routines used in both the `polynomial` and `chebyshev` modules. <ide> <del>Error objects <del>------------- <del> <del>.. autosummary:: <del> :toctree: generated/ <del> <del> PolyError base class for this sub-package's errors. <del> PolyDomainError raised when domains are mismatched. <del> <ide> Warning objects <ide> --------------- <ide> <ide> import numpy as np <ide> <ide> __all__ = [ <del> 'RankWarning', 'PolyError', 'PolyDomainError', 'as_series', 'trimseq', <add> 'RankWarning', 'as_series', 'trimseq', <ide> 'trimcoef', 'getdomain', 'mapdomain', 'mapparms'] <ide> <ide> # <ide> class RankWarning(UserWarning): <ide> """Issued by chebfit when the design matrix is rank deficient.""" <ide> pass <ide> <del>class PolyError(Exception): <del> """Base class for errors in this module.""" <del> pass <del> <del>class PolyDomainError(PolyError): <del> """Issued by the generic Poly class when two domains don't match. <del> <del> This is raised when an binary operation is passed Poly objects with <del> different domains. <del> <del> """ <del> pass <del> <del> <ide> # <ide> # Helper functions to convert inputs to 1-D arrays <ide> #
1
PHP
PHP
move ability map to a method
d0b5291098d856c3fb07075197feb165efb65c07
<ide><path>src/Illuminate/Foundation/Auth/Access/AuthorizesResources.php <ide> <ide> trait AuthorizesResources <ide> { <del> /** <del> * Map of resource methods to ability names. <del> * <del> * @var array <del> */ <del> protected $resourceAbilityMap = [ <del> 'index' => 'view', <del> 'create' => 'create', <del> 'store' => 'create', <del> 'show' => 'view', <del> 'edit' => 'update', <del> 'update' => 'update', <del> 'delete' => 'delete', <del> ]; <del> <ide> /** <ide> * Authorize a resource action based on the incoming request. <ide> * <ide> public function authorizeResource($model, $name = null, array $options = [], $re <ide> { <ide> $method = array_last(explode('@', with($request ?: request())->route()->getActionName())); <ide> <del> if (! in_array($method, array_keys($this->resourceAbilityMap))) { <add> $map = $this->resourceAbilityMap(); <add> <add> if (! in_array($method, array_keys($map))) { <ide> return new ControllerMiddlewareOptions($options); <ide> } <ide> <ide> if (! in_array($method, ['index', 'create', 'store'])) { <ide> $model = $name ?: strtolower(class_basename($model)); <ide> } <ide> <del> return $this->middleware("can:{$this->resourceAbilityMap[$method]},{$model}", $options); <add> return $this->middleware("can:{$map[$method]},{$model}", $options); <add> } <add> <add> /** <add> * Get the map of resource methods to ability names. <add> * <add> * @return array <add> */ <add> protected function resourceAbilityMap() <add> { <add> return [ <add> 'index' => 'view', <add> 'create' => 'create', <add> 'store' => 'create', <add> 'show' => 'view', <add> 'edit' => 'update', <add> 'update' => 'update', <add> 'delete' => 'delete', <add> ]; <ide> } <ide> }
1
Python
Python
fix a comment error for maxnorm constraint
f1e14ef9c57da498f37b8fe9ac7fe86bff0b3f76
<ide><path>keras/constraints.py <ide> class MaxNorm(Constraint): <ide> to have a norm less than or equal to a desired value. <ide> <ide> # Arguments <del> m: the maximum norm for the incoming weights. <add> max_value: the maximum norm for the incoming weights. <ide> axis: integer, axis along which to calculate weight norms. <ide> For instance, in a `Dense` layer the weight matrix <ide> has shape `(input_dim, output_dim)`,
1
Javascript
Javascript
improve dns lookup coverage
2d138965971109ddf6a583f78e5cdc3026c5f7f4
<ide><path>test/parallel/test-dns-lookup-promises.js <add>// Flags: --expose-internals <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const { internalBinding } = require('internal/test/binding'); <add>const cares = internalBinding('cares_wrap'); <add> <add>// Stub `getaddrinfo` to proxy its call dynamic stub. This has to be done before <add>// we load the `dns` module to guarantee that the `dns` module uses the stub. <add>let getaddrinfoStub = null; <add>cares.getaddrinfo = (req) => getaddrinfoStub(req); <add> <add>const dnsPromises = require('dns').promises; <add> <add>function getaddrinfoNegative() { <add> return function getaddrinfoNegativeHandler(req) { <add> const originalReject = req.reject; <add> req.resolve = common.mustNotCall(); <add> req.reject = common.mustCall(originalReject); <add> req.oncomplete(internalBinding('uv').UV_ENOMEM); <add> }; <add>} <add> <add>function getaddrinfoPositive(addresses) { <add> return function getaddrinfo_positive(req) { <add> const originalResolve = req.resolve; <add> req.reject = common.mustNotCall(); <add> req.resolve = common.mustCall(originalResolve); <add> req.oncomplete(null, addresses); <add> }; <add>} <add> <add>async function lookupPositive() { <add> [ <add> { <add> stub: getaddrinfoPositive(['::1']), <add> factory: () => dnsPromises.lookup('example.com'), <add> expectation: { address: '::1', family: 6 } <add> }, <add> { <add> stub: getaddrinfoPositive(['127.0.0.1']), <add> factory: () => dnsPromises.lookup('example.com'), <add> expectation: { address: '127.0.0.1', family: 4 } <add> }, <add> { <add> stub: getaddrinfoPositive(['127.0.0.1'], { family: 4 }), <add> factory: () => dnsPromises.lookup('example.com'), <add> expectation: { address: '127.0.0.1', family: 4 } <add> }, <add> { <add> stub: getaddrinfoPositive(['some-address']), <add> factory: () => dnsPromises.lookup('example.com'), <add> expectation: { address: 'some-address', family: 0 } <add> }, <add> { <add> stub: getaddrinfoPositive(['some-address2']), <add> factory: () => dnsPromises.lookup('example.com', { family: 6 }), <add> expectation: { address: 'some-address2', family: 6 } <add> } <add> ].forEach(async ({ stub, factory, expectation }) => { <add> getaddrinfoStub = stub; <add> assert.deepStrictEqual(await factory(), expectation); <add> }); <add>} <add> <add>async function lookupNegative() { <add> getaddrinfoStub = getaddrinfoNegative(); <add> const expected = { <add> code: 'ENOMEM', <add> hostname: 'example.com', <add> syscall: 'getaddrinfo' <add> }; <add> return assert.rejects(dnsPromises.lookup('example.com'), expected); <add>} <add> <add>async function lookupallPositive() { <add> [ <add> { <add> stub: getaddrinfoPositive(['::1', '::2']), <add> factory: () => dnsPromises.lookup('example', { all: true }), <add> expectation: [ <add> { address: '::1', family: 6 }, <add> { address: '::2', family: 6 } <add> ] <add> }, <add> { <add> stub: getaddrinfoPositive(['::1', '::2']), <add> factory: () => dnsPromises.lookup('example', { all: true, family: 4 }), <add> expectation: [ <add> { address: '::1', family: 4 }, <add> { address: '::2', family: 4 } <add> ] <add> }, <add> { <add> stub: getaddrinfoPositive(['127.0.0.1', 'some-address']), <add> factory: () => dnsPromises.lookup('example', { all: true }), <add> expectation: [ <add> { address: '127.0.0.1', family: 4 }, <add> { address: 'some-address', family: 0 } <add> ] <add> }, <add> { <add> stub: getaddrinfoPositive(['127.0.0.1', 'some-address']), <add> factory: () => dnsPromises.lookup('example', { all: true, family: 6 }), <add> expectation: [ <add> { address: '127.0.0.1', family: 6 }, <add> { address: 'some-address', family: 6 } <add> ] <add> }, <add> { <add> stub: getaddrinfoPositive([]), <add> factory: () => dnsPromises.lookup('example', { all: true }), <add> expectation: [] <add> } <add> ].forEach(async ({ stub, factory, expectation }) => { <add> getaddrinfoStub = stub; <add> assert.deepStrictEqual(await factory(), expectation); <add> }); <add>} <add> <add>async function lookupallNegative() { <add> getaddrinfoStub = getaddrinfoNegative(); <add> const expected = { <add> code: 'ENOMEM', <add> hostname: 'example.com', <add> syscall: 'getaddrinfo' <add> }; <add> return assert.rejects(dnsPromises.lookup('example.com', { all: true }), <add> expected); <add>} <add> <add>(async () => { <add> await Promise.all([ <add> lookupPositive(), <add> lookupNegative(), <add> lookupallPositive(), <add> lookupallNegative() <add> ]).then(common.mustCall()); <add>})();
1
Ruby
Ruby
deprecate some more legacy
a5445fd9c50161b8ccf2b36fcd26025882f73eaa
<ide><path>activemodel/lib/active_model/validations.rb <ide> def validation_method(on) <ide> end <ide> end <ide> <del> # The validation process on save can be skipped by passing false. The regular Base#save method is <del> # replaced with this when the validations module is mixed in, which it is by default. <del> def save_with_validation(perform_validation = true) <del> if perform_validation && valid? || !perform_validation <del> save_without_validation <del> else <del> false <del> end <del> end <del> <del> # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false <del> # if the record is not valid. <del> def save_with_validation! <del> if valid? <del> save_without_validation! <del> else <del> raise RecordInvalid.new(self) <del> end <del> end <del> <del> # Updates a single attribute and saves the record without going through the normal validation procedure. <del> # This is especially useful for boolean flags on existing records. The regular +update_attribute+ method <del> # in Base is replaced with this when the validations module is mixed in, which it is by default. <del> def update_attribute_with_validation_skipping(name, value) <del> send(name.to_s + '=', value) <del> save(false) <del> end <ide> <ide> # Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false. <ide> def valid? <ide> errors.clear <ide> <ide> run_callbacks(:validate) <del> validate <add> <add> if responds_to?(:validate) <add> ActiveSupport::Deprecations.warn "Base#validate has been deprecated, please use Base.validate :method instead" <add> validate <add> end <ide> <ide> if new_record? <ide> run_callbacks(:validate_on_create) <del> validate_on_create <add> <add> if responds_to?(:validate_on_create) <add> ActiveSupport::Deprecations.warn( <add> "Base#validate_on_create has been deprecated, please use Base.validate :method, :on => :create instead") <add> validate_on_create <add> end <ide> else <ide> run_callbacks(:validate_on_update) <del> validate_on_update <add> <add> if responds_to?(:validate_on_update) <add> ActiveSupport::Deprecations.warn( <add> "Base#validate_on_update has been deprecated, please use Base.validate :method, :on => :update instead") <add> validate_on_update <add> end <ide> end <ide> <ide> errors.empty? <ide> end <ide> <ide> # Returns the Errors object that holds all information about attribute error messages. <ide> def errors <del> @errors ||= Errors.new(self) <add> @errors ||= Errors.new <ide> end <del> <del> protected <del> # Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes. <del> def validate #:doc: <del> end <del> <del> # Overwrite this method for validation checks used only on creation. <del> def validate_on_create #:doc: <del> end <del> <del> # Overwrite this method for validation checks used only on updates. <del> def validate_on_update # :doc: <del> end <ide> end <del>end <add>end <ide>\ No newline at end of file
1
Go
Go
skip some if non-root
16670ed4842b1ee4853ba39b6ebf2b771d28db9a
<ide><path>daemon/daemon_linux_test.go <ide> func checkMounted(t *testing.T, p string, expect bool) { <ide> } <ide> <ide> func TestRootMountCleanup(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> t.Parallel() <ide> <ide> testRoot, err := ioutil.TempDir("", t.Name()) <ide><path>daemon/daemon_test.go <ide> func TestValidContainerNames(t *testing.T) { <ide> } <ide> <ide> func TestContainerInitDNS(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") // for chown <add> } <add> <ide> tmp, err := ioutil.TempDir("", "docker-container-test-") <ide> if err != nil { <ide> t.Fatal(err) <ide><path>daemon/reload_test.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "os" <ide> "reflect" <ide> "sort" <ide> "testing" <ide> func TestDaemonDiscoveryReloadOnlyClusterAdvertise(t *testing.T) { <ide> } <ide> <ide> func TestDaemonReloadNetworkDiagnosticPort(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <ide> daemon := &Daemon{ <ide> imageService: images.NewImageService(images.ImageServiceConfig{}), <ide> }
3
Javascript
Javascript
increase coverage for worker
565663e0468ccabeb589bc8a01ea3cc499e692e7
<ide><path>test/parallel/test-worker-execargv-invalid.js <ide> const { Worker } = require('worker_threads'); <ide> new Worker(__filename, { execArgv: ['--redirect-warnings'] }); <ide> }, expectedErr); <ide> } <add> <add>{ <add> const expectedErr = { <add> code: 'ERR_WORKER_INVALID_EXEC_ARGV', <add> name: 'Error' <add> }; <add> assert.throws(() => { <add> new Worker(__filename, { <add> env: { <add> NODE_OPTIONS: '--nonexistent-options' <add> } <add> }); <add> }, expectedErr); <add>}
1
Ruby
Ruby
avoid unnecessary serialize calls after save
5e62c194e5e2a4f7be4839ad4a61a2114155e5df
<ide><path>activemodel/lib/active_model/attribute.rb <ide> def original_value <ide> end <ide> <ide> def value_for_database <del> type.serialize(value) <add> if !defined?(@value_for_database) || type.changed_in_place?(@value_for_database, value) <add> @value_for_database = _value_for_database <add> end <add> @value_for_database <ide> end <ide> <ide> def serializable?(&block) <ide> def changed_from_assignment? <ide> assigned? && type.changed?(original_value, value, value_before_type_cast) <ide> end <ide> <add> def _value_for_database <add> type.serialize(value) <add> end <add> <ide> def _original_value_for_database <ide> type.serialize(original_value) <ide> end <ide> def type_cast(value) <ide> type.cast(value) <ide> end <ide> <del> def value_for_database <del> Type::SerializeCastValue.serialize(type, value) <del> end <del> <ide> def came_from_user? <ide> !type.value_constructed_by_mass_assignment?(value_before_type_cast) <ide> end <add> <add> private <add> def _value_for_database <add> Type::SerializeCastValue.serialize(type, value) <add> end <ide> end <ide> <ide> class WithCastValue < Attribute # :nodoc: <ide><path>activemodel/test/cases/attribute_test.rb <ide> module ActiveModel <ide> class AttributeTest < ActiveModel::TestCase <ide> class InscribingType <add> def changed_in_place?(raw_old_value, new_value) <add> false <add> end <add> <ide> def cast(value) <ide> "cast(#{value})" <ide> end <ide> def serialize_cast_value(value) <ide> assert_equal "serialize_cast_value(cast(whatever))", attribute.value_for_database <ide> end <ide> <add> test "value_for_database is memoized" do <add> count = 0 <add> @type.define_singleton_method(:serialize) do |value| <add> count += 1 <add> nil <add> end <add> <add> attribute = Attribute.from_user(nil, "whatever", @type) <add> <add> attribute.value_for_database <add> attribute.value_for_database <add> assert_equal 1, count <add> end <add> <add> test "value_for_database is recomputed when value changes in place" do <add> count = 0 <add> @type.define_singleton_method(:serialize) do |value| <add> count += 1 <add> nil <add> end <add> @type.define_singleton_method(:changed_in_place?) do |*| <add> true <add> end <add> <add> attribute = Attribute.from_user(nil, "whatever", @type) <add> <add> attribute.value_for_database <add> attribute.value_for_database <add> assert_equal 2, count <add> end <add> <ide> test "duping dups the value" do <ide> attribute = Attribute.from_database(nil, "a value", @type) <ide> <ide><path>activerecord/lib/active_record/relation/query_attribute.rb <ide> def type_cast(value) <ide> end <ide> <ide> def value_for_database <del> @value_for_database ||= super <add> @value_for_database = _value_for_database unless defined?(@value_for_database) <add> @value_for_database <ide> end <ide> <ide> def with_cast_value(value)
3
Text
Text
add missing comma
58a734e652dc52b0c5675df93349979b6d150b35
<ide><path>README.md <ide> These are the available config options for making requests. Only the `url` is re <ide> auth: { <ide> username: 'janedoe', <ide> password: 's00pers3cret' <del> } <add> }, <ide> <ide> // `responseType` indicates the type of data that the server will respond with <ide> // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
1
Javascript
Javascript
increase coverage of buffer.transcode
904b66d870e166192f34083f399499b8e6c9f216
<ide><path>test/parallel/test-icu-transcode.js <ide> assert.deepStrictEqual( <ide> buffer.transcode(uint8array, 'latin1', 'utf16le'), <ide> Buffer.from('hä', 'utf16le')); <ide> } <add> <add>{ <add> const dest = buffer.transcode(new Uint8Array(), 'utf8', 'latin1'); <add> assert.strictEqual(dest.length, 0); <add>}
1
Go
Go
embed spec when converting from grpc
a9d41184296c971c650f7d97a67ae5c9b44d4200
<ide><path>daemon/cluster/convert/secret.go <ide> func SecretFromGRPC(s *swarmapi.Secret) swarmtypes.Secret { <ide> ID: s.ID, <ide> Digest: s.Digest, <ide> SecretSize: s.SecretSize, <add> Spec: swarmtypes.SecretSpec{ <add> Annotations: swarmtypes.Annotations{ <add> Name: s.Spec.Annotations.Name, <add> Labels: s.Spec.Annotations.Labels, <add> }, <add> Data: s.Spec.Data, <add> }, <ide> } <ide> <del> // Meta <ide> secret.Version.Index = s.Meta.Version.Index <add> // Meta <ide> secret.CreatedAt, _ = ptypes.Timestamp(s.Meta.CreatedAt) <ide> secret.UpdatedAt, _ = ptypes.Timestamp(s.Meta.UpdatedAt) <ide> <del> secret.Spec = swarmtypes.SecretSpec{ <del> Annotations: swarmtypes.Annotations{ <del> Name: s.Spec.Annotations.Name, <del> Labels: s.Spec.Annotations.Labels, <del> }, <del> Data: s.Spec.Data, <del> } <del> <ide> return secret <ide> } <ide>
1
Javascript
Javascript
fix throws and doesnotthrow stack frames
d9171fef3fb1415344641b0ce82c5f4bc53936fc
<ide><path>lib/assert.js <ide> function innerThrows(shouldThrow, block, expected, message) { <ide> expected, <ide> operator: 'throws', <ide> message: `Missing expected exception${details}`, <del> stackStartFn: innerThrows <add> stackStartFn: assert.throws <ide> }); <ide> } <ide> if (expected && expectedException(actual, expected) === false) { <ide> function innerThrows(shouldThrow, block, expected, message) { <ide> expected, <ide> operator: 'doesNotThrow', <ide> message: `Got unwanted exception${details}\n${actual.message}`, <del> stackStartFn: innerThrows <add> stackStartFn: assert.doesNotThrow <ide> }); <ide> } <ide> throw actual; <ide><path>test/parallel/test-assert.js <ide> testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity }, <ide> } catch (e) { <ide> threw = true; <ide> assert.strictEqual(e.message, 'Missing expected exception.'); <add> assert.ok(!e.stack.includes('throws'), e.stack); <ide> } <ide> assert.ok(threw); <ide> } <ide> try { <ide> threw = true; <ide> assert.ok(e.message.includes(rangeError.message)); <ide> assert.ok(e instanceof assert.AssertionError); <add> assert.ok(!e.stack.includes('doesNotThrow'), e.stack); <ide> } <ide> assert.ok(threw); <ide> }
2
Javascript
Javascript
handle packages without dependencies
e2563a3c524fca42828a083872ef756e38fff118
<ide><path>scripts/release/build-commands/check-package-dependencies.js <ide> const check = async ({cwd, packages}) => { <ide> const rootVersion = rootPackage.devDependencies[module]; <ide> <ide> projectPackages.forEach(projectPackage => { <del> const projectVersion = projectPackage.dependencies[module]; <add> // Not all packages have dependencies (eg react-is) <add> const projectVersion = projectPackage.dependencies <add> ? projectPackage.dependencies[module] <add> : undefined; <ide> <ide> if (rootVersion !== projectVersion && projectVersion !== undefined) { <ide> invalidDependencies.push(
1
Ruby
Ruby
fix whitespace removal, fix string concatenation
5b3f5dcbf2c0a10239b530db354da1cd9f6480bb
<ide><path>Library/Homebrew/rubocops/lines.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> <ide> T.must(offenses[0...-1]).each do |node| <ide> offending_node(node) <del> problem "Use a single `generate_completions_from_executable` call <del> combining all specified shells" do |corrector| <del> # adjust range by +1 to also include & remove trailing \n <del> corrector.replace(@offensive_node.source_range.adjust(end_pos: 1), "") <add> problem "Use a single `generate_completions_from_executable` " \ <add> "call combining all specified shells." do |corrector| <add> # adjust range by -4 and +1 to also include & remove leading spaces and trailing \n <add> corrector.replace(@offensive_node.source_range.adjust(begin_pos: -4, end_pos: 1), "") <ide> end <ide> end <ide>
1
Javascript
Javascript
fix typing errors
92a3079f2928e07f652dfaa13e07f619e06632fa
<ide><path>lib/sharing/ConsumeSharedModule.js <ide> const { versionToString } = require("./utils"); <ide> * @property {string=} importResolved resolved fallback request <ide> * @property {string} shareKey global share key <ide> * @property {string} shareScope share scope <del> * @property {(number|string)[]} requiredVersion version requirement <add> * @property {(number|string)[] | undefined} requiredVersion version requirement <ide> * @property {string} packageName package name to determine required version automatically <ide> * @property {boolean} strictVersion don't use shared version even if version isn't valid <ide> * @property {boolean} singleton use single global version <ide> class ConsumeSharedModule extends Module { <ide> singleton, <ide> eager <ide> } = this.options; <del> return `consume-shared-module|${shareScope}|${shareKey}|${versionToString( <del> requiredVersion <del> )}|${strictVersion}|${importResolved}|${singleton}|${eager}`; <add> return `consume-shared-module|${shareScope}|${shareKey}|${ <add> requiredVersion && versionToString(requiredVersion) <add> }|${strictVersion}|${importResolved}|${singleton}|${eager}`; <ide> } <ide> <ide> /** <ide><path>lib/sharing/ConsumeSharedPlugin.js <ide> class ConsumeSharedPlugin { <ide> validateOptions(schema, options, { name: "Consumes Shared Plugin" }); <ide> } <ide> <del> /** @type {[string, ConsumeOptions][]} */ <add> /** @type {[string, ConsumesConfig][]} */ <ide> this._consumes = parseOptions( <ide> options.consumes, <ide> (item, key) => { <ide> if (Array.isArray(item)) throw new Error("Unexpected array in options"); <del> /** @type {ConsumeOptions} */ <add> /** @type {ConsumesConfig} */ <ide> let result = <ide> item === key || !isRequiredVersion(item) <ide> ? // item is a request/key <ide> class ConsumeSharedPlugin { <ide> import: key, <ide> shareScope: options.shareScope || "default", <ide> shareKey: key, <del> requiredVersion: parseRequiredVersion(item), <add> requiredVersion: <add> typeof item === "string" ? parseRequiredVersion(item) : item, <ide> strictVersion: true, <ide> packageName: undefined, <ide> singleton: false, <ide><path>test/configCases/container/1-container-full/webpack.config.js <add>// eslint-disable-next-line node/no-unpublished-require <ide> const { ModuleFederationPlugin } = require("../../../../").container; <ide> <ide> /** @type {import("../../../../").Configuration} */
3
Text
Text
update behaviour of fs.writefile
309e7723eac0442972bbaa6a725366b8ab150892
<ide><path>doc/api/fs.md <ide> recommended. <ide> 1. Any specified file descriptor has to support writing. <ide> 2. If a file descriptor is specified as the `file`, it will not be closed <ide> automatically. <del>3. The writing will begin at the beginning of the file. For example, if the <del>file already had `'Hello World'` and the newly written content is `'Aloha'`, <del>then the contents of the file would be `'Aloha World'`, rather than just <del>`'Aloha'`. <add>3. The writing will begin at the current position. For example, if the string <add>`'Hello'` is written to the file descriptor, and if `', World'` is written with <add>`fs.writeFile()` to the same file descriptor, the contents of the file would <add>become `'Hello, World'`, instead of just `', World'`. <ide> <ide> <ide> ## fs.writeFileSync(file, data[, options])
1
Ruby
Ruby
add support for sha256
3809c0b4190850d54ba64248ade6d4737067c710
<ide><path>Library/Homebrew/formula.rb <ide> def initialize name='__UNKNOWN__' <ide> @version=Pathname.new(@url).version unless @version <ide> validate_variable :version if @version <ide> @homepage=self.class.homepage unless @homepage <del> @md5=self.class.md5 unless @md5 <del> @sha1=self.class.sha1 unless @sha1 <add> CHECKSUM_TYPES.each do |type| <add> if !instance_variable_defined?("@#{type}") <add> class_value = self.class.send(type) <add> instance_variable_set("@#{type}", class_value) if class_value <add> end <add> end <ide> end <ide> <ide> # if the dir is there, but it's empty we consider it not installed <ide> def mktemp <ide> end <ide> end <ide> <add> CHECKSUM_TYPES=[:md5, :sha1, :sha256].freeze <add> <ide> def verify_download_integrity fn <ide> require 'digest' <del> type='MD5' <del> type='SHA1' if @sha1 <del> supplied=eval "@#{type.downcase}" <del> hash=eval("Digest::#{type}").hexdigest(fn.read) <add> type=CHECKSUM_TYPES.detect { |type| instance_variable_defined?("@#{type}") } <add> type ||= :md5 <add> supplied=instance_variable_get("@#{type}") <add> type=type.to_s.upcase <add> hash=Digest.const_get(type).hexdigest(fn.read) <ide> <ide> if supplied and not supplied.empty? <ide> raise "#{type} mismatch: #{hash}" unless supplied.upcase == hash.upcase <ide> def method_added method <ide> end <ide> <ide> class <<self <del> attr_reader :url, :version, :homepage, :md5, :sha1, :head <add> attr_reader :url, :version, :homepage, :head <add> attr_reader *CHECKSUM_TYPES <ide> end <ide> end <ide> <ide><path>Library/Homebrew/unittest.rb <ide> def test_badsha1 <ide> nostdout { invalid_sha1.new.brew {} } <ide> end <ide> end <add> <add> def test_sha256 <add> valid_sha256 = Class.new(TestBall) do <add> @sha256='ccbf5f44743b74add648c7e35e414076632fa3b24463d68d1f6afc5be77024f8' <add> end <add> <add> assert_nothing_raised do <add> nostdout { valid_sha256.new.brew {} } <add> end <add> end <add> <add> def test_badsha256 <add> invalid_sha256 = Class.new(TestBall) do <add> @sha256='dcbf5f44743b74add648c7e35e414076632fa3b24463d68d1f6afc5be77024f8' <add> end <add> <add> assert_raises RuntimeError do <add> nostdout { invalid_sha256.new.brew {} } <add> end <add> end <ide> <ide> FOOBAR='foo-bar' <ide> def test_formula_funcs
2
Ruby
Ruby
fix the skip code
81679ab2ae8c9f6a233374efe9fcf096cf9f8fd9
<ide><path>activerecord/test/cases/connection_specification/resolver_test.rb <ide> def resolve(spec) <ide> end <ide> <ide> def test_url_host_no_db <del> skip "only if mysql is available" unless defined?(MysqlAdapter) <add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) <ide> spec = resolve 'mysql://foo?encoding=utf8' <ide> assert_equal({ <ide> :adapter => "mysql", <ide> def test_url_host_no_db <ide> end <ide> <ide> def test_url_host_db <del> skip "only if mysql is available" unless defined?(MysqlAdapter) <add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) <ide> spec = resolve 'mysql://foo/bar?encoding=utf8' <ide> assert_equal({ <ide> :adapter => "mysql", <ide> def test_url_host_db <ide> end <ide> <ide> def test_url_port <del> skip "only if mysql is available" unless defined?(MysqlAdapter) <add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) <ide> spec = resolve 'mysql://foo:123?encoding=utf8' <ide> assert_equal({ <ide> :adapter => "mysql", <ide> def test_url_port <ide> end <ide> <ide> def test_encoded_password <del> skip "only if mysql is available" unless defined?(MysqlAdapter) <add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) <ide> password = 'am@z1ng_p@ssw0rd#!' <ide> encoded_password = URI.encode_www_form_component(password) <ide> spec = resolve "mysql://foo:#{encoded_password}@localhost/bar"
1
Javascript
Javascript
name anonymous functions for debugging purposes
5ce5ca03d32272321d07b0a624fb942b90b04d78
<ide><path>crypto.js <ide> <ide> 'use strict'; <ide> <del>var ARCFourCipher = (function() { <add>var ARCFourCipher = (function aRCFourCipher() { <ide> function constructor(key) { <ide> this.a = 0; <ide> this.b = 0; <ide> var ARCFourCipher = (function() { <ide> } <ide> <ide> constructor.prototype = { <del> encryptBlock: function(data) { <add> encryptBlock: function aRCFourCipherEncryptBlock(data) { <ide> var i, n = data.length, tmp, tmp2; <ide> var a = this.a, b = this.b, s = this.s; <ide> var output = new Uint8Array(n); <ide> var ARCFourCipher = (function() { <ide> return constructor; <ide> })(); <ide> <del>var md5 = (function() { <add>var md5 = (function md5Md5() { <ide> var r = new Uint8Array([ <ide> 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, <ide> 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, <ide> var md5 = (function() { <ide> return hash; <ide> })(); <ide> <del>var NullCipher = (function() { <add>var NullCipher = (function nullCipher() { <ide> function constructor() { <ide> } <ide> <ide> constructor.prototype = { <del> decryptBlock: function(data) { <add> decryptBlock: function nullCipherDecryptBlock(data) { <ide> return data; <ide> } <ide> }; <ide> <ide> return constructor; <ide> })(); <ide> <del>var AES128Cipher = (function() { <add>var AES128Cipher = (function aES128Cipher() { <ide> var rcon = new Uint8Array([ <ide> 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, <ide> 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, <ide> var AES128Cipher = (function() { <ide> } <ide> <ide> constructor.prototype = { <del> decryptBlock: function(data) { <add> decryptBlock: function aES128CipherDecryptBlock(data) { <ide> var i, sourceLength = data.length; <ide> var buffer = this.buffer, bufferLength = this.bufferPosition; <ide> // waiting for IV values -- they are at the start of the stream <ide> var AES128Cipher = (function() { <ide> return constructor; <ide> })(); <ide> <del>var CipherTransform = (function() { <add>var CipherTransform = (function cipherTransform() { <ide> function constructor(stringCipherConstructor, streamCipherConstructor) { <ide> this.stringCipherConstructor = stringCipherConstructor; <ide> this.streamCipherConstructor = streamCipherConstructor; <ide> } <ide> constructor.prototype = { <del> createStream: function(stream) { <add> createStream: function cipherTransformCreateStream(stream) { <ide> var cipher = new this.streamCipherConstructor(); <del> return new DecryptStream(stream, function(data) { <del> return cipher.decryptBlock(data); <del> }); <add> return new DecryptStream(stream, <add> function cipherTransformDecryptStream(data) { <add> return cipher.decryptBlock(data); <add> } <add> ); <ide> }, <del> decryptString: function(s) { <add> decryptString: function cipherTransformDecryptString(s) { <ide> var cipher = new this.stringCipherConstructor(); <ide> var data = stringToBytes(s); <ide> data = cipher.decryptBlock(data); <ide> var CipherTransform = (function() { <ide> return constructor; <ide> })(); <ide> <del>var CipherTransformFactory = (function() { <add>var CipherTransformFactory = (function cipherTransformFactory() { <ide> function prepareKeyData(fileId, password, ownerPassword, userPassword, <ide> flags, revision, keyLength, encryptMetadata) { <ide> var defaultPasswordBytes = new Uint8Array([ <ide> var CipherTransformFactory = (function() { <ide> if (cryptFilter != null) <ide> cfm = cryptFilter.get('CFM'); <ide> if (!cfm || cfm.name == 'None') { <del> return function() { <add> return function cipherTransformFactoryBuildCipherConstructorNone() { <ide> return new NullCipher(); <ide> }; <ide> } <ide> if ('V2' == cfm.name) { <del> return function() { <add> return function cipherTransformFactoryBuildCipherConstructorV2() { <ide> return new ARCFourCipher( <ide> buildObjectKey(num, gen, key, false)); <ide> }; <ide> } <ide> if ('AESV2' == cfm.name) { <del> return function() { <add> return function cipherTransformFactoryBuildCipherConstructorAESV2() { <ide> return new AES128Cipher( <ide> buildObjectKey(num, gen, key, true)); <ide> }; <ide> var CipherTransformFactory = (function() { <ide> } <ide> <ide> constructor.prototype = { <del> createCipherTransform: function(num, gen) { <add> createCipherTransform: function buildCipherCreateCipherTransform(num, <add> gen) { <ide> if (this.algorithm == 4) { <ide> return new CipherTransform( <ide> buildCipherConstructor(this.cf, this.stmf, <ide> var CipherTransformFactory = (function() { <ide> } <ide> // algorithms 1 and 2 <ide> var key = buildObjectKey(num, gen, this.encryptionKey, false); <del> var cipherConstructor = function() { <add> var cipherConstructor = function buildCipherCipherConstructor() { <ide> return new ARCFourCipher(key); <ide> }; <ide> return new CipherTransform(cipherConstructor, cipherConstructor);
1
Javascript
Javascript
fix reference to boxbuffergeometry
4dc07db7c848cd03d4e6ce4385882312bb4473ad
<ide><path>src/extras/PMREMGenerator.js <ide> import { Vector3 } from '../math/Vector3.js'; <ide> import { Color } from '../math/Color.js'; <ide> import { WebGLRenderTarget } from '../renderers/WebGLRenderTarget.js'; <ide> import { MeshBasicMaterial } from '../materials/MeshBasicMaterial.js'; <del>import { BoxBufferGeometry } from '../geometries/BoxBufferGeometry.js'; <add>import { BoxBufferGeometry } from '../geometries/BoxGeometry.js'; <ide> import { BackSide } from '../constants.js'; <ide> <ide> const LOD_MIN = 4;
1
Python
Python
find sizeof wo running on the target platform
d58becf8f9269fc6487648238383cd8cf477124c
<ide><path>numpy/distutils/command/config.py <ide> def check_decl(self, symbol, <ide> <ide> def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None): <ide> """Check size of a given type.""" <del> # XXX: should also implement the cross-compiling version (using binary <del> # search + array indexing, see AC_CHECK_SIZEOF). <ide> self._check_compiler() <ide> <del> # We declare the functions to avoid warnings with -Wstrict-prototypes <add> # First check the type can be compiled <ide> body = r""" <del>typedef %(type)s _dist_type_sizeof_; <del> <del>static long int longval (void) <del>{ <del> return (long int) (sizeof (_dist_type_sizeof_)); <del>} <del>static unsigned long int ulongval (void) <add>typedef %(type)s npy_check_sizeof_type; <add>int main () <ide> { <del> return (long int) (sizeof (_dist_type_sizeof_)); <add> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)]; <add> test_array [0] = 0 <add> <add> ; <add> return 0; <ide> } <add>""" <add> self._compile(body % {'type': type_name}, <add> headers, include_dirs, 'c') <add> self._clean() <ide> <del>#include <stdio.h> <del>#include <stdlib.h> <del>int <del>main (void) <add> # this fails to *compile* if size > sizeof(type) <add> body = r""" <add>typedef %(type)s npy_check_sizeof_type; <add>int main () <ide> { <add> static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)]; <add> test_array [0] = 0 <ide> <del> if (((long int) (sizeof (_dist_type_sizeof_))) < 0) { <del> long int i = longval (); <del> if (i != ((long int) (sizeof (_dist_type_sizeof_)))) <del> return 1; <del> printf("%%ld\n", i); <del> } else { <del> unsigned long int i = ulongval (); <del> if (i != ((long int) (sizeof (_dist_type_sizeof_)))) <del> return 1; <del> printf("%%lu\n", i); <del> } <del> <add> ; <ide> return 0; <ide> } <del>""" % {'type': type_name} <del> <del> # XXX: this should be refactored (same code as get_output) <del> exitcode, output = 255, '' <del> size = None <del> try: <del> src, obj, exe = self._link(body, headers, include_dirs, <del> [], library_dirs, 'c') <del> #exe = os.path.join('.', exe) <del> exitstatus, output = exec_command(exe, execute_in='.') <del> if hasattr(os, 'WEXITSTATUS'): <del> exitcode = os.WEXITSTATUS(exitstatus) <del> if os.WIFSIGNALED(exitstatus): <del> sig = os.WTERMSIG(exitstatus) <del> log.error('subprocess exited with signal %d' % (sig,)) <del> if sig == signal.SIGINT: <del> # control-C <del> raise KeyboardInterrupt <del> else: <del> exitcode = exitstatus <del> log.info("success!") <del> <add>""" <add> <add> # The principle is simple: we first find low and high bounds of size <add> # for the type, where low/high are looked up on a log scale. Then, we <add> # do a binary search to find the exact size between low and high <add> low = 0 <add> mid = 0 <add> while True: <ide> try: <del> size = int(output) <del> except ValueError: <del> log.error("Unexpected output %s" % output) <del> log.info("failure") <del> except (CompileError, LinkError): <del> log.info("failure.") <del> <del> self._clean() <del> if size is not None: <del> return size <del> else: <del> return -1 <add> self._compile(body % {'type': type_name, 'size': mid}, <add> headers, include_dirs, 'c') <add> self._clean() <add> break <add> except CompileError: <add> #log.info("failure to test for bound %d" % mid) <add> low = mid + 1 <add> mid = 2 * mid + 1 <add> <add> high = mid <add> # Binary search: <add> while low != high: <add> mid = (high - low) / 2 + low <add> try: <add> self._compile(body % {'type': type_name, 'size': mid}, <add> headers, include_dirs, 'c') <add> self._clean() <add> high = mid <add> except CompileError: <add> low = mid + 1 <add> return low <ide> <ide> def check_func(self, func, <ide> headers=None, include_dirs=None,
1
Javascript
Javascript
update skeleton only once in a frame
58bd51ef3668a2c225dc168d3be4f9f1564ece69
<ide><path>src/objects/Skeleton.js <ide> function Skeleton( bones, boneInverses ) { <ide> this.bones = bones.slice( 0 ); <ide> this.boneMatrices = new Float32Array( this.bones.length * 16 ); <ide> <add> this.version = - 1; <add> <ide> // use the supplied bone inverses or calculate the inverses <ide> <ide> if ( boneInverses === undefined ) { <ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> <ide> if ( object.isSkinnedMesh ) { <ide> <del> object.skeleton.update(); <add> // update skeleton only once in a frame <add> <add> if ( object.skeleton.version !== info.render.frame ) { <add> <add> object.skeleton.update(); <add> object.skeleton.version = info.render.frame; <add> <add> } <ide> <ide> } <ide>
2
PHP
PHP
fix phpcs violations
357a4af775a28e1a5f65d37081506e0daf10c245
<ide><path>src/Cache/Cache.php <ide> public static function remember($key, $callable, $config = 'default') { <ide> return $results; <ide> } <ide> <add>/** <add> * Returns an array mapping url schemes to fully qualified class names <add> * <add> * @return array <add> */ <ide> public static function getClassMap() { <ide> return [ <ide> 'apc' => 'Cake\Cache\Engine\ApcEngine', <ide><path>src/Datasource/ConnectionManager.php <ide> public static function parseDsn($config = null) { <ide> return $config; <ide> } <ide> <add>/** <add> * Returns an array mapping url schemes to fully qualified class names <add> * <add> * @return array <add> */ <ide> public static function getClassMap() { <ide> return [ <ide> 'mysql' => 'Cake\Database\Driver\Mysql', <ide><path>src/Log/Log.php <ide> public static function info($message, $context = array()) { <ide> return static::write(static::$_levelMap['info'], $message, $context); <ide> } <ide> <add>/** <add> * Returns an array mapping url schemes to fully qualified class names <add> * <add> * @return array <add> */ <ide> public static function getClassMap() { <ide> return [ <ide> 'console' => 'Cake\Log\Engine\ConsoleLog', <ide><path>src/Network/Email/Email.php <ide> protected function _getContentTypeCharset() { <ide> return strtoupper($this->charset); <ide> } <ide> <del> <add>/** <add> * Returns an array mapping url schemes to fully qualified class names <add> * <add> * @return array <add> */ <ide> public static function getClassMap() { <ide> return [ <ide> 'debug' => 'Cake\Network\Email\DebugTransport', <ide><path>tests/TestCase/Core/StaticConfigTraitTest.php <ide> public static function getClassMap() { <ide> 'sqlserver' => 'Cake\Database\Driver\Sqlserver', <ide> ]; <ide> } <add> <ide> } <ide> <ide> /** <ide> public static function getClassMap() { <ide> 'xcache' => 'Cake\Cache\Engine\XcacheEngine', <ide> ]; <ide> } <add> <ide> } <ide> <ide> /** <ide> public static function getClassMap() { <ide> 'smtp' => 'Cake\Network\Email\SmtpTransport', <ide> ]; <ide> } <add> <ide> } <ide> <ide> /** <ide> public static function getClassMap() { <ide> 'syslog' => 'Cake\Log\Engine\SyslogLog', <ide> ]; <ide> } <add> <ide> } <ide> <ide> /**
5
Text
Text
remove duplicate lines
642238de8191a447077ca132a5b7ad2a695c2a59
<ide><path>research/object_detection/g3doc/tf2_training_and_evaluation.md <ide> A local evaluation job can be run with the following command: <ide> PIPELINE_CONFIG_PATH={path to pipeline config file} <ide> MODEL_DIR={path to model directory} <ide> CHECKPOINT_DIR=${MODEL_DIR} <del>MODEL_DIR={path to model directory} <ide> python object_detection/model_main_tf2.py \ <ide> --pipeline_config_path=${PIPELINE_CONFIG_PATH} \ <ide> --model_dir=${MODEL_DIR} \ <ide> launched using the following command: <ide> PIPELINE_CONFIG_PATH={path to pipeline config file} <ide> MODEL_DIR={path to model directory} <ide> CHECKPOINT_DIR=${MODEL_DIR} <del>MODEL_DIR={path to model directory} <ide> python object_detection/model_main_tf2.py \ <ide> --pipeline_config_path=${PIPELINE_CONFIG_PATH} \ <ide> --model_dir=${MODEL_DIR} \
1
Javascript
Javascript
document the bootstrap process in node.js
008074fc38b51026f60c7397401ed6756639058f
<ide><path>lib/internal/bootstrap/node.js <ide> // Hello, and welcome to hacking node.js! <ide> // <del>// This file is invoked by node::LoadEnvironment in src/node.cc, and is <del>// responsible for bootstrapping the node.js core. As special caution is given <del>// to the performance of the startup process, many dependencies are invoked <del>// lazily. <add>// This file is invoked by `node::RunBootstrapping()` in `src/node.cc`, and is <add>// responsible for setting up node.js core before executing main scripts <add>// under `lib/internal/main/`. <add>// This file is currently run to bootstrap both the main thread and the worker <add>// threads. Some setups are conditional, controlled with isMainThread and <add>// ownsProcessState. <add>// This file is expected not to perform any asynchronous operations itself <add>// when being executed - those should be done in either <add>// `lib/internal/bootstrap/pre_execution.js` or in main scripts. The majority <add>// of the code here focus on setting up the global proxy and the process <add>// object in a synchronous manner. <add>// As special caution is given to the performance of the startup process, <add>// many dependencies are invoked lazily. <ide> // <del>// Before this file is run, lib/internal/bootstrap/loaders.js gets run first <del>// to bootstrap the internal binding and module loaders, including <del>// process.binding(), process._linkedBinding(), internalBinding() and <del>// NativeModule. And then { internalBinding, NativeModule } will be passed <del>// into this bootstrapper to bootstrap Node.js core. <add>// Scripts run before this file: <add>// - `lib/internal/bootstrap/context.js`: to setup the v8::Context with <add>// Node.js-specific tweaks - this is also done in vm contexts. <add>// - `lib/internal/bootstrap/primordials.js`: to save copies of JavaScript <add>// builtins that won't be affected by user land monkey-patching for internal <add>// modules to use. <add>// - `lib/internal/bootstrap/loaders.js`: to setup internal binding and <add>// module loaders, including `process.binding()`, `process._linkedBinding()`, <add>// `internalBinding()` and `NativeModule`. <add>// <add>// After this file is run, one of the main scripts under `lib/internal/main/` <add>// will be selected by C++ to start the actual execution. The main scripts may <add>// run additional setups exported by `lib/internal/bootstrap/pre_execution.js`, <add>// depending on the execution mode. <add> <ide> 'use strict'; <ide> <ide> // This file is compiled as if it's wrapped in a function with arguments <del>// passed by node::LoadEnvironment() <add>// passed by node::RunBootstrapping() <ide> /* global process, loaderExports, isMainThread, ownsProcessState */ <ide> <ide> const { internalBinding, NativeModule } = loaderExports;
1
Javascript
Javascript
improve logged errors
1450ea7bf608a54640863e5ba23c6f0ce430e14f
<ide><path>test/common/index.js <ide> if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { <ide> process._rawDebug(); <ide> throw new Error(`same id added to destroy list twice (${id})`); <ide> } <del> destroyListList[id] = new Error().stack; <add> destroyListList[id] = util.inspect(new Error()); <ide> _queueDestroyAsyncId(id); <ide> }; <ide> <ide> require('async_hooks').createHook({ <del> init(id, ty, tr, r) { <add> init(id, ty, tr, resource) { <ide> if (initHandles[id]) { <ide> process._rawDebug( <del> `Is same resource: ${r === initHandles[id].resource}`); <add> `Is same resource: ${resource === initHandles[id].resource}`); <ide> process._rawDebug(`Previous stack:\n${initHandles[id].stack}\n`); <ide> throw new Error(`init called twice for same id (${id})`); <ide> } <del> initHandles[id] = { resource: r, stack: new Error().stack.substr(6) }; <add> initHandles[id] = { <add> resource, <add> stack: util.inspect(new Error()).substr(6) <add> }; <ide> }, <ide> before() { }, <ide> after() { }, <ide> if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { <ide> process._rawDebug(); <ide> throw new Error(`destroy called for same id (${id})`); <ide> } <del> destroydIdsList[id] = new Error().stack; <add> destroydIdsList[id] = util.inspect(new Error()); <ide> }, <ide> }).enable(); <ide> } <ide> function _mustCallInner(fn, criteria = 1, field) { <ide> const context = { <ide> [field]: criteria, <ide> actual: 0, <del> stack: (new Error()).stack, <add> stack: util.inspect(new Error()), <ide> name: fn.name || '<anonymous>' <ide> }; <ide> <ide> function expectWarning(nameOrMap, expected, code) { <ide> function expectsError(validator, exact) { <ide> return mustCall((...args) => { <ide> if (args.length !== 1) { <del> // Do not use `assert.strictEqual()` to prevent `util.inspect` from <add> // Do not use `assert.strictEqual()` to prevent `inspect` from <ide> // always being called. <ide> assert.fail(`Expected one argument, got ${util.inspect(args)}`); <ide> } <ide><path>test/common/wpt.js <ide> const fs = require('fs'); <ide> const fsPromises = fs.promises; <ide> const path = require('path'); <ide> const vm = require('vm'); <add>const { inspect } = require('util'); <ide> <ide> // https://github.com/w3c/testharness.js/blob/master/testharness.js <ide> // TODO: get rid of this half-baked harness in favor of the one <ide> class WPTRunner { <ide> this.fail(filename, { <ide> name: '', <ide> message: err.message, <del> stack: err.stack <add> stack: inspect(err) <ide> }, 'UNCAUGHT'); <ide> this.inProgress.delete(filename); <ide> } <ide><path>test/fixtures/uncaught-exceptions/domain.js <ide> const domain = require('domain'); <ide> <ide> var d = domain.create(); <ide> d.on('error', function(err) { <del> console.log('[ignored]', err.stack); <add> console.log('[ignored]', err); <ide> }); <ide> <ide> d.run(function() { <ide><path>test/message/vm_display_runtime_error.js <ide> console.error('beginning'); <ide> try { <ide> vm.runInThisContext('throw new Error("boo!")', { filename: 'test.vm' }); <ide> } catch (err) { <del> console.error(err.stack); <add> console.error(err); <ide> } <ide> <ide> vm.runInThisContext('throw new Error("spooky!")', { filename: 'test.vm' }); <ide><path>test/message/vm_display_syntax_error.js <ide> console.error('beginning'); <ide> try { <ide> vm.runInThisContext('var 4;', { filename: 'foo.vm', displayErrors: true }); <ide> } catch (err) { <del> console.error(err.stack); <add> console.error(err); <ide> } <ide> <ide> vm.runInThisContext('var 5;', { filename: 'test.vm' }); <ide><path>test/parallel/test-assert-if-error.js <ide> assert.ifError(undefined); <ide> } catch (e) { <ide> threw = true; <ide> assert.strictEqual(e.message, 'Missing expected exception.'); <del> assert(!e.stack.includes('throws'), e.stack); <add> assert(!e.stack.includes('throws'), e); <ide> } <ide> assert(threw); <ide> } <ide><path>test/parallel/test-assert.js <ide> assert.throws( <ide> threw = true; <ide> assert.ok(e.message.includes(rangeError.message)); <ide> assert.ok(e instanceof assert.AssertionError); <del> assert.ok(!e.stack.includes('doesNotThrow'), e.stack); <add> assert.ok(!e.stack.includes('doesNotThrow'), e); <ide> } <ide> assert.ok(threw); <ide> } <ide><path>test/parallel/test-http-request-agent.js <ide> server.listen(0, common.mustCall(function() { <ide> res.resume(); <ide> server.close(); <ide> })).on('error', function(e) { <del> console.error(e.stack); <add> console.error(e); <ide> process.exit(1); <ide> }); <ide> })); <ide><path>test/parallel/test-http-unix-socket.js <ide> server.listen(common.PIPE, common.mustCall(function() { <ide> })); <ide> <ide> req.on('error', function(e) { <del> assert.fail(e.stack); <add> assert.fail(e); <ide> }); <ide> <ide> req.end(); <ide><path>test/parallel/test-promises-unhandled-rejections.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <add>const { inspect } = require('util'); <ide> <ide> common.disableCrashOnUnhandledRejection(); <ide> <ide> const asyncTest = (function() { <ide> <ide> function fail(error) { <ide> const stack = currentTest ? <del> `${error.stack}\nFrom previous event:\n${currentTest.stack}` : <del> error.stack; <add> `${inspect(error)}\nFrom previous event:\n${currentTest.stack}` : <add> inspect(error); <ide> <ide> if (currentTest) <ide> process.stderr.write(`'${currentTest.description}' failed\n\n`); <ide> const asyncTest = (function() { <ide> } <ide> <ide> return function asyncTest(description, fn) { <del> const stack = new Error().stack.split('\n').slice(1).join('\n'); <add> const stack = inspect(new Error()).split('\n').slice(1).join('\n'); <ide> asyncTestQueue.push({ <ide> action: fn, <del> stack: stack, <del> description: description <add> stack, <add> description <ide> }); <ide> if (!asyncTestsEnabled) { <ide> asyncTestsEnabled = true; <ide><path>test/parallel/test-tls-min-max-version.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const fixtures = require('../common/fixtures'); <add>const { inspect } = require('util'); <ide> <ide> // Check min/max protocol versions. <ide> <ide> function test(cmin, cmax, cprot, smin, smax, sprot, proto, cerr, serr) { <ide> // Report where test was called from. Strip leading garbage from <ide> // at Object.<anonymous> (file:line) <ide> // from the stack location, we only want the file:line part. <del> const where = (new Error()).stack.split('\n')[2].replace(/[^(]*/, ''); <add> const where = inspect(new Error()).split('\n')[2].replace(/[^(]*/, ''); <ide> connect({ <ide> client: { <ide> checkServerIdentity: (servername, cert) => { }, <ide><path>test/parallel/test-tls-securepair-server.js <ide> const key = fixtures.readKey('rsa_private.pem'); <ide> const cert = fixtures.readKey('rsa_cert.crt'); <ide> <ide> function log(a) { <del> console.error(`***server*** ${a}`); <add> console.error('***server***', a); <ide> } <ide> <ide> const server = net.createServer(common.mustCall(function(socket) { <ide> const server = net.createServer(common.mustCall(function(socket) { <ide> pair.cleartext.on('error', function(err) { <ide> log('got error: '); <ide> log(err); <del> log(err.stack); <ide> socket.destroy(); <ide> }); <ide> <ide> pair.encrypted.on('error', function(err) { <ide> log('encrypted error: '); <ide> log(err); <del> log(err.stack); <ide> socket.destroy(); <ide> }); <ide> <ide> socket.on('error', function(err) { <ide> log('socket error: '); <ide> log(err); <del> log(err.stack); <ide> socket.destroy(); <ide> }); <ide> <ide> const server = net.createServer(common.mustCall(function(socket) { <ide> pair.on('error', function(err) { <ide> log('secure error: '); <ide> log(err); <del> log(err.stack); <ide> socket.destroy(); <ide> }); <ide> })); <ide><path>test/parallel/test-tls-set-ciphers.js <ide> 'use strict'; <ide> const common = require('../common'); <del>if (!common.hasCrypto) common.skip('missing crypto'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <ide> const fixtures = require('../common/fixtures'); <add>const { inspect } = require('util'); <ide> <ide> // Test cipher: option for TLS. <ide> <ide> const { <ide> <ide> function test(cciphers, sciphers, cipher, cerr, serr) { <ide> assert(cipher || cerr || serr, 'test missing any expectations'); <del> const where = (new Error()).stack.split('\n')[2].replace(/[^(]*/, ''); <add> const where = inspect(new Error()).split('\n')[2].replace(/[^(]*/, ''); <ide> connect({ <ide> client: { <ide> checkServerIdentity: (servername, cert) => { }, <ide><path>test/parallel/test-vm-context.js <ide> 'use strict'; <ide> require('../common'); <ide> const assert = require('assert'); <del> <add>const { inspect } = require('util'); <ide> const vm = require('vm'); <ide> const Script = vm.Script; <ide> let script = new Script('"passed";'); <ide> try { <ide> } catch (e) { <ide> gh1140Exception = e; <ide> assert.ok(/expected-filename/.test(e.stack), <del> `expected appearance of filename in Error stack: ${e.stack}`); <add> `expected appearance of filename in Error stack: ${inspect(e)}`); <ide> } <ide> // This is outside of catch block to confirm catch block ran. <ide> assert.strictEqual(gh1140Exception.toString(), 'Error');
14
Javascript
Javascript
add debug flag to givebrowniepoints endpoint
c2720d784cbc25bd666675771062df4ce9d39e2e
<ide><path>common/models/user.js <ide> module.exports = function(User) { <ide> ); <ide> <ide> User.giveBrowniePoints = <del> function giveBrowniePoints(receiver, giver, data = {}, cb) { <add> function giveBrowniePoints(receiver, giver, data = {}, dev = false, cb) { <ide> const findUser = observeMethod(User, 'findOne'); <ide> if (!receiver) { <ide> return nextTick(() => { <ide> module.exports = function(User) { <ide> }) <ide> .subscribe( <ide> (user) => { <del> cb(null, getAboutProfile(user)); <add> return cb( <add> null, <add> getAboutProfile(user), <add> dev ? <add> { giver, receiver, data } : <add> null <add> ); <ide> }, <del> cb, <add> (e) => cb(e, null, dev ? { giver, receiver, data } : null), <ide> () => { <ide> debug('brownie points assigned completed'); <ide> } <ide> module.exports = function(User) { <ide> { <ide> arg: 'data', <ide> type: 'object' <add> }, <add> { <add> arg: 'debug', <add> type: 'boolean' <ide> } <ide> ], <ide> returns: [ <ide> { <ide> arg: 'about', <ide> type: 'object' <add> }, <add> { <add> arg: 'debug', <add> type: 'object' <ide> } <ide> ], <ide> http: { <ide> path: '/give-brownie-points', <del> verb: 'get' <add> verb: 'POST' <ide> } <ide> } <ide> );
1
Python
Python
move data_utils to utils.data_utils
1ebeff8ee304833a3df421d0de3b9f9480570eb9
<ide><path>examples/babi_memnn.py <ide> from keras.layers.embeddings import Embedding <ide> from keras.layers.core import Activation, Dense, Merge, Permute, Dropout <ide> from keras.layers.recurrent import LSTM <del>from keras.datasets.data_utils import get_file <add>from keras.utils.data_utils import get_file <ide> from keras.preprocessing.sequence import pad_sequences <ide> from functools import reduce <ide> import tarfile <ide><path>examples/babi_rnn.py <ide> import numpy as np <ide> np.random.seed(1337) # for reproducibility <ide> <del>from keras.datasets.data_utils import get_file <add>from keras.utils.data_utils import get_file <ide> from keras.layers.embeddings import Embedding <ide> from keras.layers.core import Dense, Merge, Dropout, RepeatVector <ide> from keras.layers import recurrent <ide><path>examples/lstm_text_generation.py <ide> from keras.models import Sequential <ide> from keras.layers.core import Dense, Activation, Dropout <ide> from keras.layers.recurrent import LSTM <del>from keras.datasets.data_utils import get_file <add>from keras.utils.data_utils import get_file <ide> import numpy as np <ide> import random <ide> import sys <ide><path>keras/datasets/cifar.py <ide> from six.moves import cPickle <ide> from six.moves import range <ide> <add> <ide> def load_batch(fpath, label_key='labels'): <ide> f = open(fpath, 'rb') <ide> if sys.version_info < (3,): <ide><path>keras/datasets/cifar10.py <ide> from __future__ import absolute_import <ide> from .cifar import load_batch <del>from .data_utils import get_file <add>from ..utils.data_utils import get_file <ide> import numpy as np <ide> import os <ide> <ide><path>keras/datasets/cifar100.py <ide> from __future__ import absolute_import <ide> from .cifar import load_batch <del>from .data_utils import get_file <add>from ..utils.data_utils import get_file <ide> import numpy as np <ide> import os <ide> <ide><path>keras/datasets/data_utils.py <del>from __future__ import absolute_import <del>from __future__ import print_function <add>from ..utils.data_utils import * <add>import warnings <ide> <del>import tarfile <del>import os <del>import sys <del>import shutil <del>from six.moves.urllib.request import urlopen <del>from six.moves.urllib.error import URLError, HTTPError <del> <del>from ..utils.generic_utils import Progbar <del> <del> <del># Under Python 2, 'urlretrieve' relies on FancyURLopener from legacy <del># urllib module, known to have issues with proxy management <del>if sys.version_info[0] == 2: <del> def urlretrieve(url, filename, reporthook=None, data=None): <del> def chunk_read(response, chunk_size=8192, reporthook=None): <del> total_size = response.info().get('Content-Length').strip() <del> total_size = int(total_size) <del> count = 0 <del> while 1: <del> chunk = response.read(chunk_size) <del> if not chunk: <del> break <del> count += 1 <del> if reporthook: <del> reporthook(count, chunk_size, total_size) <del> yield chunk <del> <del> response = urlopen(url, data) <del> with open(filename, 'wb') as fd: <del> for chunk in chunk_read(response, reporthook=reporthook): <del> fd.write(chunk) <del>else: <del> from six.moves.urllib.request import urlretrieve <del> <del> <del>def get_file(fname, origin, untar=False): <del> datadir_base = os.path.expanduser(os.path.join('~', '.keras')) <del> if not os.access(datadir_base, os.W_OK): <del> datadir_base = os.path.join('/tmp', '.keras') <del> datadir = os.path.join(datadir_base, 'datasets') <del> if not os.path.exists(datadir): <del> os.makedirs(datadir) <del> <del> if untar: <del> untar_fpath = os.path.join(datadir, fname) <del> fpath = untar_fpath + '.tar.gz' <del> else: <del> fpath = os.path.join(datadir, fname) <del> <del> if not os.path.exists(fpath): <del> print('Downloading data from', origin) <del> global progbar <del> progbar = None <del> <del> def dl_progress(count, block_size, total_size): <del> global progbar <del> if progbar is None: <del> progbar = Progbar(total_size) <del> else: <del> progbar.update(count*block_size) <del> <del> error_msg = 'URL fetch failure on {}: {} -- {}' <del> try: <del> try: <del> urlretrieve(origin, fpath, dl_progress) <del> except URLError as e: <del> raise Exception(error_msg.format(origin, e.errno, e.reason)) <del> except HTTPError as e: <del> raise Exception(error_msg.format(origin, e.code, e.msg)) <del> except (Exception, KeyboardInterrupt) as e: <del> if os.path.exists(fpath): <del> os.remove(fpath) <del> raise e <del> progbar = None <del> <del> if untar: <del> if not os.path.exists(untar_fpath): <del> print('Untaring file...') <del> tfile = tarfile.open(fpath, 'r:gz') <del> try: <del> tfile.extractall(path=datadir) <del> except (Exception, KeyboardInterrupt) as e: <del> if os.path.exists(untar_fpath): <del> if os.path.isfile(untar_fpath): <del> os.remove(untar_fpath) <del> else: <del> shutil.rmtree(untar_fpath) <del> raise e <del> tfile.close() <del> return untar_fpath <del> <del> return fpath <add>warnings.warn('data_utils has been moved to keras.utils.data_utils.') <ide>\ No newline at end of file <ide><path>keras/datasets/imdb.py <ide> from __future__ import absolute_import <ide> from six.moves import cPickle <ide> import gzip <del>from .data_utils import get_file <add>from ..utils.data_utils import get_file <ide> from six.moves import zip <ide> import numpy as np <ide> <ide><path>keras/datasets/mnist.py <ide> # -*- coding: utf-8 -*- <ide> import gzip <del>from .data_utils import get_file <add>from ..utils.data_utils import get_file <ide> from six.moves import cPickle <ide> import sys <ide> <ide><path>keras/datasets/reuters.py <ide> # -*- coding: utf-8 -*- <ide> from __future__ import absolute_import <del>from .data_utils import get_file <add>from ..utils.data_utils import get_file <ide> from six.moves import cPickle <ide> from six.moves import zip <ide> import numpy as np <ide><path>keras/utils/data_utils.py <add>from __future__ import absolute_import <add>from __future__ import print_function <add> <add>import tarfile <add>import os <add>import sys <add>import shutil <add>from six.moves.urllib.request import urlopen <add>from six.moves.urllib.error import URLError, HTTPError <add> <add>from ..utils.generic_utils import Progbar <add> <add> <add># Under Python 2, 'urlretrieve' relies on FancyURLopener from legacy <add># urllib module, known to have issues with proxy management <add>if sys.version_info[0] == 2: <add> def urlretrieve(url, filename, reporthook=None, data=None): <add> def chunk_read(response, chunk_size=8192, reporthook=None): <add> total_size = response.info().get('Content-Length').strip() <add> total_size = int(total_size) <add> count = 0 <add> while 1: <add> chunk = response.read(chunk_size) <add> if not chunk: <add> break <add> count += 1 <add> if reporthook: <add> reporthook(count, chunk_size, total_size) <add> yield chunk <add> <add> response = urlopen(url, data) <add> with open(filename, 'wb') as fd: <add> for chunk in chunk_read(response, reporthook=reporthook): <add> fd.write(chunk) <add>else: <add> from six.moves.urllib.request import urlretrieve <add> <add> <add>def get_file(fname, origin, untar=False): <add> datadir_base = os.path.expanduser(os.path.join('~', '.keras')) <add> if not os.access(datadir_base, os.W_OK): <add> datadir_base = os.path.join('/tmp', '.keras') <add> datadir = os.path.join(datadir_base, 'datasets') <add> if not os.path.exists(datadir): <add> os.makedirs(datadir) <add> <add> if untar: <add> untar_fpath = os.path.join(datadir, fname) <add> fpath = untar_fpath + '.tar.gz' <add> else: <add> fpath = os.path.join(datadir, fname) <add> <add> if not os.path.exists(fpath): <add> print('Downloading data from', origin) <add> global progbar <add> progbar = None <add> <add> def dl_progress(count, block_size, total_size): <add> global progbar <add> if progbar is None: <add> progbar = Progbar(total_size) <add> else: <add> progbar.update(count*block_size) <add> <add> error_msg = 'URL fetch failure on {}: {} -- {}' <add> try: <add> try: <add> urlretrieve(origin, fpath, dl_progress) <add> except URLError as e: <add> raise Exception(error_msg.format(origin, e.errno, e.reason)) <add> except HTTPError as e: <add> raise Exception(error_msg.format(origin, e.code, e.msg)) <add> except (Exception, KeyboardInterrupt) as e: <add> if os.path.exists(fpath): <add> os.remove(fpath) <add> raise e <add> progbar = None <add> <add> if untar: <add> if not os.path.exists(untar_fpath): <add> print('Untaring file...') <add> tfile = tarfile.open(fpath, 'r:gz') <add> try: <add> tfile.extractall(path=datadir) <add> except (Exception, KeyboardInterrupt) as e: <add> if os.path.exists(untar_fpath): <add> if os.path.isfile(untar_fpath): <add> os.remove(untar_fpath) <add> else: <add> shutil.rmtree(untar_fpath) <add> raise e <add> tfile.close() <add> return untar_fpath <add> <add> return fpath
11
Ruby
Ruby
add test for tapformulaorcaskunavailableerror
e64f2d1fd49a2a689443f5654cf47bc431f0c155
<ide><path>Library/Homebrew/test/exceptions_spec.rb <ide> } <ide> end <ide> <add> describe TapFormulaOrCaskUnavailableError do <add> subject(:error) { described_class.new(tap, "foo") } <add> <add> let(:tap) { double(Tap, user: "u", repo: "r", to_s: "u/r", installed?: false) } <add> <add> its(:to_s) { is_expected.to match(%r{Please tap it and then try again: brew tap u/r}) } <add> end <add> <ide> describe FormulaUnavailableError do <ide> subject(:error) { described_class.new("foo") } <ide>
1
Java
Java
fix rootview layout when using flex
a62aac5952c2d94120b7ed63d518da2bfbf4316d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> import android.util.Log; <ide> import android.view.View; <ide> import com.facebook.infer.annotation.Assertions; <add>import com.facebook.react.bridge.GuardedRunnable; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.ReadableMap; <ide> import com.facebook.react.bridge.ReadableNativeMap; <ide> import com.facebook.react.bridge.UIManager; <add>import com.facebook.react.common.ReactConstants; <ide> import com.facebook.react.common.annotations.VisibleForTesting; <ide> import com.facebook.react.modules.i18nmanager.I18nUtil; <ide> import com.facebook.react.uimanager.DisplayMetricsHolder; <ide> import com.facebook.react.uimanager.common.MeasureSpecProvider; <ide> import com.facebook.react.uimanager.common.SizeMonitoringFrameLayout; <ide> import java.util.ArrayList; <add>import java.util.LinkedList; <ide> import java.util.List; <ide> import javax.annotation.Nullable; <ide> <ide> public void appendChildToSet(List<ReactShadowNode> childList, ReactShadowNode ch <ide> childList.add(child); <ide> } <ide> <del> public synchronized void completeRoot(int rootTag, List<ReactShadowNode> childList) { <del> if (DEBUG) { <del> Log.d(TAG, "completeRoot rootTag: " + rootTag + ", childList: " + childList); <del> } <add> public synchronized void completeRoot(int rootTag, @Nullable List<ReactShadowNode> childList) { <ide> try { <add> childList = childList == null ? new LinkedList<ReactShadowNode>() : childList; <add> if (DEBUG) { <add> Log.d(TAG, "completeRoot rootTag: " + rootTag + ", childList: " + childList); <add> } <ide> ReactShadowNode currentRootShadowNode = getRootNode(rootTag); <ide> Assertions.assertNotNull( <ide> currentRootShadowNode, <ide> private void applyUpdatesRecursive(ReactShadowNode node, float absoluteX, float <ide> @Override <ide> public <T extends SizeMonitoringFrameLayout & MeasureSpecProvider> int addRootView( <ide> final T rootView) { <del> int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); <add> final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); <ide> ThemedReactContext themedRootContext = <ide> new ThemedReactContext(mReactApplicationContext, rootView.getContext()); <ide> <ide> public <T extends SizeMonitoringFrameLayout & MeasureSpecProvider> int addRootVi <ide> int heightMeasureSpec = rootView.getHeightMeasureSpec(); <ide> updateRootView(rootShadowNode, widthMeasureSpec, heightMeasureSpec); <ide> <add> rootView.setOnSizeChangedListener( <add> new SizeMonitoringFrameLayout.OnSizeChangedListener() { <add> @Override <add> public void onSizeChanged(final int width, final int height, int oldW, int oldH) { <add> updateRootSize(rootTag, width, height); <add> } <add> }); <add> <ide> mRootShadowNodeRegistry.registerNode(rootShadowNode); <ide> mUIViewOperationQueue.addRootView(rootTag, rootView, themedRootContext); <ide> return rootTag; <ide> } <ide> <add> /** <add> * Updates the root view size and re-render the RN surface. <add> * <add> * //TODO: change synchronization to integrate with new #render loop. <add> */ <add> private synchronized void updateRootSize(int rootTag, int newWidth, int newHeight) { <add> ReactShadowNode rootNode = mRootShadowNodeRegistry.getNode(rootTag); <add> if (rootNode == null) { <add> Log.w( <add> ReactConstants.TAG, <add> "Tried to update size of non-existent tag: " + rootTag); <add> return; <add> } <add> int newWidthSpec = View.MeasureSpec.makeMeasureSpec(newWidth, View.MeasureSpec.EXACTLY); <add> int newHeightSpec = View.MeasureSpec.makeMeasureSpec(newHeight, View.MeasureSpec.EXACTLY); <add> updateRootView(rootNode, newWidthSpec, newHeightSpec); <add> <add> completeRoot(rootTag, rootNode.getChildrenList()); <add> } <add> <ide> public void removeRootView(int rootTag) { <ide> mRootShadowNodeRegistry.removeNode(rootTag); <ide> }
1
Mixed
Javascript
update example lifecycle methods
691b9e4f2a4d68ae5f3f4d48b4c944a04877e304
<ide><path>docs/api/applyMiddleware.md <ide> class SandwichShop extends Component { <ide> this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson)) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.forPerson !== this.props.forPerson) { <del> this.props.dispatch(makeASandwichWithSecretSauce(nextProps.forPerson)) <add> componentDidUpdate(prevProps) { <add> if (prevProps.forPerson !== this.props.forPerson) { <add> this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson)) <ide> } <ide> } <ide> <ide><path>docs/recipes/ReducingBoilerplate.md <ide> class Posts extends Component { <ide> this.loadData(this.props.userId) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.userId !== this.props.userId) { <del> this.loadData(nextProps.userId) <add> componentDidUpdate(prevProps) { <add> if (prevProps.userId !== this.props.userId) { <add> this.loadData(this.props.userId) <ide> } <ide> } <ide> <ide> class Posts extends Component { <ide> this.props.dispatch(loadPosts(this.props.userId)) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.userId !== this.props.userId) { <del> this.props.dispatch(loadPosts(nextProps.userId)) <add> componentDidUpdate(prevProps) { <add> if (prevProps.userId !== this.props.userId) { <add> this.props.dispatch(loadPosts(this.props.userId)) <ide> } <ide> } <ide> <ide><path>examples/async/src/containers/App.js <ide> class App extends Component { <ide> dispatch(fetchPostsIfNeeded(selectedSubreddit)) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.selectedSubreddit !== this.props.selectedSubreddit) { <del> const { dispatch, selectedSubreddit } = nextProps <add> componentDidUpdate(prevProps) { <add> if (prevProps.selectedSubreddit !== this.props.selectedSubreddit) { <add> const { dispatch, selectedSubreddit } = this.props <ide> dispatch(fetchPostsIfNeeded(selectedSubreddit)) <ide> } <ide> } <ide><path>examples/real-world/src/components/Explore.js <ide> export default class Explore extends Component { <ide> onChange: PropTypes.func.isRequired <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.value !== this.props.value) { <del> this.setInputValue(nextProps.value) <add> componentDidUpdate(prevProps) { <add> if (prevProps.value !== this.props.value) { <add> this.setInputValue(this.props.value) <ide> } <ide> } <ide> <ide><path>examples/real-world/src/containers/RepoPage.js <ide> class RepoPage extends Component { <ide> loadStargazers: PropTypes.func.isRequired <ide> } <ide> <del> componentWillMount() { <add> componentDidMount() { <ide> loadData(this.props) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.fullName !== this.props.fullName) { <del> loadData(nextProps) <add> componentDidUpdate(prevProps) { <add> if (prevProps.fullName !== this.props.fullName) { <add> loadData(this.props.fullName) <ide> } <ide> } <ide> <ide><path>examples/real-world/src/containers/UserPage.js <ide> class UserPage extends Component { <ide> loadStarred: PropTypes.func.isRequired <ide> } <ide> <del> componentWillMount() { <add> componentDidMount() { <ide> loadData(this.props) <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.login !== this.props.login) { <del> loadData(nextProps) <add> componentDidUpdate(prevProps) { <add> if (prevProps.login !== this.props.login) { <add> loadData(this.props.login) <ide> } <ide> } <ide>
6
Javascript
Javascript
fix lint errors
5be6c4c92f0c9a779a8550c974fcc93864e18db7
<ide><path>server/middlewares/migrate-completed-challenges.js <ide> const challengeTypes = { <ide> }; <ide> <ide> const idMap = { <del> "bg9997c9c79feddfaeb9bdef": "56bbb991ad1ed5201cd392ca", <del> "bg9995c9c69feddfaeb9bdef": "56bbb991ad1ed5201cd392cb", <del> "bg9994c9c69feddfaeb9bdef": "56bbb991ad1ed5201cd392cc", <del> "bg9996c9c69feddfaeb9bdef": "56bbb991ad1ed5201cd392cd", <del> "bg9997c9c69feddfaeb9bdef": "56bbb991ad1ed5201cd392ce", <del> "bg9997c9c89feddfaeb9bdef": "56bbb991ad1ed5201cd392cf", <del> "bg9998c9c99feddfaeb9bdef": "56bbb991ad1ed5201cd392d0", <del> "bg9999c9c99feddfaeb9bdef": "56bbb991ad1ed5201cd392d1", <del> "bg9999c9c99feedfaeb9bdef": "56bbb991ad1ed5201cd392d2", <del> "bg9999c9c99fdddfaeb9bdef": "56bbb991ad1ed5201cd392d3", <del> "bb000000000000000000001": "56bbb991ad1ed5201cd392d4", <del> "bc000000000000000000001": "56bbb991ad1ed5201cd392d5", <del> "bb000000000000000000002": "56bbb991ad1ed5201cd392d6", <del> "bb000000000000000000003": "56bbb991ad1ed5201cd392d7", <del> "bb000000000000000000004": "56bbb991ad1ed5201cd392d8", <del> "bb000000000000000000005": "56bbb991ad1ed5201cd392d9", <del> "bb000000000000000000006": "56bbb991ad1ed5201cd392da" <add> bg9997c9c79feddfaeb9bdef: '56bbb991ad1ed5201cd392ca', <add> bg9995c9c69feddfaeb9bdef: '56bbb991ad1ed5201cd392cb', <add> bg9994c9c69feddfaeb9bdef: '56bbb991ad1ed5201cd392cc', <add> bg9996c9c69feddfaeb9bdef: '56bbb991ad1ed5201cd392cd', <add> bg9997c9c69feddfaeb9bdef: '56bbb991ad1ed5201cd392ce', <add> bg9997c9c89feddfaeb9bdef: '56bbb991ad1ed5201cd392cf', <add> bg9998c9c99feddfaeb9bdef: '56bbb991ad1ed5201cd392d0', <add> bg9999c9c99feddfaeb9bdef: '56bbb991ad1ed5201cd392d1', <add> bg9999c9c99feedfaeb9bdef: '56bbb991ad1ed5201cd392d2', <add> bg9999c9c99fdddfaeb9bdef: '56bbb991ad1ed5201cd392d3', <add> bb000000000000000000001: '56bbb991ad1ed5201cd392d4', <add> bc000000000000000000001: '56bbb991ad1ed5201cd392d5', <add> bb000000000000000000002: '56bbb991ad1ed5201cd392d6', <add> bb000000000000000000003: '56bbb991ad1ed5201cd392d7', <add> bb000000000000000000004: '56bbb991ad1ed5201cd392d8', <add> bb000000000000000000005: '56bbb991ad1ed5201cd392d9', <add> bb000000000000000000006: '56bbb991ad1ed5201cd392da' <ide> }; <ide> <ide> const challengeTypeReg = /^(waypoint|hike|zipline|basejump)/i; <ide> function updateName(challenge) { <ide> } <ide> <ide> function updateId(challenge) { <del> if(idMap.hasOwnProperty(challenge.id)) { <add> if (idMap.hasOwnProperty(challenge.id)) { <ide> challenge.id = idMap[challenge.id]; <ide> } <ide> return challenge;
1
Text
Text
unify err_falsy_value_rejection description
23b3bbf506b8c53dad7abf70f2a27bf2d9e41746
<ide><path>doc/api/errors.md <ide> Used when `Console` is instantiated without `stdout` stream or when `stdout` or <ide> <a id="ERR_FALSY_VALUE_REJECTION"></a> <ide> ### ERR_FALSY_VALUE_REJECTION <ide> <del>The `ERR_FALSY_VALUE_REJECTION` error code is used by the `util.callbackify()` <del>API when a callbackified `Promise` is rejected with a falsy value (e.g. `null`). <add>Used by the `util.callbackify()` API when a callbackified `Promise` is rejected <add>with a falsy value (e.g. `null`). <ide> <ide> <a id="ERR_INDEX_OUT_OF_RANGE"></a> <ide> ### ERR_INDEX_OUT_OF_RANGE
1
Javascript
Javascript
use sigil instead of comparing basestate to null
76659c418f730c19fa4ca08320efd71d8de15b43
<ide><path>src/renderers/shared/fiber/ReactFiberUpdateQueue.js <ide> export type UpdateQueue<State> = { <ide> last: Update<State> | null, <ide> callbackList: Array<Update<State>> | null, <ide> hasForceUpdate: boolean, <add> isInitialized: boolean, <ide> <ide> // Dev only <ide> isProcessing?: boolean, <ide> function createUpdateQueue<State>(baseState: State): UpdateQueue<State> { <ide> last: null, <ide> callbackList: null, <ide> hasForceUpdate: false, <add> isInitialized: false, <ide> }; <ide> if (__DEV__) { <ide> queue.isProcessing = false; <ide> function processUpdateQueue<State>( <ide> expirationTime: currentQueue.expirationTime, <ide> first: currentQueue.first, <ide> last: currentQueue.last, <add> isInitialized: currentQueue.isInitialized, <ide> // These fields are no longer valid because they were already committed. <ide> // Reset them. <ide> callbackList: null, <ide> function processUpdateQueue<State>( <ide> // It depends on which fiber is the next current. Initialize with an empty <ide> // base state, then set to the memoizedState when rendering. Not super <ide> // happy with this approach. <del> let state = queue.baseState === null <del> ? workInProgress.memoizedState <del> : queue.baseState; <add> let state; <add> if (queue.isInitialized) { <add> state = queue.baseState; <add> } else { <add> state = queue.baseState = workInProgress.memoizedState; <add> queue.isInitialized = true; <add> } <ide> let dontMutatePrevState = true; <ide> let update = queue.first; <ide> let didSkip = false;
1
Python
Python
set random seed in train script
a2357cce3fdf38382fcce783b13132f4d473ddfd
<ide><path>spacy/cli/train.py <ide> from thinc.neural._classes.model import Model <ide> from thinc.neural.optimizers import linear_decay <ide> from timeit import default_timer as timer <add>import random <add>import numpy.random <ide> <ide> from ..tokens.doc import Doc <ide> from ..scorer import Scorer <ide> from .. import displacy <ide> from ..compat import json_dumps <ide> <add>random.seed(0) <add>numpy.random.seed(0) <add> <ide> <ide> @plac.annotations( <ide> lang=("model language", "positional", None, str),
1
Java
Java
add copyright header into contextutils class
fba7c1ece25f21577fdb6c2ddb25081c367a0029
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/common/ContextUtils.java <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> */ <ide> package com.facebook.react.views.common; <ide> <ide> import android.content.Context;
1
Python
Python
migrate the memory plugin to psutil 2.0
3973d36ae6d7468972065ac7a337964280aebbe1
<ide><path>glances/plugins/glances_cpu.py <ide> def update(self): <ide> for cpu in ['user', 'system', 'idle', 'nice', <ide> 'iowait', 'irq', 'softirq', 'steal', <ide> 'guest', 'guest_nice']: <del> if hasattr(cputimespercent, cpu): <add> if (hasattr(cputimespercent, cpu)): <ide> cpu_stats[cpu] = getattr(cputimespercent, cpu) <ide> <ide> # Set the global variable to the new stats <ide><path>glances/plugins/glances_mem.py <ide> <ide> # Import system libs <ide> # Check for PSUtil already done in the glances_core script <del>import psutil <add>from psutil import virtual_memory <ide> <ide> # from ..plugins.glances_plugin import GlancesPlugin <del>from glances_plugin import GlancesPlugin <add>from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> <ide> class Plugin(GlancesPlugin): <ide> def update(self): <ide> Update MEM (RAM) stats <ide> """ <ide> <del> # RAM <del> # psutil >= 0.6 <del> if hasattr(psutil, 'virtual_memory'): <del> phymem = psutil.virtual_memory() <del> <del> # buffers and cached (Linux, BSD) <del> buffers = getattr(phymem, 'buffers', 0) <del> cached = getattr(phymem, 'cached', 0) <del> <del> # active and inactive not available on Windows <del> active = getattr(phymem, 'active', 0) <del> inactive = getattr(phymem, 'inactive', 0) <del> <del> # phymem free and usage <del> total = phymem.total <del> free = phymem.available # phymem.free + buffers + cached <del> used = total - free <del> <del> self.stats = {'total': total, <del> 'percent': phymem.percent, <del> 'used': used, <del> 'free': free, <del> 'active': active, <del> 'inactive': inactive, <del> 'buffers': buffers, <del> 'cached': cached} <del> <del> # psutil < 0.6 <del> elif hasattr(psutil, 'phymem_usage'): <del> phymem = psutil.phymem_usage() <del> <del> # buffers and cached (Linux, BSD) <del> buffers = getattr(psutil, 'phymem_buffers', 0)() <del> cached = getattr(psutil, 'cached_phymem', 0)() <del> <del> # phymem free and usage <del> total = phymem.total <del> free = phymem.free + buffers + cached <del> used = total - free <del> <del> # active and inactive not available for psutil < 0.6 <del> self.stats = {'total': total, <del> 'percent': phymem.percent, <del> 'used': used, <del> 'free': free, <del> 'buffers': buffers, <del> 'cached': cached} <del> else: <del> self.stats = {} <add> # Grab CPU using the PSUtil cpu_times_percent method <add> # !!! the first time this function is called with interval = 0.0 or None <add> # !!! it will return a meaningless 0.0 value which you are supposed to ignore <add> vm_stats = virtual_memory() <add> <add> # Get all the memory stats (copy/paste of the PsUtil documentation) <add> # total: total physical memory available. <add> # available: the actual amount of available memory that can be given instantly to processes that request more memory in bytes; this is calculated by summing different memory values depending on the platform (e.g. free + buffers + cached on Linux) and it is supposed to be used to monitor actual memory usage in a cross platform fashion. <add> # percent: the percentage usage calculated as (total - available) / total * 100. <add> # used: memory used, calculated differently depending on the platform and designed for informational purposes only. <add> # free: memory not being used at all (zeroed) that is readily available; note that this doesn’t reflect the actual memory available (use ‘available’ instead). <add> # Platform-specific fields: <add> # active: (UNIX): memory currently in use or very recently used, and so it is in RAM. <add> # inactive: (UNIX): memory that is marked as not used. <add> # buffers: (Linux, BSD): cache for things like file system metadata. <add> # cached: (Linux, BSD): cache for various things. <add> # wired: (BSD, OSX): memory that is marked to always stay in RAM. It is never moved to disk. <add> # shared: (BSD): memory that may be simultaneously accessed by multiple processes. <add> mem_stats = {} <add> for mem in ['total', 'available', 'percent', 'used', 'free', <add> 'active', 'inactive', 'buffers', 'cached', <add> 'wired', 'shared']: <add> if (hasattr(vm_stats, mem)): <add> mem_stats[mem] = getattr(vm_stats, mem) <add> <add> # Use the 'free'/htop calculation <add> # free=available+buffer+cached <add> mem_stats['free'] = mem_stats['available'] <add> if (hasattr(mem_stats, 'buffer')): <add> mem_stats['free'] += mem_stats['buffer'] <add> if (hasattr(mem_stats, 'cached')): <add> mem_stats['free'] += mem_stats['cached'] <add> # used=total-free <add> mem_stats['used'] = mem_stats['total'] - mem_stats['free'] <add> <add> # Set the global variable to the new stats <add> self.stats = mem_stats <add> <add> return self.stats <ide> <ide> def msg_curse(self, args=None): <ide> """
2
PHP
PHP
fix strict error in 5.4
921c2c67abf7afdd7d6d2199a5216fd80dc5ba3f
<ide><path>lib/Cake/Utility/ObjectCollection.php <ide> public function attached($name = null) { <ide> * @return void <ide> */ <ide> public function unload($name) { <del> $name = array_pop(pluginSplit($name)); <add> list(, $name) = pluginSplit($name); <ide> unset($this->_loaded[$name], $this->_enabled[$name]); <ide> } <ide>
1
Javascript
Javascript
run firefox in headless mode
786ca86cb03f3d5f290faafdcb1016245ce81334
<ide><path>testem.travis-browsers.js <ide> module.exports = { <ide> launch_in_dev: ['Firefox'], <ide> launch_in_ci: ['Firefox'], <ide> reporter: FailureOnlyReporter, <add> <add> browser_args: { <add> Firefox: { ci: ['-headless', '--window-size=1440,900'] }, <add> }, <ide> };
1
Python
Python
add test_connection method to azure wasbhook
f18c609d127f54fbbf4dae6b290c6cdcfc7f98d0
<ide><path>airflow/providers/microsoft/azure/hooks/wasb.py <ide> def delete_file( <ide> raise AirflowException(f'Blob(s) not found: {blob_name}') <ide> <ide> self.delete_blobs(container_name, *blobs_to_delete, **kwargs) <add> <add> def test_connection(self): <add> """Test Azure Blob Storage connection.""" <add> success = (True, "Successfully connected to Azure Blob Storage.") <add> <add> try: <add> # Attempt to retrieve storage account information <add> self.get_conn().get_account_information() <add> return success <add> except Exception as e: <add> return False, str(e) <ide><path>tests/providers/microsoft/azure/hooks/test_wasb.py <ide> def test_delete_multiple_nonexisting_blobs_fails(self, mock_getblobs): <ide> hook = WasbHook(wasb_conn_id=self.shared_key_conn_id) <ide> hook.delete_file('container', 'nonexisting_blob_prefix', is_prefix=True, ignore_if_missing=False) <ide> assert isinstance(ctx.value, AirflowException) <add> <add> @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.BlobServiceClient") <add> def test_connection_success(self, mock_service): <add> hook = WasbHook(wasb_conn_id=self.shared_key_conn_id) <add> hook.get_conn().get_account_information().return_value = { <add> 'sku_name': 'Standard_RAGRS', <add> 'account_kind': 'StorageV2', <add> } <add> status, msg = hook.test_connection() <add> <add> assert status is True <add> assert msg == "Successfully connected to Azure Blob Storage." <add> <add> @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.BlobServiceClient") <add> def test_connection_failure(self, mock_service): <add> hook = WasbHook(wasb_conn_id=self.shared_key_conn_id) <add> hook.get_conn().get_account_information = mock.PropertyMock( <add> side_effect=Exception("Authentication failed.") <add> ) <add> status, msg = hook.test_connection() <add> assert status is False <add> assert msg == "Authentication failed."
2
Javascript
Javascript
exercise more features in the randomized test
d83304cbddbdf661f656b04137ee10b66121db14
<ide><path>spec/text-editor-component-spec.js <ide> const electron = require('electron') <ide> const clipboard = require('../src/safe-clipboard') <ide> <ide> const SAMPLE_TEXT = fs.readFileSync(path.join(__dirname, 'fixtures', 'sample.js'), 'utf8') <del>const NBSP_CHARACTER = '\u00a0' <ide> <ide> document.registerElement('text-editor-component-test-element', { <ide> prototype: Object.create(HTMLElement.prototype, { <ide> describe('TextEditorComponent', () => { <ide> <ide> it('renders the visible rows correctly after randomly mutating the editor', async () => { <ide> const initialSeed = Date.now() <del> for (var i = 0; i < 50; i++) { <add> for (var i = 0; i < 20; i++) { <ide> let seed = initialSeed + i <del> // seed = 1507195048481 <add> // seed = 1507224195357 <ide> const failureMessage = 'Randomized test failed with seed: ' + seed <ide> const random = Random(seed) <ide> <ide> describe('TextEditorComponent', () => { <ide> element.focus() <ide> <ide> for (var j = 0; j < 5; j++) { <del> const k = random(10) <add> const k = random(100) <ide> const range = getRandomBufferRange(random, editor.buffer) <ide> <del> if (k < 1) { <add> if (k < 10) { <ide> editor.setSoftWrapped(!editor.isSoftWrapped()) <del> } else if (k < 4) { <add> } else if (k < 15) { <add> if (random(2)) setEditorWidthInCharacters(component, random(20)) <add> if (random(2)) setEditorHeightInLines(component, random(10)) <add> } else if (k < 40) { <ide> editor.setSelectedBufferRange(range) <ide> editor.backspace() <del> } else if (k < 8) { <add> } else if (k < 80) { <ide> const linesToInsert = buildRandomLines(random, 5) <ide> editor.setCursorBufferPosition(range.start) <ide> editor.insertText(linesToInsert) <del> } else { <add> } else if (k < 90) { <add> if (random(2)) { <add> editor.foldBufferRange(range) <add> } else { <add> editor.destroyFoldsIntersectingBufferRange(range) <add> } <add> } else if (k < 95) { <ide> editor.setSelectedBufferRange(range) <add> } else { <add> if (random(2)) component.setScrollTop(random(component.getScrollHeight())) <add> if (random(2)) component.setScrollLeft(random(component.getScrollWidth())) <ide> } <ide> <ide> component.scheduleUpdate() <ide> describe('TextEditorComponent', () => { <ide> const renderedLines = queryOnScreenLineElements(element).sort((a, b) => a.dataset.screenRow - b.dataset.screenRow) <ide> const renderedLineNumbers = queryOnScreenLineNumberElements(element).sort((a, b) => a.dataset.screenRow - b.dataset.screenRow) <ide> const renderedStartRow = component.getRenderedStartRow() <del> const actualLines = editor.displayLayer.getScreenLines(renderedStartRow, component.getRenderedEndRow()) <del> <del> expect(renderedLines.length).toBe(actualLines.length, failureMessage) <del> expect(renderedLineNumbers.length).toBe(actualLines.length, failureMessage) <del> for (let i = 0; i < renderedLines.length; i++) { <del> expect(renderedLines[i].textContent).toBe(actualLines[i].lineText || ' ', failureMessage) <del> expect(parseInt(renderedLines[i].dataset.screenRow)).toBe(renderedStartRow + i, failureMessage) <del> expect(parseInt(renderedLineNumbers[i].dataset.screenRow)).toBe(renderedStartRow + i, failureMessage) <add> const expectedLines = editor.displayLayer.getScreenLines(renderedStartRow, component.getRenderedEndRow()) <add> <add> expect(renderedLines.length).toBe(expectedLines.length, failureMessage) <add> expect(renderedLineNumbers.length).toBe(expectedLines.length, failureMessage) <add> for (let k = 0; k < renderedLines.length; k++) { <add> const expectedLine = expectedLines[k] <add> const expectedText = expectedLine.lineText || ' ' <add> <add> const renderedLine = renderedLines[k] <add> const renderedLineNumber = renderedLineNumbers[k] <add> let renderedText = renderedLine.textContent <add> // We append zero width NBSPs after folds at the end of the <add> // line in order to support measurement. <add> if (expectedText.endsWith(editor.displayLayer.foldCharacter)) { <add> renderedText = renderedText.substring(0, renderedText.length - 1) <add> } <add> <add> expect(renderedText).toBe(expectedText, failureMessage) <add> expect(parseInt(renderedLine.dataset.screenRow)).toBe(renderedStartRow + k, failureMessage) <add> expect(parseInt(renderedLineNumber.dataset.screenRow)).toBe(renderedStartRow + k, failureMessage) <ide> } <ide> } <ide>
1
Text
Text
remove unnecessary backticks
ce3ccc47d41774a284cc375d0aa3207e2ef92e09
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.md <ide> dashedName: global-vs--local-scope-in-functions <ide> <ide> # --description-- <ide> <del>It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the `local` variable takes precedence over the `global` variable. <add>It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the local variable takes precedence over the global variable. <ide> <ide> In this example: <ide> <ide> function myFun() { <ide> } <ide> ``` <ide> <del>The function `myFun` will return the string `Head` because the `local` version of the variable is present. <add>The function `myFun` will return the string `Head` because the local version of the variable is present. <ide> <ide> # --instructions-- <ide>
1
Python
Python
add check for printing complex dtypes, closes #693
be25d94bfc6f72535700432e87a52e4a15f0f8f5
<ide><path>numpy/core/tests/test_regression.py <ide> def check_floats_from_string(self, level=rlevel): <ide> assert_almost_equal(fdouble, 1.234) <ide> assert_almost_equal(flongdouble, 1.234) <ide> <add> def check_complex_dtype_printing(self, level=rlevel): <add> dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), <add> ('rtile', '>f4', (64, 36))], (3,)), <add> ('bottom', [('bleft', ('>f4', (8, 64)), (1,)), <add> ('bright', '>f4', (8, 36))])]) <add> assert_equal(str(dt), <add> "[('top', [('tiles', ('>f4', (64, 64)), (1,)), " <add> "('rtile', '>f4', (64, 36))], (3,)), " <add> "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), " <add> "('bright', '>f4', (8, 36))])]") <ide> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Text
Text
fix minor typos
15bb1d59c873357c0dc1f837d97a2aa3e5981c71
<ide><path>guides/source/i18n.md <ide> end <ide> <ide> With this approach you will not get a `Routing Error` when accessing your resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified. <ide> <del>Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.) <add>Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "dashboard#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.) <ide> <ide> You would probably need to map URLs like these: <ide> <ide> errors.attributes.name.blank <ide> errors.messages.blank <ide> ``` <ide> <del>This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes. <add>This way you can provide special translations for various error messages at different points in your model's inheritance chain and in the attributes, models, or default scopes. <ide> <ide> #### Error Message Interpolation <ide> <ide> I18n.exception_handler = I18n::JustRaiseExceptionHandler.new <ide> <ide> This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler. <ide> <del>However, if you are using `I18n::Backend::Pluralization` this handler will also raise `I18n::MissingTranslationData: translation missing: en.i18n.plural.rule` exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key: <add>However, if you are using `I18n::Backend::Pluralization` this handler will also raise `I18n::MissingTranslationData: translation missing: en.i18n.plural.rule` exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use an additional check for the translation key: <ide> <ide> ```ruby <ide> if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
1
Ruby
Ruby
show wsl version if available on linux
55c82749ad8343541d15f91227478035363bff12
<ide><path>Library/Homebrew/extend/os/linux/system_config.rb <ide> def host_ruby_version <ide> out <ide> end <ide> <add> def wsl_version(kernel) <add> return "no" unless /-microsoft/i.match?(kernel) <add> <add> return "2 (store)" if Version.new kernel[/Linux ([0-9.]*)-.*/, 1] > Version.new("5.15") <add> return "2" if /-microsoft/.match?(kernel) <add> return "1" if /-Microsoft/.match?(kernel) <add> end <add> <ide> def dump_verbose_config(out = $stdout) <add> kernel = Utils.safe_popen_read("uname", "-mors").chomp <ide> dump_generic_verbose_config(out) <del> out.puts "Kernel: #{`uname -mors`.chomp}" <add> out.puts "Kernel: #{kernel}" <ide> out.puts "OS: #{OS::Linux.os_version}" <add> out.puts "WSL: #{wsl_version(kernel)}" <ide> out.puts "Host glibc: #{host_glibc_version}" <ide> out.puts "/usr/bin/gcc: #{host_gcc_version}" <ide> out.puts "/usr/bin/ruby: #{host_ruby_version}" if RUBY_PATH != HOST_RUBY_PATH
1
Javascript
Javascript
manage children inside dom properties
7cd26b9c7172465981b70ea6bf0bb9b09ce8b715
<ide><path>src/renderers/dom/fiber/ReactDOMFiberComponent.js <ide> <ide> var AutoFocusUtils = require('AutoFocusUtils'); <ide> var CSSPropertyOperations = require('CSSPropertyOperations'); <del>var DOMLazyTree = require('DOMLazyTree'); <ide> var DOMNamespaces = require('DOMNamespaces'); <ide> var DOMProperty = require('DOMProperty'); <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <ide> var ReactDOMFiberInput = require('ReactDOMFiberInput'); <ide> var ReactDOMFiberOption = require('ReactDOMFiberOption'); <ide> var ReactDOMFiberSelect = require('ReactDOMFiberSelect'); <ide> var ReactDOMFiberTextarea = require('ReactDOMFiberTextarea'); <del>var ReactMultiChild = require('ReactMultiChild'); <ide> var ReactServerRenderingTransaction = require('ReactServerRenderingTransaction'); <ide> <ide> var emptyFunction = require('emptyFunction'); <ide> var escapeTextContentForBrowser = require('escapeTextContentForBrowser'); <ide> var invariant = require('invariant'); <ide> var isEventSupported = require('isEventSupported'); <add>var setInnerHTML = require('setInnerHTML'); <add>var setTextContent = require('setTextContent'); <ide> var shallowEqual = require('shallowEqual'); <ide> var inputValueTracking = require('inputValueTracking'); <ide> var warning = require('warning'); <ide> var registrationNameModules = EventPluginRegistry.registrationNameModules; <ide> // For quickly matching children type, to test if can be treated as content. <ide> var CONTENT_TYPES = {'string': true, 'number': true}; <ide> <add>var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML'; <add>var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning'; <add>var CHILDREN = 'children'; <ide> var STYLE = 'style'; <ide> var HTML = '__html'; <del>var RESERVED_PROPS = { <del> children: null, <del> dangerouslySetInnerHTML: null, <del> suppressContentEditableWarning: null, <del>}; <ide> <ide> // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). <ide> var DOC_FRAGMENT_TYPE = 11; <ide> function isCustomComponent(tagName, props) { <ide> return tagName.indexOf('-') >= 0 || props.is != null; <ide> } <ide> <del>function createInitialChildren(workInProgress, transaction, props, context, lazyTree) { <del> // Intentional use of != to avoid catching zero/false. <del> var innerHTML = props.dangerouslySetInnerHTML; <del> if (innerHTML != null) { <del> if (innerHTML.__html != null) { <del> DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); <del> } <del> } else { <del> var contentToUse = <del> CONTENT_TYPES[typeof props.children] ? props.children : null; <del> var childrenToUse = contentToUse != null ? null : props.children; <del> // TODO: Validate that text is allowed as a child of this node <del> if (contentToUse != null) { <del> // Avoid setting textContent when the text is empty. In IE11 setting <del> // textContent on a text area will cause the placeholder to not <del> // show within the textarea until it has been focused and blurred again. <del> // https://github.com/facebook/react/issues/6731#issuecomment-254874553 <del> if (contentToUse !== '') { <del> DOMLazyTree.queueText(lazyTree, contentToUse); <del> } <del> } else if (childrenToUse != null) { <del> var mountImages = workInProgress.mountChildren( <del> childrenToUse, <del> transaction, <del> context <del> ); <del> for (var i = 0; i < mountImages.length; i++) { <del> DOMLazyTree.queueChild(lazyTree, mountImages[i]); <del> } <del> } <del> } <del>} <del> <ide> /** <ide> * Reconciles the properties by detecting differences in property values and <ide> * updating the DOM as necessary. This function is probably the single most <ide> function updateDOMProperties( <ide> styleUpdates[styleName] = ''; <ide> } <ide> } <add> } else if (propKey === DANGEROUSLY_SET_INNER_HTML || <add> propKey === CHILDREN) { <add> // TODO: Clear innerHTML. This is currently broken in Fiber because we are <add> // too late to clear everything at this point because new children have <add> // already been inserted. <add> } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING) { <add> // Noop <ide> } else if (registrationNameModules.hasOwnProperty(propKey)) { <ide> // Do nothing for deleted listeners. <ide> } else if (isCustomComponent(workInProgress._tag, lastProps)) { <del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) { <del> DOMPropertyOperations.deleteValueForAttribute( <del> getNode(workInProgress), <del> propKey <del> ); <del> } <add> DOMPropertyOperations.deleteValueForAttribute( <add> getNode(workInProgress), <add> propKey <add> ); <ide> } else if ( <ide> DOMProperty.properties[propKey] || <ide> DOMProperty.isCustomAttribute(propKey)) { <ide> function updateDOMProperties( <ide> // Relies on `updateStylesByID` not mutating `styleUpdates`. <ide> styleUpdates = nextProp; <ide> } <add> } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { <add> if (lastProp && nextProp) { <add> var lastHtml = lastProp[HTML]; <add> var nextHtml = nextProp[HTML]; <add> if (lastHtml !== nextHtml) { <add> if (nextHtml == null) { <add> // TODO: It might be too late to clear this if we have children <add> // inserted already. <add> } else { <add> setInnerHTML(getNode(workInProgress), '' + nextHtml); <add> } <add> } <add> } else if (nextProp) { <add> var nextHtml = nextProp[HTML]; <add> setInnerHTML(getNode(workInProgress), nextProp); <add> } <add> } else if (propKey === CHILDREN) { <add> if (typeof nextProp === 'string') { <add> setTextContent(getNode(workInProgress), nextProp); <add> } else if (typeof nextProp === 'number') { <add> setTextContent(getNode(workInProgress), '' + nextProp); <add> } <add> } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING) { <add> // Noop <ide> } else if (registrationNameModules.hasOwnProperty(propKey)) { <ide> if (nextProp) { <ide> ensureListeningTo(workInProgress, propKey, transaction); <ide> } <ide> } else if (isCustomComponentTag) { <del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) { <del> DOMPropertyOperations.setValueForAttribute( <del> getNode(workInProgress), <del> propKey, <del> nextProp <del> ); <del> } <add> DOMPropertyOperations.setValueForAttribute( <add> getNode(workInProgress), <add> propKey, <add> nextProp <add> ); <ide> } else if ( <ide> DOMProperty.properties[propKey] || <ide> DOMProperty.isCustomAttribute(propKey)) { <ide> function updateDOMProperties( <ide> } <ide> } <ide> <del>/** <del> * Reconciles the children with the various properties that affect the <del> * children content. <del> * <del> * @param {object} lastProps <del> * @param {object} nextProps <del> * @param {ReactReconcileTransaction} transaction <del> * @param {object} context <del> */ <del>function updateDOMChildren(workInProgress, lastProps, nextProps, transaction, context) { <del> var lastContent = <del> CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; <del> var nextContent = <del> CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; <del> <del> var lastHtml = <del> lastProps.dangerouslySetInnerHTML && <del> lastProps.dangerouslySetInnerHTML.__html; <del> var nextHtml = <del> nextProps.dangerouslySetInnerHTML && <del> nextProps.dangerouslySetInnerHTML.__html; <del> <del> // Note the use of `!=` which checks for null or undefined. <del> var lastChildren = lastContent != null ? null : lastProps.children; <del> var nextChildren = nextContent != null ? null : nextProps.children; <del> <del> // If we're switching from children to content/html or vice versa, remove <del> // the old content <del> var lastHasContentOrHtml = lastContent != null || lastHtml != null; <del> var nextHasContentOrHtml = nextContent != null || nextHtml != null; <del> if (lastChildren != null && nextChildren == null) { <del> workInProgress.updateChildren(null, transaction, context); <del> } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { <del> workInProgress.updateTextContent(''); <del> } <del> <del> if (nextContent != null) { <del> if (lastContent !== nextContent) { <del> workInProgress.updateTextContent('' + nextContent); <del> } <del> } else if (nextHtml != null) { <del> if (lastHtml !== nextHtml) { <del> workInProgress.updateMarkup('' + nextHtml); <del> } <del> } else if (nextChildren != null) { <del> workInProgress.updateChildren(nextChildren, transaction, context); <del> } <del>} <del> <ide> var ReactDOMFiberComponent = { <ide> <ide> <ide> var ReactDOMFiberComponent = { <ide> DOMPropertyOperations.setAttributeForRoot(el); <ide> } <ide> updateDOMProperties(workInProgress, null, props, transaction, isCustomComponentTag); <del> var lazyTree = DOMLazyTree(el); <del> createInitialChildren(workInProgress, transaction, props, context, lazyTree); <del> mountImage = lazyTree; <ide> <ide> switch (workInProgress._tag) { <ide> case 'input': <ide> var ReactDOMFiberComponent = { <ide> break; <ide> } <ide> <del> return mountImage; <add> return el; <ide> }, <ide> <ide> <ide> var ReactDOMFiberComponent = { <ide> assertValidProps(workInProgress, nextProps); <ide> var isCustomComponentTag = isCustomComponent(workInProgress._tag, nextProps); <ide> updateDOMProperties(workInProgress, lastProps, nextProps, transaction, isCustomComponentTag); <del> updateDOMChildren( <del> workInProgress, <del> lastProps, <del> nextProps, <del> transaction, <del> context <del> ); <ide> <ide> switch (workInProgress._tag) { <ide> case 'input': <ide> var ReactDOMFiberComponent = { <ide> break; <ide> } <ide> <del> workInProgress.unmountChildren(safely, skipLifecycle); <ide> ReactDOMComponentTree.uncacheNode(workInProgress); <ide> workInProgress._wrapperState = null; <ide> },
1
Text
Text
correct typos in security release process
a1e47d7603b1d0bf54c8aad027298e964b8c8af4
<ide><path>doc/guides/security_release_process.md <ide> a security release. <ide> * [ ] Co-ordinate with the Release team members to line up one or more releasers <ide> to do the releases on the agreed date. <ide> <del>* [ ] Prep for the pre-security announcement and final security annoucement by <add>* [ ] Prep for the pre-security announcement and final security announcement by <ide> getting agreement on drafts following the <ide> [security_announcement_process](https://github.com/nodejs/security-wg/blob/master/processes/security_annoucement_process.md). <ide> <ide> a security release. <ide> <ide> * [ ] Co-ordinate with the Release team members and keep up to date on progress. <ide> Get an guesstimate of when releases may be ready and send an FYI to the docker <del> offical image <add> official image <ide> [maintainers](https://github.com/docker-library/official-images/blob/master/MAINTAINERS). <ide> <ide> * [ ] When the releases are promoted, ensure the final announce goes out as per <ide> a security release. <ide> [cve_management_process](https://github.com/nodejs/security-wg/blob/master/processes/cve_management_process.md). <ide> <ide> * [ ] Ensure that the announced CVEs are updated in the cve-management <del> repository as per the the <add> repository as per the <ide> [cve_management_process](https://github.com/nodejs/security-wg/blob/master/processes/cve_management_process.md) <ide> so that they are listed under Announced. <ide>
1
Python
Python
add rabbitmq export for glances
553de758d56ff09d29e5167167dc04bba236a13e
<ide><path>glances/exports/glances_rabbitmq.py <add># -*- coding: utf-8 -*- <add># <add># This file is part of Glances. <add># <add># Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> <add># <add># Glances is free software; you can redistribute it and/or modify <add># it under the terms of the GNU Lesser General Public License as published by <add># the Free Software Foundation, either version 3 of the License, or <add># (at your option) any later version. <add># <add># Glances is distributed in the hope that it will be useful, <add># but WITHOUT ANY WARRANTY; without even the implied warranty of <add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add># GNU Lesser General Public License for more details. <add># <add># You should have received a copy of the GNU Lesser General Public License <add># along with this program. If not, see <http://www.gnu.org/licenses/>. <add> <add>"""JMS interface class.""" <add> <add># Import sys libs <add>import sys, socket, datetime <add>from numbers import Number <add> <add># Import Glances lib <add>from glances.core.glances_logging import logger <add>from ConfigParser import NoSectionError, NoOptionError <add>from glances.exports.glances_export import GlancesExport <add> <add># Import pika for RabbitMQ <add>import pika <add> <add> <add>class Export(GlancesExport): <add> <add> """This class manages the rabbitMQ export module.""" <add> <add> def __init__(self, config=None, args=None): <add> """Init the RabbitMQ export IF.""" <add> GlancesExport.__init__(self, config=config, args=args) <add> <add> # Load the rabbitMQ configuration file <add> self.rabbitmq_host = None <add> self.rabbitmq_port = None <add> self.rabbitmq_user = None <add> self.rabbitmq_password = None <add> self.rabbitmq_queue = None <add> self.hostname = socket.gethostname() <add> self.export_enable = self.load_conf() <add> if not self.export_enable: <add> sys.exit(2) <add> <add> # Init the rabbitmq client <add> self.client = self.init() <add> <add> def load_conf(self, section="rabbitmq"): <add> """Load the rabbitmq configuration in the Glances configuration file""" <add> if self.config is None: <add> return False <add> try: <add> self.rabbitmq_host = self.config.get_raw_option(section, "host") <add> self.rabbitmq_port = self.config.get_raw_option(section, "port") <add> self.rabbitmq_user = self.config.get_raw_option(section, "user") <add> self.rabbitmq_password = self.config.get_raw_option(section, "password") <add> self.rabbitmq_queue = self.config.get_raw_option(section, "queue") <add> except NoSectionError: <add> logger.critical("No rabbitmq configuration found") <add> return False <add> except NoOptionError as e: <add> logger.critical("Error in the RabbitM configuration (%s)" % e) <add> return False <add> else: <add> logger.debug("Load RabbitMQ from the Glances configuration file") <add> return True <add> <add> def init(self): <add> """Init the connection to the rabbitmq server""" <add> if not self.export_enable: <add> return None <add> try: <add> parameters = pika.URLParameters("amqp://"+self.rabbitmq_user+":"+self.rabbitmq_password+"@"+self.rabbitmq_host+":"+self.rabbitmq_port+"/") <add> connection = pika.BlockingConnection(parameters) <add> channel = connection.channel() <add> return channel <add> except Exception as e: <add> logger.critical("Connection to rabbitMQ failed : %s" % e) <add> return None <add> <add> def export(self, name, columns, points): <add> """Write the points in RabbitMQ""" <add> if self.client.is_open: <add> logger.error ("ouvert") <add> data = "hostname="+self.hostname+", name="+name+", dateinfo="+datetime.datetime.utcnow().isoformat() <add> for i in range(0, len(columns)): <add> if not isinstance(points[i], Number): <add> continue <add> else: <add> data += ", "+columns[i]+"="+str(points[i]) <add> logger.debug(data) <add> try: <add> self.client.basic_publish(exchange='', routing_key="glances_queue", body=data) <add> except Exception as e: <add> logger.error("Can not export stats to RabbitMQ (%s)" % e)
1
Python
Python
add clusterresolver capability to mnist_tpu.py
87a9205b75857c1b6ac01de97f003389280c8f17
<ide><path>official/mnist/mnist_tpu.py <ide> import dataset <ide> import mnist <ide> <add># Cloud TPU Cluster Resolvers <add>tf.flags.DEFINE_string( <add> "gcp_project", default=None, <add> help="Project name for the Cloud TPU-enabled project. If not specified, we " <add> "will attempt to automatically detect the GCE project from metadata.") <add>tf.flags.DEFINE_string( <add> "tpu_zone", default=None, <add> help="GCE zone where the Cloud TPU is located in. If not specified, we " <add> "will attempt to automatically detect the GCE project from metadata.") <add>tf.flags.DEFINE_string( <add> "tpu_name", default=None, <add> help="Name of the Cloud TPU for Cluster Resolvers. You must specify either " <add> "this flag or --master.") <add> <add># Model specific paramenters <add>tf.flags.DEFINE_string( <add> "master", default=None, <add> help="GRPC URL of the master (e.g. grpc://ip.address.of.tpu:8470). You " <add> "must specify either this flag or --tpu_name.") <add> <ide> tf.flags.DEFINE_string("data_dir", "", <ide> "Path to directory containing the MNIST dataset") <ide> tf.flags.DEFINE_string("model_dir", None, "Estimator model_dir") <ide> tf.flags.DEFINE_float("learning_rate", 0.05, "Learning rate.") <ide> <ide> tf.flags.DEFINE_bool("use_tpu", True, "Use TPUs rather than plain CPUs") <del>tf.flags.DEFINE_string("master", "local", "GRPC URL of the Cloud TPU instance.") <ide> tf.flags.DEFINE_integer("iterations", 50, <ide> "Number of iterations per TPU training loop.") <ide> tf.flags.DEFINE_integer("num_shards", 8, "Number of shards (TPU chips).") <ide> def main(argv): <ide> del argv # Unused. <ide> tf.logging.set_verbosity(tf.logging.INFO) <ide> <add> if FLAGS.master is None and FLAGS.tpu_name is None: <add> raise RuntimeError("You must specify either --master or --tpu_name.") <add> <add> if FLAGS.master is not None: <add> if FLAGS.tpu_name is not None: <add> tf.logging.warn("Both --master and --tpu_name are set. Ignoring " <add> "--tpu_name and using --master.") <add> tpu_grpc_url = FLAGS.master <add> else: <add> tpu_cluster_resolver = ( <add> tf.contrib.cluster_resolver.python.training.TPUClusterResolver( <add> tpu_names=[FLAGS.tpu_name], <add> zone=FLAGS.tpu_zone, <add> project=FLAGS.gcp_project)) <add> tpu_grpc_url = tpu_cluster_resolver.get_master() <add> <ide> run_config = tf.contrib.tpu.RunConfig( <del> master=FLAGS.master, <del> evaluation_master=FLAGS.master, <add> master=tpu_grpc_url, <add> evaluation_master=tpu_grpc_url, <ide> model_dir=FLAGS.model_dir, <ide> session_config=tf.ConfigProto( <ide> allow_soft_placement=True, log_device_placement=True),
1
Text
Text
add missing entry in `globals.md`
4c81b34428914b9d80f4189835d124e420515844
<ide><path>doc/api/globals.md <ide> added: v0.0.1 <ide> <ide> [`setTimeout`][] is described in the [timers][] section. <ide> <add>## `structuredClone(value[, options])` <add> <add><!-- YAML <add>added: v17.0.0 <add>--> <add> <add><!-- type=global --> <add> <add>The WHATWG [`structuredClone`][] method. <add> <ide> ## `DOMException` <ide> <ide> <!-- YAML <ide> The object that acts as the namespace for all W3C <ide> [`setImmediate`]: timers.md#setimmediatecallback-args <ide> [`setInterval`]: timers.md#setintervalcallback-delay-args <ide> [`setTimeout`]: timers.md#settimeoutcallback-delay-args <add>[`structuredClone`]: https://developer.mozilla.org/en-US/docs/Web/API/structuredClone <ide> [buffer section]: buffer.md <ide> [built-in objects]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects <ide> [module system documentation]: modules.md
1
Javascript
Javascript
avoid new set([iterable]) for thenables
0fc15475139206f1f999b5c16bbe6f90142e936a
<ide><path>packages/react-reconciler/src/ReactFiberUnwindWork.js <ide> function throwException( <ide> // attach another listener to flip the boundary back to its normal state. <ide> const thenables: Set<Thenable> = (workInProgress.updateQueue: any); <ide> if (thenables === null) { <del> workInProgress.updateQueue = (new Set([thenable]): any); <add> workInProgress.updateQueue = (new Set(): any); <add> workInProgress.updateQueue.add(thenable); <ide> } else { <ide> thenables.add(thenable); <ide> }
1
PHP
PHP
remove invalid inflection
b2291609554b4197b5cc3669bcad64cc25c55bfc
<ide><path>src/Routing/Router.php <ide> public static function parseRoutePath(string $url): array <ide> $defaults['plugin'] = $matches['plugin']; <ide> } <ide> if ($matches['prefix'] !== '') { <del> $defaults['prefix'] = Inflector::underscore($matches['prefix']); <add> $defaults['prefix'] = $matches['prefix']; <ide> } <ide> $defaults['controller'] = $matches['controller']; <ide> $defaults['action'] = $matches['action'];
1
Text
Text
add changelogs for querystring
e9680c5e6803b42ce46c455cfed3936bfe8b60e4
<ide><path>doc/api/querystring.md <ide> necessary by assigning `querystring.escape` to an alternative function. <ide> ## querystring.parse(str[, sep[, eq[, options]]]) <ide> <!-- YAML <ide> added: v0.1.25 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/6055 <add> description: The returned object no longer inherits from `Object.prototype`. <add> - version: v6.0.0, v4.2.4 <add> pr-url: https://github.com/nodejs/node/pull/3807 <add> description: The `eq` parameter may now have a length of more than `1`. <ide> --> <ide> <ide> * `str` {String} The URL query string to parse
1
Python
Python
use empty lines for mpl_toolkits.mplot3d objects
5ee37b0e7966cd7181f3436a6758b19871d2597f
<ide><path>doc/conftest.py <ide> # https://github.com/wooyek/pytest-doctest-ellipsis-markers (MIT license) <ide> OutputChecker = doctest.OutputChecker <ide> <add>empty_line_markers = ['<matplotlib.', '<mpl_toolkits.mplot3d.'] <ide> class SkipMatplotlibOutputChecker(doctest.OutputChecker): <ide> def check_output(self, want, got, optionflags): <del> if '<matplotlib.' in got: <del> got = '' <add> for marker in empty_line_markers: <add> if marker in got: <add> got = '' <add> break <ide> return OutputChecker.check_output(self, want, got, optionflags) <ide> <ide> doctest.OutputChecker = SkipMatplotlibOutputChecker
1
Ruby
Ruby
rewrite order dependent test case.
e68505a41a5c4ceeb0ed343daa0433846b054076
<ide><path>activesupport/test/json/encoding_test.rb <ide> def test_to_json_should_not_keep_options_around <ide> f.bar = "world" <ide> <ide> hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}} <del> assert_equal(%({"foo":{"foo":"hello","bar":"world"},"other_hash":{"foo":"other_foo","test":"other_test"}}), hash.to_json) <add> assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"}, <add> "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, JSON.parse(hash.to_json)) <ide> end <ide> <ide> def test_struct_encoding
1
Go
Go
remove cli.build(), cli.inspect()
940730093b4bc71837009e815352af49f60d2fd0
<ide><path>integration-cli/cli/cli.go <ide> func DockerCmd(t testing.TB, args ...string) *icmd.Result { <ide> <ide> // BuildCmd executes the specified docker build command and expect a success <ide> func BuildCmd(t testing.TB, name string, cmdOperators ...CmdOperator) *icmd.Result { <del> return Docker(Build(name), cmdOperators...).Assert(t, icmd.Success) <add> return Docker(Args("build", "-t", name), cmdOperators...).Assert(t, icmd.Success) <ide> } <ide> <ide> // InspectCmd executes the specified docker inspect command and expect a success <ide> func InspectCmd(t testing.TB, name string, cmdOperators ...CmdOperator) *icmd.Result { <del> return Docker(Inspect(name), cmdOperators...).Assert(t, icmd.Success) <add> return Docker(Args("inspect", name), cmdOperators...).Assert(t, icmd.Success) <ide> } <ide> <ide> // WaitRun will wait for the specified container to be running, maximum 5 seconds. <ide> func validateArgs(args ...string) error { <ide> return nil <ide> } <ide> <del>// Build executes the specified docker build command <del>func Build(name string) icmd.Cmd { <del> return icmd.Command("build", "-t", name) <del>} <del> <del>// Inspect executes the specified docker inspect command <del>func Inspect(name string) icmd.Cmd { <del> return icmd.Command("inspect", name) <del>} <del> <ide> // Format sets the specified format with --format flag <ide> func Format(format string) func(*icmd.Cmd) func() { <ide> return func(cmd *icmd.Cmd) func() { <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerCLIBuildSuite) TestBuildCacheAdd(c *testing.T) { <ide> cli.BuildCmd(c, name, build.WithDockerfile(fmt.Sprintf(`FROM scratch <ide> ADD %s/robots.txt /`, server.URL()))) <ide> <del> result := cli.Docker(cli.Build(name), build.WithDockerfile(fmt.Sprintf(`FROM scratch <add> result := cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(fmt.Sprintf(`FROM scratch <ide> ADD %s/index.html /`, server.URL()))) <ide> result.Assert(c, icmd.Success) <ide> if strings.Contains(result.Combined(), "Using cache") { <ide> func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) { <ide> ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n")) <ide> defer ctx.Close() <ide> <del> result1 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx)) <add> result1 := cli.Docker(cli.Args("build", "-t", name), build.WithExternalBuildContext(ctx)) <ide> result1.Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> }) <ide> <ide> ctx.Add("Dockerfile", "FROM busybox\nCOPY ") <del> result2 := cli.Docker(cli.Build(name), build.WithExternalBuildContext(ctx)) <add> result2 := cli.Docker(cli.Args("build", "-t", name), build.WithExternalBuildContext(ctx)) <ide> result2.Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> }) <ide> func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) { <ide> } <ide> <ide> ctx.Add("Dockerfile", "FROM busybox\n COPY") <del> result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx)) <add> result2 = cli.Docker(cli.Args("build", "-t", name), build.WithoutCache, build.WithExternalBuildContext(ctx)) <ide> result2.Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> }) <ide> func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) { <ide> } <ide> <ide> ctx.Add("Dockerfile", "FROM busybox\n COPY ") <del> result2 = cli.Docker(cli.Build(name), build.WithoutCache, build.WithExternalBuildContext(ctx)) <add> result2 = cli.Docker(cli.Args("build", "-t", name), build.WithoutCache, build.WithExternalBuildContext(ctx)) <ide> result2.Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> }) <ide> func (s *DockerCLIBuildSuite) TestBuildMultiStageCopyFromErrors(c *testing.T) { <ide> "foo": "abc", <ide> })) <ide> <del> cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{ <add> cli.Docker(cli.Args("build", "-t", "build1"), build.WithExternalBuildContext(ctx)).Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> Err: tc.expectedError, <ide> }) <ide> func (s *DockerCLIBuildSuite) TestBuildCopyFromWindowsIsCaseInsensitive(c *testi <ide> COPY --from=0 c:\\fOo c:\\copied <ide> RUN type c:\\copied <ide> ` <del> cli.Docker(cli.Build("copyfrom-windows-insensitive"), build.WithBuildContext(c, <add> cli.Docker(cli.Args("build", "-t", "copyfrom-windows-insensitive"), build.WithBuildContext(c, <ide> build.WithFile("Dockerfile", dockerfile), <ide> build.WithFile("foo", "hello world"), <ide> )).Assert(c, icmd.Expected{ <ide> func (s *DockerCLIBuildSuite) TestBuildIntermediateTarget(c *testing.T) { <ide> res = cli.InspectCmd(c, "build1", cli.Format("json .Config.Cmd")).Combined() <ide> assert.Equal(c, strings.TrimSpace(res), `["/dev"]`) <ide> <del> result := cli.Docker(cli.Build("build1"), build.WithExternalBuildContext(ctx), <add> result := cli.Docker(cli.Args("build", "-t", "build1"), build.WithExternalBuildContext(ctx), <ide> cli.WithFlags("--target", "nosuchtarget")) <ide> result.Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorOnBuild(c *testing.T) { <ide> // FIXME(vdemeester) should be a unit test <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) { <ide> name := "test_build_line_error_unknown_instruction" <del> cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox <add> cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox <ide> RUN echo hello world <ide> NOINSTRUCTION echo ba <ide> RUN echo hello <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) <ide> // FIXME(vdemeester) should be a unit test <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) { <ide> name := "test_build_line_error_with_empty_lines" <del> cli.Docker(cli.Build(name), build.WithDockerfile(` <add> cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(` <ide> FROM busybox <ide> <ide> RUN echo hello world <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) { <ide> // FIXME(vdemeester) should be a unit test <ide> func (s *DockerCLIBuildSuite) TestBuildLineErrorWithComments(c *testing.T) { <ide> name := "test_build_line_error_with_comments" <del> cli.Docker(cli.Build(name), build.WithDockerfile(`FROM busybox <add> cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox <ide> # This will print hello world <ide> # and then ba <ide> RUN echo hello world <ide> func (s *DockerCLIBuildSuite) TestBuildIidFileCleanupOnFail(c *testing.T) { <ide> err = os.WriteFile(tmpIidFile, []byte("Dummy"), 0666) <ide> assert.NilError(c, err) <ide> <del> cli.Docker(cli.Build("testbuildiidfilecleanuponfail"), <add> cli.Docker(cli.Args("build", "-t", "testbuildiidfilecleanuponfail"), <ide> build.WithDockerfile(`FROM `+minimalBaseImage()+` <ide> RUN /non/existing/command`), <ide> cli.WithFlags("--iidfile", tmpIidFile)).Assert(c, icmd.Expected{ <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerCLIRunSuite) TestRunRm(c *testing.T) { <ide> name := "miss-me-when-im-gone" <ide> cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox") <ide> <del> cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ <add> cli.Docker(cli.Args("inspect", name), cli.Format(".name")).Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> Err: "No such object: " + name, <ide> }) <ide> func (s *DockerCLIRunSuite) TestRunRmPre125Api(c *testing.T) { <ide> envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24") <ide> cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success) <ide> <del> cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ <add> cli.Docker(cli.Args("inspect", name), cli.Format(".name")).Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> Err: "No such object: " + name, <ide> }) <ide><path>integration-cli/docker_utils_test.go <ide> func inspectFieldAndUnmarshall(c *testing.T, name, field string, output interfac <ide> assert.Assert(c, err == nil, "failed to unmarshal: %v", err) <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectFilter(name, filter string) (string, error) { <ide> format := fmt.Sprintf("{{%s}}", filter) <ide> result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name) <ide> func inspectFilter(name, filter string) (string, error) { <ide> return strings.TrimSpace(result.Combined()), nil <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectFieldWithError(name, field string) (string, error) { <ide> return inspectFilter(name, "."+field) <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectField(c *testing.T, name, field string) string { <ide> c.Helper() <ide> out, err := inspectFilter(name, "."+field) <ide> assert.NilError(c, err) <ide> return out <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectFieldJSON(c *testing.T, name, field string) string { <ide> c.Helper() <ide> out, err := inspectFilter(name, "json ."+field) <ide> assert.NilError(c, err) <ide> return out <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectFieldMap(c *testing.T, name, path, field string) string { <ide> c.Helper() <ide> out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field)) <ide> assert.NilError(c, err) <ide> return out <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectMountSourceField(name, destination string) (string, error) { <ide> m, err := inspectMountPoint(name, destination) <ide> if err != nil { <ide> func inspectMountSourceField(name, destination string) (string, error) { <ide> return m.Source, nil <ide> } <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectMountPoint(name, destination string) (types.MountPoint, error) { <ide> out, err := inspectFilter(name, "json .Mounts") <ide> if err != nil { <ide> func inspectMountPoint(name, destination string) (types.MountPoint, error) { <ide> <ide> var errMountNotFound = errors.New("mount point not found") <ide> <del>// Deprecated: use cli.Inspect <add>// Deprecated: use cli.Docker <ide> func inspectMountPointJSON(j, destination string) (types.MountPoint, error) { <ide> var mp []types.MountPoint <ide> if err := json.Unmarshal([]byte(j), &mp); err != nil { <ide> func getIDByName(c *testing.T, name string) string { <ide> return id <ide> } <ide> <del>// Deprecated: use cli.Build <add>// Deprecated: use cli.Docker <ide> func buildImageSuccessfully(c *testing.T, name string, cmdOperators ...cli.CmdOperator) { <ide> c.Helper() <ide> buildImage(name, cmdOperators...).Assert(c, icmd.Success) <ide> } <ide> <del>// Deprecated: use cli.Build <add>// Deprecated: use cli.Docker <ide> func buildImage(name string, cmdOperators ...cli.CmdOperator) *icmd.Result { <del> return cli.Docker(cli.Build(name), cmdOperators...) <add> return cli.Docker(cli.Args("build", "-t", name), cmdOperators...) <ide> } <ide> <ide> // Write `content` to the file at path `dst`, creating it if necessary,
4
Java
Java
expose requestpath in serverhttprequest
38a12ed4ba54b6929db0f114a5fa439677e441ac
<ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java <ide> public class MockServerHttpRequest extends AbstractServerHttpRequest { <ide> <ide> private final HttpMethod httpMethod; <ide> <del> private final String contextPath; <del> <ide> private final MultiValueMap<String, HttpCookie> cookies; <ide> <ide> private final InetSocketAddress remoteAddress; <ide> private MockServerHttpRequest(HttpMethod httpMethod, URI uri, String contextPath <ide> InetSocketAddress remoteAddress, <ide> Publisher<? extends DataBuffer> body) { <ide> <del> super(uri, headers); <add> super(uri, contextPath, headers); <ide> this.httpMethod = httpMethod; <del> this.contextPath = contextPath; <ide> this.cookies = cookies; <ide> this.remoteAddress = remoteAddress; <ide> this.body = Flux.from(body); <ide> public String getMethodValue() { <ide> return this.httpMethod.name(); <ide> } <ide> <del> @Override <del> public String getContextPath() { <del> return this.contextPath; <del> } <del> <ide> @Override <ide> public InetSocketAddress getRemoteAddress() { <ide> return this.remoteAddress; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java <ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest { <ide> <ide> private final URI uri; <ide> <add> private final RequestPath path; <add> <ide> private final HttpHeaders headers; <ide> <ide> private MultiValueMap<String, String> queryParams; <ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest { <ide> /** <ide> * Constructor with the URI and headers for the request. <ide> * @param uri the URI for the request <add> * @param contextPath the context path for the request <ide> * @param headers the headers for the request <ide> */ <del> public AbstractServerHttpRequest(URI uri, HttpHeaders headers) { <add> public AbstractServerHttpRequest(URI uri, String contextPath, HttpHeaders headers) { <ide> this.uri = uri; <add> this.path = new DefaultRequestPath(uri, contextPath, StandardCharsets.UTF_8); <ide> this.headers = HttpHeaders.readOnlyHttpHeaders(headers); <ide> } <ide> <ide> public URI getURI() { <ide> return this.uri; <ide> } <ide> <add> @Override <add> public RequestPath getPath() { <add> return this.path; <add> } <add> <ide> @Override <ide> public HttpHeaders getHeaders() { <ide> return this.headers; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ContextPathCompositeHandler.java <ide> * <p>This is intended as a coarse-grained mechanism for delegating requests to <ide> * one of several applications -- each represented by an {@code HttpHandler}, with <ide> * the application "context path" (the prefix-based mapping) exposed via <del> * {@link ServerHttpRequest#getContextPath()}. <add> * {@link ServerHttpRequest#getPath()}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> private static void assertValidContextPath(String contextPath) { <ide> @Override <ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <ide> // Remove underlying context path first (e.g. Servlet container) <del> String path = request.getPathWithinApplication(); <add> String path = request.getPath().pathWithinApplication().value(); <ide> return this.handlerMap.entrySet().stream() <ide> .filter(entry -> path.startsWith(entry.getKey())) <ide> .findFirst() <ide> .map(entry -> { <del> String contextPath = request.getContextPath() + entry.getKey(); <add> String contextPath = request.getPath().contextPath().value() + entry.getKey(); <ide> ServerHttpRequest newRequest = request.mutate().contextPath(contextPath).build(); <ide> return entry.getValue().handle(newRequest, response); <ide> }) <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultRequestPath.java <ide> class DefaultRequestPath implements RequestPath { <ide> this.pathWithinApplication = initPathWithinApplication(this.fullPath, this.contextPath); <ide> } <ide> <add> DefaultRequestPath(RequestPath requestPath, String contextPath, Charset charset) { <add> this.fullPath = new DefaultPathSegmentContainer(requestPath.value(), requestPath.pathSegments()); <add> this.contextPath = initContextPath(this.fullPath, contextPath); <add> this.pathWithinApplication = initPathWithinApplication(this.fullPath, this.contextPath); <add> } <ide> <ide> private static PathSegmentContainer parsePath(String path, Charset charset) { <ide> path = StringUtils.hasText(path) ? path : ""; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java <ide> <ide> import java.net.URI; <ide> import java.net.URISyntaxException; <add>import java.nio.charset.StandardCharsets; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> public ServerHttpRequest.Builder header(String key, String value) { <ide> <ide> @Override <ide> public ServerHttpRequest build() { <del> URI uri = null; <del> if (this.path != null) { <del> uri = this.delegate.getURI(); <del> try { <del> uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), <del> this.path, uri.getQuery(), uri.getFragment()); <del> } <del> catch (URISyntaxException ex) { <del> throw new IllegalStateException("Invalid URI path: \"" + this.path + "\""); <del> } <add> URI uriToUse = getUriToUse(); <add> RequestPath path = getRequestPathToUse(uriToUse); <add> HttpHeaders headers = getHeadersToUse(); <add> return new MutativeDecorator(this.delegate, this.httpMethod, uriToUse, path, headers); <add> } <add> <add> @Nullable <add> private URI getUriToUse() { <add> if (this.path == null) { <add> return null; <add> } <add> URI uri = this.delegate.getURI(); <add> try { <add> return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), <add> this.path, uri.getQuery(), uri.getFragment()); <add> } <add> catch (URISyntaxException ex) { <add> throw new IllegalStateException("Invalid URI path: \"" + this.path + "\""); <add> } <add> } <add> <add> @Nullable <add> private RequestPath getRequestPathToUse(@Nullable URI uriToUse) { <add> if (uriToUse == null && this.contextPath == null) { <add> return null; <add> } <add> else if (uriToUse == null) { <add> return new DefaultRequestPath(this.delegate.getPath(), this.contextPath, StandardCharsets.UTF_8); <add> } <add> else { <add> return new DefaultRequestPath(uriToUse, this.contextPath, StandardCharsets.UTF_8); <add> } <add> } <add> <add> @Nullable <add> private HttpHeaders getHeadersToUse() { <add> if (this.httpHeaders != null) { <add> HttpHeaders headers = new HttpHeaders(); <add> headers.putAll(this.delegate.getHeaders()); <add> headers.putAll(this.httpHeaders); <add> return headers; <add> } <add> else { <add> return null; <ide> } <del> return new MutativeDecorator(this.delegate, this.httpMethod, uri, this.contextPath, this.httpHeaders); <ide> } <ide> <ide> <ide> private static class MutativeDecorator extends ServerHttpRequestDecorator { <ide> <ide> private final URI uri; <ide> <del> private final String contextPath; <add> private final RequestPath requestPath; <ide> <ide> private final HttpHeaders httpHeaders; <ide> <del> public MutativeDecorator(ServerHttpRequest delegate, HttpMethod httpMethod, <del> @Nullable URI uri, String contextPath, @Nullable HttpHeaders httpHeaders) { <add> <add> public MutativeDecorator(ServerHttpRequest delegate, HttpMethod method, <add> @Nullable URI uri, @Nullable RequestPath requestPath, <add> @Nullable HttpHeaders httpHeaders) { <ide> <ide> super(delegate); <del> this.httpMethod = httpMethod; <add> this.httpMethod = method; <ide> this.uri = uri; <del> this.contextPath = contextPath; <del> if (httpHeaders != null) { <del> this.httpHeaders = new HttpHeaders(); <del> this.httpHeaders.putAll(super.getHeaders()); <del> this.httpHeaders.putAll(httpHeaders); <del> } <del> else { <del> this.httpHeaders = null; <del> } <add> this.requestPath = requestPath; <add> this.httpHeaders = httpHeaders; <ide> } <ide> <ide> @Override <ide> public URI getURI() { <ide> } <ide> <ide> @Override <del> public String getContextPath() { <del> return (this.contextPath != null ? this.contextPath : super.getContextPath()); <add> public RequestPath getPath() { <add> return (this.requestPath != null ? this.requestPath : super.getPath()); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java <ide> public class ReactorServerHttpRequest extends AbstractServerHttpRequest { <ide> public ReactorServerHttpRequest(HttpServerRequest request, NettyDataBufferFactory bufferFactory) <ide> throws URISyntaxException { <ide> <del> super(initUri(request), initHeaders(request)); <add> super(initUri(request), "", initHeaders(request)); <ide> Assert.notNull(bufferFactory, "'bufferFactory' must not be null"); <ide> this.request = request; <ide> this.bufferFactory = bufferFactory; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/RequestPath.java <ide> public interface RequestPath extends PathSegmentContainer { <ide> <ide> /** <del> * The contextPath portion of the request if any. <add> * Returns the portion of the URL path that represents the application. <add> * The context path is always at the beginning of the path and starts but <add> * does not end with "/". It is shared for URLs of the same application. <add> * <p>The context path may come from the underlying runtime API such as <add> * when deploying as a WAR to a Servlet container or it may also be assigned <add> * through the use of {@link ContextPathCompositeHandler} or both. <ide> */ <ide> PathSegmentContainer contextPath(); <ide> <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java <ide> import org.springframework.http.ReactiveHttpInputMessage; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <del>import org.springframework.util.StringUtils; <ide> <ide> /** <ide> * Represents a reactive server-side HTTP request <ide> public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage { <ide> <ide> /** <del> * Returns the portion of the URL path that represents the application. <del> * The context path is always at the beginning of the path and starts but <del> * does not end with "/". It is shared for URLs of the same application. <del> * <p>The context path may come from the underlying runtime API such as <del> * when deploying as a WAR to a Servlet container or it may also be assigned <del> * through the use of {@link ContextPathCompositeHandler} or both. <del> * <p>The context path is not decoded. <del> * @return the context path (not decoded) or an empty string <add> * Returns a structured representation of the request path including the <add> * context path + path within application portions, path segments with <add> * encoded and decoded values, and path parameters. <ide> */ <del> default String getContextPath() { <del> return ""; <del> } <del> <del> /** <del> * Returns the portion of the URL path after the {@link #getContextPath() <del> * contextPath}. The returned path is not decoded. <del> * @return the path under the contextPath <del> */ <del> default String getPathWithinApplication() { <del> String path = getURI().getRawPath(); <del> String contextPath = getContextPath(); <del> if (StringUtils.hasText(contextPath)) { <del> int length = contextPath.length(); <del> return (path.length() > length ? path.substring(length) : ""); <del> } <del> else { <del> return path; <del> } <del> } <add> RequestPath getPath(); <ide> <ide> /** <ide> * Return a read-only map with parsed and decoded query parameter values. <ide> interface Builder { <ide> Builder method(HttpMethod httpMethod); <ide> <ide> /** <del> * Set the request URI to return. <add> * Set the path to use instead of the {@code "rawPath"} of <add> * {@link ServerHttpRequest#getURI()}. <ide> */ <ide> Builder path(String path); <ide> <ide> /** <del> * Set the contextPath to return. <add> * Set the contextPath to use. <ide> */ <ide> Builder contextPath(String contextPath); <ide> <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequestDecorator.java <ide> public URI getURI() { <ide> return getDelegate().getURI(); <ide> } <ide> <add> @Override <add> public RequestPath getPath() { <add> return getDelegate().getPath(); <add> } <add> <ide> @Override <ide> public MultiValueMap<String, String> getQueryParams() { <ide> return getDelegate().getQueryParams(); <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpRequest.java <ide> public class ServletServerHttpRequest extends AbstractServerHttpRequest { <ide> public ServletServerHttpRequest(HttpServletRequest request, AsyncContext asyncContext, <ide> DataBufferFactory bufferFactory, int bufferSize) throws IOException { <ide> <del> super(initUri(request), initHeaders(request)); <add> super(initUri(request), request.getContextPath(), initHeaders(request)); <ide> <ide> Assert.notNull(bufferFactory, "'bufferFactory' must not be null"); <ide> Assert.isTrue(bufferSize > 0, "'bufferSize' must be higher than 0"); <ide> public String getMethodValue() { <ide> return getServletRequest().getMethod(); <ide> } <ide> <del> @Override <del> public String getContextPath() { <del> return getServletRequest().getContextPath(); <del> } <del> <ide> @Override <ide> protected MultiValueMap<String, HttpCookie> initCookies() { <ide> MultiValueMap<String, HttpCookie> httpCookies = new LinkedMultiValueMap<>(); <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java <ide> public class UndertowServerHttpRequest extends AbstractServerHttpRequest { <ide> <ide> <ide> public UndertowServerHttpRequest(HttpServerExchange exchange, DataBufferFactory bufferFactory) { <del> super(initUri(exchange), initHeaders(exchange)); <add> super(initUri(exchange), "", initHeaders(exchange)); <ide> this.exchange = exchange; <ide> this.body = new RequestBodyPublisher(exchange, bufferFactory); <ide> this.body.registerListeners(exchange); <ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSource.java <ide> public void registerCorsConfiguration(String path, CorsConfiguration config) { <ide> <ide> @Override <ide> public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) { <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> for (Map.Entry<String, CorsConfiguration> entry : this.corsConfigurations.entrySet()) { <ide> if (this.pathMatcher.match(entry.getKey(), lookupPath)) { <ide> return entry.getValue(); <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java <ide> public void matchWithNativeContextPath() { <ide> new ContextPathCompositeHandler(map).handle(request, new MockServerHttpResponse()); <ide> <ide> assertTrue(handler.wasInvoked()); <del> assertEquals("/yet/another/path", handler.getRequest().getContextPath()); <add> assertEquals("/yet/another/path", handler.getRequest().getPath().contextPath().value()); <ide> } <ide> <ide> @Test <ide> private ServerHttpResponse testHandle(String pathToHandle, Map<String, HttpHandl <ide> <ide> private void assertInvoked(TestHttpHandler handler, String contextPath) { <ide> assertTrue(handler.wasInvoked()); <del> assertEquals(contextPath, handler.getRequest().getContextPath()); <add> assertEquals(contextPath, handler.getRequest().getPath().contextPath().value()); <ide> } <ide> <ide> private void assertNotInvoked(TestHttpHandler... handlers) { <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/RxNettyServerHttpRequest.java <ide> public RxNettyServerHttpRequest(HttpServerRequest<ByteBuf> request, <ide> NettyDataBufferFactory dataBufferFactory, InetSocketAddress remoteAddress) <ide> throws URISyntaxException { <ide> <del> super(initUri(request, remoteAddress), initHeaders(request)); <add> super(initUri(request, remoteAddress), "", initHeaders(request)); <ide> this.request = request; <ide> <ide> Assert.notNull(dataBufferFactory, "NettyDataBufferFactory must not be null"); <ide><path>spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java <ide> public class MockServerHttpRequest extends AbstractServerHttpRequest { <ide> <ide> private final HttpMethod httpMethod; <ide> <del> private final String contextPath; <del> <ide> private final MultiValueMap<String, HttpCookie> cookies; <ide> <ide> private final InetSocketAddress remoteAddress; <ide> private MockServerHttpRequest(HttpMethod httpMethod, URI uri, String contextPath <ide> InetSocketAddress remoteAddress, <ide> Publisher<? extends DataBuffer> body) { <ide> <del> super(uri, headers); <add> super(uri, contextPath, headers); <ide> this.httpMethod = httpMethod; <del> this.contextPath = (contextPath != null ? contextPath : ""); <ide> this.cookies = cookies; <ide> this.remoteAddress = remoteAddress; <ide> this.body = Flux.from(body); <ide> public String getMethodValue() { <ide> return this.httpMethod.name(); <ide> } <ide> <del> @Override <del> public String getContextPath() { <del> return this.contextPath; <del> } <del> <ide> @Override <ide> public InetSocketAddress getRemoteAddress() { <ide> return this.remoteAddress; <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java <ide> public final Map<String, Object> getHandlerMap() { <ide> <ide> @Override <ide> public Mono<Object> getHandlerInternal(ServerWebExchange exchange) { <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> Object handler; <ide> try { <ide> handler = lookupHandler(lookupPath, exchange); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java <ide> public final Mono<String> getForRequestUrl(ServerWebExchange exchange, String re <ide> private int getLookupPathIndex(ServerWebExchange exchange) { <ide> ServerHttpRequest request = exchange.getRequest(); <ide> String requestPath = request.getURI().getPath(); <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> return requestPath.indexOf(lookupPath); <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/PatternsRequestCondition.java <ide> public PatternsRequestCondition getMatchingCondition(ServerWebExchange exchange) <ide> return this; <ide> } <ide> <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> List<String> matches = getMatchingPatterns(lookupPath); <ide> <ide> return matches.isEmpty() ? null : <ide> private String getMatchingPattern(String pattern, String lookupPath) { <ide> */ <ide> @Override <ide> public int compareTo(PatternsRequestCondition other, ServerWebExchange exchange) { <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> Comparator<String> patternComparator = this.pathMatcher.getPatternComparator(lookupPath); <ide> Iterator<String> iterator = this.patterns.iterator(); <ide> Iterator<String> iteratorOther = other.patterns.iterator(); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java <ide> protected void handlerMethodsInitialized(Map<T, HandlerMethod> handlerMethods) { <ide> */ <ide> @Override <ide> public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) { <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Looking up handler method for path " + lookupPath); <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RedirectView.java <ide> protected final String createTargetUrl(Map<String, Object> model, ServerWebExcha <ide> String url = getUrl(); <ide> Assert.state(url != null, "'url' not set"); <ide> <add> ServerHttpRequest request = exchange.getRequest(); <add> <ide> StringBuilder targetUrl = new StringBuilder(); <ide> if (isContextRelative() && url.startsWith("/")) { <del> targetUrl.append(exchange.getRequest().getContextPath()); <add> targetUrl.append(request.getPath().contextPath().value()); <ide> } <ide> targetUrl.append(url); <ide> <ide> protected final String createTargetUrl(Map<String, Object> model, ServerWebExcha <ide> } <ide> <ide> if (isPropagateQuery()) { <del> targetUrl = appendCurrentRequestQuery(targetUrl.toString(), exchange.getRequest()); <add> targetUrl = appendCurrentRequestQuery(targetUrl.toString(), request); <ide> } <ide> <ide> String result = targetUrl.toString(); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RequestContext.java <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.StringUtils; <ide> import org.springframework.validation.BindException; <ide> import org.springframework.validation.BindingResult; <ide> import org.springframework.validation.Errors; <ide> public RequestDataValueProcessor getRequestDataValueProcessor() { <ide> /** <ide> * Return the context path of the current web application. This is <ide> * useful for building links to other resources within the application. <del> * <p>Delegates to {@link ServerHttpRequest#getContextPath()}. <add> * <p>Delegates to {@link ServerHttpRequest#getPath()}. <ide> */ <ide> public String getContextPath() { <del> return this.exchange.getRequest().getContextPath(); <add> return this.exchange.getRequest().getPath().contextPath().value(); <ide> } <ide> <ide> /** <ide> public String getContextPath() { <ide> * absolute path also URL-encoded accordingly <ide> */ <ide> public String getContextUrl(String relativeUrl) { <del> String url = getContextPath() + relativeUrl; <add> String url = StringUtils.applyRelativePath(getContextPath() + "/", relativeUrl); <ide> return getExchange().getResponse().encodeUrl(url); <ide> } <ide> <ide> public String getContextUrl(String relativeUrl) { <ide> * absolute path also URL-encoded accordingly <ide> */ <ide> public String getContextUrl(String relativeUrl, Map<String, ?> params) { <del> String url = getContextPath() + relativeUrl; <add> String url = StringUtils.applyRelativePath(getContextPath() + "/", relativeUrl); <ide> UriTemplate template = new UriTemplate(url); <ide> url = template.expand(params).toASCIIString(); <ide> return getExchange().getResponse().encodeUrl(url); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java <ide> else if (View.class.isAssignableFrom(clazz)) { <ide> * Use the request path the leading and trailing slash stripped. <ide> */ <ide> private String getDefaultViewName(ServerWebExchange exchange) { <del> String path = exchange.getRequest().getPathWithinApplication(); <add> String path = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> if (path.startsWith("/")) { <ide> path = path.substring(1); <ide> } <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java <ide> public void getHandlerProducibleMediaTypesAttribute() throws Exception { <ide> @SuppressWarnings("unchecked") <ide> public void handleMatchUriTemplateVariables() throws Exception { <ide> ServerWebExchange exchange = get("/1/2").toExchange(); <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> <ide> RequestMappingInfo key = paths("/{path1}/{path2}").build(); <ide> this.handlerMapping.handleMatch(key, lookupPath, exchange); <ide> public void handleMatchUriTemplateVariablesDecode() throws Exception { <ide> URI url = URI.create("/group/a%2Fb"); <ide> ServerWebExchange exchange = method(HttpMethod.GET, url).toExchange(); <ide> <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> this.handlerMapping.handleMatch(key, lookupPath, exchange); <ide> <ide> String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; <ide> public void handleMatchUriTemplateVariablesDecode() throws Exception { <ide> public void handleMatchBestMatchingPatternAttribute() throws Exception { <ide> RequestMappingInfo key = paths("/{path1}/2", "/**").build(); <ide> ServerWebExchange exchange = get("/1/2").toExchange(); <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> this.handlerMapping.handleMatch(key, lookupPath, exchange); <ide> <ide> assertEquals("/{path1}/2", exchange.getAttributes().get(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); <ide> public void handleMatchBestMatchingPatternAttribute() throws Exception { <ide> public void handleMatchBestMatchingPatternAttributeNoPatternsDefined() throws Exception { <ide> RequestMappingInfo key = paths().build(); <ide> ServerWebExchange exchange = get("/1/2").toExchange(); <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> this.handlerMapping.handleMatch(key, lookupPath, exchange); <ide> <ide> assertEquals("/1/2", exchange.getAttributes().get(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); <ide> private void testMediaTypeNotAcceptable(String url) throws Exception { <ide> <ide> private void handleMatch(ServerWebExchange exchange, String pattern) { <ide> RequestMappingInfo info = paths(pattern).build(); <del> String lookupPath = exchange.getRequest().getPathWithinApplication(); <add> String lookupPath = exchange.getRequest().getPath().pathWithinApplication().value(); <ide> this.handlerMapping.handleMatch(info, lookupPath, exchange); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ContextPathIntegrationTests.java <ide> static class TestController { <ide> <ide> @GetMapping("/test") <ide> public String handle(ServerHttpRequest request) { <del> return "Tested in " + request.getContextPath(); <add> return "Tested in " + request.getPath().contextPath().value(); <ide> } <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java <ide> public class RedirectViewTests { <ide> <ide> @Before <ide> public void setup() { <del> this.exchange = MockServerHttpRequest.get("/").contextPath("/context").toExchange(); <add> this.exchange = MockServerHttpRequest.get("/context/path").contextPath("/context").toExchange(); <ide> } <ide> <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RequestContextTests.java <ide> */ <ide> public class RequestContextTests { <ide> <del> private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").contextPath("foo/").toExchange(); <add> private final MockServerWebExchange exchange = MockServerHttpRequest.get("/foo/path") <add> .contextPath("/foo").toExchange(); <ide> <ide> private GenericApplicationContext applicationContext; <ide> <ide> public void init() { <ide> @Test <ide> public void testGetContextUrl() throws Exception { <ide> RequestContext context = new RequestContext(this.exchange, this.model, this.applicationContext); <del> assertEquals("foo/bar", context.getContextUrl("bar")); <add> assertEquals("/foo/bar", context.getContextUrl("bar")); <ide> } <ide> <ide> @Test <ide> public void testGetContextUrlWithMap() throws Exception { <ide> Map<String, Object> map = new HashMap<>(); <ide> map.put("foo", "bar"); <ide> map.put("spam", "bucket"); <del> assertEquals("foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map)); <add> assertEquals("/foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map)); <ide> } <ide> <ide> @Test <ide> public void testGetContextUrlWithMapEscaping() throws Exception { <ide> Map<String, Object> map = new HashMap<>(); <ide> map.put("foo", "bar baz"); <ide> map.put("spam", "&bucket="); <del> assertEquals("foo/bar%20baz?spam=%26bucket%3D", context.getContextUrl("{foo}?spam={spam}", map)); <add> assertEquals("/foo/bar%20baz?spam=%26bucket%3D", context.getContextUrl("{foo}?spam={spam}", map)); <ide> } <ide> <ide> }
26