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
define 'logical unit of work'
68a9cd63cc4ca3c898388fe814a2dd8b7fca385e
<ide><path>CONTRIBUTING.md <ide> mixed into the PR. <ide> feature branch to update your pull request rather than `merge master`. <ide> <ide> Before you make a pull request, squash your commits into logical units of work <del>using `git rebase -i` and `git push -f`. After every commit, [make sure the test <del>suite passes]((https://docs.docker.com/project/test-and-docs/)). Include <del>documentation changes in the same pull request so that a revert would remove all <del>traces of the feature or fix. <add>using `git rebase -i` and `git push -f`. A logical unit of work is a consistent <add>set of patches that should be reviewed together: for example, upgrading the <add>version of a vendored dependency and taking advantage of its now available new <add>feature constitute two separate units of work. Implementing a new function and <add>calling it in another file constitute a single logical unit of work. The very <add>high majory of submissions should have a single commit, so if in doubt: squash <add>down to one. <add> <add>After every commit, [make sure the test suite passes] <add>((https://docs.docker.com/project/test-and-docs/)). Include documentation <add>changes in the same pull request so that a revert would remove all traces of <add>the feature or fix. <ide> <ide> Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that <ide> close an issue. Including references automatically closes the issue on a merge.
1
Ruby
Ruby
fix separator insertion in date_select helper
caa1c1978733b6271309db5af488c39aacff6c5a
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def input_id_from_type(type) <ide> # and join them with their appropriate separators. <ide> def build_selects_from_types(order) <ide> select = '' <add> first_visible = order.find { |type| !@options[:"discard_#{type}"] } <ide> order.reverse.each do |type| <del> separator = separator(type) unless type == order.first # don't add on last field <add> separator = separator(type) unless type == first_visible # don't add before first visible field <ide> select.insert(0, separator.to_s + send("select_#{type}").to_s) <ide> end <ide> select.html_safe <ide><path>actionpack/test/template/date_helper_test.rb <ide> def test_date_select_without_day <ide> assert_dom_equal expected, date_select("post", "written_on", :order => [ :month, :year ]) <ide> end <ide> <add> def test_date_select_without_day_with_separator <add> @post = Post.new <add> @post.written_on = Date.new(2004, 6, 15) <add> <add> expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" <add> <add> expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} <add> expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} <add> expected << "</select>\n" <add> <add> expected << "/" <add> <add> expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} <add> expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} <add> expected << "</select>\n" <add> <add> assert_dom_equal expected, date_select("post", "written_on", :date_separator => '/', :order => [ :month, :year ]) <add> end <add> <ide> def test_date_select_without_day_and_with_disabled_html_option <ide> @post = Post.new <ide> @post.written_on = Date.new(2004, 6, 15)
2
Text
Text
create initial template
bcc5591702968d011af61586a3917413455b0981
<ide><path>.github/ISSUE_TEMPLATE.md <add># Please follow the general troubleshooting steps first: <add> <add>- [ ] Ran `brew update` and retried your prior step? <add>- [ ] Ran `brew doctor`, fixed as many issues as possible and retried your prior step? <add>- [ ] If you're seeing permission errors tried running `sudo chown -R $(whoami) $(brew --prefix)`? <add> <add>### Bug reports: <add> <add>_Please replace this line with a brief summary of your issue **AND** if reporting a build issue underneath include the link from:_ <add> <add>`brew gist-logs <formula>` <add>(where `<formula>` is the name of the formula that failed to build). <add> <add>### Feature/Formula Requests: <add> <add>**Please note by far the quickest way to get a new feature or formula into Homebrew is to file a [Pull Request](CONTRIBUTING.md).** <add> <add>We will consider your request but it may be closed if it's something we're not actively planning to work on.
1
Text
Text
remove sass from requirements
0e621175ad43837ddea4299bff7539427fc449bb
<ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.arabic.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: تطبيق نمط حتى يتم استيفاء الشرط معwhile <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/create-reusable-css-with-mixins.arabic.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.arabic.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/nest-css-with-sass.arabic.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: عش المغلق مع ساس <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.arabic.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/store-data-with-sass-variables.arabic.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.arabic.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.arabic.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/arabic/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.arabic.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: '' <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.chinese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 应用样式直到满足@while的条件 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/create-reusable-css-with-mixins.chinese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用Mixins创建可重用的CSS <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.chinese.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 将一组CSS样式扩展到另一个元素 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/nest-css-with-sass.chinese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用Sass嵌套CSS <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.chinese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用Partials将您的样式拆分为较小的块 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/store-data-with-sass-variables.chinese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用Sass变量存储数据 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.chinese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用@each映射列表中的项目 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.chinese.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用@for创建Sass循环 <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.chinese.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 使用@if和@else将逻辑添加到您的样式 <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.english.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/create-reusable-css-with-mixins.english.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.english.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/nest-css-with-sass.english.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.english.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/store-data-with-sass-variables.english.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.english.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide> tests: <ide> <ide> </div> <ide> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <del> <add> <ide> The solution requires using the $color variable twice: once for the class name and once for setting the background color. You can use either the list or map data type. <ide> <ide> ### List Data type <del>```js <add>```html <ide> <style type='text/sass'> <del> <add> <ide> @each $color in blue, black, red { <ide> .#{$color}-bg {background-color: $color;} <del> } <del> <add> } <add> <ide> div { <ide> height: 200px; <ide> width: 200px; <ide> The solution requires using the $color variable twice: once for the class name a <ide> ``` <ide> <ide> ### Map Data type <del>```js <add>```html <ide> <style type='text/sass'> <del> <add> <ide> $colors: (color1: blue, color2: black, color3: red); <del> <add> <ide> @each $key, $color in $colors { <ide> .#{$color}-bg {background-color: $color;} <del> } <del> <add> } <add> <ide> div { <ide> height: 200px; <ide> width: 200px; <ide> The solution requires using the $color variable twice: once for the class name a <ide> <div class="blue-bg"></div> <ide> <div class="black-bg"></div> <ide> <div class="red-bg"></div> <del>``` <del> <del> <add>``` <add> <ide> </section> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.english.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/english/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.english.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> --- <ide> <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.portuguese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Aplicar um estilo até que uma condição seja satisfeita com @while <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/create-reusable-css-with-mixins.portuguese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Crie CSS Reutilizável com Mixins <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.portuguese.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Estenda um conjunto de estilos CSS para outro elemento <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/nest-css-with-sass.portuguese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Nest CSS com Sass <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.portuguese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Dividir seus estilos em pedaços menores com parciais <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/store-data-with-sass-variables.portuguese.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Armazenar dados com variáveis ​​Sass <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.portuguese.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Use @each para mapear itens em uma lista <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.portuguese.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Use @for para criar um loop Sass <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.portuguese.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Use @if e @else para adicionar lógica aos seus estilos <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.russian.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 'Применить стиль до тех пор, пока условие не встретится с @while' <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/create-reusable-css-with-mixins.russian.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Создать многоразовый CSS с помощью Mixins <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.russian.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Расширение одного набора стилей CSS для другого элемента <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/nest-css-with-sass.russian.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Nest CSS с Sass <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.russian.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Разделите свои стили на мелкие куски с частицами <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/store-data-with-sass-variables.russian.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Сохранять данные с помощью переменных Sass <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.russian.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Использовать @each для сопоставления элементов в списке <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.russian.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Используйте @ для создания петли Sass <ide><path>curriculum/challenges/russian/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.russian.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: 'Используйте @if и @else, чтобы добавить логику в свои стили.' <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.spanish.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbb <ide> title: Apply a Style Until a Condition is Met with @while <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Aplicar un estilo hasta que se cumpla una condición con @while <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/create-reusable-css-with-mixins.spanish.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb6 <ide> title: Create Reusable CSS with Mixins <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Crea CSS reutilizable con Mixins <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.spanish.md <ide> --- <ide> id: 587d7fa5367417b2b2512bbd <ide> title: Extend One Set of CSS Styles to Another Element <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Extiende un conjunto de estilos CSS a otro elemento <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/nest-css-with-sass.spanish.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb5 <ide> title: Nest CSS with Sass <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Nest CSS con Sass <ide> --- <ide> <ide> ## Description <ide> <section id="description"> <del>Sass permite anidamiento (<code>nesting</code>) de reglas CSS, que es una forma útil de organizar una hoja de estilo. Normalmente, cada elemento se escribe en una línea diferente para darle estilo así: <add>Sass permite anidamiento (<code>nesting</code>) de reglas CSS, que es una forma útil de organizar una hoja de estilo. Normalmente, cada elemento se escribe en una línea diferente para darle estilo así: <ide> <ide> ```html <ide> nav { <ide> background-color: red; <del>} <add>} <ide> <del>nav ul { <add>nav ul { <ide> list-style: none; <ide> } <ide> <ide> nav ul li { <ide> display: inline-block; <del>} <add>} <ide> ``` <ide> <del>Para un proyecto grande, el archivo CSS tendrá muchas líneas y reglas. Aquí es donde el <code>nesting</code> puede ayudar a organizar su código al colocar reglas de estilo secundarias dentro de los respectivos elementos principales: <del> <add>Para un proyecto grande, el archivo CSS tendrá muchas líneas y reglas. Aquí es donde el <code>nesting</code> puede ayudar a organizar su código al colocar reglas de estilo secundarias dentro de los respectivos elementos principales: <add> <ide> ```html <ide> nav { <ide> background-color: red; <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.spanish.md <ide> --- <ide> id: 587d7dbf367417b2b2512bbc <ide> title: Split Your Styles into Smaller Chunks with Partials <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Divide tus estilos en trozos más pequeños con parciales <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/store-data-with-sass-variables.spanish.md <ide> --- <ide> id: 587d7dbd367417b2b2512bb4 <ide> title: Store Data with Sass Variables <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Almacenar datos con variables Sass <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.spanish.md <ide> --- <ide> id: 587d7dbf367417b2b2512bba <ide> title: Use @each to Map Over Items in a List <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Utilice @each para asignar sobre elementos en una lista <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.spanish.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb9 <ide> title: Use @for to Create a Sass Loop <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Usa @for para crear un Sass Loop <ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.spanish.md <ide> --- <ide> id: 587d7dbe367417b2b2512bb8 <ide> title: Use @if and @else to Add Logic To Your Styles <del>required: <del> - src: 'https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.10.9/sass.sync.min.js' <del> raw: true <ide> challengeType: 0 <ide> videoUrl: '' <ide> localeTitle: Use @if y @else para agregar lógica a sus estilos
54
Python
Python
remove unused deprecated functions for sputnik
0474e706a0bd524c4de6ff97e1bbccfb1f69ef5d
<ide><path>spacy/deprecated.py <del>from sputnik.dir_package import DirPackage <del>from sputnik.package_list import (PackageNotFoundException, <del> CompatiblePackageNotFoundException) <del> <del>import sputnik <ide> from pathlib import Path <ide> from . import about <del> <del> <del>def get_package(data_dir): <del> if not isinstance(data_dir, six.string_types): <del> raise RuntimeError('data_dir must be a string') <del> return DirPackage(data_dir) <del> <del> <del>def get_package_by_name(name=None, via=None): <del> if name is None: <del> return <del> lang = get_lang_class(name) <del> try: <del> return sputnik.package(about.__title__, about.__version__, <del> name, data_path=via) <del> except PackageNotFoundException as e: <del> raise RuntimeError("Model '%s' not installed. Please run 'python -m " <del> "%s.download' to install latest compatible " <del> "model." % (name, lang.__module__)) <del> except CompatiblePackageNotFoundException as e: <del> raise RuntimeError("Installed model is not compatible with spaCy " <del> "version. Please run 'python -m %s.download " <del> "--force' to install latest compatible model." % <del> (lang.__module__)) <del> <del> <ide> from . import util <ide> <ide>
1
Python
Python
add bertencoder to keras_nlp
067e8ae355c38fe0f48eaad975b68e18b3037fec
<ide><path>official/nlp/keras_nlp/encoders/__init__.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Keras-NLP layers package definition.""" <add>from official.nlp.keras_nlp.encoders.bert_encoder import BertEncoder <ide><path>official/nlp/keras_nlp/encoders/bert_encoder.py <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Bert encoder network.""" <add># pylint: disable=g-classes-have-attributes <add> <add>import tensorflow as tf <add> <add>from official.nlp.keras_nlp import layers <add> <add> <add>@tf.keras.utils.register_keras_serializable(package='keras_nlp') <add>class BertEncoder(tf.keras.Model): <add> """Bi-directional Transformer-based encoder network. <add> <add> This network implements a bi-directional Transformer-based encoder as <add> described in "BERT: Pre-training of Deep Bidirectional Transformers for <add> Language Understanding" (https://arxiv.org/abs/1810.04805). It includes the <add> embedding lookups and transformer layers, but not the masked language model <add> or classification task networks. <add> <add> The default values for this object are taken from the BERT-Base implementation <add> in "BERT: Pre-training of Deep Bidirectional Transformers for Language <add> Understanding". <add> <add> *Note* that the network is constructed by <add> [Keras Functional API](https://keras.io/guides/functional_api/). <add> <add> Arguments: <add> vocab_size: The size of the token vocabulary. <add> hidden_size: The size of the transformer hidden layers. <add> num_layers: The number of transformer layers. <add> num_attention_heads: The number of attention heads for each transformer. The <add> hidden size must be divisible by the number of attention heads. <add> max_sequence_length: The maximum sequence length that this encoder can <add> consume. If None, max_sequence_length uses the value from sequence length. <add> This determines the variable shape for positional embeddings. <add> type_vocab_size: The number of types that the 'type_ids' input can take. <add> inner_dim: The output dimension of the first Dense layer in a two-layer <add> feedforward network for each transformer. <add> inner_activation: The activation for the first Dense layer in a two-layer <add> feedforward network for each transformer. <add> output_dropout: Dropout probability for the post-attention and output <add> dropout. <add> attention_dropout: The dropout rate to use for the attention layers <add> within the transformer layers. <add> initializer: The initialzer to use for all weights in this encoder. <add> return_all_encoder_outputs: Whether to output sequence embedding outputs of <add> all encoder transformer layers. <add> output_range: The sequence output range, [0, output_range), by slicing the <add> target sequence of the last transformer layer. `None` means the entire <add> target sequence will attend to the source sequence, which yeilds the full <add> output. <add> embedding_width: The width of the word embeddings. If the embedding width is <add> not equal to hidden size, embedding parameters will be factorized into two <add> matrices in the shape of ['vocab_size', 'embedding_width'] and <add> ['embedding_width', 'hidden_size'] ('embedding_width' is usually much <add> smaller than 'hidden_size'). <add> """ <add> <add> def __init__( <add> self, <add> vocab_size, <add> hidden_size=768, <add> num_layers=12, <add> num_attention_heads=12, <add> max_sequence_length=512, <add> type_vocab_size=16, <add> inner_dim=3072, <add> inner_activation=lambda x: tf.keras.activations.gelu(x, approximate=True), <add> output_dropout=0.1, <add> attention_dropout=0.1, <add> initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02), <add> return_all_encoder_outputs=False, <add> output_range=None, <add> embedding_width=None, <add> **kwargs): <add> activation = tf.keras.activations.get(inner_activation) <add> initializer = tf.keras.initializers.get(initializer) <add> <add> self._self_setattr_tracking = False <add> self._config_dict = { <add> 'vocab_size': vocab_size, <add> 'hidden_size': hidden_size, <add> 'num_layers': num_layers, <add> 'num_attention_heads': num_attention_heads, <add> 'max_sequence_length': max_sequence_length, <add> 'type_vocab_size': type_vocab_size, <add> 'inner_dim': inner_dim, <add> 'inner_activation': tf.keras.activations.serialize(activation), <add> 'output_dropout': output_dropout, <add> 'attention_dropout': attention_dropout, <add> 'initializer': tf.keras.initializers.serialize(initializer), <add> 'return_all_encoder_outputs': return_all_encoder_outputs, <add> 'output_range': output_range, <add> 'embedding_width': embedding_width, <add> } <add> <add> word_ids = tf.keras.layers.Input( <add> shape=(None,), dtype=tf.int32, name='input_word_ids') <add> mask = tf.keras.layers.Input( <add> shape=(None,), dtype=tf.int32, name='input_mask') <add> type_ids = tf.keras.layers.Input( <add> shape=(None,), dtype=tf.int32, name='input_type_ids') <add> <add> if embedding_width is None: <add> embedding_width = hidden_size <add> self._embedding_layer = self._build_embedding_layer() <add> word_embeddings = self._embedding_layer(word_ids) <add> <add> # Always uses dynamic slicing for simplicity. <add> self._position_embedding_layer = layers.PositionEmbedding( <add> initializer=initializer, <add> max_length=max_sequence_length, <add> name='position_embedding') <add> position_embeddings = self._position_embedding_layer(word_embeddings) <add> self._type_embedding_layer = layers.OnDeviceEmbedding( <add> vocab_size=type_vocab_size, <add> embedding_width=embedding_width, <add> initializer=initializer, <add> use_one_hot=True, <add> name='type_embeddings') <add> type_embeddings = self._type_embedding_layer(type_ids) <add> <add> embeddings = tf.keras.layers.Add()( <add> [word_embeddings, position_embeddings, type_embeddings]) <add> <add> self._embedding_norm_layer = tf.keras.layers.LayerNormalization( <add> name='embeddings/layer_norm', axis=-1, epsilon=1e-12, dtype=tf.float32) <add> <add> embeddings = self._embedding_norm_layer(embeddings) <add> embeddings = (tf.keras.layers.Dropout(rate=output_dropout)(embeddings)) <add> <add> # We project the 'embedding' output to 'hidden_size' if it is not already <add> # 'hidden_size'. <add> if embedding_width != hidden_size: <add> self._embedding_projection = tf.keras.layers.experimental.EinsumDense( <add> '...x,xy->...y', <add> output_shape=hidden_size, <add> bias_axes='y', <add> kernel_initializer=initializer, <add> name='embedding_projection') <add> embeddings = self._embedding_projection(embeddings) <add> <add> self._transformer_layers = [] <add> data = embeddings <add> attention_mask = layers.SelfAttentionMask()(data, mask) <add> encoder_outputs = [] <add> for i in range(num_layers): <add> if i == num_layers - 1 and output_range is not None: <add> transformer_output_range = output_range <add> else: <add> transformer_output_range = None <add> layer = layers.TransformerEncoderBlock( <add> num_attention_heads=num_attention_heads, <add> inner_dim=inner_dim, <add> inner_activation=inner_activation, <add> output_dropout=output_dropout, <add> attention_dropout=attention_dropout, <add> output_range=transformer_output_range, <add> kernel_initializer=initializer, <add> name='transformer/layer_%d' % i) <add> self._transformer_layers.append(layer) <add> data = layer([data, attention_mask]) <add> encoder_outputs.append(data) <add> <add> first_token_tensor = ( <add> tf.keras.layers.Lambda(lambda x: tf.squeeze(x[:, 0:1, :], axis=1))( <add> encoder_outputs[-1])) <add> self._pooler_layer = tf.keras.layers.Dense( <add> units=hidden_size, <add> activation='tanh', <add> kernel_initializer=initializer, <add> name='pooler_transform') <add> cls_output = self._pooler_layer(first_token_tensor) <add> <add> outputs = dict( <add> sequence_output=encoder_outputs[-1], <add> pooled_output=cls_output, <add> encoder_outputs=encoder_outputs, <add> ) <add> super(BertEncoder, self).__init__( <add> inputs=[word_ids, mask, type_ids], outputs=outputs, **kwargs) <add> <add> def get_embedding_table(self): <add> return self._embedding_layer.embeddings <add> <add> def _build_embedding_layer(self): <add> embedding_width = self._config_dict[ <add> 'embedding_width'] or self._config_dict['hidden_size'] <add> return layers.OnDeviceEmbedding( <add> vocab_size=self._config_dict['vocab_size'], <add> embedding_width=embedding_width, <add> initializer=self._config_dict['initializer'], <add> name='word_embeddings') <add> <add> def get_embedding_layer(self): <add> return self._embedding_layer <add> <add> def get_config(self): <add> return self._config_dict <add> <add> @property <add> def transformer_layers(self): <add> """List of Transformer layers in the encoder.""" <add> return self._transformer_layers <add> <add> @property <add> def pooler_layer(self): <add> """The pooler dense layer after the transformer layers.""" <add> return self._pooler_layer <add> <add> @classmethod <add> def from_config(cls, config, custom_objects=None): <add> return cls(**config) <ide><path>official/nlp/keras_nlp/encoders/bert_encoder_test.py <add># Copyright 2019 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Tests for transformer-based bert encoder network.""" <add> <add># Import libraries <add>from absl.testing import parameterized <add>import numpy as np <add>import tensorflow as tf <add> <add>from tensorflow.python.keras import keras_parameterized # pylint: disable=g-direct-tensorflow-import <add>from official.nlp.keras_nlp.encoders import bert_encoder <add> <add> <add># This decorator runs the test in V1, V2-Eager, and V2-Functional mode. It <add># guarantees forward compatibility of this code for the V2 switchover. <add>@keras_parameterized.run_all_keras_modes <add>class BertEncoderTest(keras_parameterized.TestCase): <add> <add> def tearDown(self): <add> super(BertEncoderTest, self).tearDown() <add> tf.keras.mixed_precision.experimental.set_policy("float32") <add> <add> def test_network_creation(self): <add> hidden_size = 32 <add> sequence_length = 21 <add> # Create a small BertEncoder for testing. <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=100, <add> hidden_size=hidden_size, <add> num_attention_heads=2, <add> num_layers=3) <add> # Create the inputs (note that the first dimension is implicit). <add> word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> data = dict_outputs["sequence_output"] <add> pooled = dict_outputs["pooled_output"] <add> <add> self.assertIsInstance(test_network.transformer_layers, list) <add> self.assertLen(test_network.transformer_layers, 3) <add> self.assertIsInstance(test_network.pooler_layer, tf.keras.layers.Dense) <add> <add> expected_data_shape = [None, sequence_length, hidden_size] <add> expected_pooled_shape = [None, hidden_size] <add> self.assertAllEqual(expected_data_shape, data.shape.as_list()) <add> self.assertAllEqual(expected_pooled_shape, pooled.shape.as_list()) <add> <add> # The default output dtype is float32. <add> self.assertAllEqual(tf.float32, data.dtype) <add> self.assertAllEqual(tf.float32, pooled.dtype) <add> <add> def test_all_encoder_outputs_network_creation(self): <add> hidden_size = 32 <add> sequence_length = 21 <add> # Create a small BertEncoder for testing. <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=100, <add> hidden_size=hidden_size, <add> num_attention_heads=2, <add> num_layers=3, <add> return_all_encoder_outputs=True) <add> # Create the inputs (note that the first dimension is implicit). <add> word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> all_encoder_outputs = dict_outputs["encoder_outputs"] <add> pooled = dict_outputs["pooled_output"] <add> <add> expected_data_shape = [None, sequence_length, hidden_size] <add> expected_pooled_shape = [None, hidden_size] <add> self.assertLen(all_encoder_outputs, 3) <add> for data in all_encoder_outputs: <add> self.assertAllEqual(expected_data_shape, data.shape.as_list()) <add> self.assertAllEqual(expected_pooled_shape, pooled.shape.as_list()) <add> <add> # The default output dtype is float32. <add> self.assertAllEqual(tf.float32, all_encoder_outputs[-1].dtype) <add> self.assertAllEqual(tf.float32, pooled.dtype) <add> <add> def test_network_creation_with_float16_dtype(self): <add> hidden_size = 32 <add> sequence_length = 21 <add> tf.keras.mixed_precision.experimental.set_policy("mixed_float16") <add> # Create a small BertEncoder for testing. <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=100, <add> hidden_size=hidden_size, <add> num_attention_heads=2, <add> num_layers=3) <add> # Create the inputs (note that the first dimension is implicit). <add> word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> data = dict_outputs["sequence_output"] <add> pooled = dict_outputs["pooled_output"] <add> <add> expected_data_shape = [None, sequence_length, hidden_size] <add> expected_pooled_shape = [None, hidden_size] <add> self.assertAllEqual(expected_data_shape, data.shape.as_list()) <add> self.assertAllEqual(expected_pooled_shape, pooled.shape.as_list()) <add> <add> # If float_dtype is set to float16, the data output is float32 (from a layer <add> # norm) and pool output should be float16. <add> self.assertAllEqual(tf.float32, data.dtype) <add> self.assertAllEqual(tf.float16, pooled.dtype) <add> <add> @parameterized.named_parameters( <add> ("all_sequence", None, 21), <add> ("output_range", 1, 1), <add> ) <add> def test_network_invocation(self, output_range, out_seq_len): <add> hidden_size = 32 <add> sequence_length = 21 <add> vocab_size = 57 <add> num_types = 7 <add> # Create a small BertEncoder for testing. <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=vocab_size, <add> hidden_size=hidden_size, <add> num_attention_heads=2, <add> num_layers=3, <add> type_vocab_size=num_types, <add> output_range=output_range) <add> # Create the inputs (note that the first dimension is implicit). <add> word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> data = dict_outputs["sequence_output"] <add> pooled = dict_outputs["pooled_output"] <add> <add> # Create a model based off of this network: <add> model = tf.keras.Model([word_ids, mask, type_ids], [data, pooled]) <add> <add> # Invoke the model. We can't validate the output data here (the model is too <add> # complex) but this will catch structural runtime errors. <add> batch_size = 3 <add> word_id_data = np.random.randint( <add> vocab_size, size=(batch_size, sequence_length)) <add> mask_data = np.random.randint(2, size=(batch_size, sequence_length)) <add> type_id_data = np.random.randint( <add> num_types, size=(batch_size, sequence_length)) <add> outputs = model.predict([word_id_data, mask_data, type_id_data]) <add> self.assertEqual(outputs[0].shape[1], out_seq_len) <add> <add> # Creates a BertEncoder with max_sequence_length != sequence_length <add> max_sequence_length = 128 <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=vocab_size, <add> hidden_size=hidden_size, <add> max_sequence_length=max_sequence_length, <add> num_attention_heads=2, <add> num_layers=3, <add> type_vocab_size=num_types) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> data = dict_outputs["sequence_output"] <add> pooled = dict_outputs["pooled_output"] <add> model = tf.keras.Model([word_ids, mask, type_ids], [data, pooled]) <add> outputs = model.predict([word_id_data, mask_data, type_id_data]) <add> self.assertEqual(outputs[0].shape[1], sequence_length) <add> <add> # Creates a BertEncoder with embedding_width != hidden_size <add> test_network = bert_encoder.BertEncoder( <add> vocab_size=vocab_size, <add> hidden_size=hidden_size, <add> max_sequence_length=max_sequence_length, <add> num_attention_heads=2, <add> num_layers=3, <add> type_vocab_size=num_types, <add> embedding_width=16) <add> dict_outputs = test_network([word_ids, mask, type_ids]) <add> data = dict_outputs["sequence_output"] <add> pooled = dict_outputs["pooled_output"] <add> model = tf.keras.Model([word_ids, mask, type_ids], [data, pooled]) <add> outputs = model.predict([word_id_data, mask_data, type_id_data]) <add> self.assertEqual(outputs[0].shape[-1], hidden_size) <add> self.assertTrue(hasattr(test_network, "_embedding_projection")) <add> <add> def test_serialize_deserialize(self): <add> # Create a network object that sets all of its config options. <add> kwargs = dict( <add> vocab_size=100, <add> hidden_size=32, <add> num_layers=3, <add> num_attention_heads=2, <add> max_sequence_length=21, <add> type_vocab_size=12, <add> inner_dim=1223, <add> inner_activation="relu", <add> output_dropout=0.05, <add> attention_dropout=0.22, <add> initializer="glorot_uniform", <add> return_all_encoder_outputs=False, <add> output_range=-1, <add> embedding_width=16) <add> network = bert_encoder.BertEncoder(**kwargs) <add> expected_config = dict(kwargs) <add> expected_config["inner_activation"] = tf.keras.activations.serialize( <add> tf.keras.activations.get(expected_config["inner_activation"])) <add> expected_config["initializer"] = tf.keras.initializers.serialize( <add> tf.keras.initializers.get(expected_config["initializer"])) <add> self.assertEqual(network.get_config(), expected_config) <add> # Create another network object from the first object's config. <add> new_network = bert_encoder.BertEncoder.from_config(network.get_config()) <add> <add> # Validate that the config can be forced to JSON. <add> _ = network.to_json() <add> <add> # If the serialization was successful, the new config should match the old. <add> self.assertAllEqual(network.get_config(), new_network.get_config()) <add> <add> # Tests model saving/loading. <add> model_path = self.get_temp_dir() + "/model" <add> network.save(model_path) <add> _ = tf.keras.models.load_model(model_path) <add> <add> <add>if __name__ == "__main__": <add> tf.test.main()
3
Mixed
Ruby
return local time for backwards compatibility
c42260a3251157070a1bafadd179e4441df8933e
<ide><path>activesupport/CHANGELOG.md <del>* Make `Time.at_with_coercion` retain the second fraction and offset from UTC. <add>* Make `Time.at_with_coercion` retain the second fraction and return local time. <ide> <ide> Fixes #11350 <ide> <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb <ide> def at_with_coercion(*args) <ide> time_or_number = args.first <ide> <ide> if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime) <del> at_without_coercion(time_or_number.to_f).getlocal(time_or_number.utc_offset) <add> at_without_coercion(time_or_number.to_f).getlocal <ide> else <ide> at_without_coercion(time_or_number) <ide> end <ide><path>activesupport/test/core_ext/time_ext_test.rb <ide> def test_at_with_datetime <ide> end <ide> end <ide> <del> def test_at_with_datetime_maintains_offset <add> def test_at_with_datetime_returns_local_time <ide> with_env_tz 'US/Eastern' do <del> assert_equal 3600, Time.at(DateTime.civil(2000, 1, 1, 0, 0, 0, '+1')).utc_offset <add> dt = DateTime.civil(2000, 1, 1, 0, 0, 0, '+0') <add> assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(dt) <add> assert_equal 'EST', Time.at(dt).zone <add> assert_equal(-18000, Time.at(dt).utc_offset) <add> <add> # Daylight savings <add> dt = DateTime.civil(2000, 7, 1, 1, 0, 0, '+1') <add> assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(dt) <add> assert_equal 'EDT', Time.at(dt).zone <add> assert_equal(-14400, Time.at(dt).utc_offset) <ide> end <ide> end <ide> <ide> def test_at_with_time_with_zone <ide> end <ide> end <ide> <del> def test_at_with_time_with_zone_maintains_offset <add> def test_at_with_time_with_zone_returns_local_time <ide> with_env_tz 'US/Eastern' do <del> assert_equal 0, Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])).utc_offset <del> assert_equal 3600, Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])).utc_offset <add> twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London']) <add> assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(twz) <add> assert_equal 'EST', Time.at(twz).zone <add> assert_equal(-18000, Time.at(twz).utc_offset) <add> <add> # Daylight savings <add> twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London']) <add> assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(twz) <add> assert_equal 'EDT', Time.at(twz).zone <add> assert_equal(-14400, Time.at(twz).utc_offset) <ide> end <ide> end <ide> <ide> def test_at_with_time_microsecond_precision <ide> def test_at_with_utc_time <ide> with_env_tz 'US/Eastern' do <ide> assert_equal Time.utc(2000), Time.at(Time.utc(2000)) <del> assert_equal 0, Time.at(Time.utc(2000)).utc_offset <ide> assert_equal 'UTC', Time.at(Time.utc(2000)).zone <add> assert_equal(0, Time.at(Time.utc(2000)).utc_offset) <ide> end <ide> end <ide> <ide> def test_at_with_local_time <ide> with_env_tz 'US/Eastern' do <ide> assert_equal Time.local(2000), Time.at(Time.local(2000)) <del> assert_equal -18000, Time.at(Time.local(2000)).utc_offset <ide> assert_equal 'EST', Time.at(Time.local(2000)).zone <add> assert_equal(-18000, Time.at(Time.local(2000)).utc_offset) <ide> <ide> assert_equal Time.local(2000, 7, 1), Time.at(Time.local(2000, 7, 1)) <del> assert_equal -14400, Time.at(Time.local(2000, 7, 1)).utc_offset <ide> assert_equal 'EDT', Time.at(Time.local(2000, 7, 1)).zone <add> assert_equal(-14400, Time.at(Time.local(2000, 7, 1)).utc_offset) <ide> end <ide> end <ide>
3
Python
Python
avoid race condition due to task duplication
c711047036819cbe003dcfbd81fc35bb0b4af5d3
<ide><path>celery/backends/base.py <ide> def _store_result(self, task_id, result, state, <ide> traceback=traceback, request=request) <ide> meta['task_id'] = bytes_to_str(task_id) <ide> <add> # Retrieve metadata from the backend, if the status <add> # is a success then we ignore any following update to the state. <add> # This solves a task deduplication issue because of network <add> # partitioning or lost workers. This issue involved a race condition <add> # making a lost task overwrite the last successful result in the <add> # result backend. <add> current_meta = self._get_task_meta_for(task_id) <add> <add> if current_meta['status'] == states.SUCCESS: <add> return result <add> <ide> self.set(self.get_key_for_task(task_id), self.encode(meta)) <ide> return result <ide>
1
Python
Python
fix nan/inf handling for complex dtypes
3feb77ee4e46962b6c9cfab2a37a0c1ef1ceda82
<ide><path>numpy/testing/tests/test_utils.py <ide> def test_inf_item(self): <ide> def test_simple_item(self): <ide> self._test_not_equal(1, 2) <ide> <add> def test_complex_item(self): <add> self._assert_func(complex(1, 2), complex(1, 2)) <add> self._assert_func(complex(1, np.nan), complex(1, np.nan)) <add> self._test_not_equal(complex(1, np.nan), complex(1, 2)) <add> self._test_not_equal(complex(np.nan, 1), complex(1, np.nan)) <add> self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2)) <add> <add> def test_complex(self): <add> x = np.array([complex(1, 2), complex(1, np.nan)]) <add> z = np.array([complex(1, 2), complex(np.nan, 1)]) <add> y = np.array([complex(1, 2), complex(1, 2)]) <add> self._assert_func(x, x) <add> self._test_not_equal(x, y) <add> self._test_not_equal(x, z) <add> <ide> class TestApproxEqual(unittest.TestCase): <ide> def setUp(self): <ide> self._assert_func = assert_approx_equal <ide><path>numpy/testing/utils.py <ide> def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): <ide> <ide> """ <ide> from numpy.core import ndarray <add> from numpy.lib import iscomplexobj, real, imag <add> <add> # Handle complex numbers: separate into real/imag to handle <add> # nan/inf/negative zero correctly <add> # XXX: catch ValueError for subclasses of ndarray where iscomplex fail <add> try: <add> usecomplex = iscomplexobj(actual) or iscomplexobj(desired) <add> except ValueError: <add> usecomplex = False <add> <add> if usecomplex: <add> if iscomplexobj(actual): <add> actualr = real(actual) <add> actuali = imag(actual) <add> else: <add> actualr = actual <add> actuali = 0 <add> if iscomplexobj(desired): <add> desiredr = real(desired) <add> desiredi = imag(desired) <add> else: <add> desiredr = desired <add> desiredi = 0 <add> try: <add> assert_almost_equal(actualr, desiredr) <add> assert_almost_equal(actuali, desiredi) <add> except AssertionError: <add> raise AssertionError("Items are not equal:\n" \ <add> "ACTUAL: %s\n" \ <add> "DESIRED: %s\n" % (str(actual), str(desired))) <add> <ide> if isinstance(actual, ndarray) or isinstance(desired, ndarray): <ide> return assert_array_almost_equal(actual, desired, decimal, err_msg) <ide> msg = build_err_msg([actual, desired], err_msg, verbose=verbose,
2
Text
Text
update render with a spacer_template [ci skip]
b13c5013ae2332a6f5425949baa1bb2d916e4aee
<ide><path>guides/source/action_view_overview.md <ide> Rails determines the name of the partial to use by looking at the model name in <ide> You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option: <ide> <ide> ```erb <del><%= render @products, spacer_template: "product_ruler" %> <add><%= render partial: @products, spacer_template: "product_ruler" %> <ide> ``` <ide> <ide> Rails will render the `_product_ruler` partial (with no data passed to it) between each pair of `_product` partials.
1
Javascript
Javascript
fix light and math tests
d83b92ec2eeb107ef6eeb2f1c212f2376a3568ed
<ide><path>src/lights/RectAreaLight.js <ide> RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { <ide> <ide> return this; <ide> <add> }, <add> <add> toJSON: function ( meta ) { <add> <add> var data = Light.prototype.toJSON.call( this, meta ); <add> <add> data.object.width = this.width; <add> data.object.height = this.height; <add> <add> return data; <add> <ide> } <ide> <ide> } ); <ide><path>src/loaders/ObjectLoader.js <ide> import { SpotLight } from '../lights/SpotLight'; <ide> import { PointLight } from '../lights/PointLight'; <ide> import { DirectionalLight } from '../lights/DirectionalLight'; <ide> import { AmbientLight } from '../lights/AmbientLight'; <add>import { RectAreaLight } from '../lights/RectAreaLight'; <ide> import { OrthographicCamera } from '../cameras/OrthographicCamera'; <ide> import { PerspectiveCamera } from '../cameras/PerspectiveCamera'; <ide> import { Scene } from '../scenes/Scene'; <ide> Object.assign( ObjectLoader.prototype, { <ide> <ide> break; <ide> <add> case 'RectAreaLight': <add> <add> object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); <add> <add> break; <add> <ide> case 'SpotLight': <ide> <ide> object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); <ide><path>test/unit/src/math/Triangle.js <ide> QUnit.test( "normal" , function( assert ) { <ide> QUnit.test( "plane" , function( assert ) { <ide> var a = new THREE.Triangle(); <ide> <del> // artificial normal is created in this case. <del> assert.ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); <del> assert.ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); <del> assert.ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); <del> assert.ok( a.plane().normal.equals( a.normal() ), "Passed!" ); <add> assert.ok( isNaN( a.plane().distanceToPoint( a.a ) ), "Passed!" ); <add> assert.ok( isNaN( a.plane().distanceToPoint( a.b ) ), "Passed!" ); <add> assert.ok( isNaN( a.plane().distanceToPoint( a.c ) ), "Passed!" ); <add> assert.propEqual( a.plane().normal, {x: NaN, y: NaN, z: NaN}, "Passed!" ); <ide> <ide> a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); <ide> assert.ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); <ide><path>test/unit/src/math/Vector2.js <ide> QUnit.test( "setLength" , function( assert ) { <ide> a = new THREE.Vector2( 0, 0 ); <ide> assert.ok( a.length() == 0, "Passed!" ); <ide> a.setLength( y ); <del> assert.ok( a.length() == 0, "Passed!" ); <add> assert.ok( isNaN( a.length() ), "Passed!" ); <ide> }); <ide> <ide> QUnit.test( "lerp/clone", function( assert ) { <ide><path>test/unit/src/math/Vector3.js <ide> QUnit.test( "setLength" , function( assert ) { <ide> a = new THREE.Vector3( 0, 0, 0 ); <ide> assert.ok( a.length() == 0, "Passed!" ); <ide> a.setLength( y ); <del> assert.ok( a.length() == 0, "Passed!" ); <add> assert.ok( isNaN( a.length() ), "Passed!" ); <ide> <ide> }); <ide> <ide><path>test/unit/src/math/Vector4.js <ide> QUnit.test( "multiply/divide", function( assert ) { <ide> <ide> b.multiplyScalar( -2 ); <ide> assert.ok( b.x == 2*x, "Passed!" ); <del> assert.ok( b.y == 2*y, "Passed!" ); <del> assert.ok( b.z == 2*z, "Passed!" ); <del> assert.ok( b.w == 2*w, "Passed!" ); <add> assert.ok( b.y == 2*y, "Passed!" ); <add> assert.ok( b.z == 2*z, "Passed!" ); <add> assert.ok( b.w == 2*w, "Passed!" ); <ide> <ide> a.divideScalar( -2 ); <ide> assert.ok( a.x == x, "Passed!" ); <ide> QUnit.test( "length/lengthSq", function( assert ) { <ide> var c = new THREE.Vector4( 0, 0, z, 0 ); <ide> var d = new THREE.Vector4( 0, 0, 0, w ); <ide> var e = new THREE.Vector4( 0, 0, 0, 0 ); <del> <add> <ide> assert.ok( a.length() == x, "Passed!" ); <ide> assert.ok( a.lengthSq() == x*x, "Passed!" ); <ide> assert.ok( b.length() == y, "Passed!" ); <ide> QUnit.test( "normalize" , function( assert ) { <ide> var b = new THREE.Vector4( 0, -y, 0, 0 ); <ide> var c = new THREE.Vector4( 0, 0, z, 0 ); <ide> var d = new THREE.Vector4( 0, 0, 0, -w ); <del> <add> <ide> a.normalize(); <ide> assert.ok( a.length() == 1, "Passed!" ); <ide> assert.ok( a.x == 1, "Passed!" ); <ide> QUnit.test( "distanceTo/distanceToSquared", function() { <ide> var c = new THREE.Vector4( 0, 0, z, 0 ); <ide> var d = new THREE.Vector4( 0, 0, 0, -w ); <ide> var e = new THREE.Vector4(); <del> <add> <ide> ok( a.distanceTo( e ) == x, "Passed!" ); <ide> ok( a.distanceToSquared( e ) == x*x, "Passed!" ); <ide> <ide> QUnit.test( "setLength" , function( assert ) { <ide> a = new THREE.Vector4( 0, 0, 0, 0 ); <ide> assert.ok( a.length() == 0, "Passed!" ); <ide> a.setLength( y ); <del> assert.ok( a.length() == 0, "Passed!" ); <add> assert.ok( isNaN( a.length() ), "Passed!" ); <ide> }); <ide> <ide> QUnit.test( "lerp/clone", function( assert ) {
6
Javascript
Javascript
add stats config for load tests
0b51b2340a701f46b67bbb7470e7624ff9377237
<ide><path>test/.stats-app/stats-config.js <ide> module.exports = { <ide> 'http://localhost:$PORT/link', <ide> 'http://localhost:$PORT/withRouter', <ide> ], <add> pagesToBench: [ <add> 'http://localhost:$PORT/', <add> 'http://localhost:$PORT/error-in-render', <add> ], <add> benchOptions: { <add> reqTimeout: 60, <add> concurrency: 50, <add> numRequests: 2500, <add> }, <ide> }, <ide> { <ide> title: 'Serverless Mode',
1
Text
Text
add contributor agreement
79327197d133b106d2f524d172705842043c9f0a
<ide><path>.github/contributors/jumasheff.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI GmbH](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Murat Jumashev | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 25.01.2021 | <add>| GitHub username | jumasheff | <add>| Website (optional) | |
1
Ruby
Ruby
use relations to build scope for named scopes
7921a73acda62c3208b173858a40221cb33f9ff8
<ide><path>activerecord/lib/active_record/named_scope.rb <ide> class Scope <ide> end <ide> end <ide> <del> delegate :scopes, :with_scope, :scoped_methods, :to => :proxy_scope <add> delegate :scopes, :with_scope, :scoped_methods, :unscoped, :to => :proxy_scope <ide> <ide> def initialize(proxy_scope, options, &block) <ide> options ||= {} <ide> def many? <ide> end <ide> <ide> protected <add> <add> def relation <add> @relation ||= unscoped.apply_finder_options(proxy_options) <add> end <add> <ide> def proxy_found <ide> @found || load_found <ide> end <ide> def method_missing(method, *args, &block) <ide> if scopes.include?(method) <ide> scopes[method].call(self, *args) <ide> else <del> with_scope({:find => proxy_options, :create => proxy_options[:conditions].is_a?(Hash) ? proxy_options[:conditions] : {}}, :reverse_merge) do <add> with_scope(relation, :reverse_merge) do <ide> method = :new if method == :build <ide> if current_scoped_methods_when_defined && !scoped_methods.include?(current_scoped_methods_when_defined) <ide> with_scope current_scoped_methods_when_defined do
1
Text
Text
clarify fd behaviour with {read,write}file
8bd6df8927c1363789b195020397c8a672a46a0a
<ide><path>doc/api/fs.md <ide> fs.readFile('<directory>', (err, data) => { <ide> }); <ide> ``` <ide> <del>Any specified file descriptor has to support reading. <del> <del>If a file descriptor is specified as the `path`, it will not be closed <del>automatically. <del> <ide> The `fs.readFile()` function buffers the entire file. To minimize memory costs, <ide> when possible prefer streaming via `fs.createReadStream()`. <ide> <add>### File Descriptors <add>1. Any specified file descriptor has to support reading. <add>2. If a file descriptor is specified as the `path`, it will not be closed <add>automatically. <add>3. The reading will begin at the current position. For example, if the file <add>already had `'Hello World`' and six bytes are read with the file descriptor, <add>the call to `fs.readFile()` with the same file descriptor, would give <add>`'World'`, rather than `'Hello World'`. <add> <ide> ## fs.readFileSync(path[, options]) <ide> <!-- YAML <ide> added: v0.1.8 <ide> If `options` is a string, then it specifies the encoding: <ide> fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback); <ide> ``` <ide> <del>Any specified file descriptor has to support writing. <del> <ide> It is unsafe to use `fs.writeFile()` multiple times on the same file without <ide> waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is <ide> recommended. <ide> <del>If a file descriptor is specified as the `file`, it will not be closed <add>### File Descriptors <add>1. Any specified file descriptor has to support writing. <add>2. If a file descriptor is specified as the `file`, it will not be closed <ide> automatically. <add>3. The writing will begin at the beginning of the file. For example, if the <add>file already had `'Hello World'` and the newly written content is `'Aloha'`, <add>then the contents of the file would be `'Aloha World'`, rather than just <add>`'Aloha'`. <add> <ide> <ide> ## fs.writeFileSync(file, data[, options]) <ide> <!-- YAML <ide> returned. <ide> <ide> The `FileHandle` has to support reading. <ide> <add>If one or more `filehandle.read()` calls are made on a file handle and then a <add>`filehandle.readFile()` call is made, the data will be read from the current <add>position till the end of the file. It doesn't always read from the beginning <add>of the file. <add> <ide> #### filehandle.stat([options]) <ide> <!-- YAML <ide> added: v10.0.0 <ide> The `FileHandle` has to support writing. <ide> It is unsafe to use `filehandle.writeFile()` multiple times on the same file <ide> without waiting for the `Promise` to be resolved (or rejected). <ide> <add>If one or more `filehandle.write()` calls are made on a file handle and then a <add>`filehandle.writeFile()` call is made, the data will be written from the <add>current position till the end of the file. It doesn't always write from the <add>beginning of the file. <add> <ide> ### fsPromises.access(path[, mode]) <ide> <!-- YAML <ide> added: v10.0.0
1
Go
Go
apply performance tuning to new sandboxes also
0dd3a2eade1d9710702cd2e04cfa8f7af1a229ce
<ide><path>libnetwork/controller.go <ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S <ide> <ide> if sb.osSbox != nil { <ide> // Apply operating specific knobs on the load balancer sandbox <add> err := sb.osSbox.InvokeFunc(func() { <add> sb.osSbox.ApplyOSTweaks(sb.oslTypes) <add> }) <add> <add> if err != nil { <add> logrus.Errorf("Failed to apply performance tuning sysctls to the sandbox: %v", err) <add> } <add> // Keep this just so performance is not changed <ide> sb.osSbox.ApplyOSTweaks(sb.oslTypes) <ide> } <ide> <ide><path>libnetwork/osl/namespace_linux.go <ide> func init() { <ide> } <ide> <ide> var ( <del> once sync.Once <del> garbagePathMap = make(map[string]bool) <del> gpmLock sync.Mutex <del> gpmWg sync.WaitGroup <del> gpmCleanupPeriod = 60 * time.Second <del> gpmChan = make(chan chan struct{}) <del> prefix = defaultPrefix <del> loadBalancerConfig = map[string]*kernel.OSValue{ <del> // disables any special handling on port reuse of existing IPVS connection table entries <del> // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L25:1 <del> "net.ipv4.vs.conn_reuse_mode": {Value: "0", CheckFn: nil}, <del> // expires connection from the IPVS connection table when the backend is not available <del> // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L126:1 <del> "net.ipv4.vs.expire_nodest_conn": {Value: "1", CheckFn: nil}, <del> // expires persistent connections to destination servers with weights set to 0 <del> // more info: https://github.com/torvalds/linux/blob/master/Documentation/networking/ipvs-sysctl.txt#L144:1 <del> "net.ipv4.vs.expire_quiescent_template": {Value: "1", CheckFn: nil}, <del> } <add> once sync.Once <add> garbagePathMap = make(map[string]bool) <add> gpmLock sync.Mutex <add> gpmWg sync.WaitGroup <add> gpmCleanupPeriod = 60 * time.Second <add> gpmChan = make(chan chan struct{}) <add> prefix = defaultPrefix <ide> ) <ide> <ide> // The networkNamespace type is the linux implementation of the Sandbox <ide> func setIPv6(path, iface string, enable bool) error { <ide> func (n *networkNamespace) ApplyOSTweaks(types []SandboxType) { <ide> for _, t := range types { <ide> switch t { <del> case SandboxTypeLoadBalancer: <del> kernel.ApplyOSTweaks(loadBalancerConfig) <add> case SandboxTypeLoadBalancer, SandboxTypeIngress: <add> kernel.ApplyOSTweaks(map[string]*kernel.OSValue{ <add> // disables any special handling on port reuse of existing IPVS connection table entries <add> // more info: https://github.com/torvalds/linux/blame/v5.15/Documentation/networking/ipvs-sysctl.rst#L32 <add> "net.ipv4.vs.conn_reuse_mode": {Value: "0", CheckFn: nil}, <add> // expires connection from the IPVS connection table when the backend is not available <add> // more info: https://github.com/torvalds/linux/blame/v5.15/Documentation/networking/ipvs-sysctl.rst#L133 <add> "net.ipv4.vs.expire_nodest_conn": {Value: "1", CheckFn: nil}, <add> // expires persistent connections to destination servers with weights set to 0 <add> // more info: https://github.com/torvalds/linux/blame/v5.15/Documentation/networking/ipvs-sysctl.rst#L151 <add> "net.ipv4.vs.expire_quiescent_template": {Value: "1", CheckFn: nil}, <add> }) <ide> } <ide> } <ide> }
2
Ruby
Ruby
expect xcode 7.2
50dc5f7a3db7af2ff222c756e06fa0debf46b4ef
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when "10.7" then "4.6.3" <ide> when "10.8" then "5.1.1" <ide> when "10.9" then "6.2" <del> when "10.10" then "7.1.1" <del> when "10.11" then "7.1.1" <add> when "10.10" then "7.2" <add> when "10.11" then "7.2" <ide> else <ide> # Default to newest known version of Xcode for unreleased OSX versions. <ide> if OS::Mac.prerelease? <del> "7.1.1" <add> "7.2" <ide> else <ide> raise "OS X '#{MacOS.version}' is invalid" <ide> end <ide> def installed? <ide> <ide> def latest_version <ide> case MacOS.version <del> when "10.11" then "700.1.76" <del> when "10.10" then "700.1.76" <add> when "10.11" then "700.1.81" <add> when "10.10" then "700.1.81" <ide> when "10.9" then "600.0.57" <ide> when "10.8" then "503.0.40" <ide> else
1
Ruby
Ruby
fix regexp for stripping `.git` from repo urls
0cced8e7bd2e0b5e52448dc0448a033bb03ec54b
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def get_repo_data(regex) <ide> _, user, repo = *regex.match(formula.homepage) unless user <ide> return if !user || !repo <ide> <del> repo.gsub!(/.git$/, "") <add> repo.delete_suffix!(".git") <ide> <ide> [user, repo] <ide> end
1
Javascript
Javascript
add url check
a79431984530554402af918f1582d325ac7f313b
<ide><path>extensions/firefox/components/PdfStreamConverter.js <ide> PdfStreamConverter.prototype = { <ide> }, <ide> onStopRequest: function() { <ide> var domWindow = getDOMWindow(channel); <del> let requestListener = new RequestListener(new ChromeActions); <del> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) { <del> requestListener.receive(event); <del> }, false, true); <add> // Double check the url is still the correct one. <add> if (domWindow.document.documentURIObject.equals(aRequest.URI)) { <add> let requestListener = new RequestListener(new ChromeActions); <add> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) { <add> requestListener.receive(event); <add> }, false, true); <add> } <ide> listener.onStopRequest.apply(listener, arguments); <ide> } <ide> };
1
Python
Python
fix invalid method signature
5e6dfd5143e5b9015ae11b2f662502c9867e8938
<ide><path>libcloud/compute/drivers/azure_arm.py <ide> def start_node(self, node): <ide> method='POST') <ide> return r.object <ide> <del> def stop_node(self, node, deallocate=True): <add> def stop_node(self, node, ex_deallocate=True): <ide> """ <ide> Stop a running node. <ide> <ide> def stop_node(self, node, deallocate=True): <ide> :type deallocate: ``bool`` <ide> """ <ide> <del> if deallocate: <add> if ex_deallocate: <ide> target = "%s/deallocate" % node.id <ide> else: <ide> target = "%s/powerOff" % node.id
1
PHP
PHP
fix double-encoding of external urls
b32edfe378f467531c24b432bc46283035682515
<ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php <ide> public function testLink() { <ide> '/a' <ide> ); <ide> $this->assertTags($result, $expected); <add> <add> $result = $this->Html->link('http://www.example.org?param1=value1&param2=value2'); <add> $expected = array('a' => array('href' => 'http://www.example.org?param1=value1&amp;param2=value2'), 'http://www.example.org?param1=value1&amp;param2=value2', '/a'); <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> /** <ide><path>lib/Cake/View/Helper/HtmlHelper.php <ide> public function link($title, $url = null, $options = array(), $confirmMessage = <ide> $url = $this->url($url); <ide> } else { <ide> $url = $this->url($title); <del> $title = h(urldecode($url)); <add> $title = htmlspecialchars_decode($url, ENT_QUOTES); <add> $title = h(urldecode($title)); <ide> $escapeTitle = false; <ide> } <ide>
2
Python
Python
update versioneer 0.19 → 0.26
b6d94fab5a7ef8897fe06d0b7a161bc8080fff26
<ide><path>numpy/_version.py <add> <ide> # This file helps to compute a version number in source trees obtained from <ide> # git-archive tarball (such as those provided by githubs download-from-tag <ide> # feature). Distribution tarballs (built by setup.py sdist) and build <ide> # directories (produced by setup.py build) will contain a much shorter file <ide> # that just contains the computed version number. <ide> <del># This file is released into the public domain. Generated by <del># versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) <add># This file is released into the public domain. <add># Generated by versioneer-0.26 <add># https://github.com/python-versioneer/python-versioneer <ide> <ide> """Git implementation of _version.py.""" <ide> <ide> import re <ide> import subprocess <ide> import sys <add>from typing import Callable, Dict <add>import functools <ide> <ide> <ide> def get_keywords(): <ide> class NotThisMethod(Exception): <ide> """Exception raised if a method is not valid for the current scenario.""" <ide> <ide> <del>LONG_VERSION_PY = {} <del>HANDLERS = {} <add>LONG_VERSION_PY: Dict[str, str] = {} <add>HANDLERS: Dict[str, Dict[str, Callable]] = {} <ide> <ide> <ide> def register_vcs_handler(vcs, method): # decorator <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> env=None): <ide> """Call the given command(s).""" <ide> assert isinstance(commands, list) <del> p = None <del> for c in commands: <add> process = None <add> <add> popen_kwargs = {} <add> if sys.platform == "win32": <add> # This hides the console window if pythonw.exe is used <add> startupinfo = subprocess.STARTUPINFO() <add> startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW <add> popen_kwargs["startupinfo"] = startupinfo <add> <add> for command in commands: <ide> try: <del> dispcmd = str([c] + args) <add> dispcmd = str([command] + args) <ide> # remember shell=False, so use git.cmd on windows, not just git <del> p = subprocess.Popen([c] + args, cwd=cwd, env=env, <del> stdout=subprocess.PIPE, <del> stderr=(subprocess.PIPE if hide_stderr <del> else None)) <add> process = subprocess.Popen([command] + args, cwd=cwd, env=env, <add> stdout=subprocess.PIPE, <add> stderr=(subprocess.PIPE if hide_stderr <add> else None), **popen_kwargs) <ide> break <del> except EnvironmentError: <add> except OSError: <ide> e = sys.exc_info()[1] <ide> if e.errno == errno.ENOENT: <ide> continue <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> if verbose: <ide> print("unable to find command, tried %s" % (commands,)) <ide> return None, None <del> stdout = p.communicate()[0].strip().decode() <del> if p.returncode != 0: <add> stdout = process.communicate()[0].strip().decode() <add> if process.returncode != 0: <ide> if verbose: <ide> print("unable to run %s (error)" % dispcmd) <ide> print("stdout was %s" % stdout) <del> return None, p.returncode <del> return stdout, p.returncode <add> return None, process.returncode <add> return stdout, process.returncode <ide> <ide> <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> """ <ide> rootdirs = [] <ide> <del> for i in range(3): <add> for _ in range(3): <ide> dirname = os.path.basename(root) <ide> if dirname.startswith(parentdir_prefix): <ide> return {"version": dirname[len(parentdir_prefix):], <ide> "full-revisionid": None, <ide> "dirty": False, "error": None, "date": None} <del> else: <del> rootdirs.append(root) <del> root = os.path.dirname(root) # up a level <add> rootdirs.append(root) <add> root = os.path.dirname(root) # up a level <ide> <ide> if verbose: <ide> print("Tried directories %s but none started with prefix %s" % <ide> def git_get_keywords(versionfile_abs): <ide> # _version.py. <ide> keywords = {} <ide> try: <del> with open(versionfile_abs, "r") as f: <del> for line in f.readlines(): <add> with open(versionfile_abs, "r") as fobj: <add> for line in fobj: <ide> if line.strip().startswith("git_refnames ="): <ide> mo = re.search(r'=\s*"(.*)"', line) <ide> if mo: <ide> def git_get_keywords(versionfile_abs): <ide> mo = re.search(r'=\s*"(.*)"', line) <ide> if mo: <ide> keywords["date"] = mo.group(1) <del> except EnvironmentError: <add> except OSError: <ide> pass <ide> return keywords <ide> <ide> <ide> @register_vcs_handler("git", "keywords") <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> """Get version information from git keywords.""" <del> if not keywords: <del> raise NotThisMethod("no keywords at all, weird") <add> if "refnames" not in keywords: <add> raise NotThisMethod("Short version file found") <ide> date = keywords.get("date") <ide> if date is not None: <ide> # Use only the last line. Previous lines may contain GPG signature <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> if verbose: <ide> print("keywords are unexpanded, not using") <ide> raise NotThisMethod("unexpanded keywords, not a git-archive tarball") <del> refs = set([r.strip() for r in refnames.strip("()").split(",")]) <add> refs = {r.strip() for r in refnames.strip("()").split(",")} <ide> # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of <ide> # just "foo-1.0". If we see a "tag: " prefix, prefer those. <ide> TAG = "tag: " <del> tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) <add> tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} <ide> if not tags: <ide> # Either we're using git < 1.8.3, or there really are no tags. We use <ide> # a heuristic: assume all version tags have a digit. The old git %d <ide> # expansion behaves like git log --decorate=short and strips out the <ide> # refs/heads/ and refs/tags/ prefixes that would let us distinguish <ide> # between branches and tags. By ignoring refnames without digits, we <ide> # filter out many common branch names like "release" and <del> # "stabilization", as well as "HEAD" and "main". <del> tags = set([r for r in refs if re.search(r'\d', r)]) <add> # "stabilization", as well as "HEAD" and "master". <add> tags = {r for r in refs if re.search(r'\d', r)} <ide> if verbose: <ide> print("discarding '%s', no digits" % ",".join(refs - tags)) <ide> if verbose: <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> # sorting will prefer e.g. "2.0" over "2.0rc1" <ide> if ref.startswith(tag_prefix): <ide> r = ref[len(tag_prefix):] <add> # Filter out refs that exactly match prefix or that don't start <add> # with a number once the prefix is stripped (mostly a concern <add> # when prefix is '') <add> if not re.match(r'\d', r): <add> continue <ide> if verbose: <ide> print("picking %s" % r) <ide> return {"version": r, <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> <ide> <ide> @register_vcs_handler("git", "pieces_from_vcs") <del>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <add>def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): <ide> """Get version from 'git describe' in the root of the source tree. <ide> <ide> This only gets called if the git-archive 'subst' keywords were *not* <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> if sys.platform == "win32": <ide> GITS = ["git.cmd", "git.exe"] <ide> <del> out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, <del> hide_stderr=True) <add> # GIT_DIR can interfere with correct operation of Versioneer. <add> # It may be intended to be passed to the Versioneer-versioned project, <add> # but that should not change where we get our version from. <add> env = os.environ.copy() <add> env.pop("GIT_DIR", None) <add> runner = functools.partial(runner, env=env) <add> <add> _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, <add> hide_stderr=not verbose) <ide> if rc != 0: <ide> if verbose: <ide> print("Directory %s not under git control" % root) <ide> raise NotThisMethod("'git rev-parse --git-dir' returned error") <ide> <ide> # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] <ide> # if there isn't one, this yields HEX[-dirty] (no NUM) <del> describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", <del> "--always", "--long", <del> "--match", "%s*" % tag_prefix], <del> cwd=root) <add> describe_out, rc = runner(GITS, [ <add> "describe", "--tags", "--dirty", "--always", "--long", <add> "--match", f"{tag_prefix}[[:digit:]]*" <add> ], cwd=root) <ide> # --long was added in git-1.5.5 <ide> if describe_out is None: <ide> raise NotThisMethod("'git describe' failed") <ide> describe_out = describe_out.strip() <del> full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) <add> full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) <ide> if full_out is None: <ide> raise NotThisMethod("'git rev-parse' failed") <ide> full_out = full_out.strip() <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> pieces["short"] = full_out[:7] # maybe improved later <ide> pieces["error"] = None <ide> <add> branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], <add> cwd=root) <add> # --abbrev-ref was added in git-1.6.3 <add> if rc != 0 or branch_name is None: <add> raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") <add> branch_name = branch_name.strip() <add> <add> if branch_name == "HEAD": <add> # If we aren't exactly on a branch, pick a branch which represents <add> # the current commit. If all else fails, we are on a branchless <add> # commit. <add> branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) <add> # --contains was added in git-1.5.4 <add> if rc != 0 or branches is None: <add> raise NotThisMethod("'git branch --contains' returned error") <add> branches = branches.split("\n") <add> <add> # Remove the first line if we're running detached <add> if "(" in branches[0]: <add> branches.pop(0) <add> <add> # Strip off the leading "* " from the list of branches. <add> branches = [branch[2:] for branch in branches] <add> if "master" in branches: <add> branch_name = "master" <add> elif not branches: <add> branch_name = None <add> else: <add> # Pick the first branch that is returned. Good or bad. <add> branch_name = branches[0] <add> <add> pieces["branch"] = branch_name <add> <ide> # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] <ide> # TAG might have hyphens. <ide> git_describe = describe_out <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> # TAG-NUM-gHEX <ide> mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) <ide> if not mo: <del> # unparseable. Maybe git-describe is misbehaving? <add> # unparsable. Maybe git-describe is misbehaving? <ide> pieces["error"] = ("unable to parse git-describe output: '%s'" <ide> % describe_out) <ide> return pieces <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> else: <ide> # HEX: no tags <ide> pieces["closest-tag"] = None <del> count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], <del> cwd=root) <del> pieces["distance"] = int(count_out) # total number of commits <add> out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) <add> pieces["distance"] = len(out.split()) # total number of commits <ide> <ide> # commit date: see ISO-8601 comment in git_versions_from_keywords() <del> date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], <del> cwd=root)[0].strip() <add> date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() <ide> # Use only the last line. Previous lines may contain GPG signature <ide> # information. <ide> date = date.splitlines()[-1] <ide> def render_pep440(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_branch(pieces): <add> """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. Note that .dev0 sorts backwards <add> (a feature branch will appear "older" than the master branch). <add> <add> Exceptions: <add> 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0" <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+untagged.%d.g%s" % (pieces["distance"], <add> pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <add>def pep440_split_post(ver): <add> """Split pep440 version string at the post-release segment. <add> <add> Returns the release segments before the post-release and the <add> post-release version number (or -1 if no post-release segment is present). <add> """ <add> vc = str.split(ver, ".post") <add> return vc[0], int(vc[1] or 0) if len(vc) == 2 else None <add> <add> <ide> def render_pep440_pre(pieces): <del> """TAG[.post0.devDISTANCE] -- No -dirty. <add> """TAG[.postN.devDISTANCE] -- No -dirty. <ide> <ide> Exceptions: <ide> 1: no tags. 0.post0.devDISTANCE <ide> """ <ide> if pieces["closest-tag"]: <del> rendered = pieces["closest-tag"] <ide> if pieces["distance"]: <del> rendered += ".post0.dev%d" % pieces["distance"] <add> # update the post release segment <add> tag_version, post_version = pep440_split_post(pieces["closest-tag"]) <add> rendered = tag_version <add> if post_version is not None: <add> rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) <add> else: <add> rendered += ".post0.dev%d" % (pieces["distance"]) <add> else: <add> # no commits, use the tag as the version <add> rendered = pieces["closest-tag"] <ide> else: <ide> # exception #1 <ide> rendered = "0.post0.dev%d" % pieces["distance"] <ide> def render_pep440_post(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_post_branch(pieces): <add> """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. <add> <add> Exceptions: <add> 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> rendered += ".post%d" % pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "g%s" % pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0.post%d" % pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+g%s" % pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <ide> def render_pep440_old(pieces): <ide> """TAG[.postDISTANCE[.dev0]] . <ide> <ide> def render(pieces, style): <ide> <ide> if style == "pep440": <ide> rendered = render_pep440(pieces) <add> elif style == "pep440-branch": <add> rendered = render_pep440_branch(pieces) <ide> elif style == "pep440-pre": <ide> rendered = render_pep440_pre(pieces) <ide> elif style == "pep440-post": <ide> rendered = render_pep440_post(pieces) <add> elif style == "pep440-post-branch": <add> rendered = render_pep440_post_branch(pieces) <ide> elif style == "pep440-old": <ide> rendered = render_pep440_old(pieces) <ide> elif style == "git-describe": <ide> def get_versions(): <ide> # versionfile_source is the relative path from the top of the source <ide> # tree (where the .git directory might live) to this file. Invert <ide> # this to find the root from __file__. <del> for i in cfg.versionfile_source.split('/'): <add> for _ in cfg.versionfile_source.split('/'): <ide> root = os.path.dirname(root) <ide> except NameError: <ide> return {"version": "0+unknown", "full-revisionid": None, <ide><path>versioneer.py <ide> <del># Version: 0.19 <add># Version: 0.26 <ide> <ide> """The Versioneer - like a rocketeer, but for versions. <ide> <ide> * like a rocketeer, but for versions! <ide> * https://github.com/python-versioneer/python-versioneer <ide> * Brian Warner <del>* License: Public Domain <del>* Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3 <add>* License: Public Domain (Unlicense) <add>* Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3 <ide> * [![Latest Version][pypi-image]][pypi-url] <ide> * [![Build Status][travis-image]][travis-url] <ide> <del>This is a tool for managing a recorded version number in distutils-based <add>This is a tool for managing a recorded version number in setuptools-based <ide> python projects. The goal is to remove the tedious and error-prone "update <ide> the embedded version string" step from your release process. Making a new <ide> release should be as easy as recording a new tag in your version-control <ide> <ide> ## Quick Install <ide> <add>Versioneer provides two installation modes. The "classic" vendored mode installs <add>a copy of versioneer into your repository. The experimental build-time dependency mode <add>is intended to allow you to skip this step and simplify the process of upgrading. <add> <add>### Vendored mode <add> <add>* `pip install versioneer` to somewhere in your $PATH <add>* add a `[tool.versioneer]` section to your `pyproject.toml or a <add> `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) <add>* run `versioneer install --vendor` in your source tree, commit the results <add>* verify version information with `python setup.py version` <add> <add>### Build-time dependency mode <add> <ide> * `pip install versioneer` to somewhere in your $PATH <del>* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) <del>* run `versioneer install` in your source tree, commit the results <del>* Verify version information with `python setup.py version` <add>* add a `[tool.versioneer]` section to your `pyproject.toml or a <add> `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) <add>* add `versioneer` to the `requires` key of the `build-system` table in <add> `pyproject.toml`: <add> ```toml <add> [build-system] <add> requires = ["setuptools", "versioneer"] <add> build-backend = "setuptools.build_meta" <add> ``` <add>* run `versioneer install --no-vendor` in your source tree, commit the results <add>* verify version information with `python setup.py version` <ide> <ide> ## Version Identifiers <ide> <ide> To upgrade your project to a new release of Versioneer, do the following: <ide> <ide> * install the new Versioneer (`pip install -U versioneer` or equivalent) <del>* edit `setup.cfg`, if necessary, to include any new configuration settings <del> indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. <del>* re-run `versioneer install` in your source tree, to replace <add>* edit `setup.cfg` and `pyproject.toml`, if necessary, <add> to include any new configuration settings indicated by the release notes. <add> See [UPGRADING](./UPGRADING.md) for details. <add>* re-run `versioneer install --[no-]vendor` in your source tree, to replace <ide> `SRC/_version.py` <ide> * commit any changed files <ide> <ide> dependency <ide> * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of <ide> versioneer <add>* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools <add> plugin <ide> <ide> ## License <ide> <ide> [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer <ide> <ide> """ <add># pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring <add># pylint:disable=missing-class-docstring,too-many-branches,too-many-statements <add># pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error <add># pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with <add># pylint:disable=attribute-defined-outside-init,too-many-arguments <ide> <ide> import configparser <ide> import errno <ide> import re <ide> import subprocess <ide> import sys <add>from pathlib import Path <add>from typing import Callable, Dict <add>import functools <add>try: <add> import tomli <add> have_tomli = True <add>except ImportError: <add> have_tomli = False <ide> <ide> <ide> class VersioneerConfig: <ide> def get_root(): <ide> # module-import table will cache the first one. So we can't use <ide> # os.path.dirname(__file__), as that will find whichever <ide> # versioneer.py was first imported, even in later projects. <del> me = os.path.realpath(os.path.abspath(__file__)) <del> me_dir = os.path.normcase(os.path.splitext(me)[0]) <add> my_path = os.path.realpath(os.path.abspath(__file__)) <add> me_dir = os.path.normcase(os.path.splitext(my_path)[0]) <ide> vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) <del> if me_dir != vsr_dir: <add> if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): <ide> print("Warning: build in %s is using versioneer.py from %s" <del> % (os.path.dirname(me), versioneer_py)) <add> % (os.path.dirname(my_path), versioneer_py)) <ide> except NameError: <ide> pass <ide> return root <ide> <ide> <ide> def get_config_from_root(root): <ide> """Read the project setup.cfg file to determine Versioneer config.""" <del> # This might raise EnvironmentError (if setup.cfg is missing), or <add> # This might raise OSError (if setup.cfg is missing), or <ide> # configparser.NoSectionError (if it lacks a [versioneer] section), or <ide> # configparser.NoOptionError (if it lacks "VCS="). See the docstring at <ide> # the top of versioneer.py for instructions on writing your setup.cfg . <del> setup_cfg = os.path.join(root, "setup.cfg") <del> parser = configparser.ConfigParser() <del> with open(setup_cfg, "r") as f: <del> parser.read_file(f) <del> VCS = parser.get("versioneer", "VCS") # mandatory <del> <del> def get(parser, name): <del> if parser.has_option("versioneer", name): <del> return parser.get("versioneer", name) <del> return None <add> root = Path(root) <add> pyproject_toml = root / "pyproject.toml" <add> setup_cfg = root / "setup.cfg" <add> section = None <add> if pyproject_toml.exists() and have_tomli: <add> try: <add> with open(pyproject_toml, 'rb') as fobj: <add> pp = tomli.load(fobj) <add> section = pp['tool']['versioneer'] <add> except (tomli.TOMLDecodeError, KeyError): <add> pass <add> if not section: <add> parser = configparser.ConfigParser() <add> with open(setup_cfg) as cfg_file: <add> parser.read_file(cfg_file) <add> parser.get("versioneer", "VCS") # raise error if missing <add> <add> section = parser["versioneer"] <add> <ide> cfg = VersioneerConfig() <del> cfg.VCS = VCS <del> cfg.style = get(parser, "style") or "" <del> cfg.versionfile_source = get(parser, "versionfile_source") <del> cfg.versionfile_build = get(parser, "versionfile_build") <del> cfg.tag_prefix = get(parser, "tag_prefix") <del> if cfg.tag_prefix in ("''", '""'): <add> cfg.VCS = section['VCS'] <add> cfg.style = section.get("style", "") <add> cfg.versionfile_source = section.get("versionfile_source") <add> cfg.versionfile_build = section.get("versionfile_build") <add> cfg.tag_prefix = section.get("tag_prefix") <add> if cfg.tag_prefix in ("''", '""', None): <ide> cfg.tag_prefix = "" <del> cfg.parentdir_prefix = get(parser, "parentdir_prefix") <del> cfg.verbose = get(parser, "verbose") <add> cfg.parentdir_prefix = section.get("parentdir_prefix") <add> cfg.verbose = section.get("verbose") <ide> return cfg <ide> <ide> <ide> class NotThisMethod(Exception): <ide> <ide> <ide> # these dictionaries contain VCS-specific tools <del>LONG_VERSION_PY = {} <del>HANDLERS = {} <add>LONG_VERSION_PY: Dict[str, str] = {} <add>HANDLERS: Dict[str, Dict[str, Callable]] = {} <ide> <ide> <ide> def register_vcs_handler(vcs, method): # decorator <ide> """Create decorator to mark a method as the handler of a VCS.""" <ide> def decorate(f): <ide> """Store f in HANDLERS[vcs][method].""" <del> if vcs not in HANDLERS: <del> HANDLERS[vcs] = {} <del> HANDLERS[vcs][method] = f <add> HANDLERS.setdefault(vcs, {})[method] = f <ide> return f <ide> return decorate <ide> <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> env=None): <ide> """Call the given command(s).""" <ide> assert isinstance(commands, list) <del> p = None <del> for c in commands: <add> process = None <add> <add> popen_kwargs = {} <add> if sys.platform == "win32": <add> # This hides the console window if pythonw.exe is used <add> startupinfo = subprocess.STARTUPINFO() <add> startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW <add> popen_kwargs["startupinfo"] = startupinfo <add> <add> for command in commands: <ide> try: <del> dispcmd = str([c] + args) <add> dispcmd = str([command] + args) <ide> # remember shell=False, so use git.cmd on windows, not just git <del> p = subprocess.Popen([c] + args, cwd=cwd, env=env, <del> stdout=subprocess.PIPE, <del> stderr=(subprocess.PIPE if hide_stderr <del> else None)) <add> process = subprocess.Popen([command] + args, cwd=cwd, env=env, <add> stdout=subprocess.PIPE, <add> stderr=(subprocess.PIPE if hide_stderr <add> else None), **popen_kwargs) <ide> break <del> except EnvironmentError: <add> except OSError: <ide> e = sys.exc_info()[1] <ide> if e.errno == errno.ENOENT: <ide> continue <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> if verbose: <ide> print("unable to find command, tried %s" % (commands,)) <ide> return None, None <del> stdout = p.communicate()[0].strip().decode() <del> if p.returncode != 0: <add> stdout = process.communicate()[0].strip().decode() <add> if process.returncode != 0: <ide> if verbose: <ide> print("unable to run %s (error)" % dispcmd) <ide> print("stdout was %s" % stdout) <del> return None, p.returncode <del> return stdout, p.returncode <add> return None, process.returncode <add> return stdout, process.returncode <ide> <ide> <ide> LONG_VERSION_PY['git'] = r''' <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> # directories (produced by setup.py build) will contain a much shorter file <ide> # that just contains the computed version number. <ide> <del># This file is released into the public domain. Generated by <del># versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) <add># This file is released into the public domain. <add># Generated by versioneer-0.26 <add># https://github.com/python-versioneer/python-versioneer <ide> <ide> """Git implementation of _version.py.""" <ide> <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> import re <ide> import subprocess <ide> import sys <add>from typing import Callable, Dict <add>import functools <ide> <ide> <ide> def get_keywords(): <ide> class NotThisMethod(Exception): <ide> """Exception raised if a method is not valid for the current scenario.""" <ide> <ide> <del>LONG_VERSION_PY = {} <del>HANDLERS = {} <add>LONG_VERSION_PY: Dict[str, str] = {} <add>HANDLERS: Dict[str, Dict[str, Callable]] = {} <ide> <ide> <ide> def register_vcs_handler(vcs, method): # decorator <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> env=None): <ide> """Call the given command(s).""" <ide> assert isinstance(commands, list) <del> p = None <del> for c in commands: <add> process = None <add> <add> popen_kwargs = {} <add> if sys.platform == "win32": <add> # This hides the console window if pythonw.exe is used <add> startupinfo = subprocess.STARTUPINFO() <add> startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW <add> popen_kwargs["startupinfo"] = startupinfo <add> <add> for command in commands: <ide> try: <del> dispcmd = str([c] + args) <add> dispcmd = str([command] + args) <ide> # remember shell=False, so use git.cmd on windows, not just git <del> p = subprocess.Popen([c] + args, cwd=cwd, env=env, <del> stdout=subprocess.PIPE, <del> stderr=(subprocess.PIPE if hide_stderr <del> else None)) <add> process = subprocess.Popen([command] + args, cwd=cwd, env=env, <add> stdout=subprocess.PIPE, <add> stderr=(subprocess.PIPE if hide_stderr <add> else None), **popen_kwargs) <ide> break <del> except EnvironmentError: <add> except OSError: <ide> e = sys.exc_info()[1] <ide> if e.errno == errno.ENOENT: <ide> continue <ide> def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, <ide> if verbose: <ide> print("unable to find command, tried %%s" %% (commands,)) <ide> return None, None <del> stdout = p.communicate()[0].strip().decode() <del> if p.returncode != 0: <add> stdout = process.communicate()[0].strip().decode() <add> if process.returncode != 0: <ide> if verbose: <ide> print("unable to run %%s (error)" %% dispcmd) <ide> print("stdout was %%s" %% stdout) <del> return None, p.returncode <del> return stdout, p.returncode <add> return None, process.returncode <add> return stdout, process.returncode <ide> <ide> <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> """ <ide> rootdirs = [] <ide> <del> for i in range(3): <add> for _ in range(3): <ide> dirname = os.path.basename(root) <ide> if dirname.startswith(parentdir_prefix): <ide> return {"version": dirname[len(parentdir_prefix):], <ide> "full-revisionid": None, <ide> "dirty": False, "error": None, "date": None} <del> else: <del> rootdirs.append(root) <del> root = os.path.dirname(root) # up a level <add> rootdirs.append(root) <add> root = os.path.dirname(root) # up a level <ide> <ide> if verbose: <ide> print("Tried directories %%s but none started with prefix %%s" %% <ide> def git_get_keywords(versionfile_abs): <ide> # _version.py. <ide> keywords = {} <ide> try: <del> f = open(versionfile_abs, "r") <del> for line in f.readlines(): <del> if line.strip().startswith("git_refnames ="): <del> mo = re.search(r'=\s*"(.*)"', line) <del> if mo: <del> keywords["refnames"] = mo.group(1) <del> if line.strip().startswith("git_full ="): <del> mo = re.search(r'=\s*"(.*)"', line) <del> if mo: <del> keywords["full"] = mo.group(1) <del> if line.strip().startswith("git_date ="): <del> mo = re.search(r'=\s*"(.*)"', line) <del> if mo: <del> keywords["date"] = mo.group(1) <del> f.close() <del> except EnvironmentError: <add> with open(versionfile_abs, "r") as fobj: <add> for line in fobj: <add> if line.strip().startswith("git_refnames ="): <add> mo = re.search(r'=\s*"(.*)"', line) <add> if mo: <add> keywords["refnames"] = mo.group(1) <add> if line.strip().startswith("git_full ="): <add> mo = re.search(r'=\s*"(.*)"', line) <add> if mo: <add> keywords["full"] = mo.group(1) <add> if line.strip().startswith("git_date ="): <add> mo = re.search(r'=\s*"(.*)"', line) <add> if mo: <add> keywords["date"] = mo.group(1) <add> except OSError: <ide> pass <ide> return keywords <ide> <ide> <ide> @register_vcs_handler("git", "keywords") <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> """Get version information from git keywords.""" <del> if not keywords: <del> raise NotThisMethod("no keywords at all, weird") <add> if "refnames" not in keywords: <add> raise NotThisMethod("Short version file found") <ide> date = keywords.get("date") <ide> if date is not None: <ide> # Use only the last line. Previous lines may contain GPG signature <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> if verbose: <ide> print("keywords are unexpanded, not using") <ide> raise NotThisMethod("unexpanded keywords, not a git-archive tarball") <del> refs = set([r.strip() for r in refnames.strip("()").split(",")]) <add> refs = {r.strip() for r in refnames.strip("()").split(",")} <ide> # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of <ide> # just "foo-1.0". If we see a "tag: " prefix, prefer those. <ide> TAG = "tag: " <del> tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) <add> tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} <ide> if not tags: <ide> # Either we're using git < 1.8.3, or there really are no tags. We use <ide> # a heuristic: assume all version tags have a digit. The old git %%d <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> # between branches and tags. By ignoring refnames without digits, we <ide> # filter out many common branch names like "release" and <ide> # "stabilization", as well as "HEAD" and "master". <del> tags = set([r for r in refs if re.search(r'\d', r)]) <add> tags = {r for r in refs if re.search(r'\d', r)} <ide> if verbose: <ide> print("discarding '%%s', no digits" %% ",".join(refs - tags)) <ide> if verbose: <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> # sorting will prefer e.g. "2.0" over "2.0rc1" <ide> if ref.startswith(tag_prefix): <ide> r = ref[len(tag_prefix):] <add> # Filter out refs that exactly match prefix or that don't start <add> # with a number once the prefix is stripped (mostly a concern <add> # when prefix is '') <add> if not re.match(r'\d', r): <add> continue <ide> if verbose: <ide> print("picking %%s" %% r) <ide> return {"version": r, <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> <ide> <ide> @register_vcs_handler("git", "pieces_from_vcs") <del>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <add>def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): <ide> """Get version from 'git describe' in the root of the source tree. <ide> <ide> This only gets called if the git-archive 'subst' keywords were *not* <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> if sys.platform == "win32": <ide> GITS = ["git.cmd", "git.exe"] <ide> <del> out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, <del> hide_stderr=True) <add> # GIT_DIR can interfere with correct operation of Versioneer. <add> # It may be intended to be passed to the Versioneer-versioned project, <add> # but that should not change where we get our version from. <add> env = os.environ.copy() <add> env.pop("GIT_DIR", None) <add> runner = functools.partial(runner, env=env) <add> <add> _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, <add> hide_stderr=not verbose) <ide> if rc != 0: <ide> if verbose: <ide> print("Directory %%s not under git control" %% root) <ide> raise NotThisMethod("'git rev-parse --git-dir' returned error") <ide> <ide> # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] <ide> # if there isn't one, this yields HEX[-dirty] (no NUM) <del> describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", <del> "--always", "--long", <del> "--match", "%%s*" %% tag_prefix], <del> cwd=root) <add> describe_out, rc = runner(GITS, [ <add> "describe", "--tags", "--dirty", "--always", "--long", <add> "--match", f"{tag_prefix}[[:digit:]]*" <add> ], cwd=root) <ide> # --long was added in git-1.5.5 <ide> if describe_out is None: <ide> raise NotThisMethod("'git describe' failed") <ide> describe_out = describe_out.strip() <del> full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) <add> full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) <ide> if full_out is None: <ide> raise NotThisMethod("'git rev-parse' failed") <ide> full_out = full_out.strip() <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> pieces["short"] = full_out[:7] # maybe improved later <ide> pieces["error"] = None <ide> <add> branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], <add> cwd=root) <add> # --abbrev-ref was added in git-1.6.3 <add> if rc != 0 or branch_name is None: <add> raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") <add> branch_name = branch_name.strip() <add> <add> if branch_name == "HEAD": <add> # If we aren't exactly on a branch, pick a branch which represents <add> # the current commit. If all else fails, we are on a branchless <add> # commit. <add> branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) <add> # --contains was added in git-1.5.4 <add> if rc != 0 or branches is None: <add> raise NotThisMethod("'git branch --contains' returned error") <add> branches = branches.split("\n") <add> <add> # Remove the first line if we're running detached <add> if "(" in branches[0]: <add> branches.pop(0) <add> <add> # Strip off the leading "* " from the list of branches. <add> branches = [branch[2:] for branch in branches] <add> if "master" in branches: <add> branch_name = "master" <add> elif not branches: <add> branch_name = None <add> else: <add> # Pick the first branch that is returned. Good or bad. <add> branch_name = branches[0] <add> <add> pieces["branch"] = branch_name <add> <ide> # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] <ide> # TAG might have hyphens. <ide> git_describe = describe_out <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> # TAG-NUM-gHEX <ide> mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) <ide> if not mo: <del> # unparseable. Maybe git-describe is misbehaving? <add> # unparsable. Maybe git-describe is misbehaving? <ide> pieces["error"] = ("unable to parse git-describe output: '%%s'" <ide> %% describe_out) <ide> return pieces <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> else: <ide> # HEX: no tags <ide> pieces["closest-tag"] = None <del> count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], <del> cwd=root) <del> pieces["distance"] = int(count_out) # total number of commits <add> out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) <add> pieces["distance"] = len(out.split()) # total number of commits <ide> <ide> # commit date: see ISO-8601 comment in git_versions_from_keywords() <del> date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], <del> cwd=root)[0].strip() <add> date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() <ide> # Use only the last line. Previous lines may contain GPG signature <ide> # information. <ide> date = date.splitlines()[-1] <ide> def render_pep440(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_branch(pieces): <add> """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. Note that .dev0 sorts backwards <add> (a feature branch will appear "older" than the master branch). <add> <add> Exceptions: <add> 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0" <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], <add> pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <add>def pep440_split_post(ver): <add> """Split pep440 version string at the post-release segment. <add> <add> Returns the release segments before the post-release and the <add> post-release version number (or -1 if no post-release segment is present). <add> """ <add> vc = str.split(ver, ".post") <add> return vc[0], int(vc[1] or 0) if len(vc) == 2 else None <add> <add> <ide> def render_pep440_pre(pieces): <del> """TAG[.post0.devDISTANCE] -- No -dirty. <add> """TAG[.postN.devDISTANCE] -- No -dirty. <ide> <ide> Exceptions: <ide> 1: no tags. 0.post0.devDISTANCE <ide> """ <ide> if pieces["closest-tag"]: <del> rendered = pieces["closest-tag"] <ide> if pieces["distance"]: <del> rendered += ".post0.dev%%d" %% pieces["distance"] <add> # update the post release segment <add> tag_version, post_version = pep440_split_post(pieces["closest-tag"]) <add> rendered = tag_version <add> if post_version is not None: <add> rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) <add> else: <add> rendered += ".post0.dev%%d" %% (pieces["distance"]) <add> else: <add> # no commits, use the tag as the version <add> rendered = pieces["closest-tag"] <ide> else: <ide> # exception #1 <ide> rendered = "0.post0.dev%%d" %% pieces["distance"] <ide> def render_pep440_post(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_post_branch(pieces): <add> """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. <add> <add> Exceptions: <add> 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> rendered += ".post%%d" %% pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "g%%s" %% pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0.post%%d" %% pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+g%%s" %% pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <ide> def render_pep440_old(pieces): <ide> """TAG[.postDISTANCE[.dev0]] . <ide> <ide> def render(pieces, style): <ide> <ide> if style == "pep440": <ide> rendered = render_pep440(pieces) <add> elif style == "pep440-branch": <add> rendered = render_pep440_branch(pieces) <ide> elif style == "pep440-pre": <ide> rendered = render_pep440_pre(pieces) <ide> elif style == "pep440-post": <ide> rendered = render_pep440_post(pieces) <add> elif style == "pep440-post-branch": <add> rendered = render_pep440_post_branch(pieces) <ide> elif style == "pep440-old": <ide> rendered = render_pep440_old(pieces) <ide> elif style == "git-describe": <ide> def get_versions(): <ide> # versionfile_source is the relative path from the top of the source <ide> # tree (where the .git directory might live) to this file. Invert <ide> # this to find the root from __file__. <del> for i in cfg.versionfile_source.split('/'): <add> for _ in cfg.versionfile_source.split('/'): <ide> root = os.path.dirname(root) <ide> except NameError: <ide> return {"version": "0+unknown", "full-revisionid": None, <ide> def git_get_keywords(versionfile_abs): <ide> # _version.py. <ide> keywords = {} <ide> try: <del> with open(versionfile_abs, "r") as f: <del> for line in f.readlines(): <add> with open(versionfile_abs, "r") as fobj: <add> for line in fobj: <ide> if line.strip().startswith("git_refnames ="): <ide> mo = re.search(r'=\s*"(.*)"', line) <ide> if mo: <ide> def git_get_keywords(versionfile_abs): <ide> mo = re.search(r'=\s*"(.*)"', line) <ide> if mo: <ide> keywords["date"] = mo.group(1) <del> except EnvironmentError: <add> except OSError: <ide> pass <ide> return keywords <ide> <ide> <ide> @register_vcs_handler("git", "keywords") <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> """Get version information from git keywords.""" <del> if not keywords: <del> raise NotThisMethod("no keywords at all, weird") <add> if "refnames" not in keywords: <add> raise NotThisMethod("Short version file found") <ide> date = keywords.get("date") <ide> if date is not None: <ide> # Use only the last line. Previous lines may contain GPG signature <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> if verbose: <ide> print("keywords are unexpanded, not using") <ide> raise NotThisMethod("unexpanded keywords, not a git-archive tarball") <del> refs = set([r.strip() for r in refnames.strip("()").split(",")]) <add> refs = {r.strip() for r in refnames.strip("()").split(",")} <ide> # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of <ide> # just "foo-1.0". If we see a "tag: " prefix, prefer those. <ide> TAG = "tag: " <del> tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) <add> tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} <ide> if not tags: <ide> # Either we're using git < 1.8.3, or there really are no tags. We use <ide> # a heuristic: assume all version tags have a digit. The old git %d <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> # between branches and tags. By ignoring refnames without digits, we <ide> # filter out many common branch names like "release" and <ide> # "stabilization", as well as "HEAD" and "master". <del> tags = set([r for r in refs if re.search(r'\d', r)]) <add> tags = {r for r in refs if re.search(r'\d', r)} <ide> if verbose: <ide> print("discarding '%s', no digits" % ",".join(refs - tags)) <ide> if verbose: <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> # sorting will prefer e.g. "2.0" over "2.0rc1" <ide> if ref.startswith(tag_prefix): <ide> r = ref[len(tag_prefix):] <add> # Filter out refs that exactly match prefix or that don't start <add> # with a number once the prefix is stripped (mostly a concern <add> # when prefix is '') <add> if not re.match(r'\d', r): <add> continue <ide> if verbose: <ide> print("picking %s" % r) <ide> return {"version": r, <ide> def git_versions_from_keywords(keywords, tag_prefix, verbose): <ide> <ide> <ide> @register_vcs_handler("git", "pieces_from_vcs") <del>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <add>def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): <ide> """Get version from 'git describe' in the root of the source tree. <ide> <ide> This only gets called if the git-archive 'subst' keywords were *not* <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> if sys.platform == "win32": <ide> GITS = ["git.cmd", "git.exe"] <ide> <del> out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, <del> hide_stderr=True) <add> # GIT_DIR can interfere with correct operation of Versioneer. <add> # It may be intended to be passed to the Versioneer-versioned project, <add> # but that should not change where we get our version from. <add> env = os.environ.copy() <add> env.pop("GIT_DIR", None) <add> runner = functools.partial(runner, env=env) <add> <add> _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, <add> hide_stderr=not verbose) <ide> if rc != 0: <ide> if verbose: <ide> print("Directory %s not under git control" % root) <ide> raise NotThisMethod("'git rev-parse --git-dir' returned error") <ide> <ide> # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] <ide> # if there isn't one, this yields HEX[-dirty] (no NUM) <del> describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", <del> "--always", "--long", <del> "--match", "%s*" % tag_prefix], <del> cwd=root) <add> describe_out, rc = runner(GITS, [ <add> "describe", "--tags", "--dirty", "--always", "--long", <add> "--match", f"{tag_prefix}[[:digit:]]*" <add> ], cwd=root) <ide> # --long was added in git-1.5.5 <ide> if describe_out is None: <ide> raise NotThisMethod("'git describe' failed") <ide> describe_out = describe_out.strip() <del> full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) <add> full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) <ide> if full_out is None: <ide> raise NotThisMethod("'git rev-parse' failed") <ide> full_out = full_out.strip() <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> pieces["short"] = full_out[:7] # maybe improved later <ide> pieces["error"] = None <ide> <add> branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], <add> cwd=root) <add> # --abbrev-ref was added in git-1.6.3 <add> if rc != 0 or branch_name is None: <add> raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") <add> branch_name = branch_name.strip() <add> <add> if branch_name == "HEAD": <add> # If we aren't exactly on a branch, pick a branch which represents <add> # the current commit. If all else fails, we are on a branchless <add> # commit. <add> branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) <add> # --contains was added in git-1.5.4 <add> if rc != 0 or branches is None: <add> raise NotThisMethod("'git branch --contains' returned error") <add> branches = branches.split("\n") <add> <add> # Remove the first line if we're running detached <add> if "(" in branches[0]: <add> branches.pop(0) <add> <add> # Strip off the leading "* " from the list of branches. <add> branches = [branch[2:] for branch in branches] <add> if "master" in branches: <add> branch_name = "master" <add> elif not branches: <add> branch_name = None <add> else: <add> # Pick the first branch that is returned. Good or bad. <add> branch_name = branches[0] <add> <add> pieces["branch"] = branch_name <add> <ide> # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] <ide> # TAG might have hyphens. <ide> git_describe = describe_out <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> # TAG-NUM-gHEX <ide> mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) <ide> if not mo: <del> # unparseable. Maybe git-describe is misbehaving? <add> # unparsable. Maybe git-describe is misbehaving? <ide> pieces["error"] = ("unable to parse git-describe output: '%s'" <ide> % describe_out) <ide> return pieces <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> else: <ide> # HEX: no tags <ide> pieces["closest-tag"] = None <del> count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], <del> cwd=root) <del> pieces["distance"] = int(count_out) # total number of commits <add> out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) <add> pieces["distance"] = len(out.split()) # total number of commits <ide> <ide> # commit date: see ISO-8601 comment in git_versions_from_keywords() <del> date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], <del> cwd=root)[0].strip() <add> date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() <ide> # Use only the last line. Previous lines may contain GPG signature <ide> # information. <ide> date = date.splitlines()[-1] <ide> def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): <ide> return pieces <ide> <ide> <del>def do_vcs_install(manifest_in, versionfile_source, ipy): <add>def do_vcs_install(versionfile_source, ipy): <ide> """Git-specific installation logic for Versioneer. <ide> <ide> For Git, this means creating/changing .gitattributes to mark _version.py <ide> def do_vcs_install(manifest_in, versionfile_source, ipy): <ide> GITS = ["git"] <ide> if sys.platform == "win32": <ide> GITS = ["git.cmd", "git.exe"] <del> files = [manifest_in, versionfile_source] <add> files = [versionfile_source] <ide> if ipy: <ide> files.append(ipy) <del> try: <del> me = __file__ <del> if me.endswith(".pyc") or me.endswith(".pyo"): <del> me = os.path.splitext(me)[0] + ".py" <del> versioneer_file = os.path.relpath(me) <del> except NameError: <del> versioneer_file = "versioneer.py" <del> files.append(versioneer_file) <add> if "VERSIONEER_PEP518" not in globals(): <add> try: <add> my_path = __file__ <add> if my_path.endswith(".pyc") or my_path.endswith(".pyo"): <add> my_path = os.path.splitext(my_path)[0] + ".py" <add> versioneer_file = os.path.relpath(my_path) <add> except NameError: <add> versioneer_file = "versioneer.py" <add> files.append(versioneer_file) <ide> present = False <ide> try: <del> with open(".gitattributes", "r") as f: <del> for line in f.readlines(): <add> with open(".gitattributes", "r") as fobj: <add> for line in fobj: <ide> if line.strip().startswith(versionfile_source): <ide> if "export-subst" in line.strip().split()[1:]: <ide> present = True <del> except EnvironmentError: <add> break <add> except OSError: <ide> pass <ide> if not present: <del> with open(".gitattributes", "a+") as f: <del> f.write("%s export-subst\n" % versionfile_source) <add> with open(".gitattributes", "a+") as fobj: <add> fobj.write(f"{versionfile_source} export-subst\n") <ide> files.append(".gitattributes") <ide> run_command(GITS, ["add", "--"] + files) <ide> <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> """ <ide> rootdirs = [] <ide> <del> for i in range(3): <add> for _ in range(3): <ide> dirname = os.path.basename(root) <ide> if dirname.startswith(parentdir_prefix): <ide> return {"version": dirname[len(parentdir_prefix):], <ide> "full-revisionid": None, <ide> "dirty": False, "error": None, "date": None} <del> else: <del> rootdirs.append(root) <del> root = os.path.dirname(root) # up a level <add> rootdirs.append(root) <add> root = os.path.dirname(root) # up a level <ide> <ide> if verbose: <ide> print("Tried directories %s but none started with prefix %s" % <ide> def versions_from_parentdir(parentdir_prefix, root, verbose): <ide> <ide> <ide> SHORT_VERSION_PY = """ <del># This file was generated by 'versioneer.py' (0.19) from <add># This file was generated by 'versioneer.py' (0.26) from <ide> # revision-control system data, or from the parent directory name of an <ide> # unpacked source archive. Distribution tarballs contain a pre-generated copy <ide> # of this file. <ide> def versions_from_file(filename): <ide> try: <ide> with open(filename) as f: <ide> contents = f.read() <del> except EnvironmentError: <add> except OSError: <ide> raise NotThisMethod("unable to read _version.py") <ide> mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", <ide> contents, re.M | re.S) <ide> def render_pep440(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_branch(pieces): <add> """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. Note that .dev0 sorts backwards <add> (a feature branch will appear "older" than the master branch). <add> <add> Exceptions: <add> 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0" <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+untagged.%d.g%s" % (pieces["distance"], <add> pieces["short"]) <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <add>def pep440_split_post(ver): <add> """Split pep440 version string at the post-release segment. <add> <add> Returns the release segments before the post-release and the <add> post-release version number (or -1 if no post-release segment is present). <add> """ <add> vc = str.split(ver, ".post") <add> return vc[0], int(vc[1] or 0) if len(vc) == 2 else None <add> <add> <ide> def render_pep440_pre(pieces): <del> """TAG[.post0.devDISTANCE] -- No -dirty. <add> """TAG[.postN.devDISTANCE] -- No -dirty. <ide> <ide> Exceptions: <ide> 1: no tags. 0.post0.devDISTANCE <ide> """ <ide> if pieces["closest-tag"]: <del> rendered = pieces["closest-tag"] <ide> if pieces["distance"]: <del> rendered += ".post0.dev%d" % pieces["distance"] <add> # update the post release segment <add> tag_version, post_version = pep440_split_post(pieces["closest-tag"]) <add> rendered = tag_version <add> if post_version is not None: <add> rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) <add> else: <add> rendered += ".post0.dev%d" % (pieces["distance"]) <add> else: <add> # no commits, use the tag as the version <add> rendered = pieces["closest-tag"] <ide> else: <ide> # exception #1 <ide> rendered = "0.post0.dev%d" % pieces["distance"] <ide> def render_pep440_post(pieces): <ide> return rendered <ide> <ide> <add>def render_pep440_post_branch(pieces): <add> """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . <add> <add> The ".dev0" means not master branch. <add> <add> Exceptions: <add> 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] <add> """ <add> if pieces["closest-tag"]: <add> rendered = pieces["closest-tag"] <add> if pieces["distance"] or pieces["dirty"]: <add> rendered += ".post%d" % pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += plus_or_dot(pieces) <add> rendered += "g%s" % pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> else: <add> # exception #1 <add> rendered = "0.post%d" % pieces["distance"] <add> if pieces["branch"] != "master": <add> rendered += ".dev0" <add> rendered += "+g%s" % pieces["short"] <add> if pieces["dirty"]: <add> rendered += ".dirty" <add> return rendered <add> <add> <ide> def render_pep440_old(pieces): <ide> """TAG[.postDISTANCE[.dev0]] . <ide> <ide> def render(pieces, style): <ide> <ide> if style == "pep440": <ide> rendered = render_pep440(pieces) <add> elif style == "pep440-branch": <add> rendered = render_pep440_branch(pieces) <ide> elif style == "pep440-pre": <ide> rendered = render_pep440_pre(pieces) <ide> elif style == "pep440-post": <ide> rendered = render_pep440_post(pieces) <add> elif style == "pep440-post-branch": <add> rendered = render_pep440_post_branch(pieces) <ide> elif style == "pep440-old": <ide> rendered = render_pep440_old(pieces) <ide> elif style == "git-describe": <ide> def get_version(): <ide> <ide> <ide> def get_cmdclass(cmdclass=None): <del> """Get the custom setuptools/distutils subclasses used by Versioneer. <add> """Get the custom setuptools subclasses used by Versioneer. <ide> <ide> If the package uses a different cmdclass (e.g. one from numpy), it <ide> should be provide as an argument. <ide> def get_cmdclass(cmdclass=None): <ide> <ide> cmds = {} if cmdclass is None else cmdclass.copy() <ide> <del> # we add "version" to both distutils and setuptools <del> from distutils.core import Command <add> # we add "version" to setuptools <add> from setuptools import Command <ide> <ide> class cmd_version(Command): <ide> description = "report generated version string" <ide> def run(self): <ide> print(" error: %s" % vers["error"]) <ide> cmds["version"] = cmd_version <ide> <del> # we override "build_py" in both distutils and setuptools <add> # we override "build_py" in setuptools <ide> # <ide> # most invocation pathways end up running build_py: <ide> # distutils/build -> build_py <ide> def run(self): <ide> # then does setup.py bdist_wheel, or sometimes setup.py install <ide> # setup.py egg_info -> ? <ide> <add> # pip install -e . and setuptool/editable_wheel will invoke build_py <add> # but the build_py command is not expected to copy any files. <add> <ide> # we override different "build_py" commands for both environments <ide> if 'build_py' in cmds: <ide> _build_py = cmds['build_py'] <del> elif "setuptools" in sys.modules: <del> from setuptools.command.build_py import build_py as _build_py <ide> else: <del> from distutils.command.build_py import build_py as _build_py <add> from setuptools.command.build_py import build_py as _build_py <ide> <ide> class cmd_build_py(_build_py): <ide> def run(self): <ide> root = get_root() <ide> cfg = get_config_from_root(root) <ide> versions = get_versions() <ide> _build_py.run(self) <add> if getattr(self, "editable_mode", False): <add> # During editable installs `.py` and data files are <add> # not copied to build_lib <add> return <ide> # now locate _version.py in the new build/ directory and replace <ide> # it with an updated value <ide> if cfg.versionfile_build: <ide> def run(self): <ide> write_to_version_file(target_versionfile, versions) <ide> cmds["build_py"] = cmd_build_py <ide> <del> if "setuptools" in sys.modules: <del> from setuptools.command.build_ext import build_ext as _build_ext <add> if 'build_ext' in cmds: <add> _build_ext = cmds['build_ext'] <ide> else: <del> from distutils.command.build_ext import build_ext as _build_ext <add> from setuptools.command.build_ext import build_ext as _build_ext <ide> <ide> class cmd_build_ext(_build_ext): <ide> def run(self): <ide> def run(self): <ide> # now locate _version.py in the new build/ directory and replace <ide> # it with an updated value <ide> target_versionfile = os.path.join(self.build_lib, <del> cfg.versionfile_source) <add> cfg.versionfile_build) <add> if not os.path.exists(target_versionfile): <add> print(f"Warning: {target_versionfile} does not exist, skipping " <add> "version update. This can happen if you are running build_ext " <add> "without first running build_py.") <add> return <ide> print("UPDATING %s" % target_versionfile) <ide> write_to_version_file(target_versionfile, versions) <ide> cmds["build_ext"] = cmd_build_ext <ide> def run(self): <ide> del cmds["build_py"] <ide> <ide> if 'py2exe' in sys.modules: # py2exe enabled? <del> from py2exe.distutils_buildexe import py2exe as _py2exe <add> try: <add> from py2exe.setuptools_buildexe import py2exe as _py2exe <add> except ImportError: <add> from py2exe.distutils_buildexe import py2exe as _py2exe <ide> <ide> class cmd_py2exe(_py2exe): <ide> def run(self): <ide> def run(self): <ide> }) <ide> cmds["py2exe"] = cmd_py2exe <ide> <add> # sdist farms its file list building out to egg_info <add> if 'egg_info' in cmds: <add> _sdist = cmds['egg_info'] <add> else: <add> from setuptools.command.egg_info import egg_info as _egg_info <add> <add> class cmd_egg_info(_egg_info): <add> def find_sources(self): <add> # egg_info.find_sources builds the manifest list and writes it <add> # in one shot <add> super().find_sources() <add> <add> # Modify the filelist and normalize it <add> root = get_root() <add> cfg = get_config_from_root(root) <add> self.filelist.append('versioneer.py') <add> if cfg.versionfile_source: <add> # There are rare cases where versionfile_source might not be <add> # included by default, so we must be explicit <add> self.filelist.append(cfg.versionfile_source) <add> self.filelist.sort() <add> self.filelist.remove_duplicates() <add> <add> # The write method is hidden in the manifest_maker instance that <add> # generated the filelist and was thrown away <add> # We will instead replicate their final normalization (to unicode, <add> # and POSIX-style paths) <add> from setuptools import unicode_utils <add> normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') <add> for f in self.filelist.files] <add> <add> manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') <add> with open(manifest_filename, 'w') as fobj: <add> fobj.write('\n'.join(normalized)) <add> <add> cmds['egg_info'] = cmd_egg_info <add> <ide> # we override different "sdist" commands for both environments <ide> if 'sdist' in cmds: <ide> _sdist = cmds['sdist'] <del> elif "setuptools" in sys.modules: <del> from setuptools.command.sdist import sdist as _sdist <ide> else: <del> from distutils.command.sdist import sdist as _sdist <add> from setuptools.command.sdist import sdist as _sdist <ide> <ide> class cmd_sdist(_sdist): <ide> def run(self): <ide> def make_release_tree(self, base_dir, files): <ide> <ide> """ <ide> <del>INIT_PY_SNIPPET = """ <add>OLD_SNIPPET = """ <ide> from ._version import get_versions <ide> __version__ = get_versions()['version'] <ide> del get_versions <ide> """ <ide> <add>INIT_PY_SNIPPET = """ <add>from . import {0} <add>__version__ = {0}.get_versions()['version'] <add>""" <add> <ide> <ide> def do_setup(): <ide> """Do main VCS-independent setup function for installing Versioneer.""" <ide> root = get_root() <ide> try: <ide> cfg = get_config_from_root(root) <del> except (EnvironmentError, configparser.NoSectionError, <add> except (OSError, configparser.NoSectionError, <ide> configparser.NoOptionError) as e: <del> if isinstance(e, (EnvironmentError, configparser.NoSectionError)): <add> if isinstance(e, (OSError, configparser.NoSectionError)): <ide> print("Adding sample versioneer config to setup.cfg", <ide> file=sys.stderr) <ide> with open(os.path.join(root, "setup.cfg"), "a") as f: <ide> def do_setup(): <ide> try: <ide> with open(ipy, "r") as f: <ide> old = f.read() <del> except EnvironmentError: <add> except OSError: <ide> old = "" <del> if INIT_PY_SNIPPET not in old: <add> module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] <add> snippet = INIT_PY_SNIPPET.format(module) <add> if OLD_SNIPPET in old: <add> print(" replacing boilerplate in %s" % ipy) <add> with open(ipy, "w") as f: <add> f.write(old.replace(OLD_SNIPPET, snippet)) <add> elif snippet not in old: <ide> print(" appending to %s" % ipy) <ide> with open(ipy, "a") as f: <del> f.write(INIT_PY_SNIPPET) <add> f.write(snippet) <ide> else: <ide> print(" %s unmodified" % ipy) <ide> else: <ide> print(" %s doesn't exist, ok" % ipy) <ide> ipy = None <ide> <del> # Make sure both the top-level "versioneer.py" and versionfile_source <del> # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so <del> # they'll be copied into source distributions. Pip won't be able to <del> # install the package without this. <del> manifest_in = os.path.join(root, "MANIFEST.in") <del> simple_includes = set() <del> try: <del> with open(manifest_in, "r") as f: <del> for line in f: <del> if line.startswith("include "): <del> for include in line.split()[1:]: <del> simple_includes.add(include) <del> except EnvironmentError: <del> pass <del> # That doesn't cover everything MANIFEST.in can do <del> # (http://docs.python.org/2/distutils/sourcedist.html#commands), so <del> # it might give some false negatives. Appending redundant 'include' <del> # lines is safe, though. <del> if "versioneer.py" not in simple_includes: <del> print(" appending 'versioneer.py' to MANIFEST.in") <del> with open(manifest_in, "a") as f: <del> f.write("include versioneer.py\n") <del> else: <del> print(" 'versioneer.py' already in MANIFEST.in") <del> if cfg.versionfile_source not in simple_includes: <del> print(" appending versionfile_source ('%s') to MANIFEST.in" % <del> cfg.versionfile_source) <del> with open(manifest_in, "a") as f: <del> f.write("include %s\n" % cfg.versionfile_source) <del> else: <del> print(" versionfile_source already in MANIFEST.in") <del> <ide> # Make VCS-specific changes. For git, this means creating/changing <ide> # .gitattributes to mark _version.py for export-subst keyword <ide> # substitution. <del> do_vcs_install(manifest_in, cfg.versionfile_source, ipy) <add> do_vcs_install(cfg.versionfile_source, ipy) <ide> return 0 <ide> <ide> <ide> def scan_setup_py(): <ide> return errors <ide> <ide> <add>def setup_command(): <add> """Set up Versioneer and exit with appropriate error code.""" <add> errors = do_setup() <add> errors += scan_setup_py() <add> sys.exit(1 if errors else 0) <add> <add> <ide> if __name__ == "__main__": <ide> cmd = sys.argv[1] <ide> if cmd == "setup": <del> errors = do_setup() <del> errors += scan_setup_py() <del> if errors: <del> sys.exit(1) <add> setup_command()
2
Python
Python
remove deprecated items from ma/core.py
ceb9ded475887c25299d798ac90094b74d593a61
<ide><path>numpy/ma/core.py <ide> def is_mask(m): <ide> except AttributeError: <ide> return False <ide> <del>def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType): <add>def make_mask(m, copy=False, shrink=True, dtype=MaskType): <ide> """ <ide> Create a boolean mask from an array. <ide> <ide> def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType): <ide> Whether to return a copy of `m` (True) or `m` itself (False). <ide> shrink : bool, optional <ide> Whether to shrink `m` to ``nomask`` if all its values are False. <del> flag : bool, optional <del> Deprecated equivalent of `shrink`. <ide> dtype : dtype, optional <ide> Data-type of the output mask. By default, the output mask has <ide> a dtype of MaskType (bool). If the dtype is flexible, each field <ide> def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType): <ide> dtype=[('man', '|b1'), ('mouse', '|b1')]) <ide> <ide> """ <del> if flag is not None: <del> warnings.warn("The flag 'flag' is now called 'shrink'!", <del> DeprecationWarning) <del> shrink = flag <ide> if m is nomask: <ide> return nomask <ide> elif isinstance(m, ndarray): <ide> class MaskedArray(ndarray): <ide> <ide> x = MaskedArray(data, mask=nomask, dtype=None, <ide> copy=False, subok=True, ndmin=0, fill_value=None, <del> keep_mask=True, hard_mask=None, flag=None, shrink=True) <add> keep_mask=True, hard_mask=None, shrink=True) <ide> <ide> Parameters <ide> ---------- <ide> class MaskedArray(ndarray): <ide> <ide> def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, <ide> subok=True, ndmin=0, fill_value=None, <del> keep_mask=True, hard_mask=None, flag=None, shrink=True, <add> keep_mask=True, hard_mask=None, shrink=True, <ide> **options): <ide> """ <ide> Create a new masked array from scratch. <ide> def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, <ide> A masked array can also be created by taking a .view(MaskedArray). <ide> <ide> """ <del> if flag is not None: <del> warnings.warn("The flag 'flag' is now called 'shrink'!", <del> DeprecationWarning) <del> shrink = flag <ide> # Process data............ <ide> _data = np.array(data, dtype=dtype, copy=copy, subok=True, ndmin=ndmin) <ide> _baseclass = getattr(data, '_baseclass', type(_data)) <ide> def _get_data(self): <ide> _data = property(fget=_get_data) <ide> data = property(fget=_get_data) <ide> <del> def raw_data(self): <del> """ <del> Return the data part of the masked array. <del> <del> DEPRECATED: You should really use ``.data`` instead. <del> <del> Examples <del> -------- <del> >>> x = np.ma.array([1, 2, 3], mask=[False, True, False]) <del> >>> x <del> masked_array(data = [1 -- 3], <del> mask = [False True False], <del> fill_value = 999999) <del> >>> x.data <del> array([1, 2, 3]) <del> <del> """ <del> warnings.warn('Use .data instead.', DeprecationWarning) <del> return self._data <del> <del> <ide> def _get_flat(self): <ide> "Return a flat iterator." <ide> return MaskedIterator(self) <ide> def sort(self, axis= -1, kind='quicksort', order=None, <ide> >>> a.sort(endwith=False, fill_value=3) <ide> >>> print a <ide> [1 -- -- 3 5] <del> <add> <ide> """ <ide> if self._mask is nomask: <ide> ndarray.sort(self, axis=axis, kind=kind, order=order) <ide> def allequal (a, b, fill_value=True): <ide> else: <ide> return False <ide> <del>def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8, fill_value=None): <add>def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8): <ide> """ <ide> Returns True if two arrays are element-wise equal within a tolerance. <ide> <ide> def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8, fill_value=None): <ide> atol : float, optional <ide> Absolute tolerance. The absolute difference is equal to `atol`. <ide> Default is 1e-8. <del> fill_value : bool, optional <del> *Deprecated* - Whether masked values in `a` or `b` are considered equal <del> (True) or not (False). <ide> <ide> Returns <ide> ------- <ide> def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8, fill_value=None): <ide> False <ide> <ide> """ <del> if fill_value is not None: <del> warnings.warn("The use of fill_value is deprecated."\ <del> " Please use masked_equal instead.") <del> masked_equal = fill_value <del> # <ide> x = masked_array(a, copy=False) <ide> y = masked_array(b, copy=False) <ide> m = mask_or(getmask(x), getmask(y)) <ide><path>numpy/ma/tests/test_core.py <ide> def test_indexing(self): <ide> junk, garbage = str(x2), repr(x2) <ide> assert_equal(np.sort(x1), sort(x2, endwith=False)) <ide> # tests of indexing <del> assert type(x2[1]) is type(x1[1]) <del> assert x1[1] == x2[1] <del> assert x2[0] is masked <add> assert_(type(x2[1]) is type(x1[1])) <add> assert_(x1[1] == x2[1]) <add> assert_(x2[0] is masked) <ide> assert_equal(x1[2], x2[2]) <ide> assert_equal(x1[2:5], x2[2:5]) <ide> assert_equal(x1[:], x2[:]) <ide> def test_indexing(self): <ide> assert_equal(x1, x2) <ide> x2[:] = x1 <ide> x2[1] = masked <del> assert allequal(getmask(x2), array([0, 1, 0, 0])) <add> assert_(allequal(getmask(x2), array([0, 1, 0, 0]))) <ide> x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) <del> assert allequal(getmask(x3), array([0, 1, 1, 0])) <add> assert_(allequal(getmask(x3), array([0, 1, 1, 0]))) <ide> x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) <del> assert allequal(getmask(x4), array([0, 1, 1, 0])) <del> assert allequal(x4, array([1, 2, 3, 4])) <add> assert_(allequal(getmask(x4), array([0, 1, 1, 0]))) <add> assert_(allequal(x4, array([1, 2, 3, 4]))) <ide> x1 = np.arange(5) * 1.0 <ide> x2 = masked_values(x1, 3.0) <ide> assert_equal(x1, x2) <del> assert allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask) <add> assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask)) <ide> assert_equal(3.0, x2.fill_value) <ide> x1 = array([1, 'hello', 2, 3], object) <ide> x2 = np.array([1, 'hello', 2, 3], object) <ide> def test_indexing(self): <ide> assert_equal(type(s2), str) <ide> assert_equal(type(s1), str) <ide> assert_equal(s1, s2) <del> assert x1[1:1].shape == (0,) <add> assert_(x1[1:1].shape == (0,)) <ide> <ide> <ide> def test_copy(self): <ide> def test_copy(self): <ide> m3 = make_mask(m, copy=1) <ide> self.assertTrue(m is not m3) <ide> <del> warnings.simplefilter('ignore', DeprecationWarning) <ide> x1 = np.arange(5) <ide> y1 = array(x1, mask=m) <ide> #self.assertTrue( y1._data is x1) <ide> assert_equal(y1._data.__array_interface__, x1.__array_interface__) <del> self.assertTrue(allequal(x1, y1.raw_data())) <add> self.assertTrue(allequal(x1, y1.data)) <ide> #self.assertTrue( y1.mask is m) <ide> assert_equal(y1._mask.__array_interface__, m.__array_interface__) <del> warnings.simplefilter('default', DeprecationWarning) <ide> <ide> y1a = array(y1) <del> #self.assertTrue( y1a.raw_data() is y1.raw_data()) <ide> self.assertTrue(y1a._data.__array_interface__ == y1._data.__array_interface__) <ide> self.assertTrue(y1a.mask is y1.mask) <ide> <ide> y2 = array(x1, mask=m) <del> #self.assertTrue( y2.raw_data() is x1) <ide> self.assertTrue(y2._data.__array_interface__ == x1.__array_interface__) <ide> #self.assertTrue( y2.mask is m) <ide> self.assertTrue(y2._mask.__array_interface__ == m.__array_interface__) <ide> def test_topython(self): <ide> self.assertRaises(TypeError, float, array([1, 1])) <ide> # <ide> warnings.simplefilter('ignore', UserWarning) <del> assert np.isnan(float(array([1], mask=[1]))) <add> assert_(np.isnan(float(array([1], mask=[1])))) <ide> warnings.simplefilter('default', UserWarning) <ide> # <ide> a = array([1, 2, 3], mask=[1, 0, 0]) <ide> def test_oddfeatures_1(self): <ide> x = arange(20) <ide> x = x.reshape(4, 5) <ide> x.flat[5] = 12 <del> assert x[1, 0] == 12 <add> assert_(x[1, 0] == 12) <ide> z = x + 10j * x <ide> assert_equal(z.real, x) <ide> assert_equal(z.imag, 10 * x) <ide> def test_oddfeatures_1(self): <ide> # <ide> x = arange(10) <ide> x[3] = masked <del> assert str(x[3]) == str(masked) <add> assert_(str(x[3]) == str(masked)) <ide> c = x >= 8 <del> assert count(where(c, masked, masked)) == 0 <del> assert shape(where(c, masked, masked)) == c.shape <add> assert_(count(where(c, masked, masked)) == 0) <add> assert_(shape(where(c, masked, masked)) == c.shape) <ide> # <ide> z = masked_where(c, x) <del> assert z.dtype is x.dtype <del> assert z[3] is masked <del> assert z[4] is not masked <del> assert z[7] is not masked <del> assert z[8] is masked <del> assert z[9] is masked <add> assert_(z.dtype is x.dtype) <add> assert_(z[3] is masked) <add> assert_(z[4] is not masked) <add> assert_(z[7] is not masked) <add> assert_(z[8] is masked) <add> assert_(z[9] is masked) <ide> assert_equal(x, z) <ide> <ide> <ide> def test_oddfeatures_2(self): <ide> c[0] = masked <ide> z = where(c, x, -x) <ide> assert_equal(z, [1., 2., 0., -4., -5]) <del> assert z[0] is masked <del> assert z[1] is not masked <del> assert z[2] is masked <add> assert_(z[0] is masked) <add> assert_(z[1] is not masked) <add> assert_(z[2] is masked) <ide> <ide> <ide> def test_oddfeatures_3(self): <ide> def test_arithmetic_with_masked_singleton(self): <ide> assert_equal(y.shape, x.shape) <ide> assert_equal(y._mask, [True, True]) <ide> y = x[0] * masked <del> assert y is masked <add> assert_(y is masked) <ide> y = x + masked <ide> assert_equal(y.shape, x.shape) <ide> assert_equal(y._mask, [True, True]) <ide> def test_count_func (self): <ide> assert_equal(1, count(1)) <ide> assert_equal(0, array(1, mask=[1])) <ide> ott = ott.reshape((2, 2)) <del> assert isinstance(count(ott, 0), ndarray) <add> assert_(isinstance(count(ott, 0), ndarray)) <ide> if sys.version_info[0] >= 3: <del> assert isinstance(count(ott), np.integer) <add> assert_(isinstance(count(ott), np.integer)) <ide> else: <del> assert isinstance(count(ott), types.IntType) <add> assert_(isinstance(count(ott), types.IntType)) <ide> assert_equal(3, count(ott)) <del> assert getmask(count(ott, 0)) is nomask <add> assert_(getmask(count(ott, 0)) is nomask) <ide> assert_equal([1, 2], count(ott, 0)) <ide> <ide> <ide> def test_minmax_func (self): <ide> y[0] = masked <ide> assert_equal(minimum(x, y), where(less(x, y), x, y)) <ide> assert_equal(maximum(x, y), where(greater(x, y), x, y)) <del> assert minimum(x) == 0 <del> assert maximum(x) == 4 <add> assert_(minimum(x) == 0) <add> assert_(maximum(x) == 4) <ide> # <ide> x = arange(4).reshape(2, 2) <ide> x[-1, -1] = masked <ide> def test_TakeTransposeInnerOuter(self): <ide> y = array(['abc', 1, 'def', 2, 3], object) <ide> y[2] = masked <ide> t = take(y, [0, 3, 4]) <del> assert t[0] == 'abc' <del> assert t[1] == 2 <del> assert t[2] == 3 <add> assert_(t[0] == 'abc') <add> assert_(t[1] == 2) <add> assert_(t[2] == 3) <ide> <ide> <ide> def test_imag_real(self): <ide> def test_inplace_addition_scalar(self): <ide> xm += 1 <ide> assert_equal(xm, y + 1) <ide> # <del> warnings.simplefilter('ignore', DeprecationWarning) <ide> (x, _, xm) = self.floatdata <del> id1 = x.raw_data().ctypes._data <add> id1 = x.data.ctypes._data <ide> x += 1. <del> assert (id1 == x.raw_data().ctypes._data) <add> assert_(id1 == x.data.ctypes._data) <ide> assert_equal(x, y + 1.) <del> warnings.simplefilter('default', DeprecationWarning) <ide> <ide> def test_inplace_addition_array(self): <ide> """Test of inplace additions""" <ide> def test_allany(self): <ide> mxbig = (mx > 0.5) <ide> mxsmall = (mx < 0.5) <ide> # <del> assert (mxbig.all() == False) <del> assert (mxbig.any() == True) <add> assert_((mxbig.all() == False)) <add> assert_((mxbig.any() == True)) <ide> assert_equal(mxbig.all(0), [False, False, True]) <ide> assert_equal(mxbig.all(1), [False, False, True]) <ide> assert_equal(mxbig.any(0), [False, False, True]) <ide> assert_equal(mxbig.any(1), [True, True, True]) <ide> # <del> assert (mxsmall.all() == False) <del> assert (mxsmall.any() == True) <add> assert_((mxsmall.all() == False)) <add> assert_((mxsmall.any() == True)) <ide> assert_equal(mxsmall.all(0), [True, True, False]) <ide> assert_equal(mxsmall.all(1), [False, False, False]) <ide> assert_equal(mxsmall.any(0), [True, True, False]) <ide> def test_allany_onmatrices(self): <ide> mXbig = (mX > 0.5) <ide> mXsmall = (mX < 0.5) <ide> # <del> assert (mXbig.all() == False) <del> assert (mXbig.any() == True) <add> assert_((mXbig.all() == False)) <add> assert_((mXbig.any() == True)) <ide> assert_equal(mXbig.all(0), np.matrix([False, False, True])) <ide> assert_equal(mXbig.all(1), np.matrix([False, False, True]).T) <ide> assert_equal(mXbig.any(0), np.matrix([False, False, True])) <ide> assert_equal(mXbig.any(1), np.matrix([ True, True, True]).T) <ide> # <del> assert (mXsmall.all() == False) <del> assert (mXsmall.any() == True) <add> assert_((mXsmall.all() == False)) <add> assert_((mXsmall.any() == True)) <ide> assert_equal(mXsmall.all(0), np.matrix([True, True, False])) <ide> assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T) <ide> assert_equal(mXsmall.any(0), np.matrix([True, True, False])) <ide> def test_round(self): <ide> c[0] = masked <ide> z = where(c, x, -x) <ide> assert_equal(z, [1., 2., 0., -4., -5]) <del> assert z[0] is masked <del> assert z[1] is not masked <del> assert z[2] is masked <add> assert_(z[0] is masked) <add> assert_(z[1] is not masked) <add> assert_(z[2] is masked) <ide> <ide> <ide> def test_round_with_output(self): <ide> def test_where_with_masked_choice(self): <ide> c = x >= 8 <ide> # Set False to masked <ide> z = where(c , x, masked) <del> assert z.dtype is x.dtype <del> assert z[3] is masked <del> assert z[4] is masked <del> assert z[7] is masked <del> assert z[8] is not masked <del> assert z[9] is not masked <add> assert_(z.dtype is x.dtype) <add> assert_(z[3] is masked) <add> assert_(z[4] is masked) <add> assert_(z[7] is masked) <add> assert_(z[8] is not masked) <add> assert_(z[9] is not masked) <ide> assert_equal(x, z) <ide> # Set True to masked <ide> z = where(c , masked, x) <del> assert z.dtype is x.dtype <del> assert z[3] is masked <del> assert z[4] is not masked <del> assert z[7] is not masked <del> assert z[8] is masked <del> assert z[9] is masked <add> assert_(z.dtype is x.dtype) <add> assert_(z[3] is masked) <add> assert_(z[4] is not masked) <add> assert_(z[7] is not masked) <add> assert_(z[8] is masked) <add> assert_(z[9] is masked) <ide> <ide> def test_where_with_masked_condition(self): <ide> x = array([1., 2., 3., 4., 5.]) <ide> def test_where_with_masked_condition(self): <ide> c[0] = masked <ide> z = where(c, x, -x) <ide> assert_equal(z, [1., 2., 0., -4., -5]) <del> assert z[0] is masked <del> assert z[1] is not masked <del> assert z[2] is masked <add> assert_(z[0] is masked) <add> assert_(z[1] is not masked) <add> assert_(z[2] is masked) <ide> # <ide> x = arange(1, 6) <ide> x[-1] = masked <ide> def test_where_with_masked_condition(self): <ide> z = where(c, x, y) <ide> zm = where(cm, x, y) <ide> assert_equal(z, zm) <del> assert getmask(zm) is nomask <add> assert_(getmask(zm) is nomask) <ide> assert_equal(zm, [1, 2, 3, 40, 50]) <ide> z = where(c, masked, 1) <ide> assert_equal(z, [99, 99, 99, 1, 1])
2
Ruby
Ruby
add docs for `object.nil!`
0222cefc405c4de7e4667a20c8e3cc4fd3200497
<ide><path>activesupport/lib/active_support/core_ext/object/try.rb <ide> def try(*a, &b) <ide> try!(*a, &b) if a.empty? || respond_to?(a.first) <ide> end <ide> <del> # Same as #try, but will raise a NoMethodError exception if the receiver is not +nil+ and <del> # does not implement the tried method. <del> <add> # Same as #try, but will raise a NoMethodError exception if the receiver is <add> # not +nil+ and does not implement the tried method. <add> # <add> # "a".try!(:upcase) # => "A" <add> # nil.try!(:upcase) # => nil <add> # 123.try!(:upcase) # => NoMethodError: undefined method `upcase' for 123:Fixnum <ide> def try!(*a, &b) <ide> if a.empty? && block_given? <ide> if b.arity.zero? <ide> def try(*args) <ide> nil <ide> end <ide> <add> # Calling +try!+ on +nil+ always returns +nil+. <add> # <add> # nil.try!(:name) # => nil <ide> def try!(*args) <ide> nil <ide> end
1
Text
Text
remove macvtkitkpythonbottles from doc
8f072724def466a37543ec279876fada932109b7
<ide><path>share/doc/homebrew/Interesting-Taps-&-Branches.md <ide> You can be added as a maintainer for one of the Homebrew organization taps and a <ide> * [petere/postgresql](https://github.com/petere/homebrew-postgresql) <ide> - Allows installing multiple PostgreSQL versions in parallel. <ide> <del>* [iMichka/MacVTKITKPythonBottles](https://github.com/iMichka/homebrew-MacVTKITKPythonBottles) <del> - VTK and ITK binaries with Python wrapping. <del> <ide> * [edavis/emacs](https://github.com/edavis/homebrew-emacs) <ide> - A tap for Emacs packages. <ide>
1
Java
Java
add throwable functional interfaces
b3efdf3c2b5b55624164d184d237795be6e7b3b5
<ide><path>spring-core/src/main/java/org/springframework/util/function/ThrowingBiFunction.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.util.function.BiFunction; <add> <add>/** <add> * A {@link BiFunction} that allows invocation of code that throws a checked <add> * exception. <add> * <add> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @since 6.0 <add> * @param <T> the type of the first argument to the function <add> * @param <U> the type of the second argument to the function <add> * @param <R> the type of the result of the function <add> */ <add>public interface ThrowingBiFunction<T, U, R> extends BiFunction<T, U, R> { <add> <add> /** <add> * Applies this function to the given argument, possibly throwing a checked <add> * exception. <add> * @param t the first function argument <add> * @param u the second function argument <add> * @return the function result <add> * @throws Exception on error <add> */ <add> R applyWithException(T t, U u) throws Exception; <add> <add> /** <add> * Default {@link BiFunction#apply(Object, Object)} that wraps any thrown <add> * checked exceptions (by default in a {@link RuntimeException}). <add> * @param t the first function argument <add> * @param u the second function argument <add> * @return the function result <add> * @see java.util.function.BiFunction#apply(Object, Object) <add> */ <add> @Override <add> default R apply(T t, U u) { <add> return apply(t, u, RuntimeException::new); <add> } <add> <add> /** <add> * Applies this function to the given argument, wrapping any thrown checked <add> * exceptions using the given {@code exceptionWrapper}. <add> * @param t the first function argument <add> * @param u the second function argument <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return a result <add> */ <add> default R apply(T t, U u, BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> try { <add> return applyWithException(t, u); <add> } <add> catch (RuntimeException ex) { <add> throw ex; <add> } <add> catch (Exception ex) { <add> throw exceptionWrapper.apply(ex.getMessage(), ex); <add> } <add> } <add> <add> /** <add> * Return a new {@link ThrowingBiFunction} where the <add> * {@link #apply(Object, Object)} method wraps any thrown checked exceptions <add> * using the given {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return the replacement {@link ThrowingBiFunction} instance <add> */ <add> default ThrowingBiFunction<T, U, R> throwing(BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> return new ThrowingBiFunction<>() { <add> <add> @Override <add> public R applyWithException(T t, U u) throws Exception { <add> return ThrowingBiFunction.this.applyWithException(t, u); <add> } <add> <add> @Override <add> public R apply(T t, U u) { <add> return apply(t, u, exceptionWrapper); <add> } <add> <add> }; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingBiFunction} where the {@link #apply(Object, Object)} <add> * method wraps any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param <T> the type of the first argument to the function <add> * @param <U> the type of the second argument to the function <add> * @param <R> the type of the result of the function <add> * @param function the source function <add> * @return a new {@link ThrowingFunction} instance <add> */ <add> static <T, U, R> ThrowingBiFunction<T, U, R> of(ThrowingBiFunction<T, U, R> function) { <add> return function; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingBiFunction} where the {@link #apply(Object, Object)} <add> * method wraps any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param <T> the type of the first argument to the function <add> * @param <U> the type of the second argument to the function <add> * @param <R> the type of the result of the function <add> * @param function the source function <add> * @param exceptionWrapper the exception wrapper to use <add> * @return a new {@link ThrowingFunction} instance <add> */ <add> static <T, U, R> ThrowingBiFunction<T, U, R> of(ThrowingBiFunction<T, U, R> function, <add> BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> <add> return function.throwing(exceptionWrapper); <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/util/function/ThrowingConsumer.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.util.function.BiFunction; <add>import java.util.function.Consumer; <add> <add>/** <add> * A {@link Consumer} that allows invocation of code that throws a checked <add> * exception. <add> * <add> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @since 6.0 <add> * @param <T> the type of the input to the operation <add> */ <add>@FunctionalInterface <add>public interface ThrowingConsumer<T> extends Consumer<T> { <add> <add> /** <add> * Performs this operation on the given argument, possibly throwing a <add> * checked exception. <add> * @param t the input argument <add> * @throws Exception on error <add> */ <add> void acceptWithException(T t) throws Exception; <add> <add> /** <add> * Default {@link Consumer#accept(Object)} that wraps any thrown checked <add> * exceptions (by default in a {@link RuntimeException}). <add> * @see java.util.function.Consumer#accept(Object) <add> */ <add> @Override <add> default void accept(T t) { <add> accept(t, RuntimeException::new); <add> } <add> <add> /** <add> * Performs this operation on the given argument, wrapping any thrown <add> * checked exceptions using the given {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> */ <add> default void accept(T t,BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> try { <add> acceptWithException(t); <add> } <add> catch (RuntimeException ex) { <add> throw ex; <add> } <add> catch (Exception ex) { <add> throw exceptionWrapper.apply(ex.getMessage(), ex); <add> } <add> } <add> <add> /** <add> * Return a new {@link ThrowingConsumer} where the {@link #accept(Object)} <add> * method wraps any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return the replacement {@link ThrowingConsumer} instance <add> */ <add> default ThrowingConsumer<T> throwing(BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> return new ThrowingConsumer<>() { <add> <add> @Override <add> public void acceptWithException(T t) throws Exception { <add> ThrowingConsumer.this.acceptWithException(t); <add> } <add> <add> @Override <add> public void accept(T t) { <add> accept(t, exceptionWrapper); <add> } <add> <add> }; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingConsumer} where the {@link #accept(Object)} method wraps <add> * any thrown checked exceptions using the given {@code exceptionWrapper}. <add> * @param <T> the type of the input to the operation <add> * @param consumer the source consumer <add> * @return a new {@link ThrowingConsumer} instance <add> */ <add> static <T> ThrowingConsumer<T> of(ThrowingConsumer<T> consumer) { <add> return consumer; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingConsumer} where the {@link #accept(Object)} method wraps <add> * any thrown checked exceptions using the given {@code exceptionWrapper}. <add> * @param <T> the type of the input to the operation <add> * @param consumer the source consumer <add> * @param exceptionWrapper the exception wrapper to use <add> * @return a new {@link ThrowingConsumer} instance <add> */ <add> static <T> ThrowingConsumer<T> of(ThrowingConsumer<T> consumer, <add> BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> <add> return consumer.throwing(exceptionWrapper); <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/util/function/ThrowingFunction.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.util.function.BiFunction; <add>import java.util.function.Function; <add> <add>/** <add> * A {@link Function} that allows invocation of code that throws a checked <add> * exception. <add> * <add> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @since 6.0 <add> * @param <T> the type of the input to the function <add> * @param <R> the type of the result of the function <add> */ <add>@FunctionalInterface <add>public interface ThrowingFunction<T, R> extends Function<T, R> { <add> <add> /** <add> * Applies this function to the given argument, possibly throwing a checked <add> * exception. <add> * @param t the function argument <add> * @return the function result <add> * @throws Exception on error <add> */ <add> R applyWithException(T t) throws Exception; <add> <add> /** <add> * Default {@link Function#apply(Object)} that wraps any thrown checked <add> * exceptions (by default in a {@link RuntimeException}). <add> * @see java.util.function.Function#apply(java.lang.Object) <add> */ <add> @Override <add> default R apply(T t) { <add> return apply(t, RuntimeException::new); <add> } <add> <add> /** <add> * Applies this function to the given argument, wrapping any thrown checked <add> * exceptions using the given {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return a result <add> */ <add> default R apply(T t, BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> try { <add> return applyWithException(t); <add> } <add> catch (RuntimeException ex) { <add> throw ex; <add> } <add> catch (Exception ex) { <add> throw exceptionWrapper.apply(ex.getMessage(), ex); <add> } <add> } <add> <add> /** <add> * Return a new {@link ThrowingFunction} where the {@link #apply(Object)} <add> * method wraps any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return the replacement {@link ThrowingFunction} instance <add> */ <add> default ThrowingFunction<T, R> throwing(BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> return new ThrowingFunction<>() { <add> <add> @Override <add> public R applyWithException(T t) throws Exception { <add> return ThrowingFunction.this.applyWithException(t); <add> } <add> <add> @Override <add> public R apply(T t) { <add> return apply(t, exceptionWrapper); <add> } <add> <add> }; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingFunction} where the {@link #apply(Object)} method wraps <add> * any thrown checked exceptions using the given {@code exceptionWrapper}. <add> * @param <T> the type of the input to the function <add> * @param <R> the type of the result of the function <add> * @param function the source function <add> * @return a new {@link ThrowingFunction} instance <add> */ <add> static <T, R> ThrowingFunction<T, R> of(ThrowingFunction<T, R> function) { <add> return function; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingFunction} where the {@link #apply(Object)} method wraps <add> * any thrown checked exceptions using the given {@code exceptionWrapper}. <add> * @param <T> the type of the input to the function <add> * @param <R> the type of the result of the function <add> * @param function the source function <add> * @param exceptionWrapper the exception wrapper to use <add> * @return a new {@link ThrowingFunction} instance <add> */ <add> static <T, R> ThrowingFunction<T, R> of(ThrowingFunction<T, R> function, <add> BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> <add> return function.throwing(exceptionWrapper); <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/util/function/ThrowingSupplier.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.util.function.BiFunction; <add>import java.util.function.Supplier; <add> <add>/** <add> * A {@link Supplier} that allows invocation of code that throws a checked <add> * exception. <add> * <add> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @since 6.0 <add> * @param <T> the type of results supplied by this supplier <add> */ <add>public interface ThrowingSupplier<T> extends Supplier<T> { <add> <add> /** <add> * Gets a result, possibly throwing a checked exception. <add> * @return a result <add> * @throws Exception on error <add> */ <add> T getWithException() throws Exception; <add> <add> /** <add> * Default {@link Supplier#get()} that wraps any thrown checked exceptions <add> * (by default in a {@link RuntimeException}). <add> * @see java.util.function.Supplier#get() <add> */ <add> @Override <add> default T get() { <add> return get(RuntimeException::new); <add> } <add> <add> /** <add> * Gets a result, wrapping any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return a result <add> */ <add> default T get(BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> try { <add> return getWithException(); <add> } <add> catch (RuntimeException ex) { <add> throw ex; <add> } <add> catch (Exception ex) { <add> throw exceptionWrapper.apply(ex.getMessage(), ex); <add> } <add> } <add> <add> /** <add> * Return a new {@link ThrowingSupplier} where the {@link #get()} method <add> * wraps any thrown checked exceptions using the given <add> * {@code exceptionWrapper}. <add> * @param exceptionWrapper {@link BiFunction} that wraps the given message <add> * and checked exception into a runtime exception <add> * @return the replacement {@link ThrowingSupplier} instance <add> */ <add> default ThrowingSupplier<T> throwing(BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> return new ThrowingSupplier<>() { <add> <add> @Override <add> public T getWithException() throws Exception { <add> return ThrowingSupplier.this.getWithException(); <add> } <add> <add> @Override <add> public T get() { <add> return get(exceptionWrapper); <add> } <add> <add> }; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingSupplier} where the {@link #get()} method wraps any <add> * thrown checked exceptions. <add> * @param <T> the type of results supplied by this supplier <add> * @param supplier the source supplier <add> * @return a new {@link ThrowingSupplier} instance <add> */ <add> static <T> ThrowingSupplier<T> of(ThrowingSupplier<T> supplier) { <add> return supplier; <add> } <add> <add> /** <add> * Lambda friendly convenience method that can be used to create <add> * {@link ThrowingSupplier} where the {@link #get()} method wraps any <add> * thrown checked exceptions using the given {@code exceptionWrapper}. <add> * @param <T> the type of results supplied by this supplier <add> * @param supplier the source supplier <add> * @param exceptionWrapper the exception wrapper to use <add> * @return a new {@link ThrowingSupplier} instance <add> */ <add> static <T> ThrowingSupplier<T> of(ThrowingSupplier<T> supplier, <add> BiFunction<String, Exception, RuntimeException> exceptionWrapper) { <add> <add> return supplier.throwing(exceptionWrapper); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/util/function/ThrowingBiFunctionTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.io.IOException; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <add> <add>/** <add> * Tests for {@link ThrowingBiFunction}. <add> * <add> * @author Phillip Webb <add> * @since 6.0 <add> */ <add>class ThrowingBiFunctionTests { <add> <add> @Test <add> void applyWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingBiFunction<Object, Object, Object> function = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy(() -> function.apply(this, this)); <add> } <add> <add> @Test <add> void applyWhenThrowingCheckedExceptionThrowsWrapperRuntimeException() { <add> ThrowingBiFunction<Object, Object, Object> function = this::throwIOException; <add> assertThatExceptionOfType(RuntimeException.class).isThrownBy( <add> () -> function.apply(this, this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingBiFunction<Object, Object, Object> function = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy( <add> () -> function.apply(this, this, IllegalStateException::new)); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingCheckedExceptionThrowsWrapper() { <add> ThrowingBiFunction<Object, Object, Object> function = this::throwIOException; <add> assertThatIllegalStateException().isThrownBy(() -> function.apply(this, this, <add> IllegalStateException::new)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void throwingModifiesThrownException() { <add> ThrowingBiFunction<Object, Object, Object> function = this::throwIOException; <add> ThrowingBiFunction<Object, Object, Object> modified = function.throwing( <add> IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> modified.apply(this, this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void ofModifiesThrowException() { <add> ThrowingBiFunction<Object, Object, Object> function = ThrowingBiFunction.of( <add> this::throwIOException, IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> function.apply(this, this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> private Object throwIOException(Object o, Object u) throws IOException { <add> throw new IOException(); <add> } <add> <add> private Object throwIllegalArgumentException(Object o, Object u) throws IOException { <add> throw new IllegalArgumentException(); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/util/function/ThrowingConsumerTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.io.IOException; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <add> <add>/** <add> * Tests for {@link ThrowingConsumer}. <add> * <add> * @author Phillip Webb <add> * @since 6.0 <add> */ <add>class ThrowingConsumerTests { <add> <add> @Test <add> void applyWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingConsumer<Object> consumer = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy(() -> consumer.accept(this)); <add> } <add> <add> @Test <add> void applyWhenThrowingCheckedExceptionThrowsWrapperRuntimeException() { <add> ThrowingConsumer<Object> consumer = this::throwIOException; <add> assertThatExceptionOfType(RuntimeException.class).isThrownBy( <add> () -> consumer.accept(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingConsumer<Object> consumer = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy( <add> () -> consumer.accept(this, IllegalStateException::new)); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingCheckedExceptionThrowsWrapper() { <add> ThrowingConsumer<Object> consumer = this::throwIOException; <add> assertThatIllegalStateException().isThrownBy(() -> consumer.accept(this, <add> IllegalStateException::new)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void throwingModifiesThrownException() { <add> ThrowingConsumer<Object> consumer = this::throwIOException; <add> ThrowingConsumer<Object> modified = consumer.throwing( <add> IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> modified.accept(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void ofModifiesThrowException() { <add> ThrowingConsumer<Object> consumer = ThrowingConsumer.of(this::throwIOException, <add> IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> consumer.accept(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> private void throwIOException(Object o) throws IOException { <add> throw new IOException(); <add> } <add> <add> private void throwIllegalArgumentException(Object o) throws IOException { <add> throw new IllegalArgumentException(); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/util/function/ThrowingFunctionTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.io.IOException; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <add> <add>/** <add> * Tests for {@link ThrowingFunction}. <add> * <add> * @author Phillip Webb <add> * @since 6.0 <add> */ <add>class ThrowingFunctionTests { <add> <add> @Test <add> void applyWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingFunction<Object, Object> function = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy(() -> function.apply(this)); <add> } <add> <add> @Test <add> void applyWhenThrowingCheckedExceptionThrowsWrapperRuntimeException() { <add> ThrowingFunction<Object, Object> function = this::throwIOException; <add> assertThatExceptionOfType(RuntimeException.class).isThrownBy( <add> () -> function.apply(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingFunction<Object, Object> function = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy( <add> () -> function.apply(this, IllegalStateException::new)); <add> } <add> <add> @Test <add> void applyWithExceptionWrapperWhenThrowingCheckedExceptionThrowsWrapper() { <add> ThrowingFunction<Object, Object> function = this::throwIOException; <add> assertThatIllegalStateException().isThrownBy(() -> function.apply(this, <add> IllegalStateException::new)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void throwingModifiesThrownException() { <add> ThrowingFunction<Object, Object> function = this::throwIOException; <add> ThrowingFunction<Object, Object> modified = function.throwing( <add> IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> modified.apply(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void ofModifiesThrowException() { <add> ThrowingFunction<Object, Object> function = ThrowingFunction.of( <add> this::throwIOException, IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> function.apply(this)).withCauseInstanceOf(IOException.class); <add> } <add> <add> private Object throwIOException(Object o) throws IOException { <add> throw new IOException(); <add> } <add> <add> private Object throwIllegalArgumentException(Object o) throws IOException { <add> throw new IllegalArgumentException(); <add> } <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/util/function/ThrowingSupplierTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util.function; <add> <add>import java.io.IOException; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <add> <add>/** <add> * Tests for {@link ThrowingSupplier}. <add> * <add> * @author Phillip Webb <add> * @since 6.0 <add> */ <add>class ThrowingSupplierTests { <add> <add> @Test <add> void getWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingSupplier<Object> supplier = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy(supplier::get); <add> } <add> <add> @Test <add> void getWhenThrowingCheckedExceptionThrowsWrapperRuntimeException() { <add> ThrowingSupplier<Object> supplier = this::throwIOException; <add> assertThatExceptionOfType(RuntimeException.class).isThrownBy( <add> supplier::get).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void getWithExceptionWrapperWhenThrowingUncheckedExceptionThrowsOriginal() { <add> ThrowingSupplier<Object> supplier = this::throwIllegalArgumentException; <add> assertThatIllegalArgumentException().isThrownBy( <add> () -> supplier.get(IllegalStateException::new)); <add> } <add> <add> @Test <add> void getWithExceptionWrapperWhenThrowingCheckedExceptionThrowsWrapper() { <add> ThrowingSupplier<Object> supplier = this::throwIOException; <add> assertThatIllegalStateException().isThrownBy( <add> () -> supplier.get(IllegalStateException::new)).withCauseInstanceOf( <add> IOException.class); <add> } <add> <add> @Test <add> void throwingModifiesThrownException() { <add> ThrowingSupplier<Object> supplier = this::throwIOException; <add> ThrowingSupplier<Object> modified = supplier.throwing( <add> IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> modified.get()).withCauseInstanceOf(IOException.class); <add> } <add> <add> @Test <add> void ofModifiesThrowException() { <add> ThrowingSupplier<Object> supplier = ThrowingSupplier.of( <add> this::throwIOException, IllegalStateException::new); <add> assertThatIllegalStateException().isThrownBy( <add> () -> supplier.get()).withCauseInstanceOf(IOException.class); <add> } <add> <add> private Object throwIOException() throws IOException { <add> throw new IOException(); <add> } <add> <add> private Object throwIllegalArgumentException() throws IOException { <add> throw new IllegalArgumentException(); <add> } <add> <add>}
8
Ruby
Ruby
remove stray character
343a05a64f96195185563abbbc885471b8c42db7
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def select_datetime(datetime = Time.current, options = {}, html_options = {}) <ide> # ==== Examples <ide> # my_date = Time.today + 6.days <ide> # <del> # # Generates a date select that defaults to the date in my_date (six days afteri today). <add> # # Generates a date select that defaults to the date in my_date (six days after today). <ide> # select_date(my_date) <ide> # <ide> # # Generates a date select that defaults to today (no specified date).
1
Ruby
Ruby
use prepend instead of extending every instance
894336a23f0d6e1987e32a6e5825f9f94ca5ced3
<ide><path>activesupport/lib/active_support/cache/file_store.rb <ide> module Cache <ide> # FileStore implements the Strategy::LocalCache strategy which implements <ide> # an in-memory cache inside of a block. <ide> class FileStore < Store <add> prepend Strategy::LocalCache <ide> attr_reader :cache_path <ide> <ide> DIR_FORMATTER = "%03X" <ide> class FileStore < Store <ide> def initialize(cache_path, options = nil) <ide> super(options) <ide> @cache_path = cache_path.to_s <del> extend Strategy::LocalCache <ide> end <ide> <ide> # Deletes all items from the cache. In this case it deletes all the entries in the specified <ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb <ide> module Cache <ide> # MemCacheStore implements the Strategy::LocalCache strategy which implements <ide> # an in-memory cache inside of a block. <ide> class MemCacheStore < Store <add> # Provide support for raw values in the local cache strategy. <add> module LocalCacheWithRaw # :nodoc: <add> protected <add> def read_entry(key, options) <add> entry = super <add> if options[:raw] && local_cache && entry <add> entry = deserialize_entry(entry.value) <add> end <add> entry <add> end <add> <add> def write_entry(key, entry, options) # :nodoc: <add> retval = super <add> if options[:raw] && local_cache && retval <add> raw_entry = Entry.new(entry.value.to_s) <add> raw_entry.expires_at = entry.expires_at <add> local_cache.write_entry(key, raw_entry, options) <add> end <add> retval <add> end <add> end <add> <add> prepend Strategy::LocalCache <add> prepend LocalCacheWithRaw <add> <ide> ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n <ide> <ide> # Creates a new Dalli::Client instance with specified addresses and options. <ide> def initialize(*addresses) <ide> UNIVERSAL_OPTIONS.each{|name| mem_cache_options.delete(name)} <ide> @data = self.class.build_mem_cache(*(addresses + [mem_cache_options])) <ide> end <del> <del> extend Strategy::LocalCache <del> extend LocalCacheWithRaw <ide> end <ide> <ide> # Reads multiple values from the cache using a single call to the <ide> def deserialize_entry(raw_value) <ide> nil <ide> end <ide> end <del> <del> # Provide support for raw values in the local cache strategy. <del> module LocalCacheWithRaw # :nodoc: <del> protected <del> def read_entry(key, options) <del> entry = super <del> if options[:raw] && local_cache && entry <del> entry = deserialize_entry(entry.value) <del> end <del> entry <del> end <del> <del> def write_entry(key, entry, options) # :nodoc: <del> retval = super <del> if options[:raw] && local_cache && retval <del> raw_entry = Entry.new(entry.value.to_s) <del> raw_entry.expires_at = entry.expires_at <del> local_cache.write_entry(key, raw_entry, options) <del> end <del> retval <del> end <del> end <ide> end <ide> end <ide> end <ide><path>activesupport/lib/active_support/cache/null_store.rb <ide> module Cache <ide> # be cached inside blocks that utilize this strategy. See <ide> # ActiveSupport::Cache::Strategy::LocalCache for more details. <ide> class NullStore < Store <del> def initialize(options = nil) <del> super(options) <del> extend Strategy::LocalCache <del> end <add> prepend Strategy::LocalCache <ide> <ide> def clear(options = nil) <ide> end
3
Ruby
Ruby
remove unused simulate method
845aabbcd3805420090f8b92b50a4562577cf210
<ide><path>actionpack/lib/action_dispatch/journey/gtg/simulator.rb <ide> def initialize(transition_table) <ide> @tt = transition_table <ide> end <ide> <del> def simulate(string) <del> ms = memos(string) { return } <del> MatchData.new(ms) <del> end <del> <del> alias :=~ :simulate <del> alias :match :simulate <del> <ide> def memos(string) <ide> input = StringScanner.new(string) <ide> state = [0] <ide><path>actionpack/test/journey/gtg/transition_table_test.rb <ide> def test_to_svg <ide> <ide> def test_simulate_gt <ide> sim = simulator_for ["/foo", "/bar"] <del> assert_match sim, "/foo" <add> assert_match_route sim, "/foo" <ide> end <ide> <ide> def test_simulate_gt_regexp <ide> sim = simulator_for [":foo"] <del> assert_match sim, "foo" <add> assert_match_route sim, "foo" <ide> end <ide> <ide> def test_simulate_gt_regexp_mix <ide> sim = simulator_for ["/get", "/:method/foo"] <del> assert_match sim, "/get" <del> assert_match sim, "/get/foo" <add> assert_match_route sim, "/get" <add> assert_match_route sim, "/get/foo" <ide> end <ide> <ide> def test_simulate_optional <ide> sim = simulator_for ["/foo(/bar)"] <del> assert_match sim, "/foo" <del> assert_match sim, "/foo/bar" <del> assert_no_match sim, "/foo/" <add> assert_match_route sim, "/foo" <add> assert_match_route sim, "/foo/bar" <add> assert_no_match_route sim, "/foo/" <ide> end <ide> <ide> def test_match_data <ide> def test_match_data <ide> <ide> sim = GTG::Simulator.new tt <ide> <del> match = sim.match "/get" <del> assert_equal [paths.first], match.memos <add> memos = sim.memos "/get" <add> assert_equal [paths.first], memos <ide> <del> match = sim.match "/get/foo" <del> assert_equal [paths.last], match.memos <add> memos = sim.memos "/get/foo" <add> assert_equal [paths.last], memos <ide> end <ide> <ide> def test_match_data_ambiguous <ide> def test_match_data_ambiguous <ide> builder = GTG::Builder.new ast <ide> sim = GTG::Simulator.new builder.transition_table <ide> <del> match = sim.match "/articles/new" <del> assert_equal [paths[1], paths[3]], match.memos <add> memos = sim.memos "/articles/new" <add> assert_equal [paths[1], paths[3]], memos <ide> end <ide> <ide> private <ide> def tt(paths) <ide> def simulator_for(paths) <ide> GTG::Simulator.new tt(paths) <ide> end <add> <add> def assert_match_route(simulator, path) <add> assert simulator.memos(path), "Simulator should match #{path}." <add> end <add> <add> def assert_no_match_route(simulator, path) <add> assert_not simulator.memos(path) { nil }, "Simulator should not match #{path}." <add> end <ide> end <ide> end <ide> end
2
Ruby
Ruby
support anonymous classes on has_many associations
1f006cd5f10663286e70b4c3e972fba91ac8c9f9
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> class << self <ide> end <ide> self.extensions = [] <ide> <del> VALID_OPTIONS = [:class_name, :foreign_key, :validate] <add> VALID_OPTIONS = [:class_name, :class, :foreign_key, :validate] <ide> <ide> attr_reader :name, :scope, :options <ide> <ide><path>activerecord/lib/active_record/reflection.rb <ide> def initialize(macro, name, scope, options, active_record) <ide> @scope = scope <ide> @options = options <ide> @active_record = active_record <add> @klass = options[:class] <ide> @plural_name = active_record.pluralize_table_names ? <ide> name.to_s.pluralize : name.to_s <ide> end <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> def setup <ide> Client.destroyed_client_ids.clear <ide> end <ide> <add> def test_anonymous_has_many <add> developer = Class.new(ActiveRecord::Base) { <add> self.table_name = 'developers' <add> dev = self <add> <add> developer_project = Class.new(ActiveRecord::Base) { <add> self.table_name = 'developers_projects' <add> belongs_to :developer, :class => dev <add> } <add> has_many :developer_projects, :class => developer_project, :foreign_key => 'developer_id' <add> } <add> dev = developer.first <add> named = Developer.find(dev.id) <add> assert_operator dev.developer_projects.count, :>, 0 <add> assert_equal named.projects.map(&:id).sort, <add> dev.developer_projects.map(&:project_id).sort <add> end <add> <ide> def test_create_from_association_should_respect_default_scope <ide> car = Car.create(:name => 'honda') <ide> assert_equal 'honda', car.name
3
Python
Python
add list_volumes to compute
3fc07bb142d43839ab582e7b6a9240dfa4693742
<ide><path>libcloud/compute/base.py <ide> def detach_volume(self, volume): <ide> <ide> raise NotImplementedError('detach not implemented for this driver') <ide> <add> def list_volumes(self): <add> """ <add> List storage volumes. <add> <add> @return: list of storageVolume objects <add> @rtype: C{list} of L{StorageVolume} <add> """ <add> raise NotImplementedError( <add> 'list_volumes not implemented for this driver') <add> <ide> def _wait_until_running(self, node, wait_period=3, timeout=600, <ide> ssh_interface='public_ips', force_ipv4=True): <ide> # This is here for backward compatibility and will be removed in the
1
Go
Go
use libcontainer cap drop method
d31ae5aed80eeb40a461930776ad2b507804bf4e
<ide><path>daemon/execdriver/lxc/driver.go <ide> import ( <ide> "github.com/docker/libcontainer/label" <ide> "github.com/docker/libcontainer/mount/nodes" <ide> "github.com/dotcloud/docker/daemon/execdriver" <add> "github.com/dotcloud/docker/pkg/system" <ide> "github.com/dotcloud/docker/utils" <ide> ) <ide> <ide> func init() { <ide> if err := setupNetworking(args); err != nil { <ide> return err <ide> } <del> if err := setupCapabilities(args); err != nil { <add> if err := setupWorkingDirectory(args); err != nil { <add> return err <add> } <add> if err := system.CloseFdsFrom(3); err != nil { <add> return err <add> } <add> if err := finalizeNamespace(args); err != nil { <ide> return err <ide> } <ide> <ide><path>daemon/execdriver/lxc/init.go <ide> import ( <ide> <ide> "github.com/docker/libcontainer/netlink" <ide> "github.com/dotcloud/docker/daemon/execdriver" <del> "github.com/dotcloud/docker/pkg/system" <del> "github.com/dotcloud/docker/pkg/user" <del> "github.com/syndtr/gocapability/capability" <ide> ) <ide> <ide> // Clear environment pollution introduced by lxc-start <ide> func setupWorkingDirectory(args *execdriver.InitArgs) error { <ide> return nil <ide> } <ide> <del>// Takes care of dropping privileges to the desired user <del>func changeUser(args *execdriver.InitArgs) error { <del> uid, gid, suppGids, err := user.GetUserGroupSupplementary( <del> args.User, <del> syscall.Getuid(), syscall.Getgid(), <del> ) <del> if err != nil { <del> return err <del> } <del> <del> if err := syscall.Setgroups(suppGids); err != nil { <del> return fmt.Errorf("Setgroups failed: %v", err) <del> } <del> if err := syscall.Setgid(gid); err != nil { <del> return fmt.Errorf("Setgid failed: %v", err) <del> } <del> if err := syscall.Setuid(uid); err != nil { <del> return fmt.Errorf("Setuid failed: %v", err) <del> } <del> <del> return nil <del>} <del> <del>var whiteList = []capability.Cap{ <del> capability.CAP_MKNOD, <del> capability.CAP_SETUID, <del> capability.CAP_SETGID, <del> capability.CAP_CHOWN, <del> capability.CAP_NET_RAW, <del> capability.CAP_DAC_OVERRIDE, <del> capability.CAP_FOWNER, <del> capability.CAP_FSETID, <del> capability.CAP_KILL, <del> capability.CAP_SETGID, <del> capability.CAP_SETUID, <del> capability.CAP_LINUX_IMMUTABLE, <del> capability.CAP_NET_BIND_SERVICE, <del> capability.CAP_NET_BROADCAST, <del> capability.CAP_IPC_LOCK, <del> capability.CAP_IPC_OWNER, <del> capability.CAP_SYS_CHROOT, <del> capability.CAP_SYS_PTRACE, <del> capability.CAP_SYS_BOOT, <del> capability.CAP_LEASE, <del> capability.CAP_SETFCAP, <del> capability.CAP_WAKE_ALARM, <del> capability.CAP_BLOCK_SUSPEND, <del>} <del> <del>func dropBoundingSet() error { <del> c, err := capability.NewPid(os.Getpid()) <del> if err != nil { <del> return err <del> } <del> c.Clear(capability.BOUNDS) <del> c.Set(capability.BOUNDS, whiteList...) <del> <del> if err := c.Apply(capability.BOUNDS); err != nil { <del> return err <del> } <del> <del> return nil <del>} <del> <del>const allCapabilityTypes = capability.CAPS | capability.BOUNDS <del> <del>func dropCapabilities() error { <del> c, err := capability.NewPid(os.Getpid()) <del> if err != nil { <del> return err <del> } <del> c.Clear(allCapabilityTypes) <del> c.Set(allCapabilityTypes, whiteList...) <del> <del> if err := c.Apply(allCapabilityTypes); err != nil { <del> return err <del> } <del> <del> return nil <del>} <del> <del>func setupCapabilities(args *execdriver.InitArgs) error { <del> if err := system.CloseFdsFrom(3); err != nil { <del> return err <del> } <del> <del> if !args.Privileged { <del> // drop capabilities in bounding set before changing user <del> if err := dropBoundingSet(); err != nil { <del> return fmt.Errorf("drop bounding set %s", err) <del> } <del> <del> // preserve existing capabilities while we change users <del> if err := system.SetKeepCaps(); err != nil { <del> return fmt.Errorf("set keep caps %s", err) <del> } <del> } <del> <del> if err := changeUser(args); err != nil { <del> return err <del> } <del> <del> if !args.Privileged { <del> if err := system.ClearKeepCaps(); err != nil { <del> return fmt.Errorf("clear keep caps %s", err) <del> } <del> <del> // drop all other capabilities <del> if err := dropCapabilities(); err != nil { <del> return fmt.Errorf("drop capabilities %s", err) <del> } <del> } <del> <del> if err := setupWorkingDirectory(args); err != nil { <del> return err <del> } <del> <del> return nil <del>} <del> <ide> func getEnv(args *execdriver.InitArgs, key string) string { <ide> for _, kv := range args.Env { <ide> parts := strings.SplitN(kv, "=", 2) <ide><path>daemon/execdriver/lxc/lxc_init_linux.go <ide> package lxc <ide> <ide> import ( <add> "fmt" <ide> "syscall" <add> <add> "github.com/docker/libcontainer/namespaces" <add> "github.com/docker/libcontainer/security/capabilities" <add> "github.com/dotcloud/docker/daemon/execdriver" <add> "github.com/dotcloud/docker/daemon/execdriver/native/template" <add> "github.com/dotcloud/docker/pkg/system" <ide> ) <ide> <ide> func setHostname(hostname string) error { <ide> return syscall.Sethostname([]byte(hostname)) <ide> } <add> <add>func finalizeNamespace(args *execdriver.InitArgs) error { <add> // We use the native drivers default template so that things like caps are consistent <add> // across both drivers <add> container := template.New() <add> <add> if !args.Privileged { <add> // drop capabilities in bounding set before changing user <add> if err := capabilities.DropBoundingSet(container); err != nil { <add> return fmt.Errorf("drop bounding set %s", err) <add> } <add> <add> // preserve existing capabilities while we change users <add> if err := system.SetKeepCaps(); err != nil { <add> return fmt.Errorf("set keep caps %s", err) <add> } <add> } <add> <add> if err := namespaces.SetupUser(args.User); err != nil { <add> return fmt.Errorf("setup user %s", err) <add> } <add> <add> if !args.Privileged { <add> if err := system.ClearKeepCaps(); err != nil { <add> return fmt.Errorf("clear keep caps %s", err) <add> } <add> <add> // drop all other capabilities <add> if err := capabilities.DropCapabilities(container); err != nil { <add> return fmt.Errorf("drop capabilities %s", err) <add> } <add> } <add> <add> return nil <add>} <ide><path>daemon/execdriver/lxc/lxc_init_unsupported.go <ide> <ide> package lxc <ide> <add>import "github.com/dotcloud/docker/daemon/execdriver" <add> <ide> func setHostname(hostname string) error { <ide> panic("Not supported on darwin") <ide> } <add> <add>func finalizeNamespace(args *execdriver.InitArgs) error { <add> panic("Not supported on darwin") <add>} <ide><path>pkg/system/unsupported.go <ide> func GetClockTicks() int { <ide> func CreateMasterAndConsole() (*os.File, string, error) { <ide> return nil, "", ErrNotSupportedPlatform <ide> } <add> <add>func SetKeepCaps() error { <add> return ErrNotSupportedPlatform <add>} <add> <add>func ClearKeepCaps() error { <add> return ErrNotSupportedPlatform <add>}
5
Java
Java
update logadapter to allow build-time code removal
04366f4129b12eb923423e34ff78b269c46b5b94
<ide><path>spring-core/src/main/java/org/springframework/aot/nativex/feature/PreComputeFieldFeature.java <ide> class PreComputeFieldFeature implements Feature { <ide> Pattern.compile(Pattern.quote("org.springframework.core.NativeDetector#imageCode")), <ide> Pattern.compile(Pattern.quote("org.springframework.") + ".*#.*Present"), <ide> Pattern.compile(Pattern.quote("org.springframework.") + ".*#.*PRESENT"), <del> Pattern.compile(Pattern.quote("reactor.") + ".*#.*Available") <add> Pattern.compile(Pattern.quote("reactor.") + ".*#.*Available"), <add> Pattern.compile(Pattern.quote("org.apache.commons.logging.LogAdapter") + "#.*Present") <ide> }; <ide> <ide> private final ThrowawayClassLoader throwawayClassLoader = new ThrowawayClassLoader(PreComputeFieldFeature.class.getClassLoader()); <ide><path>spring-jcl/src/main/java/org/apache/commons/logging/LogAdapter.java <ide> package org.apache.commons.logging; <ide> <ide> import java.io.Serializable; <add>import java.util.function.Function; <ide> import java.util.logging.LogRecord; <ide> <ide> import org.apache.logging.log4j.Level; <ide> * Detects the presence of Log4j 2.x / SLF4J, falling back to {@code java.util.logging}. <ide> * <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 5.1 <ide> */ <ide> final class LogAdapter { <ide> <del> private static final String LOG4J_SPI = "org.apache.logging.log4j.spi.ExtendedLogger"; <add> private static final boolean log4jSpiPresent = isPresent("org.apache.logging.log4j.spi.ExtendedLogger"); <ide> <del> private static final String LOG4J_SLF4J_PROVIDER = "org.apache.logging.slf4j.SLF4JProvider"; <add> private static final boolean log4jSlf4jProviderPresent = isPresent("org.apache.logging.slf4j.SLF4JProvider"); <ide> <del> private static final String SLF4J_SPI = "org.slf4j.spi.LocationAwareLogger"; <add> private static final boolean slf4jSpiPresent = isPresent("org.slf4j.spi.LocationAwareLogger"); <ide> <del> private static final String SLF4J_API = "org.slf4j.Logger"; <add> private static final boolean slf4jApiPresent = isPresent("org.slf4j.Logger"); <ide> <ide> <del> private static final LogApi logApi; <add> private static final Function<String, Log> createLog; <ide> <ide> static { <del> if (isPresent(LOG4J_SPI)) { <del> if (isPresent(LOG4J_SLF4J_PROVIDER) && isPresent(SLF4J_SPI)) { <add> if (log4jSpiPresent) { <add> if (log4jSlf4jProviderPresent && slf4jSpiPresent) { <ide> // log4j-to-slf4j bridge -> we'll rather go with the SLF4J SPI; <ide> // however, we still prefer Log4j over the plain SLF4J API since <ide> // the latter does not have location awareness support. <del> logApi = LogApi.SLF4J_LAL; <add> createLog = Slf4jAdapter::createLocationAwareLog; <ide> } <ide> else { <ide> // Use Log4j 2.x directly, including location awareness support <del> logApi = LogApi.LOG4J; <add> createLog = Log4jAdapter::createLog; <ide> } <ide> } <del> else if (isPresent(SLF4J_SPI)) { <add> else if (slf4jSpiPresent) { <ide> // Full SLF4J SPI including location awareness support <del> logApi = LogApi.SLF4J_LAL; <add> createLog = Slf4jAdapter::createLocationAwareLog; <ide> } <del> else if (isPresent(SLF4J_API)) { <add> else if (slf4jApiPresent) { <ide> // Minimal SLF4J API without location awareness support <del> logApi = LogApi.SLF4J; <add> createLog = Slf4jAdapter::createLog; <ide> } <ide> else { <ide> // java.util.logging as default <del> logApi = LogApi.JUL; <add> // Defensively use lazy-initializing adapter class here as well since the <add> // java.logging module is not present by default on JDK 9. We are requiring <add> // its presence if neither Log4j nor SLF4J is available; however, in the <add> // case of Log4j or SLF4J, we are trying to prevent early initialization <add> // of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly <add> // trying to parse the bytecode for all the cases of this switch clause. <add> createLog = JavaUtilAdapter::createLog; <ide> } <ide> } <ide> <ide> private LogAdapter() { <ide> * @param name the logger name <ide> */ <ide> public static Log createLog(String name) { <del> return switch (logApi) { <del> case LOG4J -> Log4jAdapter.createLog(name); <del> case SLF4J_LAL -> Slf4jAdapter.createLocationAwareLog(name); <del> case SLF4J -> Slf4jAdapter.createLog(name); <del> default -> <del> // Defensively use lazy-initializing adapter class here as well since the <del> // java.logging module is not present by default on JDK 9. We are requiring <del> // its presence if neither Log4j nor SLF4J is available; however, in the <del> // case of Log4j or SLF4J, we are trying to prevent early initialization <del> // of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly <del> // trying to parse the bytecode for all the cases of this switch clause. <del> JavaUtilAdapter.createLog(name); <del> }; <add> return createLog.apply(name); <ide> } <ide> <ide> private static boolean isPresent(String className) { <ide> private static boolean isPresent(String className) { <ide> } <ide> <ide> <del> private enum LogApi {LOG4J, SLF4J_LAL, SLF4J, JUL} <del> <del> <ide> private static class Log4jAdapter { <ide> <ide> public static Log createLog(String name) {
2
Javascript
Javascript
fix tests when npn feature is disabled
1824bbbff1341e253a891a804651b6338f8008e4
<ide><path>test/parallel/test-tls-alpn-server-client.js <ide> if (!common.hasCrypto) { <ide> return; <ide> } <ide> <del>if (!process.features.tls_alpn) { <del> console.error('Skipping because node compiled without OpenSSL or ' + <del> 'with old OpenSSL version.'); <del> process.exit(0); <add>if (!process.features.tls_alpn || !process.features.tls_npn) { <add> common.skip('Skipping because node compiled without NPN or ALPN' + <add> ' feature of OpenSSL.'); <add> return; <ide> } <ide> <ide> const assert = require('assert'); <ide><path>test/parallel/test-tls-npn-server-client.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> if (!process.features.tls_npn) { <del> common.skip('node compiled without OpenSSL or ' + <del> 'with old OpenSSL version.'); <add> common.skip('Skipping because node compiled without NPN feature of' + <add> ' OpenSSL.'); <ide> return; <ide> } <ide>
2
Text
Text
add link to java integration
a0fc1c9019503e873405fe7f8e81b1e1092feb79
<ide><path>docs/notes/extensions.md <ide> In addition, many plugins can be found on the [npm registry](https://www.npmjs.c <ide> <ide> ### Vue.js <ide> - <a href="https://github.com/apertureless/vue-chartjs/" target="_blank">vue-chartjs</a> <add> <add>### Java <add> - <a href="https://github.com/mdewilde/chart/" target="_blank">Chart.java</a>
1
Ruby
Ruby
remove unnecessary loop
680144d230ef13112c3d297101e4cff27e81d204
<ide><path>activerecord/test/cases/serialized_attribute_test.rb <ide> def test_serialized_column_should_not_be_wrapped_twice <ide> myobj = MyObject.new('value1', 'value2') <ide> Topic.create(content: myobj) <ide> Topic.create(content: myobj) <del> <del> Topic.all.each do |topic| <del> type = Topic.column_types["content"] <del> assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type) <del> end <add> type = Topic.column_types["content"] <add> assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type) <ide> end <ide> end
1
Python
Python
add .m .a .t .h attributes to ma
11aa95a6a4978a687288f62287c147a63f834acb
<ide><path>numpy/core/ma.py <ide> def unshare_mask (self): <ide> def _get_ctypes(self): <ide> return self._data.ctypes <ide> <add> def _get_M(self): <add> if self._mask is nomask: <add> return self._data.M <add> return self.filled().M <add> <add> def _get_A(self): <add> if self._mask is nomask: <add> return self._data.A <add> return self.filled().A <add> <add> def _get_T(self): <add> return self.swapaxes(-2,-1) <add> <add> def _get_H(self): <add> return self.conjugate().swapaxes(-2,-1) <add> <ide> shape = property(_get_shape, _set_shape, <ide> doc = 'tuple giving the shape of the array') <ide> <ide> def _get_ctypes(self): <ide> imag = imaginary <ide> <ide> ctypes = property(_get_ctypes, None, doc="ctypes") <add> M = property(_get_M, None, doc="get matrix") <add> A = property(_get_A, None, doc="get array") <add> T = property(_get_T, None, doc="get transpose") <add> H = property(_get_H, None, doc="get conj. transpose") <ide> <ide> #end class MaskedArray <ide>
1
Javascript
Javascript
add test for breadcrumbs
cd1c16b3a99243df27aa26d81d19e26486ac3de2
<ide><path>cypress/integration/learn/redirects/breadcrumbs.js <add>/* global cy */ <add> <add>const challengeUrl = <add> '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements'; <add> <add>const superBlockUrl = '/learn/responsive-web-design'; <add>const courseUrl = '/learn/responsive-web-design/#basic-html-and-html5'; <add> <add>describe('The breadcumbs should work corectly', () => { <add> it('It should have a superblock and a course', () => { <add> cy.visit(challengeUrl); <add> cy.get('.ellipsis').contains('Responsive Web Design').and('be.visible'); <add> cy.get('.breadcrumb-left') <add> .should('have.attr', 'href') <add> .and('include', superBlockUrl); <add> cy.get('.breadcrumb-right') <add> .contains('Basic HTML and HTML5') <add> .and('be.visible'); <add> cy.get('.breadcrumb-right') <add> .should('have.attr', 'href') <add> .and('include', courseUrl); <add> }); <add> <add> it('Should redirect to the right url', () => { <add> cy.visit(challengeUrl); <add> cy.get('.breadcrumb-left').click(); <add> cy.url().should('include', '/responsive-web-design'); <add> cy.visit(challengeUrl); <add> cy.get('.breadcrumb-right').click(); <add> cy.url().should('include', '/responsive-web-design/#basic-html-and-html5'); <add> }); <add>});
1
Text
Text
fix worker.resourcelimits indentation
1eb7329a3374191a4fc4db5cd4909c02b8c320fc
<ide><path>doc/api/worker_threads.md <ide> console.log(receiveMessageOnPort(port2)); <ide> When this function is used, no `'message'` event will be emitted and the <ide> `onmessage` listener will not be invoked. <ide> <del>### worker.resourceLimits <add>## worker.resourceLimits <ide> <!-- YAML <ide> added: v13.2.0 <ide> -->
1
PHP
PHP
add support for aes encrypted cookies
005a7d841d0843f1e8d8c808dd965ee6323c03ce
<ide><path>lib/Cake/Controller/Component/CookieComponent.php <ide> class CookieComponent extends Component { <ide> * Type of encryption to use. <ide> * <ide> * Currently two methods are available: cipher and rijndael <del> * Defaults to Security::cipher(); <add> * Defaults to Security::cipher(). Cipher is horribly insecure and only <add> * the default because of backwards compatibility. In new applications you should <add> * always change this to 'aes' or 'rijndael'. <ide> * <ide> * @var string <ide> */ <ide> public function destroy() { <ide> public function type($type = 'cipher') { <ide> $availableTypes = array( <ide> 'cipher', <del> 'rijndael' <add> 'rijndael', <add> 'aes' <ide> ); <ide> if (!in_array($type, $availableTypes)) { <del> trigger_error(__d('cake_dev', 'You must use cipher or rijndael for cookie encryption type'), E_USER_WARNING); <add> trigger_error(__d('cake_dev', 'You must use cipher, rijndael or aes for cookie encryption type'), E_USER_WARNING); <ide> $type = 'cipher'; <ide> } <ide> $this->_type = $type; <ide> protected function _encrypt($value) { <ide> if (is_array($value)) { <ide> $value = $this->_implode($value); <ide> } <del> <del> if ($this->_encrypted === true) { <del> $type = $this->_type; <del> $value = "Q2FrZQ==." . base64_encode(Security::$type($value, $this->key, 'encrypt')); <add> if (!$this->_encrypted) { <add> return $value; <add> } <add> $prefix = "Q2FrZQ==."; <add> if ($this->_type === 'rijndael') { <add> $cipher = Security::rijndael($value, $this->key, 'encrypt'); <add> } <add> if ($this->_type === 'cipher') { <add> $cipher = Security::cipher($value, $this->key); <add> } <add> if ($this->_type === 'aes') { <add> $cipher = Security::encrypt($value, $this->key); <ide> } <del> return $value; <add> return $prefix . base64_encode($cipher); <ide> } <ide> <ide> /** <ide> protected function _decrypt($values) { <ide> foreach ((array)$values as $name => $value) { <ide> if (is_array($value)) { <ide> foreach ($value as $key => $val) { <del> $pos = strpos($val, 'Q2FrZQ==.'); <del> $decrypted[$name][$key] = $this->_explode($val); <del> <del> if ($pos !== false) { <del> $val = substr($val, 8); <del> $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key, 'decrypt')); <del> } <add> $decrypted[$name][$key] = $this->_decode($val); <ide> } <ide> } else { <del> $pos = strpos($value, 'Q2FrZQ==.'); <del> $decrypted[$name] = $this->_explode($value); <del> <del> if ($pos !== false) { <del> $value = substr($value, 8); <del> $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key, 'decrypt')); <del> } <add> $decrypted[$name] = $this->_decode($value); <ide> } <ide> } <ide> return $decrypted; <ide> } <ide> <add>/** <add> * Decodes and decrypts a single value. <add> * <add> * @param string $value The value to decode & decrypt. <add> * @return string Decoded value. <add> */ <add> protected function _decode($value) { <add> $prefix = 'Q2FrZQ==.'; <add> $pos = strpos($value, $prefix); <add> if ($pos === false) { <add> return $this->_explode($value); <add> } <add> $value = base64_decode(substr($value, strlen($prefix))); <add> if ($this->_type === 'rijndael') { <add> $plain = Security::rijndael($value, $this->key, 'decrypt'); <add> } <add> if ($this->_type === 'cipher') { <add> $plain = Security::cipher($value, $this->key); <add> } <add> if ($this->_type === 'aes') { <add> $plain = Security::decrypt($value, $this->key); <add> } <add> return $this->_explode($plain); <add> } <add> <ide> /** <ide> * Implode method to keep keys are multidimensional arrays <ide> *
1
PHP
PHP
create lazycollection class
ecf7f30e9778c6df91677fbc8f3d407318a8d298
<ide><path>src/Illuminate/Support/LazyCollection.php <add><?php <add> <add>namespace Illuminate\Support; <add> <add>use Closure; <add>use stdClass; <add>use ArrayIterator; <add>use IteratorAggregate; <add>use Illuminate\Support\Traits\Macroable; <add>use Illuminate\Support\Traits\EnumeratesValues; <add> <add>class LazyCollection implements Enumerable <add>{ <add> use EnumeratesValues, Macroable; <add> <add> /** <add> * The source from which to generate items. <add> * <add> * @var callable|static <add> */ <add> public $source; <add> <add> /** <add> * Create a new lazy collection instance. <add> * <add> * @param mixed $source <add> * @return void <add> */ <add> public function __construct($source = null) <add> { <add> if ($source instanceof Closure || $source instanceof self) { <add> $this->source = $source; <add> } elseif (is_null($source)) { <add> $this->source = static::empty(); <add> } else { <add> $this->source = $this->getArrayableItems($source); <add> } <add> } <add> <add> /** <add> * Create a new instance with no items. <add> * <add> * @return static <add> */ <add> public static function empty() <add> { <add> return new static([]); <add> } <add> <add> /** <add> * Create a new instance by invoking the callback a given amount of times. <add> * <add> * @param int $number <add> * @param callable $callback <add> * @return static <add> */ <add> public static function times($number, callable $callback = null) <add> { <add> if ($number < 1) { <add> return new static; <add> } <add> <add> $instance = new static(function () use ($number) { <add> for ($current = 1; $current <= $number; $current++) { <add> yield $current; <add> } <add> }); <add> <add> return is_null($callback) ? $instance : $instance->map($callback); <add> } <add> <add> /** <add> * Create an enumerable with the given range. <add> * <add> * @param int $from <add> * @param int $to <add> * @return static <add> */ <add> public static function range($from, $to) <add> { <add> return new static(function () use ($from, $to) { <add> for (; $from <= $to; $from++) { <add> yield $from; <add> } <add> }); <add> } <add> <add> /** <add> * Get all items in the enumerable. <add> * <add> * @return array <add> */ <add> public function all() <add> { <add> if (is_array($this->source)) { <add> return $this->source; <add> } <add> <add> return iterator_to_array($this->getIterator()); <add> } <add> <add> /** <add> * Collect the values into a collection. <add> * <add> * @return \Illuminate\Support\Collection <add> */ <add> public function collect() <add> { <add> return new Collection($this->all()); <add> } <add> <add> /** <add> * Get the average value of a given key. <add> * <add> * @param callable|string|null $callback <add> * @return mixed <add> */ <add> public function avg($callback = null) <add> { <add> return $this->collect()->avg($callback); <add> } <add> <add> /** <add> * Get the median of a given key. <add> * <add> * @param string|array|null $key <add> * @return mixed <add> */ <add> public function median($key = null) <add> { <add> return $this->collect()->median($key); <add> } <add> <add> /** <add> * Get the mode of a given key. <add> * <add> * @param string|array|null $key <add> * @return array|null <add> */ <add> public function mode($key = null) <add> { <add> return $this->collect()->mode($key); <add> } <add> <add> /** <add> * Collapse the collection of items into a single array. <add> * <add> * @return static <add> */ <add> public function collapse() <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original) { <add> foreach ($original as $values) { <add> if (is_array($values) || $values instanceof Enumerable) { <add> foreach ($values as $value) { <add> yield $value; <add> } <add> } <add> } <add> }); <add> } <add> <add> /** <add> * Determine if an item exists in the enumerable. <add> * <add> * @param mixed $key <add> * @param mixed $operator <add> * @param mixed $value <add> * @return bool <add> */ <add> public function contains($key, $operator = null, $value = null) <add> { <add> if (func_num_args() === 1 && $this->useAsCallable($key)) { <add> $placeholder = new stdClass; <add> <add> return $this->first($key, $placeholder) !== $placeholder; <add> } <add> <add> if (func_num_args() === 1) { <add> $needle = $key; <add> <add> foreach ($this as $value) { <add> if ($value == $needle) { <add> return true; <add> } <add> } <add> <add> return false; <add> } <add> <add> return $this->contains($this->operatorForWhere(...func_get_args())); <add> } <add> <add> /** <add> * Cross join the given iterables, returning all possible permutations. <add> * <add> * @param array ...$arrays <add> * @return static <add> */ <add> public function crossJoin(...$arrays) <add> { <add> return $this->passthru('crossJoin', func_get_args()); <add> } <add> <add> /** <add> * Get the items that are not present in the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function diff($items) <add> { <add> return $this->passthru('diff', func_get_args()); <add> } <add> <add> /** <add> * Get the items that are not present in the given items, using the callback. <add> * <add> * @param mixed $items <add> * @param callable $callback <add> * @return static <add> */ <add> public function diffUsing($items, callable $callback) <add> { <add> return $this->passthru('diffUsing', func_get_args()); <add> } <add> <add> /** <add> * Get the items whose keys and values are not present in the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function diffAssoc($items) <add> { <add> return $this->passthru('diffAssoc', func_get_args()); <add> } <add> <add> /** <add> * Get the items whose keys and values are not present in the given items. <add> * <add> * @param mixed $items <add> * @param callable $callback <add> * @return static <add> */ <add> public function diffAssocUsing($items, callable $callback) <add> { <add> return $this->passthru('diffAssocUsing', func_get_args()); <add> } <add> <add> /** <add> * Get the items whose keys are not present in the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function diffKeys($items) <add> { <add> return $this->passthru('diffKeys', func_get_args()); <add> } <add> <add> /** <add> * Get the items whose keys are not present in the given items. <add> * <add> * @param mixed $items <add> * @param callable $callback <add> * @return static <add> */ <add> public function diffKeysUsing($items, callable $callback) <add> { <add> return $this->passthru('diffKeysUsing', func_get_args()); <add> } <add> <add> /** <add> * Retrieve duplicate items. <add> * <add> * @param callable|null $callback <add> * @param bool $strict <add> * @return static <add> */ <add> public function duplicates($callback = null, $strict = false) <add> { <add> return $this->passthru('duplicates', func_get_args()); <add> } <add> <add> /** <add> * Retrieve duplicate items using strict comparison. <add> * <add> * @param callable|null $callback <add> * @return static <add> */ <add> public function duplicatesStrict($callback = null) <add> { <add> return $this->passthru('duplicatesStrict', func_get_args()); <add> } <add> <add> /** <add> * Get all items except for those with the specified keys. <add> * <add> * @param mixed $keys <add> * @return static <add> */ <add> public function except($keys) <add> { <add> return $this->passthru('except', func_get_args()); <add> } <add> <add> /** <add> * Run a filter over each of the items. <add> * <add> * @param callable|null $callback <add> * @return static <add> */ <add> public function filter(callable $callback = null) <add> { <add> if (is_null($callback)) { <add> $callback = function ($value) { <add> return (bool) $value; <add> }; <add> } <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $callback) { <add> foreach ($original as $key => $value) { <add> if ($callback($value, $key)) { <add> yield $key => $value; <add> } <add> } <add> }); <add> } <add> <add> /** <add> * Get the first item from the enumerable passing the given truth test. <add> * <add> * @param callable|null $callback <add> * @param mixed $default <add> * @return mixed <add> */ <add> public function first(callable $callback = null, $default = null) <add> { <add> $iterator = $this->getIterator(); <add> <add> if (is_null($callback)) { <add> if (! $iterator->valid()) { <add> return value($default); <add> } <add> <add> return $iterator->current(); <add> } <add> <add> foreach ($iterator as $key => $value) { <add> if ($callback($value, $key)) { <add> return $value; <add> } <add> } <add> <add> return value($default); <add> } <add> <add> /** <add> * Get a flattened list of the items in the collection. <add> * <add> * @param int $depth <add> * @return static <add> */ <add> public function flatten($depth = INF) <add> { <add> $original = clone $this; <add> <add> $instance = new static(function () use ($original, $depth) { <add> foreach ($original as $item) { <add> if (! is_array($item) && ! $item instanceof Enumerable) { <add> yield $item; <add> } elseif ($depth === 1) { <add> yield from $item; <add> } else { <add> yield from (new static($item))->flatten($depth - 1); <add> } <add> } <add> }); <add> <add> return $instance->values(); <add> } <add> <add> /** <add> * Flip the items in the collection. <add> * <add> * @return static <add> */ <add> public function flip() <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original) { <add> foreach ($original as $key => $value) { <add> yield $value => $key; <add> } <add> }); <add> } <add> <add> /** <add> * Remove an item by key. <add> * <add> * @param string|array $keys <add> * @return $this <add> */ <add> public function forget($keys) <add> { <add> $original = clone $this; <add> <add> $this->source = function () use ($original, $keys) { <add> $keys = array_flip((array) $keys); <add> <add> foreach ($original as $key => $value) { <add> if (! array_key_exists($key, $keys)) { <add> yield $key => $value; <add> } <add> } <add> }; <add> <add> return $this; <add> } <add> <add> /** <add> * Get an item by key. <add> * <add> * @param mixed $key <add> * @param mixed $default <add> * @return mixed <add> */ <add> public function get($key, $default = null) <add> { <add> if (is_null($key)) { <add> return; <add> } <add> <add> foreach ($this as $outerKey => $outerValue) { <add> if ($outerKey == $key) { <add> return $outerValue; <add> } <add> } <add> <add> return value($default); <add> } <add> <add> /** <add> * Group an associative array by a field or using a callback. <add> * <add> * @param array|callable|string $groupBy <add> * @param bool $preserveKeys <add> * @return static <add> */ <add> public function groupBy($groupBy, $preserveKeys = false) <add> { <add> return $this->passthru('groupBy', func_get_args()); <add> } <add> <add> /** <add> * Key an associative array by a field or using a callback. <add> * <add> * @param callable|string $keyBy <add> * @return static <add> */ <add> public function keyBy($keyBy) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $keyBy) { <add> $keyBy = $this->valueRetriever($keyBy); <add> <add> foreach ($original as $key => $item) { <add> $resolvedKey = $keyBy($item, $key); <add> <add> if (is_object($resolvedKey)) { <add> $resolvedKey = (string) $resolvedKey; <add> } <add> <add> yield $resolvedKey => $item; <add> } <add> }); <add> } <add> <add> /** <add> * Determine if an item exists in the collection by key. <add> * <add> * @param mixed $key <add> * @return bool <add> */ <add> public function has($key) <add> { <add> $keys = array_flip(is_array($key) ? $key : func_get_args()); <add> $count = count($keys); <add> <add> foreach ($this as $key => $value) { <add> if (array_key_exists($key, $keys) && --$count == 0) { <add> return true; <add> } <add> } <add> <add> return false; <add> } <add> <add> /** <add> * Concatenate values of a given key as a string. <add> * <add> * @param string $value <add> * @param string $glue <add> * @return string <add> */ <add> public function implode($value, $glue = null) <add> { <add> return $this->collect()->implode(...func_get_args()); <add> } <add> <add> /** <add> * Intersect the collection with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function intersect($items) <add> { <add> return $this->passthru('intersect', func_get_args()); <add> } <add> <add> /** <add> * Intersect the collection with the given items by key. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function intersectByKeys($items) <add> { <add> return $this->passthru('intersectByKeys', func_get_args()); <add> } <add> <add> /** <add> * Determine if the items is empty or not. <add> * <add> * @return bool <add> */ <add> public function isEmpty() <add> { <add> return ! $this->getIterator()->valid(); <add> } <add> <add> /** <add> * Join all items from the collection using a string. The final items can use a separate glue string. <add> * <add> * @param string $glue <add> * @param string $finalGlue <add> * @return string <add> */ <add> public function join($glue, $finalGlue = '') <add> { <add> return $this->collect()->join(...func_get_args()); <add> } <add> <add> /** <add> * Get the keys of the collection items. <add> * <add> * @return static <add> */ <add> public function keys() <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original) { <add> foreach ($original as $key => $value) { <add> yield $key; <add> } <add> }); <add> } <add> <add> /** <add> * Get the last item from the collection. <add> * <add> * @param callable|null $callback <add> * @param mixed $default <add> * @return mixed <add> */ <add> public function last(callable $callback = null, $default = null) <add> { <add> $needle = $placeholder = new stdClass; <add> <add> foreach ($this as $key => $value) { <add> if (is_null($callback) || $callback($value, $key)) { <add> $needle = $value; <add> } <add> } <add> <add> return $needle === $placeholder ? value($default) : $needle; <add> } <add> <add> /** <add> * Get the values of a given key. <add> * <add> * @param string|array $value <add> * @param string|null $key <add> * @return static <add> */ <add> public function pluck($value, $key = null) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $value, $key) { <add> [$value, $key] = $this->explodePluckParameters($value, $key); <add> <add> foreach ($original as $item) { <add> $itemValue = data_get($item, $value); <add> <add> if (is_null($key)) { <add> yield $itemValue; <add> } else { <add> $itemKey = data_get($item, $key); <add> <add> if (is_object($itemKey) && method_exists($itemKey, '__toString')) { <add> $itemKey = (string) $itemKey; <add> } <add> <add> yield $itemKey => $itemValue; <add> } <add> } <add> }); <add> } <add> <add> /** <add> * Run a map over each of the items. <add> * <add> * @param callable $callback <add> * @return static <add> */ <add> public function map(callable $callback) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $callback) { <add> foreach ($original as $key => $value) { <add> yield $key => $callback($value, $key); <add> } <add> }); <add> } <add> <add> /** <add> * Run a dictionary map over the items. <add> * <add> * The callback should return an associative array with a single key/value pair. <add> * <add> * @param callable $callback <add> * @return static <add> */ <add> public function mapToDictionary(callable $callback) <add> { <add> return $this->passthru('mapToDictionary', func_get_args()); <add> } <add> <add> /** <add> * Run an associative map over each of the items. <add> * <add> * The callback should return an associative array with a single key/value pair. <add> * <add> * @param callable $callback <add> * @return static <add> */ <add> public function mapWithKeys(callable $callback) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $callback) { <add> foreach ($original as $key => $value) { <add> yield from $callback($value, $key); <add> } <add> }); <add> } <add> <add> /** <add> * Merge the collection with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function merge($items) <add> { <add> return $this->passthru('merge', func_get_args()); <add> } <add> <add> /** <add> * Recursively merge the collection with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function mergeRecursive($items) <add> { <add> return $this->passthru('mergeRecursive', func_get_args()); <add> } <add> <add> /** <add> * Create a collection by using this collection for keys and another for its values. <add> * <add> * @param mixed $values <add> * @return static <add> */ <add> public function combine($values) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $values) { <add> $values = $this->makeIterator($values); <add> <add> $errorMessage = 'Both parameters should have an equal number of elements'; <add> <add> foreach ($original as $key) { <add> if (! $values->valid()) { <add> trigger_error($errorMessage, E_USER_WARNING); <add> <add> break; <add> } <add> <add> yield $key => $values->current(); <add> <add> $values->next(); <add> } <add> <add> if ($values->valid()) { <add> trigger_error($errorMessage, E_USER_WARNING); <add> } <add> }); <add> } <add> <add> /** <add> * Union the collection with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function union($items) <add> { <add> return $this->passthru('union', func_get_args()); <add> } <add> <add> /** <add> * Create a new collection consisting of every n-th element. <add> * <add> * @param int $step <add> * @param int $offset <add> * @return static <add> */ <add> public function nth($step, $offset = 0) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $step, $offset) { <add> $position = 0; <add> <add> foreach ($original as $item) { <add> if ($position % $step === $offset) { <add> yield $item; <add> } <add> <add> $position++; <add> } <add> }); <add> } <add> <add> /** <add> * Get the items with the specified keys. <add> * <add> * @param mixed $keys <add> * @return static <add> */ <add> public function only($keys) <add> { <add> if ($keys instanceof Enumerable) { <add> $keys = $keys->all(); <add> } elseif (! is_null($keys)) { <add> $keys = is_array($keys) ? $keys : func_get_args(); <add> } <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $keys) { <add> if (is_null($keys)) { <add> yield from $original; <add> } else { <add> $keys = array_flip($keys); <add> <add> foreach ($original as $key => $value) { <add> if (array_key_exists($key, $keys)) { <add> yield $key => $value; <add> } <add> } <add> } <add> }); <add> } <add> <add> /** <add> * Get and remove the last item from the collection. <add> * <add> * @return mixed <add> */ <add> public function pop() <add> { <add> $items = $this->collect(); <add> <add> $result = $items->pop(); <add> <add> $this->source = $items; <add> <add> return $result; <add> } <add> <add> /** <add> * Push an item onto the beginning of the collection. <add> * <add> * @param mixed $value <add> * @param mixed $key <add> * @return $this <add> */ <add> public function prepend($value, $key = null) <add> { <add> $original = clone $this; <add> <add> $this->source = function () use ($original, $value, $key) { <add> $instance = new static(function () use ($original, $value, $key) { <add> yield $key => $value; <add> <add> yield from $original; <add> }); <add> <add> if (is_null($key)) { <add> $instance = $instance->values(); <add> } <add> <add> yield from $instance; <add> }; <add> <add> return $this; <add> } <add> <add> /** <add> * Push all of the given items onto the collection. <add> * <add> * @param iterable $source <add> * @return static <add> */ <add> public function concat($source) <add> { <add> $original = clone $this; <add> <add> return (new static(function () use ($original, $source) { <add> yield from $original; <add> yield from $source; <add> }))->values(); <add> } <add> <add> /** <add> * Put an item in the collection by key. <add> * <add> * @param mixed $key <add> * @param mixed $value <add> * @return $this <add> */ <add> public function put($key, $value) <add> { <add> $original = clone $this; <add> <add> if (is_null($key)) { <add> $this->source = function () use ($original, $value) { <add> foreach ($original as $innerKey => $innerValue) { <add> yield $innerKey => $innerValue; <add> } <add> <add> yield $value; <add> }; <add> } else { <add> $this->source = function () use ($original, $key, $value) { <add> $found = false; <add> <add> foreach ($original as $innerKey => $innerValue) { <add> if ($innerKey == $key) { <add> yield $key => $value; <add> <add> $found = true; <add> } else { <add> yield $innerKey => $innerValue; <add> } <add> } <add> <add> if (! $found) { <add> yield $key => $value; <add> } <add> }; <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Get one or a specified number of items randomly from the collection. <add> * <add> * @param int|null $number <add> * @return static|mixed <add> * <add> * @throws \InvalidArgumentException <add> */ <add> public function random($number = null) <add> { <add> $result = $this->collect()->random(...func_get_args()); <add> <add> return is_null($number) ? $result : new static($result); <add> } <add> <add> /** <add> * Reduce the collection to a single value. <add> * <add> * @param callable $callback <add> * @param mixed $initial <add> * @return mixed <add> */ <add> public function reduce(callable $callback, $initial = null) <add> { <add> $result = $initial; <add> <add> foreach ($this as $value) { <add> $result = $callback($result, $value); <add> } <add> <add> return $result; <add> } <add> <add> /** <add> * Replace the collection items with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function replace($items) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $items) { <add> $items = $this->getArrayableItems($items); <add> $usedItems = []; <add> <add> foreach ($original as $key => $value) { <add> if (array_key_exists($key, $items)) { <add> yield $key => $items[$key]; <add> <add> $usedItems[$key] = true; <add> } else { <add> yield $key => $value; <add> } <add> } <add> <add> foreach ($items as $key => $value) { <add> if (! array_key_exists($key, $usedItems)) { <add> yield $key => $value; <add> } <add> } <add> }); <add> } <add> <add> /** <add> * Recursively replace the collection items with the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function replaceRecursive($items) <add> { <add> return $this->passthru('replaceRecursive', func_get_args()); <add> } <add> <add> /** <add> * Reverse items order. <add> * <add> * @return static <add> */ <add> public function reverse() <add> { <add> return $this->passthru('reverse', func_get_args()); <add> } <add> <add> /** <add> * Search the collection for a given value and return the corresponding key if successful. <add> * <add> * @param mixed $value <add> * @param bool $strict <add> * @return mixed <add> */ <add> public function search($value, $strict = false) <add> { <add> $predicate = $this->useAsCallable($value) <add> ? $value <add> : function ($item) use ($value, $strict) { <add> return $strict ? $item === $value : $item == $value; <add> }; <add> <add> foreach ($this as $key => $item) { <add> if ($predicate($item, $key)) { <add> return $key; <add> } <add> } <add> <add> return false; <add> } <add> <add> /** <add> * Get and remove the first item from the collection. <add> * <add> * @return mixed <add> */ <add> public function shift() <add> { <add> return tap($this->first(), function () { <add> $this->source = $this->skip(1); <add> }); <add> } <add> <add> /** <add> * Shuffle the items in the collection. <add> * <add> * @param int $seed <add> * @return static <add> */ <add> public function shuffle($seed = null) <add> { <add> return $this->passthru('shuffle', func_get_args()); <add> } <add> <add> /** <add> * Skip the first {$count} items. <add> * <add> * @param int $count <add> * @return static <add> */ <add> public function skip($count) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $count) { <add> $iterator = $original->getIterator(); <add> <add> while ($iterator->valid() && $count--) { <add> $iterator->next(); <add> } <add> <add> while ($iterator->valid()) { <add> yield $iterator->key() => $iterator->current(); <add> <add> $iterator->next(); <add> } <add> }); <add> } <add> <add> /** <add> * Get a slice of items from the enumerable. <add> * <add> * @param int $offset <add> * @param int $length <add> * @return static <add> */ <add> public function slice($offset, $length = null) <add> { <add> if ($offset < 0 || $length < 0) { <add> return $this->passthru('slice', func_get_args()); <add> } <add> <add> $instance = $this->skip($offset); <add> <add> return is_null($length) ? $instance : $instance->take($length); <add> } <add> <add> /** <add> * Split a collection into a certain number of groups. <add> * <add> * @param int $numberOfGroups <add> * @return static <add> */ <add> public function split($numberOfGroups) <add> { <add> return $this->passthru('split', func_get_args()); <add> } <add> <add> /** <add> * Chunk the collection into chunks of the given size. <add> * <add> * @param int $size <add> * @return static <add> */ <add> public function chunk($size) <add> { <add> if ($size <= 0) { <add> return static::empty(); <add> } <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $size) { <add> $iterator = $original->getIterator(); <add> <add> while ($iterator->valid()) { <add> $values = []; <add> <add> for ($i = 0; $iterator->valid() && $i < $size; $i++, $iterator->next()) { <add> $values[$iterator->key()] = $iterator->current(); <add> } <add> <add> yield new static($values); <add> } <add> }); <add> } <add> <add> /** <add> * Sort through each item with a callback. <add> * <add> * @param callable|null $callback <add> * @return static <add> */ <add> public function sort(callable $callback = null) <add> { <add> return $this->passthru('sort', func_get_args()); <add> } <add> <add> /** <add> * Sort the collection using the given callback. <add> * <add> * @param callable|string $callback <add> * @param int $options <add> * @param bool $descending <add> * @return static <add> */ <add> public function sortBy($callback, $options = SORT_REGULAR, $descending = false) <add> { <add> return $this->passthru('sortBy', func_get_args()); <add> } <add> <add> /** <add> * Sort the collection in descending order using the given callback. <add> * <add> * @param callable|string $callback <add> * @param int $options <add> * @return static <add> */ <add> public function sortByDesc($callback, $options = SORT_REGULAR) <add> { <add> return $this->passthru('sortByDesc', func_get_args()); <add> } <add> <add> /** <add> * Sort the collection keys. <add> * <add> * @param int $options <add> * @param bool $descending <add> * @return static <add> */ <add> public function sortKeys($options = SORT_REGULAR, $descending = false) <add> { <add> return $this->passthru('sortKeys', func_get_args()); <add> } <add> <add> /** <add> * Sort the collection keys in descending order. <add> * <add> * @param int $options <add> * @return static <add> */ <add> public function sortKeysDesc($options = SORT_REGULAR) <add> { <add> return $this->passthru('sortKeysDesc', func_get_args()); <add> } <add> <add> /** <add> * Splice a portion of the underlying collection array. <add> * <add> * @param int $offset <add> * @param int|null $length <add> * @param mixed $replacement <add> * @return static <add> */ <add> public function splice($offset, $length = null, $replacement = []) <add> { <add> $items = $this->collect(); <add> <add> $extracted = $items->splice(...func_get_args()); <add> <add> $this->source = function () use ($items) { <add> yield from $items; <add> }; <add> <add> return new static($extracted); <add> } <add> <add> /** <add> * Take the first or last {$limit} items. <add> * <add> * @param int $limit <add> * @return static <add> */ <add> public function take($limit) <add> { <add> if ($limit < 0) { <add> return $this->passthru('take', func_get_args()); <add> } <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $limit) { <add> $iterator = $original->getIterator(); <add> <add> for (; $iterator->valid() && $limit--; $iterator->next()) { <add> yield $iterator->key() => $iterator->current(); <add> } <add> }); <add> } <add> <add> /** <add> * Transform each item in the collection using a callback. <add> * <add> * @param callable $callback <add> * @return $this <add> */ <add> public function transform(callable $callback) <add> { <add> $original = clone $this; <add> <add> $this->source = function () use ($original, $callback) { <add> yield from $original->map($callback); <add> }; <add> <add> return $this; <add> } <add> <add> /** <add> * Reset the keys on the underlying array. <add> * <add> * @return static <add> */ <add> public function values() <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original) { <add> foreach ($original as $item) { <add> yield $item; <add> } <add> }); <add> } <add> <add> /** <add> * Zip the collection together with one or more arrays. <add> * <add> * e.g. new LazyCollection([1, 2, 3])->zip([4, 5, 6]); <add> * => [[1, 4], [2, 5], [3, 6]] <add> * <add> * @param mixed ...$items <add> * @return static <add> */ <add> public function zip($items) <add> { <add> $iterables = func_get_args(); <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $iterables) { <add> $iterators = Collection::make($iterables)->map(function ($iterable) { <add> return $this->makeIterator($iterable); <add> })->prepend($original->getIterator()); <add> <add> while ($iterators->contains->valid()) { <add> yield new static($iterators->map->current()); <add> <add> $iterators->each->next(); <add> } <add> }); <add> } <add> <add> /** <add> * Pad collection to the specified length with a value. <add> * <add> * @param int $size <add> * @param mixed $value <add> * @return static <add> */ <add> public function pad($size, $value) <add> { <add> if ($size < 0) { <add> return $this->passthru('pad', func_get_args()); <add> } <add> <add> $original = clone $this; <add> <add> return new static(function () use ($original, $size, $value) { <add> $yielded = 0; <add> <add> foreach ($original as $index => $item) { <add> yield $index => $item; <add> <add> $yielded++; <add> } <add> <add> while ($yielded++ < $size) { <add> yield $value; <add> } <add> }); <add> } <add> <add> /** <add> * Get the values iterator. <add> * <add> * @return \Traversable <add> */ <add> public function getIterator() <add> { <add> return $this->makeIterator($this->source); <add> } <add> <add> /** <add> * Count the number of items in the collection. <add> * <add> * @return int <add> */ <add> public function count() <add> { <add> if (is_array($this->source)) { <add> return count($this->source); <add> } <add> <add> return iterator_count($this->getIterator()); <add> } <add> <add> /** <add> * Add an item to the collection. <add> * <add> * @param mixed $item <add> * @return $this <add> */ <add> public function add($item) <add> { <add> $original = clone $this; <add> <add> $this->source = function () use ($original, $item) { <add> foreach ($original as $value) { <add> yield $value; <add> } <add> <add> yield $item; <add> }; <add> <add> return $this; <add> } <add> <add> /** <add> * Make an iterator from the given source. <add> * <add> * @param mixed $source <add> * @return \Traversable <add> */ <add> protected function makeIterator($source) <add> { <add> if ($source instanceof IteratorAggregate) { <add> return $source->getIterator(); <add> } <add> <add> if (is_array($source)) { <add> return new ArrayIterator($source); <add> } <add> <add> return $source(); <add> } <add> <add> /** <add> * Explode the "value" and "key" arguments passed to "pluck". <add> * <add> * @param string|array $value <add> * @param string|array|null $key <add> * @return array <add> */ <add> protected function explodePluckParameters($value, $key) <add> { <add> $value = is_string($value) ? explode('.', $value) : $value; <add> <add> $key = is_null($key) || is_array($key) ? $key : explode('.', $key); <add> <add> return [$value, $key]; <add> } <add> <add> /** <add> * Pass this lazy collection through a method on the collection class. <add> * <add> * @param string $method <add> * @param array $params <add> * @return static <add> */ <add> protected function passthru($method, array $params) <add> { <add> $original = clone $this; <add> <add> return new static(function () use ($original, $method, $params) { <add> yield from $original->collect()->$method(...$params); <add> }); <add> } <add> <add> /** <add> * Finish cloning the collection instance. <add> * <add> * @return void <add> */ <add> public function __clone() <add> { <add> if (! is_array($this->source)) { <add> $this->source = clone $this->source; <add> } <add> } <add>} <ide><path>tests/Support/SupportCollectionTest.php <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Support\Collection; <ide> use Illuminate\Support\HtmlString; <add>use Illuminate\Support\LazyCollection; <ide> use Illuminate\Contracts\Support\Jsonable; <ide> use Illuminate\Contracts\Support\Arrayable; <ide> <ide> public function collectionClassProvider() <ide> { <ide> return [ <ide> [Collection::class], <add> [LazyCollection::class], <ide> ]; <ide> } <ide> }
2
Text
Text
add h1 title
110793e73a56b90b7ee99dd49e3dc95855b82595
<ide><path>guide/english/working-in-tech/giving-a-conference-talk/index.md <ide> --- <ide> title: Giving a Conference Talk <ide> --- <add># Giving a Conference Talk <add> <ide> <ide> Speaking at a tech conference or community meetup can be a great way to accelerate your career. It gives you a chance to share something you have learned and is a great way to challenge yourself technically. Speaking at a conference is also an opportunity to meet interesting people within the tech community. <ide>
1
Python
Python
add a tool for determining active svn committers
8c7d1bc554e6b5bbb7900a2f6d976d72795bb454
<ide><path>tools/commitstats.py <add> <add># Run svn log -l <some number> <add> <add>import re <add>import numpy as np <add>import os <add> <add>names = re.compile(r'r\d+\s[|]\s(.*)\s[|]\s200') <add> <add>def get_count(filename, repo): <add> mystr = open(filename).read() <add> result = names.findall(mystr) <add> u = np.unique(result) <add> count = [(x,result.count(x),repo) for x in u] <add> return count <add> <add> <add>command = 'svn log -l 2300 > output.txt' <add>os.chdir('..') <add>os.system(command) <add> <add>count = get_count('output.txt', 'NumPy') <add> <add> <add>os.chdir('../scipy') <add>os.system(command) <add> <add>count.extend(get_count('output.txt', 'SciPy')) <add> <add>os.chdir('../scikits') <add>os.system(command) <add>count.extend(get_count('output.txt', 'SciKits')) <add>count.sort() <add> <add> <add> <add>print "** SciPy and NumPy **" <add>print "=====================" <add>for val in count: <add> print val <add> <add> <add>
1
PHP
PHP
enable strict typing for all orm files
fd9f3931109ffcc03c6d49084cebbd6277849e3f
<ide><path>src/Database/Query.php <ide> public function rowCountAndClose() <ide> * associated values for expressions <ide> * @return string <ide> */ <del> public function sql(?ValueBinder $generator = null) <add> public function sql(?ValueBinder $generator = null): string <ide> { <ide> if (!$generator) { <ide> $generator = $this->getValueBinder(); <ide><path>src/Datasource/RepositoryInterface.php <ide> public function hasField(string $field): bool; <ide> * @param array|\ArrayAccess $options An array that will be passed to Query::applyOptions() <ide> * @return \Cake\Datasource\QueryInterface <ide> */ <del> public function find($type = 'all', $options = []); <add> public function find(string $type = 'all', $options = []); <ide> <ide> /** <ide> * Returns a single record after finding it by its primary key, if no record is <ide> public function find($type = 'all', $options = []); <ide> * @return \Cake\Datasource\EntityInterface <ide> * @see \Cake\Datasource\RepositoryInterface::find() <ide> */ <del> public function get($primaryKey, $options = []); <add> public function get($primaryKey, $options = []): EntityInterface; <ide> <ide> /** <ide> * Creates a new Query instance for this repository <ide> public function delete(EntityInterface $entity, $options = []): bool; <ide> * @param array $options A list of options for the object hydration. <ide> * @return \Cake\Datasource\EntityInterface <ide> */ <del> public function newEntity(?array $data = null, array $options = []); <add> public function newEntity(?array $data = null, array $options = []): EntityInterface; <ide> <ide> /** <ide> * Create a list of entities + associated entities from an array. <ide> public function newEntity(?array $data = null, array $options = []); <ide> * @param array $options A list of options for the objects hydration. <ide> * @return \Cake\Datasource\EntityInterface[] An array of hydrated records. <ide> */ <del> public function newEntities(array $data, array $options = []); <add> public function newEntities(array $data, array $options = []): array; <ide> <ide> /** <ide> * Merges the passed `$data` into `$entity` respecting the accessible <ide> public function newEntities(array $data, array $options = []); <ide> * @param array $options A list of options for the object hydration. <ide> * @return \Cake\Datasource\EntityInterface <ide> */ <del> public function patchEntity(EntityInterface $entity, array $data, array $options = []); <add> public function patchEntity(EntityInterface $entity, array $data, array $options = []): EntityInterface; <ide> <ide> /** <ide> * Merges each of the elements passed in `$data` into the entities <ide> public function patchEntity(EntityInterface $entity, array $data, array $options <ide> * @param array $options A list of options for the objects hydration. <ide> * @return \Cake\Datasource\EntityInterface[] <ide> */ <del> public function patchEntities($entities, array $data, array $options = []); <add> public function patchEntities($entities, array $data, array $options = []): array; <ide> } <ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> use Cake\ORM\Behavior; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <add>use Cake\ORM\Marshaller; <ide> use Cake\ORM\PropertyMarshalInterface; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\Table; <ide> public function afterSave(EventInterface $event, EntityInterface $entity): void <ide> * <ide> * {@inheritDoc} <ide> */ <del> public function buildMarshalMap($marshaller, $map, $options) <add> public function buildMarshalMap(Marshaller $marshaller, array $map, array $options): array <ide> { <ide> if (isset($options['translations']) && !$options['translations']) { <ide> return []; <ide><path>src/ORM/BehaviorRegistry.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class BehaviorRegistry extends ObjectRegistry implements EventDispatcherInterfac <ide> * <ide> * @param \Cake\ORM\Table|null $table The table this registry is attached to. <ide> */ <del> public function __construct($table = null) <add> public function __construct(?Table $table = null) <ide> { <ide> if ($table !== null) { <ide> $this->setTable($table); <ide> public function __construct($table = null) <ide> * @param \Cake\ORM\Table $table The table this registry is attached to. <ide> * @return void <ide> */ <del> public function setTable(Table $table) <add> public function setTable(Table $table): void <ide> { <ide> $this->_table = $table; <ide> $eventManager = $table->getEventManager(); <ide> public function setTable(Table $table) <ide> * @return string|null Either the correct classname or null. <ide> * @since 3.5.7 <ide> */ <del> public static function className($class) <add> public static function className(string $class): ?string <ide> { <ide> $result = App::className($class, 'Model/Behavior', 'Behavior'); <ide> if (!$result) { <ide> protected function _create($class, $alias, $config) <ide> * @return array A list of implemented finders and methods. <ide> * @throws \LogicException when duplicate methods are connected. <ide> */ <del> protected function _getMethods(Behavior $instance, $class, $alias) <add> protected function _getMethods(Behavior $instance, string $class, string $alias): array <ide> { <ide> $finders = array_change_key_case($instance->implementedFinders()); <ide> $methods = array_change_key_case($instance->implementedMethods()); <ide> protected function _getMethods(Behavior $instance, $class, $alias) <ide> * @param string $method The method to check for. <ide> * @return bool <ide> */ <del> public function hasMethod($method) <add> public function hasMethod(string $method): bool <ide> { <ide> $method = strtolower($method); <ide> <ide> public function hasMethod($method) <ide> * @param string $method The method to check for. <ide> * @return bool <ide> */ <del> public function hasFinder($method) <add> public function hasFinder(string $method): bool <ide> { <ide> $method = strtolower($method); <ide> <ide> public function hasFinder($method) <ide> * @return mixed The return value depends on the underlying behavior method. <ide> * @throws \BadMethodCallException When the method is unknown. <ide> */ <del> public function call($method, array $args = []) <add> public function call(string $method, array $args = []) <ide> { <ide> $method = strtolower($method); <ide> if ($this->hasMethod($method) && $this->has($this->_methodMap[$method][0])) { <ide> public function call($method, array $args = []) <ide> * @return mixed The return value depends on the underlying behavior method. <ide> * @throws \BadMethodCallException When the method is unknown. <ide> */ <del> public function callFinder($type, array $args = []) <add> public function callFinder(string $type, array $args = []) <ide> { <ide> $type = strtolower($type); <ide> <ide><path>src/ORM/EagerLoadable.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class EagerLoadable <ide> * @param string $name The Association name. <ide> * @param array $config The list of properties to set. <ide> */ <del> public function __construct($name, array $config = []) <add> public function __construct(string $name, array $config = []) <ide> { <ide> $this->_name = $name; <ide> $allowed = [ <ide> public function __construct($name, array $config = []) <ide> * @param \Cake\ORM\EagerLoadable $association The association to load. <ide> * @return void <ide> */ <del> public function addAssociation($name, EagerLoadable $association) <add> public function addAssociation(string $name, EagerLoadable $association): void <ide> { <ide> $this->_associations[$name] = $association; <ide> } <ide> public function addAssociation($name, EagerLoadable $association) <ide> * <ide> * @return array <ide> */ <del> public function associations() <add> public function associations(): array <ide> { <ide> return $this->_associations; <ide> } <ide> public function associations() <ide> * <ide> * @return \Cake\ORM\Association|null <ide> */ <del> public function instance() <add> public function instance(): ?Association <ide> { <ide> return $this->_instance; <ide> } <ide> public function instance() <ide> * <ide> * @return string|null <ide> */ <del> public function aliasPath() <add> public function aliasPath(): ?string <ide> { <ide> return $this->_aliasPath; <ide> } <ide> public function aliasPath() <ide> * <ide> * @return string|null <ide> */ <del> public function propertyPath() <add> public function propertyPath(): ?string <ide> { <ide> return $this->_propertyPath; <ide> } <ide> public function propertyPath() <ide> * @param bool $possible The value to set. <ide> * @return $this <ide> */ <del> public function setCanBeJoined($possible) <add> public function setCanBeJoined(bool $possible): self <ide> { <ide> $this->_canBeJoined = (bool)$possible; <ide> <ide> public function setCanBeJoined($possible) <ide> * <ide> * @return bool <ide> */ <del> public function canBeJoined() <add> public function canBeJoined(): bool <ide> { <ide> return $this->_canBeJoined; <ide> } <ide> public function canBeJoined() <ide> * @param array $config The value to set. <ide> * @return $this <ide> */ <del> public function setConfig(array $config) <add> public function setConfig(array $config): self <ide> { <ide> $this->_config = $config; <ide> <ide> public function setConfig(array $config) <ide> * <ide> * @return array <ide> */ <del> public function getConfig() <add> public function getConfig(): array <ide> { <ide> return $this->_config; <ide> } <ide> public function getConfig() <ide> * <ide> * @return bool|null <ide> */ <del> public function forMatching() <add> public function forMatching(): ?bool <ide> { <ide> return $this->_forMatching; <ide> } <ide> public function forMatching() <ide> * <ide> * @return string|null <ide> */ <del> public function targetProperty() <add> public function targetProperty(): ?string <ide> { <ide> return $this->_targetProperty; <ide> } <ide> public function targetProperty() <ide> * <ide> * @return array <ide> */ <del> public function asContainArray() <add> public function asContainArray(): array <ide> { <ide> $associations = []; <ide> foreach ($this->_associations as $assoc) { <ide><path>src/ORM/EagerLoader.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> <ide> use Cake\Database\Statement\BufferedStatement; <ide> use Cake\Database\Statement\CallbackStatement; <add>use Cake\Database\StatementInterface; <ide> use Cake\Datasource\QueryInterface; <ide> use Closure; <ide> use InvalidArgumentException; <ide> class EagerLoader <ide> * @return array Containments. <ide> * @throws \InvalidArgumentException When using $queryBuilder with an array of $associations <ide> */ <del> public function contain($associations, ?callable $queryBuilder = null) <add> public function contain($associations, ?callable $queryBuilder = null): array <ide> { <ide> if ($queryBuilder) { <ide> if (!is_string($associations)) { <ide> public function contain($associations, ?callable $queryBuilder = null) <ide> * <ide> * @return array Containments. <ide> */ <del> public function getContain() <add> public function getContain(): array <ide> { <ide> return $this->_containments; <ide> } <ide> public function getContain() <ide> * <ide> * @return void <ide> */ <del> public function clearContain() <add> public function clearContain(): void <ide> { <ide> $this->_containments = []; <ide> $this->_normalized = null; <ide> public function clearContain() <ide> * @param bool $enable The value to set. <ide> * @return $this <ide> */ <del> public function enableAutoFields($enable = true) <add> public function enableAutoFields(bool $enable = true): self <ide> { <ide> $this->_autoFields = (bool)$enable; <ide> <ide> public function enableAutoFields($enable = true) <ide> * <ide> * @return bool The current value. <ide> */ <del> public function isAutoFieldsEnabled() <add> public function isAutoFieldsEnabled(): bool <ide> { <ide> return $this->_autoFields; <ide> } <ide> public function isAutoFieldsEnabled() <ide> * @param array $options Extra options for the association matching. <ide> * @return $this <ide> */ <del> public function setMatching($assoc, ?callable $builder = null, $options = []) <add> public function setMatching(string $assoc, ?callable $builder = null, array $options = []): self <ide> { <ide> if ($this->_matching === null) { <ide> $this->_matching = new static(); <ide> public function setMatching($assoc, ?callable $builder = null, $options = []) <ide> * <ide> * @return array The resulting containments array <ide> */ <del> public function getMatching() <add> public function getMatching(): array <ide> { <ide> if ($this->_matching === null) { <ide> $this->_matching = new static(); <ide> public function getMatching() <ide> * will be normalized <ide> * @return array <ide> */ <del> public function normalized(Table $repository) <add> public function normalized(Table $repository): array <ide> { <ide> if ($this->_normalized !== null || empty($this->_containments)) { <ide> return (array)$this->_normalized; <ide> public function normalized(Table $repository) <ide> * with the new one <ide> * @return array <ide> */ <del> protected function _reformatContain($associations, $original) <add> protected function _reformatContain(array $associations, array $original): array <ide> { <ide> $result = $original; <ide> <ide> protected function _reformatContain($associations, $original) <ide> * per association in the containments array <ide> * @return void <ide> */ <del> public function attachAssociations(Query $query, Table $repository, $includeFields) <add> public function attachAssociations(Query $query, Table $repository, bool $includeFields): void <ide> { <ide> if (empty($this->_containments) && $this->_matching === null) { <ide> return; <ide> public function attachAssociations(Query $query, Table $repository, $includeFiel <ide> * attached <ide> * @return array <ide> */ <del> public function attachableAssociations(Table $repository) <add> public function attachableAssociations(Table $repository): array <ide> { <ide> $contain = $this->normalized($repository); <ide> $matching = $this->_matching ? $this->_matching->normalized($repository) : []; <ide> public function attachableAssociations(Table $repository) <ide> * to be loaded <ide> * @return \Cake\ORM\EagerLoadable[] <ide> */ <del> public function externalAssociations(Table $repository) <add> public function externalAssociations(Table $repository): array <ide> { <ide> if ($this->_loadExternal) { <ide> return $this->_loadExternal; <ide> public function externalAssociations(Table $repository) <ide> * @return \Cake\ORM\EagerLoadable Object with normalized associations <ide> * @throws \InvalidArgumentException When containments refer to associations that do not exist. <ide> */ <del> protected function _normalizeContain(Table $parent, $alias, $options, $paths) <add> protected function _normalizeContain(Table $parent, string $alias, array $options, array $paths): EagerLoadable <ide> { <ide> $defaults = $this->_containOptions; <ide> $instance = $parent->getAssociation($alias); <ide> protected function _normalizeContain(Table $parent, $alias, $options, $paths) <ide> * <ide> * @return void <ide> */ <del> protected function _fixStrategies() <add> protected function _fixStrategies(): void <ide> { <ide> foreach ($this->_aliasList as $aliases) { <ide> foreach ($aliases as $configs) { <ide> protected function _fixStrategies() <ide> * @param \Cake\ORM\EagerLoadable $loadable The association config <ide> * @return void <ide> */ <del> protected function _correctStrategy($loadable) <add> protected function _correctStrategy(EagerLoadable $loadable): void <ide> { <ide> $config = $loadable->getConfig(); <ide> $currentStrategy = $config['strategy'] ?? <ide> protected function _correctStrategy($loadable) <ide> * @param array $matching list of associations that should be forcibly joined. <ide> * @return array <ide> */ <del> protected function _resolveJoins($associations, $matching = []) <add> protected function _resolveJoins(array $associations, array $matching = []): array <ide> { <ide> $result = []; <ide> foreach ($matching as $table => $loadable) { <ide> protected function _resolveJoins($associations, $matching = []) <ide> * @param \Cake\Database\StatementInterface $statement The statement created after executing the $query <ide> * @return \Cake\Database\StatementInterface statement modified statement with extra loaders <ide> */ <del> public function loadExternal($query, $statement) <add> public function loadExternal(Query $query, StatementInterface $statement): StatementInterface <ide> { <ide> $external = $this->externalAssociations($query->getRepository()); <ide> if (empty($external)) { <ide> public function loadExternal($query, $statement) <ide> * will be normalized <ide> * @return array <ide> */ <del> public function associationsMap($table) <add> public function associationsMap(Table $table): array <ide> { <ide> $map = []; <ide> <ide> public function associationsMap($table) <ide> * @param bool $matching Whether or not it is an association loaded through `matching()`. <ide> * @return array <ide> */ <del> protected function _buildAssociationsMap($map, $level, $matching = false) <add> protected function _buildAssociationsMap(array $map, array $level, bool $matching = false): array <ide> { <ide> /* @var \Cake\ORM\EagerLoadable $meta */ <ide> foreach ($level as $assoc => $meta) { <ide> protected function _buildAssociationsMap($map, $level, $matching = false) <ide> * If not passed, the default property for the association will be used. <ide> * @return void <ide> */ <del> public function addToJoinsMap($alias, Association $assoc, $asMatching = false, $targetProperty = null) <add> public function addToJoinsMap(string $alias, Association $assoc, bool $asMatching = false, ?string $targetProperty = null): void <ide> { <ide> $this->_joinsMap[$alias] = new EagerLoadable($alias, [ <ide> 'aliasPath' => $alias, <ide> public function addToJoinsMap($alias, Association $assoc, $asMatching = false, $ <ide> * @param \Cake\Database\Statement\BufferedStatement $statement The statement to work on <ide> * @return array <ide> */ <del> protected function _collectKeys($external, $query, $statement) <add> protected function _collectKeys(array $external, Query $query, $statement): array <ide> { <ide> $collectKeys = []; <ide> /* @var \Cake\ORM\EagerLoadable $meta */ <ide> protected function _collectKeys($external, $query, $statement) <ide> * @param array $collectKeys The keys to collect <ide> * @return array <ide> */ <del> protected function _groupKeys($statement, $collectKeys) <add> protected function _groupKeys(BufferedStatement $statement, array $collectKeys): array <ide> { <ide> $keys = []; <ide> while ($result = $statement->fetch('assoc')) { <ide><path>src/ORM/Exception/PersistenceFailedException.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(EntityInterface $entity, $message, $code = null, $pr <ide> * @param string|array $error Error message. <ide> * @return string <ide> */ <del> protected function buildError($error) <add> protected function buildError($error): string <ide> { <ide> if (!is_array($error)) { <ide> return $error; <ide> protected function buildError($error) <ide> * <ide> * @return \Cake\Datasource\EntityInterface <ide> */ <del> public function getEntity() <add> public function getEntity(): EntityInterface <ide> { <ide> return $this->_entity; <ide> } <ide><path>src/ORM/LazyEagerLoader.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> namespace Cake\ORM; <ide> <ide> use Cake\Collection\Collection; <add>use Cake\Collection\CollectionInterface; <ide> use Cake\Database\Expression\TupleComparison; <ide> use Cake\Datasource\EntityInterface; <ide> <ide> public function loadInto($entities, array $contain, Table $source) <ide> * @param \Cake\ORM\Table $source The table to use for fetching the top level entities <ide> * @return \Cake\ORM\Query <ide> */ <del> protected function _getQuery($objects, $contain, $source) <add> protected function _getQuery(CollectionInterface $objects, array $contain, Table $source): Query <ide> { <ide> $primaryKey = $source->getPrimaryKey(); <ide> $method = is_string($primaryKey) ? 'get' : 'extract'; <ide> protected function _getQuery($objects, $contain, $source) <ide> * @param array $associations The name of the top level associations <ide> * @return array <ide> */ <del> protected function _getPropertyMap($source, $associations) <add> protected function _getPropertyMap(Table $source, array $associations): array <ide> { <ide> $map = []; <ide> $container = $source->associations(); <ide> protected function _getPropertyMap($source, $associations) <ide> * Injects the results of the eager loader query into the original list of <ide> * entities. <ide> * <del> * @param array|\Traversable $objects The original list of entities <add> * @param iterable $objects The original list of entities <ide> * @param \Cake\Collection\CollectionInterface|\Cake\Database\Query $results The loaded results <ide> * @param array $associations The top level associations that were loaded <ide> * @param \Cake\ORM\Table $source The table where the entities came from <ide> * @return array <ide> */ <del> protected function _injectResults($objects, $results, $associations, $source) <add> protected function _injectResults(iterable $objects, $results, array $associations, Table $source): array <ide> { <ide> $injected = []; <ide> $properties = $this->_getPropertyMap($source, $associations); <ide><path>src/ORM/Locator/LocatorAwareTrait.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function setTableLocator(LocatorInterface $tableLocator) <ide> * <ide> * @return \Cake\ORM\Locator\LocatorInterface <ide> */ <del> public function getTableLocator() <add> public function getTableLocator(): LocatorInterface <ide> { <ide> if (!$this->_tableLocator) { <ide> $this->_tableLocator = TableRegistry::getTableLocator(); <ide><path>src/ORM/Locator/LocatorInterface.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> interface LocatorInterface <ide> * @param string|null $alias Alias to get config for, null for complete config. <ide> * @return array The config data. <ide> */ <del> public function getConfig($alias = null); <add> public function getConfig(?string $alias = null): array; <ide> <ide> /** <ide> * Stores a list of options to be used when instantiating an object <ide> public function setConfig($alias, $options = null); <ide> * @param array $options The options you want to build the table with. <ide> * @return \Cake\ORM\Table <ide> */ <del> public function get($alias, array $options = []); <add> public function get(string $alias, array $options = []): Table; <ide> <ide> /** <ide> * Check to see if an instance exists in the registry. <ide> * <ide> * @param string $alias The alias to check for. <ide> * @return bool <ide> */ <del> public function exists($alias); <add> public function exists(string $alias): bool; <ide> <ide> /** <ide> * Set an instance. <ide> public function exists($alias); <ide> * @param \Cake\ORM\Table $object The table to set. <ide> * @return \Cake\ORM\Table <ide> */ <del> public function set($alias, Table $object); <add> public function set(string $alias, Table $object): Table; <ide> <ide> /** <ide> * Clears the registry of configuration and instances. <ide> * <ide> * @return void <ide> */ <del> public function clear(); <add> public function clear(): void; <ide> <ide> /** <ide> * Removes an instance from the registry. <ide> * <ide> * @param string $alias The alias to remove. <ide> * @return void <ide> */ <del> public function remove($alias); <add> public function remove(string $alias): void; <ide> } <ide><path>src/ORM/Locator/TableLocator.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function setConfig($alias, $options = null) <ide> * @param string|null $alias Alias to get config for, null for complete config. <ide> * @return array The config data. <ide> */ <del> public function getConfig($alias = null) <add> public function getConfig(?string $alias = null): array <ide> { <ide> if ($alias === null) { <ide> return $this->_config; <ide> public function getConfig($alias = null) <ide> * @return \Cake\ORM\Table <ide> * @throws \RuntimeException When you try to configure an alias that already exists. <ide> */ <del> public function get($alias, array $options = []) <add> public function get(string $alias, array $options = []): Table <ide> { <ide> if (isset($this->_instances[$alias])) { <ide> if (!empty($options) && $this->_options[$alias] !== $options) { <ide> public function get($alias, array $options = []) <ide> * @param array $options Table options array. <ide> * @return string|null <ide> */ <del> protected function _getClassName($alias, array $options = []) <add> protected function _getClassName(string $alias, array $options = []): ?string <ide> { <ide> if (empty($options['className'])) { <ide> $options['className'] = Inflector::camelize($alias); <ide> protected function _getClassName($alias, array $options = []) <ide> * @param array $options The alias to check for. <ide> * @return \Cake\ORM\Table <ide> */ <del> protected function _create(array $options) <add> protected function _create(array $options): Table <ide> { <ide> return new $options['className']($options); <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function exists($alias) <add> public function exists(string $alias): bool <ide> { <ide> return isset($this->_instances[$alias]); <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function set($alias, Table $object) <add> public function set(string $alias, Table $object): Table <ide> { <ide> return $this->_instances[$alias] = $object; <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function clear() <add> public function clear(): void <ide> { <ide> $this->_instances = []; <ide> $this->_config = []; <ide> public function clear() <ide> * <ide> * @return \Cake\ORM\Table[] <ide> */ <del> public function genericInstances() <add> public function genericInstances(): array <ide> { <ide> return $this->_fallbacked; <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function remove($alias) <add> public function remove(string $alias): void <ide> { <ide> unset( <ide> $this->_instances[$alias], <ide><path>src/ORM/Marshaller.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(Table $table) <ide> * @throws \InvalidArgumentException When associations do not exist. <ide> * @return array <ide> */ <del> protected function _buildPropertyMap($data, $options) <add> protected function _buildPropertyMap(array $data, array $options): array <ide> { <ide> $map = []; <ide> $schema = $this->_table->getSchema(); <ide> protected function _buildPropertyMap($data, $options) <ide> * @see \Cake\ORM\Table::newEntity() <ide> * @see \Cake\ORM\Entity::$_accessible <ide> */ <del> public function one(array $data, array $options = []) <add> public function one(array $data, array $options = []): EntityInterface <ide> { <ide> list($data, $options) = $this->_prepareDataAndOptions($data, $options); <ide> <ide> public function one(array $data, array $options = []) <ide> * @return array The list of validation errors. <ide> * @throws \RuntimeException If no validator can be created. <ide> */ <del> protected function _validate($data, $options, $isNew) <add> protected function _validate(array $data, array $options, bool $isNew): array <ide> { <ide> if (!$options['validate']) { <ide> return []; <ide> protected function _validate($data, $options, $isNew) <ide> * @param array $options The options passed to this marshaller. <ide> * @return array An array containing prepared data and options. <ide> */ <del> protected function _prepareDataAndOptions($data, $options) <add> protected function _prepareDataAndOptions(array $data, array $options): array <ide> { <ide> $options += ['validate' => true]; <ide> <ide> protected function _prepareDataAndOptions($data, $options) <ide> * @param array $options List of options. <ide> * @return \Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[]|null <ide> */ <del> protected function _marshalAssociation($assoc, $value, $options) <add> protected function _marshalAssociation(Association $assoc, $value, array $options) <ide> { <ide> if (!is_array($value)) { <ide> return null; <ide> protected function _marshalAssociation($assoc, $value, $options) <ide> * @see \Cake\ORM\Table::newEntities() <ide> * @see \Cake\ORM\Entity::$_accessible <ide> */ <del> public function many(array $data, array $options = []) <add> public function many(array $data, array $options = []): array <ide> { <ide> $output = []; <ide> foreach ($data as $record) { <ide> public function many(array $data, array $options = []) <ide> * @throws \InvalidArgumentException <ide> * @throws \RuntimeException <ide> */ <del> protected function _belongsToMany(BelongsToMany $assoc, array $data, $options = []) <add> protected function _belongsToMany(BelongsToMany $assoc, array $data, array $options = []): array <ide> { <ide> $associated = $options['associated'] ?? []; <ide> $forceNew = $options['forceNew'] ?? false; <ide> protected function _belongsToMany(BelongsToMany $assoc, array $data, $options = <ide> * @param array $ids The list of ids to load. <ide> * @return \Cake\Datasource\EntityInterface[] An array of entities. <ide> */ <del> protected function _loadAssociatedByIds($assoc, $ids) <add> protected function _loadAssociatedByIds(Association $assoc, array $ids): array <ide> { <ide> if (empty($ids)) { <ide> return []; <ide> protected function _loadAssociatedByIds($assoc, $ids) <ide> * @return \Cake\Datasource\EntityInterface <ide> * @see \Cake\ORM\Entity::$_accessible <ide> */ <del> public function merge(EntityInterface $entity, array $data, array $options = []) <add> public function merge(EntityInterface $entity, array $data, array $options = []): EntityInterface <ide> { <ide> list($data, $options) = $this->_prepareDataAndOptions($data, $options); <ide> <ide> public function merge(EntityInterface $entity, array $data, array $options = []) <ide> * @return \Cake\Datasource\EntityInterface[] <ide> * @see \Cake\ORM\Entity::$_accessible <ide> */ <del> public function mergeMany($entities, array $data, array $options = []) <add> public function mergeMany($entities, array $data, array $options = []): array <ide> { <ide> $primary = (array)$this->_table->getPrimaryKey(); <ide> <ide> public function mergeMany($entities, array $data, array $options = []) <ide> <ide> $conditions = (new Collection($indexed)) <ide> ->map(function ($data, $key) { <del> return explode(';', $key); <add> return explode(';', (string)$key); <ide> }) <ide> ->filter(function ($keys) use ($primary) { <ide> return count(array_filter($keys, 'strlen')) === count($primary); <ide> public function mergeMany($entities, array $data, array $options = []) <ide> * @param array $options List of options. <ide> * @return \Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[]|null <ide> */ <del> protected function _mergeAssociation($original, $assoc, $value, $options) <add> protected function _mergeAssociation($original, Association $assoc, $value, array $options) <ide> { <ide> if (!$original) { <ide> return $this->_marshalAssociation($assoc, $value, $options); <ide> protected function _mergeAssociation($original, $assoc, $value, $options) <ide> * @param array $options List of options. <ide> * @return \Cake\Datasource\EntityInterface[] <ide> */ <del> protected function _mergeBelongsToMany($original, $assoc, $value, $options) <add> protected function _mergeBelongsToMany($original, Association $assoc, $value, array $options): array <ide> { <ide> $associated = $options['associated'] ?? []; <ide> <ide> protected function _mergeBelongsToMany($original, $assoc, $value, $options) <ide> * @param array $options List of options. <ide> * @return \Cake\Datasource\EntityInterface[] An array of entities <ide> */ <del> protected function _mergeJoinData($original, $assoc, $value, $options) <add> protected function _mergeJoinData($original, BelongsToMany $assoc, array $value, array $options): array <ide> { <ide> $associated = $options['associated'] ?? []; <ide> $extra = []; <ide><path>src/ORM/PropertyMarshalInterface.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> interface PropertyMarshalInterface <ide> * @param array $options The options array used in the marshalling call. <ide> * @return array A map of `[property => callable]` of additional properties to marshal. <ide> */ <del> public function buildMarshalMap($marshaller, $map, $options); <add> public function buildMarshalMap(Marshaller $marshaller, array $map, array $options): array; <ide> } <ide><path>src/ORM/Query.php <ide> namespace Cake\ORM; <ide> <ide> use ArrayObject; <add>use Cake\Database\Connection; <ide> use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Query as DatabaseQuery; <ide> use Cake\Database\TypedResultInterface; <ide> use Cake\Database\TypeMap; <ide> use Cake\Database\ValueBinder; <ide> use Cake\Datasource\QueryInterface; <ide> use Cake\Datasource\QueryTrait; <add>use Cake\Datasource\ResultSetInterface; <ide> use JsonSerializable; <ide> use RuntimeException; <add>use Traversable; <ide> <ide> /** <ide> * Extends the base Query class to provide new methods related to association <ide> class Query extends DatabaseQuery implements JsonSerializable, QueryInterface <ide> * Tracks whether or not the original query should include <ide> * fields from the top level table. <ide> * <del> * @var bool <add> * @var bool|null <ide> */ <ide> protected $_autoFields; <ide> <ide> class Query extends DatabaseQuery implements JsonSerializable, QueryInterface <ide> * @param \Cake\Database\Connection $connection The connection object <ide> * @param \Cake\ORM\Table $table The table this query is starting on <ide> */ <del> public function __construct($connection, $table) <add> public function __construct(Connection $connection, Table $table) <ide> { <ide> parent::__construct($connection); <ide> $this->repository($table); <ide> public function __construct($connection, $table) <ide> * @param bool $overwrite whether to reset fields with passed list or not <ide> * @return $this <ide> */ <del> public function select($fields = [], $overwrite = false) <add> public function select($fields = [], $overwrite = false): self <ide> { <ide> if ($fields instanceof Association) { <ide> $fields = $fields->getTarget(); <ide> public function select($fields = [], $overwrite = false) <ide> * @return Query <ide> * @throws \InvalidArgumentException If Association|Table is not passed in first argument <ide> */ <del> public function selectAllExcept($table, array $excludedFields, $overwrite = false) <add> public function selectAllExcept($table, array $excludedFields, $overwrite = false): Query <ide> { <ide> if ($table instanceof Association) { <ide> $table = $table->getTarget(); <ide> public function selectAllExcept($table, array $excludedFields, $overwrite = fals <ide> * @param \Cake\ORM\Table $table The table to pull types from <ide> * @return $this <ide> */ <del> public function addDefaultTypes(Table $table) <add> public function addDefaultTypes(Table $table): self <ide> { <ide> $alias = $table->getAlias(); <ide> $map = $table->getSchema()->typeMap(); <ide> public function addDefaultTypes(Table $table) <ide> * @param \Cake\ORM\EagerLoader $instance The eager loader to use. <ide> * @return $this <ide> */ <del> public function setEagerLoader(EagerLoader $instance) <add> public function setEagerLoader(EagerLoader $instance): self <ide> { <ide> $this->_eagerLoader = $instance; <ide> <ide> public function setEagerLoader(EagerLoader $instance) <ide> * <ide> * @return \Cake\ORM\EagerLoader <ide> */ <del> public function getEagerLoader() <add> public function getEagerLoader(): EagerLoader <ide> { <ide> if ($this->_eagerLoader === null) { <ide> $this->_eagerLoader = new EagerLoader(); <ide> public function contain($associations, $override = false) <ide> /** <ide> * @return array <ide> */ <del> public function getContain() <add> public function getContain(): array <ide> { <ide> return $this->getEagerLoader()->getContain(); <ide> } <ide> public function getContain() <ide> * <ide> * @return $this <ide> */ <del> public function clearContain() <add> public function clearContain(): self <ide> { <ide> $this->getEagerLoader()->clearContain(); <ide> $this->_dirty(); <ide> public function clearContain() <ide> * @param array $associations The nested tree of associations to walk. <ide> * @return void <ide> */ <del> protected function _addAssociationsToTypeMap($table, $typeMap, $associations) <add> protected function _addAssociationsToTypeMap(Table $table, TypeMap $typeMap, array $associations): void <ide> { <ide> foreach ($associations as $name => $nested) { <ide> if (!$table->hasAssociation($name)) { <ide> protected function _addAssociationsToTypeMap($table, $typeMap, $associations) <ide> * that can be used to add custom conditions or selecting some fields <ide> * @return $this <ide> */ <del> public function matching($assoc, ?callable $builder = null) <add> public function matching(string $assoc, ?callable $builder = null): self <ide> { <ide> $result = $this->getEagerLoader()->setMatching($assoc, $builder)->getMatching(); <ide> $this->_addAssociationsToTypeMap($this->getRepository(), $this->getTypeMap(), $result); <ide> public function matching($assoc, ?callable $builder = null) <ide> * that can be used to add custom conditions or selecting some fields <ide> * @return $this <ide> */ <del> public function leftJoinWith($assoc, ?callable $builder = null) <add> public function leftJoinWith(string $assoc, ?callable $builder = null): self <ide> { <ide> $result = $this->getEagerLoader() <ide> ->setMatching($assoc, $builder, [ <ide> public function leftJoinWith($assoc, ?callable $builder = null) <ide> * @return $this <ide> * @see \Cake\ORM\Query::matching() <ide> */ <del> public function innerJoinWith($assoc, ?callable $builder = null) <add> public function innerJoinWith(string $assoc, ?callable $builder = null): self <ide> { <ide> $result = $this->getEagerLoader() <ide> ->setMatching($assoc, $builder, [ <ide> public function innerJoinWith($assoc, ?callable $builder = null) <ide> * that can be used to add custom conditions or selecting some fields <ide> * @return $this <ide> */ <del> public function notMatching($assoc, ?callable $builder = null) <add> public function notMatching(string $assoc, ?callable $builder = null): self <ide> { <ide> $result = $this->getEagerLoader() <ide> ->setMatching($assoc, $builder, [ <ide> public function applyOptions(array $options) <ide> * <ide> * @return \Cake\ORM\Query <ide> */ <del> public function cleanCopy() <add> public function cleanCopy(): Query <ide> { <ide> $clone = clone $this; <ide> $clone->setEagerLoader(clone $this->getEagerLoader()); <ide> public function count(): int <ide> * <ide> * @return int <ide> */ <del> protected function _performCount() <add> protected function _performCount(): int <ide> { <ide> $query = $this->cleanCopy(); <ide> $counter = $this->_counter; <ide> protected function _performCount() <ide> * @param callable|null $counter The counter value <ide> * @return $this <ide> */ <del> public function counter($counter) <add> public function counter(?callable $counter): self <ide> { <ide> $this->_counter = $counter; <ide> <ide> public function counter($counter) <ide> * @param bool $enable Use a boolean to set the hydration mode. <ide> * @return $this <ide> */ <del> public function enableHydration($enable = true) <add> public function enableHydration(bool $enable = true): self <ide> { <ide> $this->_dirty(); <ide> $this->_hydrate = (bool)$enable; <ide> public function enableHydration($enable = true) <ide> * <ide> * @return bool <ide> */ <del> public function isHydrationEnabled() <add> public function isHydrationEnabled(): bool <ide> { <ide> return $this->_hydrate; <ide> } <ide> public function isHydrationEnabled() <ide> * @return $this <ide> * @throws \RuntimeException When you attempt to cache a non-select query. <ide> */ <del> public function cache($key, $config = 'default') <add> public function cache(string $key, $config = 'default'): self <ide> { <ide> if ($this->_type !== 'select' && $this->_type !== null) { <ide> throw new RuntimeException('You cannot cache the results of non-select queries.'); <ide> public function all() <ide> * <ide> * @return void <ide> */ <del> public function triggerBeforeFind() <add> public function triggerBeforeFind(): void <ide> { <ide> if (!$this->_beforeFindFired && $this->_type === 'select') { <ide> $table = $this->getRepository(); <ide> public function triggerBeforeFind() <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function sql(?ValueBinder $binder = null) <add> public function sql(?ValueBinder $binder = null): string <ide> { <ide> $this->triggerBeforeFind(); <ide> <ide> public function sql(?ValueBinder $binder = null) <ide> * This will also setup the correct statement class in order to eager load deep <ide> * associations. <ide> * <del> * @return \Cake\ORM\ResultSet <add> * @return \Cake\Datasource\ResultSetInterface <ide> */ <del> protected function _execute() <add> protected function _execute(): ResultSetInterface <ide> { <ide> $this->triggerBeforeFind(); <ide> if ($this->_results) { <ide> protected function _execute() <ide> * @see \Cake\Database\Query::execute() <ide> * @return void <ide> */ <del> protected function _transformQuery() <add> protected function _transformQuery(): void <ide> { <ide> if (!$this->_dirty || $this->_type !== 'select') { <ide> return; <ide> protected function _transformQuery() <ide> * <ide> * @return void <ide> */ <del> protected function _addDefaultFields() <add> protected function _addDefaultFields(): void <ide> { <ide> $select = $this->clause('select'); <ide> $this->_hasFields = true; <ide> protected function _addDefaultFields() <ide> * <ide> * @return void <ide> */ <del> protected function _addDefaultSelectTypes() <add> protected function _addDefaultSelectTypes(): void <ide> { <ide> $typeMap = $this->getTypeMap()->getDefaults(); <ide> $select = $this->clause('select'); <ide> public function find($finder, array $options = []) <ide> * <ide> * @return void <ide> */ <del> protected function _dirty() <add> protected function _dirty(): void <ide> { <ide> $this->_results = null; <ide> $this->_resultsCount = null; <ide> public function delete($table = null) <ide> * @param array $types A map between columns & their datatypes. <ide> * @return $this <ide> */ <del> public function insert(array $columns, array $types = []) <add> public function insert(array $columns, array $types = []): self <ide> { <ide> $table = $this->getRepository()->getTable(); <ide> $this->into($table); <ide> public function __debugInfo() <ide> * <ide> * @return \Cake\Datasource\ResultSetInterface The data to convert to JSON. <ide> */ <del> public function jsonSerialize() <add> public function jsonSerialize(): ResultSetInterface <ide> { <ide> return $this->all(); <ide> } <ide> public function jsonSerialize() <ide> * @param bool $value Set true to enable, false to disable. <ide> * @return $this <ide> */ <del> public function enableAutoFields($value = true) <add> public function enableAutoFields(bool $value = true): self <ide> { <ide> $this->_autoFields = (bool)$value; <ide> <ide> public function enableAutoFields($value = true) <ide> * By default calling select() will disable auto-fields. You can re-enable <ide> * auto-fields with enableAutoFields(). <ide> * <del> * @return bool The current value. <add> * @return bool|null The current value. <ide> */ <del> public function isAutoFieldsEnabled() <add> public function isAutoFieldsEnabled(): ?bool <ide> { <ide> return $this->_autoFields; <ide> } <ide> public function isAutoFieldsEnabled() <ide> * @param \Traversable $result Original results <ide> * @return \Cake\Datasource\ResultSetInterface <ide> */ <del> protected function _decorateResults($result) <add> protected function _decorateResults(Traversable $result): ResultSetInterface <ide> { <ide> $result = $this->_applyDecorators($result); <ide> <ide><path>src/ORM/ResultSet.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> use Cake\Collection\Collection; <ide> use Cake\Collection\CollectionTrait; <ide> use Cake\Database\Exception; <add>use Cake\Database\StatementInterface; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\ResultSetInterface; <ide> use SplFixedArray; <ide> class ResultSet implements ResultSetInterface <ide> * @param \Cake\ORM\Query $query Query from where results come <ide> * @param \Cake\Database\StatementInterface $statement The statement to fetch from <ide> */ <del> public function __construct($query, $statement) <add> public function __construct(Query $query, StatementInterface $statement) <ide> { <ide> $repository = $query->getRepository(); <ide> $this->_statement = $statement; <ide> public function current() <ide> * <ide> * @return int <ide> */ <del> public function key() <add> public function key(): int <ide> { <ide> return $this->_index; <ide> } <ide> public function key() <ide> * <ide> * @return void <ide> */ <del> public function next() <add> public function next(): void <ide> { <ide> $this->_index++; <ide> } <ide> public function next() <ide> * @throws \Cake\Database\Exception <ide> * @return void <ide> */ <del> public function rewind() <add> public function rewind(): void <ide> { <ide> if ($this->_index === 0) { <ide> return; <ide> public function rewind() <ide> * <ide> * @return bool <ide> */ <del> public function valid() <add> public function valid(): bool <ide> { <ide> if ($this->_useBuffering) { <ide> $valid = $this->_index < $this->_count; <ide> public function first() <ide> * <ide> * @return string Serialized object <ide> */ <del> public function serialize() <add> public function serialize(): string <ide> { <ide> if (!$this->_useBuffering) { <ide> $msg = 'You cannot serialize an un-buffered ResultSet. Use Query::bufferResults() to get a buffered ResultSet.'; <ide> public function count(): int <ide> * @param \Cake\ORM\Query $query The query from where to derive the associations <ide> * @return void <ide> */ <del> protected function _calculateAssociationMap($query) <add> protected function _calculateAssociationMap(Query $query): void <ide> { <ide> $map = $query->getEagerLoader()->associationsMap($this->_defaultTable); <ide> $this->_matchingMap = (new Collection($map)) <ide> protected function _calculateAssociationMap($query) <ide> * @param \Cake\ORM\Query $query The query from where to derive the column map <ide> * @return void <ide> */ <del> protected function _calculateColumnMap($query) <add> protected function _calculateColumnMap(Query $query): void <ide> { <ide> $map = []; <ide> foreach ($query->clause('select') as $key => $field) { <ide> protected function _fetchResult() <ide> * Correctly nests results keys including those coming from associations <ide> * <ide> * @param array $row Array containing columns and values or false if there is no results <del> * @return array Results <add> * @return array|\Cake\Datasource\EntityInterface Results <ide> */ <del> protected function _groupResult($row) <add> protected function _groupResult(array $row) <ide> { <ide> $defaultAlias = $this->_defaultAlias; <ide> $results = $presentAliases = []; <ide><path>src/ORM/RulesChecker.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class RulesChecker extends BaseRulesChecker <ide> * also be an array of options. When an array, the 'message' key can be used to provide a message. <ide> * @return callable <ide> */ <del> public function isUnique(array $fields, $message = null) <add> public function isUnique(array $fields, $message = null): callable <ide> { <ide> $options = []; <ide> if (is_array($message)) { <ide> public function isUnique(array $fields, $message = null) <ide> * also be an array of options. When an array, the 'message' key can be used to provide a message. <ide> * @return callable <ide> */ <del> public function existsIn($field, $table, $message = null) <add> public function existsIn($field, $table, $message = null): callable <ide> { <ide> $options = []; <ide> if (is_array($message)) { <ide> public function existsIn($field, $table, $message = null) <ide> * @param string|null $message The error message to show in case the rule does not pass. <ide> * @return callable <ide> */ <del> public function validCount($field, $count = 0, $operator = '>', $message = null) <add> public function validCount(string $field, int $count = 0, string $operator = '>', ?string $message = null): callable <ide> { <ide> if (!$message) { <ide> if ($this->_useI18n) { <ide><path>src/ORM/SaveOptionsBuilder.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(Table $table, array $options = []) <ide> * @param array $array Options array. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function parseArrayOptions($array) <add> public function parseArrayOptions(array $array): SaveOptionsBuilder <ide> { <ide> foreach ($array as $key => $value) { <ide> $this->{$key}($value); <ide> public function parseArrayOptions($array) <ide> * @param string|array $associated String or array of associations. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function associated($associated) <add> public function associated($associated): SaveOptionsBuilder <ide> { <ide> $associated = $this->_normalizeAssociations($associated); <ide> $this->_associated($this->_table, $associated); <ide> public function associated($associated) <ide> * @param array $associations An associations array. <ide> * @return void <ide> */ <del> protected function _associated(Table $table, array $associations) <add> protected function _associated(Table $table, array $associations): void <ide> { <ide> foreach ($associations as $key => $associated) { <ide> if (is_int($key)) { <ide> protected function _associated(Table $table, array $associations) <ide> * @param string $association Association name. <ide> * @return void <ide> */ <del> protected function _checkAssociation(Table $table, $association) <add> protected function _checkAssociation(Table $table, string $association): void <ide> { <ide> if (!$table->associations()->has($association)) { <ide> throw new RuntimeException(sprintf('Table `%s` is not associated with `%s`', get_class($table), $association)); <ide> protected function _checkAssociation(Table $table, $association) <ide> * @param bool $guard Guard the properties or not. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function guard($guard) <add> public function guard(bool $guard): SaveOptionsBuilder <ide> { <ide> $this->_options['guard'] = (bool)$guard; <ide> <ide> public function guard($guard) <ide> * @param string $validate Name of the validation rule set to use. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function validate($validate) <add> public function validate(string $validate): SaveOptionsBuilder <ide> { <ide> $this->_table->getValidator($validate); <ide> $this->_options['validate'] = $validate; <ide> public function validate($validate) <ide> * @param bool $checkExisting Guard the properties or not. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function checkExisting($checkExisting) <add> public function checkExisting(bool $checkExisting): SaveOptionsBuilder <ide> { <ide> $this->_options['checkExisting'] = (bool)$checkExisting; <ide> <ide> public function checkExisting($checkExisting) <ide> * @param bool $checkRules Check the rules or not. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function checkRules($checkRules) <add> public function checkRules(bool $checkRules): SaveOptionsBuilder <ide> { <ide> $this->_options['checkRules'] = (bool)$checkRules; <ide> <ide> public function checkRules($checkRules) <ide> * @param bool $atomic Atomic or not. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function atomic($atomic) <add> public function atomic(bool $atomic): SaveOptionsBuilder <ide> { <ide> $this->_options['atomic'] = (bool)$atomic; <ide> <ide> public function atomic($atomic) <ide> /** <ide> * @return array <ide> */ <del> public function toArray() <add> public function toArray(): array <ide> { <ide> return $this->_options; <ide> } <ide> public function toArray() <ide> * @param mixed $value Option value. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function set($option, $value) <add> public function set(string $option, $value): SaveOptionsBuilder <ide> { <ide> if (method_exists($this, $option)) { <ide> return $this->{$option}($value); <ide><path>src/ORM/Table.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> use ArrayObject; <ide> use BadMethodCallException; <ide> use Cake\Core\App; <add>use Cake\Database\Connection; <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\TypeFactory; <ide> use Cake\Datasource\ConnectionInterface; <ide> class Table implements RepositoryInterface, EventListenerInterface, EventDispatc <ide> /** <ide> * Connection instance <ide> * <del> * @var \Cake\Database\Connection <add> * @var \Cake\Database\Connection|null <ide> */ <ide> protected $_connection; <ide> <ide> class Table implements RepositoryInterface, EventListenerInterface, EventDispatc <ide> /** <ide> * The name of the field that represents a human readable representation of a row <ide> * <del> * @var string <add> * @var string|array <ide> */ <ide> protected $_displayField; <ide> <ide> public function __construct(array $config = []) <ide> * @return string <ide> * @see \Cake\ORM\Locator\TableLocator::get() <ide> */ <del> public static function defaultConnectionName() <add> public static function defaultConnectionName(): string <ide> { <ide> return 'default'; <ide> } <ide> public static function defaultConnectionName() <ide> * @param array $config Configuration options passed to the constructor <ide> * @return void <ide> */ <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> } <ide> <ide> public function initialize(array $config) <ide> * @param string $table Table name. <ide> * @return $this <ide> */ <del> public function setTable($table) <add> public function setTable(string $table) <ide> { <ide> $this->_table = $table; <ide> <ide> public function setTable($table) <ide> * <ide> * @return string <ide> */ <del> public function getTable() <add> public function getTable(): string <ide> { <ide> if ($this->_table === null) { <ide> $table = namespaceSplit(get_class($this)); <ide> public function getAlias(): string <ide> * @param string $field The field to alias. <ide> * @return string The field prefixed with the table alias. <ide> */ <del> public function aliasField($field) <add> public function aliasField(string $field): string <ide> { <ide> if (strpos($field, '.') !== false) { <ide> return $field; <ide> public function aliasField($field) <ide> * @param string $registryAlias The key used to access this object. <ide> * @return $this <ide> */ <del> public function setRegistryAlias($registryAlias) <add> public function setRegistryAlias(string $registryAlias) <ide> { <ide> $this->_registryAlias = $registryAlias; <ide> <ide> public function setRegistryAlias($registryAlias) <ide> * <ide> * @return string <ide> */ <del> public function getRegistryAlias() <add> public function getRegistryAlias(): string <ide> { <ide> if ($this->_registryAlias === null) { <ide> $this->_registryAlias = $this->getAlias(); <ide> public function setConnection(ConnectionInterface $connection) <ide> /** <ide> * Returns the connection instance. <ide> * <del> * @return \Cake\Database\Connection <add> * @return \Cake\Database\Connection|null <ide> */ <del> public function getConnection() <add> public function getConnection(): ?Connection <ide> { <ide> return $this->_connection; <ide> } <ide> public function getConnection() <ide> * <ide> * @return \Cake\Database\Schema\TableSchema <ide> */ <del> public function getSchema() <add> public function getSchema(): TableSchema <ide> { <ide> if ($this->_schema === null) { <ide> $this->_schema = $this->_initializeSchema( <ide> public function setSchema($schema) <ide> * @param \Cake\Database\Schema\TableSchema $schema The table definition fetched from database. <ide> * @return \Cake\Database\Schema\TableSchema the altered schema <ide> */ <del> protected function _initializeSchema(TableSchema $schema) <add> protected function _initializeSchema(TableSchema $schema): TableSchema <ide> { <ide> return $schema; <ide> } <ide> public function getPrimaryKey() <ide> /** <ide> * Sets the display field. <ide> * <del> * @param string $key Name to be used as display field. <add> * @param string|array $fields Name to be used as display field. <ide> * @return $this <ide> */ <del> public function setDisplayField($key) <add> public function setDisplayField($field): self <ide> { <del> $this->_displayField = $key; <add> $this->_displayField = $field; <ide> <ide> return $this; <ide> } <ide> <ide> /** <ide> * Returns the display field. <ide> * <del> * @return string <add> * @return string|array <ide> */ <ide> public function getDisplayField() <ide> { <ide> public function getDisplayField() <ide> * <ide> * @return string <ide> */ <del> public function getEntityClass() <add> public function getEntityClass(): string <ide> { <ide> if (!$this->_entityClass) { <ide> $default = Entity::class; <ide> public function getEntityClass() <ide> * @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found <ide> * @return $this <ide> */ <del> public function setEntityClass($name) <add> public function setEntityClass(string $name): self <ide> { <ide> $class = App::className($name, 'Model/Entity'); <ide> if (!$class) { <ide> public function setEntityClass($name) <ide> * @throws \RuntimeException If a behavior is being reloaded. <ide> * @see \Cake\ORM\Behavior <ide> */ <del> public function addBehavior($name, array $options = []) <add> public function addBehavior(string $name, array $options = []): self <ide> { <ide> $this->_behaviors->load($name, $options); <ide> <ide> public function addBehavior($name, array $options = []) <ide> * @return $this <ide> * @throws \RuntimeException If a behavior is being reloaded. <ide> */ <del> public function addBehaviors(array $behaviors) <add> public function addBehaviors(array $behaviors): self <ide> { <ide> foreach ($behaviors as $name => $options) { <ide> if (is_int($name)) { <ide> public function addBehaviors(array $behaviors) <ide> * @return $this <ide> * @see \Cake\ORM\Behavior <ide> */ <del> public function removeBehavior($name) <add> public function removeBehavior(string $name) <ide> { <ide> $this->_behaviors->unload($name); <ide> <ide> public function removeBehavior($name) <ide> * <ide> * @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance. <ide> */ <del> public function behaviors() <add> public function behaviors(): BehaviorRegistry <ide> { <ide> return $this->_behaviors; <ide> } <ide> public function behaviors() <ide> * @return \Cake\ORM\Behavior <ide> * @throws \InvalidArgumentException If the behavior does not exist. <ide> */ <del> public function getBehavior($name) <add> public function getBehavior(string $name): Behavior <ide> { <ide> /** @var \Cake\ORM\Behavior $behavior */ <ide> $behavior = $this->_behaviors->get($name); <ide> public function getBehavior($name) <ide> * @param string $name The behavior alias to check. <ide> * @return bool Whether or not the behavior exists. <ide> */ <del> public function hasBehavior($name) <add> public function hasBehavior(string $name): bool <ide> { <ide> return $this->_behaviors->has($name); <ide> } <ide> public function hasBehavior($name) <ide> * @return \Cake\ORM\Association The association. <ide> * @throws \InvalidArgumentException <ide> */ <del> public function getAssociation($name) <add> public function getAssociation(string $name): Association <ide> { <ide> $association = $this->findAssociation($name); <ide> if (!$association) { <ide> public function getAssociation($name) <ide> * @param string $name The alias used for the association. <ide> * @return bool <ide> */ <del> public function hasAssociation($name) <add> public function hasAssociation(string $name): bool <ide> { <ide> return $this->findAssociation($name) !== null; <ide> } <ide> public function hasAssociation($name) <ide> * @param string $name The alias used for the association. <ide> * @return \Cake\ORM\Association|null Either the association or null. <ide> */ <del> protected function findAssociation($name) <add> protected function findAssociation(string $name): ?Association <ide> { <ide> if (strpos($name, '.') === false) { <ide> return $this->_associations->get($name); <ide> protected function findAssociation($name) <ide> * <ide> * @return \Cake\ORM\AssociationCollection|\Cake\ORM\Association[] The collection of association objects. <ide> */ <del> public function associations() <add> public function associations(): iterable <ide> { <ide> return $this->_associations; <ide> } <ide> public function associations() <ide> * @see \Cake\ORM\Table::hasMany() <ide> * @see \Cake\ORM\Table::belongsToMany() <ide> */ <del> public function addAssociations(array $params) <add> public function addAssociations(array $params): self <ide> { <ide> foreach ($params as $assocType => $tables) { <ide> foreach ($tables as $associated => $options) { <ide> public function addAssociations(array $params) <ide> * @param array $options list of options to configure the association definition <ide> * @return \Cake\ORM\Association\BelongsTo <ide> */ <del> public function belongsTo($associated, array $options = []) <add> public function belongsTo(string $associated, array $options = []): BelongsTo <ide> { <ide> $options += ['sourceTable' => $this]; <ide> <ide> public function belongsTo($associated, array $options = []) <ide> * @param array $options list of options to configure the association definition <ide> * @return \Cake\ORM\Association\HasOne <ide> */ <del> public function hasOne($associated, array $options = []) <add> public function hasOne(string $associated, array $options = []): HasOne <ide> { <ide> $options += ['sourceTable' => $this]; <ide> <ide> public function hasOne($associated, array $options = []) <ide> * @param array $options list of options to configure the association definition <ide> * @return \Cake\ORM\Association\HasMany <ide> */ <del> public function hasMany($associated, array $options = []) <add> public function hasMany(string $associated, array $options = []): HasMany <ide> { <ide> $options += ['sourceTable' => $this]; <ide> <ide> public function hasMany($associated, array $options = []) <ide> * @param array $options list of options to configure the association definition <ide> * @return \Cake\ORM\Association\BelongsToMany <ide> */ <del> public function belongsToMany($associated, array $options = []) <add> public function belongsToMany(string $associated, array $options = []): BelongsToMany <ide> { <ide> $options += ['sourceTable' => $this]; <ide> <ide> public function belongsToMany($associated, array $options = []) <ide> * @param array|\ArrayAccess $options An array that will be passed to Query::applyOptions() <ide> * @return \Cake\ORM\Query The query builder <ide> */ <del> public function find($type = 'all', $options = []) <add> public function find(string $type = 'all', $options = []): Query <ide> { <ide> $query = $this->query(); <ide> $query->select(); <ide> public function find($type = 'all', $options = []) <ide> * @param array $options The options to use for the find <ide> * @return \Cake\ORM\Query The query builder <ide> */ <del> public function findAll(Query $query, array $options) <add> public function findAll(Query $query, array $options): Query <ide> { <ide> return $query; <ide> } <ide> public function findAll(Query $query, array $options) <ide> * @param array $options The options for the find <ide> * @return \Cake\ORM\Query The query builder <ide> */ <del> public function findList(Query $query, array $options) <add> public function findList(Query $query, array $options): Query <ide> { <ide> $options += [ <ide> 'keyField' => $this->getPrimaryKey(), <ide> public function findList(Query $query, array $options) <ide> * @param array $options The options to find with <ide> * @return \Cake\ORM\Query The query builder <ide> */ <del> public function findThreaded(Query $query, array $options) <add> public function findThreaded(Query $query, array $options): Query <ide> { <ide> $options += [ <ide> 'keyField' => $this->getPrimaryKey(), <ide> public function findThreaded(Query $query, array $options) <ide> * the associated value <ide> * @return array <ide> */ <del> protected function _setFieldMatchers($options, $keys) <add> protected function _setFieldMatchers(array $options, array $keys): array <ide> { <ide> foreach ($keys as $field) { <ide> if (!is_array($options[$field])) { <ide> protected function _setFieldMatchers($options, $keys) <ide> * @throws \Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an <ide> * incorrect number of elements. <ide> */ <del> public function get($primaryKey, $options = []) <add> public function get($primaryKey, $options = []): EntityInterface <ide> { <ide> $key = (array)$this->getPrimaryKey(); <ide> $alias = $this->getAlias(); <ide> public function get($primaryKey, $options = []) <ide> * @param bool $atomic Whether to execute the worker inside a database transaction. <ide> * @return mixed <ide> */ <del> protected function _executeTransaction(callable $worker, $atomic = true) <add> protected function _executeTransaction(callable $worker, bool $atomic = true) <ide> { <ide> if ($atomic) { <ide> return $this->getConnection()->transactional(function () use ($worker) { <ide> protected function _executeTransaction(callable $worker, $atomic = true) <ide> * @param bool $primary True if a primary was used. <ide> * @return bool Returns true if a transaction was committed. <ide> */ <del> protected function _transactionCommitted($atomic, $primary) <add> protected function _transactionCommitted(bool $atomic, bool $primary): bool <ide> { <ide> return !$this->getConnection()->inTransaction() && ($atomic || (!$atomic && $primary)); <ide> } <ide> protected function _transactionCommitted($atomic, $primary) <ide> * @param array $options The options to use when saving. <ide> * @return \Cake\Datasource\EntityInterface An entity. <ide> */ <del> public function findOrCreate($search, ?callable $callback = null, $options = []) <add> public function findOrCreate($search, ?callable $callback = null, $options = []): EntityInterface <ide> { <ide> $options = new ArrayObject($options + [ <ide> 'atomic' => true, <ide> public function findOrCreate($search, ?callable $callback = null, $options = []) <ide> * @param array $options The options to use when saving. <ide> * @return \Cake\Datasource\EntityInterface An entity. <ide> */ <del> protected function _processFindOrCreate($search, ?callable $callback = null, $options = []) <add> protected function _processFindOrCreate($search, ?callable $callback = null, $options = []): EntityInterface <ide> { <ide> if (is_callable($search)) { <ide> $query = $this->find(); <ide> protected function _processFindOrCreate($search, ?callable $callback = null, $op <ide> * @param array|\Cake\ORM\Query|string $search The criteria to find existing records by. <ide> * @return \Cake\ORM\Query <ide> */ <del> protected function _getFindOrCreateQuery($search) <add> protected function _getFindOrCreateQuery($search): Query <ide> { <ide> if ($search instanceof Query) { <ide> return $search; <ide> protected function _getFindOrCreateQuery($search) <ide> * <ide> * @return \Cake\ORM\Query <ide> */ <del> public function query() <add> public function query(): Query <ide> { <ide> return new Query($this->getConnection(), $this); <ide> } <ide> public function save(EntityInterface $entity, $options = []) <ide> * @throws \Cake\ORM\Exception\PersistenceFailedException When the entity couldn't be saved <ide> * @see \Cake\ORM\Table::save() <ide> */ <del> public function saveOrFail(EntityInterface $entity, $options = []) <add> public function saveOrFail(EntityInterface $entity, $options = []): EntityInterface <ide> { <ide> $saved = $this->save($entity, $options); <ide> if ($saved === false) { <ide> public function saveOrFail(EntityInterface $entity, $options = []) <ide> * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction <ide> * is aborted in the afterSave event. <ide> */ <del> protected function _processSave($entity, $options) <add> protected function _processSave(EntityInterface $entity, ArrayObject $options) <ide> { <ide> $primaryColumns = (array)$this->getPrimaryKey(); <ide> <ide> protected function _processSave($entity, $options) <ide> * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction <ide> * is aborted in the afterSave event. <ide> */ <del> protected function _onSaveSuccess($entity, $options) <add> protected function _onSaveSuccess(EntityInterface $entity, ArrayObject $options): bool <ide> { <ide> $success = $this->_associations->saveChildren( <ide> $this, <ide> protected function _onSaveSuccess($entity, $options) <ide> * @throws \RuntimeException if not all the primary keys where supplied or could <ide> * be generated when the table has composite primary keys. Or when the table has no primary key. <ide> */ <del> protected function _insert($entity, $data) <add> protected function _insert(EntityInterface $entity, array $data) <ide> { <ide> $primary = (array)$this->getPrimaryKey(); <ide> if (empty($primary)) { <ide> protected function _insert($entity, $data) <ide> * @param array $primary The primary key columns to get a new ID for. <ide> * @return null|string|array Either null or the primary key value or a list of primary key values. <ide> */ <del> protected function _newId($primary) <add> protected function _newId(array $primary) <ide> { <ide> if (!$primary || count((array)$primary) > 1) { <ide> return null; <ide> protected function _newId($primary) <ide> * @return \Cake\Datasource\EntityInterface|bool <ide> * @throws \InvalidArgumentException When primary key data is missing. <ide> */ <del> protected function _update($entity, $data) <add> protected function _update(EntityInterface $entity, array $data) <ide> { <ide> $primaryColumns = (array)$this->getPrimaryKey(); <ide> $primaryKey = $entity->extract($primaryColumns); <ide> protected function _update($entity, $data) <ide> * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity. <ide> * @return bool|\Cake\Datasource\EntityInterface[]|\Cake\ORM\ResultSet False on failure, entities list on success. <ide> */ <del> public function saveMany($entities, $options = []) <add> public function saveMany(iterable $entities, $options = []) <ide> { <ide> $isNew = []; <del> $cleanup = function ($entities) use (&$isNew) { <add> $cleanup = function ($entities) use (&$isNew): void { <ide> foreach ($entities as $key => $entity) { <ide> if (isset($isNew[$key]) && $isNew[$key]) { <ide> $entity->unsetProperty($this->getPrimaryKey()); <ide> public function delete(EntityInterface $entity, $options = []): bool <ide> * @throws \Cake\ORM\Exception\PersistenceFailedException <ide> * @see \Cake\ORM\Table::delete() <ide> */ <del> public function deleteOrFail(EntityInterface $entity, $options = []) <add> public function deleteOrFail(EntityInterface $entity, $options = []): bool <ide> { <ide> $deleted = $this->delete($entity, $options); <ide> if ($deleted === false) { <ide> public function deleteOrFail(EntityInterface $entity, $options = []) <ide> * passed entity <ide> * @return bool success <ide> */ <del> protected function _processDelete($entity, $options) <add> protected function _processDelete(EntityInterface $entity, ArrayObject $options): bool <ide> { <ide> if ($entity->isNew()) { <ide> return false; <ide> protected function _processDelete($entity, $options) <ide> * <ide> * @return bool <ide> */ <del> public function hasFinder($type) <add> public function hasFinder(string $type): bool <ide> { <ide> $finder = 'find' . $type; <ide> <ide> public function hasFinder($type) <ide> * @return \Cake\ORM\Query <ide> * @throws \BadMethodCallException <ide> */ <del> public function callFinder($type, Query $query, array $options = []) <add> public function callFinder(string $type, Query $query, array $options = []): Query <ide> { <ide> $query->applyOptions($options); <ide> $options = $query->getOptions(); <ide> public function callFinder($type, Query $query, array $options = []) <ide> * @throws \BadMethodCallException when there are missing arguments, or when <ide> * and & or are combined. <ide> */ <del> protected function _dynamicFinder($method, $args) <add> protected function _dynamicFinder(string $method, array $args) <ide> { <ide> $method = Inflector::underscore($method); <ide> preg_match('/^find_([\w]+)_by_/', $method, $matches); <ide> public function __isset($property) <ide> * @return \Cake\ORM\Marshaller <ide> * @see \Cake\ORM\Marshaller <ide> */ <del> public function marshaller() <add> public function marshaller(): Marshaller <ide> { <ide> return new Marshaller($this); <ide> } <ide> public function marshaller() <ide> * You can use the `Model.beforeMarshal` event to modify request data <ide> * before it is converted into entities. <ide> */ <del> public function newEntity(?array $data = null, array $options = []) <add> public function newEntity(?array $data = null, array $options = []): EntityInterface <ide> { <ide> if ($data === null) { <ide> $class = $this->getEntityClass(); <ide> public function newEntity(?array $data = null, array $options = []) <ide> * You can use the `Model.beforeMarshal` event to modify request data <ide> * before it is converted into entities. <ide> */ <del> public function newEntities(array $data, array $options = []) <add> public function newEntities(array $data, array $options = []): array <ide> { <ide> if (!isset($options['associated'])) { <ide> $options['associated'] = $this->_associations->keys(); <ide> public function newEntities(array $data, array $options = []) <ide> * property will not be marked as dirty. This is an optimization to prevent unnecessary field <ide> * updates when persisting entities. <ide> */ <del> public function patchEntity(EntityInterface $entity, array $data, array $options = []) <add> public function patchEntity(EntityInterface $entity, array $data, array $options = []): EntityInterface <ide> { <ide> if (!isset($options['associated'])) { <ide> $options['associated'] = $this->_associations->keys(); <ide> public function patchEntity(EntityInterface $entity, array $data, array $options <ide> * You can use the `Model.beforeMarshal` event to modify request data <ide> * before it is converted into entities. <ide> */ <del> public function patchEntities($entities, array $data, array $options = []) <add> public function patchEntities($entities, array $data, array $options = []): array <ide> { <ide> if (!isset($options['associated'])) { <ide> $options['associated'] = $this->_associations->keys(); <ide> public function patchEntities($entities, array $data, array $options = []) <ide> * @param array|null $context Either the validation context or null. <ide> * @return bool True if the value is unique, or false if a non-scalar, non-unique value was given. <ide> */ <del> public function validateUnique($value, array $options, ?array $context = null) <add> public function validateUnique($value, array $options, ?array $context = null): bool <ide> { <ide> if ($context === null) { <ide> $context = $options; <ide> public function implementedEvents(): array <ide> * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. <ide> * @return \Cake\ORM\RulesChecker <ide> */ <del> public function buildRules(RulesChecker $rules) <add> public function buildRules(RulesChecker $rules): RulesChecker <ide> { <ide> return $rules; <ide> } <ide> public function buildRules(RulesChecker $rules) <ide> * @param array $options Options to parse by the builder. <ide> * @return \Cake\ORM\SaveOptionsBuilder <ide> */ <del> public function getSaveOptionsBuilder(array $options = []) <add> public function getSaveOptionsBuilder(array $options = []): SaveOptionsBuilder <ide> { <ide> return new SaveOptionsBuilder($this, $options); <ide> } <ide> public function loadInto($entities, array $contain) <ide> /** <ide> * {@inheritDoc} <ide> */ <del> protected function validationMethodExists($method) <add> protected function validationMethodExists(string $method): bool <ide> { <ide> return method_exists($this, $method) || $this->behaviors()->hasMethod($method); <ide> } <ide><path>src/ORM/TableRegistry.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class TableRegistry <ide> * @return \Cake\ORM\Locator\LocatorInterface <ide> * @deprecated 3.5.0 Use getTableLocator()/setTableLocator() instead. <ide> */ <del> public static function locator(?LocatorInterface $locator = null) <add> public static function locator(?LocatorInterface $locator = null): LocatorInterface <ide> { <ide> deprecationWarning( <ide> 'TableRegistry::locator() is deprecated. ' . <ide> public static function locator(?LocatorInterface $locator = null) <ide> * <ide> * @return \Cake\ORM\Locator\LocatorInterface <ide> */ <del> public static function getTableLocator() <add> public static function getTableLocator(): LocatorInterface <ide> { <ide> if (!static::$_locator) { <ide> static::$_locator = new static::$_defaultLocatorClass(); <ide> public static function getTableLocator() <ide> * @param \Cake\ORM\Locator\LocatorInterface $tableLocator Instance of a locator to use. <ide> * @return void <ide> */ <del> public static function setTableLocator(LocatorInterface $tableLocator) <add> public static function setTableLocator(LocatorInterface $tableLocator): void <ide> { <ide> static::$_locator = $tableLocator; <ide> } <ide> public static function setTableLocator(LocatorInterface $tableLocator) <ide> * @return array The config data. <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::getConfig()/setConfig() instead. <ide> */ <del> public static function config($alias = null, $options = null) <add> public static function config(?string $alias = null, ?array $options = null): array <ide> { <ide> deprecationWarning( <ide> 'TableRegistry::config() is deprecated. ' . <ide> public static function config($alias = null, $options = null) <ide> * @return \Cake\ORM\Table <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead. <ide> */ <del> public static function get($alias, array $options = []) <add> public static function get(string $alias, array $options = []): Table <ide> { <ide> return static::getTableLocator()->get($alias, $options); <ide> } <ide> public static function get($alias, array $options = []) <ide> * @return bool <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::exists() instead. <ide> */ <del> public static function exists($alias) <add> public static function exists(string $alias): bool <ide> { <ide> return static::getTableLocator()->exists($alias); <ide> } <ide> public static function exists($alias) <ide> * @return \Cake\ORM\Table <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::set() instead. <ide> */ <del> public static function set($alias, Table $object) <add> public static function set(string $alias, Table $object): Table <ide> { <ide> return static::getTableLocator()->set($alias, $object); <ide> } <ide> public static function set($alias, Table $object) <ide> * @return void <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::remove() instead. <ide> */ <del> public static function remove($alias) <add> public static function remove(string $alias): void <ide> { <ide> static::getTableLocator()->remove($alias); <ide> } <ide> public static function remove($alias) <ide> * @return void <ide> * @deprecated 3.6.0 Use \Cake\ORM\Locator\TableLocator::clear() instead. <ide> */ <del> public static function clear() <add> public static function clear(): void <ide> { <ide> static::getTableLocator()->clear(); <ide> } <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> */ <ide> class TestTable extends Table <ide> { <del> public function initialize(array $config = []) <add> public function initialize(array $config = []): void <ide> { <ide> $this->setSchema(['id' => ['type' => 'integer']]); <ide> } <ide><path>tests/TestCase/ORM/CompositeKeysTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\Database\Connection; <ide> use Cake\Database\Driver\Sqlite; <ide> use Cake\Database\Driver\Sqlserver; <ide> use Cake\Datasource\ConnectionManager; <ide> public function testFindThreadedCompositeKeys() <ide> $table = $this->getTableLocator()->get('SiteAuthors'); <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->setMethods(['_addDefaultFields', 'execute']) <del> ->setConstructorArgs([null, $table]) <add> ->setConstructorArgs([$table->getConnection(), $table]) <ide> ->getMock(); <ide> <ide> $items = new \Cake\Datasource\ResultSetDecorator([ <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> class GreedyCommentsTable extends Table <ide> * @param array $config Config data. <ide> * @return void <ide> */ <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->setTable('comments'); <ide> $this->setAlias('Comments'); <ide> public function initialize(array $config) <ide> * @param array $options find options <ide> * @return object <ide> */ <del> public function find($type = 'all', $options = []) <add> public function find(string $type = 'all', $options = []) <ide> { <ide> if (empty($options['conditions'])) { <ide> $options['conditions'] = []; <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testCollectionProxy($method, $arg, $return) <ide> ->getMock(); <ide> $query->select(); <ide> $resultSet = $this->getMockbuilder('Cake\ORM\ResultSet') <del> ->setConstructorArgs([$query, null]) <add> ->setConstructorArgs([$query, $this->getMockBuilder(StatementInterface::class)->getMock()]) <ide> ->getMock(); <ide> $query->expects($this->once()) <ide> ->method('all') <ide> public function testCacheReadIntegration() <ide> ->setConstructorArgs([$this->connection, $this->table]) <ide> ->getMock(); <ide> $resultSet = $this->getMockBuilder('Cake\ORM\ResultSet') <del> ->setConstructorArgs([$query, null]) <add> ->setConstructorArgs([$query, $this->getMockBuilder(StatementInterface::class)->getMock()]) <ide> ->getMock(); <ide> <ide> $query->expects($this->never()) <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testAfterSaveNotCalled() <ide> ->getMock(); <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->setMethods(['execute', 'addDefaultTypes']) <del> ->setConstructorArgs([null, $table]) <add> ->setConstructorArgs([$this->connection, $table]) <ide> ->getMock(); <ide> $statement = $this->getMockBuilder('Cake\Database\Statement\StatementDecorator')->getMock(); <ide> $data = new Entity([ <ide> public function testAtomicSaveRollback() <ide> ->getMock(); <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->setMethods(['execute', 'addDefaultTypes']) <del> ->setConstructorArgs([null, $table]) <add> ->setConstructorArgs([$connection, $table]) <ide> ->getMock(); <ide> $table->expects($this->any())->method('getConnection') <ide> ->will($this->returnValue($connection)); <ide> public function testAtomicSaveRollbackOnFailure() <ide> ->getMock(); <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->setMethods(['execute', 'addDefaultTypes']) <del> ->setConstructorArgs([null, $table]) <add> ->setConstructorArgs([$connection, $table]) <ide> ->getMock(); <ide> <ide> $table->expects($this->any())->method('getConnection') <ide> public function testSaveUpdatePrimaryKeyNotModified() <ide> <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->setMethods(['execute', 'addDefaultTypes', 'set']) <del> ->setConstructorArgs([null, $table]) <add> ->setConstructorArgs([$this->connection, $table]) <ide> ->getMock(); <ide> <ide> $table->expects($this->once())->method('query') <ide><path>tests/test_app/Plugin/TestPlugin/src/Model/Table/TestPluginCommentsTable.php <ide> */ <ide> class TestPluginCommentsTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->setTable('test_plugin_comments'); <ide> } <ide><path>tests/test_app/TestApp/Model/Table/ArticlesTable.php <ide> */ <ide> class ArticlesTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->belongsTo('Authors'); <ide> $this->belongsToMany('Tags'); <ide><path>tests/test_app/TestApp/Model/Table/ArticlesTagsTable.php <ide> */ <ide> class ArticlesTagsTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->belongsTo('Articles'); <ide> $this->belongsTo('Tags'); <ide><path>tests/test_app/TestApp/Model/Table/AuthorsTable.php <ide> */ <ide> class AuthorsTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->hasMany('articles'); <ide> } <ide><path>tests/test_app/TestApp/Model/Table/I18nTable.php <ide> */ <ide> class I18nTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->setTable('custom_i18n_table'); <ide> } <ide> <del> public static function defaultConnectionName() <add> public static function defaultConnectionName(): string <ide> { <ide> return 'custom_i18n_datasource'; <ide> } <ide><path>tests/test_app/TestApp/Model/Table/PaginatorPostsTable.php <ide> class PaginatorPostsTable extends Table <ide> * <ide> * @return void <ide> */ <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->setTable('posts'); <ide> $this->belongsTo('PaginatorAuthor', [ <ide><path>tests/test_app/TestApp/Model/Table/TagsTable.php <ide> */ <ide> class TagsTable extends Table <ide> { <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->belongsTo('Authors'); <ide> $this->belongsToMany('Articles');
31
Python
Python
fix broken ci
3d0e16d94dd8fd9ecaccbc6f0e616107415cb7d4
<ide><path>tests/providers/airbyte/hooks/test_airbyte.py <ide> def test_wait_for_job_cancelled(self, mock_get_job): <ide> <ide> @requests_mock.mock() <ide> def test_connection_success(self, m): <del> m.get(self.health_endpoint, status_code=200,) <add> m.get( <add> self.health_endpoint, <add> status_code=200, <add> ) <ide> <ide> status, msg = self.hook.test_connection() <ide> assert status is True
1
Python
Python
add roll function from ticket #293
099f140d97c07671497e5883ce2be9fcac62a3a1
<ide><path>numpy/core/numeric.py <ide> 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', <ide> 'isfortran', 'empty_like', 'zeros_like', <ide> 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', <del> 'alterdot', 'restoredot', 'rollaxis', 'cross', 'tensordot', <add> 'alterdot', 'restoredot', 'roll', 'rollaxis', 'cross', 'tensordot', <ide> 'array2string', 'get_printoptions', 'set_printoptions', <ide> 'array_repr', 'array_str', 'set_string_function', <ide> 'little_endian', 'require', <ide> def tensordot(a, b, axes=2): <ide> res = dot(at, bt) <ide> return res.reshape(olda + oldb) <ide> <add>def roll(a, shift, axis=None): <add> """Roll the elements in the array by 'shift' positions along <add> the given axis. <add> """ <add> a = asanyarray(a) <add> if axis is None: <add> n = a.size <add> reshape=1 <add> else: <add> n = a.shape[axis] <add> reshape=0 <add> shift %= n <add> indexes = concatenate((arange(n-shift,n),arange(n-shift))) <add> res = a.take(indexes, axis) <add> if reshape: <add> return res.reshape(a.shape) <add> else: <add> return res <add> <ide> def rollaxis(a, axis, start=0): <ide> """Return transposed array so that axis is rolled before start. <ide> <ide><path>numpy/lib/shape_base.py <ide> __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack', <ide> 'column_stack','row_stack', 'dstack','array_split','split','hsplit', <del> 'vsplit','dsplit','apply_over_axes','expand_dims', <add> 'vsplit','dsplit','apply_over_axes','expand_dims', <ide> 'apply_along_axis', 'kron', 'tile', 'get_array_wrap'] <ide> <ide> import numpy.core.numeric as _nx
2
PHP
PHP
fix assertions
06118cac748d9465da4e398dd4d16c2045760c27
<ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testServiceProvidersAreCorrectlyRegistered() <ide> $app = new Application; <ide> $app->register($provider); <ide> <del> $this->assertTrue(in_array($class, $app->getLoadedProviders())); <add> $this->assertArrayHasKey($class, $app->getLoadedProviders()); <ide> } <ide> <ide> public function testClassesAreBoundWhenServiceProviderIsRegistered() <ide> public function testClassesAreBoundWhenServiceProviderIsRegistered() <ide> $provider = new ServiceProviderForTestingThree($app); <ide> $app->register($provider); <ide> <del> $this->assertTrue(in_array(get_class($provider), $app->getLoadedProviders())); <add> $this->assertArrayHasKey(get_class($provider), $app->getLoadedProviders()); <ide> <ide> $this->assertInstanceOf(ConcreteClass::class, $app->make(AbstractClass::class)); <ide> } <ide> public function testSingletonsAreCreatedWhenServiceProviderIsRegistered() <ide> $provider = new ServiceProviderForTestingThree($app); <ide> $app->register($provider); <ide> <del> $this->assertTrue(in_array(get_class($provider), $app->getLoadedProviders())); <add> $this->assertArrayHasKey(get_class($provider), $app->getLoadedProviders()); <ide> <ide> $instance = $app->make(AbstractClass::class); <ide> <ide> public function testServiceProvidersAreCorrectlyRegisteredWhenRegisterMethodIsNo <ide> $app = new Application; <ide> $app->register($provider); <ide> <del> $this->assertTrue(in_array($class, $app->getLoadedProviders())); <add> $this->assertArrayHasKey($class, $app->getLoadedProviders()); <ide> } <ide> <ide> public function testDeferredServicesMarkedAsBound()
1
Text
Text
add changelog entry for
b6b088429c945b5c0c213fcdb9b4f6658faf686a
<ide><path>actionpack/CHANGELOG.md <add>* Fix regression where a gzip file response would have a Content-type, <add> even when it was a 304 status code. <add> <add> See #19271. <add> <add> *Kohei Suzuki* <add> <ide> * Fix handling of empty X_FORWARDED_HOST header in raw_host_with_port <ide> <ide> Previously, an empty X_FORWARDED_HOST header would cause
1
Javascript
Javascript
add noop appendchild to outletview
3605c774d409b309e8e75aa70199ca431dee0b4c
<ide><path>packages/ember-glimmer/lib/ember-routing-view/index.js <ide> export class OutletView { <ide> } <ide> } <ide> <add> appendChild() { } <add> <ide> rerender() { <ide> if (this._renderResult) { this.renderer.rerender(this); } <ide> }
1
Javascript
Javascript
drop dead code
fda788458e8d40454c343a3ccf34f05e7a98bf69
<ide><path>packages/ember-routing/lib/system/router.js <ide> var EmberRouter = EmberObject.extend(Evented, { <ide> } <ide> if (!this._toplevelView) { <ide> var OutletView = this.container.lookupFactory('view:-outlet'); <del> this._toplevelView = OutletView.create({ _isTopLevel: true }); <add> this._toplevelView = OutletView.create(); <ide> var instance = this.container.lookup('-application-instance:main'); <ide> instance.didCreateRootView(this._toplevelView); <ide> }
1
Text
Text
introduce action creators in redux-actions
782c5ba553b206b79f450cc57c6544c6c8cd6b74
<ide><path>guide/english/redux/redux-actions/index.md <ide> We can send these actions to the store by using <ide> store.dispatch(action) <ide> ``` <ide> <add>like so <add>```javascript <add>store.dispatch({ <add> type: ADD_ITEM, <add> text: 'This is the first item' <add>}) <add>``` <add>In real world apps it is often better to use functions aptly called Action Creators that accept a payload and return the action object, making them reusable. <add>```javascript <add>function addItem(text) { <add> return { <add> type: ADD_ITEM, <add> text <add> } <add>} <add> <add>store.dispatch(addItem('This is the second item')) <add>``` <add> <ide> An application can have different sorts of events happening at a time and these actions help describe these events. Without these actions there is no way to change the state of the application. <ide> <ide> ## Action Creators
1
Ruby
Ruby
use options from previous installs
ec1c7aaa38d7a41ac872f27bb67fc855721346d9
<ide><path>Library/Homebrew/formula_installer.rb <ide> def filtered_args <ide> # Did the user actually pass the formula this installer is considering on <ide> # the command line? <ide> def explicitly_requested?; ARGV.formulae.include? f end <add> previous_install = Tab.for_formula f <ide> <ide> args = ARGV.clone <del> args.uniq! # Just in case someone was playing around... <add> args.concat previous_install.used_options <add> args.uniq! # Just in case some dupes were added <ide> <ide> %w[--HEAD --verbose -v --debug -d --interactive -i].each {|f| args.delete f} unless explicitly_requested? <ide> <ide><path>Library/Homebrew/tab.rb <ide> def self.for_install f, args <ide> :tabfile => f.prefix + 'INSTALL_RECEIPT.json' <ide> end <ide> <add> def self.from_file path <add> tab = Tab.new MultiJson.decode(open(path).read) <add> tab.tabfile = path <add> <add> return tab <add> end <add> <add> def self.for_formula f <add> f = Formula.factory f unless f.kind_of? Formula <add> path = HOMEBREW_REPOSITORY + 'Library' + 'LinkedKegs' + f.name + 'INSTALL_RECEIPT.json' <add> <add> if path.exist? <add> self.from_file path <add> else <add> # Really should bail out with an error if a formula was not installed <add> # with a Tab. However, there will be lots of legacy installs that have no <add> # receipt---so we fabricate one that claims the formula was installed with <add> # no options. <add> # <add> # TODO: <add> # This isn't the best behavior---perhaps a future version of Homebrew can <add> # treat missing Tabs as errors. <add> Tab.new :used_options => [], <add> :unused_options => f.options.map { |o, _| o} <add> end <add> end <add> <add> def installed_with? opt <add> used_options.include? opt <add> end <add> <add> def options <add> used_options + unused_options <add> end <add> <ide> def to_json <ide> MultiJson.encode({ <ide> :used_options => used_options,
2
Javascript
Javascript
fix overwrite for this._prompt
7166b55015261de8ab69758320f3d9159b3eaadd
<ide><path>lib/readline.js <ide> function Interface(input, output, completer, terminal) { <ide> } <ide> <ide> this._sawReturn = false; <add> this._defaultPrompt = '> '; <ide> <ide> EventEmitter.call(this); <ide> <ide> function Interface(input, output, completer, terminal) { <ide> callback(null, completer(v)); <ide> }; <ide> <del> this.setPrompt('> '); <add> this.setDefaultPrompt(); <ide> <ide> this.terminal = !!terminal; <ide> <ide> Interface.prototype.setPrompt = function(prompt) { <ide> this._prompt = prompt; <ide> }; <ide> <add>Interface.prototype.setDefaultPrompt = function(prompt) { <add> if (!util.isUndefined(prompt)) <add> this._defaultPrompt = prompt; <add> this._prompt = this._defaultPrompt; <add>}; <ide> <ide> Interface.prototype._setRawMode = function(mode) { <ide> if (util.isFunction(this.input.setRawMode)) { <ide><path>lib/repl.js <ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { <ide> options.terminal <ide> ]); <ide> <del> self.setPrompt(!util.isUndefined(prompt) ? prompt : '> '); <add> self.setDefaultPrompt(prompt); <ide> <ide> this.commands = {}; <ide> defineDefaultCommands(this); <ide> REPLServer.prototype.resetContext = function() { <ide> }; <ide> <ide> REPLServer.prototype.displayPrompt = function(preserveCursor) { <del> var initial = this._prompt; <del> var prompt = initial; <add> var prompt = this._prompt; <ide> if (this.bufferedCommand.length) { <ide> prompt = '...'; <ide> var levelInd = new Array(this.lines.level.length).join('..'); <ide> prompt += levelInd + ' '; <add> this.setPrompt(prompt); <add> } else { <add> this.setDefaultPrompt(); <ide> } <del> this.setPrompt(prompt); <ide> this.prompt(preserveCursor); <del> this.setPrompt(initial); <ide> }; <ide> <ide> // A stream to push an array into a REPL <ide><path>test/simple/test-repl.js <ide> var net = require('net'), <ide> 'node repl, in your normal shell.\n' + <ide> '(Press Control-D to exit.)\n', <ide> expect_npm = prompt_npm + prompt_unix, <del> server_tcp, server_unix, client_tcp, client_unix, timer; <add> server_tcp, server_unix, client_tcp, client_unix, timer, <add> repl_unix; <ide> <ide> <ide> // absolute path to test/fixtures/a.js <ide> function error_test() { <ide> } else if (read_buffer.indexOf(prompt_multiline) !== -1) { <ide> // Check that you meant to send a multiline test <ide> assert.strictEqual(prompt_multiline, client_unix.expect); <add> assert.equal(repl_unix._prompt, prompt_multiline); <ide> read_buffer = ''; <ide> if (client_unix.list && client_unix.list.length > 0) { <ide> send_expect(client_unix.list); <ide> function unix_test() { <ide> socket.end(); <ide> }); <ide> <del> repl.start({ <add> repl_unix = repl.start({ <ide> prompt: prompt_unix, <ide> input: socket, <ide> output: socket, <ide> useGlobal: true <del> }).context.message = message; <add> }); <add> repl_unix.context.message = message; <ide> }); <ide> <ide> server_unix.on('listening', function() {
3
Ruby
Ruby
improve regexp to recognize comments
42486c1181bdf4ed85f334ccb1edbb6632cfc4b2
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge <ide> else <ide> string = s.sub!( <ide> /( <add> (\ {2}\#[^\n]*\n)* # comments <ide> \ {2}( # two spaces at the beginning <ide> (url|head)\ ['"][\S\ ]+['"] # url or head with a string <ide> (
1
Javascript
Javascript
support empty src in `player#src`
6541467ad8e3ce11ace391e36253b269a47b61ff
<ide><path>src/js/player.js <ide> import ModalDialog from './modal-dialog'; <ide> import Tech from './tech/tech.js'; <ide> import * as middleware from './tech/middleware.js'; <ide> import {ALL as TRACK_TYPES} from './tracks/track-types'; <add>import filterSource from './utils/filter-source'; <ide> <ide> // The following imports are used only to ensure that the corresponding modules <ide> // are always included in the video.js package. Importing the modules will <ide> class Player extends Component { <ide> * The current video source when getting <ide> */ <ide> src(source) { <del> if (source === undefined) { <add> // getter usage <add> if (typeof source === 'undefined') { <ide> return this.cache_.src; <ide> } <add> // filter out invalid sources and turn our source into <add> // an array of source objects <add> const sources = filterSource(source); <ide> <del> this.changingSrc_ = true; <del> <del> let src = source; <del> <del> if (Array.isArray(source)) { <del> this.cache_.sources = source; <del> src = source[0]; <del> } else if (typeof source === 'string') { <del> src = { <del> src: source <del> }; <del> <del> this.cache_.sources = [src]; <add> // if a source was passed in then it is invalid because <add> // it was filtered to a zero length Array. So we have to <add> // show an error <add> if (!sources.length) { <add> this.setTimeout(function() { <add> this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); <add> }, 0); <add> return; <ide> } <ide> <del> this.cache_.source = src; <add> // intial sources <add> this.cache_.sources = sources; <add> this.changingSrc_ = true; <ide> <del> this.currentType_ = src.type; <add> // intial source <add> this.cache_.source = sources[0]; <ide> <del> middleware.setSource(this, src, (src_, mws) => { <add> // middlewareSource is the source after it has been changed by middleware <add> middleware.setSource(this, sources[0], (middlewareSource, mws) => { <ide> this.middleware_ = mws; <ide> <del> const err = this.src_(src_); <add> const err = this.src_(middlewareSource); <ide> <ide> if (err) { <del> if (Array.isArray(source) && source.length > 1) { <del> return this.src(source.slice(1)); <add> if (sources.length > 1) { <add> return this.src(sources.slice(1)); <ide> } <ide> <ide> // We need to wrap this in a timeout to give folks a chance to add error event handlers <ide> class Player extends Component { <ide> } <ide> <ide> this.changingSrc_ = false; <del> this.cache_.src = src_.src; <add> // video element listed source <add> this.cache_.src = middlewareSource.src; <add> <ide> middleware.setTech(mws, this.tech_); <ide> }); <ide> } <ide> <add> /** <add> * Set the source object on the tech, returns a boolean that indicates wether <add> * there is a tech that can play the source or not <add> * <add> * @param {Tech~SourceObject} source <add> * The source object to set on the Tech <add> * <add> * @return {Boolean} <add> * - True if there is no Tech to playback this source <add> * - False otherwise <add> * <add> * @private <add> */ <ide> src_(source) { <ide> const sourceTech = this.selectSource([source]); <ide> <ide> class Player extends Component { <ide> return false; <ide> } <ide> <del> /** <del> * Handle an array of source objects <del> * <del> * @param {Tech~SourceObject[]} sources <del> * Array of source objects <del> * <del> * @private <del> */ <del> sourceList_(sources) { <del> const sourceTech = this.selectSource(sources); <del> <del> if (sourceTech) { <del> if (sourceTech.tech === this.techName_) { <del> // if this technology is already loaded, set the source <del> this.src(sourceTech.source); <del> } else { <del> // load this technology with the chosen source <del> this.loadTech_(sourceTech.tech, sourceTech.source); <del> } <del> <del> this.cache_.sources = sources; <del> } else { <del> // We need to wrap this in a timeout to give folks a chance to add error event handlers <del> this.setTimeout(function() { <del> this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); <del> }, 0); <del> <del> // we could not find an appropriate tech, but let's still notify the delegate that this is it <del> // this needs a better comment about why this is needed <del> this.triggerReady(); <del> } <del> } <del> <ide> /** <ide> * Begin loading the src data. <ide> */ <ide> class Player extends Component { <ide> * The current source object <ide> */ <ide> currentSource() { <del> const source = {}; <del> const src = this.currentSrc(); <del> <del> if (src) { <del> source.src = src; <del> } <del> <del> return this.cache_.source || source; <add> return this.cache_.source || {}; <ide> } <ide> <ide> /** <ide> class Player extends Component { <ide> * The current source <ide> */ <ide> currentSrc() { <del> return this.cache_.source && this.cache_.source.src || ''; <add> return this.currentSource() && this.currentSource().src || ''; <ide> } <ide> <ide> /** <ide> class Player extends Component { <ide> * The source MIME type <ide> */ <ide> currentType() { <del> return this.currentType_ || ''; <add> return this.currentSource() && this.currentSource().type || ''; <ide> } <ide> <ide> /** <ide><path>src/js/utils/filter-source.js <add>/** <add> * @module filter-source <add> */ <add>import {isObject} from './obj'; <add> <add>/** <add> * Filter out single bad source objects or multiple source objects in an <add> * array. Also flattens nested source object arrays into a 1 dimensional <add> * array of source objects. <add> * <add> * @param {Tech~SourceObject|Tech~SourceObject[]} src <add> * The src object to filter <add> * <add> * @return {Tech~SourceObject[]} <add> * An array of sourceobjects containing only valid sources <add> * <add> * @private <add> */ <add>const filterSource = function(src) { <add> // traverse array <add> if (Array.isArray(src)) { <add> let newsrc = []; <add> <add> src.forEach(function(srcobj) { <add> srcobj = filterSource(srcobj); <add> <add> if (Array.isArray(srcobj)) { <add> newsrc = newsrc.concat(srcobj); <add> } else if (isObject(srcobj)) { <add> newsrc.push(srcobj); <add> } <add> }); <add> <add> src = newsrc; <add> } else if (typeof src === 'string' && src.trim()) { <add> // convert string into object <add> src = [{src}]; <add> } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) { <add> // src is already valid <add> src = [src]; <add> } else { <add> // invalid source, turn it into an empty array <add> src = []; <add> } <add> <add> return src; <add>}; <add> <add>export default filterSource; <ide><path>test/unit/utils/filter-source.test.js <add>/* eslint-env qunit */ <add>import filterSource from '../../../src/js/utils/filter-source'; <add> <add>QUnit.module('utils/filter-source'); <add> <add>QUnit.test('invalid sources', function(assert) { <add> assert.deepEqual(filterSource(null), [], 'null source is filtered to []'); <add> assert.deepEqual(filterSource(undefined), [], 'undefined source is filtered to []'); <add> assert.deepEqual(filterSource(''), [], 'empty string source is filtered to []'); <add> assert.deepEqual(filterSource(' '), [], 'bad string source is filtered to []'); <add> assert.deepEqual(filterSource(1), [], 'number source is filtered to []'); <add> assert.deepEqual(filterSource([]), [], 'empty array source is filtered to []'); <add> assert.deepEqual(filterSource([[]]), [], 'empty array source is filtered to []'); <add> assert.deepEqual(filterSource(new Date()), [], 'Date source is filtered to []'); <add> assert.deepEqual(filterSource(new RegExp()), [], 'RegExp source is filtered to []'); <add> assert.deepEqual(filterSource(true), [], 'true boolean source is filtered to []'); <add> assert.deepEqual(filterSource(false), [], 'false boolean source is filtered to []'); <add> assert.deepEqual(filterSource([null]), [], 'invalid array source is filtered to []'); <add> assert.deepEqual(filterSource([undefined]), [], 'invalid array source is filtered to []'); <add> assert.deepEqual(filterSource([{src: 1}]), [], 'invalid array source is filtered to []'); <add> assert.deepEqual(filterSource({}), [], 'empty object source is filtered to []'); <add> assert.deepEqual(filterSource({src: 1}), [], 'invalid object source is filtered to []'); <add> assert.deepEqual(filterSource({src: ''}), [], 'invalid object source is filtered to []'); <add> assert.deepEqual(filterSource({src: null}), [], 'invalid object source is filtered to []'); <add> assert.deepEqual(filterSource({url: 1}), [], 'invalid object source is filtered to []'); <add>}); <add> <add>QUnit.test('valid sources', function(assert) { <add> assert.deepEqual( <add> filterSource('some-url'), <add> [{src: 'some-url'}], <add> 'string source filters to object' <add> ); <add> assert.deepEqual( <add> filterSource({src: 'some-url'}), <add> [{src: 'some-url'}], <add> 'valid source filters to itself' <add> ); <add> assert.deepEqual( <add> filterSource([{src: 'some-url'}]), <add> [{src: 'some-url'}], <add> 'valid source filters to itself' <add> ); <add> assert.deepEqual( <add> filterSource([{src: 'some-url'}, {src: 'some-url2'}]), <add> [{src: 'some-url'}, {src: 'some-url2'}], <add> 'valid source filters to itself' <add> ); <add> assert.deepEqual( <add> filterSource(['some-url', {src: 'some-url2'}]), <add> [{src: 'some-url'}, {src: 'some-url2'}], <add> 'mixed array filters to object array' <add> ); <add> assert.deepEqual( <add> filterSource(['some-url', undefined, {src: 'some-url2'}]), <add> [{src: 'some-url'}, {src: 'some-url2'}], <add> 'mostly-valid array filters to valid object array' <add> ); <add> assert.deepEqual( <add> filterSource([[{src: 'some-url'}]]), <add> [{src: 'some-url'}], <add> 'nested array filters to flattened array itself' <add> ); <add> <add> assert.deepEqual( <add> filterSource([[[{src: 'some-url'}]]]), <add> [{src: 'some-url'}], <add> 'double nested array filters to flattened array' <add> ); <add> <add> assert.deepEqual( <add> filterSource([{src: 'some-url2'}, [{src: 'some-url'}], undefined]), <add> [{src: 'some-url2'}, {src: 'some-url'}], <add> 'nested array filters to flattened array' <add> ); <add> <add> assert.deepEqual( <add> filterSource([[{src: 'some-url2'}], [[[{src: 'some-url'}]]], [undefined]]), <add> [{src: 'some-url2'}, {src: 'some-url'}], <add> 'nested array filters to flattened array in correct order' <add> ); <add>}); <add> <add>QUnit.test('Order is maintained', function(assert) { <add> assert.deepEqual( <add> filterSource([{src: 'one'}, {src: 'two'}, {src: 'three'}, undefined]), <add> [{src: 'one'}, {src: 'two'}, {src: 'three'}], <add> 'source order is maintained for array' <add> ); <add> <add> assert.deepEqual( <add> filterSource([{src: 'one'}, {src: 'two'}, {src: 'three'}, undefined]), <add> [{src: 'one'}, {src: 'two'}, {src: 'three'}], <add> 'source order is maintained for array' <add> ); <add> <add> assert.deepEqual( <add> filterSource([null, [{src: 'one'}], [[[{src: 'two'}]]], {src: 'three'}, undefined]), <add> [{src: 'one'}, {src: 'two'}, {src: 'three'}], <add> 'source order is maintained for mixed nested arrays' <add> ); <add> <add>}); <add> <add>QUnit.test('Dont filter extra object properties', function(assert) { <add> assert.deepEqual( <add> filterSource({src: 'some-url', type: 'some-type'}), <add> [{src: 'some-url', type: 'some-type'}], <add> 'type key is maintained' <add> ); <add> <add> assert.deepEqual( <add> filterSource({src: 'some-url', type: 'some-type', foo: 'bar'}), <add> [{src: 'some-url', type: 'some-type', foo: 'bar'}], <add> 'foo and bar keys are maintained' <add> ); <add> <add> assert.deepEqual( <add> filterSource([{src: 'some-url', type: 'some-type', foo: 'bar'}]), <add> [{src: 'some-url', type: 'some-type', foo: 'bar'}], <add> 'foo and bar keys are not removed' <add> ); <add> <add>});
3
Text
Text
add link to homebrew blog
09dcdc2a6b86df92409c7c5865f48063d4680a90
<ide><path>docs/README.md <ide> ## Users <ide> <ide> - [`brew` man-page (command documentation)](Manpage.md) <add>- [Homebrew Blog (news on major updates)](https://brew.sh/blog/) <ide> - [Troubleshooting](Troubleshooting.md) <ide> - [Installation](Installation.md) <ide> - [Frequently Asked Questions](FAQ.md)
1
Go
Go
remove unnecessary getimageidandos use getimage
c10e6a4d15b907da22ab508770d67e1447a8d0bd
<ide><path>daemon/images/image.go <ide> func (e ErrImageDoesNotExist) Error() string { <ide> // NotFound implements the NotFound interface <ide> func (e ErrImageDoesNotExist) NotFound() {} <ide> <del>// GetImageIDAndOS returns an image ID and operating system corresponding to the image referred to by <del>// refOrID. <del>// called from list.go foldFilter() <del>func (i ImageService) GetImageIDAndOS(refOrID string) (image.ID, string, error) { <add>// GetImage returns an image corresponding to the image referred to by refOrID. <add>func (i *ImageService) GetImage(refOrID string) (*image.Image, error) { <ide> ref, err := reference.ParseAnyReference(refOrID) <ide> if err != nil { <del> return "", "", errdefs.InvalidParameter(err) <add> return nil, errdefs.InvalidParameter(err) <ide> } <ide> namedRef, ok := ref.(reference.Named) <ide> if !ok { <ide> digested, ok := ref.(reference.Digested) <ide> if !ok { <del> return "", "", ErrImageDoesNotExist{ref} <add> return nil, ErrImageDoesNotExist{ref} <ide> } <ide> id := image.IDFromDigest(digested.Digest()) <ide> if img, err := i.imageStore.Get(id); err == nil { <del> return id, img.OperatingSystem(), nil <add> return img, nil <ide> } <del> return "", "", ErrImageDoesNotExist{ref} <add> return nil, ErrImageDoesNotExist{ref} <ide> } <ide> <ide> if digest, err := i.referenceStore.Get(namedRef); err == nil { <ide> // Search the image stores to get the operating system, defaulting to host OS. <ide> id := image.IDFromDigest(digest) <ide> if img, err := i.imageStore.Get(id); err == nil { <del> return id, img.OperatingSystem(), nil <add> return img, nil <ide> } <ide> } <ide> <ide> // Search based on ID <ide> if id, err := i.imageStore.Search(refOrID); err == nil { <ide> img, err := i.imageStore.Get(id) <ide> if err != nil { <del> return "", "", ErrImageDoesNotExist{ref} <add> return nil, ErrImageDoesNotExist{ref} <ide> } <del> return id, img.OperatingSystem(), nil <add> return img, nil <ide> } <ide> <del> return "", "", ErrImageDoesNotExist{ref} <del>} <del> <del>// GetImage returns an image corresponding to the image referred to by refOrID. <del>func (i *ImageService) GetImage(refOrID string) (*image.Image, error) { <del> imgID, _, err := i.GetImageIDAndOS(refOrID) <del> if err != nil { <del> return nil, err <del> } <del> return i.imageStore.Get(imgID) <add> return nil, ErrImageDoesNotExist{ref} <ide> } <ide><path>daemon/images/image_delete.go <ide> func (i *ImageService) ImageDelete(imageRef string, force, prune bool) ([]types. <ide> start := time.Now() <ide> records := []types.ImageDeleteResponseItem{} <ide> <del> imgID, operatingSystem, err := i.GetImageIDAndOS(imageRef) <add> img, err := i.GetImage(imageRef) <ide> if err != nil { <ide> return nil, err <ide> } <del> if !system.IsOSSupported(operatingSystem) { <add> if !system.IsOSSupported(img.OperatingSystem()) { <ide> return nil, errors.Errorf("unable to delete image: %q", system.ErrNotSupportedOperatingSystem) <ide> } <ide> <add> imgID := img.ID() <ide> repoRefs := i.referenceStore.References(imgID.Digest()) <ide> <ide> using := func(c *container.Container) bool { <ide><path>daemon/images/image_tag.go <ide> import ( <ide> // TagImage creates the tag specified by newTag, pointing to the image named <ide> // imageName (alternatively, imageName can also be an image ID). <ide> func (i *ImageService) TagImage(imageName, repository, tag string) (string, error) { <del> imageID, _, err := i.GetImageIDAndOS(imageName) <add> img, err := i.GetImage(imageName) <ide> if err != nil { <ide> return "", err <ide> } <ide> func (i *ImageService) TagImage(imageName, repository, tag string) (string, erro <ide> } <ide> } <ide> <del> err = i.TagImageWithReference(imageID, newTag) <add> err = i.TagImageWithReference(img.ID(), newTag) <ide> return reference.FamiliarString(newTag), err <ide> } <ide> <ide><path>daemon/list.go <ide> func (daemon *Daemon) foldFilter(view container.View, config *types.ContainerLis <ide> if psFilters.Contains("ancestor") { <ide> ancestorFilter = true <ide> psFilters.WalkValues("ancestor", func(ancestor string) error { <del> id, _, err := daemon.imageService.GetImageIDAndOS(ancestor) <add> img, err := daemon.imageService.GetImage(ancestor) <ide> if err != nil { <ide> logrus.Warnf("Error while looking up for image %v", ancestor) <ide> return nil <ide> } <del> if imagesFilter[id] { <add> if imagesFilter[img.ID()] { <ide> // Already seen this ancestor, skip it <ide> return nil <ide> } <ide> // Then walk down the graph and put the imageIds in imagesFilter <del> populateImageFilterByParents(imagesFilter, id, daemon.imageService.Children) <add> populateImageFilterByParents(imagesFilter, img.ID(), daemon.imageService.Children) <ide> return nil <ide> }) <ide> } <ide> func (daemon *Daemon) refreshImage(s *container.Snapshot, ctx *listContext) (*ty <ide> c := s.Container <ide> image := s.Image // keep the original ref if still valid (hasn't changed) <ide> if image != s.ImageID { <del> id, _, err := daemon.imageService.GetImageIDAndOS(image) <add> img, err := daemon.imageService.GetImage(image) <ide> if _, isDNE := err.(images.ErrImageDoesNotExist); err != nil && !isDNE { <ide> return nil, err <ide> } <del> if err != nil || id.String() != s.ImageID { <add> if err != nil || img.ImageID() != s.ImageID { <ide> // ref changed, we need to use original ID <ide> image = s.ImageID <ide> }
4
Javascript
Javascript
support more ci services in `getcolordepth`
f1940824d9f0e769d4ecce07307d4b126cd8dbb4
<ide><path>lib/internal/tty.js <ide> function getColorDepth(env = process.env) { <ide> } <ide> <ide> if (env.CI) { <del> if ('TRAVIS' in env || 'CIRCLECI' in env || 'APPVEYOR' in env || <del> 'GITLAB_CI' in env || env.CI_NAME === 'codeship') { <add> if ([ <add> 'APPVEYOR', <add> 'BUILDKITE', <add> 'CIRCLECI', <add> 'DRONE', <add> 'GITHUB_ACTIONS', <add> 'GITLAB_CI', <add> 'TRAVIS', <add> ].some((sign) => sign in env) || env.CI_NAME === 'codeship') { <ide> return COLORS_256; <ide> } <ide> return COLORS_2;
1
Python
Python
load all job models at once
d2042b7bf6f9dc061032e4fb13cf21fc826684f2
<ide><path>airflow/jobs/__init__.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> # <add>import airflow.jobs.backfill_job # noqa <add>import airflow.jobs.base_job # noqa <add>import airflow.jobs.local_task_job # noqa <add>import airflow.jobs.scheduler_job # noqa
1
Javascript
Javascript
fix lint error in mutli compiler
934534e96935e56c001b3b77b3969338e37e98c8
<ide><path>lib/MultiCompiler.js <ide> module.exports = class MultiCompiler extends Tapable { <ide> const missing = []; <ide> for(const source of this.compilers) { <ide> if(source.dependencies) { <del> for(const d of source.dependencies) { <del> const target = this.compilers.find((c) => c.name === d); <add> for(const dep of source.dependencies) { <add> const target = this.compilers.find((c) => c.name === dep); <ide> if(!target) { <del> missing.push(d); <add> missing.push(dep); <ide> } else { <del> edges.push({ source, target }); <add> edges.push({ <add> source, <add> target <add> }); <ide> } <ide> } <ide> }
1
Javascript
Javascript
match jest.d.ts by regex
efb6d80e60e400f1d6b4549099939cf334afa687
<ide><path>scripts/jest/ts-preprocessor.js <ide> function compile(content, contentFilename) { <ide> path.join('/', '(?:React|ReactDOM)(?:\.d)?\.ts$') <ide> ); <ide> <add> var jestRegex = /jest\.d\.ts/; <add> <ide> if (filename === 'lib.d.ts') { <ide> source = fs.readFileSync( <ide> require.resolve('typescript/lib/lib.d.ts') <ide> ).toString(); <del> } else if (filename === 'jest.d.ts') { <add> } else if (filename.match(jestRegex)) { <ide> source = fs.readFileSync( <ide> path.join(__dirname, 'jest.d.ts') <ide> ).toString();
1
Ruby
Ruby
remove prefix from email subject
4ae5ea7dbeb754a5039775e66b62e3da0419a79b
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> end <ide> <ide> if failed_steps.empty? <del> email_subject = 'brew test-bot: PASSED' <add> email_subject = 'PASSED' <ide> else <del> email_subject = "brew test-bot: FAILED: #{failed_steps.join ', '}" <add> email_subject = "#{failed_steps.join ', '}" <ide> end <ide> <ide> File.open "brew test-bot.email.txt", 'w' do |file|
1
Javascript
Javascript
reduce syscalls during require search
a71ee93afeada095aaefb0656ef744c5bcc9e9ce
<ide><path>lib/module.js <ide> const noopDeprecateRequireDot = util.deprecate(function() {}, <ide> Module._findPath = function(request, paths) { <ide> var exts = Object.keys(Module._extensions); <ide> <del> if (request.charAt(0) === '/') { <add> if (path.isAbsolute(request)) { <ide> paths = ['']; <ide> } <ide> <ide> Module._findPath = function(request, paths) { <ide> <ide> // For each path <ide> for (var i = 0, PL = paths.length; i < PL; i++) { <add> // Don't search further if path doesn't exist <add> if (paths[i] && internalModuleStat(paths[i]) < 1) continue; <ide> var basePath = path.resolve(paths[i], request); <ide> var filename; <ide>
1
Ruby
Ruby
remove delegated methods from generators test case
3e7070622af7b6efe9eb86c2275b2ad895bd5510
<ide><path>railties/lib/rails/generators/test_case.rb <ide> class TestCase < ActiveSupport::TestCase <ide> include FileUtils <ide> <ide> class_attribute :destination_root, :current_path, :generator_class, :default_arguments <del> delegate :destination_root, :current_path, :generator_class, :default_arguments, :to => :'self.class' <ide> <ide> # Generators frequently change the current path using +FileUtils.cd+. <ide> # So we need to store the path at file load and revert back to it after each test.
1
Python
Python
throw custom error when state_type is invalid
25b34bba9406a3185406e79e8b0e45048e7f3914
<ide><path>spacy/errors.py <ide> class Errors: <ide> E201 = ("Span index out of range.") <ide> <ide> # TODO: fix numbering after merging develop into master <add> E917 = ("Received invalid value {value} for 'state_type' in " <add> "TransitionBasedParser: only 'parser' or 'ner' are valid options.") <ide> E918 = ("Received invalid value for vocab: {vocab} ({vocab_type}). Valid " <ide> "values are an instance of spacy.vocab.Vocab or True to create one" <ide> " (default).") <ide><path>spacy/ml/models/parser.py <ide> from thinc.api import Model, chain, list2array, Linear, zero_init, use_ops <ide> from thinc.types import Floats2d <ide> <add>from ... import Errors <ide> from ...util import registry <ide> from .._precomputable_affine import PrecomputableAffine <ide> from ..tb_framework import TransitionModel <ide> def build_tb_parser_model( <ide> elif state_type == "ner": <ide> nr_feature_tokens = 6 if extra_state_tokens else 3 <ide> else: <del> raise ValueError(f"unknown state type {state_type}") # TODO error <add> raise ValueError(Errors.E917.format(value=state_type)) <ide> t2v_width = tok2vec.get_dim("nO") if tok2vec.has_dim("nO") else None <ide> tok2vec = chain(tok2vec, list2array(), Linear(hidden_width, t2v_width)) <ide> tok2vec.set_dim("nO", hidden_width)
2
Javascript
Javascript
fix error in test-cluster-worker-death.js
68488e9c75cf24632fd68063168992ca6830655c
<ide><path>test/parallel/test-cluster-worker-death.js <ide> if (!cluster.isMaster) { <ide> } else { <ide> var worker = cluster.fork(); <ide> worker.on('exit', common.mustCall(function(exitCode, signalCode) { <del> assert.equal(exitCode, 42); <del> assert.equal(signalCode, null); <add> assert.strictEqual(exitCode, 42); <add> assert.strictEqual(signalCode, null); <ide> })); <ide> cluster.on('exit', common.mustCall(function(worker_) { <del> assert.equal(worker_, worker); <add> assert.strictEqual(worker_, worker); <ide> })); <ide> }
1
PHP
PHP
update the phpunit install instructions
1d8199b86d231287a2089c5db42f81a11cb44461
<ide><path>lib/Cake/TestSuite/templates/phpunit.php <ide> <div id="content"> <ide> <h2>PHPUnit is not installed!</h2> <ide> <p>You must install PHPUnit to use the CakePHP(tm) Test Suite.</p> <del> <p>PHPUnit can either be installed with pear, using the pear installer. Or the 'PHPUnit' directory from the distribution can be placed in one of your vendors directories.</p> <del> <ul> <del> <li><?php echo CAKE; ?>vendors </li> <del> <li><?php echo APP_DIR . DS; ?>vendors</li> <del> </ul> <add> <p>PHPUnit can be installed with pear, using the pear installer.</p> <ide> <p>To install with the PEAR installer run the following commands:</p> <ide> <ul> <del> <li>pear channel-discover pear.phpunit.de</li> <del> <li>pear channel-discover components.ez.no</li> <del> <li>pear channel-discover pear.symfony-project.com</li> <del> <li>pear install phpunit/PHPUnit</li> <add> <li><code>pear channel-discover pear.phpunit.de</code></li> <add> <li><code>pear channel-discover components.ez.no</code></li> <add> <li><code>pear channel-discover pear.symfony-project.com</code></li> <add> <li><code>pear install phpunit/PHPUnit-3.5.15</code></li> <ide> </ul> <ide> <p>For full instructions on how to <a href="http://www.phpunit.de/manual/current/en/installation.html">install PHPUnit, see the PHPUnit installation guide</a>.</p> <ide> <p><a href="http://github.com/sebastianbergmann/phpunit" target="_blank">Download PHPUnit</a></p> <ide> </div> <del><?php include dirname(__FILE__) . DS . 'footer.php'; ?> <ide>\ No newline at end of file <add><?php include dirname(__FILE__) . DS . 'footer.php'; ?>
1
Mixed
Ruby
unify the collation api for the database adpters
aafa00f4c10a6791e6470112f0f1fbe5f2c3f649
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Brian Cardarella* <ide> <del>* Add `collate` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later. <add>* Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later. <ide> Example: <ide> <ide> development: <ide> username: foo <ide> password: bar <ide> encoding: UTF8 <del> collate: ja_JP.UTF8 <add> collation: ja_JP.UTF8 <ide> ctype: ja_JP.UTF8 <ide> <ide> *kennyj* <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def recreate_database(name, options = {}) #:nodoc: <ide> end <ide> <ide> # Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>, <del> # <tt>:encoding</tt>, <tt>:collate</tt>, <tt>:ctype</tt>, <add> # <tt>:encoding</tt>, <tt>:collation</tt>, <tt>:ctype</tt>, <ide> # <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses <ide> # <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>). <ide> # <ide> def create_database(name, options = {}) <ide> " TEMPLATE = \"#{value}\"" <ide> when :encoding <ide> " ENCODING = '#{value}'" <del> when :collate <add> when :collation <ide> " LC_COLLATE = '#{value}'" <ide> when :ctype <ide> " LC_CTYPE = '#{value}'" <ide> def encoding <ide> end_sql <ide> end <ide> <del> # Returns the current database collate. <del> def collate <add> # Returns the current database collation. <add> def collation <ide> query(<<-end_sql, 'SCHEMA')[0][0] <ide> SELECT pg_database.datcollate FROM pg_database WHERE pg_database.datname LIKE '#{current_database}' <ide> end_sql <ide><path>activerecord/lib/active_record/tasks/postgresql_database_tasks.rb <ide> def charset <ide> end <ide> <ide> def collation <del> connection.collate <add> connection.collation <ide> end <ide> <ide> def purge <ide><path>activerecord/test/cases/adapters/postgresql/active_schema_test.rb <ide> def test_create_database_with_encoding <ide> assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1) <ide> end <ide> <del> def test_create_database_with_collate_and_ctype <del> assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collate => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8") <add> def test_create_database_with_collation_and_ctype <add> assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collation => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8") <ide> end <ide> <ide> def test_add_index <ide><path>activerecord/test/cases/adapters/postgresql/connection_test.rb <ide> def test_encoding <ide> assert_not_nil @connection.encoding <ide> end <ide> <del> def test_collate <del> assert_not_nil @connection.collate <add> def test_collation <add> assert_not_nil @connection.collation <ide> end <ide> <ide> def test_ctype <ide><path>activerecord/test/cases/tasks/postgresql_rake_test.rb <ide> def test_creates_database_with_given_encoding <ide> merge('encoding' => 'latin') <ide> end <ide> <del> def test_creates_database_with_given_collate_and_ctype <add> def test_creates_database_with_given_collation_and_ctype <ide> @connection.expects(:create_database). <del> with('my-app-db', @configuration.merge('encoding' => 'utf8', 'collate' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8')) <add> with('my-app-db', @configuration.merge('encoding' => 'utf8', 'collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8')) <ide> <ide> ActiveRecord::Tasks::DatabaseTasks.create @configuration. <del> merge('collate' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8') <add> merge('collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8') <ide> end <ide> <ide> def test_establishes_connection_to_new_database <ide> def setup <ide> end <ide> <ide> def test_db_retrieves_collation <del> @connection.expects(:collate) <add> @connection.expects(:collation) <ide> ActiveRecord::Tasks::DatabaseTasks.collation @configuration <ide> end <ide> end
6
Text
Text
add django rest messaging in third party packages
f1a384b61bdfe61bc45e71b25089609043c3d069
<ide><path>docs/topics/third-party-resources.md <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> * [django-rest-framework-braces][django-rest-framework-braces] - Collection of utilities for working with Django Rest Framework. The most notable ones are [FormSerializer](https://django-rest-framework-braces.readthedocs.org/en/latest/overview.html#formserializer) and [SerializerForm](https://django-rest-framework-braces.readthedocs.org/en/latest/overview.html#serializerform), which are adapters between DRF serializers and Django forms. <ide> * [drf-haystack][drf-haystack] - Haystack search for Django Rest Framework <ide> * [django-rest-framework-version-transforms][django-rest-framework-version-transforms] - Enables the use of delta transformations for versioning of DRF resource representations. <add>* [django-rest-messaging][django-rest-messaging], [django-rest-messaging-centrifugo][django-rest-messaging-centrifugo] and [django-rest-messaging-js][django-rest-messaging-js] - A real-time pluggable messaging service using DRM. <ide> <ide> ## Other Resources <ide>
1
Text
Text
simplify troubleshooting text
22de2cfb71f3f1ab63e9663f4aa62bd9016b762a
<ide><path>COLLABORATOR_GUIDE.md <ide> hint: See the 'Note about fast-forwards' in 'git push --help' for details. <ide> ``` <ide> <ide> That means a commit has landed since your last rebase against `upstream/master`. <del>To fix this, pull with rebase from upstream and run the tests again (to make <del>sure no interactions between your changes and the new changes cause any <del>problems), and push again: <add>To fix this, pull with rebase from upstream, run the tests again, and (if the <add>tests pass) push again: <ide> <ide> ```sh <ide> git pull upstream master --rebase
1
PHP
PHP
change @copyright to @see
f89533e1c184dc8448f6a0718a6de8e5af31d434
<ide><path>src/Validation/Validation.php <ide> public static function datetime($check, $dateFormat = 'ymd', $regex = null) <ide> * <ide> * @return bool True if the value is valid, false otherwise <ide> * <del> * @copyright Regex credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ <add> * @see Regex credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ <ide> */ <ide> public static function iso8601($check) <ide> { <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testDateTimeISO() <ide> * <ide> * @return void <ide> * <del> * @copyright Validation tests values credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ <add> * @see Validation tests values credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ <ide> */ <ide> public function testDateTimeISO8601() <ide> {
2
Go
Go
remove daemon check for test
9af6b57a5d466ab3fdea0db8ba8d9a417519a63e
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) restore() error { <ide> } <ide> <ide> var ( <del> debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "") <add> debug = os.Getenv("DEBUG") != "" <ide> currentDriver = daemon.driver.String() <ide> containers = make(map[string]*cr) <ide> )
1
Java
Java
fix condition in servletinvocablehandlermethod
9960ed55aa3ce3f75dd8c5a0e550438323a0344a
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java <ide> private boolean isRequestNotModified(ServletWebRequest webRequest) { <ide> } <ide> <ide> private void disableContentCachingIfNecessary(ServletWebRequest webRequest) { <del> if (!isRequestNotModified(webRequest)) { <add> if (isRequestNotModified(webRequest)) { <ide> HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); <ide> Assert.notNull(response, "Expected HttpServletResponse"); <ide> if (StringUtils.hasText(response.getHeader(HttpHeaders.ETAG))) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.annotation.AliasFor; <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> import org.springframework.web.context.request.async.DeferredResult; <add>import org.springframework.web.filter.ShallowEtagHeaderFilter; <ide> import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; <ide> import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite; <ide> import org.springframework.web.method.support.HandlerMethodReturnValueHandler; <ide> public void invokeAndHandle_VoidRequestNotModified() throws Exception { <ide> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "notModified"); <ide> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <ide> <del> assertThat(this.mavContainer.isRequestHandled()).as("Null return value + 'not modified' request should result in 'request handled'").isTrue(); <add> assertThat(this.mavContainer.isRequestHandled()) <add> .as("Null return value + 'not modified' request should result in 'request handled'") <add> .isTrue(); <add> } <add> <add> @Test // gh-23775 <add> public void invokeAndHandle_VoidNotModifiedWithEtag() throws Exception { <add> String etag = "\"deadb33f8badf00d\""; <add> this.request.addHeader(HttpHeaders.IF_NONE_MATCH, etag); <add> this.webRequest.checkNotModified(etag); <add> <add> ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "notModified"); <add> handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); <add> <add> assertThat(this.mavContainer.isRequestHandled()) <add> .as("Null return value + 'not modified' request should result in 'request handled'") <add> .isTrue(); <add> <add> assertThat(this.request.getAttribute(ShallowEtagHeaderFilter.class.getName() + ".STREAMING")) <add> .isEqualTo(true); <ide> } <ide> <ide> @Test // SPR-9159
2
Javascript
Javascript
handle effective dataset visibility per chart
82b1e5cd99d77744aac3c1a3c532bbf99b2578cf
<ide><path>src/controllers/controller.bar.js <ide> module.exports = function(Chart) { <ide> var barCount = 0; <ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <ide> var meta = this.chart.getDatasetMeta(datasetIndex); <del> if (meta.bar && helpers.isDatasetVisible(dataset)) { <add> if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) { <ide> ++barCount; <ide> } <ide> }, this); <ide> module.exports = function(Chart) { <ide> for (var i = 0; i < datasetIndex; i++) { <ide> var negDS = this.chart.data.datasets[i]; <ide> var negDSMeta = this.chart.getDatasetMeta(i); <del> if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(negDS)) { <add> if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { <ide> base += negDS.data[index] < 0 ? negDS.data[index] : 0; <ide> } <ide> } <ide> } else { <ide> for (var j = 0; j < datasetIndex; j++) { <ide> var posDS = this.chart.data.datasets[j]; <ide> var posDSMeta = this.chart.getDatasetMeta(j); <del> if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(posDS)) { <add> if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(j)) { <ide> base += posDS.data[index] > 0 ? posDS.data[index] : 0; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> <ide> for (j = 0; j < datasetIndex; ++j) { <ide> meta = this.chart.getDatasetMeta(j); <del> if (meta.bar && helpers.isDatasetVisible(this.chart.data.datasets[j])) { <add> if (meta.bar && this.chart.isDatasetVisible(j)) { <ide> ++barIndex; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> for (var i = 0; i < datasetIndex; i++) { <ide> var ds = this.chart.data.datasets[i]; <ide> var dsMeta = this.chart.getDatasetMeta(i); <del> if (dsMeta.bar && dsMeta.yAxisID === yScale.id && helpers.isDatasetVisible(ds)) { <add> if (dsMeta.bar && dsMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { <ide> if (ds.data[index] < 0) { <ide> sumNeg += ds.data[index] || 0; <ide> } else { <ide><path>src/controllers/controller.doughnut.js <ide> module.exports = function(Chart) { <ide> } <ide> }, <ide> onClick: function(e, legendItem) { <del> helpers.each(this.chart.data.datasets, function(dataset) { <del> dataset.metaHiddenData = dataset.metaHiddenData || []; <add> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <add> var meta = this.chart.getDatasetMeta(datasetIndex); <ide> var idx = legendItem.index; <ide> <ide> if (!isNaN(dataset.data[idx])) { <del> dataset.metaHiddenData[idx] = dataset.data[idx]; <add> meta.hiddenData[idx] = dataset.data[idx]; <ide> dataset.data[idx] = NaN; <del> } else if (!isNaN(dataset.metaHiddenData[idx])) { <del> dataset.data[idx] = dataset.metaHiddenData[idx]; <add> } else if (!isNaN(meta.hiddenData[idx])) { <add> dataset.data[idx] = meta.hiddenData[idx]; <ide> } <del> }); <add> }, this); <ide> <ide> this.chart.update(); <ide> } <ide> module.exports = function(Chart) { <ide> this.updateElement(arc, index, true); <ide> }, <ide> <del> getVisibleDatasetCount: function getVisibleDatasetCount() { <del> return helpers.where(this.chart.data.datasets, function(ds) { <del> return helpers.isDatasetVisible(ds); <del> }).length; <del> }, <del> <ide> // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly <ide> getRingIndex: function getRingIndex(datasetIndex) { <ide> var ringIndex = 0; <ide> <ide> for (var j = 0; j < datasetIndex; ++j) { <del> if (helpers.isDatasetVisible(this.chart.data.datasets[j])) { <add> if (this.chart.isDatasetVisible(j)) { <ide> ++ringIndex; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> <ide> this.chart.outerRadius = Math.max(minSize / 2, 0); <ide> this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); <del> this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.getVisibleDatasetCount(); <add> this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount(); <ide> this.chart.offsetX = offset.x * this.chart.outerRadius; <ide> this.chart.offsetY = offset.y * this.chart.outerRadius; <ide> <ide><path>src/controllers/controller.line.js <ide> module.exports = function(Chart) { <ide> for (var i = 0; i < datasetIndex; i++) { <ide> var ds = this.chart.data.datasets[i]; <ide> var dsMeta = this.chart.getDatasetMeta(i); <del> if (dsMeta.type === 'line' && helpers.isDatasetVisible(ds)) { <add> if (dsMeta.type === 'line' && this.chart.isDatasetVisible(i)) { <ide> if (ds.data[index] < 0) { <ide> sumNeg += ds.data[index] || 0; <ide> } else { <ide><path>src/controllers/controller.polarArea.js <ide> module.exports = function(Chart) { <ide> } <ide> }, <ide> onClick: function(e, legendItem) { <del> helpers.each(this.chart.data.datasets, function(dataset) { <del> dataset.metaHiddenData = dataset.metaHiddenData || []; <add> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <add> var meta = this.chart.getDatasetMeta(datasetIndex); <ide> var idx = legendItem.index; <ide> <ide> if (!isNaN(dataset.data[idx])) { <del> dataset.metaHiddenData[idx] = dataset.data[idx]; <add> meta.hiddenData[idx] = dataset.data[idx]; <ide> dataset.data[idx] = NaN; <del> } else if (!isNaN(dataset.metaHiddenData[idx])) { <del> dataset.data[idx] = dataset.metaHiddenData[idx]; <add> } else if (!isNaN(meta.hiddenData[idx])) { <add> dataset.data[idx] = meta.hiddenData[idx]; <ide> } <del> }); <add> }, this); <ide> <ide> this.chart.update(); <ide> } <ide> module.exports = function(Chart) { <ide> this.getMeta().data.splice(index, 0, arc); <ide> this.updateElement(arc, index, true); <ide> }, <del> getVisibleDatasetCount: function getVisibleDatasetCount() { <del> return helpers.where(this.chart.data.datasets, function(ds) { <del> return helpers.isDatasetVisible(ds); <del> }).length; <del> }, <ide> <ide> update: function update(reset) { <ide> var minSize = Math.min(this.chart.chartArea.right - this.chart.chartArea.left, this.chart.chartArea.bottom - this.chart.chartArea.top); <ide> this.chart.outerRadius = Math.max((minSize - this.chart.options.elements.arc.borderWidth / 2) / 2, 0); <ide> this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0); <del> this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.getVisibleDatasetCount(); <add> this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount(); <ide> <ide> this.getDataset().total = 0; <ide> helpers.each(this.getDataset().data, function(value) { <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> <ide> // Draw each dataset via its respective controller (reversed to support proper line stacking) <ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> if (helpers.isDatasetVisible(dataset)) { <add> if (this.isDatasetVisible(datasetIndex)) { <ide> this.getDatasetMeta(datasetIndex).controller.draw(ease); <ide> } <ide> }, this, true); <ide> module.exports = function(Chart) { <ide> var elementsArray = []; <ide> <ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> var meta = this.getDatasetMeta(datasetIndex); <del> if (helpers.isDatasetVisible(dataset)) { <add> if (this.isDatasetVisible(datasetIndex)) { <add> var meta = this.getDatasetMeta(datasetIndex); <ide> helpers.each(meta.data, function(element, index) { <ide> if (element.inRange(eventPosition.x, eventPosition.y)) { <ide> elementsArray.push(element); <ide> module.exports = function(Chart) { <ide> if (this.data.datasets) { <ide> for (var i = 0; i < this.data.datasets.length; i++) { <ide> var meta = this.getDatasetMeta(i); <del> if (helpers.isDatasetVisible(this.data.datasets[i])) { <add> if (this.isDatasetVisible(i)) { <ide> for (var j = 0; j < meta.data.length; j++) { <ide> if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) { <ide> return meta.data[j]; <ide> module.exports = function(Chart) { <ide> } <ide> <ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> var meta = this.getDatasetMeta(datasetIndex); <del> if (helpers.isDatasetVisible(dataset)) { <add> if (this.isDatasetVisible(datasetIndex)) { <add> var meta = this.getDatasetMeta(datasetIndex); <ide> elementsArray.push(meta.data[found._index]); <ide> } <ide> }, this); <ide> module.exports = function(Chart) { <ide> data: [], <ide> dataset: null, <ide> controller: null, <add> hiddenData: {}, <add> hidden: null, // See isDatasetVisible() comment <ide> xAxisID: null, <ide> yAxisID: null <ide> }; <ide> module.exports = function(Chart) { <ide> return meta; <ide> }, <ide> <add> getVisibleDatasetCount: function() { <add> var count = 0; <add> for (var i = 0, ilen = this.data.datasets.length; i<ilen; ++i) { <add> if (this.isDatasetVisible(i)) { <add> count++; <add> } <add> } <add> return count; <add> }, <add> <add> isDatasetVisible: function(datasetIndex) { <add> var meta = this.getDatasetMeta(datasetIndex); <add> <add> // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false, <add> // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned. <add> return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden; <add> }, <add> <ide> generateLegend: function generateLegend() { <ide> return this.options.legendCallback(this); <ide> }, <ide><path>src/core/core.helpers.js <ide> module.exports = function(Chart) { <ide> array.push(element); <ide> } <ide> }; <del> helpers.isDatasetVisible = function(dataset) { <del> return !dataset.hidden; <del> }; <ide> helpers.callCallback = function(fn, args, _tArg) { <ide> if (fn && typeof fn.call === 'function') { <ide> fn.apply(_tArg, args); <ide><path>src/core/core.legend.js <ide> module.exports = function(Chart) { <ide> <ide> // a callback that will handle <ide> onClick: function(e, legendItem) { <del> var dataset = this.chart.data.datasets[legendItem.datasetIndex]; <del> dataset.hidden = !dataset.hidden; <add> var index = legendItem.datasetIndex; <add> var meta = this.chart.getDatasetMeta(index); <add> <add> // See controller.isDatasetVisible comment <add> meta.hidden = meta.hidden === null? !this.chart.data.datasets[index].hidden : null; <ide> <ide> // We hid a dataset ... rerender the chart <ide> this.chart.update(); <ide> module.exports = function(Chart) { <ide> return { <ide> text: dataset.label, <ide> fillStyle: dataset.backgroundColor, <del> hidden: dataset.hidden, <add> hidden: !chart.isDatasetVisible(i), <ide> lineCap: dataset.borderCapStyle, <ide> lineDash: dataset.borderDash, <ide> lineDashOffset: dataset.borderDashOffset, <ide><path>src/core/core.tooltip.js <ide> module.exports = function(Chart) { <ide> tooltipPosition = this.getAveragePosition(this._active); <ide> } else { <ide> helpers.each(this._data.datasets, function(dataset, datasetIndex) { <del> if (!helpers.isDatasetVisible(dataset)) { <add> if (!this._chartInstance.isDatasetVisible(datasetIndex)) { <ide> return; <ide> } <ide> <ide><path>src/scales/scale.linear.js <ide> module.exports = function(Chart) { <ide> var positiveValues = valuesPerType[meta.type].positiveValues; <ide> var negativeValues = valuesPerType[meta.type].negativeValues; <ide> <del> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <add> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> <ide> var value = +this.getRightValue(rawValue); <ide> module.exports = function(Chart) { <ide> } else { <ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <ide> var meta = this.chart.getDatasetMeta(datasetIndex); <del> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <add> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var value = +this.getRightValue(rawValue); <ide> if (isNaN(value)) { <ide><path>src/scales/scale.logarithmic.js <ide> module.exports = function(Chart) { <ide> <ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <ide> var meta = this.chart.getDatasetMeta(datasetIndex); <del> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <add> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <ide> if (valuesPerType[meta.type] === undefined) { <ide> valuesPerType[meta.type] = []; <ide> } <ide> module.exports = function(Chart) { <ide> } else { <ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <ide> var meta = this.chart.getDatasetMeta(datasetIndex); <del> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <add> if (this.chart.isDatasetVisible(dataset, datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var value = +this.getRightValue(rawValue); <ide> if (isNaN(value)) { <ide><path>src/scales/scale.radialLinear.js <ide> module.exports = function(Chart) { <ide> this.min = null; <ide> this.max = null; <ide> <del> helpers.each(this.chart.data.datasets, function(dataset) { <del> if (helpers.isDatasetVisible(dataset)) { <add> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <add> if (this.chart.isDatasetVisible(datasetIndex)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var value = +this.getRightValue(rawValue); <ide> if (isNaN(value)) { <ide> module.exports = function(Chart) { <ide> } <ide> // Extra 3px out for some label spacing <ide> var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5); <del> <add> <ide> var pointLabelFontColor = helpers.getValueOrDefault(this.options.pointLabels.fontColor, Chart.defaults.global.defaultFontColor); <ide> var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); <ide> var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle);
11
PHP
PHP
apply suggestions from code review
56a2773ac99060ebc1529e6528189ce313fe5abb
<ide><path>src/Cache/Cache.php <ide> * There are 7 built-in caching engines: <ide> * <ide> * - `ApcuEngine` - Uses the APCu object cache, one of the fastest caching engines. <del> * - `ArrayEngine` - Uses only memory to store all data, not actually a persistent engin. <del> * Can be useful in test or CLI enviroment. <add> * - `ArrayEngine` - Uses only memory to store all data, not actually a persistent engine. <add> * Can be useful in test or CLI environment. <ide> * - `FileEngine` - Uses simple files to store content. Poor performance, but good for <ide> * storing large objects, or things that are not IO sensitive. Well suited to development <ide> * as it is an easy cache to inspect and manually flush.
1
Ruby
Ruby
store the object itself in the failed download set
c5885757e5586cb69c4d9a09d66772ea712c89bb
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch_patch p <ide> <ide> def retry_fetch? f <ide> @fetch_failed ||= Set.new <del> if ARGV.include?("--retry") && @fetch_failed.add?(f.name) <add> if ARGV.include?("--retry") && @fetch_failed.add?(f) <ide> ohai "Retrying download" <ide> f.clear_cache <ide> true
1
Javascript
Javascript
add test for
432a2e4d397908965cfbdc44eb8a10c7fb840701
<ide><path>test/simple/test-http-parser-bad-ref.js <add>// Run this program with valgrind or efence with --expose_gc to expose the <add>// problem. <add> <add>// Flags: --expose_gc <add> <add>var assert = require('assert'); <add>var HTTPParser = process.binding('http_parser').HTTPParser; <add> <add>var headersComplete = 0; <add>var messagesComplete = 0; <add> <add>function flushPool() { <add> new Buffer(Buffer.poolSize - 1); <add> gc(); <add>} <add> <add>function demoBug(part1, part2) { <add> var parser = new HTTPParser('REQUEST'); <add> <add> parser.headers = []; <add> parser.url = ''; <add> <add> parser.onHeaders = function(headers, url) { <add> parser.headers = parser.headers.concat(headers); <add> parser.url += url; <add> }; <add> <add> parser.onHeadersComplete = function(info) { <add> headersComplete++; <add> console.log("url", info.url); <add> }; <add> <add> parser.onBody = function(b, start, len) { }; <add> <add> parser.onMessageComplete = function() { <add> messagesComplete++; <add> }; <add> <add> <add> // We use a function to eliminate references to the Buffer b <add> // We want b to be GCed. The parser will hold a bad reference to it. <add> (function() { <add> var b = Buffer(part1); <add> flushPool(); <add> <add> console.log("parse the first part of the message"); <add> parser.execute(b, 0, b.length); <add> })(); <add> <add> flushPool(); <add> <add> (function() { <add> var b = Buffer(part2); <add> <add> console.log("parse the second part of the message"); <add> parser.execute(b, 0, b.length); <add> parser.finish(); <add> })(); <add>} <add> <add> <add>demoBug('POST /1', '/22 HTTP/1.1\r\n' + <add> 'Content-Type: text/plain\r\n' + <add> 'Content-Length: 4\r\n\r\n' + <add> 'pong'); <add> <add> <add>process.on('exit', function() { <add> assert.equal(1, headersComplete); <add> assert.equal(1, messagesComplete); <add> console.log("done!"); <add>});
1
Ruby
Ruby
fix typos [ci-skip]
5fdbd217d18302cd277f80a9ba7fd567844ec324
<ide><path>actioncable/lib/action_cable/channel/naming.rb <ide> def channel_name <ide> end <ide> end <ide> <del> # Delegates to the class' <tt>channel_name</tt> <add> # Delegates to the class's <tt>channel_name</tt>. <ide> delegate :channel_name, to: :class <ide> end <ide> end <ide><path>actionpack/lib/abstract_controller/base.rb <ide> def process(action, *args) <ide> process_action(action_name, *args) <ide> end <ide> <del> # Delegates to the class' ::controller_path <add> # Delegates to the class's ::controller_path. <ide> def controller_path <ide> self.class.controller_path <ide> end <ide> <del> # Delegates to the class' ::action_methods <add> # Delegates to the class's ::action_methods. <ide> def action_methods <ide> self.class.action_methods <ide> end <ide><path>actionpack/lib/action_controller/metal.rb <ide> def self.action_encoding_template(action) # :nodoc: <ide> false <ide> end <ide> <del> # Delegates to the class' <tt>controller_name</tt>. <add> # Delegates to the class's <tt>controller_name</tt>. <ide> def controller_name <ide> self.class.controller_name <ide> end <ide><path>actionpack/lib/action_controller/metal/conditional_get.rb <ide> def stale?(object = nil, **freshness_kwargs) <ide> # expires_in 3.hours, public: true, stale_while_revalidate: 60.seconds, stale_if_error: 5.minutes <ide> # <ide> # HTTP Cache-Control Extensions other values: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control <del> # Any additional key-value pairs are concatenated onto the `Cache-Control` header in the response: <add> # Any additional key-value pairs are concatenated onto the Cache-Control header in the response: <ide> # <ide> # expires_in 3.hours, public: true, "s-maxage": 3.hours, "no-transform": true <ide> # <ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> def authenticate_or_request_with_http_digest(realm = "Application", message = ni <ide> authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm, message) <ide> end <ide> <del> # Authenticate with HTTP Digest, returns true or false <add> # Authenticate with HTTP \Digest. Returns true or false. <ide> def authenticate_with_http_digest(realm = "Application", &password_procedure) <ide> HttpAuthentication::Digest.authenticate(request, realm, &password_procedure) <ide> end <ide> <del> # Render output including the HTTP Digest authentication header <add> # Render output including the HTTP \Digest authentication header. <ide> def request_http_digest_authentication(realm = "Application", message = nil) <ide> HttpAuthentication::Digest.authentication_request(self, realm, message) <ide> end <ide> end <ide> <del> # Returns false on a valid response, true otherwise <add> # Returns false on a valid response, true otherwise. <ide> def authenticate(request, realm, &password_procedure) <ide> request.authorization && validate_digest_response(request, realm, &password_procedure) <ide> end <ide> def token_params_from(auth) <ide> rewrite_param_values params_array_from raw_params auth <ide> end <ide> <del> # Takes raw_params and turns it into an array of parameters <add> # Takes raw_params and turns it into an array of parameters. <ide> def params_array_from(raw_params) <ide> raw_params.map { |param| param.split %r/=(.+)?/ } <ide> end <ide><path>actionview/lib/action_view/helpers/text_helper.rb <ide> def word_wrap(text, line_width: 80, break_sequence: "\n") <ide> end <ide> <ide> # Returns +text+ transformed into HTML using simple formatting rules. <del> # Two or more consecutive newlines(<tt>\n\n</tt> or <tt>\r\n\r\n</tt>) are <add> # Two or more consecutive newlines (<tt>\n\n</tt> or <tt>\r\n\r\n</tt>) are <ide> # considered a paragraph and wrapped in <tt><p></tt> tags. One newline <ide> # (<tt>\n</tt> or <tt>\r\n</tt>) is considered a linebreak and a <ide> # <tt><br /></tt> tag is appended. This method does not remove the <ide><path>actionview/lib/action_view/layouts.rb <ide> module ActionView <ide> # be rendered directly, without wrapping a layout around the rendered view. <ide> # <ide> # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so <del> # #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>. <add> # <tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>. <ide> # <ide> # == Using a different layout in the action render call <ide> # <ide> def _conditional_layout? <ide> # <ide> # Return value of +Proc+ and +Symbol+ arguments should be +String+, +false+, +true+ or +nil+ <ide> # with the same meaning as described above. <add> # <ide> # ==== Parameters <add> # <ide> # * <tt>layout</tt> - The layout to use. <ide> # <ide> # ==== Options (conditions) <add> # <ide> # * :only - A list of actions to apply this layout to. <ide> # * :except - Apply this layout to all actions but this one. <ide> def layout(layout, conditions = {}) <ide><path>activemodel/lib/active_model/errors.rb <ide> def copy!(other) # :nodoc: <ide> } <ide> end <ide> <del> # Imports one error <add> # Imports one error. <ide> # Imported errors are wrapped as a NestedError, <ide> # providing access to original error object. <ide> # If attribute or type needs to be overridden, use +override_options+. <ide> # <ide> # override_options - Hash <del> # @option override_options [Symbol] :attribute Override the attribute the error belongs to <add> # @option override_options [Symbol] :attribute Override the attribute the error belongs to. <ide> # @option override_options [Symbol] :type Override type of the error. <ide> def import(error, override_options = {}) <ide> [:attribute, :type].each do |key| <ide><path>activemodel/lib/active_model/type/boolean.rb <ide> module Type <ide> # A class that behaves like a boolean type, including rules for coercion of <ide> # user input. <ide> # <del> # - <tt>"false"</tt>, <tt>"f"</tt> , <tt>"0"</tt>, +0+ or any other value in <add> # - <tt>"false"</tt>, <tt>"f"</tt>, <tt>"0"</tt>, +0+ or any other value in <ide> # +FALSE_VALUES+ will be coerced to +false+. <ide> # - Empty strings are coerced to +nil+. <ide> # - All other values will be coerced to +true+. <ide><path>activemodel/lib/active_model/validations.rb <ide> def clear_validators! <ide> # class Person <ide> # include ActiveModel::Validations <ide> # <del> # attr_accessor :name , :age <add> # attr_accessor :name, :age <ide> # <ide> # validates_presence_of :name <ide> # validates_inclusion_of :age, in: 0..99 <ide><path>activemodel/lib/active_model/validations/absence.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_absence_of(*attr_names) <ide> validates_with AbsenceValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/callbacks.rb <ide> def set_options_for_callback(options) <ide> end <ide> <ide> private <del> # Overwrite run validations to include callbacks. <add> # Overwrite run_validations! to include callbacks. <ide> def run_validations! <ide> _run_validation_callbacks { super } <ide> end <ide><path>activemodel/lib/active_model/validations/comparison.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ . <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> # <ide> # The validator requires at least one of the following checks to be supplied. <ide> # Each will accept a proc, value, or a symbol which corresponds to a method: <ide><path>activemodel/lib/active_model/validations/confirmation.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_confirmation_of(*attr_names) <ide> validates_with ConfirmationValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/exclusion.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_exclusion_of(*attr_names) <ide> validates_with ExclusionValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/format.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_format_of(*attr_names) <ide> validates_with FormatValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/inclusion.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_inclusion_of(*attr_names) <ide> validates_with InclusionValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/length.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+ and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_length_of(*attr_names) <ide> validates_with LengthValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ . <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> # <ide> # The following checks can also be supplied with a proc or a symbol which <ide> # corresponds to a method: <ide><path>activemodel/lib/active_model/validations/presence.rb <ide> module HelperMethods <ide> # <ide> # There is also a list of default options supported by every validator: <ide> # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. <del> # See <tt>ActiveModel::Validations#validates</tt> for more information <add> # See <tt>ActiveModel::Validations#validates</tt> for more information. <ide> def validates_presence_of(*attr_names) <ide> validates_with PresenceValidator, _merge_attributes(attr_names) <ide> end <ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def delete(*records) <ide> end <ide> <ide> # Deletes the +records+ and removes them from this association calling <del> # +before_remove+ , +after_remove+ , +before_destroy+ and +after_destroy+ callbacks. <add> # +before_remove+, +after_remove+, +before_destroy+ and +after_destroy+ callbacks. <ide> # <ide> # Note that this method removes records from the database ignoring the <ide> # +:dependent+ option. <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> def delete_all(dependent = nil) <ide> <ide> # Deletes the records of the collection directly from the database <ide> # ignoring the +:dependent+ option. Records are instantiated and it <del> # invokes +before_remove+, +after_remove+ , +before_destroy+ and <add> # invokes +before_remove+, +after_remove+, +before_destroy+ and <ide> # +after_destroy+ callbacks. <ide> # <ide> # class Person < ActiveRecord::Base <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def connection_class # :nodoc: <ide> @pool.connection_class <ide> end <ide> <del> # The role (ie :writing) for the current connection. In a <add> # The role (e.g. +:writing+) for the current connection. In a <ide> # non-multi role application, `:writing` is returned. <ide> def role <ide> @pool.role <ide> end <ide> <del> # The shard (ie :default) for the current connection. In <add> # The shard (e.g. +:default+) for the current connection. In <ide> # a non-sharded application, `:default` is returned. <ide> def shard <ide> @pool.shard <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def new_client(conn_params) <ide> <ide> ## <ide> # :singleton-method: <del> # PostgreSQL supports multiple types for DateTimes. By default if you use `datetime` <add> # PostgreSQL supports multiple types for DateTimes. By default, if you use `datetime` <ide> # in migrations, Rails will translate this to a PostgreSQL "timestamp without time zone". <ide> # Change this in an initializer to use another NATIVE_DATABASE_TYPES. For example, to <ide> # store DateTimes as "timestamp with time zone": <ide><path>activerecord/lib/active_record/connection_handling.rb <ide> def connects_to(database: {}, shards: {}) <ide> connections <ide> end <ide> <del> # Connects to a role (ex writing, reading or a custom role) and/or <add> # Connects to a role (e.g. writing, reading or a custom role) and/or <ide> # shard for the duration of the block. At the end of the block the <ide> # connection will be returned to the original role / shard. <ide> # <ide><path>activerecord/lib/active_record/encryption/encryptor.rb <ide> class Encryptor <ide> # <ide> # [:key_provider] <ide> # Key provider to use for the encryption operation. It will default to <del> # +ActiveRecord::Encryption.key_provider+ when not provided <add> # +ActiveRecord::Encryption.key_provider+ when not provided. <ide> # <ide> # [:cipher_options] <ide> # +Cipher+-specific options that will be passed to the Cipher configured in <ide><path>activerecord/lib/active_record/encryption/envelope_encryption_key_provider.rb <ide> module ActiveRecord <ide> module Encryption <ide> # Implements a simple envelope encryption approach where: <ide> # <del> # * It generates a random data-encryption key for each encryption operation <add> # * It generates a random data-encryption key for each encryption operation. <ide> # * It stores the generated key along with the encrypted payload. It encrypts this key <del> # with the master key provided in the credential +active_record.encryption.master key+ <add> # with the master key provided in the credential +active_record.encryption.master key+. <ide> # <ide> # This provider can work with multiple master keys. It will use the last one for encrypting. <ide> # <ide><path>activerecord/lib/active_record/encryption/extended_deterministic_queries.rb <ide> module ActiveRecord <ide> module Encryption <ide> # Automatically expand encrypted arguments to support querying both encrypted and unencrypted data <ide> # <del> # Active Record Encryption supports querying the db using deterministic attributes. For example: <add> # Active Record \Encryption supports querying the db using deterministic attributes. For example: <ide> # <ide> # Contact.find_by(email_address: "[email protected]") <ide> # <ide><path>activerecord/lib/active_record/migration.rb <ide> def self.valid_version_format?(version_string) # :nodoc: <ide> end <ide> <ide> # This class is used to verify that all migrations have been run before <del> # loading a web page if <tt>config.active_record.migration_error</tt> is set to :page_load <add> # loading a web page if <tt>config.active_record.migration_error</tt> is set to :page_load. <ide> class CheckPending <ide> def initialize(app, file_watcher: ActiveSupport::FileUpdateChecker) <ide> @app = app <ide><path>activerecord/lib/active_record/model_schema.rb <ide> def compute_table_name <ide> <ide> "#{full_table_name_prefix}#{contained}#{undecorated_table_name(model_name)}#{full_table_name_suffix}" <ide> else <del> # STI subclasses always use their superclass' table. <add> # STI subclasses always use their superclass's table. <ide> base_class.table_name <ide> end <ide> end <ide><path>activerecord/lib/active_record/relation.rb <ide> def delete_by(*args) <ide> # for queries to actually be executed concurrently. Otherwise it defaults to <ide> # executing them in the foreground. <ide> # <del> # +load_async+ will also fallback to executing in the foreground in the test environment when transactional <add> # +load_async+ will also fall back to executing in the foreground in the test environment when transactional <ide> # fixtures are enabled. <ide> # <ide> # If the query was actually executed in the background, the Active Record logs will show <ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def #{method_name}=(value) # def includes_values=(value) <ide> # <ide> # users = User.includes(:address, friends: [:address, :followers]) <ide> # <del> # === conditions <add> # === Conditions <ide> # <ide> # If you want to add string conditions to your included models, you'll have <ide> # to explicitly reference them. For example: <ide><path>activesupport/lib/active_support/callbacks.rb <ide> def invoke_after(arg) <ide> end <ide> end <ide> <del> class CallbackChain # :nodoc:# <add> class CallbackChain # :nodoc: <ide> include Enumerable <ide> <ide> attr_reader :name, :config <ide><path>activesupport/lib/active_support/core_ext/date/conversions.rb <ide> def readable_inspect <ide> # date.to_time(:utc) # => 2007-11-10 00:00:00 UTC <ide> # <ide> # NOTE: The :local timezone is Ruby's *process* timezone, i.e. ENV['TZ']. <del> # If the *application's* timezone is needed, then use +in_time_zone+ instead. <add> # If the <b>application's</b> timezone is needed, then use +in_time_zone+ instead. <ide> def to_time(form = :local) <ide> raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form) <ide> ::Time.public_send(form, year, month, day) <ide><path>activesupport/lib/active_support/core_ext/date_and_time/calculations.rb <ide> def next_weekday <ide> end <ide> end <ide> <del> # Short-hand for months_since(3) <add> # Short-hand for months_since(3). <ide> def next_quarter <ide> months_since(3) <ide> end <ide><path>activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb <ide> # of the module. <ide> # <ide> # Note that it can also be scoped per-fiber if Rails.application.config.active_support.isolation_level <del># is set to `:fiber` <add># is set to `:fiber`. <ide> class Module <ide> # Defines a per-thread class attribute and creates class and instance reader methods. <ide> # The underlying per-thread class variable is set to +nil+, if it is not previously defined. <ide> class Module <ide> # <ide> # Current.user = "DHH" <ide> # Current.user # => "DHH" <del> # Thread.new { Current.user }.values # => nil <add> # Thread.new { Current.user }.value # => nil <ide> # <ide> # The attribute name must be a valid method name in Ruby. <ide> # <ide><path>activesupport/lib/active_support/error_reporter.rb <ide> module ActiveSupport <ide> # <ide> # Additionally a +severity+ can be passed along to communicate how important the error report is. <ide> # +severity+ can be one of +:error+, +:warning+ or +:info+. Handled errors default to the +:warning+ <del> # severity, and unhandled ones to +error+. <add> # severity, and unhandled ones to +:error+. <ide> # <ide> # Both +handle+ and +record+ pass through the return value from the block. In the case of +handle+ <ide> # rescuing an error, a fallback can be provided. The fallback must be a callable whose result will <ide><path>activesupport/lib/active_support/evented_file_update_checker.rb <ide> <ide> module ActiveSupport <ide> # Allows you to "listen" to changes in a file system. <del> # The evented file updater does not hit disk when checking for updates <del> # instead it uses platform specific file system events to trigger a change <add> # The evented file updater does not hit disk when checking for updates. <add> # Instead, it uses platform-specific file system events to trigger a change <ide> # in state. <ide> # <ide> # The file checker takes an array of files to watch or a hash specifying directories <ide><path>activesupport/lib/active_support/inflector/transliterate.rb <ide> module Inflector <ide> # transliterate('Jürgen', locale: :de) <ide> # # => "Juergen" <ide> # <del> # Transliteration is restricted to UTF-8, US-ASCII and GB18030 strings <add> # Transliteration is restricted to UTF-8, US-ASCII and GB18030 strings. <ide> # Other encodings will raise an ArgumentError. <ide> def transliterate(string, replacement = "?", locale: nil) <ide> string = string.dup if string.frozen? <ide><path>activesupport/lib/active_support/log_subscriber/test_helper.rb <ide> class LogSubscriber <ide> # <ide> # All you need to do is to ensure that your log subscriber is added to <ide> # Rails::Subscriber, as in the second line of the code above. The test <del> # helpers are responsible for setting up the queue, subscriptions and <add> # helpers are responsible for setting up the queue and subscriptions, and <ide> # turning colors in logs off. <ide> # <ide> # The messages are available in the @logger instance, which is a logger with <ide><path>activesupport/lib/active_support/message_encryptor.rb <ide> module ActiveSupport <ide> # crypt = ActiveSupport::MessageEncryptor.new(key) # => #<ActiveSupport::MessageEncryptor ...> <ide> # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..." <ide> # crypt.decrypt_and_verify(encrypted_data) # => "my secret data" <add> # <ide> # The +decrypt_and_verify+ method will raise an <ide> # <tt>ActiveSupport::MessageEncryptor::InvalidMessage</tt> exception if the data <ide> # provided cannot be decrypted or verified. <ide><path>activesupport/lib/active_support/notifications.rb <ide> require "active_support/notifications/fanout" <ide> <ide> module ActiveSupport <del> # = Notifications <add> # = \Notifications <ide> # <ide> # <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for <ide> # Ruby. <ide><path>railties/lib/rails/application.rb <ide> module Rails <ide> # Rails::Application::Bootstrap) and finishing initializers, after all the others <ide> # are executed (check Rails::Application::Finisher). <ide> # <del> # == Configuration <add> # == \Configuration <ide> # <ide> # Besides providing the same configuration as Rails::Engine and Rails::Railtie, <ide> # the application object has several specific configurations, for example <ide> module Rails <ide> # 5) Load config/environments/ENV.rb <ide> # 6) Run config.before_initialize callbacks <ide> # 7) Run Railtie#initializer defined by railties, engines and application. <del> # One by one, each engine sets up its load paths, routes and runs its config/initializers/* files. <add> # One by one, each engine sets up its load paths and routes, and runs its config/initializers/* files. <ide> # 8) Custom Railtie#initializers added by railties, engines and applications are executed <ide> # 9) Build the middleware stack and run to_prepare callbacks <ide> # 10) Run config.before_eager_load and eager_load! if eager_load is true <ide><path>railties/lib/rails/console/helpers.rb <ide> module Rails <ide> module ConsoleMethods <ide> # Gets the helper methods available to the controller. <ide> # <del> # This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+ <add> # This method assumes an +ApplicationController+ exists, and that it extends +ActionController::Base+. <ide> def helper <ide> ApplicationController.helpers <ide> end <ide> <ide> # Gets a new instance of a controller object. <ide> # <del> # This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+ <add> # This method assumes an +ApplicationController+ exists, and that it extends +ActionController::Base+. <ide> def controller <ide> @controller ||= ApplicationController.new <ide> end <ide><path>railties/lib/rails/engine.rb <ide> module Rails <ide> # end <ide> # <ide> # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt> <del> # (or in your +Gemfile+) and it will automatically load models, controllers and helpers <add> # (or in your +Gemfile+), and it will automatically load models, controllers and helpers <ide> # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at <ide> # <tt>config/locales/**/*</tt>, and load tasks at <tt>lib/tasks/**/*</tt>. <ide> # <ide> def load_runner(app = self) <ide> self <ide> end <ide> <del> # Load Rake, railties tasks and invoke the registered hooks. <add> # Load Rake and railties tasks, and invoke the registered hooks. <ide> # Check <tt>Rails::Railtie.rake_tasks</tt> for more info. <ide> def load_tasks(app = self) <ide> require "rake"
45
Ruby
Ruby
add comment about error pipe (mis)behavior
1b6f23c8a96fcb78163ba5a58a5e0e342d390663
<ide><path>Library/Homebrew/build.rb <ide> # can be inconvenient for the user. But we need to be safe. <ide> system "/usr/bin/sudo -k" <ide> <add> # The main Homebrew process expects to eventually see EOF on the error <add> # pipe in FormulaInstaller#build. However, if any child process fails to <add> # terminate (i.e, fails to close the descriptor), this won't happen, and <add> # the installer will hang. Set close-on-exec to prevent this. <add> # Whether it is *wise* to launch daemons from formulae is a separate <add> # question altogether. <ide> if ENV['HOMEBREW_ERROR_PIPE'] <ide> require 'fcntl' <ide> IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w').fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
1
Python
Python
add unit tests for samba provider
f149ca9ecf8c11e683606831578bb94aa364c60b
<ide><path>tests/providers/samba/__init__.py <add># <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <ide><path>tests/providers/samba/hooks/__init__.py <add># <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <ide><path>tests/providers/samba/hooks/test_samba.py <add># <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import unittest <add>from unittest.mock import call <add> <add>import mock <add>import smbclient <add> <add>from airflow.exceptions import AirflowException <add>from airflow.models import Connection <add>from airflow.providers.samba.hooks.samba import SambaHook <add> <add>connection = Connection(host='ip', schema='share', login='username', password='password') <add> <add> <add>class TestSambaHook(unittest.TestCase): <add> def test_get_conn_should_fail_if_conn_id_does_not_exist(self): <add> with self.assertRaises(AirflowException): <add> SambaHook('conn') <add> <add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection') <add> def test_get_conn(self, get_conn_mock): <add> get_conn_mock.return_value = connection <add> hook = SambaHook('samba_default') <add> <add> self.assertEqual(smbclient.SambaClient, type(hook.get_conn())) <add> get_conn_mock.assert_called_once_with('samba_default') <add> <add> @mock.patch('airflow.providers.samba.hooks.samba.SambaHook.get_conn') <add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection') <add> def test_push_from_local_should_succeed_if_destination_has_same_name_but_not_a_file(self, base_conn_mock, <add> samba_hook_mock): <add> base_conn_mock.return_value = connection <add> samba_hook_mock.get_conn.return_value = mock.Mock() <add> <add> samba_hook_mock.return_value.exists.return_value = True <add> samba_hook_mock.return_value.isfile.return_value = False <add> samba_hook_mock.return_value.exists.return_value = True <add> <add> hook = SambaHook('samba_default') <add> destination_filepath = "/path/to/dest/file" <add> local_filepath = "/path/to/local/file" <add> hook.push_from_local(destination_filepath=destination_filepath, local_filepath=local_filepath) <add> <add> base_conn_mock.assert_called_once_with('samba_default') <add> samba_hook_mock.assert_called_once() <add> samba_hook_mock.return_value.exists.assert_called_once_with(destination_filepath) <add> samba_hook_mock.return_value.isfile.assert_called_once_with(destination_filepath) <add> samba_hook_mock.return_value.remove.assert_not_called() <add> samba_hook_mock.return_value.upload.assert_called_once_with(local_filepath, destination_filepath) <add> <add> @mock.patch('airflow.providers.samba.hooks.samba.SambaHook.get_conn') <add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection') <add> def test_push_from_local_should_delete_file_if_exists_and_save_file(self, base_conn_mock, <add> samba_hook_mock): <add> base_conn_mock.return_value = connection <add> samba_hook_mock.get_conn.return_value = mock.Mock() <add> <add> samba_hook_mock.return_value.exists.return_value = False <add> samba_hook_mock.return_value.exists.return_value = False <add> <add> hook = SambaHook('samba_default') <add> destination_folder = "/path/to/dest" <add> destination_filepath = destination_folder + "/file" <add> local_filepath = "/path/to/local/file" <add> hook.push_from_local(destination_filepath=destination_filepath, local_filepath=local_filepath) <add> <add> base_conn_mock.assert_called_once_with('samba_default') <add> samba_hook_mock.assert_called_once() <add> samba_hook_mock.return_value.exists.assert_has_calls([call(destination_filepath), <add> call(destination_folder)]) <add> samba_hook_mock.return_value.isfile.assert_not_called() <add> samba_hook_mock.return_value.remove.assert_not_called() <add> samba_hook_mock.return_value.mkdir.assert_called_once_with(destination_folder) <add> samba_hook_mock.return_value.upload.assert_called_once_with(local_filepath, destination_filepath) <add> <add> @mock.patch('airflow.providers.samba.hooks.samba.SambaHook.get_conn') <add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection') <add> def test_push_from_local_should_create_directory_if_not_exist_and_save_file(self, base_conn_mock, <add> samba_hook_mock): <add> base_conn_mock.return_value = connection <add> samba_hook_mock.get_conn.return_value = mock.Mock() <add> <add> samba_hook_mock.return_value.exists.return_value = False <add> samba_hook_mock.return_value.exists.return_value = False <add> <add> hook = SambaHook('samba_default') <add> destination_folder = "/path/to/dest" <add> destination_filepath = destination_folder + "/file" <add> local_filepath = "/path/to/local/file" <add> hook.push_from_local(destination_filepath=destination_filepath, local_filepath=local_filepath) <add> <add> base_conn_mock.assert_called_once_with('samba_default') <add> samba_hook_mock.assert_called_once() <add> samba_hook_mock.return_value.exists.assert_has_calls([call(destination_filepath), <add> call(destination_folder)]) <add> samba_hook_mock.return_value.isfile.assert_not_called() <add> samba_hook_mock.return_value.remove.assert_not_called() <add> samba_hook_mock.return_value.mkdir.assert_called_once_with(destination_folder) <add> samba_hook_mock.return_value.upload.assert_called_once_with(local_filepath, destination_filepath) <ide><path>tests/test_project_structure.py <ide> 'tests/providers/google/cloud/utils/test_mlengine_prediction_summary.py', <ide> 'tests/providers/microsoft/azure/sensors/test_azure_cosmos.py', <ide> 'tests/providers/microsoft/azure/log/test_wasb_task_handler.py', <del> 'tests/providers/samba/hooks/test_samba.py' <ide> } <ide> <ide>
4
Go
Go
add restrictions to proc in libcontainer
60a90970bc4add3547064004f08c19ab5027141b
<ide><path>daemon/execdriver/native/create.go <ide> func (d *driver) createContainer(c *execdriver.Command) (*libcontainer.Container <ide> container.Cgroups.Name = c.ID <ide> // check to see if we are running in ramdisk to disable pivot root <ide> container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != "" <add> container.Context["restriction_path"] = d.restrictionPath <ide> <ide> if err := d.createNetwork(container, c); err != nil { <ide> return nil, err <ide> func (d *driver) setPrivileged(container *libcontainer.Container) error { <ide> c.Enabled = true <ide> } <ide> container.Cgroups.DeviceAccess = true <add> delete(container.Context, "restriction_path") <add> <ide> if apparmor.IsEnabled() { <ide> container.Context["apparmor_profile"] = "unconfined" <ide> } <ide><path>daemon/execdriver/native/driver.go <ide> type driver struct { <ide> root string <ide> initPath string <ide> activeContainers map[string]*exec.Cmd <add> restrictionPath string <ide> } <ide> <ide> func NewDriver(root, initPath string) (*driver, error) { <ide> func NewDriver(root, initPath string) (*driver, error) { <ide> if err := apparmor.InstallDefaultProfile(filepath.Join(root, "../..", BackupApparmorProfilePath)); err != nil { <ide> return nil, err <ide> } <add> restrictionPath := filepath.Join(root, "empty") <add> if err := os.MkdirAll(restrictionPath, 0700); err != nil { <add> return nil, err <add> } <add> <ide> return &driver{ <ide> root: root, <add> restrictionPath: restrictionPath, <ide> initPath: initPath, <ide> activeContainers: make(map[string]*exec.Cmd), <ide> }, nil <ide><path>pkg/libcontainer/nsinit/init.go <ide> func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consol <ide> <ide> label.Init() <ide> ns.logger.Println("setup mount namespace") <del> if err := setupNewMountNamespace(rootfs, container.Mounts, console, container.ReadonlyFs, container.NoPivotRoot, container.Context["mount_label"]); err != nil { <add> if err := setupNewMountNamespace(rootfs, console, container); err != nil { <ide> return fmt.Errorf("setup mount namespace %s", err) <ide> } <ide> if err := system.Sethostname(container.Hostname); err != nil { <ide><path>pkg/libcontainer/nsinit/mount.go <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/pkg/label" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <add> "github.com/dotcloud/docker/pkg/libcontainer/security/restrict" <ide> "github.com/dotcloud/docker/pkg/system" <ide> "io/ioutil" <ide> "os" <ide> const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NOD <ide> // <ide> // There is no need to unmount the new mounts because as soon as the mount namespace <ide> // is no longer in use, the mounts will be removed automatically <del>func setupNewMountNamespace(rootfs string, bindMounts []libcontainer.Mount, console string, readonly, noPivotRoot bool, mountLabel string) error { <add>func setupNewMountNamespace(rootfs, console string, container *libcontainer.Container) error { <ide> flag := syscall.MS_PRIVATE <del> if noPivotRoot { <add> if container.NoPivotRoot { <ide> flag = syscall.MS_SLAVE <ide> } <ide> if err := system.Mount("", "/", "", uintptr(flag|syscall.MS_REC), ""); err != nil { <ide> func setupNewMountNamespace(rootfs string, bindMounts []libcontainer.Mount, cons <ide> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, ""); err != nil { <ide> return fmt.Errorf("mouting %s as bind %s", rootfs, err) <ide> } <del> if err := mountSystem(rootfs, mountLabel); err != nil { <add> if err := mountSystem(rootfs, container.Context["mount_label"]); err != nil { <ide> return fmt.Errorf("mount system %s", err) <ide> } <del> <del> for _, m := range bindMounts { <del> var ( <del> flags = syscall.MS_BIND | syscall.MS_REC <del> dest = filepath.Join(rootfs, m.Destination) <del> ) <del> if !m.Writable { <del> flags = flags | syscall.MS_RDONLY <del> } <del> if err := system.Mount(m.Source, dest, "bind", uintptr(flags), ""); err != nil { <del> return fmt.Errorf("mounting %s into %s %s", m.Source, dest, err) <del> } <del> if !m.Writable { <del> if err := system.Mount(m.Source, dest, "bind", uintptr(flags|syscall.MS_REMOUNT), ""); err != nil { <del> return fmt.Errorf("remounting %s into %s %s", m.Source, dest, err) <del> } <del> } <del> if m.Private { <del> if err := system.Mount("", dest, "none", uintptr(syscall.MS_PRIVATE), ""); err != nil { <del> return fmt.Errorf("mounting %s private %s", dest, err) <del> } <add> if err := setupBindmounts(rootfs, container.Mounts); err != nil { <add> return fmt.Errorf("bind mounts %s", err) <add> } <add> if restrictionPath := container.Context["restriction_path"]; restrictionPath != "" { <add> if err := restrict.Restrict(rootfs, restrictionPath); err != nil { <add> return fmt.Errorf("restrict %s", err) <ide> } <ide> } <del> <ide> if err := copyDevNodes(rootfs); err != nil { <ide> return fmt.Errorf("copy dev nodes %s", err) <ide> } <del> if err := setupPtmx(rootfs, console, mountLabel); err != nil { <add> if err := setupPtmx(rootfs, console, container.Context["mount_label"]); err != nil { <ide> return err <ide> } <ide> if err := system.Chdir(rootfs); err != nil { <ide> return fmt.Errorf("chdir into %s %s", rootfs, err) <ide> } <ide> <del> if noPivotRoot { <add> if container.NoPivotRoot { <ide> if err := rootMsMove(rootfs); err != nil { <ide> return err <ide> } <ide> func setupNewMountNamespace(rootfs string, bindMounts []libcontainer.Mount, cons <ide> } <ide> } <ide> <del> if readonly { <add> if container.ReadonlyFs { <ide> if err := system.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, ""); err != nil { <ide> return fmt.Errorf("mounting %s as readonly %s", rootfs, err) <ide> } <ide> func remountSys() error { <ide> } <ide> return nil <ide> } <add> <add>func setupBindmounts(rootfs string, bindMounts []libcontainer.Mount) error { <add> for _, m := range bindMounts { <add> var ( <add> flags = syscall.MS_BIND | syscall.MS_REC <add> dest = filepath.Join(rootfs, m.Destination) <add> ) <add> if !m.Writable { <add> flags = flags | syscall.MS_RDONLY <add> } <add> if err := system.Mount(m.Source, dest, "bind", uintptr(flags), ""); err != nil { <add> return fmt.Errorf("mounting %s into %s %s", m.Source, dest, err) <add> } <add> if !m.Writable { <add> if err := system.Mount(m.Source, dest, "bind", uintptr(flags|syscall.MS_REMOUNT), ""); err != nil { <add> return fmt.Errorf("remounting %s into %s %s", m.Source, dest, err) <add> } <add> } <add> if m.Private { <add> if err := system.Mount("", dest, "none", uintptr(syscall.MS_PRIVATE), ""); err != nil { <add> return fmt.Errorf("mounting %s private %s", dest, err) <add> } <add> } <add> } <add> return nil <add>} <ide><path>pkg/libcontainer/security/restrict/restrict.go <add>package restrict <add> <add>import ( <add> "fmt" <add> "github.com/dotcloud/docker/pkg/system" <add> "path/filepath" <add> "syscall" <add>) <add> <add>const flags = syscall.MS_BIND | syscall.MS_REC | syscall.MS_RDONLY <add> <add>var restrictions = map[string]string{ <add> // dirs <add> "/proc/sys": "", <add> "/proc/irq": "", <add> "/proc/acpi": "", <add> <add> // files <add> "/proc/sysrq-trigger": "/dev/null", <add> "/proc/kcore": "/dev/null", <add>} <add> <add>// Restrict locks down access to many areas of proc <add>// by using the asumption that the user does not have mount caps to <add>// revert the changes made here <add>func Restrict(rootfs, empty string) error { <add> for dest, source := range restrictions { <add> dest = filepath.Join(rootfs, dest) <add> <add> // we don't have a "/dev/null" for dirs so have the requester pass a dir <add> // for us to bind mount <add> switch source { <add> case "": <add> source = empty <add> default: <add> source = filepath.Join(rootfs, source) <add> } <add> if err := system.Mount(source, dest, "bind", flags, ""); err != nil { <add> return fmt.Errorf("unable to mount %s over %s %s", source, dest, err) <add> } <add> if err := system.Mount("", dest, "bind", flags|syscall.MS_REMOUNT, ""); err != nil { <add> return fmt.Errorf("unable to mount %s over %s %s", source, dest, err) <add> } <add> } <add> return nil <add>}
5
Python
Python
make create_cb_arglist work with py3 functions
dc9621d502c87ea78e1e68212724eb9ffcc2037c
<ide><path>numpy/f2py/cfuncs.py <ide> fprintf(stderr,\"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\\n\",(fun==NULL?\"NULL\":Py_TYPE(fun)->tp_name)); <ide> goto capi_fail; <ide> } <add>#if PY_VERSION_HEX >= 0x03000000 <add>\tif (PyObject_HasAttrString(tmp_fun,\"__code__\")) { <add>\t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) <add>#else <ide> \tif (PyObject_HasAttrString(tmp_fun,\"func_code\")) { <ide> \t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"func_code\"),\"co_argcount\")) <add>#endif <ide> \t\t\ttot = PyInt_AsLong(PyObject_GetAttrString(tmp,\"co_argcount\")) - di; <ide> \t\tPy_XDECREF(tmp); <ide> \t} <ide> \t/* Get the number of optional arguments */ <add>#if PY_VERSION_HEX >= 0x03000000 <add>\tif (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) <add>\t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) <add>#else <ide> \tif (PyObject_HasAttrString(tmp_fun,\"func_defaults\")) <ide> \t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"func_defaults\"))) <add>#endif <ide> \t\t\topt = PyTuple_Size(tmp); <ide> \t\tPy_XDECREF(tmp); <ide> \t/* Get the number of extra arguments */
1
Ruby
Ruby
use plugin name consistently
11862932ecfe528e7bc12c983e3b85b65350c24d
<ide><path>railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb <ide> def valid_const? <ide> elsif RESERVED_NAMES.include?(name) <ide> raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words." <ide> elsif Object.const_defined?(camelized) <del> raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another application name." <add> raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another plugin name." <ide> end <ide> end <ide>
1
PHP
PHP
fix cs error
725399b1f398fb403ab78e330313bedd2b4aded3
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php <ide> use Cake\ORM\Behavior\Translate\ShadowTableStrategy; <ide> use Cake\ORM\Behavior\TranslateBehavior; <ide> use Cake\Utility\Hash; <del>use Cake\Validation\Validator; <ide> use TestApp\Model\Entity\TranslateArticle; <ide> use TestApp\Model\Entity\TranslateBakedArticle; <ide>
1
Text
Text
add return values in crypto documentation
a3a106865a95665a3f2d8d7c03a1a12f1680a087
<ide><path>doc/api/crypto.md <ide> added: v0.11.14 <ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, <ide> `RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`. <ide> - `buffer` {Buffer | TypedArray | DataView} <add>- Returns: {Buffer} A new `Buffer` with the decrypted content. <ide> <ide> Decrypts `buffer` with `privateKey`. <ide> <ide> added: v1.1.0 <ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or <ide> `RSA_PKCS1_PADDING`. <ide> - `buffer` {Buffer | TypedArray | DataView} <add>- Returns: {Buffer} A new `Buffer` with the encrypted content. <ide> <ide> Encrypts `buffer` with `privateKey`. <ide> <ide> added: v1.1.0 <ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or <ide> `RSA_PKCS1_PADDING`. <ide> - `buffer` {Buffer | TypedArray | DataView} <add>- Returns: {Buffer} A new `Buffer` with the decrypted content. <ide> <ide> Decrypts `buffer` with `publicKey`. <ide> <ide> added: v0.11.14 <ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, <ide> `RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`. <ide> - `buffer` {Buffer | TypedArray | DataView} <add>- Returns: {Buffer} A new `Buffer` with the encrypted content. <ide> <ide> Encrypts the content of `buffer` with `publicKey` and returns a new <ide> [`Buffer`][] with encrypted content.
1
Ruby
Ruby
use github wrapper for private tap check
25c4e336f48c4f9d549efc5511d87788a99d291c
<ide><path>Library/Homebrew/cmd/tap.rb <ide> def install_tap user, repo <ide> link_tap_formula(files) <ide> puts "Tapped #{files.length} formula" <ide> <del> # Figure out if this repo is private <del> # curl will throw an exception if the repo is private (Github returns a 404) <del> begin <del> curl('-Ifso', '/dev/null', "https://api.github.com/repos/#{repouser}/homebrew-#{repo}") <del> rescue <del> puts <del> puts "It looks like you tapped a private repository" <del> puts "In order to not input your credentials every time" <del> puts "you can use git HTTP credential caching or issue the" <del> puts "following command:" <del> puts <del> puts " cd #{tapd}" <del> puts " git remote set-url origin [email protected]:#{repouser}/homebrew-#{repo}.git" <del> puts <add> if private_tap?(repouser, repo) then puts <<-EOS.undent <add> It looks like you tapped a private repository. To avoid entering your <add> credentials each time you update, you can use git HTTP credential caching <add> or issue the following command: <add> <add> cd #{tapd} <add> git remote set-url origin [email protected]:#{repouser}/homebrew-#{repo}.git <add> EOS <ide> end <ide> <ide> true <ide> def tap_args <ide> [$1, $3] <ide> end <ide> <add> def private_tap?(user, repo) <add> GitHub.private_repo?(user, "homebrew-#{repo}") <add> rescue GitHub::HTTPNotFoundError => e <add> true <add> rescue GitHub::Error <add> false <add> end <ide> end <ide> <ide> <ide><path>Library/Homebrew/utils.rb <ide> module GitHub extend self <ide> <ide> Error = Class.new(StandardError) <ide> RateLimitExceededError = Class.new(Error) <add> HTTPNotFoundError = Class.new(Error) <ide> <ide> def open url, headers={}, &block <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> def open url, headers={}, &block <ide> You may want to create an API token: https://github.com/settings/applications <ide> and then set HOMEBREW_GITHUB_API_TOKEN. <ide> EOS <add> elsif e.io.status.first == "404" <add> raise HTTPNotFoundError, e.message, e.backtrace <ide> else <ide> raise Error, e.message, e.backtrace <ide> end <ide> def find_pull_requests rx <ide> <ide> prs.each {|i| yield "#{i["title"]} (#{i["pull_request"]["html_url"]})" } <ide> end <add> <add> def private_repo?(user, repo) <add> uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}") <add> open(uri) { |json| json["private"] } <add> end <ide> end
2
Ruby
Ruby
add an operator to inequality
389c4fc2582ae42c32a20b7f6a6cb2c5680343fc
<ide><path>lib/arel/algebra/predicates.rb <ide> def complement <ide> Equality.new(operand1, operand2) <ide> end <ide> <add> def operator; :"!=" end <ide> def eval(row) <ide> operand1.eval(row) != operand2.eval(row) <ide> end <ide><path>spec/algebra/unit/predicates/inequality_spec.rb <ide> module Predicates <ide> @b = Inequality.new(right, left) <ide> end <ide> <add> describe 'operator' do <add> it "should have one" do <add> @a.operator.should == :"!=" <add> end <add> end <add> <ide> describe '==' do <ide> it "is equal to itself" do <ide> @a.should == @a
2
Java
Java
fix race in catalyst tests
294185ac328b1c9ae2da6331575d48fc1bb818ff
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java <ide> public void initializeWithInstance(CatalystInstance instance) { <ide> mBridgeIdleSignaler = new ReactBridgeIdleSignaler(); <ide> mInstance.addBridgeIdleDebugListener(mBridgeIdleSignaler); <ide> getContext().initializeWithInstance(mInstance); <del> ApplicationHolder.setApplication((Application) getContext().getApplicationContext()); <ide> } <ide> <ide> public boolean waitForBridgeIdle(long millis) { <ide> public void waitForBridgeAndUIIdle() { <ide> IDLE_TIMEOUT_MS); <ide> } <ide> <add> @Override <add> protected void setUp() throws Exception { <add> super.setUp(); <add> ApplicationHolder.setApplication((Application) getContext().getApplicationContext()); <add> } <add> <ide> @Override <ide> protected void tearDown() throws Exception { <ide> super.tearDown();
1
PHP
PHP
fix failing tests in isunique rule
86e24efc7d60643509c0e285c16515e86362fbff
<ide><path>src/ORM/Rule/IsUnique.php <ide> public function __invoke(EntityInterface $entity, array $options) <ide> if (!$entity->extract($this->_fields, true)) { <ide> return true; <ide> } <del> <del> $allowMultipleNulls = true; <del> if (isset($options['allowMultipleNulls'])) { <del> $allowMultipleNulls = $options['allowMultipleNulls'] === true ? true : false; <del> } <add> $options += ['allowMultipleNulls' => true]; <add> $allowMultipleNulls = $options['allowMultipleNulls']; <ide> <ide> $alias = $options['repository']->alias(); <del> $conditions = $this->_alias($alias, $entity->extract($this->_fields)); <add> $conditions = $this->_alias($alias, $entity->extract($this->_fields), $allowMultipleNulls); <ide> if ($entity->isNew() === false) { <ide> $keys = (array)$options['repository']->primaryKey(); <del> $keys = $this->_alias($alias, $entity->extract($keys)); <add> $keys = $this->_alias($alias, $entity->extract($keys), $allowMultipleNulls); <ide> if (array_filter($keys, 'strlen')) { <ide> $conditions['NOT'] = $keys; <ide> } <ide> public function __invoke(EntityInterface $entity, array $options) <ide> * <ide> * @param string $alias The alias to add. <ide> * @param array $conditions The conditions to alias. <add> * @param bool $multipleNulls Whether or not to allow multiple nulls. <ide> * @return array <ide> */ <del> protected function _alias($alias, $conditions) <add> protected function _alias($alias, $conditions, $multipleNulls) <ide> { <ide> $aliased = []; <ide> foreach ($conditions as $key => $value) { <del> $aliased["$alias.$key"] = $value; <add> if ($multipleNulls) { <add> $aliased["$alias.$key"] = $value; <add> } else { <add> $aliased["$alias.$key IS"] = $value; <add> } <ide> } <ide> return $aliased; <ide> }
1
Python
Python
add missing license header
e7957b13aff383f38c81f72296ec97c7622cf3bb
<ide><path>libcloud/test/container/test_lxd.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <ide> import sys <ide> <ide> from libcloud.test import unittest <ide> def _vlinux_124_containers_a68c1872c74630522c7aa74b85558b06824c5e672cee334296c50 <ide> """ <ide> <ide> if __name__ == '__main__': <del> sys.exit(unittest.main()) <ide>\ No newline at end of file <add> sys.exit(unittest.main())
1
Text
Text
move sebdeckers to emeritus
62c44af5c5f2964849bba92ff90c32e867d63f83
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Saúl Ibarra Corretgé** &lt;[email protected]&gt; <ide> * [santigimeno](https://github.com/santigimeno) - <ide> **Santiago Gimeno** &lt;[email protected]&gt; <del>* [sebdeckers](https://github.com/sebdeckers) - <del>**Sebastiaan Deckers** &lt;[email protected]&gt; <ide> * [seishun](https://github.com/seishun) - <ide> **Nikolai Vavilov** &lt;[email protected]&gt; <ide> * [shigeki](https://github.com/shigeki) - <ide> For information about the governance of the Node.js project, see <ide> **Ingvar Stepanyan** &lt;[email protected]&gt; <ide> * [sam-github](https://github.com/sam-github) - <ide> **Sam Roberts** &lt;[email protected]&gt; <add>* [sebdeckers](https://github.com/sebdeckers) - <add>**Sebastiaan Deckers** &lt;[email protected]&gt; <ide> * [stefanmb](https://github.com/stefanmb) - <ide> **Stefan Budeanu** &lt;[email protected]&gt; <ide> * [tellnes](https://github.com/tellnes) -
1
Python
Python
fix broken test
405b9dcd8b16fe923e1d4beadc8bb05906eaf7d5
<ide><path>tests/migrations/test_operations.py <ide> def test_add_field_ignore_swapped(self): <ide> project_state, new_state = self.make_test_state("test_adfligsw", operation) <ide> # Test the database alteration <ide> self.assertTableNotExists("test_adfligsw_pont") <del> self.assertColumnNotExists("test_adfligsw_pony", "height") <ide> with connection.schema_editor() as editor: <ide> operation.database_forwards("test_adfligsw", editor, project_state, new_state) <del> self.assertColumnNotExists("test_adfligsw_pony", "height") <add> self.assertTableNotExists("test_adfligsw_pont") <ide> # And test reversal <ide> with connection.schema_editor() as editor: <ide> operation.database_backwards("test_adfligsw", editor, new_state, project_state) <del> self.assertColumnNotExists("test_adfligsw_pony", "height") <add> self.assertTableNotExists("test_adfligsw_pont")
1
Python
Python
add control/msg to lib import
171d6d5b6bc79231a24eed3ea76ada912ace5a46
<ide><path>src/glances.py <ide> <ide> from __future__ import generators <ide> <add>import sys <add> <ide> try: <ide> import os <ide> import platform <ide> import getopt <del> import sys <ide> import signal <ide> import time <ide> import datetime <ide> import multiprocessing <ide> import gettext <del>except KeyboardInterrupt: <del> pass <add>except: <add> print "Error during Python libraries import:", sys.exc_info()[1] <add> sys.exit(1) <add> <ide> <ide> # Application informations <ide> #========================= <ide> <ide> application = 'glances' <del>__version__ = "1.4b5" <add>__version__ = "1.4b6" <ide> gettext.install(application) <ide> <ide> # Test methods
1
Python
Python
skip some gpt_neox tests that require 80g ram
14fb8a63b99326186951370828e2752857076df7
<ide><path>tests/models/gpt_neox/test_modeling_gpt_neox.py <ide> import unittest <ide> <ide> from transformers import GPTNeoXConfig, is_torch_available <del>from transformers.testing_utils import require_torch, slow, torch_device <add>from transformers.testing_utils import require_torch, torch_device <ide> <ide> from ...test_configuration_common import ConfigTester <ide> from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask <ide> import torch <ide> <ide> from transformers import GPTNeoXForCausalLM, GPTNeoXModel <del> from transformers.models.gpt_neox.modeling_gpt_neox import GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST <ide> <ide> <ide> class GPTNeoXModelTester: <ide> def test_model_for_causal_lm(self): <ide> @unittest.skip(reason="Feed forward chunking is not implemented") <ide> def test_feed_forward_chunking(self): <ide> pass <del> <del> @slow <del> def test_model_from_pretrained(self): <del> for model_name in GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: <del> model = GPTNeoXModel.from_pretrained(model_name) <del> self.assertIsNotNone(model) <del> <del> <del>@require_torch <del>class GPTNeoXModelIntegrationTest(unittest.TestCase): <del> @slow <del> def test_inference_masked_lm(self): <del> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b") <del> input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) <del> output = model(input_ids)[0] <del> <del> vocab_size = model.config.vocab_size <del> <del> expected_shape = torch.Size((1, 6, vocab_size)) <del> self.assertEqual(output.shape, expected_shape) <del> <del> expected_slice = torch.tensor( <del> [[[33.5938, 2.3789, 34.0312], [63.4688, 4.8164, 63.3438], [66.8750, 5.2422, 63.0625]]] <del> ) <del> <del> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
1
Ruby
Ruby
fix que integration in active job tests part 2
4eefa1feb00bac259201ba403088e747e69f9a55
<ide><path>activejob/test/support/que/inline.rb <ide> def self.enqueue(*args) <ide> run(*args) <ide> end <ide> end <add> <add>Que::ActiveJob::WrapperExtensions.class_eval do <add> def run(args) <add> super(args.deep_stringify_keys) <add> end <add>end
1
Python
Python
remove import of removed retryqueuemanager
ffa98aab1db925398d624fcf94641ac72665a8d1
<ide><path>celery/models.py <ide> from django.db import models <ide> from celery.registry import tasks <ide> from celery.managers import TaskManager, PeriodicTaskManager <del>from celery.managers import RetryQueueManager <ide> from yadayada.models import PickledObjectField <ide> from django.utils.translation import ugettext_lazy as _ <ide> from Queue import Queue
1
Text
Text
clarify sudoku solver instructions
594b63bc3571ec64c340fc57d5ea53e919350bb4
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md <ide> When you are done, make sure a working demo of your project is hosted somewhere <ide> <ide> # --instructions-- <ide> <del>- All puzzle logic can go into `/controllers/sudoku-solver.js` <del>- All routing logic can go into `/routes/api.js` <del>- See the `puzzle-strings.js` file in `/controllers` for some sample puzzles your application should solve <del>- To run the challenge tests on this page, set `NODE_ENV` to `test` without quotes in the `.env` file <del>- To run the tests in the console, use the command `npm run test`. To open the Repl.it console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell" <add>- All puzzle logic can go into `/controllers/sudoku-solver.js` <add> - The `validate` function should take a given puzzle string and check it to see if it has 81 valid characters for the input. <add> - The `check` functions should be validating against the *current* state of the board. <add> - The `solve` function should handle solving any given valid puzzle string, not just the test inputs and solutions. You are expected to write out the logic to solve this. <add>- All routing logic can go into `/routes/api.js` <add>- See the `puzzle-strings.js` file in `/controllers` for some sample puzzles your application should solve <add>- To run the challenge tests on this page, set `NODE_ENV` to `test` without quotes in the `.env` file <add>- To run the tests in the console, use the command `npm run test`. To open the Repl.it console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell" <ide> <ide> Write the following tests in `tests/1_unit-tests.js`: <ide>
1
Python
Python
catch a misc import error
8a4fb936484cf0ba8b5e76706dc9b52b535549af
<ide><path>numpy/f2py/__version__.py <ide> from __svn_version__ import version <ide> version_info = (major, version) <ide> version = '%s_%s' % version_info <del>except ImportError: <add>except (ImportError, ValueError): <ide> version = str(major)
1
Text
Text
change links to doc instead of js
78f0c7178f359d147962fc829479f52f036a707c
<ide><path>docs/Style.md <ide> var List = React.createClass({ <ide> <ide> You can checkout latest support of CSS Properties in following Links. <ide> <del>- [View Properties](https://github.com/facebook/react-native/blob/72d3d724a3a0c6bc46981efd0dad8f7f61121a47/Libraries/Components/View/ViewStylePropTypes.js) <del>- [Image Properties](https://github.com/facebook/react-native/blob/72d3d724a3a0c6bc46981efd0dad8f7f61121a47/Libraries/Image/ImageStylePropTypes.js) <del>- [Text Properties](https://github.com/facebook/react-native/blob/72d3d724a3a0c6bc46981efd0dad8f7f61121a47/Libraries/Text/TextStylePropTypes.js) <add>- [View Properties](http://facebook.github.io/react-native/docs/view.html#style) <add>- [Image Properties](http://facebook.github.io/react-native/docs/image.html#style) <add>- [Text Properties](http://facebook.github.io/react-native/docs/text.html#style) <ide> - [Flex Properties](http://facebook.github.io/react-native/docs/flexbox.html#content)
1
PHP
PHP
remove optional parameter
dd2e3a3dc0a1e227db49096f654f1dc8cac291ab
<ide><path>src/TestSuite/IntegrationTestCase.php <ide> public function assertRedirect($url = null, $message = '') <ide> * @param string $message The failure message that will be appended to the generated message. <ide> * @return void <ide> */ <del> public function assertRedirectContains($url = null, $message = '') <add> public function assertRedirectContains($url, $message = '') <ide> { <ide> if (!$this->_response) { <ide> $this->fail('No response set, cannot assert location header. ' . $message);
1