content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
update migration guide
e22f8bd7dcb26532d1c5703f4c7c632ffb406c6c
<ide><path>docs/getting-started/v3-migration.md <ide> Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released <ide> * Chart.js is no longer providing the `Chart.bundle.js` and `Chart.bundle.min.js`. Please see the [installation](installation.md) and [integration](integration.md) docs for details on the recommended way to setup Chart.js if you were using these builds. <ide> * `moment` is no longer specified as an npm dependency. If you are using the time scale, you must include one of [the available adapters](https://github.com/chartjs/awesome#adapters) and corresponding date library. You no longer need to exclude moment from your build. <ide> <del>### Ticks <del> <del>* `options.ticks.userCallback` was renamed to `options.ticks.callback` <del>* `options.ticks.major` and `options.ticks.minor` were replaced with scriptable options for tick fonts. <del>* `Chart.Ticks.formatters.linear` and `Chart.Ticks.formatters.logarithmic` were replaced with `Chart.Ticks.formatters.numeric`. <del> <del>### Tooltip <del> <del>* `xLabel` and `yLabel` were removed. Please use `index` and `value` <del> <del>### Interactions <del> <del>* `interactions` are now limited to the chart area <del>* `{mode: 'label'}` was replaced with `{mode: 'index'}` <del>* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}` <del>* `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}` <del>* `options.onClick` is now limited to the chart area <del> <del>### Customizability <del> <del>* `custom` attribute of elements was removed. Please use scriptable options <del>* The `hover` property of scriptable options `context` object was renamed to `active` to align it with the datalabels plugin. <del>* The `zeroLine*` options of axes were removed. Use scriptable scale options instead. <del> <del>## Defaults <del> <del>* `global` namespace was removed from `defaults`. So `Chart.defaults.global` is now `Chart.defaults` <del>* `default` prefix was removed from defaults. For example `Chart.defaults.global.defaultColor` is now `Chart.defaults.color` <del> * `defaultColor` was renamed to `color` <del> * `defaultFontColor` was renamed to `fontColor` <del> * `defaultFontFamily` was renamed to `fontFamily` <del> * `defaultFontSize` was renamed to `fontSize` <del> * `defaultFontStyle` was renamed to `fontStyle` <del> * `defaultLineHeight` was renamed to `lineHeight` <del> <ide> ### Options <ide> <del>* Dataset options are now configured as `options[type].datasets` rather than `options.datasets[type]` <del>* `Polar area` `startAngle` option is now consistent with `Radar`, 0 is at top and value is in degrees. Default is changed from `-½π` to `0`. <add>A number of changes were made to the configuration options passed to the `Chart` constructor. Those changes are documented below. <add> <add>* `hover.animationDuration` is now configured in `animation.active.duration` <add>* `responsiveAnimationDuration` is now configured in `animation.resize.duration` <add>* Polar area `startAngle` option is now consistent with `Radar`, 0 is at top and value is in degrees. Default is changed from `-½π` to `0`. <ide> * `scales.[x/y]Axes` arrays were removed. Scales are now configured directly to `options.scales` object with the object key being the scale Id. <ide> * `scales.[x/y]Axes.barPercentage` was moved to dataset option `barPercentage` <ide> * `scales.[x/y]Axes.barThickness` was moved to dataset option `barThickness` <ide> Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released <ide> * `scales.[x/y]Axes.ticks.suggestedMax` was renamed to `scales[id].suggestedMax` <ide> * `scales.[x/y]Axes.ticks.suggestedMin` was renamed to `scales[id].suggestedMin` <ide> * `scales.[x/y]Axes.ticks.unitStepSize` was removed. Use `scales[id].ticks.stepSize` <add>* `scales.[x/y]Axes.ticks.userCallback` was renamed to `scales[id].ticks.callback` <ide> * `scales.[x/y]Axes.time.format` was renamed to `scales[id].time.parser` <ide> * `scales.[x/y]Axes.time.max` was renamed to `scales[id].max` <ide> * `scales.[x/y]Axes.time.min` was renamed to `scales[id].min` <add>* `scales.[x/y]Axes.zeroLine*` options of axes were removed. Use scriptable scale options instead. <ide> * The dataset option `steppedLine` was removed. Use `stepped` <ide> * The dataset option `tension` was removed. Use `lineTension` <add>* Dataset options are now configured as `options[type].datasets` rather than `options.datasets[type]` <ide> * To override the platform class used in a chart instance, pass `platform: PlatformClass` in the config object. Note that the class should be passed, not an instance of the class. <ide> <del>### Animations <add>#### Defaults <add> <add>* `global` namespace was removed from `defaults`. So `Chart.defaults.global` is now `Chart.defaults` <add>* `default` prefix was removed from defaults. For example `Chart.defaults.global.defaultColor` is now `Chart.defaults.color` <add>* `defaultColor` was renamed to `color` <add>* `defaultFontColor` was renamed to `fontColor` <add>* `defaultFontFamily` was renamed to `fontFamily` <add>* `defaultFontSize` was renamed to `fontSize` <add>* `defaultFontStyle` was renamed to `fontStyle` <add>* `defaultLineHeight` was renamed to `lineHeight` <add> <add>#### Scales <add> <add>The configuration options for scales is the largest change in v3. The `xAxes` and `yAxes` arrays were removed and axis options are individual scales now keyed by scale ID. <add> <add>The v2 configuration below is shown with it's new v3 configuration <add> <add>```javascript <add>options: { <add> scales: { <add> xAxes: [{ <add> id: 'x', <add> type: 'time', <add> display: true, <add> scaleLabel: { <add> display: true, <add> labelString: 'Date' <add> }, <add> ticks: { <add> major: { <add> enabled: true <add> }, <add> fontStyle: function(context) { <add> return context.tick && context.tick.major ? 'bold' : undefined; <add> }, <add> fontColor: function(context) { <add> return context.tick && context.tick.major ? '#FF0000' : undefined; <add> } <add> } <add> }], <add> yAxes: [{ <add> id: 'y', <add> display: true, <add> scaleLabel: { <add> display: true, <add> labelString: 'value' <add> } <add> }] <add> } <add>} <add>``` <add> <add>And now, in v3: <add> <add>```javascript <add>options: { <add> scales: { <add> x: { <add> type: 'time', <add> display: true, <add> scaleLabel: { <add> display: true, <add> labelString: 'Date' <add> }, <add> ticks: { <add> major: { <add> enabled: true <add> }, <add> fontStyle: function(context) { <add> return context.tick && context.tick.major ? 'bold' : undefined; <add> }, <add> fontColor: function(context) { <add> return context.tick && context.tick.major ? '#FF0000' : undefined; <add> } <add> } <add> }, <add> y: { <add> display: true, <add> scaleLabel: { <add> display: true, <add> labelString: 'value' <add> } <add> } <add> } <add>} <add>``` <add> <add>#### Animations <ide> <ide> Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.md) docs for details. <ide> <del>* `hover.animationDuration` is now configured in `animation.active.duration` <del>* `responsiveAnimationDuration` is now configured in `animation.resize.duration` <add> <add>#### Customizability <add> <add>* `custom` attribute of elements was removed. Please use scriptable options <add>* The `hover` property of scriptable options `context` object was renamed to `active` to align it with the datalabels plugin. <add> <add>#### Interactions <add> <add>* `interactions` are now limited to the chart area <add>* `{mode: 'label'}` was replaced with `{mode: 'index'}` <add>* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}` <add>* `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}` <add>* `options.onClick` is now limited to the chart area <add> <add>#### Ticks <add> <add>* `options.ticks.major` and `options.ticks.minor` were replaced with scriptable options for tick fonts. <add>* `Chart.Ticks.formatters.linear` and `Chart.Ticks.formatters.logarithmic` were replaced with `Chart.Ticks.formatters.numeric`. <add> <add>#### Tooltip <add> <add>* `xLabel` and `yLabel` were removed. Please use `index` and `value` <ide> <ide> ## Developer migration <ide> <ide> ### Removed <ide> <add>The following properties and methods were removed: <add> <add>#### Chart <ide> * `Chart.borderWidth` <ide> * `Chart.chart.chart` <ide> * `Chart.Controller` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> * `Chart.radiusLength` <ide> * `Chart.types` <ide> * `Chart.Tooltip` is now provided by the tooltip plugin. The positioners can be accessed from `tooltipPlugin.positioners` <add>* `ILayoutItem.minSize` <add> <add>#### Dataset Controller <add> <ide> * `DatasetController.addElementAndReset` <ide> * `DatasetController.createMetaData` <ide> * `DatasetController.createMetaDataset` <add> <add>#### Elements <add> <ide> * `Element.getArea` <ide> * `Element.height` <ide> * `Element.hidden` was replaced by chart level status, usable with `getDataVisibility(index)` / `toggleDataVisibility(index)` <ide> * `Element.initialize` <ide> * `Element.inLabelRange` <add>* `Line.calculatePointY` <add> <add>#### Helpers <add> <ide> * `helpers.addEvent` <ide> * `helpers.aliasPixel` <ide> * `helpers.configMerge` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> * `helpers.roundedRect` <ide> * `helpers.scaleMerge` <ide> * `helpers.where` <del>* `ILayoutItem.minSize` <del>* `IPlugin.afterScaleUpdate`. Use `afterLayout` instead <del>* `Legend.margins` is now private <del>* `Line.calculatePointY` <add> <add>#### Scales <add> <ide> * `LogarithmicScale.minNotZero` <ide> * `Scale.getRightValue` <ide> * `Scale.longestLabelWidth` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> * `Scale.tickValues` is now private <ide> * `TimeScale.getLabelCapacity` is now private <ide> * `TimeScale.tickFormatFunction` is now private <add> <add>#### Plugins (Legend, Title, and Tooltip) <add> <add>* `IPlugin.afterScaleUpdate`. Use `afterLayout` instead <add>* `Legend.margins` is now private <ide> * `Title.margins` is now private <ide> * The tooltip item's `x` and `y` attributes were removed. Use `datasetIndex` and `index` to get the element and any corresponding data from it <ide> <ide> #### Removal of private APIs <ide> <add>The following private APIs were removed. <add> <ide> * `Chart.data.datasets[datasetIndex]._meta` <ide> * `Element._ctx` <ide> * `Element._model` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ### Renamed <ide> <add>The following properties were renamed during v3 development: <add> <ide> * `Chart.Animation.animationObject` was renamed to `Chart.Animation` <ide> * `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` <ide> * `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> #### Renamed private APIs <ide> <add>The private APIs listed below were renamed: <add> <ide> * `BarController.calculateBarIndexPixels` was renamed to `BarController._calculateBarIndexPixels` <ide> * `BarController.calculateBarValuePixels` was renamed to `BarController._calculateBarValuePixels` <ide> * `BarController.getStackCount` was renamed to `BarController._getStackCount` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ### Changed <ide> <add>The APIs listed in this section have changed in signature or behaviour from version 2. <add> <ide> #### Scales <ide> <ide> * `Scale.getLabelForIndex` was replaced by `scale.getLabelForValue`
1
Text
Text
update the issue template
2fc9d7ee437e5b666fe1121c10129999ead87b4d
<ide><path>.github/ISSUE_TEMPLATE.md <del>## Hey there and thank you for using React Native! <add>We use GitHub Issues for bugs. <ide> <del>React Native, as you've probably heard, is getting really popular and truth is we're getting a bit overwhelmed by the activity surrounding it. Before opening a new issue, make sure to carefully read the following guidelines. <add>If you have a non-bug question, ask on Stack Overflow: http://stackoverflow.com/questions/tagged/react-native <ide> <del>- Is this something you can **debug and fix**? <del> Send a pull request! Bug fixes and documentation fixes are welcome. <del>- Have a **usage** question? <del> We use GitHub Issues for bugs. Ask your usage question on Stack Overflow: http://stackoverflow.com/questions/tagged/react-native <del>- Have an idea for a **feature**? <del> Post the feature request on Product Pains, which has a voting system to surface important issues: https://productpains.com/product/react-native/ <add>If you have a feature request, post it on Product Pains: https://productpains.com/product/react-native/ <ide> <del>GitHub issues should only be used for bugs. Make sure these boxes are checked before submitting your issue: <add>--- Please use this template, and delete everything above this line before submitting your issue --- <ide> <del>- [ ] You're using the latest release of React Native: https://github.com/facebook/react-native/releases <add>### Description <ide> <del>- [ ] You've searched through existing issues: https://github.com/facebook/react-native/issues <del> Chances are that your issue has been reported or resolved before. <add>[FILL THIS OUT: Explain what you did, what you expected to happen, and what actually happens.] <ide> <del>- [ ] You have filled out the template below, or provided an equivalent amount of detail. <del> Issues without sufficient information will be labeled 'Needs more information' and will be closed until there is enough information. <add>### Reproduction <ide> <del>Describe your issue in as much detail as possible. Provide **screenshots** where appropriate. Provide a **minimal code snippet** / [rnplay](https://rnplay.org/) example that reproduces the bug, or include a list of detailed list of steps that reproduce the issue. <del> <del>--- delete everything above this line before submitting your issue --- <del> <del>### Issue Description <del> <del>[FILL THIS OUT] <del> <del>### Steps to Reproduce / Code Snippets <del> <del>[FILL THIS OUT] <del> <del>#### Expected Results <del> <del>[FILL THIS OUT] <add>[FILL THIS OUT: Try to reproduce your bug on rnplay.org and provide a link. If you can't reproduce the bug on rnplay.org, provide a sample project.] <ide> <ide> ### Additional Information <ide> <ide> * React Native version: [FILL THIS OUT] <del>* Platform(s) (iOS, Android, or both?): [FILL THIS OUT] <del>* Operating System (macOS, Linux, or Windows?): [FILL THIS OUT] <add>* Platform: [FILL THIS OUT: iOS, Android, or both?] <add>* Operating System: [FILL THIS OUT: MacOS, Linux, or Windows?]
1
PHP
PHP
add depth to log()
7a4cabe5d3d608b4a0d77d53640b22024e25d487
<ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php <ide> public function testLog() { <ide> $this->assertRegExp("/'here'/", $result); <ide> } <ide> <add>/** <add> * test log() depth <add> * <add> * @return void <add> */ <add> public function testLogDepth() { <add> if (file_exists(LOGS . 'debug.log')) { <add> unlink(LOGS . 'debug.log'); <add> } <add> CakeLog::config('file', array('engine' => 'File', 'path' => TMP . 'logs' . DS)); <add> <add> $val = [ <add> 'test' => ['key' => 'val'] <add> ]; <add> Debugger::log($val, LOG_DEBUG, 0); <add> $result = file_get_contents(LOGS . 'debug.log'); <add> $this->assertContains('DebuggerTest::testLog', $result); <add> $this->assertNotContains("/'val'/", $result); <add> <add> unlink(LOGS . 'debug.log'); <add> } <add> <ide> /** <ide> * testDump method <ide> * <ide><path>lib/Cake/Utility/Debugger.php <ide> public static function dump($var, $depth = 3) { <ide> * <ide> * @param mixed $var Variable or content to log <ide> * @param integer $level type of log to use. Defaults to LOG_DEBUG <add> * @param int $depth The depth to output to. Defaults to 3. <ide> * @return void <ide> * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log <ide> */ <del> public static function log($var, $level = LOG_DEBUG) { <add> public static function log($var, $level = LOG_DEBUG, $depth = 3) { <ide> $source = self::trace(array('start' => 1)) . "\n"; <del> CakeLog::write($level, "\n" . $source . self::exportVar($var)); <add> CakeLog::write($level, "\n" . $source . self::exportVar($var, $depth)); <ide> } <ide> <ide> /**
2
Javascript
Javascript
add getowner/setowner shims
75876e5a1c20c9b20e0feca9038d71d3baeb0e48
<ide><path>vendor/ember/shims.js <ide> 'ember-object': { <ide> 'default': Ember.Object <ide> }, <add> 'ember-owner/get': { <add> 'default': Ember.getOwner <add> }, <add> 'ember-owner/set': { <add> 'default': Ember.setOwner <add> }, <ide> 'ember-platform': { <ide> 'assign': Ember.merge, <ide> 'create': Ember.create,
1
PHP
PHP
fix empty paths for server.php
bd3ac842a4af4d86576234b08371ee54e1920772
<ide><path>src/Illuminate/Foundation/resources/server.php <ide> $publicPath = getcwd(); <ide> <ide> $uri = urldecode( <del> parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) <add> parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '' <ide> ); <ide> <ide> // This file allows us to emulate Apache's "mod_rewrite" functionality from the
1
PHP
PHP
update doc block
21cddebfde8132b549269969db1ae9be7c6a03bf
<ide><path>src/ORM/Association/BelongsToMany.php <ide> public function conditions($conditions = null) <ide> } <ide> <ide> /** <del> * @param string|\Cake\ORM\Table $through <add> * Sets the current join table, either the name of the Table instance or the instance itself. <add> * <add> * @param string|\Cake\ORM\Table $through Name of the Table instance or the instance itself <ide> * @return $this <ide> */ <ide> public function setThrough($through) <ide> public function setThrough($through) <ide> } <ide> <ide> /** <add> * Gets the current join table, either the name of the Table instance or the instance itself. <add> * <ide> * @return string|\Cake\ORM\Table <ide> */ <ide> public function getThrough()
1
Ruby
Ruby
use full path to stty
ebbc2e5b3fae09f6497723a2f0cb12c2248c082e
<ide><path>install_homebrew.rb <ide> def sudo *args <ide> end <ide> <ide> def getc # NOTE only tested on OS X <del> system "stty raw -echo" <add> system "/bin/stty raw -echo" <ide> STDIN.getc <ide> ensure <del> system "stty -raw echo" <add> system "/bin/stty -raw echo" <ide> end <ide> <ide> ####################################################################### script
1
Text
Text
add equalsignorecase to the file
ef8c5e5bfa7e0808680758e43718e134cf4f5e91
<ide><path>guide/english/java/equality/index.md <ide> For example, the `java.util.Set` interface specifies that a `Set`'s `equals()` m <ide> <ide> However, if a class does not override the default `equals()` implementation, the default implementation will apply, which simply uses the `==` operator to compare the two objects. <ide> <add>## The `.equalsIgnoreCase()` Method <add> <add>This built-in function in java is used to compare the equality of 2 strings return true or false depending on the match but this function does not see if the characters are in upper case or in lower case. <add>Example: <add> <add>```java <add>String s1="DEMO for Equality"; <add>String s2="Demo for equality"; <add>System.out.println(s1.equals(s2)); //false <add>System.out.println(s1.equalsIgnoreCase(s2)); //true <add>``` <add> <ide> #### More Information: <ide> - [Oracle Java Docs : Equality Operators](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21)
1
Text
Text
prepend some pre-release notes
ee79b453974f3dc8ead83bff86784366d59a4fb1
<ide><path>docs/topics/3.0-announcement.md <del>**THIS DOCUMENT IS CURRENTLY A WORK IN PROGRESS** <add>## Pre-release notes: <ide> <del>See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details. <add>The 3.0 release is now ready for some tentative testing and upgrades for super keen early adopters. You can install the development version directly from GitHub like so: <add> <add> pip install https://github.com/tomchristie/django-rest-framework/archive/version-3.0.zip <add> <add>See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details on remaining work. <ide> <ide> The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: <ide> <ide> The most notable outstanding issues still to resolved on the `version-3.0` branc <ide> * `.validate()` method on fields. <ide> * `.transform_<field>()` method on serializers. <ide> <add>**Your feedback on the upgrade process and 3.0 changes is hugely important!** <add> <add>Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group. <add> <add>--- <add> <ide> # REST framework 3.0 <ide> <ide> The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
1
Javascript
Javascript
remove extraneous assert
976826aec0930b0c316837fe3ec14c4a13e43507
<ide><path>src/event/EventPluginHub.js <ide> var EventPluginHub = { <ide> * @param {?function} listener The callback to store. <ide> */ <ide> putListener: function(id, registrationName, listener) { <del> invariant( <del> ExecutionEnvironment.canUseDOM, <del> 'Cannot call putListener() in a non-DOM environment.' <del> ); <ide> invariant( <ide> !listener || typeof listener === 'function', <ide> 'Expected %s listener to be a function, instead got type %s',
1
Go
Go
allow named volumes for external drivers
3bf0ca31cf61e445554326ba405cc32c7ef64189
<ide><path>daemon/volumes.go <ide> func parseBindMount(spec string, config *runconfig.Config) (*mountPoint, error) <ide> return nil, fmt.Errorf("Invalid volume specification: %s", spec) <ide> } <ide> <del> if !filepath.IsAbs(arr[0]) { <del> return nil, fmt.Errorf("cannot bind mount volume: %s volume paths must be absolute.", spec) <add> name, source, err := parseVolumeSource(arr[0], config) <add> if err != nil { <add> return nil, err <add> } <add> <add> if len(source) == 0 { <add> bind.Driver = config.VolumeDriver <add> if len(bind.Driver) == 0 { <add> bind.Driver = volume.DefaultDriverName <add> } <add> } else { <add> bind.Source = filepath.Clean(source) <ide> } <ide> <del> bind.Source = filepath.Clean(arr[0]) <add> bind.Name = name <ide> bind.Destination = filepath.Clean(bind.Destination) <ide> return bind, nil <ide> } <ide> func (daemon *Daemon) verifyOldVolumesInfo(container *Container) error { <ide> if strings.HasPrefix(hostPath, vfsPath) { <ide> id := filepath.Base(hostPath) <ide> <del> container.addLocalMountPoint(id, destination, vols.VolumesRW[destination]) <add> rw := vols.VolumesRW != nil && vols.VolumesRW[destination] <add> container.addLocalMountPoint(id, destination, rw) <ide> } <ide> } <ide> <ide> func (daemon *Daemon) verifyOldVolumesInfo(container *Container) error { <ide> <ide> func createVolume(name, driverName string) (volume.Volume, error) { <ide> vd, err := getVolumeDriver(driverName) <add> <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/volumes_experimental.go <ide> package daemon <ide> <ide> import ( <add> "path/filepath" <add> <add> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> ) <ide> func getVolumeDriver(name string) (volume.Driver, error) { <ide> } <ide> return volumedrivers.Lookup(name) <ide> } <add> <add>func parseVolumeSource(spec string, config *runconfig.Config) (string, string, error) { <add> if !filepath.IsAbs(spec) { <add> return spec, "", nil <add> } <add> <add> return "", spec, nil <add>} <ide><path>daemon/volumes_experimental_unit_test.go <ide> package daemon <ide> import ( <ide> "testing" <ide> <add> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> ) <ide> func TestGetVolumeDriver(t *testing.T) { <ide> t.Fatalf("Expected fake driver, got %s\n", d.Name()) <ide> } <ide> } <add> <add>func TestParseBindMount(t *testing.T) { <add> cases := []struct { <add> bind string <add> driver string <add> expDest string <add> expSource string <add> expName string <add> expDriver string <add> expRW bool <add> fail bool <add> }{ <add> {"/tmp:/tmp", "", "/tmp", "/tmp", "", "", true, false}, <add> {"/tmp:/tmp:ro", "", "/tmp", "/tmp", "", "", false, false}, <add> {"/tmp:/tmp:rw", "", "/tmp", "/tmp", "", "", true, false}, <add> {"/tmp:/tmp:foo", "", "/tmp", "/tmp", "", "", false, true}, <add> {"name:/tmp", "", "/tmp", "", "name", "local", true, false}, <add> {"name:/tmp", "external", "/tmp", "", "name", "external", true, false}, <add> {"name:/tmp:ro", "local", "/tmp", "", "name", "local", false, false}, <add> {"local/name:/tmp:rw", "", "/tmp", "", "local/name", "local", true, false}, <add> } <add> <add> for _, c := range cases { <add> conf := &runconfig.Config{VolumeDriver: c.driver} <add> m, err := parseBindMount(c.bind, conf) <add> if c.fail { <add> if err == nil { <add> t.Fatalf("Expected error, was nil, for spec %s\n", c.bind) <add> } <add> continue <add> } <add> <add> if m.Destination != c.expDest { <add> t.Fatalf("Expected destination %s, was %s, for spec %s\n", c.expDest, m.Destination, c.bind) <add> } <add> <add> if m.Source != c.expSource { <add> t.Fatalf("Expected source %s, was %s, for spec %s\n", c.expSource, m.Source, c.bind) <add> } <add> <add> if m.Name != c.expName { <add> t.Fatalf("Expected name %s, was %s for spec %s\n", c.expName, m.Name, c.bind) <add> } <add> <add> if m.Driver != c.expDriver { <add> t.Fatalf("Expected driver %s, was %s, for spec %s\n", c.expDriver, m.Driver, c.bind) <add> } <add> <add> if m.RW != c.expRW { <add> t.Fatalf("Expected RW %v, was %v for spec %s\n", c.expRW, m.RW, c.bind) <add> } <add> } <add>} <ide><path>daemon/volumes_stubs.go <ide> package daemon <ide> <ide> import ( <add> "fmt" <add> "path/filepath" <add> <add> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> ) <ide> <ide> func getVolumeDriver(_ string) (volume.Driver, error) { <ide> return volumedrivers.Lookup(volume.DefaultDriverName) <ide> } <add> <add>func parseVolumeSource(spec string, _ *runconfig.Config) (string, string, error) { <add> if !filepath.IsAbs(spec) { <add> return "", "", fmt.Errorf("cannot bind mount volume: %s volume paths must be absolute.", spec) <add> } <add> <add> return "", spec, nil <add>} <ide><path>daemon/volumes_stubs_unit_test.go <ide> import ( <ide> "os" <ide> "testing" <ide> <add> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> "github.com/docker/docker/volume/local" <ide> func TestGetVolumeDefaultDriver(t *testing.T) { <ide> t.Fatalf("Expected local driver, was %s\n", d.Name) <ide> } <ide> } <add> <add>func TestParseBindMount(t *testing.T) { <add> cases := []struct { <add> bind string <add> expDest string <add> expSource string <add> expName string <add> expRW bool <add> fail bool <add> }{ <add> {"/tmp:/tmp", "/tmp", "/tmp", "", true, false}, <add> {"/tmp:/tmp:ro", "/tmp", "/tmp", "", false, false}, <add> {"/tmp:/tmp:rw", "/tmp", "/tmp", "", true, false}, <add> {"/tmp:/tmp:foo", "/tmp", "/tmp", "", false, true}, <add> {"name:/tmp", "", "", "", false, true}, <add> {"local/name:/tmp:rw", "", "", "", true, true}, <add> } <add> <add> for _, c := range cases { <add> conf := &runconfig.Config{} <add> m, err := parseBindMount(c.bind, conf) <add> if c.fail { <add> if err == nil { <add> t.Fatalf("Expected error, was nil, for spec %s\n", c.bind) <add> } <add> continue <add> } <add> <add> if m.Destination != c.expDest { <add> t.Fatalf("Expected destination %s, was %s, for spec %s\n", c.expDest, m.Destination, c.bind) <add> } <add> <add> if m.Source != c.expSource { <add> t.Fatalf("Expected source %s, was %s, for spec %s\n", c.expSource, m.Source, c.bind) <add> } <add> <add> if m.Name != c.expName { <add> t.Fatalf("Expected name %s, was %s for spec %s\n", c.expName, m.Name, c.bind) <add> } <add> <add> if m.RW != c.expRW { <add> t.Fatalf("Expected RW %v, was %v for spec %s\n", c.expRW, m.RW, c.bind) <add> } <add> } <add>} <ide><path>daemon/volumes_unit_test.go <ide> package daemon <ide> <del>import ( <del> "testing" <del> <del> "github.com/docker/docker/runconfig" <del>) <del> <del>func TestParseBindMount(t *testing.T) { <del> cases := []struct { <del> bind string <del> driver string <del> expDest string <del> expSource string <del> expName string <del> expDriver string <del> expRW bool <del> fail bool <del> }{ <del> {"/tmp:/tmp", "", "/tmp", "/tmp", "", "", true, false}, <del> {"/tmp:/tmp:ro", "", "/tmp", "/tmp", "", "", false, false}, <del> {"/tmp:/tmp:rw", "", "/tmp", "/tmp", "", "", true, false}, <del> {"/tmp:/tmp:foo", "", "/tmp", "/tmp", "", "", false, true}, <del> {"name:/tmp", "", "", "", "", "", false, true}, <del> {"name:/tmp", "external", "/tmp", "", "name", "external", true, true}, <del> {"external/name:/tmp:rw", "", "/tmp", "", "name", "external", true, true}, <del> {"external/name:/tmp:ro", "", "/tmp", "", "name", "external", false, true}, <del> {"external/name:/tmp:foo", "", "/tmp", "", "name", "external", false, true}, <del> {"name:/tmp", "local", "", "", "", "", false, true}, <del> {"local/name:/tmp:rw", "", "", "", "", "", true, true}, <del> } <del> <del> for _, c := range cases { <del> conf := &runconfig.Config{VolumeDriver: c.driver} <del> m, err := parseBindMount(c.bind, conf) <del> if c.fail { <del> if err == nil { <del> t.Fatalf("Expected error, was nil, for spec %s\n", c.bind) <del> } <del> continue <del> } <del> <del> if m.Destination != c.expDest { <del> t.Fatalf("Expected destination %s, was %s, for spec %s\n", c.expDest, m.Destination, c.bind) <del> } <del> <del> if m.Source != c.expSource { <del> t.Fatalf("Expected source %s, was %s, for spec %s\n", c.expSource, m.Source, c.bind) <del> } <del> <del> if m.Name != c.expName { <del> t.Fatalf("Expected name %s, was %s for spec %s\n", c.expName, m.Name, c.bind) <del> } <del> <del> if m.Driver != c.expDriver { <del> t.Fatalf("Expected driver %s, was %s, for spec %s\n", c.expDriver, m.Driver, c.bind) <del> } <del> <del> if m.RW != c.expRW { <del> t.Fatalf("Expected RW %v, was %v for spec %s\n", c.expRW, m.RW, c.bind) <del> } <del> } <del>} <add>import "testing" <ide> <ide> func TestParseVolumeFrom(t *testing.T) { <ide> cases := []struct {
6
Ruby
Ruby
reduce array allocations
0fa8c0a1d9d1e51f7dd904c483723eb5d4b9f393
<ide><path>activesupport/lib/active_support/parameter_filter.rb <ide> class CompiledFilter # :nodoc: <ide> def self.compile(filters, mask:) <ide> return lambda { |params| params.dup } if filters.empty? <ide> <del> strings, regexps, blocks = [], [], [] <add> strings, regexps, blocks, deep_regexps, deep_strings = [], [], [], nil, nil <ide> <ide> filters.each do |item| <ide> case item <ide> when Proc <ide> blocks << item <ide> when Regexp <del> regexps << item <add> if item.to_s.include?("\\.") <add> (deep_regexps ||= []) << item <add> else <add> regexps << item <add> end <ide> else <del> strings << Regexp.escape(item.to_s) <add> s = Regexp.escape(item.to_s) <add> if s.include?("\\.") <add> (deep_strings ||= []) << s <add> else <add> strings << s <add> end <ide> end <ide> end <ide> <del> deep_regexps = regexps.extract! { |r| r.to_s.include?("\\.") } <del> deep_strings = strings.extract! { |s| s.include?("\\.") } <del> <ide> regexps << Regexp.new(strings.join("|"), true) unless strings.empty? <del> deep_regexps << Regexp.new(deep_strings.join("|"), true) unless deep_strings.empty? <add> (deep_regexps ||= []) << Regexp.new(deep_strings.join("|"), true) if deep_strings&.any? <ide> <ide> new regexps, deep_regexps, blocks, mask: mask <ide> end <ide> def self.compile(filters, mask:) <ide> <ide> def initialize(regexps, deep_regexps, blocks, mask:) <ide> @regexps = regexps <del> @deep_regexps = deep_regexps.any? ? deep_regexps : nil <add> @deep_regexps = deep_regexps&.any? ? deep_regexps : nil <ide> @blocks = blocks <ide> @mask = mask <ide> end
1
PHP
PHP
add registered method
dadc76237b58ded295fa5459b1d7a9e4e6f4f33a
<ide><path>src/Illuminate/Foundation/Auth/RegistersUsers.php <ide> public function register(Request $request) <ide> <ide> $this->guard()->login($user); <ide> <del> return redirect($this->redirectPath()); <add> return $this->registered($request, $user) <add> ?: redirect($this->redirectPath()); <ide> } <ide> <ide> /** <ide> protected function guard() <ide> { <ide> return Auth::guard(); <ide> } <add> <add> /** <add> * The user has been registered. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @param mixed $user <add> * @return mixed <add> */ <add> protected function registered(Request $request, $user) <add> { <add> return null; <add> } <ide> }
1
Ruby
Ruby
remove outdated comment
b730a85e3a327040ae4a8d8f6dcee9335573c100
<ide><path>Library/Homebrew/download_strategy.rb <ide> def stage <ide> raise "You must install 7zip: brew install p7zip" unless which "7zr" <ide> safe_system '7zr', 'x', @tarball_path <ide> else <del> # we are assuming it is not an archive, use original filename <del> # this behaviour is due to ScriptFileFormula expectations <del> # So I guess we should cp, but we mv, for this historic reason <del> # HOWEVER if this breaks some expectation you had we *will* change the <del> # behaviour, just open an issue at github <del> # We also do this for jar files, as they are in fact zip files, but <del> # we don't want to unzip them <ide> FileUtils.cp @tarball_path, basename_without_params <ide> end <ide> end
1
Go
Go
fix empty-lines (revive)
8a2e1245d42d3fb1d27e61b83774354129eb123a
<ide><path>distribution/manifest_test.go <ide> func TestManifestStore(t *testing.T) { <ide> <ide> err = w.Commit(ctx, desc.Size, desc.Digest, opts...) <ide> assert.NilError(t, err) <del> <ide> } <ide> <ide> // All tests should end up with no active ingest <ide> func TestDetectManifestBlobMediaType(t *testing.T) { <ide> assert.Equal(t, mt, tc.expected) <ide> }) <ide> } <del> <ide> } <ide> <ide> func TestDetectManifestBlobMediaTypeInvalid(t *testing.T) { <ide> func TestDetectManifestBlobMediaTypeInvalid(t *testing.T) { <ide> assert.Equal(t, mt, "") <ide> }) <ide> } <del> <ide> } <ide><path>distribution/xfer/download.go <ide> func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor, <ide> d.err = errors.New("download cancelled during retry delay") <ide> return <ide> } <del> <ide> } <ide> } <ide> <ide><path>image/fs_test.go <ide> func TestFSInvalidRoot(t *testing.T) { <ide> <ide> os.RemoveAll(root) <ide> } <del> <ide> } <ide> <ide> func TestFSMetadataGetSet(t *testing.T) { <ide><path>image/tarexport/save.go <ide> func (l *tarexporter) parseNames(names []string) (desc map[image.ID]*imageDescri <ide> if err := addAssoc(image.IDFromDigest(id), namedRef); err != nil { <ide> return nil, err <ide> } <del> <ide> } <ide> return imgDescr, nil <ide> } <ide><path>layer/layer_unix_test.go <ide> func TestLayerSize(t *testing.T) { <ide> if expected := len(content1) + len(content2); int(layer2Size) != expected { <ide> t.Fatalf("Unexpected size %d, expected %d", layer2Size, expected) <ide> } <del> <ide> } <ide><path>oci/devices_linux.go <ide> func DevicesFromPath(pathOnHost, pathInContainer, cgroupPermissions string) (dev <ide> // if the device is not a device node <ide> // try to see if it's a directory holding many devices <ide> if err == devices.ErrNotADevice { <del> <ide> // check if it is a directory <ide> if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() { <del> <ide> // mount the internal devices recursively <ide> // TODO check if additional errors should be handled or logged <ide> _ = filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, _ error) error { <ide><path>registry/config_test.go <ide> func TestValidateIndexName(t *testing.T) { <ide> if assert.Check(t, err) { <ide> assert.Check(t, is.Equal(testCase.expect, result)) <ide> } <del> <ide> } <del> <ide> } <ide> <ide> func TestValidateIndexNameWithError(t *testing.T) { <ide><path>runconfig/config_test.go <ide> type f struct { <ide> } <ide> <ide> func TestDecodeContainerConfig(t *testing.T) { <del> <ide> var ( <ide> fixtures []f <ide> image string <ide> func TestDecodeContainerConfig(t *testing.T) { <ide> // to the daemon in the hostConfig structure. Note this is platform specific <ide> // as to what level of container isolation is supported. <ide> func TestDecodeContainerConfigIsolation(t *testing.T) { <del> <ide> // An Invalid isolation level <ide> if _, _, _, err := callDecodeContainerConfigIsolation("invalid"); err != nil { <ide> if !strings.Contains(err.Error(), `Invalid isolation: "invalid"`) {
8
Python
Python
fix typo in automatically generated marker
00d823ee8210f5b16bfac336de1edf2027c7d0cc
<ide><path>dev/provider_packages/prepare_provider_packages.py <ide> def replace_content(file_path, old_text, new_text, provider_package_id): <ide> os.remove(temp_file_path) <ide> <ide> <add>AUTOMATICALLY_GENERATED_MARKER = "AUTOMATICALLY GENERATED" <ide> AUTOMATICALLY_GENERATED_CONTENT = ( <del> ".. THE REMINDER OF THE FILE IS AUTOMATICALLY GENERATED. IT WILL BE OVERWRITTEN AT RELEASE TIME!" <add> f".. THE REMAINDER OF THE FILE IS {AUTOMATICALLY_GENERATED_MARKER}. " <add> f"IT WILL BE OVERWRITTEN AT RELEASE TIME!" <ide> ) <ide> <ide> <ide> def update_index_rst( <ide> new_text = deepcopy(old_text) <ide> lines = old_text.splitlines(keepends=False) <ide> for index, line in enumerate(lines): <del> if line == AUTOMATICALLY_GENERATED_CONTENT: <add> if AUTOMATICALLY_GENERATED_MARKER in line: <ide> new_text = "\n".join(lines[:index]) <ide> new_text += "\n" + AUTOMATICALLY_GENERATED_CONTENT + "\n" <ide> new_text += index_update
1
Javascript
Javascript
fix spelling error in assertion (ngattr*)
f6663b4314e4e8312ec54fb3265fc25754a22f8c
<ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope); <ide> expect(element.attr('test')).toBeUndefined(); <ide> expect(element.attr('test2')).toBeUndefined(); <del> expect(element.attr('test2')).toBeUndefined(); <add> expect(element.attr('test3')).toBeUndefined(); <ide> $rootScope.$digest(); <ide> expect(element.attr('test')).toBe('Misko'); <ide> expect(element.attr('test2')).toBe('Misko');
1
Python
Python
try #1 to fix ctl
f0a8be5daf03c80a59b4acf087a832cd77e868d1
<ide><path>official/recommendation/ncf_keras_main.py <ide> def call(self, inputs): <ide> return inputs[0] <ide> <ide> <del> def _get_train_and_eval_data(producer, params): <add>def _get_train_and_eval_data(producer, params): <ide> """Returns the datasets for training and evalutating.""" <ide> <ide> def preprocess_train_input(features, labels): <ide> def step_fn(inputs): <ide> """Computes loss and applied gradient per replica.""" <ide> features, labels = inputs <ide> with tf.GradientTape() as tape: <del> softmax_logits = keras_model([features[movielens.USER_COLUMN], <del> features[movielens.ITEM_COLUMN]]) <add> softmax_logits = keras_model(features) <ide> loss = loss_object(labels, softmax_logits, <ide> sample_weight=features[rconst.VALID_POINT_MASK]) <ide> loss *= (1.0 / (batch_size*strategy.num_replicas_in_sync)) <ide> def eval_step(): <ide> def step_fn(inputs): <ide> """Computes eval metrics per replica.""" <ide> features, _ = inputs <del> softmax_logits = keras_model([features[movielens.USER_COLUMN], <del> features[movielens.ITEM_COLUMN]]) <add> softmax_logits = keras_model(features) <ide> logits = tf.slice(softmax_logits, [0, 0, 1], [-1, -1, -1]) <ide> dup_mask = features[rconst.DUPLICATE_MASK] <ide> in_top_k, _, metric_weights, _ = neumf_model.compute_top_k_and_ndcg( <ide> def step_fn(inputs): <ide> train_history = history.history <ide> train_loss = train_history["loss"][-1] <ide> <del> stats = build_stats(train_loss, eval_results, time_callback) <add> stats = build_stats(train_loss, eval_results, None) #, time_callback) <ide> return stats <ide> <ide>
1
Python
Python
add transformers id to hub requests
f2b744f690e71756e0752255f3580b75f845ff95
<ide><path>src/transformers/file_utils.py <ide> from types import ModuleType <ide> from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union <ide> from urllib.parse import urlparse <add>from uuid import uuid4 <ide> from zipfile import ZipFile, is_zipfile <ide> <ide> import numpy as np <ide> PYTORCH_PRETRAINED_BERT_CACHE = os.getenv("PYTORCH_PRETRAINED_BERT_CACHE", default_cache_path) <ide> PYTORCH_TRANSFORMERS_CACHE = os.getenv("PYTORCH_TRANSFORMERS_CACHE", PYTORCH_PRETRAINED_BERT_CACHE) <ide> TRANSFORMERS_CACHE = os.getenv("TRANSFORMERS_CACHE", PYTORCH_TRANSFORMERS_CACHE) <add>SESSION_ID = uuid4().hex <ide> DISABLE_TELEMETRY = os.getenv("DISABLE_TELEMETRY", False) <ide> <ide> WEIGHTS_NAME = "pytorch_model.bin" <ide> def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str: <ide> """ <ide> Formats a user-agent string with basic info about a request. <ide> """ <del> ua = "transformers/{}; python/{}".format(__version__, sys.version.split()[0]) <add> ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}" <ide> if is_torch_available(): <ide> ua += f"; torch/{_torch_version}" <ide> if is_tf_available():
1
Python
Python
add tags inside try block.
190e911c46900459ab8d211acc76cefa18090cbf
<ide><path>airflow/sentry.py <ide> class ConfiguredSentry(DummySentry): <ide> """Configure Sentry SDK.""" <ide> <ide> SCOPE_DAG_RUN_TAGS = frozenset(("data_interval_end", "data_interval_start", "execution_date")) <del> SCOPE_TASK_TAGS = frozenset(("operator",)) <ide> SCOPE_TASK_INSTANCE_TAGS = frozenset(("task_id", "dag_id", "try_number")) <del> SCOPE_TAGS = SCOPE_DAG_RUN_TAGS | SCOPE_TASK_TAGS | SCOPE_TASK_INSTANCE_TAGS <ide> SCOPE_CRUMBS = frozenset(("task_id", "state", "operator", "duration")) <ide> <ide> UNSUPPORTED_SENTRY_OPTIONS = frozenset( <ide> def wrapper(_self, *args, **kwargs): <ide> <ide> with sentry_sdk.push_scope(): <ide> try: <del> return func(_self, *args, **kwargs) <del> except Exception as e: <ide> # Is a LocalTaskJob get the task instance <ide> if hasattr(_self, 'task_instance'): <ide> task_instance = _self.task_instance <ide> def wrapper(_self, *args, **kwargs): <ide> <ide> self.add_tagging(task_instance) <ide> self.add_breadcrumbs(task_instance, session=session) <add> return func(_self, *args, **kwargs) <add> except Exception as e: <ide> sentry_sdk.capture_exception(e) <ide> raise <ide>
1
PHP
PHP
remove unnecessary else
093409654608daa7b28d7c30933bda6f92935014
<ide><path>src/Illuminate/Queue/Queue.php <ide> protected function createPayload($job, $data = '', $queue = null) <ide> { <ide> if ($job instanceof Closure) { <ide> return json_encode($this->createClosurePayload($job, $data)); <del> } elseif (is_object($job)) { <add> } <add> <add> if (is_object($job)) { <ide> return json_encode([ <ide> 'job' => 'Illuminate\Queue\CallQueuedHandler@call', <ide> 'data' => ['commandName' => get_class($job), 'command' => serialize(clone $job)],
1
Javascript
Javascript
add more path.basename() tests
27549f64cea9b4822cc9e39e2d88b2481ca012a9
<ide><path>test/parallel/test-path.js <ide> assert.equal(path.basename('aaa/bbb', 'bbb'), 'bbb'); <ide> assert.equal(path.basename('aaa/bbb//', 'bbb'), 'bbb'); <ide> assert.equal(path.basename('aaa/bbb', 'bb'), 'b'); <ide> assert.equal(path.basename('aaa/bbb', 'b'), 'bb'); <add>assert.equal(path.basename('/aaa/bbb', '/bbb'), 'bbb'); <add>assert.equal(path.basename('/aaa/bbb', 'a/bbb'), 'bbb'); <add>assert.equal(path.basename('/aaa/bbb', 'bbb'), 'bbb'); <add>assert.equal(path.basename('/aaa/bbb//', 'bbb'), 'bbb'); <add>assert.equal(path.basename('/aaa/bbb', 'bb'), 'b'); <add>assert.equal(path.basename('/aaa/bbb', 'b'), 'bb'); <add>assert.equal(path.basename('/aaa/bbb'), 'bbb'); <add>assert.equal(path.basename('/aaa/'), 'aaa'); <add>assert.equal(path.basename('/aaa/b'), 'b'); <add>assert.equal(path.basename('/a/b'), 'b'); <add>assert.equal(path.basename('//a'), 'a'); <ide> <ide> // On Windows a backslash acts as a path separator. <ide> assert.equal(path.win32.basename('\\dir\\basename.ext'), 'basename.ext');
1
Python
Python
ignore cache on request.get_json(cache=false) call
36425d5f91b57210f7707de9564377fea93825b2
<ide><path>flask/wrappers.py <ide> def get_json(self, force=False, silent=False, cache=True): <ide> on the request. <ide> """ <ide> rv = getattr(self, '_cached_json', _missing) <del> if rv is not _missing: <add> # We return cached JSON only when the cache is enabled. <add> if cache and rv is not _missing: <ide> return rv <ide> <ide> if not (force or self.is_json): <ide><path>tests/test_helpers.py <ide> def has_encoding(name): <ide> <ide> class TestJSON(object): <ide> <add> def test_ignore_cached_json(self): <add> app = flask.Flask(__name__) <add> with app.test_request_context('/', method='POST', data='malformed', <add> content_type='application/json'): <add> assert flask.request.get_json(silent=True, cache=True) is None <add> with pytest.raises(BadRequest): <add> flask.request.get_json(silent=False, cache=False) <add> <ide> def test_post_empty_json_adds_exception_to_response_content_in_debug(self): <ide> app = flask.Flask(__name__) <ide> app.config['DEBUG'] = True
2
Go
Go
update documents of `dispatchadd`
9b374801ac843c3401bfb21d8fd5e205d0bba0d3
<ide><path>builder/dockerfile/dispatchers.go <ide> func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error { <ide> <ide> // ADD foo /path <ide> // <del>// Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling <add>// Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling <ide> // exist here. If you do not wish to have this automatic handling, use COPY. <ide> // <ide> func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
1
Javascript
Javascript
remove property for compatibility
0a7420c63b59d22f6a89c5f3967fac106f743a78
<ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> function iter(key, value) { <ide> */ <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> <del> // compatibility <del> isEnumerable: true, <del> <ide> /** <ide> Implement this method to make your class enumerable. <ide>
1
Python
Python
add short delay to prevent busy waiting
b8adad947084c8d0c51d1ee1d858ed8de2fb5745
<ide><path>libcloud/compute/ssh.py <ide> # Ref: https://bugs.launchpad.net/paramiko/+bug/392973 <ide> <ide> import os <add>import time <ide> import subprocess <ide> import logging <ide> <ide> def run(self, cmd): <ide> <ide> data = chan.recv_stderr(CHUNK_SIZE) <ide> <add> # Short sleep to prevent busy waiting <add> time.sleep(1.5) <add> <ide> # Receive the exit status code of the command we ran. <ide> status = chan.recv_exit_status() <ide>
1
Ruby
Ruby
fix paths usage
9ebf3388040f696f61144c5baf50673fcadadff6
<ide><path>Library/Homebrew/diagnostic.rb <ide> def check_user_path_1 <ide> <ide> message = "" <ide> <del> paths(ENV["HOMEBREW_PATH"]).each do |p| <add> paths.each do |p| <ide> case p <ide> when "/usr/bin" <ide> unless @seen_prefix_bin <ide> def check_for_config_scripts <ide> /Applications/Server.app/Contents/ServerRoot/usr/sbin <ide> ].map(&:downcase) <ide> <del> paths(ENV["HOMEBREW_PATH"]).each do |p| <add> paths.each do |p| <ide> next if whitelist.include?(p.downcase) || !File.directory?(p) <ide> <ide> realpath = Pathname.new(p).realpath.to_s <ide> def check_for_pth_support <ide> end <ide> <ide> def check_for_external_cmd_name_conflict <del> cmds = paths.flat_map { |p| Dir["#{p}/brew-*"] }.uniq <add> cmds = Tap.cmd_directories.flat_map { |p| Dir["#{p}/brew-*"] }.uniq <ide> cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) } <ide> cmd_map = {} <ide> cmds.each do |cmd| <ide><path>Library/Homebrew/test/diagnostic_spec.rb <ide> FileUtils.chmod 0755, cmd <ide> end <ide> <del> ENV["PATH"] = [path1, path2, ENV["PATH"]].join File::PATH_SEPARATOR <add> allow(Tap).to receive(:cmd_directories).and_return([path1, path2]) <ide> <ide> expect(subject.check_for_external_cmd_name_conflict) <ide> .to match("brew-foo") <ide><path>Library/Homebrew/utils.rb <ide> def nostdout <ide> end <ide> end <ide> <del>def paths(env_path = ENV["PATH"]) <del> @paths ||= PATH.new(env_path).collect do |p| <add>def paths <add> @paths ||= PATH.new(ENV["HOMEBREW_PATH"]).collect do |p| <ide> begin <ide> File.expand_path(p).chomp("/") <ide> rescue ArgumentError
3
Java
Java
fix checkstyle violations
dd1330d05ee139987000ce8802357611090fef49
<ide><path>spring-test/src/main/java/org/springframework/test/context/event/EventPublishingTestExecutionListener.java <ide> * <p>These events may be consumed for various reasons, such as resetting <em>mock</em> <ide> * beans or tracing test execution. Since these events may be consumed by regular <ide> * Spring beans, they can be shared among different test classes. <del> * <add> * <ide> * <h3>Supported Events</h3> <ide> * <ul> <ide> * <li>{@link BeforeTestClassEvent}</li> <ide><path>spring-test/src/main/java/org/springframework/test/context/event/annotation/PrepareTestInstance.java <ide> <ide> package org.springframework.test.context.event.annotation; <ide> <del>import org.springframework.context.event.EventListener; <del>import org.springframework.test.context.event.PrepareTestInstanceEvent; <del> <ide> import java.lang.annotation.Documented; <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.context.event.EventListener; <add>import org.springframework.test.context.event.PrepareTestInstanceEvent; <add> <ide> import static java.lang.annotation.ElementType.ANNOTATION_TYPE; <ide> import static java.lang.annotation.ElementType.METHOD; <ide> import static java.lang.annotation.RetentionPolicy.RUNTIME; <ide><path>spring-test/src/main/java/org/springframework/test/context/event/annotation/package-info.java <ide> /** <ide> * Test event annotations for the <em>Spring TestContext Framework</em>. <ide> */ <del>package org.springframework.test.context.event.annotation; <ide>\ No newline at end of file <add>package org.springframework.test.context.event.annotation; <ide><path>spring-test/src/main/java/org/springframework/test/context/event/package-info.java <ide> /** <ide> * Test event support classes for the <em>Spring TestContext Framework</em>. <ide> */ <del>package org.springframework.test.context.event; <ide>\ No newline at end of file <add>package org.springframework.test.context.event;
4
Javascript
Javascript
add semicolon for jshint
a19131494c7661d8dee04aa9a422c1f171f249e0
<ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> }); <ide> return function deregisterWatchGroup() { <ide> shouldCall = false; <del> } <add> }; <ide> } <ide> <ide> if (watchExpressions.length === 1) {
1
Python
Python
fix xlnet save_steps and steps_per_epoch conflicts
e6750c5d3d7429d15b7c101f8e5ff24b6a4be53d
<ide><path>official/modeling/model_training_utils.py <ide> def _float_metric_value(metric): <ide> return metric.result().numpy().astype(float) <ide> <ide> <del>def _steps_to_run(current_step, steps_per_epoch, steps_per_loop): <add>def steps_to_run(current_step, steps_per_epoch, steps_per_loop): <ide> """Calculates steps to run on device.""" <ide> if steps_per_loop <= 0: <ide> raise ValueError('steps_per_loop should be positive integer.') <ide> def _run_callbacks_on_batch_end(batch): <ide> <ide> _run_callbacks_on_batch_begin(current_step) <ide> # Runs several steps in the host while loop. <del> steps = _steps_to_run(current_step, steps_per_epoch, steps_per_loop) <add> steps = steps_to_run(current_step, steps_per_epoch, steps_per_loop) <ide> <ide> if steps == 1: <ide> # TODO(zongweiz): merge with train_steps once tf.while_loop <ide><path>official/nlp/xlnet/common_flags.py <ide> flags.DEFINE_float( <ide> "init_range", default=0.1, help="Initialization std when init is uniform.") <ide> <del>flags.DEFINE_integer( <del> "train_data_size", default=130738, help="Number of training data samples.") <ide> flags.DEFINE_integer( <ide> "test_data_size", default=12048, help="Number of test data samples.") <ide> flags.DEFINE_string( <ide><path>official/nlp/xlnet/run_classifier.py <ide> def main(unused_argv): <ide> strategy, False, FLAGS.test_tfrecord_path) <ide> <ide> total_training_steps = FLAGS.train_steps <del> steps_per_epoch = int(FLAGS.train_data_size / FLAGS.train_batch_size) <ide> steps_per_loop = FLAGS.iterations <ide> eval_steps = int(FLAGS.test_data_size / FLAGS.test_batch_size) <ide> eval_fn = functools.partial(run_evaluation, strategy, test_input_fn, <ide> def main(unused_argv): <ide> init_checkpoint=FLAGS.init_checkpoint, <ide> init_from_transformerxl=FLAGS.init_from_transformerxl, <ide> total_training_steps=total_training_steps, <del> steps_per_epoch=steps_per_epoch, <ide> steps_per_loop=steps_per_loop, <ide> optimizer=optimizer, <ide> learning_rate_fn=learning_rate_fn, <ide><path>official/nlp/xlnet/run_pretrain.py <ide> def main(unused_argv): <ide> num_hosts) <ide> <ide> total_training_steps = FLAGS.train_steps <del> steps_per_epoch = int(FLAGS.train_data_size / FLAGS.train_batch_size) <add> <ide> steps_per_loop = FLAGS.iterations <ide> <ide> optimizer, learning_rate_fn = optimization.create_optimizer( <ide> def main(unused_argv): <ide> init_checkpoint=FLAGS.init_checkpoint, <ide> init_from_transformerxl=FLAGS.init_from_transformerxl, <ide> total_training_steps=total_training_steps, <del> steps_per_epoch=steps_per_epoch, <ide> steps_per_loop=steps_per_loop, <ide> optimizer=optimizer, <ide> learning_rate_fn=learning_rate_fn, <ide><path>official/nlp/xlnet/run_squad.py <ide> def main(unused_argv): <ide> FLAGS.test_tfrecord_path) <ide> <ide> total_training_steps = FLAGS.train_steps <del> steps_per_epoch = int(FLAGS.train_data_size / FLAGS.train_batch_size) <ide> steps_per_loop = FLAGS.iterations <ide> eval_steps = int(FLAGS.test_data_size / FLAGS.test_batch_size) <ide> <ide> def main(unused_argv): <ide> init_checkpoint=FLAGS.init_checkpoint, <ide> init_from_transformerxl=FLAGS.init_from_transformerxl, <ide> total_training_steps=total_training_steps, <del> steps_per_epoch=steps_per_epoch, <ide> steps_per_loop=steps_per_loop, <ide> optimizer=optimizer, <ide> learning_rate_fn=learning_rate_fn, <ide><path>official/nlp/xlnet/training_utils.py <ide> def _float_metric_value(metric): <ide> return metric.result().numpy().astype(float) <ide> <ide> <del>def _steps_to_run(current_step, steps_per_epoch, steps_per_loop): <del> """Calculates steps to run on device.""" <del> if steps_per_loop <= 0: <del> raise ValueError("steps_per_loop should be positive integer.") <del> if steps_per_loop == 1: <del> return steps_per_loop <del> remainder_in_epoch = current_step % steps_per_epoch <del> if remainder_in_epoch != 0: <del> return min(steps_per_epoch - remainder_in_epoch, steps_per_loop) <del> else: <del> return steps_per_loop <del> <del> <ide> def train( <ide> strategy: tf.distribute.Strategy, <ide> model_fn: Callable, <ide> input_meta_data: Dict, <ide> train_input_fn: Callable, <ide> total_training_steps: int, <del> steps_per_epoch: int, <ide> steps_per_loop: int, <ide> optimizer: tf.keras.optimizers.Optimizer, <ide> learning_rate_fn: tf.keras.optimizers.schedules.LearningRateSchedule, <ide> def train( <ide> `n_layer`, `batch_size_per_core` and `d_model`. <ide> train_input_fn: Function returns a tf.data.Dataset used for training. <ide> total_training_steps: Number of steps to train in total. <del> steps_per_epoch: Number of steps to run per epoch. At the end of each <del> epoch, model checkpoint will be saved and evaluation will be conducted <del> if evaluation dataset is provided. <ide> steps_per_loop: Number of steps per graph-mode loop. In order to reduce <ide> communication in eager context, training logs are printed every <ide> steps_per_loop. <ide> def train( <ide> `model_fn`. <ide> model_dir: The directory of model (checkpoints, summaries). <ide> save_steps: The frequency to save checkpoints. Every save_steps, we save a <del> model checkpoint. <add> model checkpoint. Model checkpoint will be saved and evaluation will be <add> conducted if evaluation dataset is provided. <ide> run_eagerly: Whether to run training eagerly. <ide> <ide> Returns: <ide> def train( <ide> TypeError: if model directory is not specified. <ide> """ <ide> required_arguments = [ <del> train_input_fn, total_training_steps, steps_per_epoch, steps_per_loop, <del> optimizer, learning_rate_fn <add> train_input_fn, total_training_steps, steps_per_loop, optimizer, <add> learning_rate_fn, save_steps <ide> ] <ide> if [arg for arg in required_arguments if arg is None]: <ide> raise ValueError("`train_input_fn`, `total_training_steps`, " <del> "`steps_per_epoch`, `steps_per_loop`, `optimizer` and " <add> "`steps_per_loop`, `optimizer`, `save_steps` and " <ide> "`learning_rate_fn` are required parameters.") <ide> if not model_dir: <ide> raise TypeError("Model directory must be specified.") <ide> def train( <ide> transformer_xl=model.transformerxl_model) <ide> else: <ide> checkpoint = tf.train.Checkpoint(model=model) <del> checkpoint.restore(init_checkpoint) <add> checkpoint.restore(init_checkpoint).assert_existing_objects_matched() <ide> <ide> model.optimizer = optimizer <ide> <ide> def cache_fn(): <ide> if train_metric: <ide> train_metric.reset_states() <ide> <del> steps = _steps_to_run(current_step, steps_per_epoch, steps_per_loop) <add> steps = model_training_utils.steps_to_run(current_step, save_steps, <add> steps_per_loop) <ide> train_steps(train_iterator, tf.convert_to_tensor(steps, dtype=tf.int32)) <ide> current_step += steps <ide> train_loss = _float_metric_value(train_loss_metric) <ide> def cache_fn(): <ide> _float_metric_value(train_metric), <ide> step=current_step) <ide> train_summary_writer.flush() <del> if model_dir: <del> if (save_steps is None) or (save_steps and <del> current_step % save_steps == 0): <del> _save_checkpoint(checkpoint, model_dir, <del> checkpoint_name.format(step=current_step)) <add> if model_dir and current_step % save_steps == 0: <add> _save_checkpoint(checkpoint, model_dir, <add> checkpoint_name.format(step=current_step)) <ide> <del> if test_input_fn and current_step % steps_per_epoch == 0: <add> if test_input_fn and current_step % save_steps == 0: <ide> <ide> logging.info("Running evaluation after step: %s.", current_step) <ide>
6
Ruby
Ruby
fix incorrect example
b95f8be594d64509bb251ecd8315474fab368073
<ide><path>activesupport/lib/active_support/ordered_options.rb <ide> <ide> # Usually key value pairs are handled something like this: <ide> # <del># h = ActiveSupport::OrderedOptions.new <add># h = {} <ide> # h[:boy] = 'John' <ide> # h[:girl] = 'Mary' <ide> # h[:boy] # => 'John' <ide> # h[:girl] # => 'Mary' <ide> # <del># Using <tt>OrderedOptions</tt> above code could be reduced to: <add># Using <tt>OrderedOptions</tt>, the above code could be reduced to: <ide> # <ide> # h = ActiveSupport::OrderedOptions.new <ide> # h.boy = 'John'
1
PHP
PHP
fix failing tests in entity test
ae59d5c4a1d2d04a3db1453e2beb5b7ce815acf6
<ide><path>Cake/Test/TestCase/ORM/EntityTest.php <ide> <?php <ide> /** <del> * PHP Version 5.4 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> public function testSetOneParamNoSetters() { <ide> */ <ide> public function testSetMultiplePropertiesNoSetters() { <ide> $entity = new Entity; <add> $entity->accessible('*', true); <add> <ide> $entity->set(['foo' => 'bar', 'id' => 1]); <ide> $this->assertEquals('bar', $entity->foo); <ide> $this->assertSame(1, $entity->id); <ide> public function testSetOneParamWithSetter() { <ide> */ <ide> public function testMultipleWithSetter() { <ide> $entity = $this->getMock('\Cake\ORM\Entity', ['setName', 'setStuff']); <add> $entity->accessible('*', true); <ide> $entity->expects($this->once())->method('setName') <ide> ->with('Jones') <ide> ->will($this->returnCallback(function($name) { <ide> public function testMultipleWithSetter() { <ide> */ <ide> public function testBypassSetters() { <ide> $entity = $this->getMock('\Cake\ORM\Entity', ['setName', 'setStuff']); <add> $entity->accessible('*', true); <add> <ide> $entity->expects($this->never())->method('setName'); <ide> $entity->expects($this->never())->method('setStuff'); <ide> <ide> public function testGetArrayAccess() { <ide> */ <ide> public function testSetArrayAccess() { <ide> $entity = $this->getMock('\Cake\ORM\Entity', ['set']); <add> $entity->accessible('*', true); <add> <ide> $entity->expects($this->at(0)) <ide> ->method('set') <del> ->with(['foo' => 1]) <add> ->with('foo', 1) <ide> ->will($this->returnSelf()); <ide> <ide> $entity->expects($this->at(1)) <ide> ->method('set') <del> ->with(['bar' => 2]) <add> ->with('bar', 2) <ide> ->will($this->returnSelf()); <ide> <ide> $entity['foo'] = 1; <ide> public function testToArrayRecursive() { <ide> */ <ide> public function testToArrayWithAccessor() { <ide> $entity = $this->getMock('\Cake\ORM\Entity', ['getName']); <add> $entity->accessible('*', true); <ide> $entity->set(['name' => 'Mark', 'email' => 'mark@example.com']); <ide> $entity->expects($this->any()) <ide> ->method('getName') <ide> public function testToArrayHiddenProperties() { <ide> */ <ide> public function testToArrayVirtualProperties() { <ide> $entity = $this->getMock('\Cake\ORM\Entity', ['getName']); <add> $entity->accessible('*', true); <add> <ide> $entity->expects($this->any()) <ide> ->method('getName') <ide> ->will($this->returnValue('Jose')); <ide> public function testValidateMissingFields() { <ide> ->setMethods(['getSomething']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <add> $entity->accessible('*', true); <add> <ide> $validator = $this->getMock('\Cake\Validation\Validator'); <ide> $entity->set('a', 'b'); <ide>
1
Python
Python
skip failing test until @gante fix it
870ff9e1dab249e4ffd8363ce132aa5145c94604
<ide><path>tests/utils/test_cli.py <ide> def test_cli_env(self): <ide> self.assertIn("Platform", cs.out) <ide> self.assertIn("Using distributed or parallel set-up in script?", cs.out) <ide> <add> @unittest.skip("Joao will fix me tomorrow.") <ide> @is_pt_tf_cross_test <ide> @patch( <ide> "sys.argv", ["fakeprogrampath", "pt-to-tf", "--model-name", "hf-internal-testing/tiny-random-gptj", "--no-pr"]
1
Ruby
Ruby
ignore matches to source code
79b1d4178e25d674cc7e831a9888769dbd673eb3
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_formula(f) <ide> prefix_check = prefix <ide> end <ide> <del> ignores = [] <add> # Ignore matches to source code, which is not required at run time. <add> # These matches may be caused by debugging symbols. <add> ignores = [%r{/include/|\.(c|cc|cpp|h|hpp)$}] <ide> any_go_deps = f.deps.any? do |dep| <ide> dep.name =~ Version.formula_optionally_versioned_regex(:go) <ide> end
1
PHP
PHP
remove repeated code
65fec46142e4e9d284aee2a4d8b07c87be8934bf
<ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> public function rollback($pretend = false) <ide> // of them "down" to reverse the last migration "operation" which ran. <ide> $migrations = $this->repository->getLast(); <ide> <del> $migrationsCount = count($migrations); <add> $count = count($migrations); <ide> <del> if ($migrationsCount === 0) { <add> if ($count === 0) { <ide> $this->note('<info>Nothing to rollback.</info>'); <del> <del> return $migrationsCount; <del> } <del> <del> // We need to reverse these migrations so that they are "downed" in reverse <del> // to what they run on "up". It lets us backtrack through the migrations <del> // and properly reverse the entire database schema operation that ran. <del> foreach ($migrations as $migration) { <del> $this->runDown((object) $migration, $pretend); <add> } else { <add> // We need to reverse these migrations so that they are "downed" in reverse <add> // to what they run on "up". It lets us backtrack through the migrations <add> // and properly reverse the entire database schema operation that ran. <add> foreach ($migrations as $migration) { <add> $this->runDown((object) $migration, $pretend); <add> } <ide> } <ide> <del> return $migrationsCount; <add> return $count; <ide> } <ide> <ide> /** <ide> public function reset($pretend = false) <ide> <ide> $migrations = array_reverse($this->repository->getRan()); <ide> <del> $migrationsCount = count($migrations); <add> $count = count($migrations); <ide> <del> if ($migrationsCount === 0) { <add> if ($count === 0) { <ide> $this->note('<info>Nothing to rollback.</info>'); <del> <del> return $migrationsCount; <del> } <del> <del> foreach ($migrations as $migration) { <del> $this->runDown((object) ['migration' => $migration], $pretend); <add> } else { <add> foreach ($migrations as $migration) { <add> $this->runDown((object) ['migration' => $migration], $pretend); <add> } <ide> } <ide> <del> return $migrationsCount; <add> return $count; <ide> } <ide> <ide> /**
1
Go
Go
fix tests with dockerinit lookup path
01f9815b55742654b2f35d13c3aba6a9e48634c7
<ide><path>docker/docker.go <ide> import ( <ide> ) <ide> <ide> func main() { <del> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || strings.Contains(selfPath, "/.dockerinit") { <add> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || strings.Contains(selfPath, ".dockerinit") { <ide> // Running in init mode <ide> sysinit.SysInit() <ide> return <ide><path>execdriver/namespaces/driver.go <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> return -1, err <ide> } <ide> args := append([]string{c.Entrypoint}, c.Arguments...) <del> return nsinit.Exec(container, factory, stateWriter, term, "/nsinit.log", args) <add> return nsinit.Exec(container, factory, stateWriter, term, "", args) <ide> } <ide> <ide> func (d *driver) Kill(p *execdriver.Command, sig int) error { <ide> func (d *dockerCommandFactory) Create(container *libcontainer.Container, <ide> "-driver", DriverName, <ide> "-console", console, <ide> "-pipe", fmt.Sprint(syncFd), <add> "-log", logFile, <ide> }, args...) <ide> c.SysProcAttr = &syscall.SysProcAttr{ <ide> Cloneflags: uintptr(nsinit.GetNamespaceFlags(container.Namespaces)), <ide><path>integration/runtime_test.go <ide> func init() { <ide> os.Setenv("TEST", "1") <ide> <ide> // Hack to run sys init during unit testing <del> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" { <add> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || strings.Contains(selfPath, ".dockerinit") { <ide> sysinit.SysInit() <ide> return <ide> } <ide><path>pkg/libcontainer/nsinit/nsinit/main.go <ide> var ( <ide> ErrWrongArguments = errors.New("Wrong argument count") <ide> ) <ide> <del>func init() { <add>func registerFlags() { <ide> flag.StringVar(&console, "console", "", "console (pty slave) path") <ide> flag.StringVar(&logFile, "log", "none", "log options (none, stderr, or a file path)") <ide> flag.IntVar(&pipeFd, "pipe", 0, "sync pipe fd") <ide> func init() { <ide> } <ide> <ide> func main() { <add> registerFlags() <add> <ide> if flag.NArg() < 1 { <ide> log.Fatal(ErrWrongArguments) <ide> } <ide><path>sysinit/sysinit.go <ide> import ( <ide> "github.com/dotcloud/docker/execdriver" <ide> _ "github.com/dotcloud/docker/execdriver/chroot" <ide> _ "github.com/dotcloud/docker/execdriver/lxc" <add> "io" <ide> "io/ioutil" <ide> "log" <ide> "os" <ide> func SysInit() { <ide> driver = flag.String("driver", "", "exec driver") <ide> pipe = flag.Int("pipe", 0, "sync pipe fd") <ide> console = flag.String("console", "", "console (pty slave) path") <add> logFile = flag.String("log", "", "log file path") <ide> ) <ide> flag.Parse() <ide> <add> if err := setupLogging(*logFile); err != nil { <add> log.Fatalf("setup logging %s", err) <add> } <add> <ide> // Get env <ide> var env []string <ide> content, err := ioutil.ReadFile("/.dockerenv") <ide> func SysInit() { <ide> if err := json.Unmarshal(content, &env); err != nil { <ide> log.Fatalf("Unable to unmarshal environment variables: %v", err) <ide> } <del> <ide> // Propagate the plugin-specific container env variable <ide> env = append(env, "container="+os.Getenv("container")) <ide> <ide> func SysInit() { <ide> log.Fatal(err) <ide> } <ide> } <add> <add>func setupLogging(logFile string) (err error) { <add> var writer io.Writer <add> switch logFile { <add> case "stderr": <add> writer = os.Stderr <add> case "none", "": <add> writer = ioutil.Discard <add> default: <add> writer, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755) <add> if err != nil { <add> return err <add> } <add> } <add> log.SetOutput(writer) <add> return nil <add>}
5
Javascript
Javascript
improve coverage of modulemap.js
3b90bd006f6a585f5c992a249712d3b456d4e759
<ide><path>test/parallel/test-internal-module-map-asserts.js <add>// Flags: --expose-internals <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const ModuleMap = require('internal/loader/ModuleMap'); <add> <add>// ModuleMap.get, ModuleMap.has and ModuleMap.set should only accept string <add>// values as url argument. <add>{ <add> const errorReg = common.expectsError({ <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: /^The "url" argument must be of type string/ <add> }, 15); <add> <add> const moduleMap = new ModuleMap(); <add> <add> // As long as the assertion of "job" argument is done after the assertion of <add> // "url" argument this test suite is ok. Tried to mock the "job" parameter, <add> // but I think it's useless, and was not simple to mock... <add> const job = undefined; <add> <add> [{}, [], true, 1, () => {}].forEach((value) => { <add> assert.throws(() => moduleMap.get(value), errorReg); <add> assert.throws(() => moduleMap.has(value), errorReg); <add> assert.throws(() => moduleMap.set(value, job), errorReg); <add> }); <add>} <add> <add>// ModuleMap.set, job argument should only accept ModuleJob values. <add>{ <add> const errorReg = common.expectsError({ <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: /^The "job" argument must be of type ModuleJob/ <add> }, 5); <add> <add> const moduleMap = new ModuleMap(); <add> <add> [{}, [], true, 1, () => {}].forEach((value) => { <add> assert.throws(() => moduleMap.set('', value), errorReg); <add> }); <add>}
1
Ruby
Ruby
warn linux users about using --cask
020c50e588750151520296fe3b59d7de08de3de3
<ide><path>Library/Homebrew/cli/parser.rb <ide> def parse(argv = ARGV.freeze, ignore_invalid_options: false) <ide> <ide> @args_parsed = true <ide> <del> if !ignore_invalid_options && @args.help? <del> puts generate_help_text <del> exit <add> unless ignore_invalid_options <add> if @args.help? <add> puts generate_help_text <add> exit <add> end <add> <add> validate_options <ide> end <ide> <ide> @args <ide> end <ide> <add> def validate_options; end <add> <ide> def generate_help_text <ide> Formatter.format_help_text(@parser.to_s, width: COMMAND_DESC_WIDTH) <ide> .gsub(/\n.*?.*?(?=\n)/, "") <ide> def initialize(minimum, types: []) <ide> end <ide> end <ide> end <add> <add>require "extend/os/parser" <ide><path>Library/Homebrew/extend/os/linux/parser.rb <add># typed: false <add># frozen_string_literal: true <add> <add>module Homebrew <add> module CLI <add> class Parser <add> undef validate_options <add> <add> def validate_options <add> return unless @args.respond_to?(:cask?) <add> return unless @args.cask? <add> <add> msg = "Casks are not supported on Linux" <add> raise UsageError, msg unless Homebrew::EnvConfig.developer? <add> <add> opoo msg unless @args.quiet? <add> end <add> end <add> end <add>end <ide><path>Library/Homebrew/extend/os/parser.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "extend/os/linux/parser" if OS.linux? <ide><path>Library/Homebrew/test/cli/parser_spec.rb <ide> expect { parser.parse(["--not-a-command"]) }.to raise_error(OptionParser::InvalidOption, /--not-a-command/) <ide> end <ide> end <add> <add> describe "--cask on linux", :needs_linux do <add> subject(:parser) do <add> described_class.new do <add> switch "--cask" <add> end <add> end <add> <add> it "throws an error for normal users" do <add> allow(Homebrew::EnvConfig).to receive(:developer?).and_return(false) <add> expect { parser.parse(["--cask"]) }.to raise_error UsageError, /Casks are not supported on Linux/ <add> end <add> <add> it "only warns developers" do <add> allow(Homebrew::EnvConfig).to receive(:developer?).and_return(true) <add> expect { parser.parse(["--cask"]) }.not_to raise_error <add> end <add> end <ide> end <ide><path>Library/Homebrew/test/cmd/--cache_spec.rb <ide> .and be_a_success <ide> end <ide> <del> it "prints the cache files for a given Cask", :integration_test do <add> it "prints the cache files for a given Cask", :integration_test, :needs_macos do <ide> expect { brew "--cache", cask_path("local-caffeine") } <ide> .to output(%r{#{HOMEBREW_CACHE}/downloads/[\da-f]{64}--caffeine\.zip}o).to_stdout <ide> .and output(/Treating #{Regexp.escape(cask_path("local-caffeine"))} as a cask/).to_stderr <ide><path>Library/Homebrew/test/cmd/home_spec.rb <ide> .and be_a_success <ide> end <ide> <del> it "opens the homepage for a given Cask", :integration_test do <add> it "opens the homepage for a given Cask", :integration_test, :needs_macos do <ide> expect { brew "home", local_caffeine_path, "HOMEBREW_BROWSER" => "echo" } <ide> .to output(/#{local_caffeine_homepage}/).to_stdout <ide> .and output(/Treating #{Regexp.escape(local_caffeine_path)} as a cask/).to_stderr
6
Javascript
Javascript
prevent double $digest when using jquery trigger
1147f21999edf9a434cd8d24865a6455e744d858
<ide><path>src/ng/directive/input.js <ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { <ide> }); <ide> } <ide> <del> var listener = function() { <add> var listener = function(ev) { <ide> if (composing) return; <ide> var value = element.val(); <ide> <ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { <ide> } <ide> <ide> if (ctrl.$viewValue !== value) { <del> scope.$apply(function() { <add> // If an event was performed natively, jQuery sets the isTrigger property. <add> // When triggering event manually, the field is not present. Manually <add> // triggered events are performed synchronously which causes the "$digest <add> // already in progress" error. <add> if (ev && ev.isTrigger) { <ide> ctrl.$setViewValue(value); <del> }); <add> } else { <add> scope.$apply(function() { <add> ctrl.$setViewValue(value); <add> }); <add> } <ide> } <ide> }; <ide> <ide><path>src/ngScenario/Scenario.js <ide> function callerFile(offset) { <ide> * To work around this we instead use our own handler that fires a real event. <ide> */ <ide> (function(fn){ <del> var parentTrigger = fn.trigger; <add> // We need a handle to the original trigger function for input tests. <add> var parentTrigger = fn._originalTrigger = fn.trigger; <ide> fn.trigger = function(type) { <ide> if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) { <ide> var processDefaults = []; <ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> 'event so that form auto complete works',function() { <ide> assertBrowserSupportsChangeEvent(true); <ide> }); <add> <add> if (!_jqLiteMode) { <add> it('should not cause the double $digest when triggering an event using jQuery', function() { <add> $sniffer.hasEvent = function(eventName) { <add> return eventName !== 'input'; <add> }; <add> <add> compileInput('<input type="text" ng-model="name" name="alias" ng-change="change()" />'); <add> <add> scope.field = 'fake field'; <add> scope.$watch('field', function() { <add> // We need to use _originalTrigger since trigger is modified by Angular Scenario. <add> inputElm._originalTrigger('change'); <add> }); <add> scope.$apply(); <add> }); <add> } <ide> }); <ide> <ide> describe('"paste" and "cut" events', function() {
3
Text
Text
fix a link to a slack clone example in supabase
cfca41cbfd9e59de95563e60fedcbfe375df5048
<ide><path>examples/with-supabase-auth-realtime-db/README.md <ide> This is a full-stack Slack clone example using: <ide> <ide> ![Demo animation gif](./docs/slack-clone-demo.gif) <ide> <del>This example is a clone of the [Slack Clone example](https://github.com/supabase/supabase/tree/master/examples/slack-clone) in the supabase repo, feel free to check it out! <add>This example is a clone of the [Slack Clone example](https://github.com/supabase/supabase/tree/master/examples/nextjs-slack-clone) in the supabase repo, feel free to check it out! <ide> <ide> ## Deploy your own <ide>
1
Text
Text
add link to ubuntu notes about ltsenablementstack
27f44b9bb162dce988913b981f1f21eb149d875f
<ide><path>docs/sources/installation/ubuntulinux.md <ide> VirtualBox guest additions. If you didn't install the headers for your <ide> "precise" kernel, then you can skip these headers for the "raring" <ide> kernel. But it is safer to include them if you're not sure. <ide> <add>Please read the installation instructions for backported kernels at <add>Ubuntu.org to understand why you also need to install the Xorg packages <add>if running Docker on a machine with a graphical environment like Unity. <add>[LTS Enablement Stack](https://wiki.ubuntu.com/Kernel/LTSEnablementStack) refer to note 5 under <add>each version. <add> <ide> # install the backported kernel <ide> $ sudo apt-get update <ide> $ sudo apt-get install linux-image-generic-lts-raring linux-headers-generic-lts-raring <add> <add> # install the backported kernel and xorg if using Unity/Xorg <add> $ sudo apt-get install --install-recommends linux-generic-lts-raring xserver-xorg-lts-raring libgl1-mesa-glx-lts-raring <ide> <ide> # reboot <ide> $ sudo reboot
1
Java
Java
use emptyobserver instead of subscribers.empty()
5a381a2d6ba3d1b0dbf4754720f708720357a203
<ide><path>src/main/java/rx/internal/operators/BufferUntilSubscriber.java <ide> import rx.Observer; <ide> import rx.Subscriber; <ide> import rx.functions.Action0; <add>import rx.observers.EmptyObserver; <ide> import rx.observers.Subscribers; <ide> import rx.subjects.Subject; <ide> import rx.subscriptions.Subscriptions; <ide> */ <ide> public class BufferUntilSubscriber<T> extends Subject<T, T> { <ide> <add> @SuppressWarnings("rawtypes") <add> private final static Observer EMPTY_OBSERVER = new EmptyObserver(); <add> <ide> /** <ide> * @warn create() undescribed <ide> * @return <ide> public void call(final Subscriber<? super T> s) { <ide> s.add(Subscriptions.create(new Action0() { <ide> @Override <ide> public void call() { <del> state.observerRef = Subscribers.empty(); <add> state.observerRef = EMPTY_OBSERVER; <ide> } <ide> })); <ide> boolean win = false;
1
Text
Text
use "long term support" in readme
16ae37848dfed4c2a2fdea68ea2d4f53c982fa47
<ide><path>README.md <ide> Looking for help? Check out the <ide> April and October every year. Releases appearing each October have a support <ide> life of 8 months. Releases appearing each April convert to LTS (see below) <ide> each October. <del>* **LTS**: Releases that receive Long-term Support, with a focus on stability <add>* **LTS**: Releases that receive Long Term Support, with a focus on stability <ide> and security. Every even-numbered major version will become an LTS release. <ide> LTS releases receive 12 months of _Active LTS_ support and a further 18 months <ide> of _Maintenance_. LTS release lines have alphabetically-ordered code names,
1
Javascript
Javascript
sync router.js - closes
4ce4b1fc613db57740bcf0e3c8fbde358f784757
<ide><path>packages/ember-routing/lib/vendor/router.js <ide> define("router", <ide> .then(handleAbort) <ide> .then(afterModel) <ide> .then(handleAbort) <del> .then(proceed) <del> .then(null, handleError); <add> .then(null, handleError) <add> .then(proceed); <ide> <ide> function handleAbort(result) { <ide> if (transition.isAborted) { <ide> define("router", <ide> // `error` event from this handler info up to root. <ide> trigger(handlerInfos.slice(0, index + 1), true, ['error', reason, transition]); <ide> <del> if (handler.error) { <del> handler.error(reason, transition); <del> } <del> <ide> // Propagate the original error. <ide> return RSVP.reject(reason); <ide> }
1
Go
Go
reuse our pkg/locker
a7851e2556edb3e5333b6fe53160755fb5b7d616
<ide><path>libcontainerd/client.go <ide> import ( <ide> "fmt" <ide> "sync" <ide> <del> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/pkg/locker" <ide> ) <ide> <ide> // clientCommon contains the platform agnostic fields used in the client structure <ide> type clientCommon struct { <del> backend Backend <del> containers map[string]*container <del> containerMutexes map[string]*sync.Mutex // lock by container ID <del> mapMutex sync.RWMutex // protects read/write oprations from containers map <del> sync.Mutex // lock for containerMutexes map access <add> backend Backend <add> containers map[string]*container <add> locker *locker.Locker <add> mapMutex sync.RWMutex // protects read/write oprations from containers map <ide> } <ide> <ide> func (clnt *client) lock(containerID string) { <del> clnt.Lock() <del> if _, ok := clnt.containerMutexes[containerID]; !ok { <del> clnt.containerMutexes[containerID] = &sync.Mutex{} <del> } <del> clnt.Unlock() <del> clnt.containerMutexes[containerID].Lock() <add> clnt.locker.Lock(containerID) <ide> } <ide> <ide> func (clnt *client) unlock(containerID string) { <del> clnt.Lock() <del> if l, ok := clnt.containerMutexes[containerID]; ok { <del> l.Unlock() <del> } else { <del> logrus.Warnf("unlock of non-existing mutex: %s", containerID) <del> } <del> clnt.Unlock() <add> clnt.locker.Unlock(containerID) <ide> } <ide> <ide> // must hold a lock for cont.containerID <ide><path>libcontainerd/remote_linux.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> containerd "github.com/docker/containerd/api/grpc/types" <add> "github.com/docker/docker/pkg/locker" <ide> sysinfo "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/utils" <ide> "golang.org/x/net/context" <ide> func (r *remote) Cleanup() { <ide> func (r *remote) Client(b Backend) (Client, error) { <ide> c := &client{ <ide> clientCommon: clientCommon{ <del> backend: b, <del> containerMutexes: make(map[string]*sync.Mutex), <del> containers: make(map[string]*container), <add> backend: b, <add> containers: make(map[string]*container), <add> locker: locker.New(), <ide> }, <ide> remote: r, <ide> exitNotifiers: make(map[string]*exitNotifier), <ide><path>libcontainerd/remote_windows.go <ide> package libcontainerd <ide> <del>import "sync" <add>import "github.com/docker/docker/pkg/locker" <ide> <ide> type remote struct { <ide> } <ide> <ide> func (r *remote) Client(b Backend) (Client, error) { <ide> c := &client{ <ide> clientCommon: clientCommon{ <del> backend: b, <del> containerMutexes: make(map[string]*sync.Mutex), <del> containers: make(map[string]*container), <add> backend: b, <add> containers: make(map[string]*container), <add> locker: locker.New(), <ide> }, <ide> } <ide> return c, nil
3
PHP
PHP
fix return value of setentity()
f4da682a925ef4453f17a7cccfd81697bca3fe21
<ide><path>src/Datasource/EntityTrait.php <ide> public function setDirty($property, $isDirty) <ide> if ($isDirty === false) { <ide> unset($this->_dirty[$property]); <ide> <del> return false; <add> return $this; <ide> } <ide> <ide> $this->_dirty[$property] = true; <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testExtract() <ide> } <ide> <ide> /** <del> * Tests dirty() method on a newly created object <add> * Tests isDirty() method on a newly created object <ide> * <ide> * @return void <ide> */ <del> public function testDirty() <add> public function testIsDirty() <ide> { <ide> $entity = new Entity([ <ide> 'id' => 1, <ide> 'title' => 'Foo', <ide> 'author_id' => 3 <ide> ]); <ide> $this->assertTrue($entity->dirty('id')); <del> $this->assertTrue($entity->dirty('title')); <del> $this->assertTrue($entity->dirty('author_id')); <add> $this->assertTrue($entity->isDirty('id')); <add> $this->assertTrue($entity->isDirty('title')); <add> $this->assertTrue($entity->isDirty('author_id')); <ide> <ide> $this->assertTrue($entity->dirty()); <add> $this->assertTrue($entity->isDirty()); <ide> <ide> $entity->dirty('id', false); <ide> $this->assertFalse($entity->dirty('id')); <ide> $this->assertTrue($entity->dirty('title')); <del> $entity->dirty('title', false); <del> $this->assertFalse($entity->dirty('title')); <del> $this->assertTrue($entity->dirty()); <del> $entity->dirty('author_id', false); <del> $this->assertFalse($entity->dirty()); <add> <add> $entity->setDirty('title', false); <add> $this->assertFalse($entity->isDirty('title')); <add> $this->assertTrue($entity->isDirty(), 'should be dirty, one field left'); <add> <add> $entity->setDirty('author_id', false); <add> $this->assertFalse($entity->isDirty(), 'all fields are clean.'); <add> } <add> <add> /** <add> * Test setDirty(). <add> * <add> * @return void <add> */ <add> public function testSetDirty() <add> { <add> $entity = new Entity([ <add> 'id' => 1, <add> 'title' => 'Foo', <add> 'author_id' => 3 <add> ], ['markClean' => true]); <add> <add> $this->assertFalse($entity->isDirty()); <add> $this->assertSame($entity, $entity->setDirty('title', true)); <add> $this->assertSame($entity, $entity->setDirty('id', false)); <add> <add> $entity->setErrors(['title' => ['badness']]); <add> $entity->setDirty('title', true); <add> $this->assertEmpty($entity->getErrors('title'), 'Making a field dirty clears errors.'); <ide> } <ide> <ide> /** <ide> public function testDirtyChangingProperties() <ide> 'title' => 'Foo', <ide> ]); <ide> <del> $entity->dirty('title', false); <del> $this->assertFalse($entity->dirty('title')); <add> $entity->setDirty('title', false); <add> $this->assertFalse($entity->isDirty('title')); <ide> <ide> $entity->set('title', 'Foo'); <del> $this->assertTrue($entity->dirty('title')); <add> $this->assertTrue($entity->isDirty('title')); <ide> <ide> $entity->set('title', 'Foo'); <del> $this->assertTrue($entity->dirty('title')); <add> $this->assertTrue($entity->isDirty('title')); <ide> <ide> $entity->set('something', 'else'); <del> $this->assertTrue($entity->dirty('something')); <add> $this->assertTrue($entity->isDirty('something')); <ide> } <ide> <ide> /** <ide> public function testExtractDirty() <ide> 'title' => 'Foo', <ide> 'author_id' => 3 <ide> ]); <del> $entity->dirty('id', false); <del> $entity->dirty('title', false); <add> $entity->setDirty('id', false); <add> $entity->setDirty('title', false); <ide> $expected = ['author_id' => 3]; <ide> $result = $entity->extract(['id', 'title', 'author_id'], true); <ide> $this->assertEquals($expected, $result);
2
Python
Python
enhance the ability of add
367f8ceddd0f4c7ec1bdc506ed1d6b1c2808b2f2
<ide><path>matrix/matrix_operation.py <ide> from typing import List, Tuple <ide> <ide> <del>def add(matrix_a: List[list], matrix_b: List[list]) -> List[list]: <add>def add(*matrix_s: List[list]) -> List[list]: <ide> """ <ide> >>> add([[1,2],[3,4]],[[2,3],[4,5]]) <ide> [[3, 5], [7, 9]] <ide> >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) <ide> [[3.2, 5.4], [7, 9]] <add> >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]]) <add> [[7, 14], [12, 16]] <ide> """ <del> if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): <del> _verify_matrix_sizes(matrix_a, matrix_b) <del> return [[i + j for i, j in zip(m, n)] for m, n in zip(matrix_a, matrix_b)] <add> if all(_check_not_integer(m) for m in matrix_s): <add> a, *b = matrix_s <add> for matrix in b: <add> _verify_matrix_sizes(a, matrix) <add> return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] <ide> <ide> <ide> def subtract(matrix_a: List[list], matrix_b: List[list]) -> List[list]: <ide> def subtract(matrix_a: List[list], matrix_b: List[list]) -> List[list]: <ide> """ <ide> if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): <ide> _verify_matrix_sizes(matrix_a, matrix_b) <del> return [[i - j for i, j in zip(m, n)] for m, n in zip(matrix_a, matrix_b)] <add> return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] <ide> <ide> <ide> def scalar_multiply(matrix: List[list], n: int) -> List[list]: <ide> def minor(matrix: List[list], row: int, column: int) -> List[list]: <ide> >>> minor([[1, 2], [3, 4]], 1, 1) <ide> [[1]] <ide> """ <del> minor = matrix[:row] + matrix[row + 1 :] <del> return [row[:column] + row[column + 1 :] for row in minor] <add> minor = matrix[:row] + matrix[row + 1:] <add> return [row[:column] + row[column + 1:] for row in minor] <ide> <ide> <ide> def determinant(matrix: List[list]) -> int: <ide> def _shape(matrix: List[list]) -> list: <ide> return list((len(matrix), len(matrix[0]))) <ide> <ide> <del>def _verify_matrix_sizes(matrix_a: List[list], matrix_b: List[list]) -> Tuple[list]: <add>def _verify_matrix_sizes( <add> matrix_a: List[list], matrix_b: List[list]) -> Tuple[list]: <ide> shape = _shape(matrix_a) <ide> shape += _shape(matrix_b) <ide> if shape[0] != shape[2] or shape[1] != shape[3]: <ide> def _verify_matrix_sizes(matrix_a: List[list], matrix_b: List[list]) -> Tuple[li <ide> def main(): <ide> matrix_a = [[12, 10], [3, 9]] <ide> matrix_b = [[3, 4], [7, 4]] <del> matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] <add> matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], <add> [31, 32, 33, 34], [41, 42, 43, 44]] <ide> matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] <del> print(f"Add Operation, {matrix_a} + {matrix_b} = {add(matrix_a, matrix_b)} \n") <add> print( <add> f"Add Operation, {matrix_a} + {matrix_b} =" <add> f"{add(matrix_a, matrix_b)} \n") <ide> print( <ide> f"Multiply Operation, {matrix_a} * {matrix_b}", <ide> f"= {multiply(matrix_a, matrix_b)} \n",
1
Text
Text
add link to rack website
e42100cf42345e84a83c3e711671b7e6de7fef2b
<ide><path>guides/source/getting_started.md <ide> of the files and folders that Rails created by default: <ide> |app/|Contains the controllers, models, views, helpers, mailers, channels, jobs and assets for your application. You'll focus on this folder for the remainder of this guide.| <ide> |bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy or run your application.| <ide> |config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).| <del>|config.ru|Rack configuration for Rack based servers used to start the application.| <add>|config.ru|Rack configuration for Rack based servers used to start the application. For more information about Rack, see the [Rack website](https://rack.github.io/).| <ide> |db/|Contains your current database schema, as well as the database migrations.| <ide> |Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the [Bundler website](https://bundler.io).| <ide> |lib/|Extended modules for your application.|
1
Mixed
Ruby
avoid eager loading in relation#pretty_print
546de0f6c6a91e4e2019f4759098caa5185176e0
<ide><path>activerecord/CHANGELOG.md <add>* Avoid loading every records in `ActiveRecord::Relation#pretty_print` <add> <add> ```ruby <add> # Before <add> pp Foo.all # Loads the whole table. <add> <add> # After <add> pp Foo.all # Shows 10 items and an ellipsis. <add> ``` <add> <add> *Ulysse Buonomo* <add> <ide> * Change `QueryMethods#in_order_of` to drop records not listed in values. <ide> <ide> `in_order_of` now filters down to the values provided, to match the behavior of the `Enumerable` version. <ide><path>activerecord/lib/active_record/relation.rb <ide> def ==(other) <ide> end <ide> end <ide> <del> def pretty_print(q) <del> q.pp(records) <add> def pretty_print(pp) <add> subject = loaded? ? records : annotate("loading for pp") <add> entries = subject.take([limit_value, 11].compact.min) <add> <add> entries[10] = "..." if entries.size == 11 <add> <add> pp.pp(entries) <ide> end <ide> <ide> # Returns true if relation is blank. <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_destroy_by <ide> end <ide> end <ide> <add> test "relations limit the records in #pretty_print at 10" do <add> relation = Post.limit(11) <add> out = StringIO.new <add> PP.pp(relation, out) <add> assert_equal 10, out.string.scan(/#<\w*Post:/).size <add> assert out.string.end_with?("\"...\"]\n"), "Did not end with an ellipsis." <add> end <add> <add> test "relations don't load all records in #pretty_print" do <add> assert_sql(/LIMIT|ROWNUM <=|FETCH FIRST/) do <add> PP.pp Post.all, StringIO.new # avoid outputting. <add> end <add> end <add> <add> test "loading query is annotated in #pretty_print" do <add> assert_sql(%r(/\* loading for pp \*/)) do <add> PP.pp Post.all, StringIO.new # avoid outputting. <add> end <add> end <add> <add> test "already-loaded relations don't perform a new query in #pretty_print" do <add> relation = Post.limit(2) <add> relation.to_a <add> <add> assert_no_queries do <add> PP.pp relation, StringIO.new # avoid outputting. <add> end <add> end <add> <ide> test "using a custom table affects the wheres" do <ide> post = posts(:welcome) <ide>
3
Text
Text
fix typo in util.parseargs usage example
aba2cd74dce406da2f3dcf6a2bd08d9552fa3671
<ide><path>doc/api/util.md <ide> const { <ide> positionals <ide> } = parseArgs({ args, options }); <ide> console.log(values, positionals); <del>// Prints: [Object: null prototype] { foo: true, bar: 'b' } []ss <add>// Prints: [Object: null prototype] { foo: true, bar: 'b' } [] <ide> ``` <ide> <ide> `util.parseArgs` is experimental and behavior may change. Join the
1
Text
Text
add examples readme
81efde0ce401f3004e23fc1ed794d445b8cafa51
<ide><path>examples/README.md <add><a href="https://explosion.ai"><img src="https://explosion.ai/assets/img/logo.svg" width="125" height="125" align="right" /></a> <add> <add># spaCy examples <add> <add>For spaCy v3 we've converted many of the [v2 example <add>scripts](https://github.com/explosion/spaCy/tree/v2.3.x/examples/) into <add>end-to-end [spacy projects](https://spacy.io/usage/projects) workflows. The <add>workflows include all the steps to go from data to packaged spaCy models. <add> <add>## 🪐 Pipeline component demos <add> <add>The simplest demos for training a single pipeline component are in the <add>[`pipelines`](https://github.com/explosion/projects/blob/v3/pipelines) category <add>including: <add> <add>- [`pipelines/ner_demo`](https://github.com/explosion/projects/blob/v3/pipelines/ner_demo): <add> Train a named entity recognizer <add>- [`pipelines/textcat_demo`](https://github.com/explosion/projects/blob/v3/pipelines/textcat_demo): <add> Train a text classifier <add>- [`pipelines/parser_intent_demo`](https://github.com/explosion/projects/blob/v3/pipelines/parser_intent_demo): <add> Train a dependency parser for custom semantics <add> <add>## 🪐 Tutorials <add> <add>The [`tutorials`](https://github.com/explosion/projects/blob/v3/tutorials) <add>category includes examples that work through specific NLP use cases end-to-end: <add> <add>- [`tutorials/textcat_goemotions`](https://github.com/explosion/projects/blob/v3/tutorials/textcat_goemotions): <add> Train a text classifier to categorize emotions in Reddit posts <add>- [`tutorials/nel_emerson`](https://github.com/explosion/projects/blob/v3/tutorials/nel_emerson): <add> Use an entity linker to disambiguate mentions of the same name <add> <add>Check out the [projects documentation](https://spacy.io/usage/projects) and <add>browse through the [available <add>projects](https://github.com/explosion/projects/)! <add> <add>## 🚀 Get started with a demo project <add> <add>The <add>[`pipelines/ner_demo`](https://github.com/explosion/projects/blob/v3/pipelines/ner_demo) <add>project converts the spaCy v2 <add>[`train_ner.py`](https://github.com/explosion/spaCy/blob/v2.3.x/examples/training/train_ner.py) <add>demo script into a spaCy v3 project. <add> <add>1. Clone the project: <add> <add> ```bash <add> python -m spacy project clone pipelines/ner_demo <add> ``` <add> <add>2. Install requirements and download any data assets: <add> <add> ```bash <add> cd ner_demo <add> python -m pip install -r requirements.txt <add> python -m spacy project assets <add> ``` <add> <add>3. Run the default workflow to convert, train and evaluate: <add> <add> ```bash <add> python -m spacy project run all <add> ``` <add> <add> Sample output: <add> <add> ```none <add> ℹ Running workflow 'all' <add> <add> ================================== convert ================================== <add> Running command: /home/user/venv/bin/python scripts/convert.py en assets/train.json corpus/train.spacy <add> Running command: /home/user/venv/bin/python scripts/convert.py en assets/dev.json corpus/dev.spacy <add> <add> =============================== create-config =============================== <add> Running command: /home/user/venv/bin/python -m spacy init config --lang en --pipeline ner configs/config.cfg --force <add> ℹ Generated config template specific for your use case <add> - Language: en <add> - Pipeline: ner <add> - Optimize for: efficiency <add> - Hardware: CPU <add> - Transformer: None <add> ✔ Auto-filled config with all values <add> ✔ Saved config <add> configs/config.cfg <add> You can now add your data and train your pipeline: <add> python -m spacy train config.cfg --paths.train ./train.spacy --paths.dev ./dev.spacy <add> <add> =================================== train =================================== <add> Running command: /home/user/venv/bin/python -m spacy train configs/config.cfg --output training/ --paths.train corpus/train.spacy --paths.dev corpus/dev.spacy --training.eval_frequency 10 --training.max_steps 100 --gpu-id -1 <add> ℹ Using CPU <add> <add> =========================== Initializing pipeline =========================== <add> [2021-03-11 19:34:59,101] [INFO] Set up nlp object from config <add> [2021-03-11 19:34:59,109] [INFO] Pipeline: ['tok2vec', 'ner'] <add> [2021-03-11 19:34:59,113] [INFO] Created vocabulary <add> [2021-03-11 19:34:59,113] [INFO] Finished initializing nlp object <add> [2021-03-11 19:34:59,265] [INFO] Initialized pipeline components: ['tok2vec', 'ner'] <add> ✔ Initialized pipeline <add> <add> ============================= Training pipeline ============================= <add> ℹ Pipeline: ['tok2vec', 'ner'] <add> ℹ Initial learn rate: 0.001 <add> E # LOSS TOK2VEC LOSS NER ENTS_F ENTS_P ENTS_R SCORE <add> --- ------ ------------ -------- ------ ------ ------ ------ <add> 0 0 0.00 7.90 0.00 0.00 0.00 0.00 <add> 10 10 0.11 71.07 0.00 0.00 0.00 0.00 <add> 20 20 0.65 22.44 50.00 50.00 50.00 0.50 <add> 30 30 0.22 6.38 80.00 66.67 100.00 0.80 <add> 40 40 0.00 0.00 80.00 66.67 100.00 0.80 <add> 50 50 0.00 0.00 80.00 66.67 100.00 0.80 <add> 60 60 0.00 0.00 100.00 100.00 100.00 1.00 <add> 70 70 0.00 0.00 100.00 100.00 100.00 1.00 <add> 80 80 0.00 0.00 100.00 100.00 100.00 1.00 <add> 90 90 0.00 0.00 100.00 100.00 100.00 1.00 <add> 100 100 0.00 0.00 100.00 100.00 100.00 1.00 <add> ✔ Saved pipeline to output directory <add> training/model-last <add> ``` <add> <add>4. Package the model: <add> <add> ```bash <add> python -m spacy project run package <add> ``` <add> <add>5. Visualize the model's output with [Streamlit](https://streamlit.io): <add> <add> ```bash <add> python -m spacy project run visualize-model <add> ``` <ide><path>examples/training/README.md <add><a href="https://explosion.ai"><img src="https://explosion.ai/assets/img/logo.svg" width="125" height="125" align="right" /></a> <add> <add># spaCy examples <add> <add>See [examples/README.md](../README.md)
2
Ruby
Ruby
check integrity after uploads
894e1e3183b78d62d873454312882df53a29f850
<ide><path>lib/active_storage/blob.rb <ide> def upload(io) <ide> self.checksum = compute_checksum_in_chunks(io) <ide> self.byte_size = io.size <ide> <del> service.upload(key, io) <add> service.upload(key, io, checksum: checksum) <ide> end <ide> <ide> def download <ide><path>lib/active_storage/service.rb <ide> # Abstract class serving as an interface for concrete services. <ide> class ActiveStorage::Service <add> class ActiveStorage::IntegrityError < StandardError; end <add> <ide> def self.configure(service, **options) <ide> begin <ide> require "active_storage/service/#{service.to_s.downcase}_service" <ide> def self.configure(service, **options) <ide> end <ide> <ide> <del> def upload(key, io) <add> def upload(key, io, checksum: nil) <ide> raise NotImplementedError <ide> end <ide> <ide><path>lib/active_storage/service/disk_service.rb <ide> def initialize(root:) <ide> @root = root <ide> end <ide> <del> def upload(key, io) <add> def upload(key, io, checksum: nil) <ide> File.open(make_path_for(key), "wb") do |file| <ide> while chunk = io.read(64.kilobytes) <ide> file.write(chunk) <ide> end <ide> end <add> <add> ensure_integrity_of(key, checksum) if checksum <ide> end <ide> <ide> def download(key) <ide> def folder_for(key) <ide> def make_path_for(key) <ide> path_for(key).tap { |path| FileUtils.mkdir_p File.dirname(path) } <ide> end <add> <add> def ensure_integrity_of(key, checksum) <add> unless Digest::MD5.file(path_for(key)).base64digest == checksum <add> raise ActiveStorage::IntegrityError <add> end <add> end <ide> end <ide><path>lib/active_storage/service/gcs_service.rb <ide> def initialize(project:, keyfile:, bucket:) <ide> @bucket = @client.bucket(bucket) <ide> end <ide> <del> def upload(key, io) <add> def upload(key, io, checksum: nil) <add> # FIXME: Ensure integrity by sending the checksum for service side verification <ide> bucket.create_file(io, key) <ide> end <ide> <ide><path>lib/active_storage/service/mirror_service.rb <ide> def initialize(services:) <ide> @services = services <ide> end <ide> <del> def upload(key, io) <add> def upload(key, io, checksum: nil) <ide> services.collect do |service| <del> service.upload key, io <add> service.upload key, io, checksum: checksum <ide> io.rewind <ide> end <ide> end <ide><path>lib/active_storage/service/s3_service.rb <ide> def initialize(access_key_id:, secret_access_key:, region:, bucket:) <ide> @bucket = @client.bucket(bucket) <ide> end <ide> <del> def upload(key, io) <add> def upload(key, io, checksum: nil) <add> # FIXME: Ensure integrity by sending the checksum for service side verification <ide> object_for(key).put(body: io) <ide> end <ide> <ide><path>test/service/shared_service_tests.rb <ide> module ActiveStorage::Service::SharedServiceTests <ide> FIXTURE_FILE.rewind <ide> end <ide> <del> test "uploading" do <add> test "uploading with integrity" do <ide> begin <ide> key = SecureRandom.base58(24) <ide> data = "Something else entirely!" <del> @service.upload(key, StringIO.new(data)) <add> @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data)) <ide> <ide> assert_equal data, @service.download(key) <ide> ensure <ide> @service.delete key <ide> end <ide> end <ide> <add> test "upload without integrity" do <add> begin <add> key = SecureRandom.base58(24) <add> data = "Something else entirely!" <add> <add> assert_raises(ActiveStorage::IntegrityError) do <add> @service.upload(key, StringIO.new(data), checksum: "BAD_CHECKSUM") <add> end <add> ensure <add> @service.delete key <add> end <add> end <add> <ide> test "downloading" do <ide> assert_equal FIXTURE_FILE.read, @service.download(FIXTURE_KEY) <ide> end
7
Ruby
Ruby
fix serialization problem with yaml in 1.8.3
76a7a525576fa1ed12a362fac5da6e2f8b6dc92c
<ide><path>activerecord/lib/active_record/base.rb <ide> def quoted_comma_pair_list(quoter, hash) <ide> <ide> def object_from_yaml(string) <ide> return string unless string.is_a?(String) <del> if has_yaml_encoding_header?(string) <del> begin <del> YAML::load(string) <del> rescue Object <del> # Apparently wasn't YAML anyway <del> string <del> end <del> else <del> string <del> end <del> end <del> <del> def has_yaml_encoding_header?(string) <del> string[0..3] == "--- " <add> YAML::load(string) rescue string <ide> end <ide> <ide> def clone_attributes(reader_method = :read_attribute, attributes = {}) <ide><path>activerecord/test/base_test.rb <ide> def test_serialized_attribute_with_class_constraint <ide> end <ide> <ide> def test_quote <del> content = "\\ \001 ' \n \\n \"" <del> topic = Topic.create('content' => content) <del> assert_equal content, Topic.find(topic.id).content <add> author_name = "\\ \001 ' \n \\n \"" <add> topic = Topic.create('author_name' => author_name) <add> assert_equal author_name, Topic.find(topic.id).author_name <ide> end <ide> <ide> def test_class_level_destroy
2
Ruby
Ruby
remove intermediate variable
0c28247db19f2af9cb71e74f6824715e72f11076
<ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb <ide> def through_records_by_owner <ide> <ide> owners.each_with_object({}) do |owner, h| <ide> association = owner.association through_reflection.name <del> through_records = Array(association.reader) <add> h[owner] = Array(association.reader) <ide> <ide> # Dont cache the association - we would only be caching a subset <ide> association.reset if should_reset <del> <del> h[owner] = through_records <ide> end <ide> end <ide>
1
PHP
PHP
use constants where possible
1d42ee0298e08da186974f3c5b91b3afcf6f580b
<ide><path>src/Datasource/QueryTrait.php <ide> public function getMapReducers(): array <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> public function formatResults(?callable $formatter = null, $mode = 0) <add> public function formatResults(?callable $formatter = null, $mode = self::APPEND) <ide> { <ide> if ($mode === self::OVERWRITE) { <ide> $this->_formatters = []; <ide><path>src/ORM/Query.php <ide> public function cleanCopy() <ide> $clone = clone $this; <ide> $clone->setEagerLoader(clone $this->getEagerLoader()); <ide> $clone->triggerBeforeFind(); <del> $clone->enableAutoFields(false); <add> $clone->disableAutoFields(); <ide> $clone->limit(null); <ide> $clone->order([], true); <ide> $clone->offset(null); <ide> $clone->mapReduce(null, null, true); <del> $clone->formatResults(null, true); <add> $clone->formatResults(null, self::OVERWRITE); <ide> $clone->setSelectTypeMap(new TypeMap()); <ide> $clone->decorateResults(null, true); <ide>
2
Java
Java
remove junit 3.8 based test class hierarchy
4525068f56314e8e322e412852feedc1486a0d02
<ide><path>spring-test/src/main/java/org/springframework/test/annotation/Timed.java <ide> * @author Sam Brannen <ide> * @since 2.0 <ide> * @see Repeat <del> * @see AbstractAnnotationAwareTransactionalTests <ide> */ <ide> @Documented <ide> @Retention(RetentionPolicy.RUNTIME) <ide><path>spring-test/src/main/java/org/springframework/test/jpa/OrmXmlOverridingShadowingClassLoader.java <del>/* <del> * Copyright 2002-2012 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.test.jpa; <del> <del>import org.springframework.instrument.classloading.ResourceOverridingShadowingClassLoader; <del> <del>/** <del> * Subclass of ShadowingClassLoader that overrides attempts to <del> * locate {@code orm.xml}. <del> * <del> * <p>This class must <b>not</b> be an inner class of AbstractJpaTests <del> * to avoid it being loaded until first used. <del> * <del> * @author Rod Johnson <del> * @author Adrian Colyer <del> * @author Juergen Hoeller <del> * @since 2.0 <del> */ <del>class OrmXmlOverridingShadowingClassLoader extends ResourceOverridingShadowingClassLoader { <del> <del> /** <del> * Default location of the {@code orm.xml} file in the class path: <del> * "META-INF/orm.xml" <del> */ <del> public static final String DEFAULT_ORM_XML_LOCATION = "META-INF/orm.xml"; <del> <del> <del> public OrmXmlOverridingShadowingClassLoader(ClassLoader loader, String realOrmXmlLocation) { <del> super(loader); <del> <del> // Automatically exclude classes from these well-known persistence providers. <del> // Do NOT exclude Hibernate classes -- <del> // this causes class casts due to use of CGLIB by Hibernate. <del> // Same goes for OpenJPA which will not enhance the domain classes. <del> excludePackage("oracle.toplink.essentials"); <del> excludePackage("junit"); <del> <del> override(DEFAULT_ORM_XML_LOCATION, realOrmXmlLocation); <del> } <del> <del>} <ide><path>spring-test/src/main/java/org/springframework/test/jpa/package-info.java <del> <del>/** <del> * <del> * As of Spring 3.0, this package has been deprecated in favor of using the listener-based <del> * <em>Spring TestContext Framework</em>. <del> * <del> */ <del>package org.springframework.test.jpa; <del>
3
PHP
PHP
add @link to cookiecomponent docblocks
bc0e0b5c053de525e3966f4e553b7e730ea6e3d5
<ide><path>lib/Cake/Controller/Component/CookieComponent.php <ide> public function startup($controller) { <ide> * @param boolean $encrypt Set to true to encrypt value, false otherwise <ide> * @param string $expires Can be either Unix timestamp, or date string <ide> * @return void <add> * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write <ide> */ <ide> public function write($key, $value = null, $encrypt = true, $expires = null) { <ide> if (is_null($encrypt)) { <ide> public function write($key, $value = null, $encrypt = true, $expires = null) { <ide> * <ide> * @param mixed $key Key of the value to be obtained. If none specified, obtain map key => values <ide> * @return string or null, value for specified key <add> * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::read <ide> */ <ide> public function read($key = null) { <ide> if (empty($this->_values) && isset($_COOKIE[$this->name])) { <ide> public function read($key = null) { <ide> * <ide> * @param string $key Key of the value to be deleted <ide> * @return void <add> * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::delete <ide> */ <ide> public function delete($key) { <ide> if (empty($this->_values)) { <ide> public function delete($key) { <ide> * Failure to do so will result in header already sent errors. <ide> * <ide> * @return void <add> * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::destroy <ide> */ <ide> public function destroy() { <ide> if (isset($_COOKIE[$this->name])) { <ide> protected function _delete($name) { <ide> protected function _setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly = false) { <ide> setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); <ide> } <add> <ide> /** <ide> * Encrypts $value using public $type method in Security class <ide> *
1
PHP
PHP
fix param types in docblocks
9f0af8433eaae7a59e297229ca84d998e0e56edf
<ide><path>src/Illuminate/Auth/Access/HandlesAuthorization.php <ide> protected function allow($message = null, $code = null) <ide> /** <ide> * Throws an unauthorized exception. <ide> * <del> * @param string $message <add> * @param string|null $message <ide> * @param mixed|null $code <ide> * @return \Illuminate\Auth\Access\Response <ide> */ <ide><path>src/Illuminate/Cookie/CookieJar.php <ide> public function hasQueued($key, $path = null) <ide> * <ide> * @param string $key <ide> * @param mixed $default <del> * @param string $path <add> * @param string|null $path <ide> * @return \Symfony\Component\HttpFoundation\Cookie <ide> */ <ide> public function queued($key, $default = null, $path = null) <ide><path>src/Illuminate/Database/Concerns/BuildsQueries.php <ide> public function chunkById($count, callable $callback, $column = null, $alias = n <ide> * <ide> * @param callable $callback <ide> * @param int $count <del> * @param string $column <del> * @param string $alias <add> * @param string|null $column <add> * @param string|null $alias <ide> * @return bool <ide> */ <ide> public function eachById(callable $callback, $count = 1000, $column = null, $alias = null) <ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function pluck($column, $key = null) <ide> /** <ide> * Paginate the given query. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int|null $page <ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', <ide> /** <ide> * Paginate the given query into a simple paginator. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int|null $page <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php <ide> trait HasRelationships <ide> * Define a one-to-one relationship. <ide> * <ide> * @param string $related <del> * @param string $foreignKey <del> * @param string $localKey <add> * @param string|null $foreignKey <add> * @param string|null $localKey <ide> * @return \Illuminate\Database\Eloquent\Relations\HasOne <ide> */ <ide> public function hasOne($related, $foreignKey = null, $localKey = null) <ide> protected function newHasOneThrough(Builder $query, Model $farParent, Model $thr <ide> * <ide> * @param string $related <ide> * @param string $name <del> * @param string $type <del> * @param string $id <del> * @param string $localKey <add> * @param string|null $type <add> * @param string|null $id <add> * @param string|null $localKey <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphOne <ide> */ <ide> public function morphOne($related, $name, $type = null, $id = null, $localKey = null) <ide> protected function newMorphOne(Builder $query, Model $parent, $type, $id, $local <ide> * Define an inverse one-to-one or many relationship. <ide> * <ide> * @param string $related <del> * @param string $foreignKey <del> * @param string $ownerKey <del> * @param string $relation <add> * @param string|null $foreignKey <add> * @param string|null $ownerKey <add> * @param string|null $relation <ide> * @return \Illuminate\Database\Eloquent\Relations\BelongsTo <ide> */ <ide> public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null) <ide> protected function newBelongsTo(Builder $query, Model $child, $foreignKey, $owne <ide> /** <ide> * Define a polymorphic, inverse one-to-one or many relationship. <ide> * <del> * @param string $name <del> * @param string $type <del> * @param string $id <del> * @param string $ownerKey <add> * @param string|null $name <add> * @param string|null $type <add> * @param string|null $id <add> * @param string|null $ownerKey <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphTo <ide> */ <ide> public function morphTo($name = null, $type = null, $id = null, $ownerKey = null) <ide> protected function guessBelongsToRelation() <ide> * Define a one-to-many relationship. <ide> * <ide> * @param string $related <del> * @param string $foreignKey <del> * @param string $localKey <add> * @param string|null $foreignKey <add> * @param string|null $localKey <ide> * @return \Illuminate\Database\Eloquent\Relations\HasMany <ide> */ <ide> public function hasMany($related, $foreignKey = null, $localKey = null) <ide> protected function newHasManyThrough(Builder $query, Model $farParent, Model $th <ide> * <ide> * @param string $related <ide> * @param string $name <del> * @param string $type <del> * @param string $id <del> * @param string $localKey <add> * @param string|null $type <add> * @param string|null $id <add> * @param string|null $localKey <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphMany <ide> */ <ide> public function morphMany($related, $name, $type = null, $id = null, $localKey = null) <ide> protected function newMorphMany(Builder $query, Model $parent, $type, $id, $loca <ide> * Define a many-to-many relationship. <ide> * <ide> * @param string $related <del> * @param string $table <del> * @param string $foreignPivotKey <del> * @param string $relatedPivotKey <del> * @param string $parentKey <del> * @param string $relatedKey <del> * @param string $relation <add> * @param string|null $table <add> * @param string|null $foreignPivotKey <add> * @param string|null $relatedPivotKey <add> * @param string|null $parentKey <add> * @param string|null $relatedKey <add> * @param string|null $relation <ide> * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany <ide> */ <ide> public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, <ide> protected function newBelongsToMany(Builder $query, Model $parent, $table, $fore <ide> * <ide> * @param string $related <ide> * @param string $name <del> * @param string $table <del> * @param string $foreignPivotKey <del> * @param string $relatedPivotKey <del> * @param string $parentKey <del> * @param string $relatedKey <add> * @param string|null $table <add> * @param string|null $foreignPivotKey <add> * @param string|null $relatedPivotKey <add> * @param string|null $parentKey <add> * @param string|null $relatedKey <ide> * @param bool $inverse <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphToMany <ide> */ <ide> public function morphToMany($related, $name, $table = null, $foreignPivotKey = n <ide> * @param string $relatedPivotKey <ide> * @param string $parentKey <ide> * @param string $relatedKey <del> * @param string $relationName <add> * @param string|null $relationName <ide> * @param bool $inverse <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphToMany <ide> */ <ide> protected function newMorphToMany(Builder $query, Model $parent, $name, $table, <ide> * <ide> * @param string $related <ide> * @param string $name <del> * @param string $table <del> * @param string $foreignPivotKey <del> * @param string $relatedPivotKey <del> * @param string $parentKey <del> * @param string $relatedKey <add> * @param string|null $table <add> * @param string|null $foreignPivotKey <add> * @param string|null $relatedPivotKey <add> * @param string|null $parentKey <add> * @param string|null $relatedKey <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphToMany <ide> */ <ide> public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null, <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function as($accessor) <ide> * Set a where clause for a pivot table column. <ide> * <ide> * @param string $column <del> * @param string $operator <add> * @param string|null $operator <ide> * @param mixed $value <ide> * @param string $boolean <ide> * @return $this <ide> public function wherePivotIn($column, $values, $boolean = 'and', $not = false) <ide> * Set an "or where" clause for a pivot table column. <ide> * <ide> * @param string $column <del> * @param string $operator <add> * @param string|null $operator <ide> * @param mixed $value <ide> * @return $this <ide> */ <ide> protected function aliasedPivotColumns() <ide> /** <ide> * Get a paginator for the "select" statement. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int|null $page <ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', <ide> /** <ide> * Paginate the given query into a simple paginator. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int|null $page <ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php <ide> public function get($columns = ['*']) <ide> /** <ide> * Get a paginator for the "select" statement. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int $page <ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', <ide> /** <ide> * Paginate the given query into a simple paginator. <ide> * <del> * @param int $perPage <add> * @param int|null $perPage <ide> * @param array $columns <ide> * @param string $pageName <ide> * @param int|null $page <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> class MorphToMany extends BelongsToMany <ide> * @param string $relatedPivotKey <ide> * @param string $parentKey <ide> * @param string $relatedKey <del> * @param string $relationName <add> * @param string|null $relationName <ide> * @param bool $inverse <ide> * @return void <ide> */ <ide><path>src/Illuminate/Foundation/helpers.php <ide> function __($key = null, $replace = [], $locale = null) <ide> /** <ide> * Generate a url for the application. <ide> * <del> * @param string $path <add> * @param string|null $path <ide> * @param mixed $parameters <ide> * @param bool|null $secure <ide> * @return \Illuminate\Contracts\Routing\UrlGenerator|string <ide><path>src/Illuminate/Support/Facades/Cookie.php <ide> public static function has($key) <ide> /** <ide> * Retrieve a cookie from the request. <ide> * <del> * @param string $key <add> * @param string|null $key <ide> * @param mixed $default <ide> * @return string|array|null <ide> */ <ide><path>src/Illuminate/Support/MessageBag.php <ide> public function hasAny($keys = []) <ide> /** <ide> * Get the first message from the message bag for a given key. <ide> * <del> * @param string $key <del> * @param string $format <add> * @param string|null $key <add> * @param string|null $format <ide> * @return string <ide> */ <ide> public function first($key = null, $format = null) <ide><path>src/Illuminate/Support/ServiceProvider.php <ide> protected function addPublishGroup($group, $paths) <ide> /** <ide> * Get the paths to publish. <ide> * <del> * @param string $provider <del> * @param string $group <add> * @param string|null $provider <add> * @param string|null $group <ide> * @return array <ide> */ <ide> public static function pathsToPublish($provider = null, $group = null) <ide><path>src/Illuminate/Support/Str.php <ide> public static function kebab($value) <ide> * Return the length of the given string. <ide> * <ide> * @param string $value <del> * @param string $encoding <add> * @param string|null $encoding <ide> * @return int <ide> */ <ide> public static function length($value, $encoding = null) <ide><path>src/Illuminate/Support/Traits/EnumeratesValues.php <ide> protected function getArrayableItems($items) <ide> * Get an operator checker callback. <ide> * <ide> * @param string $key <del> * @param string $operator <add> * @param string|string $operator <ide> * @param mixed $value <ide> * @return \Closure <ide> */
14
PHP
PHP
remove deprecated code in serverrequest
3c98d7699ba54db8b398613812934d6bd0f00ae4
<ide><path>src/Http/ServerRequest.php <ide> */ <ide> namespace Cake\Http; <ide> <del>use ArrayAccess; <ide> use BadMethodCallException; <ide> use Cake\Core\Configure; <ide> use Cake\Http\Cookie\CookieCollection; <ide> * A class that helps wrap Request information and particulars about a single request. <ide> * Provides methods commonly used to introspect on the request headers and request body. <ide> */ <del>class ServerRequest implements ArrayAccess, ServerRequestInterface <add>class ServerRequest implements ServerRequestInterface <ide> { <ide> <ide> /** <ide> * Array of parameters parsed from the URL. <ide> * <ide> * @var array <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getParam() instead. <ide> */ <ide> protected $params = [ <ide> 'plugin' => null, <ide> class ServerRequest implements ArrayAccess, ServerRequestInterface <ide> * data. <ide> * <ide> * @var null|array|object <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getData() instead. <ide> */ <ide> protected $data = []; <ide> <ide> /** <ide> * Array of query string arguments <ide> * <ide> * @var array <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getQuery() or getQueryParams() instead. <ide> */ <ide> protected $query = []; <ide> <ide> /** <ide> * Array of cookie data. <ide> * <ide> * @var array <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getCookie() instead. <ide> */ <ide> protected $cookies = []; <ide> <ide> class ServerRequest implements ArrayAccess, ServerRequestInterface <ide> * The URL string used for the request. <ide> * <ide> * @var string <del> * @deprecated 3.6.0 This public property will be removed in 4.0.0. Use getRequestTarget() instead. <ide> */ <ide> protected $url; <ide> <ide> /** <ide> * Base URL path. <ide> * <ide> * @var string <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead. <ide> */ <ide> protected $base; <ide> <ide> /** <ide> * webroot path segment for the request. <ide> * <ide> * @var string <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead. <ide> */ <ide> protected $webroot = '/'; <ide> <ide> /** <ide> * The full address to the current request <ide> * <ide> * @var string <del> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('here') or getUri()->getPath() instead. <ide> */ <ide> protected $here; <ide> <ide> class ServerRequest implements ArrayAccess, ServerRequestInterface <ide> */ <ide> protected $requestTarget; <ide> <del> /** <del> * List of deprecated properties that have backwards <del> * compatibility offered through magic methods. <del> * <del> * @var array <del> */ <del> private $deprecatedProperties = [ <del> 'data' => ['get' => 'getData()', 'set' => 'withData()'], <del> 'query' => ['get' => 'getQuery()', 'set' => 'withQueryParams()'], <del> 'params' => ['get' => 'getParam()', 'set' => 'withParam()'], <del> 'cookies' => ['get' => 'getCookie()', 'set' => 'withCookieParams()'], <del> 'url' => ['get' => 'getPath()', 'set' => 'withRequestTarget()'], <del> 'base' => ['get' => 'getAttribute("base")', 'set' => 'withAttribute("base")'], <del> 'webroot' => ['get' => 'getAttribute("webroot")', 'set' => 'withAttribute("webroot")'], <del> 'here' => ['get' => 'getAttribute("here")', 'set' => 'withAttribute("here")'], <del> ]; <del> <del> /** <del> * Wrapper method to create a new request from PHP superglobals. <del> * <del> * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct <del> * the request. <del> * <del> * @return self <del> * @deprecated 3.4.0 Use `Cake\Http\ServerRequestFactory` instead. <del> */ <del> public static function createFromGlobals() <del> { <del> deprecationWarning( <del> 'ServerRequest::createFromGlobals() is deprecated. ' . <del> 'Use `Cake\Http\ServerRequestFactory` instead.' <del> ); <del> <del> return ServerRequestFactory::fromGlobals(); <del> } <del> <ide> /** <ide> * Create a new request object. <ide> * <ide> public static function createFromGlobals() <ide> * - `files` Uploaded file data formatted like $_FILES. <ide> * - `cookies` Cookies for this request. <ide> * - `environment` $_SERVER and $_ENV data. <del> * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0 <del> * - `uri` The PSR7 UriInterface object. If null, one will be created. <add> * - `url` The URL without the base path for the request. <add> * - `uri` The PSR7 UriInterface object. If null, one will be created from `url` or `environment`. <ide> * - `base` The base URL for the request. <ide> * - `webroot` The webroot directory for the request. <ide> * - `input` The data that would come from php://input this is useful for simulating <ide> public static function createFromGlobals() <ide> public function __construct($config = []) <ide> { <ide> if (is_string($config)) { <del> $config = ['url' => $config]; <add> trigger_error('ServerRequest no longer accepts a string as its argument.', E_USER_WARNING); <ide> } <ide> $config += [ <ide> 'params' => $this->params, <ide> public function getSession() <ide> return $this->session; <ide> } <ide> <del> /** <del> * Returns the instance of the Session object for this request <del> * <del> * If a session object is passed as first argument it will be set as <del> * the session to use for this request <del> * <del> * @deprecated 3.5.0 Use getSession() instead. The setter part will be removed. <del> * @param \Cake\Http\Session|null $session the session object to use <del> * @return \Cake\Http\Session <del> */ <del> public function session(Session $session = null) <del> { <del> deprecationWarning( <del> 'ServerRequest::session() is deprecated. ' . <del> 'Use getSession() instead. The setter part will be removed.' <del> ); <del> <del> if ($session === null) { <del> return $this->session; <del> } <del> <del> return $this->session = $session; <del> } <del> <ide> /** <ide> * Get the IP the client is using, or says they are using. <ide> * <ide> public function __call($name, $params) <ide> throw new BadMethodCallException(sprintf('Method %s does not exist', $name)); <ide> } <ide> <del> /** <del> * Magic set method allows backward compatibility for former public properties <del> * <del> * <del> * @param string $name The property being accessed. <del> * @param mixed $value The property value. <del> * @return mixed Either the value of the parameter or null. <del> * @deprecated 3.6.0 Public properties will be removed in 4.0.0. <del> * Use appropriate setters instead. <del> */ <del> public function __set($name, $value) <del> { <del> if (isset($this->deprecatedProperties[$name])) { <del> $method = $this->deprecatedProperties[$name]['set']; <del> deprecationWarning( <del> "Setting {$name} as a property will be removed in 4.0.0. " . <del> "Use {$method} instead." <del> ); <del> <del> return $this->{$name} = $value; <del> } <del> throw new BadMethodCallException("Cannot set {$name} it is not a known property."); <del> } <del> <del> /** <del> * Magic get method allows access to parsed routing parameters directly on the object. <del> * <del> * Allows access to `$this->params['controller']` via `$this->controller` <del> * <del> * @param string $name The property being accessed. <del> * @return mixed Either the value of the parameter or null. <del> * @deprecated 3.4.0 Accessing routing parameters through __get will removed in 4.0.0. <del> * Use getParam() instead. <del> */ <del> public function &__get($name) <del> { <del> if (isset($this->deprecatedProperties[$name])) { <del> $method = $this->deprecatedProperties[$name]['get']; <del> deprecationWarning( <del> "Accessing `{$name}` as a property will be removed in 4.0.0. " . <del> "Use request->{$method} instead." <del> ); <del> <del> return $this->{$name}; <del> } <del> <del> deprecationWarning(sprintf( <del> 'Accessing routing parameters through `%s` will removed in 4.0.0. ' . <del> 'Use `getParam()` instead.', <del> $name <del> )); <del> <del> if (isset($this->params[$name])) { <del> return $this->params[$name]; <del> } <del> $value = null; <del> <del> return $value; <del> } <del> <del> /** <del> * Magic isset method allows isset/empty checks <del> * on routing parameters. <del> * <del> * @param string $name The property being accessed. <del> * @return bool Existence <del> * @deprecated 3.4.0 Accessing routing parameters through __isset will removed in 4.0.0. <del> * Use getParam() instead. <del> */ <del> public function __isset($name) <del> { <del> if (isset($this->deprecatedProperties[$name])) { <del> $method = $this->deprecatedProperties[$name]['get']; <del> deprecationWarning( <del> "Accessing {$name} as a property will be removed in 4.0.0. " . <del> "Use {$method} instead." <del> ); <del> <del> return isset($this->{$name}); <del> } <del> <del> deprecationWarning( <del> 'Accessing routing parameters through __isset will removed in 4.0.0. ' . <del> 'Use getParam() instead.' <del> ); <del> <del> return isset($this->params[$name]); <del> } <del> <ide> /** <ide> * Check whether or not a Request is a certain type. <ide> * <ide> public static function addDetector($name, $callable) <ide> static::$_detectors[$name] = $callable; <ide> } <ide> <del> /** <del> * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters. <del> * This modifies the parameters available through `$request->getParam()`. <del> * <del> * @param array $params Array of parameters to merge in <del> * @return $this The current object, you can chain this method. <del> * @deprecated 3.6.0 ServerRequest::addParams() is deprecated. Use `withParam()` or <del> * `withAttribute('params')` instead. <del> */ <del> public function addParams(array $params) <del> { <del> deprecationWarning( <del> 'ServerRequest::addParams() is deprecated. ' . <del> 'Use `withParam()` or `withAttribute("params", $params)` instead.' <del> ); <del> $this->params = array_merge($this->params, $params); <del> <del> return $this; <del> } <del> <del> /** <del> * Add paths to the requests' paths vars. This will overwrite any existing paths. <del> * Provides an easy way to modify, here, webroot and base. <del> * <del> * @param array $paths Array of paths to merge in <del> * @return $this The current object, you can chain this method. <del> * @deprecated 3.6.0 Mutating a request in place is deprecated. Use `withAttribute()` to modify paths instead. <del> */ <del> public function addPaths(array $paths) <del> { <del> deprecationWarning( <del> 'ServerRequest::addPaths() is deprecated. ' . <del> 'Use `withAttribute($key, $value)` instead.' <del> ); <del> foreach (['webroot', 'here', 'base'] as $element) { <del> if (isset($paths[$element])) { <del> $this->{$element} = $paths[$element]; <del> } <del> } <del> <del> return $this; <del> } <del> <del> /** <del> * Get the value of the current requests URL. Will include the query string arguments. <del> * <del> * @param bool $base Include the base path, set to false to trim the base path off. <del> * @return string The current request URL including query string args. <del> * @deprecated 3.4.0 This method will be removed in 4.0.0. You should use getRequestTarget() instead. <del> */ <del> public function here($base = true) <del> { <del> deprecationWarning( <del> 'ServerRequest::here() will be removed in 4.0.0. You should use getRequestTarget() instead.' <del> ); <del> <del> $url = $this->here; <del> if (!empty($this->query)) { <del> $url .= '?' . http_build_query($this->query, null, '&'); <del> } <del> if (!$base) { <del> $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1); <del> } <del> <del> return $url; <del> } <del> <ide> /** <ide> * Normalize a header name into the SERVER version. <ide> * <ide> protected function normalizeHeaderName($name) <ide> return $name; <ide> } <ide> <del> /** <del> * Read an HTTP header from the Request information. <del> * <del> * If the header is not defined in the request, this method <del> * will fallback to reading data from $_SERVER and $_ENV. <del> * This fallback behavior is deprecated, and will be removed in 4.0.0 <del> * <del> * @param string $name Name of the header you want. <del> * @return string|null Either null on no header being set or the value of the header. <del> * @deprecated 4.0.0 The automatic fallback to env() will be removed in 4.0.0, see getHeader() <del> */ <del> public function header($name) <del> { <del> deprecationWarning( <del> 'ServerRequest::header() is deprecated. ' . <del> 'The automatic fallback to env() will be removed in 4.0.0, see getHeader()' <del> ); <del> <del> $name = $this->normalizeHeaderName($name); <del> <del> return $this->getEnv($name); <del> } <del> <ide> /** <ide> * Get all headers in the request. <ide> * <ide> public function withoutHeader($name) <ide> return $new; <ide> } <ide> <del> /** <del> * Get the HTTP method used for this request. <del> * <del> * @return string The name of the HTTP method used. <del> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use getMethod() instead. <del> */ <del> public function method() <del> { <del> deprecationWarning( <del> 'ServerRequest::method() is deprecated. ' . <del> 'This method will be removed in 4.0.0. Use getMethod() instead.' <del> ); <del> <del> return $this->getEnv('REQUEST_METHOD'); <del> } <del> <ide> /** <ide> * Get the HTTP method used for this request. <ide> * There are a few ways to specify a method. <ide> protected function _parseAcceptWithQualifier($header) <ide> return $accept; <ide> } <ide> <del> /** <del> * Provides a read accessor for `$this->query`. <del> * Allows you to use a `Hash::get()` compatible syntax for reading post data. <del> * <del> * @param string|null $name Query string variable name or null to read all. <del> * @return string|array|null The value being read <del> * @deprecated 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead. <del> */ <del> public function query($name = null) <del> { <del> deprecationWarning( <del> 'ServerRequest::query() is deprecated. ' . <del> 'Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.' <del> ); <del> <del> if ($name === null) { <del> return $this->query; <del> } <del> <del> return $this->getQuery($name); <del> } <del> <ide> /** <ide> * Read a specific query value or dotted path. <ide> * <ide> public function getQuery($name = null, $default = null) <ide> return Hash::get($this->query, $name, $default); <ide> } <ide> <del> /** <del> * Provides a read/write accessor for `$this->data`. <del> * Allows you to use a `Hash::get()` compatible syntax for reading post data. <del> * <del> * ### Reading values. <del> * <del> * ``` <del> * $request->data('Post.title'); <del> * ``` <del> * <del> * When reading values you will get `null` for keys/values that do not exist. <del> * <del> * ### Writing values <del> * <del> * ``` <del> * $request->data('Post.title', 'New post!'); <del> * ``` <del> * <del> * You can write to any value, even paths/keys that do not exist, and the arrays <del> * will be created for you. <del> * <del> * @param string|null $name Dot separated name of the value to read/write <del> * @param mixed ...$args The data to set (deprecated) <del> * @return mixed|$this Either the value being read, or this so you can chain consecutive writes. <del> * @deprecated 3.4.0 Use withData() and getData() or getParsedBody() instead. <del> */ <del> public function data($name = null, ...$args) <del> { <del> deprecationWarning( <del> 'ServerRequest::data() is deprecated. ' . <del> 'Use withData() and getData() or getParsedBody() instead.' <del> ); <del> <del> if (count($args) === 1) { <del> $this->data = Hash::insert($this->data, $name, $args[0]); <del> <del> return $this; <del> } <del> if ($name !== null) { <del> return Hash::get($this->data, $name); <del> } <del> <del> return $this->data; <del> } <del> <ide> /** <ide> * Provides a safe accessor for request data. Allows <ide> * you to use Hash::get() compatible paths. <ide> public function getData($name = null, $default = null) <ide> return Hash::get($this->data, $name, $default); <ide> } <ide> <del> /** <del> * Safely access the values in $this->params. <del> * <del> * @param string $name The name of the parameter to get. <del> * @param mixed ...$args Value to set (deprecated). <del> * @return mixed|$this The value of the provided parameter. Will <del> * return false if the parameter doesn't exist or is falsey. <del> * @deprecated 3.4.0 Use getParam() and withParam() instead. <del> */ <del> public function param($name, ...$args) <del> { <del> deprecationWarning( <del> 'ServerRequest::param() is deprecated. ' . <del> 'Use getParam() and withParam() instead.' <del> ); <del> <del> if (count($args) === 1) { <del> $this->params = Hash::insert($this->params, $name, $args[0]); <del> <del> return $this; <del> } <del> <del> return $this->getParam($name); <del> } <del> <ide> /** <ide> * Read data from `php://input`. Useful when interacting with XML or JSON <ide> * request body content. <ide> public function input($callback = null, ...$args) <ide> return $input; <ide> } <ide> <del> /** <del> * Read cookie data from the request's cookie data. <del> * <del> * @param string $key The key you want to read. <del> * @return null|string Either the cookie value, or null if the value doesn't exist. <del> * @deprecated 3.4.0 Use getCookie() instead. <del> */ <del> public function cookie($key) <del> { <del> deprecationWarning( <del> 'ServerRequest::cookie() is deprecated. ' . <del> 'Use getCookie() instead.' <del> ); <del> <del> if (isset($this->cookies[$key])) { <del> return $this->cookies[$key]; <del> } <del> <del> return null; <del> } <del> <ide> /** <ide> * Read cookie data from the request's cookie data. <ide> * <ide> public function withEnv($key, $value) <ide> return $new; <ide> } <ide> <del> /** <del> * Get/Set value from the request's environment data. <del> * Fallback to using env() if key not set in $environment property. <del> * <del> * @deprecated 3.5.0 Use getEnv()/withEnv() instead. <del> * @param string $key The key you want to read/write from/to. <del> * @param string|null $value Value to set. Default null. <del> * @param string|null $default Default value when trying to retrieve an environment <del> * variable's value that does not exist. The value parameter must be null. <del> * @return $this|string|null This instance if used as setter, <del> * if used as getter either the environment value, or null if the value doesn't exist. <del> */ <del> public function env($key, $value = null, $default = null) <del> { <del> deprecationWarning( <del> 'ServerRequest::env() is deprecated. ' . <del> 'Use getEnv()/withEnv() instead.' <del> ); <del> <del> if ($value !== null) { <del> $this->_environment[$key] = $value; <del> $this->clearDetectorCache(); <del> <del> return $this; <del> } <del> <del> $key = strtoupper($key); <del> if (!array_key_exists($key, $this->_environment)) { <del> $this->_environment[$key] = env($key); <del> } <del> <del> return $this->_environment[$key] !== null ? $this->_environment[$key] : $default; <del> } <del> <ide> /** <ide> * Allow only certain HTTP request methods, if the request method does not match <ide> * a 405 error will be shown and the required "Allow" response header will be set. <ide> protected function _readInput() <ide> return $this->_input; <ide> } <ide> <del> /** <del> * Modify data originally from `php://input`. Useful for altering json/xml data <del> * in middleware or DispatcherFilters before it gets to RequestHandlerComponent <del> * <del> * @param string $input A string to replace original parsed data from input() <del> * @return void <del> * @deprecated 3.4.0 This method will be removed in 4.0.0. Use withBody() instead. <del> */ <del> public function setInput($input) <del> { <del> deprecationWarning( <del> 'This method will be removed in 4.0.0.' . <del> 'Use withBody() instead.' <del> ); <del> <del> $stream = new Stream('php://memory', 'rw'); <del> $stream->write($input); <del> $stream->rewind(); <del> $this->stream = $stream; <del> } <del> <ide> /** <ide> * Update the request with a new request data element. <ide> * <ide> public function getPath() <ide> <ide> return $path; <ide> } <del> <del> /** <del> * Array access read implementation <del> * <del> * @param string $name Name of the key being accessed. <del> * @return mixed <del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam(), getData() and getQuery() instead. <del> */ <del> public function offsetGet($name) <del> { <del> deprecationWarning( <del> 'The ArrayAccess methods will be removed in 4.0.0.' . <del> 'Use getParam(), getData() and getQuery() instead.' <del> ); <del> <del> if (isset($this->params[$name])) { <del> return $this->params[$name]; <del> } <del> if ($name === 'url') { <del> return $this->query; <del> } <del> if ($name === 'data') { <del> return $this->data; <del> } <del> <del> return null; <del> } <del> <del> /** <del> * Array access write implementation <del> * <del> * @param string $name Name of the key being written <del> * @param mixed $value The value being written. <del> * @return void <del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead. <del> */ <del> public function offsetSet($name, $value) <del> { <del> deprecationWarning( <del> 'The ArrayAccess methods will be removed in 4.0.0.' . <del> 'Use withParam() instead.' <del> ); <del> <del> $this->params[$name] = $value; <del> } <del> <del> /** <del> * Array access isset() implementation <del> * <del> * @param string $name thing to check. <del> * @return bool <del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam() instead. <del> */ <del> public function offsetExists($name) <del> { <del> deprecationWarning( <del> 'The ArrayAccess methods will be removed in 4.0.0.' . <del> 'Use getParam() instead.' <del> ); <del> <del> if ($name === 'url' || $name === 'data') { <del> return true; <del> } <del> <del> return isset($this->params[$name]); <del> } <del> <del> /** <del> * Array access unset() implementation <del> * <del> * @param string $name Name to unset. <del> * @return void <del> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead. <del> */ <del> public function offsetUnset($name) <del> { <del> deprecationWarning( <del> 'The ArrayAccess methods will be removed in 4.0.0.' . <del> 'Use withParam() instead.' <del> ); <del> <del> unset($this->params[$name]); <del> } <ide> } <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php <ide> public function testConstructor() <ide> */ <ide> public function testAuthenticateNoData() <ide> { <del> $request = new ServerRequest('posts/index'); <add> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> $this->response->expects($this->never()) <ide> ->method('withHeader'); <ide> public function testAuthenticateUsernameZero() <ide> */ <ide> public function testAuthenticateChallenge() <ide> { <del> $request = new ServerRequest('posts/index'); <add> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> try { <ide> $this->auth->unauthenticated($request, $this->response); <ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php <ide> public function testControllerErrorOnMissingMethod() <ide> public function testAuthorizeFailure() <ide> { <ide> $user = []; <del> $request = new ServerRequest('/posts/index'); <add> $request = new ServerRequest(['url' => '/posts/index']); <ide> $this->assertFalse($this->auth->authorize($user, $request)); <ide> } <ide> <ide> public function testAuthorizeFailure() <ide> public function testAuthorizeSuccess() <ide> { <ide> $user = ['User' => ['username' => 'mark']]; <del> $request = new ServerRequest('/posts/index'); <add> $request = new ServerRequest(['url' => '/posts/index']); <ide> <ide> $this->controller->expects($this->once()) <ide> ->method('isAuthorized') <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> public function testConstructor() <ide> */ <ide> public function testAuthenticateNoData() <ide> { <del> $request = new ServerRequest('posts/index'); <add> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> $this->response->expects($this->never()) <ide> ->method('withHeader'); <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testAuthenticateNoPassword() <ide> */ <ide> public function testAuthenticatePasswordIsFalse() <ide> { <del> $request = new ServerRequest('posts/index', false); <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <ide> 'post' => [ <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function setUp() <ide> */ <ide> protected function _init() <ide> { <del> $request = new ServerRequest('controller_posts/index'); <add> $request = new ServerRequest(['url' => 'controller_posts/index']); <ide> $response = $this->getMockBuilder('Cake\Http\Response') <ide> ->setMethods(['_sendHeader', 'stop']) <ide> ->getMock(); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function tearDown() <ide> */ <ide> public function testTableAutoload() <ide> { <del> $request = new ServerRequest('controller_posts/index'); <add> $request = new ServerRequest(['url' => 'controller/posts/index']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new Controller($request, $response); <ide> $Controller->modelClass = 'SiteArticles'; <ide> public function testTableAutoload() <ide> */ <ide> public function testLoadModel() <ide> { <del> $request = new ServerRequest('controller_posts/index'); <add> $request = new ServerRequest(['url' => 'controller/posts/index']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new Controller($request, $response); <ide> <ide> public function testRefererSlash() <ide> */ <ide> public function testSetAction() <ide> { <del> $request = new ServerRequest('controller_posts/index'); <add> $request = new ServerRequest(['url' => 'controller/posts/index']); <ide> <ide> $TestController = new TestController($request); <ide> $TestController->setAction('view', 1, 2); <ide> public function testViewPathConventions() <ide> */ <ide> public function testComponents() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $controller = new TestController($request, $response); <ide> public function testHelpersPropertyError() <ide> */ <ide> public function testComponentsWithCustomRegistry() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry') <ide> ->setMethods(['offsetGet']) <ide> public function testComponentsWithCustomRegistry() <ide> */ <ide> public function testLoadComponent() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $controller = new TestController($request, $response); <ide> public function testLoadComponent() <ide> */ <ide> public function testLoadComponentDuplicate() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $controller = new TestController($request, $response); <ide> public function testLoadComponentDuplicate() <ide> */ <ide> public function testIsAction() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $controller = new TestController($request, $response); <ide> <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testError400() <ide> { <ide> Router::reload(); <ide> <del> $request = new ServerRequest('posts/view/1000'); <add> $request = new ServerRequest(['url' => 'posts/view/1000']); <ide> Router::setRequestInfo($request); <ide> <ide> $exception = new NotFoundException('Custom message'); <ide> public function testError400AsJson() <ide> { <ide> Router::reload(); <ide> <del> $request = new ServerRequest('posts/view/1000?sort=title&direction=desc'); <add> $request = new ServerRequest(['url' => 'posts/view/1000?sort=title&direction=desc']); <ide> $request = $request->withHeader('Accept', 'application/json'); <ide> $request = $request->withHeader('Content-Type', 'application/json'); <ide> Router::setRequestInfo($request); <ide> public function testError400NoInjection() <ide> { <ide> Router::reload(); <ide> <del> $request = new ServerRequest('pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>'); <add> $request = new ServerRequest(['url' => 'pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>']); <ide> Router::setRequestInfo($request); <ide> <ide> $exception = new NotFoundException('Custom message'); <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testGetPath() <ide> $this->assertEquals('/foo/bar', $request->getPath()); <ide> } <ide> <del> /** <del> * Test addParams() method <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testAddParams() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> $request = $request <del> ->withParam('controller', 'posts') <del> ->withParam('action', 'view'); <del> $result = $request->addParams(['plugin' => null, 'action' => 'index']); <del> <del> $this->assertSame($result, $request, 'Method did not return itself. %s'); <del> <del> $this->assertEquals('posts', $request->getParam('controller')); <del> $this->assertEquals('index', $request->getParam('action')); <del> $this->assertEquals(null, $request->getParam('plugin')); <del> }); <del> } <del> <del> /** <del> * Test splicing in paths. <del> * <del> * @return void <del> */ <del> public function testAddPaths() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> $request->webroot = '/some/path/going/here/'; <del> $result = $request->addPaths([ <del> 'random' => '/something', 'webroot' => '/', 'here' => '/', 'base' => '/base_dir' <del> ]); <del> <del> $this->assertSame($result, $request, 'Method did not return itself. %s'); <del> <del> $this->assertEquals('/', $request->webroot); <del> $this->assertEquals('/base_dir', $request->base); <del> $this->assertEquals('/', $request->here); <del> $this->assertFalse(isset($request->random)); <del> }); <del> } <del> <ide> /** <ide> * Test parsing POST data into the object. <ide> * <ide> public function testMethodOverrides() <ide> $this->assertEquals('POST', $request->getEnv('ORIGINAL_REQUEST_METHOD')); <ide> } <ide> <del> /** <del> * Tests the env() method returning a default value in case the requested environment variable is not set. <del> */ <del> public function testDefaultEnvValue() <del> { <del> $this->deprecated(function () { <del> $_ENV['DOES_NOT_EXIST'] = null; <del> $request = new ServerRequest(); <del> $this->assertNull($request->getEnv('DOES_NOT_EXIST')); <del> $this->assertEquals('default', $request->env('DOES_NOT_EXIST', null, 'default')); <del> <del> $_ENV['DOES_EXIST'] = 'some value'; <del> $request = new ServerRequest(); <del> $this->assertEquals('some value', $request->env('DOES_EXIST')); <del> $this->assertEquals('some value', $request->env('DOES_EXIST', null, 'default')); <del> <del> $_ENV['EMPTY_VALUE'] = ''; <del> $request = new ServerRequest(); <del> $this->assertEquals('', $request->env('EMPTY_VALUE')); <del> $this->assertEquals('', $request->env('EMPTY_VALUE', null, 'default')); <del> <del> $_ENV['ZERO'] = '0'; <del> $request = new ServerRequest(); <del> $this->assertEquals('0', $request->env('ZERO')); <del> $this->assertEquals('0', $request->env('ZERO', null, 'default')); <del> }); <del> } <del> <ide> /** <ide> * Test the clientIp method. <ide> * <ide> public function testIsAll() <ide> $this->assertFalse($request->isAll(['ajax', 'post'])); <ide> } <ide> <del> /** <del> * Test the method() method. <del> * <del> * @return void <del> * @deprecated <del> */ <del> public function testMethod() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(['environment' => ['REQUEST_METHOD' => 'delete']]); <del> <del> $this->assertEquals('delete', $request->method()); <del> }); <del> } <del> <ide> /** <ide> * Test getMethod() <ide> * <ide> public function testIsSsl() <ide> $this->assertFalse($request->is('ssl')); <ide> } <ide> <del> /** <del> * Test getting request params with object properties. <del> * <del> * @return void <del> */ <del> public function testMagicget() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <del> <del> $this->assertEquals('posts', $request->controller); <del> $this->assertEquals('view', $request->action); <del> $this->assertEquals('blogs', $request->plugin); <del> $this->assertNull($request->banana); <del> }); <del> } <del> <del> /** <del> * Test isset()/empty() with overloaded properties. <del> * <del> * @return void <del> */ <del> public function testMagicisset() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> $request->params = [ <del> 'controller' => 'posts', <del> 'action' => 'view', <del> 'plugin' => 'blogs', <del> ]; <del> <del> $this->assertTrue(isset($request->controller)); <del> $this->assertFalse(isset($request->notthere)); <del> $this->assertNotEmpty($request->controller); <del> }); <del> } <del> <del> /** <del> * Test the array access implementation <del> * <del> * @return void <del> */ <del> public function testArrayAccess() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <del> <del> $this->assertEquals('posts', $request['controller']); <del> <del> $request['slug'] = 'speedy-slug'; <del> $this->assertEquals('speedy-slug', $request->slug); <del> $this->assertEquals('speedy-slug', $request['slug']); <del> <del> $this->assertArrayHasKey('action', $request); <del> $this->assertArrayNotHasKey('wrong-param', $request); <del> <del> $this->assertArrayHasKey('plugin', $request); <del> unset($request['plugin']); <del> $this->assertArrayNotHasKey('plugin', $request); <del> $this->assertNull($request['plugin']); <del> $this->assertNull($request->plugin); <del> <del> $request = new ServerRequest(['url' => 'some/path?one=something&two=else']); <del> $this->assertTrue(isset($request['url']['one'])); <del> <del> $request->data = ['Post' => ['title' => 'something']]; <del> $this->assertEquals('something', $request['data']['Post']['title']); <del> }); <del> } <del> <ide> /** <ide> * Test adding detectors and having them work. <ide> * <ide> public function testWithHeader() <ide> <ide> $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged'); <ide> $this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct'); <del> $this->deprecated(function () use ($new) { <del> $this->assertEquals(999, $new->header('Content-Length')); <del> }); <ide> <ide> $new = $request->withHeader('Double', ['a']); <ide> $this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten'); <del> <del> $this->deprecated(function () use ($new) { <del> $this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.'); <del> }); <ide> } <ide> <ide> /** <ide> public function testWithAddedHeader() <ide> $this->assertEquals('a, b', $request->getHeaderLine('Double'), 'old request is unchanged'); <ide> $this->assertEquals('a, b, c', $new->getHeaderLine('Double'), 'new request is correct'); <ide> <del> $this->deprecated(function () use ($new) { <del> $this->assertEquals(['a', 'b', 'c'], $new->header('Double')); <del> }); <del> <ide> $new = $request->withAddedHeader('Content-Length', 777); <ide> $this->assertEquals([1337, 777], $new->getHeader('Content-Length'), 'scalar values are appended'); <ide> <ide> public function testWithoutHeader() <ide> <ide> $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged'); <ide> $this->assertEquals('', $new->getHeaderLine('Content-length'), 'new request is correct'); <del> <del> $this->deprecated(function () use ($new) { <del> $this->assertNull($new->header('Content-Length')); <del> }); <ide> } <ide> <ide> /** <ide> public function testEnvironmentDetection($name, $env, $expected) <ide> if (isset($expected['urlParams'])) { <ide> $this->assertEquals($expected['urlParams'], $request->getQueryParams(), 'GET param mismatch'); <ide> } <del> <del> $this->deprecated(function () use ($request, $expected) { <del> $this->assertEquals($expected['url'], $request->url, 'URL is incorrect'); <del> $this->assertEquals($expected['base'], $request->base, 'base is incorrect'); <del> $this->assertEquals($expected['webroot'], $request->webroot, 'webroot error'); <del> }); <del> } <del> <del> /** <del> * Test the query() method <del> * <del> * @return void <del> */ <del> public function testQuery() <del> { <del> $this->deprecated(function () { <del> $array = [ <del> 'query' => ['foo' => 'bar', 'zero' => '0'] <del> ]; <del> $request = new ServerRequest($array); <del> <del> $this->assertSame('bar', $request->query('foo')); <del> $this->assertSame('0', $request->query('zero')); <del> $this->assertNull($request->query('imaginary')); <del> $this->assertSame($array['query'], $request->query()); <del> }); <ide> } <ide> <ide> /** <ide> public function testReadingParams() <ide> $this->assertSame('0', $request->getParam('zero')); <ide> } <ide> <del> /** <del> * Test using param() <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testReadingParamsOld() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest([ <del> 'params' => [ <del> 'controller' => 'posts', <del> 'admin' => true, <del> 'truthy' => 1, <del> 'zero' => '0', <del> ] <del> ]); <del> $this->assertNull($request->param('not_set')); <del> $this->assertTrue($request->param('admin')); <del> $this->assertSame(1, $request->param('truthy')); <del> $this->assertSame('posts', $request->param('controller')); <del> $this->assertSame('0', $request->param('zero')); <del> }); <del> } <del> <ide> /** <ide> * Test the data() method reading <ide> * <ide> public function testGetData() <ide> ] <ide> ]; <ide> $request = new ServerRequest(compact('post')); <del> $this->deprecated(function () use ($post, $request) { <del> $this->assertEquals($post['Model'], $request->data('Model')); <del> }); <ide> $this->assertEquals($post['Model'], $request->getData('Model')); <ide> <del> $this->deprecated(function () use ($post, $request) { <del> $this->assertEquals($post, $request->data()); <del> }); <ide> $this->assertEquals($post, $request->getData()); <del> <del> $this->deprecated(function () use ($request) { <del> $this->assertNull($request->data('Model.imaginary')); <del> }); <ide> $this->assertNull($request->getData('Model.imaginary')); <ide> <ide> $this->assertSame('value', $request->getData('Model.field', 'default')); <ide> public function testGetDataOnStringData() <ide> $this->assertNull($request->getData('Model.field')); <ide> } <ide> <del> /** <del> * Test writing with data() <del> * <del> * @return void <del> */ <del> public function testDataWriting() <del> { <del> $this->deprecated(function () { <del> $_POST['data'] = [ <del> 'Model' => [ <del> 'field' => 'value' <del> ] <del> ]; <del> $request = new ServerRequest(); <del> $result = $request->data('Model.new_value', 'new value'); <del> $this->assertSame($result, $request, 'Return was not $this'); <del> <del> $this->assertEquals('new value', $request->data['Model']['new_value']); <del> <del> $request->data('Post.title', 'New post')->data('Comment.1.author', 'Mark'); <del> $this->assertEquals('New post', $request->data['Post']['title']); <del> $this->assertEquals('Mark', $request->data['Comment']['1']['author']); <del> }); <del> } <del> <ide> /** <ide> * Test writing falsey values. <ide> * <ide> public function testDataWritingFalsey() <ide> /** <ide> * Test reading params <ide> * <del> * @group deprecated <ide> * @dataProvider paramReadingDataProvider <ide> */ <ide> public function testGetParam($toRead, $expected) <ide> public function paramReadingDataProvider() <ide> */ <ide> public function testParamWriting() <ide> { <del> $request = new ServerRequest('/'); <add> $request = new ServerRequest(['url' => '/']); <ide> $request = $request->withParam('action', 'index'); <ide> <ide> $this->assertInstanceOf( <ide> public function testAcceptLanguage() <ide> $this->assertFalse($result); <ide> } <ide> <del> /** <del> * Test the here() method <del> * <del> * @return void <del> */ <del> public function testHere() <del> { <del> $this->deprecated(function () { <del> Configure::write('App.base', '/base_path'); <del> $q = ['test' => 'value']; <del> $request = new ServerRequest([ <del> 'query' => $q, <del> 'url' => '/posts/add/1/value', <del> 'base' => '/base_path' <del> ]); <del> <del> $result = $request->here(); <del> $this->assertEquals('/base_path/posts/add/1/value?test=value', $result); <del> <del> $result = $request->here(false); <del> $this->assertEquals('/posts/add/1/value?test=value', $result); <del> <del> $request = new ServerRequest([ <del> 'url' => '/posts/base_path/1/value', <del> 'query' => ['test' => 'value'], <del> 'base' => '/base_path' <del> ]); <del> $result = $request->here(); <del> $this->assertEquals('/base_path/posts/base_path/1/value?test=value', $result); <del> <del> $result = $request->here(false); <del> $this->assertEquals('/posts/base_path/1/value?test=value', $result); <del> }); <del> } <del> <del> /** <del> * Test the here() with space in URL <del> * <del> * @return void <del> */ <del> public function testHereWithSpaceInUrl() <del> { <del> $this->deprecated(function () { <del> Configure::write('App.base', ''); <del> $_GET = ['/admin/settings/settings/prefix/Access_Control' => '']; <del> $request = new ServerRequest('/admin/settings/settings/prefix/Access%20Control'); <del> <del> $result = $request->here(); <del> $this->assertEquals('/admin/settings/settings/prefix/Access%20Control', $result); <del> }); <del> } <del> <del> /** <del> * Test the input() method. <del> * <del> * @return void <del> */ <del> public function testSetInput() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(); <del> <del> $request->setInput('I came from setInput'); <del> $result = $request->input(); <del> $this->assertEquals('I came from setInput', $result); <del> }); <del> } <del> <ide> /** <ide> * Test the input() method. <ide> * <ide> public function testGetUri() <ide> $this->assertEquals('/articles/view/3', $result->getPath()); <ide> } <ide> <del> /** <del> * test url property <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testUrlProperty() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest(['url' => 'articles/view/3']); <del> $this->assertEquals('articles/view/3', $request->url); <del> }); <del> } <del> <ide> /** <ide> * Test withUri <ide> * <ide> public function testWithUri() <ide> $this->assertSame($uri, $new->getUri()); <ide> } <ide> <del> /** <del> * Test withUri <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testWithUriCompatibility() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest([ <del> 'environment' => [ <del> 'HTTP_HOST' => 'example.com', <del> ], <del> 'url' => 'articles/view/3' <del> ]); <del> $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock(); <del> $new = $request->withUri($uri); <del> $this->assertNotSame($new, $request); <del> $this->assertNotSame($uri, $request->getUri()); <del> $this->assertSame($uri, $new->getUri()); <del> $this->assertSame('articles/view/3', $new->url); <del> $this->assertSame('articles/view/3', $request->url); <del> $this->assertSame('example.com', $new->getHeaderLine('Host')); <del> }); <del> } <del> <ide> /** <ide> * Test withUri() and preserveHost <ide> * <ide> public function testGetCookie() <ide> ] <ide> ] <ide> ]); <del> <del> $this->deprecated(function () use ($request) { <del> $this->assertEquals('A value in the cookie', $request->cookie('testing')); <del> }); <ide> $this->assertEquals('A value in the cookie', $request->getCookie('testing')); <del> <del> $this->deprecated(function () use ($request) { <del> $this->assertNull($request->cookie('not there')); <del> }); <del> <ide> $this->assertNull($request->getCookie('not there')); <ide> $this->assertSame('default', $request->getCookie('not there', 'default')); <ide> <ide> public function testAllowMethodException() <ide> $request->allowMethod('POST'); <ide> } <ide> <del> /** <del> * Tests getting the sessions from the request <del> * <del> * @return void <del> */ <del> public function testSession() <del> { <del> $this->deprecated(function () { <del> $session = new Session; <del> $request = new ServerRequest(['session' => $session]); <del> $this->assertSame($session, $request->session()); <del> <del> $request = ServerRequestFactory::fromGlobals(); <del> $this->assertEquals($session, $request->session()); <del> }); <del> } <del> <ide> /** <ide> * Tests getting the session from the request <ide> * <ide> public function testWithAttribute() <ide> $this->assertSame(['complex'], $update->getAttribute('key')); <ide> } <ide> <del> /** <del> * Test that withAttribute() can modify the deprecated public properties. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testWithAttributesCompatibility() <del> { <del> $this->deprecated(function () { <del> $request = new ServerRequest([ <del> 'params' => [ <del> 'controller' => 'Articles', <del> 'action' => 'index' <del> ], <del> 'base' => '/cakeapp', <del> 'webroot' => '/cakeapp/' <del> ]); <del> <del> $new = $request->withAttribute('base', '/replace') <del> ->withAttribute('webroot', '/replace/') <del> ->withAttribute('params', ['controller' => 'Tags']); <del> <del> // Original request should not change. <del> $this->assertSame('/cakeapp', $request->getAttribute('base')); <del> $this->assertSame('/cakeapp/', $request->getAttribute('webroot')); <del> $this->assertSame( <del> ['controller' => 'Articles', 'action' => 'index'], <del> $request->getAttribute('params') <del> ); <del> <del> $this->assertSame('/replace', $new->getAttribute('base')); <del> $this->assertSame('/replace', $new->base); <del> $this->assertSame('/replace/', $new->getAttribute('webroot')); <del> $this->assertSame('/replace/', $new->webroot); <del> <del> $this->assertSame(['controller' => 'Tags'], $new->getAttribute('params')); <del> $this->assertSame(['controller' => 'Tags'], $new->params); <del> }); <del> } <del> <del> /** <del> * Test that getAttribute() can read deprecated public properties. <del> * <del> * @group deprecated <del> * @dataProvider emulatedPropertyProvider <del> * @return void <del> */ <del> public function testGetAttributesCompatibility($prop) <del> { <del> $this->deprecated(function () use ($prop) { <del> $request = new ServerRequest([ <del> 'params' => [ <del> 'controller' => 'Articles', <del> 'action' => 'index' <del> ], <del> 'url' => '/articles/view', <del> 'base' => '/cakeapp', <del> 'webroot' => '/cakeapp/' <del> ]); <del> <del> if ($prop === 'session') { <del> $this->assertSame($request->getSession(), $request->getAttribute($prop)); <del> } else { <del> $this->assertNotEmpty($request->getAttribute($prop)); <del> $this->assertSame($request->{$prop}, $request->getAttribute($prop)); <del> } <del> }); <del> } <del> <ide> /** <ide> * Test getting all attributes. <ide> * <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testReverseToArrayRequestQuery() <ide> */ <ide> public function testGetRequest() <ide> { <del> $requestA = new ServerRequest('/'); <del> $requestB = new ServerRequest('/posts'); <add> $requestA = new ServerRequest(['url' => '/']); <add> $requestB = new ServerRequest(['url' => '/posts']); <ide> <ide> Router::pushRequest($requestA); <ide> Router::pushRequest($requestB); <ide><path>tests/TestCase/View/ViewTest.php <ide> public function setUp() <ide> $this->View = $this->PostsController->createView(); <ide> $this->View->setTemplatePath('Posts'); <ide> <del> $themeRequest = new ServerRequest('posts/index'); <add> $themeRequest = new ServerRequest(['url' => 'posts/index']); <ide> $this->ThemeController = new Controller($themeRequest); <ide> $this->ThemePostsController = new ThemePostsController($themeRequest); <ide> $this->ThemePostsController->index();
11
Java
Java
enable registersegment in venice
a23596f70f9ca8a60382ac065a49cfad39c3f38c
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java <ide> public JavaScriptContextHolder getJavaScriptContextHolder() { <ide> public @Nullable String getSourceURL() { <ide> return mCatalystInstance.getSourceURL(); <ide> } <add> <add> /** <add> * Register a JS segment after loading it from cache or server, make sure mCatalystInstance is <add> * properly initialised and not null before calling. <add> * <add> * @param segmentId <add> * @param path <add> */ <add> public void registerSegment(int segmentId, String path) { <add> Assertions.assertNotNull(mCatalystInstance).registerSegment(segmentId, path); <add> } <ide> }
1
Javascript
Javascript
fix comments in animationaction
8cda17649d7cfaff1a9728f3f02c7bc5075ab949
<ide><path>src/animation/AnimationAction.js <ide> function AnimationAction( mixer, clip, localRoot ) { <ide> <ide> this.repetitions = Infinity; // no. of repetitions when looping <ide> <del> this.paused = false; // false -> zero effective time scale <del> this.enabled = true; // true -> zero effective weight <add> this.paused = false; // true -> zero effective time scale <add> this.enabled = true; // false -> zero effective weight <ide> <ide> this.clampWhenFinished = false; // keep feeding the last frame? <ide> <ide> Object.assign( AnimationAction.prototype, { <ide> <ide> // Time Scale Control <ide> <del> // set the weight stopping any scheduled warping <add> // set the time scale stopping any scheduled warping <ide> // although .paused = true yields an effective time scale of zero, this <ide> // method does *not* change .paused, because it would be confusing <ide> setEffectiveTimeScale: function( timeScale ) {
1
Java
Java
fix systrace section for lazy view managers
52a67db629ff12c407605163bdbe3d5dfb5373f1
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> import com.facebook.react.uimanager.events.EventDispatcher; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <del> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.Map; <ide> private static Map<String, Object> createConstants( <ide> return null; <ide> } <ide> <del> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "constants for ViewManager") <add> SystraceMessage.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "UIManagerModule.getConstantsForViewManager") <ide> .arg("ViewManager", targetView.getName()) <ide> .arg("Lazy", true) <ide> .flush(); <ide> private static Map<String, Object> createConstants( <ide> } <ide> return null; <ide> } finally { <del> SystraceMessage.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> SystraceMessage.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE).flush(); <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java <ide> for (ViewManager viewManager : viewManagers) { <ide> final String viewManagerName = viewManager.getName(); <ide> <del> SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "constants for ViewManager") <add> SystraceMessage.beginSection( <add> TRACE_TAG_REACT_JAVA_BRIDGE, "UIManagerModuleConstantsHelper.createConstants") <ide> .arg("ViewManager", viewManagerName) <ide> .arg("Lazy", false) <ide> .flush();
2
Javascript
Javascript
correct pdfdocumentproxyclosure name
117256ce788cd1c28a9bb39d97e646248624466a
<ide><path>src/api.js <ide> PDFJS.getDocument = function getDocument(source) { <ide> * Proxy to a PDFDocument in the worker thread. Also, contains commonly used <ide> * properties that can be read synchronously. <ide> */ <del>var PDFDocumentProxy = (function() { <add>var PDFDocumentProxy = (function PDFDocumentProxyClosure() { <ide> function PDFDocumentProxy(pdfInfo, transport) { <ide> this.pdfInfo = pdfInfo; <ide> this.transport = transport;
1
Java
Java
fix race in turbomodulemanager initialization
9fdc8daf6152382e787b5da175722435c28bf8b9
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public interface ReactInstanceEventListener { <ide> private @Nullable @ThreadConfined(UI) DefaultHardwareBackBtnHandler mDefaultBackButtonImpl; <ide> private @Nullable Activity mCurrentActivity; <ide> private final Collection<ReactInstanceEventListener> mReactInstanceEventListeners = <del> Collections.synchronizedSet(new HashSet<ReactInstanceEventListener>()); <add> Collections.synchronizedList(new ArrayList<ReactInstanceEventListener>()); <ide> // Identifies whether the instance manager is or soon will be initialized (on background thread) <ide> private volatile boolean mHasStartedCreatingInitialContext = false; <ide> // Identifies whether the instance manager destroy function is in process,
1
PHP
PHP
fix cs issue
777a46ff6de464ef88580cf62c09265948086a06
<ide><path>lib/Cake/Network/CakeResponse.php <ide> public function send() { <ide> $this->_setContentLength(); <ide> $this->_setContentType(); <ide> foreach ($this->_headers as $header => $values) { <del> foreach((array)$values as $value) { <add> foreach ((array)$values as $value) { <ide> $this->_sendHeader($header, $value); <ide> } <ide> }
1
Javascript
Javascript
remove unneeded weakset
aefcbcda47a2249a2ebd56a5895e07555e8be895
<ide><path>src/main-process/file-recovery-service.js <ide> export default class FileRecoveryService { <ide> this.recoveryDirectory = recoveryDirectory <ide> this.recoveryFilesByFilePath = new Map() <ide> this.recoveryFilesByWindow = new WeakMap() <del> this.observedWindows = new WeakSet() <ide> } <ide> <ide> willSavePath (window, path) { <ide> export default class FileRecoveryService { <ide> console.log(`Couldn't retain ${recoveryFile.recoveryPath}. Code: ${err.code}. Message: ${err.message}`) <ide> } <ide> <del> if (!this.observedWindows.has(window)) { <del> this.observedWindows.add(window) <del> } <del> <ide> if (!this.recoveryFilesByWindow.has(window)) { <ide> this.recoveryFilesByWindow.set(window, new Set()) <ide> } <ide> export default class FileRecoveryService { <ide> } <ide> <ide> didCloseWindow (window) { <del> this.observedWindows.delete(window) <ide> this.recoveryFilesByWindow.delete(window) <ide> } <ide> }
1
Javascript
Javascript
add position tracking to vrcontrols
5f6b04a5848e5cb0f2392a7b407bde6dd26137bc
<ide><path>examples/js/controls/VRControls.js <ide> THREE.VRControls = function ( object, callback ) { <ide> <ide> if ( vrInput === undefined ) return; <ide> <del> var orientation = vrInput.getState().orientation; <add> var state = vrInput.getState(); <ide> <del> if ( orientation !== null ) { <add> if ( state.orientation !== null ) { <ide> <del> object.quaternion.set( orientation.x, orientation.y, orientation.z, orientation.w ); <add> object.quaternion.copy( state.orientation ); <add> <add> } <add> <add> if ( state.position !== null ) { <add> <add> object.position.copy( state.position ); <ide> <ide> } <ide>
1
Ruby
Ruby
remove unnecessary `query_scope`
5047a1229fe13983274bf9675d09748cba281645
<ide><path>activerecord/lib/active_record/associations/preloader/association.rb <ide> def scope <ide> end <ide> <ide> def records_for(ids) <del> query_scope(ids) <del> end <del> <del> def query_scope(ids) <ide> scope.where(association_key_name => ids) <ide> end <ide>
1
Java
Java
use specified resolvabletype in jacksonjsonencoder
a0e223177927608e67d8b3e20436ecd6e68e7ec5
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/support/JacksonJsonEncoder.java <ide> import java.nio.ByteBuffer; <ide> import java.nio.charset.StandardCharsets; <ide> <add>import com.fasterxml.jackson.databind.JavaType; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.fasterxml.jackson.databind.ObjectWriter; <add>import com.fasterxml.jackson.databind.type.TypeFactory; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> public JacksonJsonEncoder(ObjectMapper mapper) { <ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, <ide> DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, <ide> Object... hints) { <add> Assert.notNull(inputStream, "'inputStream' must not be null"); <add> Assert.notNull(bufferFactory, "'bufferFactory' must not be null"); <add> Assert.notNull(elementType, "'elementType' must not be null"); <ide> if (inputStream instanceof Mono) { <ide> // single object <ide> return Flux.from(inputStream) <del> .map(value -> serialize(value, bufferFactory)); <add> .map(value -> serialize(value, bufferFactory, elementType)); <ide> } <ide> else { <ide> // array <ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, <ide> Mono.just(bufferFactory.wrap(END_ARRAY_BUFFER)); <ide> <ide> Flux<DataBuffer> serializedObjects = Flux.from(inputStream) <del> .map(value -> serialize(value, bufferFactory)); <add> .map(value -> serialize(value, bufferFactory, elementType)); <ide> <ide> Flux<DataBuffer> array = Flux.zip(serializedObjects, arraySeparators) <ide> .flatMap(tuple -> Flux.just(tuple.getT1(), tuple.getT2())); <ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, <ide> } <ide> } <ide> <del> private DataBuffer serialize(Object value, DataBufferFactory dataBufferFactory) { <add> private DataBuffer serialize(Object value, DataBufferFactory dataBufferFactory, <add> ResolvableType type) { <add> TypeFactory typeFactory = this.mapper.getTypeFactory(); <add> JavaType javaType = typeFactory.constructType(type.getType()); <add> ObjectWriter writer = this.mapper.writerFor(javaType); <ide> DataBuffer buffer = dataBufferFactory.allocateBuffer(); <ide> OutputStream outputStream = buffer.asOutputStream(); <ide> try { <del> this.mapper.writeValue(outputStream, value); <add> writer.writeValue(outputStream, value); <ide> } <ide> catch (IOException e) { <ide> throw new CodecException("Error while writing the data", e); <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/DefaultHttpRequestBuilder.java <ide> public class DefaultHttpRequestBuilder implements HttpRequestBuilder { <ide> <ide> protected Publisher contentPublisher; <ide> <add> protected ResolvableType contentType; <add> <ide> protected final List<HttpCookie> cookies = new ArrayList<HttpCookie>(); <ide> <ide> protected DefaultHttpRequestBuilder() { <ide> public DefaultHttpRequestBuilder accept(String... mediaTypes) { <ide> <ide> public DefaultHttpRequestBuilder content(Object content) { <ide> this.contentPublisher = Mono.just(content); <add> this.contentType = ResolvableType.forInstance(content); <ide> return this; <ide> } <ide> <del> public DefaultHttpRequestBuilder contentStream(Publisher<?> content) { <add> public DefaultHttpRequestBuilder contentStream(Publisher<?> content, ResolvableType type) { <ide> this.contentPublisher = Flux.from(content); <add> this.contentType = type; <ide> return this; <ide> } <ide> <ide> public ClientHttpRequest build(ClientHttpRequestFactory factory, List<Encoder<?> <ide> request.getHeaders().putAll(this.httpHeaders); <ide> <ide> if (this.contentPublisher != null) { <del> ResolvableType requestBodyType = ResolvableType.forInstance(this.contentPublisher); <ide> MediaType mediaType = request.getHeaders().getContentType(); <ide> <ide> Optional<Encoder<?>> messageEncoder = messageEncoders <ide> .stream() <del> .filter(e -> e.canEncode(requestBodyType, mediaType)) <add> .filter(e -> e.canEncode(this.contentType, mediaType)) <ide> .findFirst(); <ide> <ide> if (messageEncoder.isPresent()) { <ide> request.writeWith(messageEncoder.get() <ide> .encode(this.contentPublisher, request.bufferFactory(), <del> requestBodyType, mediaType)); <add> this.contentType, mediaType)); <ide> } <ide> else { <ide> throw new WebClientException("Can't write request body " + <del> "of type '" + requestBodyType.toString() + <add> "of type '" + this.contentType.toString() + <ide> "' for content-type '" + mediaType.toString() + "'"); <ide> } <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/JacksonJsonEncoderTests.java <ide> <ide> package org.springframework.core.codec.support; <ide> <add>import com.fasterxml.jackson.annotation.JsonTypeInfo; <add>import com.fasterxml.jackson.annotation.JsonTypeName; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.test.TestSubscriber; <ide> <add>import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.http.MediaType; <ide> public void canWrite() { <ide> public void write() { <ide> Flux<Pojo> source = Flux.just(new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar")); <ide> <add> ResolvableType type = ResolvableType.forClass(Pojo.class); <ide> Flux<DataBuffer> output = <del> this.encoder.encode(source, this.dataBufferFactory, null, null); <add> this.encoder.encode(source, this.dataBufferFactory, type, null); <ide> <ide> TestSubscriber <ide> .subscribe(output) <ide> public void write() { <ide> stringConsumer("]")); <ide> } <ide> <add> @Test <add> public void writeWithType() { <add> Flux<ParentClass> source = Flux.just(new Foo(), new Bar()); <add> <add> ResolvableType type = ResolvableType.forClass(ParentClass.class); <add> Flux<DataBuffer> output = <add> this.encoder.encode(source, this.dataBufferFactory, type, null); <add> <add> TestSubscriber <add> .subscribe(output) <add> .assertComplete() <add> .assertNoError() <add> .assertValuesWith(stringConsumer("["), <add> stringConsumer("{\"type\":\"foo\"}"), <add> stringConsumer(","), <add> stringConsumer("{\"type\":\"bar\"}"), <add> stringConsumer("]")); <add> } <add> <add> @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") <add> private static class ParentClass { <add> } <add> <add> @JsonTypeName("foo") <add> private static class Foo extends ParentClass { <add> } <add> <add> @JsonTypeName("bar") <add> private static class Bar extends ParentClass { <add> } <add> <ide> }
3
PHP
PHP
commit application trait
8efd39e5b6d5e74928a40709ee54d7ef3c591b89
<ide><path>src/Illuminate/Foundation/Testing/ApplicationTrait.php <add><?php namespace Illuminate\Foundation\Testing; <add> <add>use Illuminate\Http\Request; <add>use InvalidArgumentException; <add>use Symfony\Component\DomCrawler\Form; <add>use Symfony\Component\DomCrawler\Crawler; <add>use Illuminate\Contracts\Auth\Authenticatable as UserContract; <add>use PHPUnit_Framework_ExpectationFailedException as PHPUnitException; <add> <add>trait ApplicationTrait <add>{ <add> /** <add> * The Illuminate application instance. <add> * <add> * @var \Illuminate\Foundation\Application <add> */ <add> protected $app; <add> <add> /** <add> * The last code returned by Artisan CLI. <add> * <add> * @var int <add> */ <add> protected $code; <add> <add> /** <add> * Refresh the application instance. <add> * <add> * @return void <add> */ <add> protected function refreshApplication() <add> { <add> putenv('APP_ENV=testing'); <add> <add> $this->app = $this->createApplication(); <add> } <add> <add> /** <add> * Set the session to the given array. <add> * <add> * @param array $data <add> * @return void <add> */ <add> public function session(array $data) <add> { <add> $this->startSession(); <add> <add> foreach ($data as $key => $value) { <add> $this->app['session']->put($key, $value); <add> } <add> } <add> <add> /** <add> * Start the session for the application. <add> * <add> * @return void <add> */ <add> protected function startSession() <add> { <add> if (! $this->app['session']->isStarted()) { <add> $this->app['session']->start(); <add> } <add> } <add> <add> /** <add> * Flush all of the current session data. <add> * <add> * @return void <add> */ <add> public function flushSession() <add> { <add> $this->startSession(); <add> <add> $this->app['session']->flush(); <add> } <add> <add> /** <add> * Set the currently logged in user for the application. <add> * <add> * @param \Illuminate\Contracts\Auth\Authenticatable $user <add> * @param string $driver <add> * @return void <add> */ <add> public function be(UserContract $user, $driver = null) <add> { <add> $this->app['auth']->driver($driver)->setUser($user); <add> } <add> <add> /** <add> * Seed a given database connection. <add> * <add> * @param string $class <add> * @return void <add> */ <add> public function seed($class = 'DatabaseSeeder') <add> { <add> $this->artisan('db:seed', ['--class' => $class]); <add> } <add> <add> /** <add> * Call artisan command and return code. <add> * <add> * @param string $command <add> * @param array $parameters <add> * @return int <add> */ <add> public function artisan($command, $parameters = []) <add> { <add> return $this->code = $this->app['Illuminate\Contracts\Console\Kernel']->call($command, $parameters); <add> } <add>}
1
PHP
PHP
fix existence check in mailsentwith
2297484f72ee5ce50f9ca7bc9c58d1b4acd15c5e
<ide><path>src/TestSuite/Constraint/Email/MailSentWith.php <ide> public function matches($other) <ide> $emails = $this->getEmails(); <ide> foreach ($emails as $email) { <ide> $value = $email->{'get' . ucfirst($this->method)}(); <del> if (in_array($this->method, ['to', 'cc', 'bcc', 'from']) && isset($value[$other])) { <add> if (in_array($this->method, ['to', 'cc', 'bcc', 'from']) <add> && array_key_exists($other, $value) <add> ) { <ide> return true; <ide> } <ide> if ($value === $other) { <ide><path>tests/TestCase/TestSuite/EmailTraitTest.php <ide> public function testMultipleAssertions() <ide> <ide> $this->sendEmails(); <ide> <del> $this->assertMailCount(2); <add> $this->assertMailCount(3); <ide> <ide> $this->assertMailSentFromAt(0, 'default@example.com'); <ide> $this->assertMailSentFromAt(1, 'alternate@example.com'); <ide> <ide> $this->assertMailSentToAt(0, 'to@example.com'); <ide> $this->assertMailSentToAt(1, 'to2@example.com'); <add> $this->assertMailSentToAt(2, 'to3@example.com'); <ide> <ide> $this->assertMailContainsAt(0, 'text'); <ide> $this->assertMailContainsAt(1, 'html'); <ide> private function sendEmails() <ide> ->setCc('cc2@example.com') <ide> ->setEmailFormat(Email::MESSAGE_HTML) <ide> ->send('html'); <add> <add> (new Email('alternate')) <add> ->setTo(['to3@example.com' => null]) <add> ->send('html'); <ide> } <ide> }
2
Python
Python
add option to worker to control heartbeat interval
574559dd435c1303bfdc06e78211771c241ee0f8
<ide><path>celery/bin/worker.py <ide> <ide> Do not send event heartbeats. <ide> <add>.. cmdoption:: --heartbeat-interval <add> <add> Interval in seconds at which to send worker heartbeat <add> <ide> .. cmdoption:: --purge <ide> <ide> Purges all waiting tasks before the daemon is started. <ide> def get_options(self): <ide> Option('--without-gossip', action='store_true', default=False), <ide> Option('--without-mingle', action='store_true', default=False), <ide> Option('--without-heartbeat', action='store_true', default=False), <add> Option('--heartbeat-interval', type='int'), <ide> Option('-O', dest='optimization'), <ide> Option('-D', '--detach', action='store_true'), <ide> ) + daemon_options() + tuple(self.app.user_options['worker']) <ide><path>celery/tests/bin/test_worker.py <ide> def test_set_process_status(self): <ide> def test_parse_options(self): <ide> cmd = worker() <ide> cmd.app = self.app <del> opts, args = cmd.parse_options('worker', ['--concurrency=512']) <add> opts, args = cmd.parse_options('worker', ['--concurrency=512', <add> '--heartbeat-interval=10']) <ide> self.assertEqual(opts.concurrency, 512) <add> self.assertEqual(opts.heartbeat_interval, 10) <ide> <ide> @disable_stdouts <ide> def test_main(self): <ide><path>celery/tests/worker/test_consumer.py <ide> def test_start(self): <ide> with patch('celery.worker.heartbeat.Heart') as hcls: <ide> h = Heart(c) <ide> self.assertTrue(h.enabled) <add> self.assertEqual(h.heartbeat_interval, None) <ide> self.assertIsNone(c.heart) <ide> <ide> h.start(c) <ide> self.assertTrue(c.heart) <del> hcls.assert_called_with(c.timer, c.event_dispatcher) <add> hcls.assert_called_with(c.timer, c.event_dispatcher, <add> h.heartbeat_interval) <add> c.heart.start.assert_called_with() <add> <add> def test_start_heartbeat_interval(self): <add> c = Mock() <add> c.timer = Mock() <add> c.event_dispatcher = Mock() <add> <add> with patch('celery.worker.heartbeat.Heart') as hcls: <add> h = Heart(c, False, 20) <add> self.assertTrue(h.enabled) <add> self.assertEqual(h.heartbeat_interval, 20) <add> self.assertIsNone(c.heart) <add> <add> h.start(c) <add> self.assertTrue(c.heart) <add> hcls.assert_called_with(c.timer, c.event_dispatcher, <add> h.heartbeat_interval) <ide> c.heart.start.assert_called_with() <ide> <ide> <ide><path>celery/worker/consumer.py <ide> def shutdown(self, c): <ide> class Heart(bootsteps.StartStopStep): <ide> requires = (Events, ) <ide> <del> def __init__(self, c, without_heartbeat=False, **kwargs): <add> def __init__(self, c, without_heartbeat=False, heartbeat_interval=None, <add> **kwargs): <ide> self.enabled = not without_heartbeat <add> self.heartbeat_interval = heartbeat_interval <ide> c.heart = None <ide> <ide> def start(self, c): <del> c.heart = heartbeat.Heart(c.timer, c.event_dispatcher) <add> c.heart = heartbeat.Heart(c.timer, c.event_dispatcher, <add> self.heartbeat_interval) <ide> c.heart.start() <ide> <ide> def stop(self, c):
4
Python
Python
add xfailing test (see , , )
414a69b736546b3f5adfb1a6f8dccf5b91160694
<ide><path>spacy/tests/regression/test_issue1971.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>from spacy.matcher import Matcher <add>from spacy.tokens import Token, Doc <add> <add> <add>def test_issue1971(en_vocab): <add> # Possibly related to #2675 and #2671? <add> matcher = Matcher(en_vocab) <add> pattern = [ <add> {"ORTH": "Doe"}, <add> {"ORTH": "!", "OP": "?"}, <add> {"_": {"optional": True}, "OP": "?"}, <add> {"ORTH": "!", "OP": "?"}, <add> ] <add> Token.set_extension("optional", default=False) <add> matcher.add("TEST", None, pattern) <add> doc = Doc(en_vocab, words=["Hello", "John", "Doe", "!"]) <add> # We could also assert length 1 here, but this is more conclusive, because <add> # the real problem here is that it returns a duplicate match for a match_id <add> # that's not actually in the vocab! <add> assert all(match_id in en_vocab.strings for match_id, start, end in matcher(doc))
1
PHP
PHP
add arraycache engine
ed45089396c133b51f370426af868af3b86e9a71
<ide><path>src/Cache/Engine/ArrayEngine.php <add><?php <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 3.7.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Cache\Engine; <add> <add>use Cake\Cache\CacheEngine; <add> <add>/** <add> * Array storage engine for cache. <add> * <add> * Not actually a persistent cache engine. All data is only <add> * stored in memory for the duration of a single process. While not <add> * useful in production settings this engine can be useful in tests <add> * or console tools where you don't want the overhead of interacting <add> * with a cache servers, but want the work saving properties a cache <add> * provides. <add> */ <add>class ArrayEngine extends CacheEngine <add>{ <add> /** <add> * Cached data. <add> * <add> * Structured as [key => [expiration, value]] <add> * <add> * @var aray <add> */ <add> protected $data = []; <add> <add> /** <add> * Write data for key into cache <add> * <add> * @param string $key Identifier for the data <add> * @param mixed $value Data to be cached <add> * @return bool True if the data was successfully cached, false on failure <add> */ <add> public function write($key, $value) <add> { <add> $key = $this->_key($key); <add> $expires = time() + $this->_config['duration']; <add> $this->data[$key] = [$expires, $value]; <add> <add> return true; <add> } <add> <add> /** <add> * Read a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return mixed The cached data, or false if the data doesn't exist, <add> * has expired, or if there was an error fetching it <add> */ <add> public function read($key) <add> { <add> $key = $this->_key($key); <add> if (!isset($this->data[$key])) { <add> return false; <add> } <add> $data = $this->data[$key]; <add> <add> // Check expiration <add> $now = time(); <add> if ($data[0] <= $now) { <add> unset($this->data[$key]); <add> <add> return false; <add> } <add> <add> return $data[1]; <add> } <add> <add> /** <add> * Increments the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to increment <add> * @return bool|int New incremented value, false otherwise <add> */ <add> public function increment($key, $offset = 1) <add> { <add> if (!$this->read($key)) { <add> $this->write($key, 0); <add> } <add> $key = $this->_key($key); <add> $this->data[$key][1] += $offset; <add> <add> return true; <add> } <add> <add> /** <add> * Decrements the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to subtract <add> * @return bool|int New decremented value, false otherwise <add> */ <add> public function decrement($key, $offset = 1) <add> { <add> if (!$this->read($key)) { <add> $this->write($key, 0); <add> } <add> $key = $this->_key($key); <add> $this->data[$key][1] -= $offset; <add> <add> return true; <add> } <add> <add> /** <add> * Delete a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed <add> */ <add> public function delete($key) <add> { <add> $key = $this->_key($key); <add> unset($this->data[$key]); <add> <add> return true; <add> } <add> <add> /** <add> * Delete all keys from the cache. This will clear every cache config using APC. <add> * <add> * @param bool $check Unused argument required by interface. <add> * @return bool True Returns true. <add> */ <add> public function clear($check) <add> { <add> $this->data = []; <add> <add> return true; <add> } <add> <add> /** <add> * Returns the `group value` for each of the configured groups <add> * If the group initial value was not found, then it initializes <add> * the group accordingly. <add> * <add> * @return array <add> */ <add> public function groups() <add> { <add> $result = []; <add> foreach ($this->_config['groups'] as $group) { <add> $key = $this->_config['prefix'] . $group; <add> if (!isset($this->data[$key])) { <add> $this->data[$key] = [PHP_INT_MAX, 1]; <add> } <add> $value = $this->data[$key][1]; <add> $result[] = $group . $value; <add> } <add> <add> return $result; <add> } <add> <add> /** <add> * Increments the group value to simulate deletion of all keys under a group <add> * old values will remain in storage until they expire. <add> * <add> * @param string $group The group to clear. <add> * @return bool success <add> */ <add> public function clearGroup($group) <add> { <add> $key = $this->_config['prefix'] . $group; <add> if (isset($this->data[$key])) { <add> $this->data[$key][1] += 1; <add> } <add> <add> return true; <add> } <add>} <ide><path>tests/TestCase/Cache/Engine/ArrayEngineTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.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 3.7.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\Cache\Engine; <add> <add>use Cake\Cache\Cache; <add>use Cake\TestSuite\TestCase; <add> <add>/** <add> * ArrayEngineTest class <add> */ <add>class ArrayEngineTest extends TestCase <add>{ <add> /** <add> * setUp method <add> * <add> * @return void <add> */ <add> public function setUp() <add> { <add> parent::setUp(); <add> <add> Cache::enable(); <add> $this->_configCache(); <add> Cache::clearAll(); <add> } <add> <add> /** <add> * tearDown method <add> * <add> * @return void <add> */ <add> public function tearDown() <add> { <add> parent::tearDown(); <add> Cache::drop('array'); <add> Cache::drop('array_groups'); <add> } <add> <add> /** <add> * Helper method for testing. <add> * <add> * @param array $config <add> * @return void <add> */ <add> protected function _configCache($config = []) <add> { <add> $defaults = [ <add> 'className' => 'Array', <add> 'prefix' => 'cake_', <add> 'warnOnWriteFailures' => true, <add> ]; <add> Cache::drop('array'); <add> Cache::setConfig('array', array_merge($defaults, $config)); <add> } <add> <add> /** <add> * testReadAndWriteCache method <add> * <add> * @return void <add> */ <add> public function testReadAndWriteCache() <add> { <add> $this->_configCache(['duration' => 1]); <add> <add> $result = Cache::read('test', 'array'); <add> $expecting = ''; <add> $this->assertEquals($expecting, $result); <add> <add> $data = 'this is a test of the emergency broadcasting system'; <add> $result = Cache::write('test', $data, 'array'); <add> $this->assertTrue($result); <add> <add> $result = Cache::read('test', 'array'); <add> $expecting = $data; <add> $this->assertEquals($expecting, $result); <add> <add> Cache::delete('test', 'array'); <add> } <add> <add> /** <add> * testExpiry method <add> * <add> * @return void <add> */ <add> public function testExpiry() <add> { <add> $this->_configCache(['duration' => 1]); <add> <add> $result = Cache::read('test', 'array'); <add> $this->assertFalse($result); <add> <add> $data = 'this is a test of the emergency broadcasting system'; <add> $result = Cache::write('other_test', $data, 'array'); <add> $this->assertTrue($result); <add> <add> sleep(2); <add> $result = Cache::read('other_test', 'array'); <add> $this->assertFalse($result); <add> } <add> <add> /** <add> * testDeleteCache method <add> * <add> * @return void <add> */ <add> public function testDeleteCache() <add> { <add> $data = 'this is a test of the emergency broadcasting system'; <add> $result = Cache::write('delete_test', $data, 'array'); <add> $this->assertTrue($result); <add> <add> $result = Cache::delete('delete_test', 'array'); <add> $this->assertTrue($result); <add> } <add> <add> /** <add> * testDecrement method <add> * <add> * @return void <add> */ <add> public function testDecrement() <add> { <add> $result = Cache::write('test_decrement', 5, 'array'); <add> $this->assertTrue($result); <add> <add> $result = Cache::decrement('test_decrement', 1, 'array'); <add> $this->assertEquals(4, $result); <add> <add> $result = Cache::read('test_decrement', 'array'); <add> $this->assertEquals(4, $result); <add> <add> $result = Cache::decrement('test_decrement', 2, 'array'); <add> $this->assertEquals(2, $result); <add> <add> $result = Cache::read('test_decrement', 'array'); <add> $this->assertEquals(2, $result); <add> } <add> <add> /** <add> * testIncrement method <add> * <add> * @return void <add> */ <add> public function testIncrement() <add> { <add> $result = Cache::write('test_increment', 5, 'array'); <add> $this->assertTrue($result); <add> <add> $result = Cache::increment('test_increment', 1, 'array'); <add> $this->assertEquals(6, $result); <add> <add> $result = Cache::read('test_increment', 'array'); <add> $this->assertEquals(6, $result); <add> <add> $result = Cache::increment('test_increment', 2, 'array'); <add> $this->assertEquals(8, $result); <add> <add> $result = Cache::read('test_increment', 'array'); <add> $this->assertEquals(8, $result); <add> } <add> <add> /** <add> * test the clearing of cache keys <add> * <add> * @return void <add> */ <add> public function testClear() <add> { <add> Cache::write('some_value', 'value', 'array'); <add> <add> $result = Cache::clear(false, 'array'); <add> $this->assertTrue($result); <add> $this->assertFalse(Cache::read('some_value', 'array')); <add> } <add> <add> /** <add> * Tests that configuring groups for stored keys return the correct values when read/written <add> * Shows that altering the group value is equivalent to deleting all keys under the same <add> * group <add> * <add> * @return void <add> */ <add> public function testGroupsReadWrite() <add> { <add> Cache::setConfig('array_groups', [ <add> 'engine' => 'array', <add> 'duration' => 30, <add> 'groups' => ['group_a', 'group_b'], <add> 'prefix' => 'test_', <add> 'warnOnWriteFailures' => true, <add> ]); <add> $this->assertTrue(Cache::write('test_groups', 'value', 'array_groups')); <add> $this->assertEquals('value', Cache::read('test_groups', 'array_groups')); <add> <add> Cache::clearGroup('group_a', 'array_groups'); <add> $this->assertFalse(Cache::read('test_groups', 'array_groups')); <add> $this->assertTrue(Cache::write('test_groups', 'value2', 'array_groups')); <add> $this->assertEquals('value2', Cache::read('test_groups', 'array_groups')); <add> <add> Cache::clearGroup('group_b', 'array_groups'); <add> $this->assertFalse(Cache::read('test_groups', 'array_groups')); <add> $this->assertTrue(Cache::write('test_groups', 'value3', 'array_groups')); <add> $this->assertEquals('value3', Cache::read('test_groups', 'array_groups')); <add> } <add> <add> /** <add> * Tests that deleting from a groups-enabled config is possible <add> * <add> * @return void <add> */ <add> public function testGroupDelete() <add> { <add> Cache::setConfig('array_groups', [ <add> 'engine' => 'array', <add> 'duration' => 10, <add> 'groups' => ['group_a', 'group_b'], <add> 'prefix' => 'test_', <add> 'warnOnWriteFailures' => true, <add> ]); <add> $this->assertTrue(Cache::write('test_groups', 'value', 'array_groups')); <add> $this->assertEquals('value', Cache::read('test_groups', 'array_groups')); <add> <add> $this->assertTrue(Cache::delete('test_groups', 'array_groups')); <add> $this->assertFalse(Cache::read('test_groups', 'array_groups')); <add> } <add> <add> /** <add> * Test clearing a cache group <add> * <add> * @return void <add> */ <add> public function testGroupClear() <add> { <add> Cache::setConfig('array_groups', [ <add> 'engine' => 'array', <add> 'duration' => 10, <add> 'groups' => ['group_a', 'group_b'], <add> 'prefix' => 'test_', <add> 'warnOnWriteFailures' => true, <add> ]); <add> <add> $this->assertTrue(Cache::write('test_groups', 'value', 'array_groups')); <add> $this->assertTrue(Cache::clearGroup('group_a', 'array_groups')); <add> $this->assertFalse(Cache::read('test_groups', 'array_groups')); <add> <add> $this->assertTrue(Cache::write('test_groups', 'value2', 'array_groups')); <add> $this->assertTrue(Cache::clearGroup('group_b', 'array_groups')); <add> $this->assertFalse(Cache::read('test_groups', 'array_groups')); <add> } <add> <add> /** <add> * Test add <add> * <add> * @return void <add> */ <add> public function testAdd() <add> { <add> Cache::delete('test_add_key', 'array'); <add> <add> $result = Cache::add('test_add_key', 'test data', 'array'); <add> $this->assertTrue($result); <add> <add> $expected = 'test data'; <add> $result = Cache::read('test_add_key', 'array'); <add> $this->assertEquals($expected, $result); <add> <add> $result = Cache::add('test_add_key', 'test data 2', 'array'); <add> $this->assertFalse($result); <add> } <add>}
2
Python
Python
handle http_auth in elasticsearch backend results
193be0be9dd8b925b3a46fed80887e73707db935
<ide><path>celery/backends/elasticsearch.py <ide> class ElasticsearchBackend(KeyValueStoreBackend): <ide> scheme = 'http' <ide> host = 'localhost' <ide> port = 9200 <add> username = None <add> password = None <ide> es_retry_on_timeout = False <ide> es_timeout = 10 <ide> es_max_retries = 3 <ide> def __init__(self, url=None, *args, **kwargs): <ide> if elasticsearch is None: <ide> raise ImproperlyConfigured(E_LIB_MISSING) <ide> <del> index = doc_type = scheme = host = port = None <add> index = doc_type = scheme = host = port = username = password = None <ide> <ide> if url: <del> scheme, host, port, _, _, path, _ = _parse_url(url) # noqa <add> scheme, host, port, username, password, path, _ = _parse_url(url) # noqa <add> if scheme == 'elasticsearch': <add> scheme = None <ide> if path: <ide> path = path.strip('/') <ide> index, _, doc_type = path.partition('/') <ide> def __init__(self, url=None, *args, **kwargs): <ide> self.scheme = scheme or self.scheme <ide> self.host = host or self.host <ide> self.port = port or self.port <add> self.username = username or self.username <add> self.password = password or self.password <ide> <ide> self.es_retry_on_timeout = ( <ide> _get('elasticsearch_retry_on_timeout') or self.es_retry_on_timeout <ide> def delete(self, key): <ide> <ide> def _get_server(self): <ide> """Connect to the Elasticsearch server.""" <add> http_auth = None <add> if self.username and self.password: <add> http_auth = (self.username, self.password) <ide> return elasticsearch.Elasticsearch( <ide> '%s:%s' % (self.host, self.port), <ide> retry_on_timeout=self.es_retry_on_timeout, <ide> max_retries=self.es_max_retries, <del> timeout=self.es_timeout <add> timeout=self.es_timeout, <add> scheme=self.scheme, <add> http_auth=http_auth, <ide> ) <ide> <ide> @property <ide><path>t/unit/backends/test_elasticsearch.py <ide> from __future__ import absolute_import, unicode_literals <ide> <ide> import pytest <del>from case import Mock, sentinel, skip <add>from case import Mock, sentinel, skip, patch <ide> <ide> from celery.app import backends <ide> from celery.backends import elasticsearch as module <ide> def test_backend_params_by_url(self): <ide> <ide> assert x.index == 'index' <ide> assert x.doc_type == 'doc_type' <del> assert x.scheme == 'elasticsearch' <add> assert x.scheme == 'http' <ide> assert x.host == 'localhost' <ide> assert x.port == 9200 <ide> <add> @patch('elasticsearch.Elasticsearch') <add> def test_get_server_with_auth(self, mock_es_client): <add> url = 'elasticsearch+https://fake_user:fake_pass@localhost:9200/index/doc_type' <add> with self.Celery(backend=url) as app: <add> x = app.backend <add> <add> assert x.username == 'fake_user' <add> assert x.password == 'fake_pass' <add> assert x.scheme == 'https' <add> <add> x._get_server() <add> mock_es_client.assert_called_once_with( <add> 'localhost:9200', <add> http_auth=('fake_user', 'fake_pass'), <add> max_retries=x.es_max_retries, <add> retry_on_timeout=x.es_retry_on_timeout, <add> scheme='https', <add> timeout=x.es_timeout, <add> ) <add> <add> @patch('elasticsearch.Elasticsearch') <add> def test_get_server_without_auth(self, mock_es_client): <add> url = 'elasticsearch://localhost:9200/index/doc_type' <add> with self.Celery(backend=url) as app: <add> x = app.backend <add> x._get_server() <add> mock_es_client.assert_called_once_with( <add> 'localhost:9200', <add> http_auth=None, <add> max_retries=x.es_max_retries, <add> retry_on_timeout=x.es_retry_on_timeout, <add> scheme='http', <add> timeout=x.es_timeout, <add> ) <add> <ide> def test_index(self): <ide> x = ElasticsearchBackend(app=self.app) <ide> x.doc_type = 'test-doc-type'
2
PHP
PHP
remove request from context classes
decf51d2f8e360e11c9478c3899245fec4a785ea
<ide><path>src/Form/Form.php <ide> public function setErrors(array $errors) <ide> */ <ide> public function execute(array $data): bool <ide> { <add> $this->_data = $data; <add> <ide> if (!$this->validate($data)) { <ide> return false; <ide> } <ide><path>src/View/Form/ArrayContext.php <ide> */ <ide> namespace Cake\View\Form; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\Utility\Hash; <ide> <ide> /** <ide> * <ide> * Important keys: <ide> * <add> * - `data` Holds the current values supplied for the fields. <ide> * - `defaults` The default values for fields. These values <del> * will be used when there is no request data set. Data should be nested following <add> * will be used when there is no data set. Data should be nested following <ide> * the dot separated paths you access your fields with. <ide> * - `required` A nested array of fields, relationships and boolean <ide> * flags to indicate a field is required. The value can also be a string to be used <ide> * ### Example <ide> * <ide> * ``` <del> * $data = [ <add> * $article = [ <add> * 'data' => [ <add> * 'id' => '1', <add> * 'title' => 'First post!', <add> * ], <ide> * 'schema' => [ <ide> * 'id' => ['type' => 'integer'], <ide> * 'title' => ['type' => 'string', 'length' => 255], <ide> * ] <ide> * ], <ide> * 'defaults' => [ <del> * 'id' => 1, <del> * 'title' => 'First post!', <add> * 'title' => 'Default title', <ide> * ], <ide> * 'required' => [ <ide> * 'id' => true, // will use default required message <ide> */ <ide> class ArrayContext implements ContextInterface <ide> { <del> /** <del> * The request object. <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $_request; <del> <ide> /** <ide> * Context data for this object. <ide> * <ide> class ArrayContext implements ContextInterface <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\ServerRequest $request The request object. <ide> * @param array $context Context info. <ide> */ <del> public function __construct(ServerRequest $request, array $context) <add> public function __construct(array $context) <ide> { <del> $this->_request = $request; <ide> $context += [ <add> 'data' => [], <ide> 'schema' => [], <ide> 'required' => [], <ide> 'defaults' => [], <ide> public function isCreate(): bool <ide> /** <ide> * Get the current value for a given field. <ide> * <del> * This method will coalesce the current request data and the 'defaults' <del> * array. <add> * This method will coalesce the current data and the 'defaults' array. <ide> * <ide> * @param string $field A dot separated path to the field a value <ide> * is needed for. <ide> * @param array $options Options: <ide> * <del> * - `default`: Default value to return if no value found in request <del> * data or context record. <add> * - `default`: Default value to return if no value found in data or <add> * context record. <ide> * - `schemaDefault`: Boolean indicating whether default value from <del> * context's schema should be used if it's not explicitly provided. <add> * context's schema should be used if it's not explicitly provided. <ide> * <ide> * @return mixed <ide> */ <ide> public function val(string $field, array $options = []) <ide> 'schemaDefault' => true, <ide> ]; <ide> <del> $val = $this->_request->getData($field); <del> if ($val !== null) { <del> return $val; <add> if (Hash::check($this->_context['data'], $field)) { <add> return Hash::get($this->_context['data'], $field); <ide> } <add> <ide> if ($options['default'] !== null || !$options['schemaDefault']) { <ide> return $options['default']; <ide> } <ide><path>src/View/Form/ContextFactory.php <ide> use Cake\Collection\Collection; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Form\Form; <del>use Cake\Http\ServerRequest; <ide> use RuntimeException; <ide> <ide> /** <ide> public static function createWithDefaults(array $providers = []) <ide> $providers = [ <ide> [ <ide> 'type' => 'orm', <del> 'callable' => function ($request, $data) { <add> 'callable' => function ($data) { <ide> if ($data['entity'] instanceof EntityInterface) { <del> return new EntityContext($request, $data); <add> return new EntityContext($data); <ide> } <ide> if (isset($data['table'])) { <del> return new EntityContext($request, $data); <add> return new EntityContext($data); <ide> } <ide> if (is_iterable($data['entity'])) { <ide> $pass = (new Collection($data['entity']))->first() !== null; <ide> if ($pass) { <del> return new EntityContext($request, $data); <add> return new EntityContext($data); <ide> } else { <del> return new NullContext($request, $data); <add> return new NullContext($data); <ide> } <ide> } <ide> }, <ide> ], <ide> [ <ide> 'type' => 'form', <del> 'callable' => function ($request, $data) { <add> 'callable' => function ($data) { <ide> if ($data['entity'] instanceof Form) { <del> return new FormContext($request, $data); <add> return new FormContext($data); <ide> } <ide> }, <ide> ], <ide> [ <ide> 'type' => 'array', <del> 'callable' => function ($request, $data) { <add> 'callable' => function ($data) { <ide> if (is_array($data['entity']) && isset($data['entity']['schema'])) { <del> return new ArrayContext($request, $data['entity']); <add> return new ArrayContext($data['entity']); <ide> } <ide> }, <ide> ], <ide> [ <ide> 'type' => 'null', <del> 'callable' => function ($request, $data) { <add> 'callable' => function ($data) { <ide> if ($data['entity'] === null) { <del> return new NullContext($request, $data); <add> return new NullContext($data); <ide> } <ide> }, <ide> ], <ide> public function addProvider(string $type, callable $check) <ide> * <ide> * If no type can be matched a NullContext will be returned. <ide> * <del> * @param \Cake\Http\ServerRequest $request Request instance. <ide> * @param array $data The data to get a context provider for. <ide> * @return \Cake\View\Form\ContextInterface Context provider. <ide> * @throws \RuntimeException When a context instace cannot be generated for given entity. <ide> */ <del> public function get(ServerRequest $request, array $data = []): ContextInterface <add> public function get(array $data = []): ContextInterface <ide> { <ide> $data += ['entity' => null]; <ide> <ide> foreach ($this->providers as $provider) { <ide> $check = $provider['callable']; <del> $context = $check($request, $data); <add> $context = $check($data); <ide> if ($context) { <ide> break; <ide> } <ide><path>src/View/Form/ContextInterface.php <ide> public function isCreate(): bool; <ide> * Classes implementing this method can optionally have a second argument <ide> * `$options`. Valid key for `$options` array are: <ide> * <del> * - `default`: Default value to return if no value found in request <del> * data or context record. <add> * - `default`: Default value to return if no value found in data or <add> * context record. <ide> * - `schemaDefault`: Boolean indicating whether default value from <del> * context's schema should be used if it's not explicitly provided. <add> * context's schema should be used if it's not explicitly provided. <ide> * <ide> * @param string $field A dot separated path to the field a value <ide> * @param array $options Options. <ide><path>src/View/Form/EntityContext.php <ide> use ArrayAccess; <ide> use Cake\Collection\Collection; <ide> use Cake\Datasource\EntityInterface; <del>use Cake\Http\ServerRequest; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <ide> use Cake\ORM\Table; <ide> class EntityContext implements ContextInterface <ide> { <ide> use LocatorAwareTrait; <ide> <del> /** <del> * The request object. <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $_request; <del> <ide> /** <ide> * Context data for this object. <ide> * <ide> class EntityContext implements ContextInterface <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\ServerRequest $request The request object. <ide> * @param array $context Context info. <ide> */ <del> public function __construct(ServerRequest $request, array $context) <add> public function __construct(array $context) <ide> { <del> $this->_request = $request; <ide> $context += [ <ide> 'entity' => null, <ide> 'table' => null, <ide> public function isCreate(): bool <ide> * @param string $field The dot separated path to the value. <ide> * @param array $options Options: <ide> * <del> * - `default`: Default value to return if no value found in request <del> * data or entity. <add> * - `default`: Default value to return if no value found in data or <add> * entity. <ide> * - `schemaDefault`: Boolean indicating whether default value from table <ide> * schema should be used if it's not explicitly provided. <ide> * <ide> public function val(string $field, array $options = []) <ide> 'schemaDefault' => true, <ide> ]; <ide> <del> $val = $this->_request->getData($field); <del> if ($val !== null) { <del> return $val; <del> } <ide> if (empty($this->_context['entity'])) { <ide> return $options['default']; <ide> } <ide> public function val(string $field, array $options = []) <ide> <ide> if ($entity instanceof EntityInterface) { <ide> $part = end($parts); <add> <add> $val = $entity->getInvalidField($part); <add> if ($val !== null) { <add> return $val; <add> } <add> <ide> $val = $entity->get($part); <ide> if ($val !== null) { <ide> return $val; <ide><path>src/View/Form/FormContext.php <ide> */ <ide> namespace Cake\View\Form; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\Utility\Hash; <ide> <ide> /** <ide> * Provides a context provider for Cake\Form\Form instances. <ide> * <ide> * This context provider simply fulfils the interface requirements <del> * that FormHelper has and allows access to the request data. <add> * that FormHelper has and allows access to the form data. <ide> */ <ide> class FormContext implements ContextInterface <ide> { <del> /** <del> * The request object. <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $_request; <del> <ide> /** <ide> * The form object. <ide> * <ide> class FormContext implements ContextInterface <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\ServerRequest $request The request object. <ide> * @param array $context Context info. <ide> */ <del> public function __construct(ServerRequest $request, array $context) <add> public function __construct(array $context) <ide> { <del> $this->_request = $request; <ide> $context += [ <ide> 'entity' => null, <ide> ]; <ide> public function val(string $field, array $options = []) <ide> 'schemaDefault' => true, <ide> ]; <ide> <del> $val = $this->_request->getData($field); <del> if ($val !== null) { <del> return $val; <del> } <del> <ide> $val = $this->_form->getData($field); <ide> if ($val !== null) { <ide> return $val; <ide><path>src/View/Form/NullContext.php <ide> */ <ide> namespace Cake\View\Form; <ide> <del>use Cake\Http\ServerRequest; <del> <ide> /** <ide> * Provides a context provider that does nothing. <ide> * <ide> * This context provider simply fulfils the interface requirements <del> * that FormHelper has and allows access to the request data. <add> * that FormHelper has. <ide> */ <ide> class NullContext implements ContextInterface <ide> { <del> /** <del> * The request object. <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $_request; <del> <ide> /** <ide> * Constructor. <ide> * <ide> * @param \Cake\Http\ServerRequest $request The request object. <ide> * @param array $context Context info. <ide> */ <del> public function __construct(ServerRequest $request, array $context) <add> public function __construct(array $context) <ide> { <del> $this->_request = $request; <ide> } <ide> <ide> /** <ide> public function isCreate(): bool <ide> */ <ide> public function val(string $field, array $options = []) <ide> { <del> return $this->_request->getData($field); <add> return null; <ide> } <ide> <ide> /** <ide><path>src/View/Helper/FormHelper.php <ide> class FormHelper extends Helper <ide> * <ide> * @var string[] <ide> */ <del> protected $_valueSources = ['context']; <add> protected $_valueSources = ['data', 'context']; <ide> <ide> /** <ide> * Grouped input types. <ide> public function end(array $secureAttributes = []): string <ide> $this->templater()->pop(); <ide> $this->requestType = null; <ide> $this->_context = null; <del> $this->_valueSources = ['context']; <add> $this->_valueSources = ['data', 'context']; <ide> $this->_idPrefix = $this->getConfig('idPrefix'); <ide> $this->formProtector = null; <ide> <ide> protected function _getContext($data = []): ContextInterface <ide> $data += ['entity' => null]; <ide> <ide> return $this->_context = $this->contextFactory() <del> ->get($this->_View->getRequest(), $data); <add> ->get($data); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Form/ArrayContextTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Form; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\ArrayContext; <ide> <ide> */ <ide> class ArrayContextTest extends TestCase <ide> { <del> /** <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $request; <del> <ide> /** <ide> * setup method. <ide> * <ide> class ArrayContextTest extends TestCase <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <del> $this->request = new ServerRequest(); <ide> } <ide> <ide> public function testGetRequiredMessage() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'required' => [ <ide> 'Comments' => [ <ide> 'required' => 'My custom message', <ide> public function testGetRequiredMessage() <ide> */ <ide> public function testPrimaryKey() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertEquals([], $context->getPrimaryKey()); <ide> <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'schema' => [ <ide> '_constraints' => 'mistake', <ide> ], <ide> public function testPrimaryKey() <ide> ], <ide> ], <ide> ]; <del> $context = new ArrayContext($this->request, $data); <add> $context = new ArrayContext($data); <ide> <ide> $expected = ['id']; <ide> $this->assertEquals($expected, $context->getPrimaryKey()); <ide> public function testPrimaryKey() <ide> */ <ide> public function testIsPrimaryKey() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertFalse($context->isPrimaryKey('id')); <ide> <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'schema' => [ <ide> '_constraints' => 'mistake', <ide> ], <ide> public function testIsPrimaryKey() <ide> ], <ide> ], <ide> ]; <del> $context = new ArrayContext($this->request, $data); <add> $context = new ArrayContext($data); <ide> $this->assertTrue($context->isPrimaryKey('id')); <ide> $this->assertFalse($context->isPrimaryKey('name')); <ide> <ide> public function testIsPrimaryKey() <ide> ], <ide> ], <ide> ]; <del> $context = new ArrayContext($this->request, $data); <add> $context = new ArrayContext($data); <ide> $this->assertTrue($context->isPrimaryKey('id')); <ide> $this->assertTrue($context->isPrimaryKey('name')); <ide> } <ide> public function testIsPrimaryKey() <ide> */ <ide> public function testIsCreate() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertTrue($context->isCreate()); <ide> <ide> $data = [ <ide> public function testIsCreate() <ide> ], <ide> ], <ide> ]; <del> $context = new ArrayContext($this->request, $data); <add> $context = new ArrayContext($data); <ide> $this->assertTrue($context->isCreate()); <ide> <ide> $data['defaults'] = ['id' => 2]; <del> $context = new ArrayContext($this->request, $data); <add> $context = new ArrayContext($data); <ide> $this->assertFalse($context->isCreate()); <ide> } <ide> <ide> /** <del> * Test reading values from the request & defaults. <add> * Test reading values from data & defaults. <ide> */ <ide> public function testValPresent() <ide> { <del> $this->request = $this->request->withParsedBody([ <del> 'Articles' => [ <del> 'title' => 'New title', <del> 'body' => 'My copy', <add> $context = new ArrayContext([ <add> 'data' => [ <add> 'Articles' => [ <add> 'title' => 'New title', <add> 'body' => 'My copy', <add> ], <ide> ], <del> ]); <del> $context = new ArrayContext($this->request, [ <ide> 'defaults' => [ <ide> 'Articles' => [ <ide> 'title' => 'Default value', <ide> public function testValPresent() <ide> } <ide> <ide> /** <del> * Test getting values when the request and defaults are missing. <add> * Test getting values when the data and defaults are missing. <ide> * <ide> * @return void <ide> */ <ide> public function testValMissing() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertNull($context->val('Comments.field')); <ide> } <ide> <ide> public function testValMissing() <ide> */ <ide> public function testValDefault() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'defaults' => [ <ide> 'title' => 'Default value', <ide> 'users' => ['tags' => 'common1', '9tags' => 'common2'], <ide> public function testValDefault() <ide> */ <ide> public function testIsRequired() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'required' => [ <ide> 'Comments' => [ <ide> 'required' => true, <ide> public function testIsRequired() <ide> */ <ide> public function testIsRequiredUndefined() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertNull($context->isRequired('Comments.field')); <ide> } <ide> <ide> public function testIsRequiredUndefined() <ide> */ <ide> public function testType() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'schema' => [ <ide> 'Comments' => [ <ide> 'id' => ['type' => 'integer'], <ide> public function testType() <ide> */ <ide> public function testIsTypeUndefined() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertNull($context->type('Comments.undefined')); <ide> } <ide> <ide> public function testIsTypeUndefined() <ide> */ <ide> public function testAttributes() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'schema' => [ <ide> 'Comments' => [ <ide> 'id' => ['type' => 'integer'], <ide> public function testAttributes() <ide> */ <ide> public function testError() <ide> { <del> $context = new ArrayContext($this->request, []); <add> $context = new ArrayContext([]); <ide> $this->assertEquals([], $context->error('Comments.empty')); <ide> <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'errors' => [ <ide> 'Comments' => [ <ide> 'comment' => ['Comment is required'], <ide> public function testError() <ide> */ <ide> public function testHasError() <ide> { <del> $context = new ArrayContext($this->request, [ <add> $context = new ArrayContext([ <ide> 'errors' => [ <ide> 'Comments' => [ <ide> 'comment' => ['Comment is required'], <ide><path>tests/TestCase/View/Form/ContextFactoryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Form; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\ContextFactory; <ide> <ide> public function testGetException() <ide> ); <ide> <ide> $factory = new ContextFactory(); <del> $factory->get(new ServerRequest(), ['entity' => false]); <add> $factory->get(['entity' => false]); <ide> } <ide> } <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> use ArrayIterator; <ide> use ArrayObject; <ide> use Cake\Collection\Collection; <del>use Cake\Http\ServerRequest; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validator; <ide> class EntityContextTest extends TestCase <ide> */ <ide> protected $fixtures = ['core.Articles', 'core.Comments', 'core.ArticlesTags', 'core.Tags']; <ide> <del> /** <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $request; <del> <ide> /** <ide> * setup method. <ide> * <ide> class EntityContextTest extends TestCase <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <del> $this->request = new ServerRequest(); <ide> } <ide> <ide> /** <ide> public function testGetRequiredMessage() <ide> { <ide> $this->_setupTables(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Article(), <ide> 'table' => 'Articles', <ide> 'validator' => 'create', <ide> public function testGetRequiredMessage() <ide> public function testEntity() <ide> { <ide> $row = new Article(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> $this->assertSame($row, $context->entity()); <ide> public function testEntity() <ide> public function testPrimaryKey() <ide> { <ide> $row = new Article(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> $this->assertEquals(['id'], $context->getPrimaryKey()); <ide> public function testIsPrimaryKey() <ide> $this->_setupTables(); <ide> <ide> $row = new Article(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> $this->assertTrue($context->isPrimaryKey('id')); <ide> public function testIsPrimaryKey() <ide> public function testIsCreateSingle() <ide> { <ide> $row = new Article(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> $this->assertTrue($context->isCreate()); <ide> public function testIsCreateSingle() <ide> */ <ide> public function testIsCreateCollection($collection) <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> ]); <ide> $this->assertTrue($context->isCreate()); <ide> public function testInvalidTable() <ide> $this->expectException(\RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to find table class for current entity'); <ide> $row = new \stdClass(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> } <ide> public function testDefaultEntityError() <ide> { <ide> $this->expectException(\RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to find table class for current entity'); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Entity(), <ide> ]); <ide> } <ide> public function testTableFromEntitySource() <ide> { <ide> $entity = new Entity(); <ide> $entity->setSource('Articles'); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $entity, <ide> ]); <ide> $expected = ['id', 'author_id', 'title', 'body', 'published']; <ide> public function testTableFromEntitySource() <ide> */ <ide> public function testOperationsNoEntity() <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'table' => 'Articles', <ide> ]); <ide> <ide> public function testOperationsNoTableArg() <ide> ]); <ide> $row->setError('title', ['Title is required.']); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> <ide> public function testOperationsNoTableArg() <ide> */ <ide> public function testCollectionOperationsNoTableArg($collection) <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> ]); <ide> <ide> public static function collectionProvider() <ide> */ <ide> public function testValOnCollections($collection) <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValOnCollections($collection) <ide> */ <ide> public function testValOnCollectionsWithRootName($collection) <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValOnCollectionsWithRootName($collection) <ide> */ <ide> public function testErrorsOnCollections($collection) <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testErrorsOnCollections($collection) <ide> public function testSchemaOnCollections($collection) <ide> { <ide> $this->_setupTables(); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValidatorsOnCollections($collection) <ide> { <ide> $this->_setupTables(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $collection, <ide> 'table' => 'Articles', <ide> 'validator' => [ <ide> public function testValBasic() <ide> 'title' => 'Test entity', <ide> 'body' => 'Something new', <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValBasic() <ide> $this->assertNull($result); <ide> } <ide> <add> /** <add> * Test reading invalid data. <add> * <add> * @return void <add> */ <add> public function testValInvalid() <add> { <add> $row = new Article([ <add> 'title' => 'Valid title', <add> ]); <add> $row->setInvalidField('title', 'Invalid title'); <add> <add> $context = new EntityContext([ <add> 'entity' => $row, <add> 'table' => 'Articles', <add> ]); <add> $result = $context->val('title'); <add> $this->assertEquals('Invalid title', $result); <add> } <add> <ide> /** <ide> * Test default values when entity is an array. <ide> * <ide> * @return void <ide> */ <ide> public function testValDefaultArray() <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Article([ <ide> 'prop' => ['title' => 'foo'], <ide> ]), <ide> public function testValGetArrayValue() <ide> 'aliases' => new ArrayObject(['dave', 'david']), <ide> ]), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValGetArrayValue() <ide> $this->assertNull($context->val('author.roles.3')); <ide> } <ide> <del> /** <del> * Test that val() reads from the request. <del> * <del> * @return void <del> */ <del> public function testValReadsRequest() <del> { <del> $this->request = $this->request->withParsedBody([ <del> 'title' => 'New title', <del> 'notInEntity' => 'yes', <del> ]); <del> $row = new Article([ <del> 'title' => 'Test entity', <del> 'body' => 'Something new', <del> ]); <del> $context = new EntityContext($this->request, [ <del> 'entity' => $row, <del> 'table' => 'Articles', <del> ]); <del> $this->assertSame('New title', $context->val('title')); <del> $this->assertSame('yes', $context->val('notInEntity')); <del> $this->assertEquals($row->body, $context->val('body')); <del> } <del> <ide> /** <ide> * Test reading values from associated entities. <ide> * <ide> public function testValAssociated() <ide> new Entity(['comment' => 'Second comment']), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValMissingAssociation() <ide> $row = new Article([ <ide> 'id' => 1, <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValAssociatedHasMany() <ide> ], <ide> ]), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValAssociatedDefaultIds() <ide> ], <ide> ]), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValAssociatedCustomIds() <ide> ], <ide> ]), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValSchemaDefault() <ide> $table->getSchema()->addColumn('title', ['default' => 'default title'] + $column); <ide> $row = $table->newEmptyEntity(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValAssociatedSchemaDefault() <ide> $associatedTable->getSchema()->addColumn('comment', ['default' => 'default comment'] + $column); <ide> $row = $table->newEmptyEntity(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValAssociatedJoinTableSchemaDefault() <ide> ]); <ide> $row = $table->newEmptyEntity(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testIsRequiredBooleanField() <ide> { <ide> $this->_setupTables(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Entity(), <ide> 'table' => 'Articles', <ide> ]); <ide> public function testIsRequiredStringValidator() <ide> { <ide> $this->_setupTables(); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Entity(), <ide> 'table' => 'Articles', <ide> 'validator' => 'create', <ide> public function testIsRequiredAssociatedHasMany() <ide> new Entity(['comment' => 'Second comment']), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => 'default', <ide> public function testIsRequiredAssociatedHasManyBoolean() <ide> new Entity(['comment' => 'First comment']), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => 'default', <ide> public function testIsRequiredAssociatedCustomValidator() <ide> $row = new Entity([ <ide> 'username' => 'mark', <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Users', <ide> 'validator' => 'default', <ide> public function testIsRequiredAssociatedHasManyMissingObject() <ide> new Entity(['comment' => 'First comment'], ['markNew' => false]), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => 'default', <ide> public function testIsRequiredAssociatedValidator() <ide> new Entity(['comment' => 'Second comment']), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => [ <ide> public function testIsRequiredAssociatedBelongsTo() <ide> 'title' => 'My title', <ide> 'user' => new Entity(['username' => 'Mark']), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => [ <ide> public function testIsRequiredAssociatedJoinTable() <ide> ]), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testType() <ide> 'title' => 'My title', <ide> 'body' => 'Some content', <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testTypeAssociated() <ide> 'title' => 'My title', <ide> 'user' => new Entity(['username' => 'Mark']), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testTypeAssociatedJoinData() <ide> ]), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testAttributes() <ide> ]), <ide> ], <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testHasError() <ide> $row->setError('title', []); <ide> $row->setError('body', 'Gotta have one'); <ide> $row->setError('user_id', ['Required field']); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testHasErrorAssociated() <ide> $row->setError('title', []); <ide> $row->setError('body', 'Gotta have one'); <ide> $row->user->setError('username', ['Required']); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testError() <ide> <ide> $row->user->setError('username', ['Required']); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testErrorAssociatedHasMany() <ide> $row->comments[0]->setError('comment', ['Is required']); <ide> $row->comments[0]->setError('article_id', ['Is required']); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> 'validator' => 'default', <ide> public function testErrorAssociatedJoinTable() <ide> ]); <ide> $row->tags[0]->_joinData->setError('tag_id', ['Is required']); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testErrorNestedValidator() <ide> ]); <ide> $row->setError('options', ['subpages' => ['_empty' => 'required value']]); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testErrorAssociatedNestedValidator() <ide> ], <ide> ]); <ide> <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> protected function _setupTables() <ide> */ <ide> public function testFieldNames() <ide> { <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => new Entity(), <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValidatorEntityProvider() <ide> 'title' => 'Test entity', <ide> 'body' => 'Something new', <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide> public function testValidatorEntityProvider() <ide> ], <ide> ]), <ide> ]); <del> $context = new EntityContext($this->request, [ <add> $context = new EntityContext([ <ide> 'entity' => $row, <ide> 'table' => 'Articles', <ide> ]); <ide><path>tests/TestCase/View/Form/FormContextTest.php <ide> namespace Cake\Test\TestCase\View\Form; <ide> <ide> use Cake\Form\Form; <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validator; <ide> use Cake\View\Form\FormContext; <ide> */ <ide> class FormContextTest extends TestCase <ide> { <del> /** <del> * The request object. <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> protected $request; <del> <ide> /** <ide> * setup method. <ide> * <ide> class FormContextTest extends TestCase <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <del> $this->request = new ServerRequest(); <ide> } <ide> <ide> /** <ide> public function testGetRequiredMessage() <ide> $form = new Form(); <ide> $form->setValidator(Form::DEFAULT_VALIDATOR, $validator); <ide> <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> <ide> public function testGetRequiredMessage() <ide> */ <ide> public function testPrimaryKey() <ide> { <del> $context = new FormContext($this->request, ['entity' => new Form()]); <add> $context = new FormContext(['entity' => new Form()]); <ide> $this->assertEquals([], $context->getPrimaryKey()); <ide> } <ide> <ide> public function testPrimaryKey() <ide> */ <ide> public function testIsPrimaryKey() <ide> { <del> $context = new FormContext($this->request, ['entity' => new Form()]); <add> $context = new FormContext(['entity' => new Form()]); <ide> $this->assertFalse($context->isPrimaryKey('id')); <ide> } <ide> <ide> public function testIsPrimaryKey() <ide> */ <ide> public function testIsCreate() <ide> { <del> $context = new FormContext($this->request, ['entity' => new Form()]); <add> $context = new FormContext(['entity' => new Form()]); <ide> $this->assertTrue($context->isCreate()); <ide> } <ide> <del> /** <del> * Test reading values from the request & defaults. <del> */ <del> public function testValPresent() <del> { <del> $this->request = $this->request->withParsedBody([ <del> 'Articles' => [ <del> 'title' => 'New title', <del> 'body' => 'My copy', <del> ], <del> ]); <del> $context = new FormContext($this->request, ['entity' => new Form()]); <del> $this->assertSame('New title', $context->val('Articles.title')); <del> $this->assertSame('My copy', $context->val('Articles.body')); <del> $this->assertNull($context->val('Articles.nope')); <del> } <del> <ide> /** <ide> * Test reading values from form data. <ide> */ <del> public function testValPresentInForm() <add> public function testValPresent() <ide> { <ide> $form = new Form(); <ide> $form->setData(['title' => 'set title']); <ide> <del> $context = new FormContext($this->request, ['entity' => $form]); <add> $context = new FormContext(['entity' => $form]); <ide> <ide> $this->assertSame('set title', $context->val('title')); <del> $this->assertNull($context->val('Articles.body')); <del> <del> $this->request = $this->request->withParsedBody([ <del> 'title' => 'New title', <del> ]); <del> $context = new FormContext($this->request, ['entity' => $form]); <del> <del> $this->assertSame('New title', $context->val('title')); <ide> } <ide> <ide> /** <del> * Test getting values when the request and defaults are missing. <add> * Test getting values when data and defaults are missing. <ide> * <ide> * @return void <ide> */ <ide> public function testValMissing() <ide> { <del> $context = new FormContext($this->request, ['entity' => new Form()]); <add> $context = new FormContext(['entity' => new Form()]); <ide> $this->assertNull($context->val('Comments.field')); <ide> } <ide> <ide> public function testValDefault() <ide> { <ide> $form = new Form(); <ide> $form->getSchema()->addField('name', ['default' => 'schema default']); <del> $context = new FormContext($this->request, ['entity' => $form]); <add> $context = new FormContext(['entity' => $form]); <ide> <ide> $result = $context->val('title'); <ide> $this->assertNull($result); <ide> public function testIsRequired() <ide> ->requirePresence('name') <ide> ->add('email', 'format', ['rule' => 'email']); <ide> <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> $this->assertTrue($context->isRequired('name')); <ide> public function testType() <ide> ->addField('email', 'string') <ide> ->addField('user_id', 'integer'); <ide> <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> $this->assertNull($context->type('undefined')); <ide> public function testType() <ide> public function testFieldNames() <ide> { <ide> $form = new Form(); <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> $expected = []; <ide> public function testFieldNames() <ide> $form->getSchema() <ide> ->addField('email', 'string') <ide> ->addField('password', 'string'); <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> <ide> public function testAttributes() <ide> 'length' => 5, <ide> 'precision' => 2, <ide> ]); <del> $context = new FormContext($this->request, [ <add> $context = new FormContext([ <ide> 'entity' => $form, <ide> ]); <ide> $this->assertEquals([], $context->attributes('id')); <ide> public function testError() <ide> ], <ide> ]); <ide> <del> $context = new FormContext($this->request, ['entity' => $form]); <add> $context = new FormContext(['entity' => $form]); <ide> $this->assertEquals([], $context->error('empty')); <ide> $this->assertEquals(['format' => 'The provided value is invalid'], $context->error('email')); <ide> $this->assertEquals(['length' => 'The provided value is invalid'], $context->error('name')); <ide> public function testError() <ide> $validator->requirePresence('key', true, 'should be an array, not a string'); <ide> $form->setValidator('default', $validator); <ide> $form->validate([]); <del> $context = new FormContext($this->request, ['entity' => $form]); <add> $context = new FormContext(['entity' => $form]); <ide> $this->assertEquals( <ide> ['_required' => 'should be an array, not a string'], <ide> $context->error('key'), <ide> public function testHasError() <ide> ], <ide> ]); <ide> <del> $context = new FormContext($this->request, ['entity' => $form]); <add> $context = new FormContext(['entity' => $form]); <ide> $this->assertTrue($context->hasError('email')); <ide> $this->assertTrue($context->hasError('name')); <ide> $this->assertFalse($context->hasError('nope')); <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddContextProvider() <ide> { <ide> $context = 'My data'; <ide> $stub = $this->getMockBuilder('Cake\View\Form\ContextInterface')->getMock(); <del> $this->Form->addContextProvider('test', function ($request, $data) use ($context, $stub) { <del> $this->assertInstanceOf('Cake\Http\ServerRequest', $request); <add> $this->Form->addContextProvider('test', function ($data) use ($context, $stub) { <ide> $this->assertEquals($context, $data['entity']); <ide> <ide> return $stub; <ide> public function testAddContextProviderReplace() <ide> { <ide> $entity = new Article(); <ide> $stub = $this->getMockBuilder('Cake\View\Form\ContextInterface')->getMock(); <del> $this->Form->addContextProvider('orm', function ($request, $data) use ($stub) { <add> $this->Form->addContextProvider('orm', function ($data) use ($stub) { <ide> return $stub; <ide> }); <ide> $this->Form->create($entity); <ide> public function testAddContextProviderAdd() <ide> { <ide> $entity = new Article(); <ide> $stub = $this->getMockBuilder('Cake\View\Form\ContextInterface')->getMock(); <del> $this->Form->addContextProvider('newshiny', function ($request, $data) use ($stub) { <add> $this->Form->addContextProvider('newshiny', function ($data) use ($stub) { <ide> if ($data['entity'] instanceof Entity) { <ide> return $stub; <ide> } <ide> public function testAddContextProviderInvalid() <ide> $this->expectException(\TypeError::class); <ide> $this->expectExceptionMessage('Return value of Cake\View\Form\ContextFactory::get() must implement interface Cake\View\Form\ContextInterface, instance of stdClass returned'); <ide> $context = 'My data'; <del> $this->Form->addContextProvider('test', function ($request, $data) use ($context) { <add> $this->Form->addContextProvider('test', function ($data) use ($context) { <ide> return new \stdClass(); <ide> }); <ide> $this->Form->create($context); <ide> public function testFormValueSourcesSettersGetters() <ide> ->withData('id', '1') <ide> ->withQueryParams(['id' => '2'])); <ide> <del> $expected = ['context']; <add> $expected = ['data', 'context']; <ide> $result = $this->Form->getValueSources(); <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testFormValueSourcesSettersGetters() <ide> $this->assertEquals($expected, $result); <ide> <ide> $this->Form->setValueSources(['context']); <del> $expected = '1'; <ide> $result = $this->Form->getSourceValue('id'); <del> $this->assertEquals($expected, $result); <add> $this->assertNull($result); <ide> <ide> $this->Form->setValueSources('query'); <ide> $expected = ['query']; <ide> public function testFormValueSourcesSingleSwitchRendering() <ide> $this->Form->create($article); <ide> $result = $this->Form->control('id'); <ide> $expected = [ <del> ['input' => ['type' => 'hidden', 'name' => 'id', 'id' => 'id', 'value' => '5b']], <add> ['input' => ['type' => 'hidden', 'name' => 'id', 'id' => 'id', 'value' => '3']], <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <ide> public function testFormValueSourcesSwitchViaOptionsRendering() <ide> $this->Form->create($article, ['valueSources' => ['context', 'data']]); <ide> $result = $this->Form->control('id'); <ide> $expected = [ <del> ['input' => ['type' => 'hidden', 'name' => 'id', 'id' => 'id', 'value' => '4']], <add> ['input' => ['type' => 'hidden', 'name' => 'id', 'id' => 'id', 'value' => '3']], <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> $result = $this->Form->getSourceValue('id'); <del> $this->assertSame('4', $result); <add> $this->assertSame(3, $result); <ide> } <ide> <ide> /** <ide> public function testFormValueSourcesSwitchViaOptionsAndSetterRendering() <ide> */ <ide> public function testFormValueSourcesResetViaEnd() <ide> { <del> $expected = ['context']; <add> $expected = ['data', 'context']; <ide> $result = $this->Form->getValueSources(); <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testFormValueSourcesResetViaEnd() <ide> <ide> $this->Form->end(); <ide> $result = $this->Form->getValueSources(); <del> $this->assertEquals(['context'], $result); <add> $this->assertEquals(['data', 'context'], $result); <ide> } <ide> <ide> /** <ide> public function testControlMaxLengthEntityContext() <ide> $validator = new Validator(); <ide> $validator->maxLength('title', 10); <ide> $article = new EntityContext( <del> new ServerRequest(), <ide> [ <ide> 'entity' => new Entity($this->article), <ide> 'table' => new Table([ <ide> public function testControlMaxLengthEntityContext() <ide> $validator = new Validator(); <ide> $validator->maxLength('title', 55); <ide> $article = new EntityContext( <del> new ServerRequest(), <ide> [ <ide> 'entity' => new Entity($this->article), <ide> 'table' => new Table([ <ide> public function testControlMaxLengthEntityContext() <ide> $validator = new Validator(); <ide> $validator->maxLength('title', 55); <ide> $article = new EntityContext( <del> new ServerRequest(), <ide> [ <ide> 'entity' => new Entity($this->article), <ide> 'table' => new Table([ <ide> public function testControlMinMaxLengthEntityContext() <ide> $validator = new Validator(); <ide> $validator->maxLength('title', 10); <ide> $article = new EntityContext( <del> new ServerRequest(), <ide> [ <ide> 'entity' => new Entity($this->article), <ide> 'table' => new Table([ <ide><path>tests/TestCase/View/Widget/BasicWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/ButtonWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'button' => '<button{{attrs}}>{{text}}</button>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/CheckboxWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> $this->DateTime = new DateTimeWidget($this->templates); <ide> } <ide> <ide><path>tests/TestCase/View/Widget/FileWidgetTest.php <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <ide> use Cake\Core\Configure; <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'file' => '<input type="file" name="{{name}}"{{attrs}}>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/LabelWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'label' => '<label{{attrs}}>{{text}}</label>', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/MultiCheckboxWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'selectedClass' => 'selected', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/RadioWidgetTest.php <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <ide> use Cake\Collection\Collection; <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'selectedClass' => 'selected', <ide> ]; <ide> $this->templates = new StringTemplate($templates); <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <ide> use Cake\Collection\Collection; <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>', <ide> 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>', <ide> ]; <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide><path>tests/TestCase/View/Widget/TextareaWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <del>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> public function setUp(): void <ide> $templates = [ <ide> 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>', <ide> ]; <del> $this->context = new NullContext(new ServerRequest(), []); <add> $this->context = new NullContext([]); <ide> $this->templates = new StringTemplate($templates); <ide> } <ide>
23
Java
Java
fix checkstyle error
e72f4ec501f2bcf37931628cc44d48db03607609
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseCookie.java <ide> public interface ResponseCookieBuilder { <ide> * attached to same site requests if {@code "Strict"} or cross-site <ide> * requests if {@code "Lax"}. <ide> * <p>By default set to {@code "Strict"}. <del> * @see <a href="https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis#section-4.1.2.7">RFC6265 bis</a> <ide> * @since 5.1 <add> * @see <a href="https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis#section-4.1.2.7">RFC6265 bis</a> <ide> */ <ide> ResponseCookieBuilder sameSite(@Nullable String sameSite); <ide>
1
Text
Text
add strategic initiative for shadow realm
5a3de828c92f989b54b688fa90fdf8ba8e4180ae
<ide><path>doc/contributing/strategic-initiatives.md <ide> agenda to ensure they are active and have the support they need. <ide> | ------------------- | --------------------------- | --------------------------------------------- | <ide> | Core Promise APIs | [Antoine du Hamel][aduh95] | <https://github.com/nodejs/TSC/issues/1094> | <ide> | QUIC / HTTP3 | [James M Snell][jasnell] | <https://github.com/nodejs/quic> | <add>| Shadow Realm | [Chengzhong Wu][legendecas] | <https://github.com/nodejs/node/issues/42528> | <ide> | Startup performance | [Joyee Cheung][joyeecheung] | <https://github.com/nodejs/node/issues/35711> | <ide> | V8 Currency | [Michaël Zasso][targos] | | <ide> | Next-10 | [Michael Dawson][mhdawson] | <https://github.com/nodejs/next-10> | <ide> agenda to ensure they are active and have the support they need. <ide> [aduh95]: https://github.com/aduh95 <ide> [jasnell]: https://github.com/jasnell <ide> [joyeecheung]: https://github.com/joyeecheung <add>[legendecas]: https://github.com/legendecas <ide> [mhdawson]: https://github.com/mhdawson <ide> [targos]: https://github.com/targos
1
Javascript
Javascript
update the legend object during beforeupdate
537cd749192a211225414804ba0f38a2c6f1811c
<ide><path>src/plugins/plugin.legend.js <ide> export default { <ide> } <ide> }, <ide> <del> afterUpdate(chart) { <add> // During the beforeUpdate step, the layout configuration needs to run <add> // This ensures that if the legend position changes (via an option update) <add> // the layout system respects the change. See https://github.com/chartjs/Chart.js/issues/7527 <add> beforeUpdate(chart) { <ide> const legendOpts = chart.options.legend; <ide> const legend = chart.legend; <ide> <ide> export default { <ide> if (legend) { <ide> layouts.configure(chart, legend, legendOpts); <ide> legend.options = legendOpts; <del> legend.buildLabels(); <ide> } else { <ide> createNewLegendAndAttach(chart, legendOpts); <ide> } <ide> export default { <ide> } <ide> }, <ide> <add> // The labels need to be built after datasets are updated to ensure that colors <add> // and other styling are correct. See https://github.com/chartjs/Chart.js/issues/6968 <add> afterUpdate(chart) { <add> if (chart.legend) { <add> chart.legend.buildLabels(); <add> } <add> }, <add> <add> <ide> afterEvent(chart, e) { <ide> const legend = chart.legend; <ide> if (legend) {
1
Go
Go
remove the redundant stripcomment
6c79ee7d1e38f7b2f408105db9af7fcf9942f7ca
<ide><path>builder/parser/parser.go <ide> func Parse(rwc io.Reader) (*Node, error) { <ide> <ide> for scanner.Scan() { <ide> scannedLine := strings.TrimLeftFunc(scanner.Text(), unicode.IsSpace) <del> if stripComments(scannedLine) == "" { <del> continue <del> } <del> <ide> line, child, err := parseLine(scannedLine) <ide> if err != nil { <ide> return nil, err
1
PHP
PHP
fix errors when columns match value lengths
0711368f184ca0b44253674e055ae0a244b2d508
<ide><path>lib/Cake/Database/Dialect/SqliteDialectTrait.php <ide> protected function _transformFunctionExpression(FunctionExpression $expression) <ide> } <ide> <ide> /** <del> * Transforms an insert query that is meant to insert multiple tows at a time, <add> * Transforms an insert query that is meant to insert multiple rows at a time, <ide> * otherwise it leaves the query untouched. <ide> * <ide> * The way SQLite works with multi insert is by having multiple select statements <ide> protected function _insertQueryTranslator($query) { <ide> $cols = $v->columns(); <ide> $newQuery = $query->connection()->newQuery(); <ide> $values = []; <add> debug($cols); <ide> foreach ($v->values() as $k => $val) { <ide> $values[] = $val; <del> $val = array_merge($val, array_fill(0, count($cols) - count($val), null)); <add> $fillLength = count($cols) - count($val); <add> if ($fillLength > 0) { <add> $val = array_merge($val, array_fill(0, $fillLength, null)); <add> } <ide> $val = array_map(function($val) { <ide> return $val instanceof ExpressionInterface ? $val : '?'; <ide> }, $val);
1
Javascript
Javascript
remove call to checkframebufferstatus
6f1caec4b6116fdad310d72148805e89d2ed6087
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters = {} ) { <ide> <ide> } <ide> <del> if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { <add> // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) <ide> <del> // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) <add> if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { <ide> <del> if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { <del> <del> _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); <del> <del> } <del> <del> } else { <del> <del> console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); <add> _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); <ide> <ide> } <ide>
1
PHP
PHP
fix cs errors
63b77c356a31119ad66f0ebefeeb0dee9fafe467
<ide><path>src/TestSuite/IntegrationTestTrait.php <ide> public function assertFlashMessageAt(int $at, string $expected, string $key = 'f <ide> $verboseMessage = $this->extractVerboseMessage($message); <ide> $this->assertThat( <ide> $expected, <del> new FlashParamEquals($this->_requestSession, $key, 'message', $at), $verboseMessage <add> new FlashParamEquals($this->_requestSession, $key, 'message', $at), <add> $verboseMessage <ide> ); <ide> } <ide> <ide> public function assertFlashElement(string $expected, string $key = 'flash', stri <ide> $verboseMessage = $this->extractVerboseMessage($message); <ide> $this->assertThat( <ide> $expected, <del> new FlashParamEquals($this->_requestSession, $key, 'element'), $verboseMessage <add> new FlashParamEquals($this->_requestSession, $key, 'element'), <add> $verboseMessage <ide> ); <ide> } <ide> <ide> public function assertFlashElementAt(int $at, string $expected, string $key = 'f <ide> $verboseMessage = $this->extractVerboseMessage($message); <ide> $this->assertThat( <ide> $expected, <del> new FlashParamEquals($this->_requestSession, $key, 'element', $at), $verboseMessage <add> new FlashParamEquals($this->_requestSession, $key, 'element', $at), <add> $verboseMessage <ide> ); <ide> } <ide> <ide><path>src/Validation/Validator.php <ide> class Validator implements ArrayAccess, IteratorAggregate, Countable <ide> * <ide> * @var int <ide> */ <del> public const EMPTY_ALL = self::EMPTY_STRING | self::EMPTY_ARRAY | self::EMPTY_FILE | self::EMPTY_DATE | self::EMPTY_TIME; <add> public const EMPTY_ALL = self::EMPTY_STRING <add> | self::EMPTY_ARRAY <add> | self::EMPTY_FILE <add> | self::EMPTY_DATE <add> | self::EMPTY_TIME; <ide> <ide> /** <ide> * Holds the ValidationSet objects array
2
Text
Text
fix typo in error markdown
bb05e42698a9ea74560ef20b51e2266eb85ba382
<ide><path>errors/gssp-component-member.md <del># getStaticProps/getServerProps can not be attached to the page component <add># getStaticProps/getServerSideProps can not be attached to the page component <ide> <ide> #### Why This Error Occurred <ide>
1
PHP
PHP
add types to insert queries
3462539a5d32bd94d9307120e5ce156455d1c93b
<ide><path>lib/Cake/Model/Datasource/Database/Expression/ValuesExpression.php <ide> class ValuesExpression implements Expression { <ide> */ <ide> protected $_columns = []; <ide> <add>/** <add> * List of column types. <add> * <add> * @var array <add> */ <add> protected $_types = []; <add> <ide> /** <ide> * Flag for tracking whether or not the values are an instance of Query <ide> * <ide> class ValuesExpression implements Expression { <ide> * Constructor <ide> * <ide> * @param array $columns The list of columns that are going to be part of the values. <add> * @param array $types A dictionary of column -> type names <ide> * @return void <ide> */ <del> public function __construct(array $columns) { <add> public function __construct(array $columns, array $types = []) { <ide> $this->_columns = $columns; <add> $this->_types = $types; <ide> } <ide> <ide> /** <ide> public function bindings() { <ide> if (is_array($row)) { <ide> $row = array_merge($defaults, $row); <ide> foreach ($row as $column => $value) { <add> $type = isset($this->_types[$column]) ? $this->_types[$column] : null; <ide> $bindings[] = [ <del> // TODO add types. <del> 'type' => null, <add> 'type' => $type, <ide> 'placeholder' => $i, <ide> 'value' => $value <ide> ]; <ide><path>lib/Cake/Model/Datasource/Database/Query.php <ide> protected function _buildValuesPart($parts) { <ide> * @param array $columns The columns to insert into. <ide> * @return Query <ide> */ <del> public function insert($table, $columns) { <add> public function insert($table, $columns, $types = []) { <ide> $this->_dirty = true; <ide> $this->_type = 'insert'; <ide> $this->_parts['insert'] = [$table, $columns]; <del> $this->_parts['values'] = new ValuesExpression($columns); <add> $this->_parts['values'] = new ValuesExpression($columns, $types); <ide> return $this; <ide> } <ide> <ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php <ide> public function testInsertFromSelect() { <ide> ->where(['id' => 1]); <ide> <ide> $query = new Query($this->connection); <del> $query->insert('articles', ['title', 'body', 'author_id']) <del> ->values($select); <add> $query->insert( <add> 'articles', <add> ['title', 'body', 'author_id'], <add> ['title' => 'string', 'body' => 'string', 'author_id' => 'integer'] <add> ) <add> ->values($select); <ide> <ide> $result = $query->sql(false); <ide> $this->assertContains('INSERT INTO articles (title, body, author_id) SELECT', $result);
3
Ruby
Ruby
take care not to mix in public methods
347db97eddfc4c303a005b71fce9faf12e74e63a
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def clean_backtrace(&block) <ide> # <ide> # The exception is stored in the exception accessor for further inspection. <ide> module RaiseActionExceptions <del> attr_accessor :exception <add> protected <add> attr_accessor :exception <ide> <del> def rescue_action_without_handler(e) <del> self.exception = e <del> <del> if request.remote_addr == "0.0.0.0" <del> raise(e) <del> else <del> super(e) <add> def rescue_action_without_handler(e) <add> self.exception = e <add> <add> if request.remote_addr == "0.0.0.0" <add> raise(e) <add> else <add> super(e) <add> end <ide> end <del> end <ide> end <ide> <ide> setup :setup_controller_request_and_response
1
Javascript
Javascript
remove usage of `mozfillrule`
95732279b647adde43d0bb0a3a835ba5b83f86ca
<ide><path>src/display/canvas.js <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> } <ide> <ide> if (this.pendingEOFill) { <del> if (ctx.mozFillRule !== undefined) { <del> ctx.mozFillRule = 'evenodd'; <del> ctx.fill(); <del> ctx.mozFillRule = 'nonzero'; <del> } else { <del> ctx.fill('evenodd'); <del> } <add> ctx.fill('evenodd'); <ide> this.pendingEOFill = false; <ide> } else { <ide> ctx.fill(); <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var ctx = this.ctx; <ide> if (this.pendingClip) { <ide> if (this.pendingClip === EO_CLIP) { <del> if (ctx.mozFillRule !== undefined) { <del> ctx.mozFillRule = 'evenodd'; <del> ctx.clip(); <del> ctx.mozFillRule = 'nonzero'; <del> } else { <del> ctx.clip('evenodd'); <del> } <add> ctx.clip('evenodd'); <ide> } else { <ide> ctx.clip(); <ide> } <ide><path>test/features/tests.js <ide> var tests = [ <ide> var ctx = canvas.getContext('2d'); <ide> ctx.rect(1, 1, 50, 50); <ide> ctx.rect(5, 5, 41, 41); <del> <del> if ('mozFillRule' in ctx) { <del> ctx.mozFillRule = 'evenodd'; <del> ctx.fill(); <del> } else { <del> ctx.fill('evenodd'); <del> } <add> ctx.fill('evenodd'); <ide> <ide> var data = ctx.getImageData(0, 0, 50, 50).data; <ide> var isEvenOddFill = data[20 * 4 + 20 * 200 + 3] == 0 &&
2
PHP
PHP
update the datetime formatting
2fc66e7910a568dccd4bb061971d5f333f8a3319
<ide><path>src/Collection/Iterator/SortIterator.php <ide> public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU <ide> $callback = $this->_propertyExtractor($callback); <ide> $results = []; <ide> foreach ($items as $key => $value) { <del> if ($value instanceof \DateTime && $type === SORT_NUMERIC) { <del> $value = $value->format('U'); <del> } <ide> $results[$key] = $callback($value); <add> if ($results[$key] instanceof \DateTime && $type === SORT_NUMERIC) { <add> $results[$key] = $results[$key]->format('U'); <add> } <ide> } <ide> <ide> $dir === SORT_DESC ? arsort($results, $type) : asort($results, $type);
1
Ruby
Ruby
pull namespace defaults out of the options hash
8711086f5a2e73cd068434a5fafef258ba9f4fe1
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def controller(controller, options={}) <ide> # end <ide> def namespace(path, options = {}) <ide> path = path.to_s <del> options = { :path => path, :as => path, :module => path, <del> :shallow_path => path, :shallow_prefix => path }.merge!(options) <del> scope(options) { yield } <add> <add> defaults = { <add> module: path, <add> path: options.fetch(:path, path), <add> as: options.fetch(:as, path), <add> shallow_path: options.fetch(:path, path), <add> shallow_prefix: options.fetch(:as, path) <add> } <add> <add> scope(defaults.merge!(options)) { yield } <ide> end <ide> <ide> # === Parameter Restriction <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def test_namespace_with_options <ide> assert_equal 'users/home#index', @response.body <ide> end <ide> <add> def test_namespaced_shallow_routes_with_module_option <add> draw do <add> namespace :foo, module: 'bar' do <add> resources :posts, only: [:index, :show] do <add> resources :comments, only: [:index, :show], shallow: true <add> end <add> end <add> end <add> <add> get '/foo/posts' <add> assert_equal '/foo/posts', foo_posts_path <add> assert_equal 'bar/posts#index', @response.body <add> <add> get '/foo/posts/1' <add> assert_equal '/foo/posts/1', foo_post_path('1') <add> assert_equal 'bar/posts#show', @response.body <add> <add> get '/foo/posts/1/comments' <add> assert_equal '/foo/posts/1/comments', foo_post_comments_path('1') <add> assert_equal 'bar/comments#index', @response.body <add> <add> get '/foo/comments/2' <add> assert_equal '/foo/comments/2', foo_comment_path('2') <add> assert_equal 'bar/comments#show', @response.body <add> end <add> <add> def test_namespaced_shallow_routes_with_path_option <add> draw do <add> namespace :foo, path: 'bar' do <add> resources :posts, only: [:index, :show] do <add> resources :comments, only: [:index, :show], shallow: true <add> end <add> end <add> end <add> <add> get '/bar/posts' <add> assert_equal '/bar/posts', foo_posts_path <add> assert_equal 'foo/posts#index', @response.body <add> <add> get '/bar/posts/1' <add> assert_equal '/bar/posts/1', foo_post_path('1') <add> assert_equal 'foo/posts#show', @response.body <add> <add> get '/bar/posts/1/comments' <add> assert_equal '/bar/posts/1/comments', foo_post_comments_path('1') <add> assert_equal 'foo/comments#index', @response.body <add> <add> get '/bar/comments/2' <add> assert_equal '/bar/comments/2', foo_comment_path('2') <add> assert_equal 'foo/comments#show', @response.body <add> end <add> <add> def test_namespaced_shallow_routes_with_as_option <add> draw do <add> namespace :foo, as: 'bar' do <add> resources :posts, only: [:index, :show] do <add> resources :comments, only: [:index, :show], shallow: true <add> end <add> end <add> end <add> <add> get '/foo/posts' <add> assert_equal '/foo/posts', bar_posts_path <add> assert_equal 'foo/posts#index', @response.body <add> <add> get '/foo/posts/1' <add> assert_equal '/foo/posts/1', bar_post_path('1') <add> assert_equal 'foo/posts#show', @response.body <add> <add> get '/foo/posts/1/comments' <add> assert_equal '/foo/posts/1/comments', bar_post_comments_path('1') <add> assert_equal 'foo/comments#index', @response.body <add> <add> get '/foo/comments/2' <add> assert_equal '/foo/comments/2', bar_comment_path('2') <add> assert_equal 'foo/comments#show', @response.body <add> end <add> <add> def test_namespaced_shallow_routes_with_shallow_path_option <add> draw do <add> namespace :foo, shallow_path: 'bar' do <add> resources :posts, only: [:index, :show] do <add> resources :comments, only: [:index, :show], shallow: true <add> end <add> end <add> end <add> <add> get '/foo/posts' <add> assert_equal '/foo/posts', foo_posts_path <add> assert_equal 'foo/posts#index', @response.body <add> <add> get '/foo/posts/1' <add> assert_equal '/foo/posts/1', foo_post_path('1') <add> assert_equal 'foo/posts#show', @response.body <add> <add> get '/foo/posts/1/comments' <add> assert_equal '/foo/posts/1/comments', foo_post_comments_path('1') <add> assert_equal 'foo/comments#index', @response.body <add> <add> get '/bar/comments/2' <add> assert_equal '/bar/comments/2', foo_comment_path('2') <add> assert_equal 'foo/comments#show', @response.body <add> end <add> <add> def test_namespaced_shallow_routes_with_shallow_prefix_option <add> draw do <add> namespace :foo, shallow_prefix: 'bar' do <add> resources :posts, only: [:index, :show] do <add> resources :comments, only: [:index, :show], shallow: true <add> end <add> end <add> end <add> <add> get '/foo/posts' <add> assert_equal '/foo/posts', foo_posts_path <add> assert_equal 'foo/posts#index', @response.body <add> <add> get '/foo/posts/1' <add> assert_equal '/foo/posts/1', foo_post_path('1') <add> assert_equal 'foo/posts#show', @response.body <add> <add> get '/foo/posts/1/comments' <add> assert_equal '/foo/posts/1/comments', foo_post_comments_path('1') <add> assert_equal 'foo/comments#index', @response.body <add> <add> get '/foo/comments/2' <add> assert_equal '/foo/comments/2', bar_comment_path('2') <add> assert_equal 'foo/comments#show', @response.body <add> end <add> <ide> def test_namespace_containing_numbers <ide> draw do <ide> namespace :v2 do
2
Python
Python
add a comment explaining why we use normal assert
4dbd084fd7f6448da24feb99a01b4d7bc275b3ff
<ide><path>numpy/tests/test_public_api.py <ide> def test_numpy_namespace(): <ide> 'who': 'numpy.lib.utils.who', <ide> } <ide> bad_results = check_dir(np) <add> # pytest gives better error messages with the builtin assert than with <add> # assert_equal <ide> assert bad_results == whitelist <ide> <ide>
1
Javascript
Javascript
fix couple of failing e2e tests
517ada2662019aae99af4bffb0e7fc673bbe9ebd
<ide><path>src/service/location.js <ide> var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+) <ide> <doc:source> <ide> <div ng:init="$location = $service('$location')"> <ide> <a id="ex-test" href="#myPath?name=misko">test hash</a>| <del> <a id="ex-reset" href="#!angular.service.$location">reset hash</a><br/> <add> <a id="ex-reset" href="#!/api/angular.service.$location">reset hash</a><br/> <ide> <input type='text' name="$location.hash" size="30"> <ide> <pre>$location = {{$location}}</pre> <ide> </div> <ide> </doc:source> <ide> <doc:scenario> <ide> it('should initialize the input field', function() { <ide> expect(using('.doc-example-live').element('input[name=$location.hash]').val()). <del> toBe('!angular.service.$location'); <add> toBe('!/api/angular.service.$location'); <ide> }); <ide> <ide> <ide> var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+) <ide> using('.doc-example-live').input('$location.hash').enter('foo'); <ide> using('.doc-example-live').element('#ex-reset').click(); <ide> expect(using('.doc-example-live').element('input[name=$location.hash]').val()). <del> toBe('!angular.service.$location'); <add> toBe('!/api/angular.service.$location'); <ide> }); <ide> <ide> </doc:scenario> <ide><path>src/widgets.js <ide> * @name angular.widget <ide> * @description <ide> * <del> * Widgets are custom DOM elements. An angular widget can be either a custom <add> * Widgets are custom DOM elements. An angular widget can be either a custom <ide> * attribute that modifies an existing DOM elements or an entirely new DOM element. <ide> * <ide> * Following is the list of built-in angular widgets: <ide> angularWidget('option', function(){ <ide> <doc:example> <ide> <doc:source> <ide> <select name="url"> <del> <option value="angular.filter.date.html">date filter</option> <del> <option value="angular.filter.html.html">html filter</option> <add> <option value="api/angular.filter.date.html">date filter</option> <add> <option value="api/angular.filter.html.html">html filter</option> <ide> <option value="">(blank)</option> <ide> </select> <ide> <tt>url = <a href="{{url}}">{{url}}</a></tt> <ide> angularWidget('option', function(){ <ide> expect(element('.doc-example-live ng\\:include').text()).toMatch(/angular\.filter\.date/); <ide> }); <ide> it('should change to html filter', function(){ <del> select('url').option('angular.filter.html.html'); <add> select('url').option('api/angular.filter.html.html'); <ide> expect(element('.doc-example-live ng\\:include').text()).toMatch(/angular\.filter\.html/); <ide> }); <ide> it('should change to blank', function(){
2
Ruby
Ruby
remove unnecessary require of minitest
4ca5a5ea679508603f28dcae5407a634037670e5
<ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> require 'active_support/core_ext/kernel/singleton_class' <ide> require 'active_support/core_ext/object/try' <ide> require 'rack/test' <del>require 'minitest' <ide> <ide> module ActionDispatch <ide> module Integration #:nodoc: <ide><path>activesupport/lib/active_support/test_case.rb <del>gem 'minitest' # make sure we get the gem, not stdlib <del>require 'minitest' <ide> require 'active_support/testing/tagged_logging' <ide> require 'active_support/testing/setup_and_teardown' <ide> require 'active_support/testing/assertions' <ide><path>railties/test/generators/argv_scrubber_test.rb <del>require 'active_support/test_case' <ide> require 'active_support/testing/autorun' <add>require 'active_support/test_case' <ide> require 'rails/generators/rails/app/app_generator' <ide> require 'tempfile' <ide> <ide><path>railties/test/generators/generator_test.rb <del>require 'active_support/test_case' <ide> require 'active_support/testing/autorun' <add>require 'active_support/test_case' <ide> require 'rails/generators/app_base' <ide> <ide> module Rails
4
Javascript
Javascript
add 308 status_code, see rfc7238
ab50fad63bcbedd7c935a9c5d2ab9e4c7202c9f2
<ide><path>lib/_http_server.js <ide> var STATUS_CODES = exports.STATUS_CODES = { <ide> 304 : 'Not Modified', <ide> 305 : 'Use Proxy', <ide> 307 : 'Temporary Redirect', <add> 308 : 'Permanent Redirect', // RFC 7238 <ide> 400 : 'Bad Request', <ide> 401 : 'Unauthorized', <ide> 402 : 'Payment Required',
1
Java
Java
allow modifying handshakeinterceptor list
e81862eed6438c1acf1ecaf6f6d554e31300fb56
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java <ide> public void setHandshakeInterceptors(List<HandshakeInterceptor> interceptors) { <ide> * Return the configured WebSocket handshake request interceptors. <ide> */ <ide> public List<HandshakeInterceptor> getHandshakeInterceptors() { <del> return Collections.unmodifiableList(this.interceptors); <add> return this.interceptors; <ide> } <ide> <ide>
1
Ruby
Ruby
fix typo in postressqladapter's documentation
a4139a167421e2c8ca3b84a333d337006282e928
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> module ConnectionAdapters <ide> # <tt>SET client_min_messages TO <min_messages></tt> call on the connection. <ide> # * <tt>:variables</tt> - An optional hash of additional parameters that <ide> # will be used in <tt>SET SESSION key = val</tt> calls on the connection. <del> # * <tt>:insert_returning</tt> - An optional boolean to control the use or <tt>RETURNING</tt> for <tt>INSERT</tt> statements <add> # * <tt>:insert_returning</tt> - An optional boolean to control the use of <tt>RETURNING</tt> for <tt>INSERT</tt> statements <ide> # defaults to true. <ide> # <ide> # Any further options are used as connection parameters to libpq. See
1
Ruby
Ruby
hide output from brew cask uninstall test
d11e417105c04a1c21edfb4481bc26e21f1c94f9
<ide><path>Library/Homebrew/test/cask/cli/uninstall_spec.rb <ide> <ide> it "tries anyway on a non-present Cask when --force is given" do <ide> expect { <del> Hbc::CLI::Uninstall.run("local-caffeine", "--force") <add> shutup do <add> Hbc::CLI::Uninstall.run("local-caffeine", "--force") <add> end <ide> }.not_to raise_error <ide> end <ide>
1
Javascript
Javascript
convert the `pageviewport` to a proper es6 class
51673dbc5a752520571f0ce6094608f49293f4d0
<ide><path>src/display/dom_utils.js <ide> class DOMSVGFactory { <ide> <ide> /** <ide> * PDF page viewport created based on scale, rotation and offset. <del> * @class <del> * @alias PageViewport <ide> */ <del>var PageViewport = (function PageViewportClosure() { <add>class PageViewport { <ide> /** <del> * @constructor <del> * @private <ide> * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. <ide> * @param scale {number} scale of the viewport. <ide> * @param rotation {number} rotations of the viewport in degrees. <ide> * @param offsetX {number} offset X <ide> * @param offsetY {number} offset Y <ide> * @param dontFlip {boolean} if true, axis Y will not be flipped. <ide> */ <del> function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { <add> constructor(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { <ide> this.viewBox = viewBox; <ide> this.scale = scale; <ide> this.rotation = rotation; <ide> var PageViewport = (function PageViewportClosure() { <ide> <ide> // creating transform to convert pdf coordinate system to the normal <ide> // canvas like coordinates taking in account scale and rotation <del> var centerX = (viewBox[2] + viewBox[0]) / 2; <del> var centerY = (viewBox[3] + viewBox[1]) / 2; <del> var rotateA, rotateB, rotateC, rotateD; <add> let centerX = (viewBox[2] + viewBox[0]) / 2; <add> let centerY = (viewBox[3] + viewBox[1]) / 2; <add> let rotateA, rotateB, rotateC, rotateD; <ide> rotation = rotation % 360; <ide> rotation = rotation < 0 ? rotation + 360 : rotation; <ide> switch (rotation) { <ide> var PageViewport = (function PageViewportClosure() { <ide> rotateC = -rotateC; rotateD = -rotateD; <ide> } <ide> <del> var offsetCanvasX, offsetCanvasY; <del> var width, height; <add> let offsetCanvasX, offsetCanvasY; <add> let width, height; <ide> if (rotateA === 0) { <ide> offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; <ide> offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; <ide> var PageViewport = (function PageViewportClosure() { <ide> this.width = width; <ide> this.height = height; <ide> } <del> PageViewport.prototype = /** @lends PageViewport.prototype */ { <del> /** <del> * Clones viewport with additional properties. <del> * @param args {Object} (optional) If specified, may contain the 'scale' or <del> * 'rotation' properties to override the corresponding properties in <del> * the cloned viewport. <del> * @returns {PageViewport} Cloned viewport. <del> */ <del> clone: function PageViewPort_clone(args) { <del> args = args || {}; <del> var scale = 'scale' in args ? args.scale : this.scale; <del> var rotation = 'rotation' in args ? args.rotation : this.rotation; <del> return new PageViewport(this.viewBox.slice(), scale, rotation, <del> this.offsetX, this.offsetY, args.dontFlip); <del> }, <del> /** <del> * Converts PDF point to the viewport coordinates. For examples, useful for <del> * converting PDF location into canvas pixel coordinates. <del> * @param x {number} X coordinate. <del> * @param y {number} Y coordinate. <del> * @returns {Object} Object that contains 'x' and 'y' properties of the <del> * point in the viewport coordinate space. <del> * @see {@link convertToPdfPoint} <del> * @see {@link convertToViewportRectangle} <del> */ <del> convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { <del> return Util.applyTransform([x, y], this.transform); <del> }, <del> /** <del> * Converts PDF rectangle to the viewport coordinates. <del> * @param rect {Array} xMin, yMin, xMax and yMax coordinates. <del> * @returns {Array} Contains corresponding coordinates of the rectangle <del> * in the viewport coordinate space. <del> * @see {@link convertToViewportPoint} <del> */ <del> convertToViewportRectangle: <del> function PageViewport_convertToViewportRectangle(rect) { <del> var tl = Util.applyTransform([rect[0], rect[1]], this.transform); <del> var br = Util.applyTransform([rect[2], rect[3]], this.transform); <del> return [tl[0], tl[1], br[0], br[1]]; <del> }, <del> /** <del> * Converts viewport coordinates to the PDF location. For examples, useful <del> * for converting canvas pixel location into PDF one. <del> * @param x {number} X coordinate. <del> * @param y {number} Y coordinate. <del> * @returns {Object} Object that contains 'x' and 'y' properties of the <del> * point in the PDF coordinate space. <del> * @see {@link convertToViewportPoint} <del> */ <del> convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { <del> return Util.applyInverseTransform([x, y], this.transform); <del> }, <del> }; <del> return PageViewport; <del>})(); <add> <add> /** <add> * Clones viewport with additional properties. <add> * @param args {Object} (optional) If specified, may contain the 'scale' or <add> * 'rotation' properties to override the corresponding properties in <add> * the cloned viewport. <add> * @returns {PageViewport} Cloned viewport. <add> */ <add> clone(args) { <add> args = args || {}; <add> let scale = 'scale' in args ? args.scale : this.scale; <add> let rotation = 'rotation' in args ? args.rotation : this.rotation; <add> return new PageViewport(this.viewBox.slice(), scale, rotation, <add> this.offsetX, this.offsetY, args.dontFlip); <add> } <add> <add> /** <add> * Converts PDF point to the viewport coordinates. For examples, useful for <add> * converting PDF location into canvas pixel coordinates. <add> * @param x {number} X coordinate. <add> * @param y {number} Y coordinate. <add> * @returns {Object} Object that contains 'x' and 'y' properties of the <add> * point in the viewport coordinate space. <add> * @see {@link convertToPdfPoint} <add> * @see {@link convertToViewportRectangle} <add> */ <add> convertToViewportPoint(x, y) { <add> return Util.applyTransform([x, y], this.transform); <add> } <add> <add> /** <add> * Converts PDF rectangle to the viewport coordinates. <add> * @param rect {Array} xMin, yMin, xMax and yMax coordinates. <add> * @returns {Array} Contains corresponding coordinates of the rectangle <add> * in the viewport coordinate space. <add> * @see {@link convertToViewportPoint} <add> */ <add> convertToViewportRectangle(rect) { <add> let tl = Util.applyTransform([rect[0], rect[1]], this.transform); <add> let br = Util.applyTransform([rect[2], rect[3]], this.transform); <add> return [tl[0], tl[1], br[0], br[1]]; <add> } <add> <add> /** <add> * Converts viewport coordinates to the PDF location. For examples, useful <add> * for converting canvas pixel location into PDF one. <add> * @param x {number} X coordinate. <add> * @param y {number} Y coordinate. <add> * @returns {Object} Object that contains 'x' and 'y' properties of the <add> * point in the PDF coordinate space. <add> * @see {@link convertToViewportPoint} <add> */ <add> convertToPdfPoint(x, y) { <add> return Util.applyInverseTransform([x, y], this.transform); <add> } <add>} <ide> <ide> var RenderingCancelledException = (function RenderingCancelledException() { <ide> function RenderingCancelledException(msg, type) {
1
Python
Python
add implementation of typical sampling
0113aae5b7a3e9de7f6300c71ca593a5fdc3b0c2
<ide><path>src/transformers/configuration_utils.py <ide> def __init__(self, **kwargs): <ide> self.temperature = kwargs.pop("temperature", 1.0) <ide> self.top_k = kwargs.pop("top_k", 50) <ide> self.top_p = kwargs.pop("top_p", 1.0) <add> self.typical_p = kwargs.pop("typical_p", 1.0) <ide> self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0) <ide> self.length_penalty = kwargs.pop("length_penalty", 1.0) <ide> self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0) <ide><path>src/transformers/generation_logits_process.py <ide> def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to <ide> return scores <ide> <ide> <add>class TypicalLogitsWarper(LogitsWarper): <add> def __init__(self, mass: float = 0.9, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1): <add> <add> self.filter_value = filter_value <add> self.mass = mass <add> self.min_tokens_to_keep = min_tokens_to_keep <add> <add> def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: <add> <add> # calculate entropy <add> normalized = torch.nn.functional.log_softmax(scores, dim=-1) <add> p = torch.exp(normalized) <add> ent = -(normalized * p).nansum(-1, keepdim=True) <add> <add> # shift and sort <add> shifted_scores = torch.abs((-normalized) - ent) <add> sorted_scores, sorted_indices = torch.sort(shifted_scores, descending=False) <add> sorted_logits = scores.gather(-1, sorted_indices) <add> cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1) <add> <add> # Remove tokens with cumulative mass above the threshold <add> last_ind = (cumulative_probs < self.mass).sum(dim=1) <add> last_ind[last_ind < 0] = 0 <add> sorted_indices_to_remove = sorted_scores > sorted_scores.gather(1, last_ind.view(-1, 1)) <add> if self.min_tokens_to_keep > 1: <add> # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below) <add> sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0 <add> indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove) <add> <add> scores = scores.masked_fill(indices_to_remove, self.filter_value) <add> return scores <add> <add> <ide> def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int): <ide> generated_ngrams = [{} for _ in range(num_hypos)] <ide> for idx in range(num_hypos): <ide><path>src/transformers/generation_utils.py <ide> TemperatureLogitsWarper, <ide> TopKLogitsWarper, <ide> TopPLogitsWarper, <add> TypicalLogitsWarper, <ide> ) <ide> from .generation_stopping_criteria import ( <ide> MaxLengthCriteria, <ide> def _reorder_cache(self, past, beam_idx): <ide> ) <ide> <ide> def _get_logits_warper( <del> self, top_k: int = None, top_p: float = None, temperature: float = None, num_beams: int = None <add> self, <add> top_k: int = None, <add> top_p: float = None, <add> typical_p: float = None, <add> temperature: float = None, <add> num_beams: int = None, <ide> ) -> LogitsProcessorList: <ide> """ <ide> This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`] instances <ide> def _get_logits_warper( <ide> # init warp parameters <ide> top_k = top_k if top_k is not None else self.config.top_k <ide> top_p = top_p if top_p is not None else self.config.top_p <add> typical_p = typical_p if typical_p is not None else self.config.typical_p <ide> temperature = temperature if temperature is not None else self.config.temperature <ide> # instantiate warpers list <ide> warpers = LogitsProcessorList() <ide> def _get_logits_warper( <ide> warpers.append(TopKLogitsWarper(top_k=top_k, min_tokens_to_keep=(2 if num_beams > 1 else 1))) <ide> if top_p is not None and top_p < 1.0: <ide> warpers.append(TopPLogitsWarper(top_p=top_p, min_tokens_to_keep=(2 if num_beams > 1 else 1))) <add> if typical_p is not None and typical_p < 1.0: <add> warpers.append(TypicalLogitsWarper(mass=typical_p, min_tokens_to_keep=(2 if num_beams > 1 else 1))) <ide> return warpers <ide> <ide> def _get_logits_processor( <ide> def generate( <ide> temperature: Optional[float] = None, <ide> top_k: Optional[int] = None, <ide> top_p: Optional[float] = None, <add> typical_p: Optional[float] = None, <ide> repetition_penalty: Optional[float] = None, <ide> bad_words_ids: Optional[Iterable[int]] = None, <ide> bos_token_id: Optional[int] = None, <ide> def generate( <ide> elif is_sample_gen_mode: <ide> # 10. prepare logits warper <ide> logits_warper = self._get_logits_warper( <del> top_k=top_k, top_p=top_p, temperature=temperature, num_beams=num_beams <add> top_k=top_k, top_p=top_p, typical_p=typical_p, temperature=temperature, num_beams=num_beams <ide> ) <ide> <ide> # 11. expand input_ids with `num_return_sequences` additional sequences per batch <ide> def generate( <ide> elif is_beam_sample_gen_mode: <ide> # 10. prepare logits warper <ide> logits_warper = self._get_logits_warper( <del> top_k=top_k, top_p=top_p, temperature=temperature, num_beams=num_beams <add> top_k=top_k, top_p=top_p, typical_p=typical_p, temperature=temperature, num_beams=num_beams <ide> ) <ide> <ide> if stopping_criteria.max_length is None: <ide><path>tests/test_configuration_common.py <ide> "temperature": 2.0, <ide> "top_k": 10, <ide> "top_p": 0.7, <add> "typical_p": 0.2, <ide> "repetition_penalty": 0.8, <ide> "length_penalty": 0.8, <ide> "no_repeat_ngram_size": 5, <ide><path>tests/test_generation_logits_process.py <ide> TemperatureLogitsWarper, <ide> TopKLogitsWarper, <ide> TopPLogitsWarper, <add> TypicalLogitsWarper, <ide> ) <ide> <ide> <ide> def test_top_p_dist_warper(self): <ide> # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. <ide> self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [3, 2]) <ide> <add> def test_typical_dist_warper(self): <add> input_ids = None <add> vocab_size = 10 <add> batch_size = 2 <add> <add> # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) <add> dist = torch.log( <add> torch.tensor([[0.97, 0.01, 0.01, 0.01], [0.4, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float) <add> ) <add> <add> typical_warp = TypicalLogitsWarper(0.5) <add> filtered_dist = torch.exp(typical_warp(input_ids, dist)) <add> <add> # dist should be filtered to keep min num values so that sum is >= 0.7 <add> # exp (-inf) => 0 <add> EXPECTED_FILTERED_DIST = torch.tensor( <add> [[0.97, 0.0, 0.0, 0.0], [0.0, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float <add> ) <add> self.assertTrue(torch.allclose(filtered_dist, EXPECTED_FILTERED_DIST, atol=1e-3)) <add> <add> # check special cases <add> length = 5 <add> <add> logits = self._get_uniform_logits(batch_size=batch_size, length=length) <add> typical_warp_safety_check = TypicalLogitsWarper(mass=0.5, filter_value=0.0, min_tokens_to_keep=3) <add> <add> scores = typical_warp_safety_check(input_ids, logits) <add> # uniform dist is not changed <add> self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [0, 0]) <add> <add> # check edge cases with negative and extreme logits <add> ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat( <add> batch_size, 1 <add> ) - (vocab_size // 2) <add> <add> # make ramp_logits more extreme <add> ramp_logits[1] = ramp_logits[1] * 100.0 <add> <add> # make sure at least 2 tokens are kept <add> typical_warp = TypicalLogitsWarper(0.7, min_tokens_to_keep=2, filter_value=0.0) <add> filtered_dist = typical_warp(input_ids, ramp_logits) <add> <add> # first batch should keep two tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. <add> self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2]) <add> <ide> def test_no_repeat_ngram_dist_processor(self): <ide> vocab_size = 3 <ide> batch_size = 2
5
Python
Python
get process stats
39c82ef24b32fb0992036315a3c30c5178774fa5
<ide><path>glances/glances.py <ide> def __get_process_statsNEW__(self, proc): <ide> Get process (proc) statistics <ide> !!! Waiting PATCH for PsUtil <ide> !!! http://code.google.com/p/psutil/issues/detail?id=329 <del> !!! Performance ? <add> !!! Performance gap ??? <ide> """ <ide> procstat = proc.as_dict(['memory_info', 'cpu_percent', 'memory_percent', <ide> 'io_counters', 'pid', 'username', 'nice',
1
Ruby
Ruby
use ruby 2.4+ native transform_values(!)
bb175287697768c7312c51f14dcc5b65b1d31fb8
<ide><path>activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb <ide> def deep_transform_values!(&block) <ide> def _deep_transform_values_in_object(object, &block) <ide> case object <ide> when Hash <del> object.each_with_object({}) do |(key, value), result| <del> result[key] = _deep_transform_values_in_object(value, &block) <del> end <add> object.transform_values { |value| _deep_transform_values_in_object(value, &block) } <ide> when Array <ide> object.map { |e| _deep_transform_values_in_object(e, &block) } <ide> else <ide> def _deep_transform_values_in_object(object, &block) <ide> def _deep_transform_values_in_object!(object, &block) <ide> case object <ide> when Hash <del> object.keys.each do |key| <del> value = object.delete(key) <del> object[key] = _deep_transform_values_in_object!(value, &block) <del> end <add> object.transform_values! { |value| _deep_transform_values_in_object!(value, &block) } <ide> object <ide> when Array <ide> object.map! { |e| _deep_transform_values_in_object!(e, &block) }
1