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 |
|---|---|---|---|---|---|
Ruby | Ruby | reduce duplication when generating translations | c946b2a30038701cdff3ed6e22b8fdcbe2ee3b7d | <ide><path>actionview/lib/action_view/helpers/tags.rb
<ide> module Tags #:nodoc:
<ide>
<ide> eager_autoload do
<ide> autoload :Base
<add> autoload :Translator
<ide> autoload :CheckBox
<ide> autoload :CollectionCheckBoxes
<ide> autoload :CollectionRadioButtons
<ide><path>actionview/lib/action_view/helpers/tags/label.rb
<ide> def initialize(template_object, object_name, method_name, object, tag_value)
<ide>
<ide> def translation
<ide> method_and_value = @tag_value.present? ? "#{@method_name}.#{@tag_value}" : @method_name
<del> @object_name.gsub!(/\[(.*)_attributes\]\[\d+\]/, '.\1')
<del>
<del> if object.respond_to?(:to_model)
<del> model = object.to_model
<del> end
<del>
<del> if model
<del> key = model.model_name.i18n_key
<del> i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
<del> end
<del>
<del> i18n_default ||= ""
<del> content = I18n.t("#{@object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence
<del>
<del> content ||= if model && model.class.respond_to?(:human_attribute_name)
<del> model.class.human_attribute_name(method_and_value)
<del> end
<ide>
<add> content ||= Translator
<add> .new(object, @object_name, method_and_value, "helpers.label")
<add> .call
<ide> content ||= @method_name.humanize
<ide>
<ide> content
<ide><path>actionview/lib/action_view/helpers/tags/placeholderable.rb
<ide> def initialize(*)
<ide>
<ide> if tag_value = @options[:placeholder]
<ide> placeholder = tag_value if tag_value.is_a?(String)
<del>
<del> object_name = @object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1')
<ide> method_and_value = tag_value.is_a?(TrueClass) ? @method_name : "#{@method_name}.#{tag_value}"
<ide>
<del> if object.respond_to?(:to_model)
<del> model = object.to_model
<del> end
<del>
<del> if model
<del> key = model.model_name.i18n_key
<del> i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
<del> end
<del>
<del> i18n_default ||= ""
<del> placeholder ||= I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.placeholder").presence
<del> placeholder ||= if model && model.class.respond_to?(:human_attribute_name)
<del> model.class.human_attribute_name(method_and_value)
<del> end
<add> placeholder ||= Tags::Translator
<add> .new(object, @object_name, method_and_value, "helpers.placeholder")
<add> .call
<ide> placeholder ||= @method_name.humanize
<del>
<ide> @options[:placeholder] = placeholder
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/helpers/tags/translator.rb
<add>module ActionView
<add> module Helpers
<add> module Tags # :nodoc:
<add> class Translator # :nodoc:
<add> attr_reader :object, :object_name, :method_and_value, :i18n_scope
<add>
<add> def initialize(object, object_name, method_and_value, i18n_scope)
<add> @object = object
<add> @object_name = object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1')
<add> @method_and_value = method_and_value
<add> @i18n_scope = i18n_scope
<add> end
<add>
<add> def call
<add> placeholder ||= I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => i18n_scope).presence
<add> placeholder || human_attribute_name
<add> end
<add>
<add> def i18n_default
<add> if model
<add> key = model.model_name.i18n_key
<add> ["#{key}.#{method_and_value}".to_sym, ""]
<add> else
<add> ""
<add> end
<add> end
<add>
<add> def human_attribute_name
<add> if model && model.class.respond_to?(:human_attribute_name)
<add> model.class.human_attribute_name(method_and_value)
<add> end
<add> end
<add>
<add> def model
<add> @model ||= object.to_model if object.respond_to?(:to_model)
<add> end
<add> end
<add> end
<add> end
<add>end | 4 |
Text | Text | немного поправил текст | 9010fbc8f0422dd9f2dcef118217b0651d327061 | <ide><path>guide/russian/css/css-frameworks/css-framework-bootstrap/index.md
<ide> ---
<ide> title: CSS Framework Bootstrap
<del>localeTitle: Исходный код CSS Framework
<add>localeTitle: CSS фреймворк Bootstrap
<ide> ---
<del># Исходный код CSS Framework
<add># CSS фреймворк Bootstrap
<ide>
<del>Bootstrap - это самый популярный CSS-фреймворк в Интернете для создания адаптивных проектов, разработка которых начинается с применения стратегии "сначала мобильные".
<add>Bootstrap - это самый популярный CSS-фреймворк в Интернете для создания адаптивных проектов, разработка которых начинается с применения стратегии "Mobile First".
<ide>
<ide> ## Начало работы - Последняя версия: 4.1
<ide>
<del>Вот простой HTML-шаблон, который включает в себя последние скомпилированные и мини-CSS и Javascript для библиотеки Bootstrap. В этом примере мы использовали CDN, но вы можете проверить [другие способы установки Bootstrap](https://getbootstrap.com/docs/4.1/getting-started/download/) .
<add>Вот простой HTML-шаблон, который включает в себя скомпилированный и минифицированный CSS и Javascript код для библиотеки Bootstrap. В этом примере мы использовали CDN, но вы можете проверить [другие способы установки Bootstrap](https://getbootstrap.com/docs/4.1/getting-started/download/) .
<ide>
<ide> ```html
<ide>
<ide> Bootstrap - это самый популярный CSS-фреймворк в И
<ide> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<ide> </head>
<ide> <body>
<del> <!-- Add all HTML Code below -->
<add> <!-- Добавьте HTML код ниже -->
<ide>
<del> <!-- Add all HTML Code above -->
<add> <!-- Добавьте HTML код выше -->
<ide>
<ide> <!-- jQuery -->
<ide> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<ide> Bootstrap - это самый популярный CSS-фреймворк в И
<ide>
<ide> ## Начало работы - Bootstrap 3
<ide>
<del>Bootstrap 3 - это не последняя стабильная версия Bootstrap, но она по-прежнему является самой распространенной версией. Вы найдете его во множестве шаблонов, в темах для WordPress, проектах и многом другом. Исходя из всего вышесказанного, становится понятно, что очень полезно знать, как его использовать. Не стесняйтесь прочитать превосходную [документацию Bootstrap 3](https://getbootstrap.com/docs/3.3/getting-started/) .
<add>Bootstrap 3 - это не последняя стабильная версия Bootstrap, но она по-прежнему является самой распространенной версией. Вы найдете её во множестве шаблонов, в темах для WordPress, проектах и многом другом. Исходя из всего вышесказанного, становится понятно, что очень полезно знать, как его использовать. Не стесняйтесь прочитать превосходную [документацию Bootstrap 3](https://getbootstrap.com/docs/3.3/getting-started/) .
<ide>
<ide> ```html
<ide> | 1 |
Java | Java | drop support for standalone "l" in cronexpression | 4d670ee25d8a1e615883dfb4468919c2b43c33b0 | <ide><path>spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java
<ide> private CronExpression(
<ide> * </li>
<ide> * <li>
<ide> * In the "day of week" field, {@code L} stands for "the last day of the
<del> * week", and uses the
<del> * {@linkplain java.util.Locale#getDefault() system default locale}
<del> * to determine which day that is (i.e. Sunday or Saturday).
<add> * week".
<ide> * If prefixed by a number or three-letter name (i.e. {@code dL} or
<ide> * {@code DDDL}), it means "the last day of week {@code d} (or {@code DDD})
<ide> * in the month".
<ide> private CronExpression(
<ide> * <li>{@code "0 0 0 L-3 * *"} = third-to-last day of the month at midnight</li>
<ide> * <li>{@code "0 0 0 1W * *"} = first weekday of the month at midnight</li>
<ide> * <li>{@code "0 0 0 LW * *"} = last weekday of the month at midnight</li>
<del> * <li>{@code "0 0 0 * * L"} = last day of the week at midnight</li>
<ide> * <li>{@code "0 0 0 * * 5L"} = last Friday of the month at midnight</li>
<ide> * <li>{@code "0 0 0 * * THUL"} = last Thursday of the month at midnight</li>
<ide> * <li>{@code "0 0 0 ? * 5#2"} = the second Friday in the month at midnight</li>
<ide><path>spring-context/src/main/java/org/springframework/scheduling/support/QuartzCronField.java
<ide> import java.time.temporal.Temporal;
<ide> import java.time.temporal.TemporalAdjuster;
<ide> import java.time.temporal.TemporalAdjusters;
<del>import java.time.temporal.TemporalField;
<del>import java.time.temporal.WeekFields;
<del>import java.util.Locale;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public static QuartzCronField parseDaysOfWeek(String value) {
<ide> }
<ide> else {
<ide> TemporalAdjuster adjuster;
<del> if (idx == 0) { // "L"
<del> adjuster = lastDayOfWeek(Locale.getDefault());
<add> if (idx == 0) {
<add> throw new IllegalArgumentException("No day-of-week before 'L' in '" + value + "'");
<ide> }
<ide> else { // "[0-7]L"
<ide> DayOfWeek dayOfWeek = parseDayOfWeek(value.substring(0, idx));
<ide> private static TemporalAdjuster lastDayWithOffset(int offset) {
<ide> };
<ide> }
<ide>
<del> /**
<del> * Return a temporal adjuster that finds the last day-of-week, depending
<del> * on the given locale.
<del> * @param locale the locale to base the last day calculation on
<del> * @return the last day-of-week adjuster
<del> */
<del> private static TemporalAdjuster lastDayOfWeek(Locale locale) {
<del> Assert.notNull(locale, "Locale must not be null");
<del> TemporalField dayOfWeek = WeekFields.of(locale).dayOfWeek();
<del> return temporal -> temporal.with(dayOfWeek, 7);
<del> }
<del>
<ide> /**
<ide> * Return a temporal adjuster that finds the weekday nearest to the given
<ide> * day-of-month. If {@code dayOfMonth} falls on a Saturday, the date is
<ide><path>spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java
<ide> import java.time.ZonedDateTime;
<ide> import java.time.temporal.ChronoField;
<ide> import java.time.temporal.Temporal;
<del>import java.util.Locale;
<ide>
<ide> import org.assertj.core.api.Condition;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import static java.time.DayOfWeek.FRIDAY;
<ide> import static java.time.DayOfWeek.MONDAY;
<del>import static java.time.DayOfWeek.SATURDAY;
<ide> import static java.time.DayOfWeek.SUNDAY;
<ide> import static java.time.DayOfWeek.TUESDAY;
<ide> import static java.time.DayOfWeek.WEDNESDAY;
<ide> void quartzLastWeekdayOfMonth() {
<ide> assertThat(actual).is(weekday);
<ide> }
<ide>
<del> @Test
<del> public void quartzLastDayOfWeekFirstDayMonday() {
<del> Locale defaultLocale = Locale.getDefault();
<del> try {
<del> Locale.setDefault(Locale.UK);
<del>
<del> CronExpression expression = CronExpression.parse("0 0 0 * * L");
<del>
<del> LocalDateTime last = LocalDateTime.of(LocalDate.of(2008, 1, 4), LocalTime.now());
<del> LocalDateTime expected = LocalDateTime.of(2008, 1, 6, 0, 0);
<del> LocalDateTime actual = expression.next(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SUNDAY);
<del>
<del> last = actual;
<del> expected = expected.plusWeeks(1);
<del> actual = expression.next(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SUNDAY);
<del> }
<del> finally {
<del> Locale.setDefault(defaultLocale);
<del> }
<del> }
<del>
<del> @Test
<del> public void quartzLastDayOfWeekFirstDaySunday() {
<del> Locale defaultLocale = Locale.getDefault();
<del> try {
<del> Locale.setDefault(Locale.US);
<del>
<del> CronExpression expression = CronExpression.parse("0 0 0 * * L");
<del>
<del> LocalDateTime last = LocalDateTime.of(LocalDate.of(2008, 1, 4), LocalTime.now());
<del> LocalDateTime expected = LocalDateTime.of(2008, 1, 5, 0, 0);
<del> LocalDateTime actual = expression.next(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SATURDAY);
<del>
<del> last = actual;
<del> expected = expected.plusWeeks(1);
<del> actual = expression.next(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SATURDAY);
<del> }
<del> finally {
<del> Locale.setDefault(defaultLocale);
<del> }
<del> }
<del>
<ide> @Test
<ide> public void quartzLastDayOfWeekOffset() {
<ide> // last Friday (5) of the month
<ide><path>spring-context/src/test/java/org/springframework/scheduling/support/QuartzCronFieldTests.java
<ide>
<ide> import java.time.DayOfWeek;
<ide> import java.time.LocalDate;
<del>import java.util.Locale;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import static java.time.DayOfWeek.SATURDAY;
<del>import static java.time.DayOfWeek.SUNDAY;
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<ide>
<ide> void lastWeekdayOfMonth() {
<ide> assertThat(actual).isEqualTo(expected);
<ide> }
<ide>
<del> @Test
<del> public void lastDayOfWeekFirstDayMonday() {
<del> Locale defaultLocale = Locale.getDefault();
<del> try {
<del> Locale.setDefault(Locale.UK);
<del> QuartzCronField field = QuartzCronField.parseDaysOfWeek("L");
<del>
<del> LocalDate last = LocalDate.of(2020, 6, 16);
<del> LocalDate expected = LocalDate.of(2020, 6, 21);
<del> assertThat(field.nextOrSame(last)).isEqualTo(expected);
<del>
<del> LocalDate actual = field.nextOrSame(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SUNDAY);
<del> }
<del> finally {
<del> Locale.setDefault(defaultLocale);
<del> }
<del> }
<del>
<del> @Test
<del> public void lastDayOfWeekFirstDaySunday() {
<del> Locale defaultLocale = Locale.getDefault();
<del> try {
<del> Locale.setDefault(Locale.US);
<del> QuartzCronField field = QuartzCronField.parseDaysOfWeek("L");
<del>
<del> LocalDate last = LocalDate.of(2020, 6, 16);
<del> LocalDate expected = LocalDate.of(2020, 6, 20);
<del> assertThat(field.nextOrSame(last)).isEqualTo(expected);
<del>
<del> LocalDate actual = field.nextOrSame(last);
<del> assertThat(actual).isNotNull();
<del> assertThat(actual).isEqualTo(expected);
<del> assertThat(actual.getDayOfWeek()).isEqualTo(SATURDAY);
<del> }
<del> finally {
<del> Locale.setDefault(defaultLocale);
<del> }
<del> }
<del>
<ide> @Test
<ide> void lastDayOfWeekOffset() {
<ide> // last Thursday (4) of the month
<ide> void invalidValues() {
<ide>
<ide> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek(""));
<ide> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek("1"));
<add> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek("L"));
<ide> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek("L1"));
<ide> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek("LL"));
<ide> assertThatIllegalArgumentException().isThrownBy(() -> QuartzCronField.parseDaysOfWeek("-4L")); | 4 |
Javascript | Javascript | remove duplicate code | 67793318310b06fa916bfc44774f035b7960b332 | <ide><path>lib/dns.js
<ide> function onlookup(err, addresses) {
<ide> if (err) {
<ide> return this.callback(dnsException(err, 'getaddrinfo', this.hostname));
<ide> }
<del> if (this.family) {
<del> this.callback(null, addresses[0], this.family);
<del> } else {
<del> this.callback(null, addresses[0], isIP(addresses[0]));
<del> }
<add> this.callback(null, addresses[0], this.family || isIP(addresses[0]));
<ide> }
<ide>
<ide> | 1 |
Python | Python | add regression test for #859 | c4f16c66d1c61181dd52c5543b40fec5ea33c10d | <ide><path>spacy/tests/regression/test_issue859.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>
<add>import pytest
<add>
<add>
<add>@pytest.mark.xfail
<add>@pytest.mark.parametrize('text', ["aaabbb@ccc.com\nThank you!"])
<add>def test_issue859(en_tokenizer, text):
<add> """Test that no extra space is added in doc.text method."""
<add> doc = en_tokenizer(text)
<add> assert ' ' not in doc.text
<add> assert doc.text == text | 1 |
Javascript | Javascript | return a promise from pane.destroyactiveitem | 56926695ba359cd10eeba50ed349c8f1853d8160 | <ide><path>src/pane.js
<ide> class Pane {
<ide> }
<ide>
<ide> // Public: Destroy the active item and activate the next item.
<add> //
<add> // Returns a {Promise} that resolves when the item is destroyed.
<ide> destroyActiveItem () {
<del> this.destroyItem(this.activeItem)
<del> return false
<add> return this.destroyItem(this.activeItem)
<ide> }
<ide>
<ide> // Public: Destroy the given item. | 1 |
Text | Text | add docs for biluo_to_iob and iob_to_biluo. | 9cf3fa9711dfff94e88d6e137a52ebabdcceaad8 | <ide><path>website/docs/api/top-level.md
<ide> This method was previously available as `spacy.gold.spans_from_biluo_tags`.
<ide> | `tags` | A sequence of [BILUO](/usage/linguistic-features#accessing-ner) tags with each tag describing one token. Each tag string will be of the form of either `""`, `"O"` or `"{action}-{label}"`, where action is one of `"B"`, `"I"`, `"L"`, `"U"`. ~~List[str]~~ |
<ide> | **RETURNS** | A sequence of `Span` objects with added entity labels. ~~List[Span]~~ |
<ide>
<add>### training.biluo_to_iob {#biluo_to_iob tag="function"}
<add>
<add>Convert a sequence of [BILUO](/usage/linguistic-features#accessing-ner) tags to
<add>[IOB](/usage/linguistic-features#accessing-ner) tags. This is useful if you want
<add>use the BILUO tags with a model that only supports IOB tags.
<add>
<add>> #### Example
<add>>
<add>> ```python
<add>> from spacy.training import biluo_to_iob
<add>>
<add>> tags = ["O", "O", "B-LOC", "I-LOC", "L-LOC", "O"]
<add>> iob_tags = biluo_to_iob(tags)
<add>> assert iob_tags == ["O", "O", "B-LOC", "I-LOC", "I-LOC", "O"]
<add>> ```
<add>
<add>| Name | Description |
<add>| ----------- | --------------------------------------------------------------------------------------- |
<add>| `tags` | A sequence of [BILUO](/usage/linguistic-features#accessing-ner) tags. ~~Iterable[str]~~ |
<add>| **RETURNS** | A list of [IOB](/usage/linguistic-features#accessing-ner) tags. ~~List[str]~~ |
<add>
<add>### training.iob_to_biluo {#iob_to_biluo tag="function"}
<add>
<add>Convert a sequence of [IOB](/usage/linguistic-features#accessing-ner) tags to
<add>[BILUO](/usage/linguistic-features#accessing-ner) tags. This is useful if you
<add>want use the IOB tags with a model that only supports BILUO tags.
<add>
<add><Infobox title="Changed in v3.0" variant="warning" id="iob_to_biluo">
<add>
<add>This method was previously available as `spacy.gold.iob_to_biluo`.
<add>
<add></Infobox>
<add>
<add>> #### Example
<add>>
<add>> ```python
<add>> from spacy.training import iob_to_biluo
<add>>
<add>> tags = ["O", "O", "B-LOC", "I-LOC", "O"]
<add>> biluo_tags = iob_to_biluo(tags)
<add>> assert biluo_tags == ["O", "O", "B-LOC", "L-LOC", "O"]
<add>> ```
<add>
<add>| Name | Description |
<add>| ----------- | ------------------------------------------------------------------------------------- |
<add>| `tags` | A sequence of [IOB](/usage/linguistic-features#accessing-ner) tags. ~~Iterable[str]~~ |
<add>| **RETURNS** | A list of [BILUO](/usage/linguistic-features#accessing-ner) tags. ~~List[str]~~ |
<add>
<ide> ## Utility functions {#util source="spacy/util.py"}
<ide>
<ide> spaCy comes with a small collection of utility functions located in | 1 |
Ruby | Ruby | fix tests from rails.png removal | c959798571b4060b19712e022f4236d75b2b7cfd | <ide><path>railties/test/application/assets_test.rb
<ide> def assert_no_file_exists(filename)
<ide> end
<ide>
<ide> test "assets routes have higher priority" do
<add> app_file "app/assets/images/rails.png", "notactuallyapng"
<ide> app_file "app/assets/javascripts/demo.js.erb", "a = <%= image_path('rails.png').inspect %>;"
<ide>
<ide> app_file 'config/routes.rb', <<-RUBY
<ide> class User < ActiveRecord::Base; end
<ide> end
<ide>
<ide> test "precompile properly refers files referenced with asset_path and runs in the provided RAILS_ENV" do
<add> app_file "app/assets/images/rails.png", "notactuallyapng"
<ide> app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
<ide> # digest is default in false, we must enable it for test environment
<ide> add_to_env_config "test", "config.assets.digest = true"
<ide> class User < ActiveRecord::Base; end
<ide> end
<ide>
<ide> test "precompile shouldn't use the digests present in manifest.json" do
<add> app_file "app/assets/images/rails.png", "notactuallyapng"
<add>
<ide> app_file "app/assets/stylesheets/application.css.erb", "//= depend_on rails.png\np { url: <%= asset_path('rails.png') %> }"
<ide>
<ide> ENV["RAILS_ENV"] = "production"
<ide> class User < ActiveRecord::Base; end
<ide> end
<ide>
<ide> test "precompile appends the md5 hash to files referenced with asset_path and run in production with digest true" do
<add> app_file "app/assets/images/rails.png", "notactuallyapng"
<ide> app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
<ide> add_to_config "config.assets.compile = true"
<ide> add_to_config "config.assets.digest = true"
<ide> class User < ActiveRecord::Base; end
<ide>
<ide> manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
<ide> assets = ActiveSupport::JSON.decode(File.read(manifest))
<del> assert asset_path = assets["assets"].find { |(k, _)| k !~ /rails.png/ && k =~ /.png/ }[1]
<add> assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1]
<ide>
<ide> require "#{app_path}/config/environment"
<ide>
<ide> class ::PostsController < ActionController::Base; end
<ide> end
<ide>
<ide> test "asset urls should be protocol-relative if no request is in scope" do
<add> app_file "app/assets/images/rails.png", "notreallyapng"
<ide> app_file "app/assets/javascripts/image_loader.js.erb", 'var src="<%= image_path("rails.png") %>";'
<ide> add_to_config "config.assets.precompile = %w{image_loader.js}"
<ide> add_to_config "config.asset_host = 'example.com'"
<ide> class ::PostsController < ActionController::Base; end
<ide>
<ide> test "asset paths should use RAILS_RELATIVE_URL_ROOT by default" do
<ide> ENV["RAILS_RELATIVE_URL_ROOT"] = "/sub/uri"
<add> app_file "app/assets/images/rails.png", "notreallyapng"
<ide>
<ide> app_file "app/assets/javascripts/app.js.erb", 'var src="<%= image_path("rails.png") %>";'
<ide> add_to_config "config.assets.precompile = %w{app.js}" | 1 |
Javascript | Javascript | improve support for new execution contexts | ae1b0ca7a598438330854ccd83bae13db3e7d2b0 | <ide><path>lib/assert.js
<ide> function expectedException(actual, expected) {
<ide> return false;
<ide> }
<ide>
<del> if (expected instanceof RegExp) {
<add> if (Object.prototype.toString.call(expected) == '[object RegExp]') {
<ide> return expected.test(actual);
<ide> } else if (actual instanceof expected) {
<ide> return true;
<ide><path>test/simple/test-script-context.js
<ide> result = script.runInContext(context);
<ide> assert.equal(3, context.foo);
<ide> assert.equal('lala', context.thing);
<ide>
<del>
<ide> // Issue GH-227:
<ide> Script.runInNewContext('', null, 'some.js');
<ide>
<ide> function isTypeError(o) {
<ide> assert.throws(function() { script.runInContext(e); }, isTypeError);
<ide> assert.throws(function() { vm.runInContext('', e); }, isTypeError);
<ide> }));
<add>
<add>// Issue GH-693:
<add>common.debug('test RegExp as argument to assert.throws');
<add>script = vm.createScript('var assert = require(\'assert\'); assert.throws(' +
<add> 'function() { throw "hello world"; }, /hello/);',
<add> 'some.js');
<add>script.runInNewContext({ require : require }); | 2 |
Text | Text | prefer environment over mode | 0dc9b59d2edf1983fca04280cacce3232c6164cb | <ide><path>guides/source/action_view_overview.md
<ide> more examples and information.
<ide>
<ide> #### Template Caching
<ide>
<del>By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
<add>By default, Rails will compile each template to a method in order to render it. In the development environment, when you alter a template, Rails will check the file's modification time and recompile it.
<ide>
<ide> ### Partials
<ide>
<ide><path>guides/source/configuring.md
<ide> These configuration methods are to be called on a `Rails::Railtie` object, such
<ide>
<ide> * `config.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints built-in in browsers using different domain aliases. Shorter version of `config.action_controller.asset_host`.
<ide>
<del>* `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is `false`, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array.
<add>* `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is `false`, which is the default in the development environment. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array.
<ide>
<ide> * `config.autoload_paths` accepts an array of paths from which Rails will autoload constants. Default is all directories under `app`. It is no longer recommended to adjust this. See [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html#autoload-paths)
<ide>
<ide> * `config.add_autoload_paths_to_load_path` says whether autoload paths have to be added to `$LOAD_PATH`. This flag is `true` by default, but it is recommended to be set to `false` in `:zeitwerk` mode early, in `config/application.rb`. Zeitwerk uses absolute paths internally, and applications running in `:zeitwerk` mode do not need `require_dependency`, so models, controllers, jobs, etc. do not need to be in `$LOAD_PATH`. Setting this to `false` saves Ruby from checking these directories when resolving `require` calls with relative paths, and saves Bootsnap work and RAM, since it does not need to build an index for them.
<ide>
<del>* `config.cache_classes` controls whether or not application classes and modules should be reloaded if they change. Defaults to `false` in development mode, and `true` in production mode. In `test` mode, the default is `false` if Spring is installed, `true` otherwise.
<add>* `config.cache_classes` controls whether or not application classes and modules should be reloaded if they change. Defaults to `false` in the development environment, and `true` in production. In the test environment, the default is `false` if Spring is installed, `true` otherwise.
<ide>
<ide> * `config.beginning_of_week` sets the default beginning of week for the
<ide> application. Accepts a valid day of week as a symbol (e.g. `:monday`).
<ide> application. Accepts a valid day of week as a symbol (e.g. `:monday`).
<ide>
<ide> * `config.colorize_logging` specifies whether or not to use ANSI color codes when logging information. Defaults to `true`.
<ide>
<del>* `config.consider_all_requests_local` is a flag. If `true` then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. `true` by default in development and test environments, and `false` in production mode. For finer-grained control, set this to `false` and implement `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors.
<add>* `config.consider_all_requests_local` is a flag. If `true` then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. `true` by default in the development and test environments, and `false` in production. For finer-grained control, set this to `false` and implement `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors.
<ide>
<ide> * `config.console` allows you to set class that will be used as console you run `bin/rails console`. It's best to run it in `console` block:
<ide>
<ide> application. Accepts a valid day of week as a symbol (e.g. `:monday`).
<ide>
<ide> * `config.exceptions_app` sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.
<ide>
<del>* `config.debug_exception_response_format` sets the format used in responses when errors occur in development mode. Defaults to `:api` for API only apps and `:default` for normal apps.
<add>* `config.debug_exception_response_format` sets the format used in responses when errors occur in the development environment. Defaults to `:api` for API only apps and `:default` for normal apps.
<ide>
<ide> * `config.file_watcher` is the class used to detect file updates in the file system when `config.reload_classes_only_on_change` is `true`. Rails ships with `ActiveSupport::FileUpdateChecker`, the default, and `ActiveSupport::EventedFileUpdateChecker` (this one depends on the [listen](https://github.com/guard/listen) gem). Custom classes must conform to the `ActiveSupport::FileUpdateChecker` API.
<ide>
<ide> numbers. It also filters out sensitive values of database columns when call `#in
<ide>
<ide> * `config.javascript_path` sets the path where your app's JavaScript lives relative to the `app` directory. The default is `javascript`, used by [webpacker](https://github.com/rails/webpacker). An app's configured `javascript_path` will be excluded from `autoload_paths`.
<ide>
<del>* `config.log_formatter` defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all modes. If you are setting a value for `config.logger` you must manually pass the value of your formatter to your logger before it is wrapped in an `ActiveSupport::TaggedLogging` instance, Rails will not do it for you.
<add>* `config.log_formatter` defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all environments. If you are setting a value for `config.logger` you must manually pass the value of your formatter to your logger before it is wrapped in an `ActiveSupport::TaggedLogging` instance, Rails will not do it for you.
<ide>
<ide> * `config.log_level` defines the verbosity of the Rails logger. This option defaults to `:debug` for all environments except production, where it defaults to `:info`. The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`.
<ide>
<ide> numbers. It also filters out sensitive values of database columns when call `#in
<ide>
<ide> * `secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get a random generated key in test and development environments, other environments should set one in `config/credentials.yml.enc`.
<ide>
<del>* `config.public_file_server.enabled` configures Rails to serve static files from the public directory. This option defaults to `true`, but in the production environment it is set to `false` because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to `true`. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.
<add>* `config.public_file_server.enabled` configures Rails to serve static files from the public directory. This option defaults to `true`, but in the production environment it is set to `false` because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production using WEBrick (it is not recommended to use WEBrick in production) set the option to `true`. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.
<ide>
<ide> * `config.session_store` specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Defaults to a cookie store with application name as the session key. Custom session stores can also be specified:
<ide>
<ide> The schema dumper adds two additional configuration options:
<ide>
<ide> * `config.action_controller.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself.
<ide>
<del>* `config.action_controller.perform_caching` configures whether the application should perform the caching features provided by the Action Controller component or not. Set to `false` in development mode, `true` in production. If it's not specified, the default will be `true`.
<add>* `config.action_controller.perform_caching` configures whether the application should perform the caching features provided by the Action Controller component or not. Set to `false` in the development environment, `true` in production. If it's not specified, the default will be `true`.
<ide>
<ide> * `config.action_controller.default_static_extension` configures the extension used for cached pages. Defaults to `.html`.
<ide>
<ide> The schema dumper adds two additional configuration options:
<ide>
<ide> * `config.action_controller.request_forgery_protection_token` sets the token parameter name for RequestForgery. Calling `protect_from_forgery` sets it to `:authenticity_token` by default.
<ide>
<del>* `config.action_controller.allow_forgery_protection` enables or disables CSRF protection. By default this is `false` in test mode and `true` in all other modes.
<add>* `config.action_controller.allow_forgery_protection` enables or disables CSRF protection. By default this is `false` in the test environment and `true` in all other environments.
<ide>
<ide> * `config.action_controller.forgery_protection_origin_check` configures whether the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense.
<ide>
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `bootstrap_hook`: Runs all configured `before_initialize` blocks.
<ide>
<del>* `i18n.callbacks`: In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
<add>* `i18n.callbacks`: In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production this callback will only run on the first request.
<ide>
<ide> * `active_support.deprecation_behavior`: Sets up deprecation reporting for environments, defaulting to `:log` for development, `:notify` for production, and `:stderr` for test. If a value isn't set for `config.active_support.deprecation` then this initializer will prompt the user to configure this line in the current environment's `config/environments` file. Can be set to an array of values. This initializer also sets up behaviors for disallowed deprecations, defaulting to `:raise` for development and test and `:log` for production. Disallowed deprecation warnings default to an empty array.
<ide>
<ide><path>guides/source/getting_started.md
<ide> your application in action, open a browser window and navigate to
<ide> TIP: To stop the web server, hit Ctrl+C in the terminal window where it's
<ide> running. To verify the server has stopped you should see your command prompt
<ide> cursor again. For most UNIX-like systems including macOS this will be a
<del>dollar sign `$`. In development mode, Rails does not generally require you to
<del>restart the server; changes you make in files will be automatically picked up by
<del>the server.
<add>dollar sign `$`. In the development environment, Rails does not generally
<add>require you to restart the server; changes you make in files will be
<add>automatically picked up by the server.
<ide>
<ide> The "Yay! You're on Rails!" page is the _smoke test_ for a new Rails
<ide> application: it makes sure that you have your software configured correctly
<ide> TIP: If you want to link to an action in the same controller, you don't need to
<ide> specify the `:controller` option, as Rails will use the current controller by
<ide> default.
<ide>
<del>TIP: In development mode (which is what you're working in by default), Rails
<del>reloads your application with every browser request, so there's no need to stop
<del>and restart the web server when a change is made.
<add>TIP: In the development environment (which is what you're working in by
<add>default), Rails reloads your application with every browser request, so there's
<add>no need to stop and restart the web server when a change is made.
<ide>
<ide> ### Adding Some Validation
<ide>
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> By opting-out you optimize `$LOAD_PATH` lookups (less directories to check), and
<ide>
<ide> #### Thread-safety
<ide>
<del>In classic mode, constant autoloading is not thread-safe, though Rails has locks in place for example to make web requests thread-safe when autoloading is enabled, as it is common in `development` mode.
<add>In classic mode, constant autoloading is not thread-safe, though Rails has locks in place for example to make web requests thread-safe when autoloading is enabled, as it is common in the development environment.
<ide>
<ide> Constant autoloading is thread-safe in `zeitwerk` mode. For example, you can now autoload in multi-threaded scripts executed by the `runner` command.
<ide>
<ide> are also fine because the file defining them will have been eager loaded while b
<ide>
<ide> For the vast majority of applications this change needs no action. But in the
<ide> very rare event that your application needs autoloading while running in
<del>production mode, set `Rails.application.config.enable_dependency_loading` to
<del>true.
<add>production, set `Rails.application.config.enable_dependency_loading` to true.
<ide>
<ide> ### XML Serialization
<ide>
<ide> should also extend the module with `ActiveSupport::Concern`. Alternatively, you
<ide> to include `ActionController::Live` directly to the controller once the `StreamingSupport` is included.
<ide>
<ide> This means that if your application used to have its own streaming module, the following code
<del>would break in production mode:
<add>would break in production:
<ide>
<ide> ```ruby
<ide> # This is a work-around for streamed controllers performing authentication with Warden/Devise.
<ide> secrets, you need to:
<ide>
<ide> 2. Use your existing `secret_key_base` from the `secret_token.rb` initializer to
<ide> set the SECRET_KEY_BASE environment variable for whichever users running the
<del> Rails application in production mode. Alternatively, you can simply copy the existing
<add> Rails application in production. Alternatively, you can simply copy the existing
<ide> `secret_key_base` from the `secret_token.rb` initializer to `secrets.yml`
<ide> under the `production` section, replacing '<%= ENV["SECRET_KEY_BASE"] %>'.
<ide> | 4 |
Python | Python | document some choices in the ssh client | 6e53bfff2edaee590cb1d70ba333e7a9a82c203a | <ide><path>libcloud/compute/ssh.py
<ide> def delete(self, path):
<ide> return True
<ide>
<ide> def run(self, cmd):
<add> """
<add> Note: This function is based on paramiko's exec_command()
<add> method.
<add> """
<ide> extra = {'_cmd': cmd}
<ide> self.logger.debug('Executing command', extra=extra)
<ide>
<del> # based on exec_command()
<add> # Use the system default buffer size
<ide> bufsize = -1
<del> t = self.client.get_transport()
<del> chan = t.open_session()
<add>
<add> transport = self.client.get_transport()
<add> chan = transport.open_session()
<add>
<ide> chan.exec_command(cmd)
<add>
<ide> stdin = chan.makefile('wb', bufsize)
<ide> stdout = chan.makefile('rb', bufsize)
<ide> stderr = chan.makefile_stderr('rb', bufsize)
<del> #stdin, stdout, stderr = self.client.exec_command(cmd)
<add>
<ide> stdin.close()
<add>
<add> # Receive the exit status code of the command we ran.
<add> # Note: If the command hasn't finished yet, this method will block
<add> # until it does
<ide> status = chan.recv_exit_status()
<add>
<ide> so = stdout.read()
<ide> se = stderr.read()
<ide> | 1 |
Javascript | Javascript | remove function hastextdecoder in encoding.js | 25dc25b1111a9bdb8b60064eb0afe73873e96b83 | <ide><path>lib/internal/encoding.js
<ide> Object.defineProperties(
<ide> value: 'TextEncoder'
<ide> } });
<ide>
<del>const { hasConverter, TextDecoder } =
<add>const TextDecoder =
<ide> process.binding('config').hasIntl ?
<ide> makeTextDecoderICU() :
<ide> makeTextDecoderJS();
<ide>
<del>function hasTextDecoder(encoding = 'utf-8') {
<del> validateArgument(encoding, 'string', 'encoding', 'string');
<del> return hasConverter(getEncodingFromLabel(encoding));
<del>}
<del>
<ide> function makeTextDecoderICU() {
<ide> const {
<ide> decode: _decode,
<ide> getConverter,
<del> hasConverter
<ide> } = internalBinding('icu');
<ide>
<ide> class TextDecoder {
<ide> function makeTextDecoderICU() {
<ide> }
<ide> }
<ide>
<del> return { hasConverter, TextDecoder };
<add> return TextDecoder;
<ide> }
<ide>
<ide> function makeTextDecoderJS() {
<ide> function makeTextDecoderJS() {
<ide> }
<ide> }
<ide>
<del> return { hasConverter, TextDecoder };
<add> return TextDecoder;
<ide> }
<ide>
<ide> // Mix in some shared properties.
<ide> function makeTextDecoderJS() {
<ide>
<ide> module.exports = {
<ide> getEncodingFromLabel,
<del> hasTextDecoder,
<ide> TextDecoder,
<ide> TextEncoder
<ide> }; | 1 |
Javascript | Javascript | add view config for androidhorizontalscrollview | b7fac14b6457ae49412cf7d0923250ce0f4f59ce | <ide><path>Libraries/Components/ScrollView/AndroidHorizontalScrollViewNativeComponent.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @format
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>
<add>const registerGeneratedViewConfig = require('../../Utilities/registerGeneratedViewConfig');
<add>const requireNativeComponent = require('../../ReactNative/requireNativeComponent');
<add>
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import type {ScrollViewNativeProps} from './ScrollViewNativeComponentType';
<add>
<add>const AndroidHorizontalScrollViewViewConfig = {
<add> uiViewClassName: 'AndroidHorizontalScrollView',
<add> bubblingEventTypes: {},
<add> directEventTypes: {},
<add> validAttributes: {
<add> decelerationRate: true,
<add> disableIntervalMomentum: true,
<add> endFillColor: {process: require('../../StyleSheet/processColor')},
<add> fadingEdgeLength: true,
<add> nestedScrollEnabled: true,
<add> overScrollMode: true,
<add> pagingEnabled: true,
<add> persistentScrollbar: true,
<add> scrollEnabled: true,
<add> scrollPerfTag: true,
<add> sendMomentumEvents: true,
<add> showsHorizontalScrollIndicator: true,
<add> snapToEnd: true,
<add> snapToInterval: true,
<add> snapToStart: true,
<add> snapToOffsets: true,
<add> },
<add>};
<add>
<add>let AndroidHorizontalScrollViewNativeComponent;
<add>if (global.RN$Bridgeless) {
<add> registerGeneratedViewConfig(
<add> 'AndroidHorizontalScrollView',
<add> AndroidHorizontalScrollViewViewConfig,
<add> );
<add> AndroidHorizontalScrollViewNativeComponent = 'AndroidHorizontalScrollView';
<add>} else {
<add> AndroidHorizontalScrollViewNativeComponent = requireNativeComponent<ScrollViewNativeProps>(
<add> 'AndroidHorizontalScrollView',
<add> );
<add>}
<add>
<add>export default ((AndroidHorizontalScrollViewNativeComponent: any): HostComponent<ScrollViewNativeProps>);
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> import type {Props as ScrollViewStickyHeaderProps} from './ScrollViewStickyHeade
<ide>
<ide> import ScrollViewNativeComponent from './ScrollViewNativeComponent';
<ide> import ScrollContentViewNativeComponent from './ScrollContentViewNativeComponent';
<add>import AndroidHorizontalScrollViewNativeComponent from './AndroidHorizontalScrollViewNativeComponent';
<ide>
<ide> let AndroidScrollView;
<ide> let AndroidHorizontalScrollContentView;
<ide> let RCTScrollContentView;
<ide>
<ide> if (Platform.OS === 'android') {
<ide> AndroidScrollView = ScrollViewNativeComponent;
<del> AndroidHorizontalScrollView = requireNativeComponent(
<del> 'AndroidHorizontalScrollView',
<del> );
<add> AndroidHorizontalScrollView = AndroidHorizontalScrollViewNativeComponent;
<ide> AndroidHorizontalScrollContentView = requireNativeComponent(
<ide> 'AndroidHorizontalScrollContentView',
<ide> ); | 2 |
Python | Python | fix syntaxerror in test_leak.py | 3ade3cb57ecfc58067f0f38132220313690090a6 | <ide><path>funtests/suite/test_leak.py
<ide> def get_rsize(self, cmd=GET_RSIZE):
<ide> shlex.split(cmd % {'pid': os.getpid()}),
<ide> stdout=subprocess.PIPE).communicate()[0].strip())
<ide> except OSError, exc:
<del> raise SkipTest('Can't execute command: %r: %r' % (cmd, exc))
<add> raise SkipTest("Can't execute command: %r: %r" % (cmd, exc))
<ide>
<ide> def sample_allocated(self, fun, *args, **kwargs):
<ide> before = self.get_rsize() | 1 |
PHP | PHP | fix cache clearing for apcengine | a30f911725ad85a684882e87d3c9603fdfdc826b | <ide><path>src/Cache/Engine/ApcEngine.php
<ide> public function clear($check)
<ide> if ($check) {
<ide> return true;
<ide> }
<del> $iterator = new APCUIterator(
<del> '/^' . preg_quote($this->_config['prefix'], '/') . '/',
<del> APC_ITER_NONE
<del> );
<del> apcu_delete($iterator);
<add> if (class_exists('APCIterator', false)) {
<add> $iterator = new APCUIterator(
<add> '/^' . preg_quote($this->_config['prefix'], '/') . '/',
<add> APC_ITER_NONE
<add> );
<add> apcu_delete($iterator);
<add> return true;
<add> }
<add> $cache = apcu_cache_info();
<add> foreach ($cache['cache_list'] as $key) {
<add> if (strpos($key['info'], $this->_config['prefix']) === 0) {
<add> apcu_delete($key['info']);
<add> }
<add> }
<ide> return true;
<ide> }
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 3c6febb810af2128c479b402c36859d7572665cc | <ide><path>src/Illuminate/Validation/Rules/RequiredIf.php
<ide>
<ide> namespace Illuminate\Validation\Rules;
<ide>
<del>use Closure;
<del>
<ide> class RequiredIf
<ide> {
<ide> /** | 1 |
Mixed | Javascript | fix the spelling of "separate" | 02616b9f17b336762ad061dc96b0688affd79b79 | <ide><path>docs/06-Advanced.md
<ide> npm install -g gulp
<ide>
<ide> This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
<ide>
<del>Now, we can run the `gulp build` task, and pass in a comma seperated list of types as an argument to build a custom version of Chart.js with only specified chart types.
<add>Now, we can run the `gulp build` task, and pass in a comma-separated list of types as an argument to build a custom version of Chart.js with only specified chart types.
<ide>
<ide> Here we will create a version of Chart.js with only Line, Radar and Bar charts included:
<ide>
<ide><path>src/Chart.Core.js
<ide> var maxValue = max(valuesArray),
<ide> minValue = min(valuesArray);
<ide>
<del> // We need some degree of seperation here to calculate the scales if all the values are the same
<add> // We need some degree of separation here to calculate the scales if all the values are the same
<ide> // Adding/minusing 0.5 will give us a range of 1.
<ide> if (maxValue === minValue){
<ide> maxValue += 0.5;
<ide><path>src/Chart.Line.js
<ide> },this);
<ide>
<ide>
<del> // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
<add> // Control points need to be calculated in a separate loop, because we need to know the current x/y of the point
<ide> // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
<ide> if (this.options.bezierCurve){
<ide> helpers.each(pointsWithValues, function(point, index){ | 3 |
Javascript | Javascript | add link to ngmodelcontroller | a53e466b80162b6b7b70956f08ef3ca4cf1043f0 | <ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> *
<ide> * @description
<ide> * Is a directive that tells Angular to do two-way data binding. It works together with `input`,
<del> * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
<add> * `select`, `textarea` and even custom form controls that use {@link ng.directive:ngModel.NgModelController
<add> * NgModelController} exposed by this directive.
<ide> *
<ide> * `ngModel` is responsible for:
<ide> * | 1 |
Javascript | Javascript | improve code coverage | e4b883312857115c7cdf18a5c419530357c79b4b | <add><path>test/cases/parsing/issue-4608-1/index.js
<del><path>test/cases/parsing/issue-4608/index.js
<ide> it("should find var declaration in control statements", function() {
<ide>
<ide> require("fail");
<ide> }());
<add>
<add> (function() {
<add> with({ a: 1 }) {
<add> var require = f;
<add> }
<add>
<add> require("fail");
<add> }());
<ide> });
<ide>
<ide> it("should find var declaration in control statements after usage", function() {
<ide> it("should find var declaration in control statements after usage", function() {
<ide>
<ide> test();
<ide> }());
<add>
<add> (function() {
<add> var test = (function() { require("fail"); });
<add>
<add> with({ a: 1 }) {
<add> var require = f;
<add> }
<add>
<add> test();
<add> }());
<ide> });
<ide><path>test/cases/parsing/issue-4608-2/index.js
<add>"use strict";
<add>
<add>it("should find var declaration in control statements", function() {
<add> var f = (function(x) {
<add> x.should.be.eql("fail");
<add> });
<add>
<add> (function() {
<add> for(let x of ["a"]) {
<add> var require = f;
<add> }
<add>
<add> require("fail");
<add> }());
<add>});
<add>
<add>it("should find var declaration in control statements after usage", function() {
<add> var f = (function(x) {
<add> x.should.be.eql("fail");
<add> });
<add>
<add> (function() {
<add> var test = (function() { require("fail"); });
<add>
<add> for(let x of ["a"]) {
<add> var require = f;
<add> }
<add>
<add> test();
<add> }());
<add>});
<ide><path>test/cases/parsing/issue-4608-2/test.filter.js
<add>var supportsForOf = require("../../../helpers/supportsForOf");
<add>
<add>module.exports = function(config) {
<add> return !config.minimize && supportsForOf();
<add>};
<ide><path>test/helpers/supportsForOf.js
<add>module.exports = function supportDefaultAssignment() {
<add> try {
<add> var f = eval("(function f() { for(var x of ['ok', 'fail']) return x; })");
<add> return f() === "ok" ;
<add> } catch(e) {
<add> return false;
<add> }
<add>}; | 4 |
Text | Text | fix typo in readme.md | 1072ed9238ac48b6be5a7db8546103ec50a92c0d | <ide><path>README.md
<ide> Files:
<ide> * `dist/Chart.bundle.js`
<ide> * `dist/Chart.bundle.min.js`
<ide>
<del>The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include a single file. You should not use this build if your application already included Moment.js. Otherwise, Moment.js will be included twice which results in increasing page load time and possible version compatability issues.
<add>The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include a single file. You should not use this build if your application already included Moment.js. Otherwise, Moment.js will be included twice which results in increasing page load time and possible version compatibility issues.
<ide>
<ide> ## Documentation
<ide> | 1 |
PHP | PHP | add ability to pretty print response | 420609a83efd0eb59b7c3643d30e7242333837cb | <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasInDatabase.php
<ide> public function failureDescription($table)
<ide> {
<ide> return sprintf(
<ide> "a row in the table [%s] matches the attributes %s.\n\n%s",
<del> $table, $this->toString(), $this->getAdditionalInfo($table)
<add> $table, $this->toString(JSON_PRETTY_PRINT), $this->getAdditionalInfo($table)
<ide> );
<ide> }
<ide>
<ide> protected function getAdditionalInfo($table)
<ide> /**
<ide> * Get a string representation of the object.
<ide> *
<add> * @param int $options
<ide> * @return string
<ide> */
<del> public function toString()
<add> public function toString($options = 0)
<ide> {
<del> return json_encode($this->data);
<add> return json_encode($this->data, $options);
<ide> }
<ide> } | 1 |
Ruby | Ruby | organize compiler methods | f2e076e5cc87e25602c07c030c47ecf048906176 | <ide><path>Library/Homebrew/macos.rb
<ide> def default_compiler
<ide> end
<ide> end
<ide>
<del> def gcc_42_build_version
<del> @gcc_42_build_version ||= if File.exist? "#{dev_tools_path}/gcc-4.2" \
<del> and not Pathname.new("#{dev_tools_path}/gcc-4.2").realpath.basename.to_s =~ /^llvm/
<del> `#{dev_tools_path}/gcc-4.2 --version` =~ /build (\d{4,})/
<del> $1.to_i
<del> end
<del> end
<del>
<del> def gcc_40_build_version
<del> @gcc_40_build_version ||= if File.exist? "#{dev_tools_path}/gcc-4.0"
<del> `#{dev_tools_path}/gcc-4.0 --version` =~ /build (\d{4,})/
<del> $1.to_i
<del> end
<del> end
<del>
<ide> def xcode_prefix
<ide> @xcode_prefix ||= begin
<ide> path = Pathname.new xcode_folder
<ide> def xcode_version
<ide> end
<ide> end
<ide>
<add> def gcc_40_build_version
<add> @gcc_40_build_version ||= if locate("gcc-4.0")
<add> `#{locate("gcc-4.0")} --version` =~ /build (\d{4,})/
<add> $1.to_i
<add> end
<add> end
<add>
<add> def gcc_42_build_version
<add> @gcc_42_build_version ||= if locate("gcc-4.2") \
<add> and not locate("gcc-4.2").realpath.basename.to_s =~ /^llvm/
<add> `#{locate("gcc-4.2")} --version` =~ /build (\d{4,})/
<add> $1.to_i
<add> end
<add> end
<add>
<ide> def llvm_build_version
<ide> # for Xcode 3 on OS X 10.5 this will not exist
<ide> # NOTE may not be true anymore but we can't test | 1 |
Javascript | Javascript | add test for moment#locale(false) | 6307ac453a8ea440b2ee811337ea761dbd40dca2 | <ide><path>test/moment/locale.js
<ide> exports.locale = {
<ide> m.lang("fr");
<ide> test.equal(m.locale(), "fr", "m.lang(key) changes instance locale");
<ide>
<add> test.done();
<add> },
<add>
<add> "moment#locale(false) resets to global locale" : function (test) {
<add> var m = moment();
<add>
<add> moment.locale("fr");
<add> m.locale("it");
<add>
<add> test.equal(moment.locale(), "fr", "global locale is it");
<add> test.equal(m.locale(), "it", "instance locale is it");
<add> m.locale(false);
<add> test.equal(m.locale(), "fr", "instance locale reset to global locale");
<add>
<ide> test.done();
<ide> }
<ide> }; | 1 |
PHP | PHP | fix mail tags silently failing | faf384276ee437c556eabc1fed4c6262ce8103d2 | <ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php
<ide> protected function componentString(string $component, array $attributes)
<ide> // component and pass the component as a view parameter to the data so it
<ide> // can be accessed within the component and we can render out the view.
<ide> if (! class_exists($class)) {
<add> $view = Str::startsWith($component, 'mail::')
<add> ? "\$__env->getContainer()->make(Illuminate\\View\\Factory::class)->make('{$component}')"
<add> : "'$class'";
<add>
<ide> $parameters = [
<del> 'view' => "'$class'",
<add> 'view' => $view,
<ide> 'data' => '['.$this->attributesToString($data->all(), $escapeBound = false).']',
<ide> ];
<ide> | 1 |
Python | Python | fix use_cache value assign | 07c2607d4d453e250888f14232bbccce6302fd69 | <ide><path>src/transformers/models/prophetnet/modeling_prophetnet.py
<ide> def forward(
<ide> >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states
<ide> >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states
<ide> """
<del> use_cache == use_cache if use_cache is not None else self.config.use_cache
<add> use_cache = use_cache if use_cache is not None else self.config.use_cache
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> output_hidden_states = (
<ide> output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states | 1 |
Javascript | Javascript | add batch of known issue tests | 10bc673123f29692b7dae5e306a155ed0210e413 | <ide><path>test/known_issues/test-child-process-max-buffer.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/1901
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>const unicode = '中文测试'; // Length = 4, Byte length = 13
<add>
<add>if (process.argv[2] === 'child') {
<add> console.log(unicode);
<add>} else {
<add> const cmd = `${process.execPath} ${__filename} child`;
<add>
<add> cp.exec(cmd, { maxBuffer: 10 }, common.mustCall((err, stdout, stderr) => {
<add> assert.strictEqual(err.message, 'stdout maxBuffer exceeded');
<add> }));
<add>}
<ide><path>test/known_issues/test-events-known-properties.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/728
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const EventEmitter = require('events');
<add>const ee = new EventEmitter();
<add>
<add>ee.on('__proto__', common.mustCall((data) => {
<add> assert.strictEqual(data, 42);
<add>}));
<add>
<add>ee.emit('__proto__', 42);
<ide><path>test/known_issues/test-module-deleted-extensions.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/4778
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const file = path.join(common.tmpDir, 'test-extensions.foo.bar');
<add>
<add>common.refreshTmpDir();
<add>fs.writeFileSync(file, '', 'utf8');
<add>require.extensions['.foo.bar'] = (module, path) => {};
<add>delete require.extensions['.foo.bar'];
<add>require.extensions['.bar'] = common.mustCall((module, path) => {
<add> assert.strictEqual(module.id, file);
<add> assert.strictEqual(path, file);
<add>});
<add>require(path.join(common.tmpDir, 'test-extensions'));
<ide><path>test/known_issues/test-process-external-stdio-close.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/947
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>
<add>if (process.argv[2] === 'child') {
<add> process.on('message', common.mustCall((msg) => {
<add> assert.strictEqual(msg, 'go');
<add> console.log('logging should not cause a crash');
<add> process.disconnect();
<add> }));
<add>} else {
<add> const child = cp.fork(__filename, ['child'], {silent: true});
<add>
<add> child.on('close', common.mustCall((exitCode, signal) => {
<add> assert.strictEqual(exitCode, 0);
<add> assert.strictEqual(signal, null);
<add> }));
<add>
<add> child.stdout.destroy();
<add> child.send('go');
<add>}
<ide><path>test/known_issues/test-vm-getters.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/2734
<add>require('../common');
<add>const assert = require('assert');
<add>const vm = require('vm');
<add>const sandbox = {};
<add>
<add>Object.defineProperty(sandbox, 'prop', {
<add> get() {
<add> return 'foo';
<add> }
<add>});
<add>
<add>const descriptor = Object.getOwnPropertyDescriptor(sandbox, 'prop');
<add>const context = vm.createContext(sandbox);
<add>const code = 'Object.getOwnPropertyDescriptor(this, "prop");';
<add>const result = vm.runInContext(code, context);
<add>
<add>assert.strictEqual(result, descriptor); | 5 |
Text | Text | add a daytime for daily stand up meetings | 9004e1ce299b97192b767c41a15aa8912e410743 | <ide><path>guide/english/agile/daily-standup-and-daily-scrum/index.md
<ide> title: Daily Stand-Up and Daily Scrum
<ide>
<ide> The Daily Stand-Up (DSU) or Daily Scrum meeting is one of the integral parts of scrum methodology.
<ide>
<del>As the name suggests, you hold the meeting daily, at the same time and, for a co-located team, in the same location. The meeting should be brief, finished in less than 15 minutes.
<add>As the name suggests, you hold the meeting daily, at the same time (usually in the beginning of the day) and, for a co-located team, in the same location. The meeting should be brief, finished in less than 15 minutes.
<ide>
<ide> Only members of the Development team are required to attend the Daily Stand-up. Typically, the Scrum Master and Product Owners will also attend, but they are not required.
<ide> | 1 |
Javascript | Javascript | fix subsequent end calls to not throw | a4e923f5c13b80bf43ecfca4e9be483535011dbe | <ide><path>lib/internal/http2/compat.js
<ide> class Http2ServerResponse extends Stream {
<ide> cb = encoding;
<ide> encoding = 'utf8';
<ide> }
<add> if (stream === undefined || stream.finished === true) {
<add> return false;
<add> }
<ide> if (chunk !== null && chunk !== undefined) {
<ide> this.write(chunk, encoding);
<ide> }
<ide>
<del> if (stream === undefined) {
<del> return;
<del> }
<del>
<ide> if (typeof cb === 'function') {
<ide> stream.once('finish', cb);
<ide> }
<ide><path>test/parallel/test-http2-compat-serverresponse-end.js
<ide> const { mustCall, mustNotCall, hasCrypto, skip } = require('../common');
<ide> if (!hasCrypto)
<ide> skip('missing crypto');
<del>const { strictEqual } = require('assert');
<add>const { doesNotThrow, strictEqual } = require('assert');
<ide> const {
<ide> createServer,
<ide> connect,
<ide> const {
<ide> // but may be invoked repeatedly without throwing errors.
<ide> const server = createServer(mustCall((request, response) => {
<ide> strictEqual(response.closed, false);
<add> response.on('finish', mustCall(() => process.nextTick(
<add> mustCall(() => doesNotThrow(() => response.end('test', mustNotCall())))
<add> )));
<ide> response.end(mustCall(() => {
<ide> server.close();
<ide> })); | 2 |
Java | Java | add msdn links | 21e7523bd0f6cc845cf65729df9e6960b9ee38f3 | <ide><path>rxjava-core/src/main/java/rx/observables/BlockingObservable.java
<ide> public Iterator<T> getIterator() {
<ide> * @return the first item emitted by the source {@link Observable}
<ide> * @throws IllegalArgumentException
<ide> * if source contains no elements
<add> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229177(v=vs.103).aspx">MSDN: Observable.First</a>
<ide> */
<ide> public T first() {
<ide> return from(o.first()).single();
<ide> public T first() {
<ide> * @return the first item emitted by the {@link Observable} that matches the predicate
<ide> * @throws IllegalArgumentException
<ide> * if no such items are emitted.
<add> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229739(v=vs.103).aspx">MSDN: Observable.First</a>
<ide> */
<ide> public T first(Func1<? super T, Boolean> predicate) {
<ide> return from(o.first(predicate)).single(); | 1 |
Python | Python | handle typeerror in _generate_str for coefs | 66365a57ff9b68a191fd232dc823cc2cf69d267f | <ide><path>numpy/polynomial/_polybase.py
<ide> def _generate_string(self, term_method):
<ide> out += " "
<ide> power = str(i + 1)
<ide> # Polynomial coefficient
<del> if coef >= 0:
<add> try:
<add> if coef >= 0:
<add> next_term = f"+ {coef}"
<add> else:
<add> next_term = f"- {-coef}"
<add> # The coefficient array can be an object array with elements that
<add> # will raise a TypeError with >= 0 (e.g. strings or Python
<add> # complex). In this case, represent the coeficient as-is.
<add> except TypeError:
<ide> next_term = f"+ {coef}"
<del> else:
<del> next_term = f"- {-coef}"
<ide> # Polynomial term
<ide> next_term += term_method(power, "x")
<ide> # Length of the current line with next term added
<ide><path>numpy/polynomial/tests/test_printing.py
<ide> import pytest
<del>from numpy.core import arange, printoptions
<add>from numpy.core import array, arange, printoptions
<ide> import numpy.polynomial as poly
<ide> from numpy.testing import assert_equal, assert_
<ide>
<add># For testing polynomial printing with object arrays
<add>from fractions import Fraction
<add>from decimal import Decimal
<add>
<ide>
<ide> class TestStrUnicodeSuperSubscripts:
<ide>
<ide> def test_set_default_printoptions():
<ide>
<ide>
<ide> def test_complex_coefficients():
<del> p = poly.Polynomial([0+1j, 1+1j, -2+2j, 3+0j])
<add> """Test both numpy and built-in complex."""
<add> coefs = [0+1j, 1+1j, -2+2j, 3+0j]
<add> # numpy complex
<add> p1 = poly.Polynomial(coefs)
<add> # Python complex
<add> p2 = poly.Polynomial(array(coefs, dtype=object))
<ide> poly.set_default_printstyle('unicode')
<del> assert_equal(str(p), "1j + (1+1j)·x¹ - (2-2j)·x² + (3+0j)·x³")
<add> assert_equal(str(p1), "1j + (1+1j)·x¹ - (2-2j)·x² + (3+0j)·x³")
<add> assert_equal(str(p2), "1j + (1+1j)·x¹ + (-2+2j)·x² + (3+0j)·x³")
<ide> poly.set_default_printstyle('ascii')
<del> assert_equal(str(p), "1j + (1+1j) x**1 - (2-2j) x**2 + (3+0j) x**3")
<add> assert_equal(str(p1), "1j + (1+1j) x**1 - (2-2j) x**2 + (3+0j) x**3")
<add> assert_equal(str(p2), "1j + (1+1j) x**1 + (-2+2j) x**2 + (3+0j) x**3")
<add>
<add>
<add>@pytest.mark.parametrize(('coefs', 'tgt'), (
<add> (array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (
<add> "1/2 + 3/4·x¹"
<add> )),
<add> (array([1, 2, Fraction(5, 7)], dtype=object), (
<add> "1 + 2·x¹ + 5/7·x²"
<add> )),
<add> (array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (
<add> "1.00 + 2.2·x¹ + 3·x²"
<add> )),
<add>))
<add>def test_numeric_object_coefficients(coefs, tgt):
<add> p = poly.Polynomial(coefs)
<add> poly.set_default_printstyle('unicode')
<add> assert_equal(str(p), tgt)
<add>
<add>
<add>@pytest.mark.parametrize(('coefs', 'tgt'), (
<add> (array([1, 2, 'f'], dtype=object), '1 + 2·x¹ + f·x²'),
<add> (array([1, 2, [3, 4]], dtype=object), '1 + 2·x¹ + [3, 4]·x²'),
<add>))
<add>def test_nonnumeric_object_coefficients(coefs, tgt):
<add> """
<add> Test coef fallback for object arrays of non-numeric coefficients.
<add> """
<add> p = poly.Polynomial(coefs)
<add> poly.set_default_printstyle('unicode')
<add> assert_equal(str(p), tgt)
<ide>
<ide>
<ide> class TestFormat: | 2 |
Python | Python | update numpy.extract docstring | 5856a12a3aa3f0474bfd5b7c0c24a32b15728580 | <ide><path>numpy/lib/function_base.py
<ide> def extract(condition, arr):
<ide> This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
<ide> `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
<ide>
<add> Note that `place` does the exact opposite of `extract`.
<add>
<ide> Parameters
<ide> ----------
<ide> condition : array_like
<ide> def extract(condition, arr):
<ide>
<ide> See Also
<ide> --------
<del> take, put, copyto, compress
<add> take, put, copyto, compress, place
<ide>
<ide> Examples
<ide> -------- | 1 |
Ruby | Ruby | use clearer variable name in examples | ced2b25036f9456212dc8d980d2c43b20f0dce2c | <ide><path>activemodel/lib/active_model/serializers/json.rb
<ide> module JSON
<ide> # of +as_json+. If true (the default) +as_json+ will emit a single root
<ide> # node named after the object's type. For example:
<ide> #
<del> # konata = User.find(1)
<del> # konata.as_json
<add> # user = User.find(1)
<add> # user.as_json
<ide> # # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true} }
<ide> #
<ide> # ActiveRecord::Base.include_root_in_json = false
<del> # konata.as_json
<add> # user.as_json
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true}
<ide> #
<ide> module JSON
<ide> # Without any +options+, the returned JSON string will include all the model's
<ide> # attributes. For example:
<ide> #
<del> # konata = User.find(1)
<del> # konata.as_json
<add> # user = User.find(1)
<add> # user.as_json
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true}
<ide> #
<ide> # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
<ide> # included, and work similar to the +attributes+ method. For example:
<ide> #
<del> # konata.as_json(:only => [ :id, :name ])
<add> # user.as_json(:only => [ :id, :name ])
<ide> # # => {"id": 1, "name": "Konata Izumi"}
<ide> #
<del> # konata.as_json(:except => [ :id, :created_at, :age ])
<add> # user.as_json(:except => [ :id, :created_at, :age ])
<ide> # # => {"name": "Konata Izumi", "awesome": true}
<ide> #
<ide> # To include the result of some method calls on the model use <tt>:methods</tt>:
<ide> #
<del> # konata.as_json(:methods => :permalink)
<add> # user.as_json(:methods => :permalink)
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true,
<ide> # "permalink": "1-konata-izumi"}
<ide> #
<ide> # To include associations use <tt>:include</tt>:
<ide> #
<del> # konata.as_json(:include => :posts)
<add> # user.as_json(:include => :posts)
<ide> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<ide> # "created_at": "2006/08/01", "awesome": true,
<ide> # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
<ide> # {"id": 2, author_id: 1, "title": "So I was thinking"}]}
<ide> #
<ide> # Second level and higher order associations work as well:
<ide> #
<del> # konata.as_json(:include => { :posts => {
<add> # user.as_json(:include => { :posts => {
<ide> # :include => { :comments => {
<ide> # :only => :body } },
<ide> # :only => :title } })
<ide><path>activemodel/lib/active_model/serializers/xml.rb
<ide> def add_procs
<ide> # Without any +options+, the returned XML string will include all the model's
<ide> # attributes. For example:
<ide> #
<del> # konata = User.find(1)
<del> # konata.to_xml
<add> # user = User.find(1)
<add> # user.to_xml
<ide> #
<ide> # <?xml version="1.0" encoding="UTF-8"?>
<ide> # <user> | 2 |
Text | Text | fix wrong example of api exec | 221fa4c3d11973f6b973daf26fd962554945fc68 | <ide><path>docs/reference/api/docker_remote_api_v1.20.md
<ide> Sets up an exec instance in a running container `id`
<ide> "Tty": false,
<ide> "Cmd": [
<ide> "date"
<del> ],
<add> ]
<ide> }
<ide>
<ide> **Example response**:
<ide> interactive session with the `exec` command.
<ide>
<ide> {
<ide> "Detach": false,
<del> "Tty": false,
<add> "Tty": false
<ide> }
<ide>
<ide> **Example response**: | 1 |
PHP | PHP | fix incompatible signature | e7dddf809546ddc7ca63ba868b8cc863b614ac20 | <ide><path>src/Shell/Task/UnloadTask.php
<ide> */
<ide> namespace Cake\Shell\Task;
<ide>
<add>use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\Shell;
<ide> use Cake\Filesystem\File;
<ide>
<ide> protected function _modifyBootstrap($plugin)
<ide> *
<ide> * @return \Cake\Console\ConsoleOptionParser
<ide> */
<del> public function getOptionParser()
<add> public function getOptionParser(): ConsoleOptionParser
<ide> {
<ide> $parser = parent::getOptionParser();
<ide> | 1 |
Ruby | Ruby | hide homebrew_bundle_* env vars | 7c04c34a88924b1edf9268be9a3faf870b78c080 | <ide><path>Library/Homebrew/system_config.rb
<ide> def dump_verbose_config(f = $stdout)
<ide> unless ENV["HOMEBREW_ENV"]
<ide> ENV.sort.each do |key, value|
<ide> next unless key.start_with?("HOMEBREW_")
<add> next if key.start_with?("HOMEBREW_BUNDLE_")
<ide> next if boring_keys.include?(key)
<ide> next if defaults_hash[key.to_sym]
<ide> | 1 |
Go | Go | move remote api client to api/ | ee59ba969fdd1837fe0151638cc01637e18139c3 | <add><path>api/client.go
<del><path>commands.go
<del>package docker
<add>package api
<ide>
<ide> import (
<ide> "bufio"
<ide> import (
<ide> "encoding/json"
<ide> "errors"
<ide> "fmt"
<del> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/auth"
<ide> "github.com/dotcloud/docker/dockerversion"
<ide> func (cli *DockerCli) CmdHelp(args ...string) error {
<ide> return nil
<ide> }
<ide> }
<del> help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[unix://%s]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", api.DEFAULTUNIXSOCKET)
<add> help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[unix://%s]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", DEFAULTUNIXSOCKET)
<ide> for _, command := range [][]string{
<ide> {"attach", "Attach to a running container"},
<ide> {"build", "Build a container from a Dockerfile"},
<ide> func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo b
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), params)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
<ide> if err != nil {
<ide> return nil, -1, err
<ide> }
<ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, h
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), in)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, h
<ide> return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
<ide> }
<ide>
<del> if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
<add> if MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
<ide> return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
<ide> }
<ide> if _, err := io.Copy(out, resp.Body); err != nil {
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), nil)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>docker/docker.go
<ide> import (
<ide> "os"
<ide> "strings"
<ide>
<del> "github.com/dotcloud/docker"
<ide> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/dockerversion"
<ide> "github.com/dotcloud/docker/engine"
<ide> func main() {
<ide> log.Fatal("Please specify only one -H")
<ide> }
<ide> protoAddrParts := strings.SplitN(flHosts.GetAll()[0], "://", 2)
<del> if err := docker.ParseCommands(protoAddrParts[0], protoAddrParts[1], flag.Args()...); err != nil {
<add> if err := api.ParseCommands(protoAddrParts[0], protoAddrParts[1], flag.Args()...); err != nil {
<ide> if sterr, ok := err.(*utils.StatusError); ok {
<ide> if sterr.Status != "" {
<ide> log.Println(sterr.Status)
<ide><path>integration/commands_test.go
<ide> import (
<ide> "bufio"
<ide> "fmt"
<ide> "github.com/dotcloud/docker"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/pkg/term"
<ide> "github.com/dotcloud/docker/utils"
<ide> func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error
<ide> func TestRunHostname(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestRunHostname(t *testing.T) {
<ide> func TestRunWorkdir(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestRunWorkdir(t *testing.T) {
<ide> func TestRunWorkdirExists(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestRunExit(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c1 := make(chan struct{})
<ide> func TestRunDisconnect(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c1 := make(chan struct{})
<ide> func TestRunDisconnectTty(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c1 := make(chan struct{})
<ide> func TestRunAttachStdin(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> ch := make(chan struct{})
<ide> func TestRunDetach(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> ch := make(chan struct{})
<ide> func TestAttachDetach(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> ch := make(chan struct{})
<ide> func TestAttachDetach(t *testing.T) {
<ide>
<ide> stdin, stdinPipe = io.Pipe()
<ide> stdout, stdoutPipe = io.Pipe()
<del> cli = docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli = api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide>
<ide> ch = make(chan struct{})
<ide> go func() {
<ide> func TestAttachDetachTruncatedID(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> // Discard the CmdRun output
<ide> func TestAttachDetachTruncatedID(t *testing.T) {
<ide>
<ide> stdin, stdinPipe = io.Pipe()
<ide> stdout, stdoutPipe = io.Pipe()
<del> cli = docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli = api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide>
<ide> ch := make(chan struct{})
<ide> go func() {
<ide> func TestAttachDisconnect(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> go func() {
<ide> func TestAttachDisconnect(t *testing.T) {
<ide> func TestRunAutoRemove(t *testing.T) {
<ide> t.Skip("Fixme. Skipping test for now, race condition")
<ide> stdout, stdoutPipe := io.Pipe()
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestRunAutoRemove(t *testing.T) {
<ide>
<ide> func TestCmdLogs(t *testing.T) {
<ide> t.Skip("Test not impemented")
<del> cli := docker.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> if err := cli.CmdRun(unitTestImageID, "sh", "-c", "ls -l"); err != nil {
<ide> func TestCmdLogs(t *testing.T) {
<ide> // Expected behaviour: error out when attempting to bind mount non-existing source paths
<ide> func TestRunErrorBindNonExistingSource(t *testing.T) {
<ide>
<del> cli := docker.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, nil, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestRunErrorBindNonExistingSource(t *testing.T) {
<ide> func TestImagesViz(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> image := buildTestImages(t, globalEngine)
<ide> func TestImagesViz(t *testing.T) {
<ide> func TestImagesTree(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> image := buildTestImages(t, globalEngine)
<ide> func TestRunCidFile(t *testing.T) {
<ide> }
<ide> tmpCidFile := path.Join(tmpDir, "cid")
<ide>
<del> cli := docker.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> c := make(chan struct{})
<ide> func TestContainerOrphaning(t *testing.T) {
<ide> defer os.RemoveAll(tmpDir)
<ide>
<ide> // setup a CLI and server
<del> cli := docker.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide> srv := mkServerFromEngine(globalEngine, t)
<ide>
<ide> func TestCmdKill(t *testing.T) {
<ide> stdin, stdinPipe := io.Pipe()
<ide> stdout, stdoutPipe := io.Pipe()
<ide>
<del> cli := docker.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<del> cli2 := docker.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli := api.NewDockerCli(stdin, stdoutPipe, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> cli2 := api.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<ide> defer cleanup(globalEngine, t)
<ide>
<ide> ch := make(chan struct{}) | 3 |
Python | Python | fix lazy translation of listfield errors | 19ca86d8d69d37d0e953837fbba1c1934d31dc75 | <ide><path>rest_framework/fields.py
<ide> def __init__(self, *args, **kwargs):
<ide> super().__init__(*args, **kwargs)
<ide> self.child.bind(field_name='', parent=self)
<ide> if self.max_length is not None:
<del> message = self.error_messages['max_length'].format(max_length=self.max_length)
<add> message = lazy(self.error_messages['max_length'].format, str)(max_length=self.max_length)
<ide> self.validators.append(MaxLengthValidator(self.max_length, message=message))
<ide> if self.min_length is not None:
<del> message = self.error_messages['min_length'].format(min_length=self.min_length)
<add> message = lazy(self.error_messages['min_length'].format, str)(min_length=self.min_length)
<ide> self.validators.append(MinLengthValidator(self.min_length, message=message))
<ide>
<ide> def get_value(self, dictionary):
<ide><path>tests/importable/__init__.py
<del>from rest_framework import compat # noqa
<add>"""
<add>This test "app" exists to ensure that parts of Django REST Framework can be
<add>imported/invoked before Django itself has been fully initialized.
<add>"""
<add>
<add>from rest_framework import compat, serializers # noqa
<add>
<add>
<add># test initializing fields with lazy translations
<add>class ExampleSerializer(serializers.Serializer):
<add> charfield = serializers.CharField(min_length=1, max_length=2)
<add> integerfield = serializers.IntegerField(min_value=1, max_value=2)
<add> floatfield = serializers.FloatField(min_value=1, max_value=2)
<add> decimalfield = serializers.DecimalField(max_digits=10, decimal_places=1, min_value=1, max_value=2)
<add> durationfield = serializers.DurationField(min_value=1, max_value=2)
<add> listfield = serializers.ListField(min_length=1, max_length=2)
<ide><path>tests/importable/test_installed.py
<ide>
<ide>
<ide> def test_installed():
<del> # ensure that apps can freely import rest_framework.compat
<add> # ensure the test app hasn't been removed from the test suite
<ide> assert 'tests.importable' in settings.INSTALLED_APPS
<ide>
<ide>
<del>def test_imported():
<del> # ensure that the __init__ hasn't been mucked with
<add>def test_compat():
<ide> assert hasattr(importable, 'compat')
<add>
<add>
<add>def test_serializer_fields_initialization():
<add> assert hasattr(importable, 'ExampleSerializer')
<add>
<add> serializer = importable.ExampleSerializer()
<add> assert 'charfield' in serializer.fields
<add> assert 'integerfield' in serializer.fields
<add> assert 'floatfield' in serializer.fields
<add> assert 'decimalfield' in serializer.fields
<add> assert 'durationfield' in serializer.fields
<add> assert 'listfield' in serializer.fields | 3 |
Ruby | Ruby | add support for 7zip archives | 32b1d46c966c790f1a04b1848ebc25b1170f5295 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> when :rar
<ide> raise "You must install unrar: brew install unrar" unless which "unrar"
<ide> quiet_safe_system 'unrar', 'x', {:quiet_flag => '-inul'}, @tarball_path
<add> when :p7zip
<add> raise "You must install 7zip: brew install p7zip" unless which "7zr"
<add> safe_system '7zr', 'x', @tarball_path
<ide> else
<ide> # we are assuming it is not an archive, use original filename
<ide> # this behaviour is due to ScriptFileFormula expectations
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def compression_type
<ide> case extname
<ide> when ".tar.gz", ".tgz", ".tar.bz2", ".tbz" then :tar
<ide> when ".zip" then :zip
<add> when ".7z" then :p7zip
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | apply a middleware only once | 185447cbd5374770d98cf8d869996c05dcb6e09e | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function middleware($middleware = null)
<ide> $middleware = [$middleware];
<ide> }
<ide>
<del> $this->action['middleware'] = array_merge(
<add> $this->action['middleware'] = array_unique(array_merge(
<ide> (array) Arr::get($this->action, 'middleware', []), $middleware
<del> );
<add> ));
<ide>
<ide> return $this;
<ide> }
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testRouteMiddlewareMergeWithMiddlewareAttributesAsStrings()
<ide> );
<ide> }
<ide>
<add> public function testRouteMiddlewareAppliedOnlyOnce()
<add> {
<add> $router = $this->getRouter();
<add> $router->group(['middleware' => 'foo'], function () use ($router) {
<add> $router->get('bar', function () { return 'hello'; })->middleware(['foo', 'foo']);
<add> });
<add> $routes = $router->getRoutes()->getRoutes();
<add> $route = $routes[0];
<add> $this->assertEquals(
<add> ['foo'],
<add> $route->middleware()
<add> );
<add> }
<add>
<ide> public function testRoutePrefixing()
<ide> {
<ide> /* | 2 |
Ruby | Ruby | move cpu variant to sh.brew.cpu.variant | e627885e16b5ea2df0414ddc5dd6f5a44abe4d13 | <ide><path>Library/Homebrew/github_packages.rb
<ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, dry_run:)
<ide>
<ide> created_date = bottle_hash["bottle"]["date"]
<ide> formula_annotations_hash = {
<add> "com.github.package.type" => GITHUB_PACKAGE_TYPE,
<ide> "org.opencontainers.image.created" => created_date,
<ide> "org.opencontainers.image.description" => bottle_hash["formula"]["desc"],
<ide> "org.opencontainers.image.documentation" => documentation,
<ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, dry_run:)
<ide> raise TypeError, "unknown tab['built_on']['os']: #{tab["built_on"]["os"]}" if os.blank?
<ide>
<ide> os_version = tab["built_on"]["os_version"] if tab["built_on"].present?
<del> os_version = case os
<add> case os
<ide> when "darwin"
<del> os_version || "macOS #{MacOS::Version.from_symbol(bottle_tag)}"
<add> os_version ||= "macOS #{MacOS::Version.from_symbol(bottle_tag)}"
<ide> when "linux"
<del> (os_version || "Ubuntu 16.04.7").delete_suffix " LTS"
<del> else
<del> os_version
<del> end
<del>
<del> glibc_version = if os == "linux"
<del> (tab["built_on"]["glibc_version"] if tab["built_on"].present?) || "2.23"
<add> os_version = (os_version || "Ubuntu 16.04.7").delete_suffix " LTS"
<add> glibc_version = (tab["built_on"]["glibc_version"] if tab["built_on"].present?) || "2.23"
<add> cpu_variant = tab["oldest_cpu_family"] || "core2"
<ide> end
<ide>
<del> variant = tab["oldest_cpu_family"] || "core2" if os == "linux"
<del>
<ide> platform_hash = {
<ide> architecture: architecture,
<del> variant: variant,
<ide> os: os,
<ide> "os.version" => os_version,
<ide> }.compact
<ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, dry_run:)
<ide>
<ide> tag = GitHubPackages.version_rebuild(version, rebuild, bottle_tag)
<ide>
<del> annotations_hash = formula_annotations_hash.merge({
<del> "org.opencontainers.image.created" => created_date,
<del> "org.opencontainers.image.documentation" => documentation,
<del> "org.opencontainers.image.ref.name" => tag,
<del> "org.opencontainers.image.title" => "#{formula_full_name} #{tag}",
<del> "com.github.package.type" => GITHUB_PACKAGE_TYPE,
<del> "sh.brew.bottle.glibc.version" => glibc_version,
<del> "sh.brew.tab" => tab.to_json,
<del> }).compact.sort.to_h
<add> descriptor_annotations_hash = {
<add> "org.opencontainers.image.ref.name" => tag,
<add> "sh.brew.bottle.cpu.variant" => cpu_variant,
<add> "sh.brew.bottle.digest" => tar_gz_sha256,
<add> "sh.brew.bottle.glibc.version" => glibc_version,
<add> "sh.brew.tab" => tab.to_json,
<add> }.compact
<add>
<add> annotations_hash = formula_annotations_hash.merge(descriptor_annotations_hash).merge(
<add> {
<add> "org.opencontainers.image.created" => created_date,
<add> "org.opencontainers.image.documentation" => documentation,
<add> "org.opencontainers.image.title" => "#{formula_full_name} #{tag}",
<add> },
<add> ).compact.sort.to_h
<ide>
<ide> image_manifest = {
<ide> schemaVersion: 2,
<ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, dry_run:)
<ide> digest: "sha256:#{manifest_json_sha256}",
<ide> size: manifest_json_size,
<ide> platform: platform_hash,
<del> annotations: {
<del> "org.opencontainers.image.ref.name" => tag,
<del> "sh.brew.bottle.digest" => tar_gz_sha256,
<del> "sh.brew.bottle.glibc.version" => glibc_version,
<del> "sh.brew.tab" => tab.to_json,
<del> }.compact,
<add> annotations: descriptor_annotations_hash,
<ide> }
<ide> end
<ide> | 1 |
Text | Text | add v3.8.2 to changelog.md | 5eca0045b4ef3606923e4b124034f6063a813b6f | <ide><path>CHANGELOG.md
<ide> - [#17874](https://github.com/emberjs/ember.js/pull/17874) [BUGFIX] Fix issue with `event.stopPropagation()` in component event handlers when jQuery is disabled.
<ide> - [#17876](https://github.com/emberjs/ember.js/pull/17876) [BUGFIX] Fix issue with multiple `{{action}}` modifiers on the same element when jQuery is disabled.
<ide>
<add>### v3.8.2 (June, 4, 2019)
<add>
<add>- [#18071](https://github.com/emberjs/ember.js/pull/18071) [BUGFIX] Ensure modifiers do not run in FastBoot modes. (#18071)
<add>- [#18064](https://github.com/emberjs/ember.js/pull/18064) [BUGFIX] Fix 'hasAttribute is not a function' when jQuery is disabled (#18064)
<add>- [#17974](https://github.com/emberjs/ember.js/pull/17974) [BUGFIX] Ensure inheritable observers on object proxies are string based
<add>- [#17859](https://github.com/emberjs/ember.js/pull/17859) [BUGFIX] Fixes a regression in the legacy build
<add>
<ide> ### v3.8.1 (April 02, 2019)
<ide>
<ide> - [#17684](https://github.com/emberjs/ember.js/pull/17684) [BUGFIX] Enable maximum rerendering limit to be customized. | 1 |
Python | Python | add training call argument for multiheadattention | 229f1dd5a31655a810809965d6b1019e03c29362 | <ide><path>official/nlp/modeling/layers/talking_heads_attention.py
<ide> def _compute_attention(self,
<ide> query_tensor,
<ide> key_tensor,
<ide> value_tensor,
<del> attention_mask=None):
<add> attention_mask=None,
<add> training=None):
<ide> """Applies Dot-product attention with query, key, value tensors.
<ide>
<ide> This function overrides base class to apply additional linear projection
<ide> def _compute_attention(self,
<ide> value_tensor: Projected value `Tensor` of shape `[B, T, N, value_dim]`.
<ide> attention_mask: a boolean mask of shape `[B, T, S]`, that prevents
<ide> attention to certain positions.
<add> training: Python boolean indicating whether the layer should behave in
<add> training mode (adding dropout) or in inference mode (doing nothing).
<ide>
<ide> Returns:
<ide> attention_output: Multi-headed outputs of attention computation.
<ide> def _compute_attention(self,
<ide>
<ide> # This is actually dropping out entire tokens to attend to, which might
<ide> # seem a bit unusual, but is taken from the original Transformer paper.
<del> attention_scores_dropout = self._dropout_layer(attention_scores)
<add> attention_scores_dropout = self._dropout_layer(
<add> attention_scores, training=training)
<ide>
<ide> # `context_layer` = [B, T, N, H]
<ide> attention_output = tf.einsum(self._combine_equation, | 1 |
Javascript | Javascript | use fixtures in test-process-warnings | cd64b4166b4001bdcd45ac808e2c9715956d52e1 | <ide><path>test/sequential/test-process-warnings.js
<ide> 'use strict';
<ide>
<del>const common = require('../common');
<add>require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<ide> const execFile = require('child_process').execFile;
<del>const warnmod = require.resolve(`${common.fixturesDir}/warnings.js`);
<add>const warnmod = require.resolve(fixtures.path('warnings.js'));
<ide> const node = process.execPath;
<ide>
<ide> const normal = [warnmod]; | 1 |
Text | Text | update collaborator email in readme | 4d47bba467f380ee16cb6e7239d530811b9c03e2 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> * [gibfahn](https://github.com/gibfahn) -
<ide> **Gibson Fahnestock** <gibfahn@gmail.com> (he/him)
<ide> * [indutny](https://github.com/indutny) -
<del>**Fedor Indutny** <fedor.indutny@gmail.com>
<add>**Fedor Indutny** <fedor@indutny.com>
<ide> * [isaacs](https://github.com/isaacs) -
<ide> **Isaac Z. Schlueter** <i@izs.me>
<ide> * [joshgav](https://github.com/joshgav) -
<ide> For information about the governance of the Node.js project, see
<ide> * [iansu](https://github.com/iansu) -
<ide> **Ian Sutherland** <ian@iansutherland.ca>
<ide> * [indutny](https://github.com/indutny) -
<del>**Fedor Indutny** <fedor.indutny@gmail.com>
<add>**Fedor Indutny** <fedor@indutny.com>
<ide> * [JacksonTian](https://github.com/JacksonTian) -
<ide> **Jackson Tian** <shyvo1987@gmail.com>
<ide> * [jasnell](https://github.com/jasnell) - | 1 |
Ruby | Ruby | use copy instead of export for release | cf0467c6425a528acfe2cb14709253a8a4a99b37 | <ide><path>release.rb
<ide> VERSION = ARGV.first
<ide> PACKAGES = %w(activesupport activerecord actionpack actionmailer activeresource)
<ide>
<del># Checkout source
<del># `rm -rf release && svn export http://dev.rubyonrails.org/svn/rails/trunk release`
<add># Copy source
<add>`mkdir release`
<add>(PACKAGES + %w(railties)).each do |p|
<add> `cp -R #{p} release/#{p}`
<add>end
<ide>
<ide> # Create Rails packages
<ide> `cd release/railties && rake template=jamis package` | 1 |
Text | Text | fix small typo in 15.11.0 release | ed633f239f4a16af255d5dd21b112cf7f2f446d7 | <ide><path>doc/changelogs/CHANGELOG_V15.md
<ide>
<ide> ### Notable Changes
<ide>
<del>* [[`a3e3156b52`](https://github.com/nodejs/node/commit/a3e3156b52)] - **(SEMVER-MINOR)** **crypto**: make FIPS related options always awailable (Vít Ondruch) [#36341](https://github.com/nodejs/node/pull/36341)
<add>* [[`a3e3156b52`](https://github.com/nodejs/node/commit/a3e3156b52)] - **(SEMVER-MINOR)** **crypto**: make FIPS related options always available (Vít Ondruch) [#36341](https://github.com/nodejs/node/pull/36341)
<ide> * [[`9ba5c0f9ba`](https://github.com/nodejs/node/commit/9ba5c0f9ba)] - **(SEMVER-MINOR)** **errors**: remove experimental from --enable-source-maps (Benjamin Coe) [#37362](https://github.com/nodejs/node/pull/37362)
<ide>
<ide> ### Commits | 1 |
Python | Python | fix test_utils.py for python 3.7 | dce7f20e95e6bd3fc07517c0b2daf3942a34ddf7 | <ide><path>numpy/testing/tests/test_utils.py
<ide> def test_simple(self):
<ide> lambda: assert_string_equal("foo", "hello"))
<ide>
<ide>
<del>def assert_warn_len_equal(mod, n_in_context, py3_n_in_context=None):
<add>def assert_warn_len_equal(mod, n_in_context, py34=None, py37=None):
<ide> mod_warns = mod.__warningregistry__
<add> num_warns = len(mod_warns)
<ide> # Python 3.4 appears to clear any pre-existing warnings of the same type,
<ide> # when raising warnings inside a catch_warnings block. So, there is a
<ide> # warning generated by the tests within the context manager, but no
<ide> # previous warnings.
<ide> if 'version' in mod_warns:
<del> if py3_n_in_context is None:
<del> py3_n_in_context = n_in_context
<del> assert_equal(len(mod_warns) - 1, py3_n_in_context)
<del> else:
<del> assert_equal(len(mod_warns), n_in_context)
<add> # Python 3 adds a 'version' entry to the registry,
<add> # do not count it.
<add> num_warns -= 1
<add>
<add> # Behavior of warnings is Python version dependent. Adjust the
<add> # expected result to compensate. In particular, Python 3.7 does
<add> # not make an entry for ignored warnings.
<add> if sys.version_info[:2] >= (3, 7):
<add> if py37 is not None:
<add> n_in_context = py37
<add> elif sys.version_info[:2] >= (3, 4):
<add> if py34 is not None:
<add> n_in_context = py34
<add> assert_equal(num_warns, n_in_context)
<ide>
<ide>
<ide> def _get_fresh_mod():
<ide> def _get_fresh_mod():
<ide> try:
<ide> my_mod.__warningregistry__.clear()
<ide> except AttributeError:
<add> # will not have a __warningregistry__ unless warning has been
<add> # raised in the module at some point
<ide> pass
<ide> return my_mod
<ide>
<ide> def test_clear_and_catch_warnings():
<ide> warnings.warn('Some warning')
<ide> assert_equal(my_mod.__warningregistry__, {})
<ide> # Without specified modules, don't clear warnings during context
<add> # Python 3.7 catch_warnings doesn't make an entry for 'ignore'.
<ide> with clear_and_catch_warnings():
<ide> warnings.simplefilter('ignore')
<ide> warnings.warn('Some warning')
<del> assert_warn_len_equal(my_mod, 1)
<add> assert_warn_len_equal(my_mod, 1, py37=0)
<ide> # Confirm that specifying module keeps old warning, does not add new
<ide> with clear_and_catch_warnings(modules=[my_mod]):
<ide> warnings.simplefilter('ignore')
<ide> warnings.warn('Another warning')
<del> assert_warn_len_equal(my_mod, 1)
<add> assert_warn_len_equal(my_mod, 1, py37=0)
<ide> # Another warning, no module spec does add to warnings dict, except on
<ide> # Python 3.4 (see comments in `assert_warn_len_equal`)
<add> # Python 3.7 catch_warnings doesn't make an entry for 'ignore'.
<ide> with clear_and_catch_warnings():
<ide> warnings.simplefilter('ignore')
<ide> warnings.warn('Another warning')
<del> assert_warn_len_equal(my_mod, 2, 1)
<add> assert_warn_len_equal(my_mod, 2, py34=1, py37=0)
<ide>
<ide>
<ide> def test_suppress_warnings_module():
<ide> def warn(arr):
<ide> np.apply_along_axis(warn, 0, [0])
<ide>
<ide> # Test module based warning suppression:
<add> assert_warn_len_equal(my_mod, 0)
<ide> with suppress_warnings() as sup:
<ide> sup.record(UserWarning)
<ide> # suppress warning from other module (may have .pyc ending),
<ide> def warn(arr):
<ide> # got filtered)
<ide> assert_(len(sup.log) == 1)
<ide> assert_(sup.log[0].message.args[0] == "Some warning")
<del>
<del> assert_warn_len_equal(my_mod, 0)
<add> assert_warn_len_equal(my_mod, 0, py37=0)
<ide> sup = suppress_warnings()
<ide> # Will have to be changed if apply_along_axis is moved:
<ide> sup.filter(module=my_mod)
<ide> def warn(arr):
<ide> assert_warn_len_equal(my_mod, 0)
<ide>
<ide> # Without specified modules, don't clear warnings during context
<add> # Python 3.7 does not add ignored warnings.
<ide> with suppress_warnings():
<ide> warnings.simplefilter('ignore')
<ide> warnings.warn('Some warning')
<del> assert_warn_len_equal(my_mod, 1)
<del>
<add> assert_warn_len_equal(my_mod, 1, py37=0)
<ide>
<ide> def test_suppress_warnings_type():
<ide> # Initial state of module, no warnings
<ide> def test_suppress_warnings_type():
<ide> assert_warn_len_equal(my_mod, 0)
<ide>
<ide> # Without specified modules, don't clear warnings during context
<add> # Python 3.7 does not add ignored warnings.
<ide> with suppress_warnings():
<ide> warnings.simplefilter('ignore')
<ide> warnings.warn('Some warning')
<del> assert_warn_len_equal(my_mod, 1)
<add> assert_warn_len_equal(my_mod, 1, py37=0)
<ide>
<ide>
<ide> def test_suppress_warnings_decorate_no_record(): | 1 |
Ruby | Ruby | prefer method sensors over actual ddl changes | 8037c51083c99c3f8925a6236a9969e697fab410 | <ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_add_table_with_decimals
<ide> assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) }
<ide> end
<ide>
<del> def test_migrator
<del> assert !Person.column_methods_hash.include?(:last_name)
<del> assert !Reminder.table_exists?
<del>
<del> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid")
<del>
<del> assert_equal 3, ActiveRecord::Migrator.current_version
<del> Person.reset_column_information
<del> assert Person.column_methods_hash.include?(:last_name)
<del> assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
<del> assert_equal "hello world", Reminder.find(:first).content
<del>
<del> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
<del>
<del> assert_equal 0, ActiveRecord::Migrator.current_version
<del> Person.reset_column_information
<del> assert !Person.column_methods_hash.include?(:last_name)
<del> assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
<del> end
<del>
<ide> def test_filtering_migrations
<ide> assert !Person.column_methods_hash.include?(:last_name)
<ide> assert !Reminder.table_exists?
<ide> def test_instance_based_migration_down
<ide> assert migration.went_down, 'have not gone down'
<ide> end
<ide>
<del> def test_migrator_one_up
<del> assert !Person.column_methods_hash.include?(:last_name)
<del> assert !Reminder.table_exists?
<del>
<del> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
<del>
<del> Person.reset_column_information
<del> assert Person.column_methods_hash.include?(:last_name)
<del> assert !Reminder.table_exists?
<del>
<del> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 2)
<del>
<del> assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
<del> assert_equal "hello world", Reminder.find(:first).content
<del> end
<del>
<del> def test_migrator_one_down
<del> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid")
<del>
<del> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 1)
<del>
<del> Person.reset_column_information
<del> assert Person.column_methods_hash.include?(:last_name)
<del> assert !Reminder.table_exists?
<del> end
<del>
<del> def test_migrator_one_up_one_down
<del> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
<del> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
<del>
<del> assert !Person.column_methods_hash.include?(:last_name)
<del> assert !Reminder.table_exists?
<del> end
<del>
<del> def test_migrator_double_up
<del> assert_equal(0, ActiveRecord::Migrator.current_version)
<del> ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1)
<del> assert_nothing_raised { ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) }
<del> assert_equal(1, ActiveRecord::Migrator.current_version)
<del> end
<del>
<del> def test_migrator_double_down
<del> assert_equal(0, ActiveRecord::Migrator.current_version)
<del> ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1)
<del> ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1)
<del> assert_nothing_raised { ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) }
<del> assert_equal(0, ActiveRecord::Migrator.current_version)
<del> end
<del>
<ide> def test_migrator_one_up_with_exception_and_rollback
<ide> unless ActiveRecord::Base.connection.supports_ddl_transactions?
<ide> skip "not supported on #{ActiveRecord::Base.connection.class}"
<ide><path>activerecord/test/cases/migrator_test.rb
<ide> def test_current_version
<ide> ActiveRecord::SchemaMigration.create!(:version => '1000')
<ide> assert_equal 1000, ActiveRecord::Migrator.current_version
<ide> end
<add>
<add> def test_migrator_one_up
<add> calls, migrations = sensors(3)
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 1).migrate
<add> assert_equal [[:up, 0], [:up, 1]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 2).migrate
<add> assert_equal [[:up, 2]], calls
<add> end
<add>
<add> def test_migrator_one_down
<add> calls, migrations = sensors(3)
<add>
<add> ActiveRecord::Migrator.new(:up, migrations).migrate
<add> assert_equal [[:up, 0], [:up, 1], [:up, 2]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:down, migrations, 1).migrate
<add>
<add> assert_equal [[:down, 2]], calls
<add> end
<add>
<add> def test_migrator_one_up_one_down
<add> calls, migrations = sensors(3)
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 1).migrate
<add> assert_equal [[:up, 0], [:up, 1]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:down, migrations, 0).migrate
<add> assert_equal [[:down, 1]], calls
<add> end
<add>
<add> def test_migrator_double_up
<add> calls, migrations = sensors(3)
<add> assert_equal(0, ActiveRecord::Migrator.current_version)
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 1).migrate
<add> assert_equal [[:up, 0], [:up, 1]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 1).migrate
<add> assert_equal [], calls
<add> end
<add>
<add> def test_migrator_double_down
<add> calls, migrations = sensors(3)
<add>
<add> assert_equal(0, ActiveRecord::Migrator.current_version)
<add>
<add> ActiveRecord::Migrator.new(:up, migrations, 1).run
<add> assert_equal [[:up, 1]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:down, migrations, 1).run
<add> assert_equal [[:down, 1]], calls
<add> calls.clear
<add>
<add> ActiveRecord::Migrator.new(:down, migrations, 1).run
<add> assert_equal [], calls
<add>
<add> assert_equal(0, ActiveRecord::Migrator.current_version)
<add> end
<add>
<add> private
<add> def m(name, version, &block)
<add> x = Sensor.new name, version
<add> x.extend(Module.new {
<add> define_method(:up) { block.call(:up, x); super() }
<add> define_method(:down) { block.call(:down, x); super() }
<add> }) if block_given?
<add> end
<add>
<add> def sensors(count)
<add> calls = []
<add> migrations = 3.times.map { |i|
<add> m(nil, i) { |c,migration|
<add> calls << [c, migration.version]
<add> }
<add> }
<add> [calls, migrations]
<add> end
<ide> end
<ide> end | 2 |
Ruby | Ruby | fix go_cache cleanup | 9102c120bb0ab57added0ea60edcc160ce37e136 | <ide><path>Library/Homebrew/cleanup.rb
<ide> def nested_cache?
<ide> directory? && %w[go_cache glide_home java_cache npm_cache gclient_cache].include?(basename.to_s)
<ide> end
<ide>
<add> def go_cache_directory?
<add> # Go makes its cache contents read-only to ensure cache integrity,
<add> # which makes sense but is something we need to undo for cleanup.
<add> directory? && %w[go_cache].include?(basename.to_s)
<add> end
<add>
<ide> def prune?(days)
<ide> return false unless days
<ide> return true if days.zero?
<ide> def cleanup_cache(entries = nil)
<ide> entries ||= [cache, cache/"Cask"].select(&:directory?).flat_map(&:children)
<ide>
<ide> entries.each do |path|
<add> FileUtils.chmod_R 0755, path if path.go_cache_directory? && !dry_run?
<ide> next cleanup_path(path) { path.unlink } if path.incomplete?
<ide> next cleanup_path(path) { FileUtils.rm_rf path } if path.nested_cache?
<ide> | 1 |
Text | Text | remove changelog entry for | 38bda383ee24c30e5a68db1f01c740b9d7dfad98 | <ide><path>railties/CHANGELOG.md
<ide>
<ide> *Gabe Kopley*
<ide>
<del>* `Rails.version` now returns an instance of `Gem::Version`
<del>
<del> *Charlie Somerville*
<del>
<ide> * Don't generate a scaffold.css when --no-assets is specified
<ide>
<ide> *Kevin Glowacz* | 1 |
Java | Java | remove unused var | 888a1e63d5b0c7cd943846345754c12b1d6f1999 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java
<ide> public PendingJSCall(
<ide> private boolean mInitialized = false;
<ide> private volatile boolean mAcceptCalls = false;
<ide>
<del> private boolean mJSBundleHasStartedLoading;
<ide> private boolean mJSBundleHasLoaded;
<ide> private @Nullable String mSourceURL;
<ide>
<ide> private native void initializeBridge(
<ide> public void runJSBundle() {
<ide> Assertions.assertCondition(!mJSBundleHasLoaded, "JS bundle was already loaded!");
<ide>
<del> mJSBundleHasStartedLoading = true;
<del>
<ide> // incrementPendingJSCalls();
<ide> mJSBundleLoader.loadScript(CatalystInstanceImpl.this);
<ide> | 1 |
Go | Go | remove job from commit | c8529fde5f6f2e4b62f9c1b3382fd814c11a7639 | <ide><path>api/server/server.go
<ide> func postCommit(eng *engine.Engine, version version.Version, w http.ResponseWrit
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<del> var (
<del> config engine.Env
<del> job = eng.Job("commit", r.Form.Get("container"))
<del> stdoutBuffer = bytes.NewBuffer(nil)
<del> )
<ide>
<ide> if err := checkForJson(r); err != nil {
<ide> return err
<ide> }
<ide>
<del> if err := config.Decode(r.Body); err != nil {
<del> logrus.Errorf("%s", err)
<del> }
<add> cont := r.Form.Get("container")
<ide>
<add> pause := toBool(r.Form.Get("pause"))
<ide> if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
<del> job.Setenv("pause", "1")
<del> } else {
<del> job.Setenv("pause", r.FormValue("pause"))
<add> pause = true
<ide> }
<ide>
<del> job.Setenv("repo", r.Form.Get("repo"))
<del> job.Setenv("tag", r.Form.Get("tag"))
<del> job.Setenv("author", r.Form.Get("author"))
<del> job.Setenv("comment", r.Form.Get("comment"))
<del> job.SetenvList("changes", r.Form["changes"])
<del> job.SetenvSubEnv("config", &config)
<add> containerCommitConfig := &daemon.ContainerCommitConfig{
<add> Pause: pause,
<add> Repo: r.Form.Get("repo"),
<add> Tag: r.Form.Get("tag"),
<add> Author: r.Form.Get("author"),
<add> Comment: r.Form.Get("comment"),
<add> Changes: r.Form["changes"],
<add> Config: r.Body,
<add> }
<ide>
<del> job.Stdout.Add(stdoutBuffer)
<del> if err := job.Run(); err != nil {
<add> d := getDaemon(eng)
<add>
<add> imgID, err := d.ContainerCommit(cont, containerCommitConfig)
<add> if err != nil {
<ide> return err
<ide> }
<add>
<ide> return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
<del> ID: engine.Tail(stdoutBuffer, 1),
<add> ID: imgID,
<ide> })
<ide> }
<ide>
<ide><path>daemon/commit.go
<ide> package daemon
<ide> import (
<ide> "bytes"
<ide> "encoding/json"
<del> "fmt"
<add> "io"
<ide>
<add> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerCommit(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("Not enough arguments. Usage: %s CONTAINER\n", job.Name)
<del> }
<del> name := job.Args[0]
<add>type ContainerCommitConfig struct {
<add> Pause bool
<add> Repo string
<add> Tag string
<add> Author string
<add> Comment string
<add> Changes []string
<add> Config io.ReadCloser
<add>}
<ide>
<add>func (daemon *Daemon) ContainerCommit(name string, c *ContainerCommitConfig) (string, error) {
<ide> container, err := daemon.Get(name)
<ide> if err != nil {
<del> return err
<add> return "", err
<ide> }
<ide>
<ide> var (
<add> subenv engine.Env
<ide> config = container.Config
<ide> stdoutBuffer = bytes.NewBuffer(nil)
<ide> newConfig runconfig.Config
<ide> )
<ide>
<add> if err := subenv.Decode(c.Config); err != nil {
<add> logrus.Errorf("%s", err)
<add> }
<add>
<ide> buildConfigJob := daemon.eng.Job("build_config")
<ide> buildConfigJob.Stdout.Add(stdoutBuffer)
<del> buildConfigJob.Setenv("changes", job.Getenv("changes"))
<add> buildConfigJob.SetenvList("changes", c.Changes)
<ide> // FIXME this should be remove when we remove deprecated config param
<del> buildConfigJob.Setenv("config", job.Getenv("config"))
<add> buildConfigJob.SetenvSubEnv("config", &subenv)
<ide>
<ide> if err := buildConfigJob.Run(); err != nil {
<del> return err
<add> return "", err
<ide> }
<ide> if err := json.NewDecoder(stdoutBuffer).Decode(&newConfig); err != nil {
<del> return err
<add> return "", err
<ide> }
<ide>
<ide> if err := runconfig.Merge(&newConfig, config); err != nil {
<del> return err
<add> return "", err
<ide> }
<ide>
<del> img, err := daemon.Commit(container, job.Getenv("repo"), job.Getenv("tag"), job.Getenv("comment"), job.Getenv("author"), job.GetenvBool("pause"), &newConfig)
<add> img, err := daemon.Commit(container, c.Repo, c.Tag, c.Comment, c.Author, c.Pause, &newConfig)
<ide> if err != nil {
<del> return err
<add> return "", err
<ide> }
<del> job.Printf("%s\n", img.ID)
<del> return nil
<add>
<add> return img.ID, nil
<ide> }
<ide>
<ide> // Commit creates a new filesystem image from the current state of a container.
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> // Install installs daemon capabilities to eng.
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> for name, method := range map[string]engine.Handler{
<del> "commit": daemon.ContainerCommit,
<ide> "container_inspect": daemon.ContainerInspect,
<ide> "container_stats": daemon.ContainerStats,
<ide> "create": daemon.ContainerCreate,
<ide><path>integration/server_test.go
<ide> package docker
<ide>
<del>import (
<del> "bytes"
<del> "testing"
<del>
<del> "github.com/docker/docker/builder"
<del> "github.com/docker/docker/engine"
<del>)
<add>import "testing"
<ide>
<ide> func TestCreateNumberHostname(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> func TestCreateNumberHostname(t *testing.T) {
<ide> createTestContainer(eng, config, t)
<ide> }
<ide>
<del>func TestCommit(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> b := &builder.BuilderJob{Engine: eng}
<del> b.Install()
<del> defer mkDaemonFromEngine(eng, t).Nuke()
<del>
<del> config, _, _, err := parseRun([]string{unitTestImageID, "/bin/cat"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> id := createTestContainer(eng, config, t)
<del>
<del> job := eng.Job("commit", id)
<del> job.Setenv("repo", "testrepo")
<del> job.Setenv("tag", "testtag")
<del> job.SetenvJson("config", config)
<del> if err := job.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del>}
<del>
<del>func TestMergeConfigOnCommit(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> b := &builder.BuilderJob{Engine: eng}
<del> b.Install()
<del> runtime := mkDaemonFromEngine(eng, t)
<del> defer runtime.Nuke()
<del>
<del> container1, _, _ := mkContainer(runtime, []string{"-e", "FOO=bar", unitTestImageID, "echo test > /tmp/foo"}, t)
<del> defer runtime.Rm(container1)
<del>
<del> config, _, _, err := parseRun([]string{container1.ID, "cat /tmp/foo"})
<del> if err != nil {
<del> t.Error(err)
<del> }
<del>
<del> job := eng.Job("commit", container1.ID)
<del> job.Setenv("repo", "testrepo")
<del> job.Setenv("tag", "testtag")
<del> job.SetenvJson("config", config)
<del> var outputBuffer = bytes.NewBuffer(nil)
<del> job.Stdout.Add(outputBuffer)
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> container2, _, _ := mkContainer(runtime, []string{engine.Tail(outputBuffer, 1)}, t)
<del> defer runtime.Rm(container2)
<del>
<del> job = eng.Job("container_inspect", container1.Name)
<del> baseContainer, _ := job.Stdout.AddEnv()
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> job = eng.Job("container_inspect", container2.Name)
<del> commitContainer, _ := job.Stdout.AddEnv()
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> baseConfig := baseContainer.GetSubEnv("Config")
<del> commitConfig := commitContainer.GetSubEnv("Config")
<del>
<del> if commitConfig.Get("Env") != baseConfig.Get("Env") {
<del> t.Fatalf("Env config in committed container should be %v, was %v",
<del> baseConfig.Get("Env"), commitConfig.Get("Env"))
<del> }
<del>
<del> if baseConfig.Get("Cmd") != "[\"echo test \\u003e /tmp/foo\"]" {
<del> t.Fatalf("Cmd in base container should be [\"echo test \\u003e /tmp/foo\"], was %s",
<del> baseConfig.Get("Cmd"))
<del> }
<del>
<del> if commitConfig.Get("Cmd") != "[\"cat /tmp/foo\"]" {
<del> t.Fatalf("Cmd in committed container should be [\"cat /tmp/foo\"], was %s",
<del> commitConfig.Get("Cmd"))
<del> }
<del>}
<del>
<ide> func TestRunWithTooLowMemoryLimit(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkDaemonFromEngine(eng, t).Nuke() | 4 |
Ruby | Ruby | replace if ! with unless | ea14396c455b0816e87abe424275290fc4b09b32 | <ide><path>actionmailer/lib/action_mailer/old_api.rb
<ide> def create_parts
<ide>
<ide> # If this is a multipart e-mail add the mime_version if it is not
<ide> # already set.
<del> @mime_version ||= "1.0" if !@parts.empty?
<add> @mime_version ||= "1.0" unless @parts.empty?
<ide> end
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb
<ide> def request_http_token_authentication(realm = "Application")
<ide> # Returns nil if no token is found.
<ide> def authenticate(controller, &login_procedure)
<ide> token, options = token_and_options(controller.request)
<del> if !token.blank?
<add> unless token.blank?
<ide> login_procedure.call(token, options)
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
<ide> def self.establish_connection(spec = nil)
<ide> end
<ide>
<ide> adapter_method = "#{spec[:adapter]}_connection"
<del> if !respond_to?(adapter_method)
<add> unless respond_to?(adapter_method)
<ide> raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/dependencies.rb
<ide> def self.exclude_from(base)
<ide> def const_missing(const_name, nesting = nil)
<ide> klass_name = name.presence || "Object"
<ide>
<del> if !nesting
<add> unless nesting
<ide> # We'll assume that the nesting of Foo::Bar is ["Foo::Bar", "Foo"]
<ide> # even though it might not be, such as in the case of
<ide> # class Foo::Bar; Baz; end
<ide><path>activesupport/lib/active_support/secure_random.rb
<ide> def self.random_bytes(n=nil)
<ide> end
<ide> end
<ide>
<del> if !defined?(@has_win32)
<add> unless defined?(@has_win32)
<ide> begin
<ide> require 'Win32API'
<ide>
<ide><path>railties/lib/rails/application.rb
<ide> def default_middleware_stack
<ide> middleware.use ::Rack::Cache, rack_cache if rack_cache
<ide>
<ide> middleware.use ::ActionDispatch::Static, config.static_asset_paths if config.serve_static_assets
<del> middleware.use ::Rack::Lock if !config.allow_concurrency
<add> middleware.use ::Rack::Lock unless config.allow_concurrency
<ide> middleware.use ::Rack::Runtime
<ide> middleware.use ::Rails::Rack::Logger
<ide> middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local if config.action_dispatch.show_exceptions
<ide><path>railties/lib/rails/rack/log_tailer.rb
<ide> def call(env)
<ide> def tail!
<ide> @file.seek @cursor
<ide>
<del> if !@file.eof?
<add> unless @file.eof?
<ide> contents = @file.read
<ide> @cursor = @file.tell
<ide> $stdout.print contents | 7 |
Python | Python | add tuple and set to allowed listfield data types | b9316154b163ee6ecf2005f986f40f7fe7ef5bcc | <ide><path>rest_framework/fields.py
<ide> from __future__ import unicode_literals
<add>from sets import Set
<ide>
<ide> import collections
<ide> import copy
<ide> def to_internal_value(self, data):
<ide> """
<ide> if html.is_html_input(data):
<ide> data = html.parse_html_list(data)
<del> if not isinstance(data, list):
<add> if not isinstance(data, (list, tuple, Set)):
<ide> self.fail('not_a_list', input_type=type(data).__name__)
<ide> if not self.allow_empty and len(data) == 0:
<ide> self.fail('empty') | 1 |
PHP | PHP | backport the better faker default | 3a2cfbc2f4f59e4c602781a8a49931c487d65f55 | <ide><path>database/factories/ModelFactory.php
<ide> $factory->define(App\User::class, function (Faker\Generator $faker) {
<ide> return [
<ide> 'name' => $faker->name,
<del> 'email' => $faker->email,
<add> 'email' => $faker->safeEmail,
<ide> 'password' => bcrypt(str_random(10)),
<ide> 'remember_token' => str_random(10),
<ide> ]; | 1 |
Javascript | Javascript | update error message on unrecognized commands | 16a97c80274ef50493b30e1b4871ba4bbae1f447 | <ide><path>react-native-cli/index.js
<ide> if (cli) {
<ide> default:
<ide> console.error(
<ide> 'Command `%s` unrecognized. ' +
<del> 'Did you mean to run this inside a react-native project?',
<add> 'Make sure that you have run `npm install` and that you are inside a react-native project.',
<ide> commands[0]
<ide> );
<ide> process.exit(1); | 1 |
Javascript | Javascript | fix typo that happened during rebasing | 168da8d55782f3b34e2a6aa0c4dd0587696afdbd | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> export function isInterleavedUpdate(fiber: Fiber, lane: Lane) {
<ide> // defensive coding measure in case a new update comes in between when
<ide> // rendering has finished and when the interleaved updates are transferred
<ide> // to the main queue.
<del> hasInterleavedUpdates() !== null) &&
<add> hasInterleavedUpdates()) &&
<ide> (fiber.mode & ConcurrentMode) !== NoMode &&
<ide> // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps),
<ide> // then don't treat this as an interleaved update. This pattern is
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> export function isInterleavedUpdate(fiber: Fiber, lane: Lane) {
<ide> // defensive coding measure in case a new update comes in between when
<ide> // rendering has finished and when the interleaved updates are transferred
<ide> // to the main queue.
<del> hasInterleavedUpdates() !== null) &&
<add> hasInterleavedUpdates()) &&
<ide> (fiber.mode & ConcurrentMode) !== NoMode &&
<ide> // If this is a render phase update (i.e. UNSAFE_componentWillReceiveProps),
<ide> // then don't treat this as an interleaved update. This pattern is | 2 |
Ruby | Ruby | exclude template files for rdoc api [ci skip] | a77ad86ff1be70dee945e6425b3209ab8da72cd4 | <ide><path>railties/lib/rails/api/task.rb
<ide> class Task < RDoc::Task
<ide> CHANGELOG.md
<ide> MIT-LICENSE
<ide> lib/**/*.rb
<del> )
<add> ),
<add> :exclude => 'lib/rails/generators/rails/**/templates/**/*.rb'
<ide> }
<ide> }
<ide> | 1 |
Python | Python | use mongodb color for mongotos3operator | cddbf9c11d092422e6695d7a5a5c859fdf140753 | <ide><path>airflow/providers/amazon/aws/transfers/mongo_to_s3.py
<ide> class MongoToS3Operator(BaseOperator):
<ide> """
<ide>
<ide> template_fields = ('s3_bucket', 's3_key', 'mongo_query', 'mongo_collection')
<add> ui_color = '#589636'
<ide> # pylint: disable=too-many-instance-attributes
<ide>
<ide> @apply_defaults | 1 |
Javascript | Javascript | use willdestroy in stead of destroy | aca371cb177d504cf844fb81b7de70578e29e611 | <ide><path>packages/@ember/-internals/runtime/lib/mixins/-proxy.js
<ide> export default Mixin.create({
<ide> m.writableTag(() => combine([DirtyableTag.create(), UpdatableTag.create(CONSTANT_TAG)]));
<ide> },
<ide>
<del> destroy() {
<del> this._super(...arguments);
<add> willDestroy() {
<ide> this.set('content', null);
<add> this._super(...arguments);
<ide> },
<ide>
<ide> isTruthy: computed('content', function() { | 1 |
Ruby | Ruby | remove unused variable | d89a696d83cd325656e30a99cb4ba8342ffb39c9 | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_installed_alias_with_core
<ide> def test_installed_alias_with_tap
<ide> tap = Tap.new("user", "repo")
<ide> name = "foo"
<del> full_name = "#{tap.user}/#{tap.repo}/#{name}"
<ide> path = "#{tap.path}/Formula/#{name}.rb"
<ide> f = formula(name, path) { url "foo-1.0" }
<ide> | 1 |
Java | Java | replace foreach with putall | 2afe560e41c52c51a36314de3884416a9b1ed432 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/BindingContext.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Mono<Map<String, Object>> getValuesToBind(ServerWebExchange exchange) {
<ide> return Mono.zip(Mono.just(vars), Mono.just(queryParams), formData, multipartData)
<ide> .map(tuple -> {
<ide> Map<String, Object> result = new TreeMap<>();
<del> tuple.getT1().forEach(result::put);
<add> result.putAll(tuple.getT1());
<ide> tuple.getT2().forEach((key, values) -> addBindValue(result, key, values));
<ide> tuple.getT3().forEach((key, values) -> addBindValue(result, key, values));
<ide> tuple.getT4().forEach((key, values) -> addBindValue(result, key, values));
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/JettyWebSocketClient.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private Object createHandler(URI url, WebSocketHandler handler, Sinks.Empty<Void
<ide>
<ide> private HandshakeInfo createHandshakeInfo(URI url, Session jettySession) {
<ide> HttpHeaders headers = new HttpHeaders();
<del> jettySession.getUpgradeResponse().getHeaders().forEach(headers::put);
<add> headers.putAll(jettySession.getUpgradeResponse().getHeaders());
<ide> String protocol = headers.getFirst("Sec-WebSocket-Protocol");
<ide> return new HandshakeInfo(url, headers, Mono.empty(), protocol);
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/StandardWebSocketClient.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void beforeRequest(Map<String, List<String>> requestHeaders) {
<ide>
<ide> @Override
<ide> public void afterResponse(HandshakeResponse response) {
<del> response.getHeaders().forEach(this.responseHeaders::put);
<add> this.responseHeaders.putAll(response.getHeaders());
<ide> }
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public HttpHeaders getResponseHeaders() {
<ide>
<ide> @Override
<ide> public void beforeRequest(Map<String, List<String>> headers) {
<del> this.requestHeaders.forEach(headers::put);
<add> headers.putAll(this.requestHeaders);
<ide> if (this.delegate != null) {
<ide> this.delegate.beforeRequest(headers);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void afterRequest(Map<String, List<String>> headers) {
<del> headers.forEach(this.responseHeaders::put);
<add> this.responseHeaders.putAll(headers);
<ide> if (this.delegate != null) {
<ide> this.delegate.afterRequest(headers);
<ide> } | 4 |
Javascript | Javascript | handle tick callbacks after each tick | 4e5fe2d45aef5aacf4a6c6c2db28f0b9cc64f123 | <ide><path>src/node.js
<ide>
<ide> if (domain) domain.exit();
<ide>
<add> // process the nextTicks after each time we get called.
<add> process._tickCallback();
<ide> return ret;
<ide> };
<ide> };
<ide> var nextTickQueue = [];
<ide> var nextTickIndex = 0;
<ide> var inTick = false;
<add> var tickDepth = 0;
<add>
<add> // the maximum number of times it'll process something like
<add> // nextTick(function f(){nextTick(f)})
<add> // It's unlikely, but not illegal, to hit this limit. When
<add> // that happens, it yields to libuv's tick spinner.
<add> // This is a loop counter, not a stack depth, so we aren't using
<add> // up lots of memory here. I/O can sneak in before nextTick if this
<add> // limit is hit, which is not ideal, but not terrible.
<add> process.maxTickDepth = 1000;
<ide>
<ide> function tickDone() {
<add> tickDepth = 0;
<ide> nextTickQueue.splice(0, nextTickIndex);
<ide> nextTickIndex = 0;
<ide> inTick = false;
<ide>
<ide> process._tickCallback = function() {
<ide> if (inTick) return;
<del> var nextTickLength = nextTickQueue.length;
<del> if (nextTickLength === 0) return;
<ide> inTick = true;
<ide>
<del> while (nextTickIndex < nextTickLength) {
<del> var tock = nextTickQueue[nextTickIndex++];
<del> var callback = tock.callback;
<del> if (tock.domain) {
<del> if (tock.domain._disposed) continue;
<del> tock.domain.enter();
<del> }
<del> var threw = true;
<del> try {
<del> callback();
<del> threw = false;
<del> } finally {
<del> if (threw) tickDone();
<del> }
<del> if (tock.domain) {
<del> tock.domain.exit();
<add> // always do this at least once. otherwise if process.maxTickDepth
<add> // is set to some negative value, we'd never process any of them.
<add> do {
<add> tickDepth++;
<add> var nextTickLength = nextTickQueue.length;
<add> if (nextTickLength === 0) return tickDone();
<add> while (nextTickIndex < nextTickLength) {
<add> var tock = nextTickQueue[nextTickIndex++];
<add> var callback = tock.callback;
<add> if (tock.domain) {
<add> if (tock.domain._disposed) continue;
<add> tock.domain.enter();
<add> }
<add> var threw = true;
<add> try {
<add> callback();
<add> threw = false;
<add> } finally {
<add> if (threw) tickDone();
<add> }
<add> if (tock.domain) {
<add> tock.domain.exit();
<add> }
<ide> }
<del> }
<add> nextTickQueue.splice(0, nextTickIndex);
<add> nextTickIndex = 0;
<add>
<add> // continue until the max depth or we run out of tocks.
<add> } while (tickDepth < process.maxTickDepth &&
<add> nextTickQueue.length > 0);
<ide>
<ide> tickDone();
<ide> };
<ide><path>test/simple/test-next-tick-intentional-starvation.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>// this is the inverse of test-next-tick-starvation.
<add>// it verifies that process.nextTick will *always* come before other
<add>// events, up to the limit of the process.maxTickDepth value.
<add>
<add>// WARNING: unsafe!
<add>process.maxTickDepth = Infinity;
<add>
<add>var ran = false;
<add>var starved = false;
<add>var start = +new Date();
<add>var timerRan = false;
<add>
<add>function spin() {
<add> ran = true;
<add> var now = +new Date();
<add> if (now - start > 100) {
<add> console.log('The timer is starving, just as we planned.');
<add> starved = true;
<add>
<add> // now let it out.
<add> return;
<add> }
<add>
<add> process.nextTick(spin);
<add>}
<add>
<add>function onTimeout() {
<add> if (!starved) throw new Error('The timer escaped!');
<add> console.log('The timer ran once the ban was lifted');
<add> timerRan = true;
<add>}
<add>
<add>spin();
<add>setTimeout(onTimeout, 50);
<add>
<add>process.on('exit', function() {
<add> assert.ok(ran);
<add> assert.ok(starved);
<add> assert.ok(timerRan);
<add>});
<ide><path>test/simple/test-process-active-wraps.js
<ide> function expect(activeHandles, activeRequests) {
<ide> expect(2, 1); // client handle doesn't shut down until next tick
<ide> })();
<ide>
<add>// Force the nextTicks to be deferred to a later time.
<add>process.maxTickDepth = 1;
<add>
<ide> process.nextTick(function() {
<ide> process.nextTick(function() {
<ide> process.nextTick(function() {
<del> // the handles should be gone but the connect req could still be alive
<del> assert.equal(process._getActiveHandles().length, 0);
<add> process.nextTick(function() {
<add> // the handles should be gone but the connect req could still be alive
<add> assert.equal(process._getActiveHandles().length, 0);
<add> });
<ide> });
<ide> });
<ide> }); | 3 |
Ruby | Ruby | remove rbx support | d4db443b1926b97660399f361e0b7a98ea24c608 | <ide><path>Library/Homebrew/dependency_collector.rb
<ide> class DependencyCollector
<ide> # Define the languages that we can handle as external dependencies.
<ide> LANGUAGE_MODULES = Set[
<del> :chicken, :jruby, :lua, :node, :ocaml, :perl, :python, :python3, :rbx, :ruby
<add> :chicken, :jruby, :lua, :node, :ocaml, :perl, :python, :python3, :ruby
<ide> ].freeze
<ide>
<ide> CACHE = {}
<ide><path>Library/Homebrew/requirements/language_module_requirement.rb
<ide> def the_test
<ide> when :python then %W[/usr/bin/env python -c import\ #{@import_name}]
<ide> when :python3 then %W[/usr/bin/env python3 -c import\ #{@import_name}]
<ide> when :ruby then %W[/usr/bin/env ruby -rubygems -e require\ '#{@import_name}']
<del> when :rbx then %W[/usr/bin/env rbx -rubygems -e require\ '#{@import_name}']
<ide> end
<ide> end
<ide>
<ide> def command_line
<ide> when :perl then "cpan -i"
<ide> when :python then "pip install"
<ide> when :python3 then "pip3 install"
<del> when :rbx then "rbx gem install"
<ide> when :ruby then "gem install"
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_language_module_requirement.rb
<ide> def test_good_ruby_deps
<ide> assert_deps_pass "date" => :ruby
<ide> end
<ide>
<del> if which("rbx")
<del> def test_bad_rubinius_deps
<del> assert_deps_fail "notapackage" => :rbx
<del> end
<del>
<del> def test_good_rubinius_deps
<del> assert_deps_pass "date" => :rbx
<del> end
<del> end
<del>
<ide> if which("csc")
<ide> def test_bad_chicken_deps
<ide> assert_deps_fail "notapackage" => :chicken | 3 |
Text | Text | add translation kr/threejs-tips.md | a9a96cfb8af23788ac97d77176ca1842daf2e865 | <ide><path>threejs/lessons/kr/threejs-tips.md
<add>Title: Three.js 팁
<add>Description: Three.js를 쓸 때 필요할 수도 있는 것들
<add>TOC: #
<add>
<add>이 글은 Three.js의 팁에 관한 글들 중 너무 짧아 별도의 글로 분리하기 애매한 글들을 묶은 것입니다.
<add>
<add>---
<add>
<add><a id="screenshot" data-toc="스크린샷 찍기"></a>
<add>
<add># 캔버스의 스크린샷 찍기
<add>
<add>브라우저에서 스크린샷을 찍을 수 있는 방법은 2가지 정도가 있습니다. 예전부터 사용하던 [`canvas.toDataURL`](https://developer.mozilla.org/ko/docs/Web/API/HTMLCanvasElement/toDataURL)과, 새로 등장한 [`canvas.toBlob`](https://developer.mozilla.org/ko/docs/Web/API/HTMLCanvasElement/toBlob)이 있죠.
<add>
<add>그냥 메서만 호출하면 되는 거라니, 얼핏 쉬워 보입니다. 아래 정도의 코드면 손쉽게 스크린샷을 찍을 수 있을 것 같네요.
<add>
<add>```html
<add><canvas id="c"></canvas>
<add>+<button id="screenshot" type="button">Save...</button>
<add>```
<add>
<add>```js
<add>const elem = document.querySelector('#screenshot');
<add>elem.addEventListener('click', () => {
<add> canvas.toBlob((blob) => {
<add> saveBlob(blob, `screencapture-${ canvas.width }x${ canvas.height }.png`);
<add> });
<add>});
<add>
<add>const saveBlob = (function() {
<add> const a = document.createElement('a');
<add> document.body.appendChild(a);
<add> a.style.display = 'none';
<add> return function saveData(blob, fileName) {
<add> const url = window.URL.createObjectURL(blob);
<add> a.href = url;
<add> a.download = fileName;
<add> a.click();
<add> };
<add>}());
<add>```
<add>
<add>아래는 [반응형 디자인](threejs-responsive.html)의 예제에 버튼과 버튼을 꾸밀 CSS를 추가한 예제입니다.
<add>
<add>{{{example url="../threejs-tips-screenshot-bad.html"}}}
<add>
<add>하지만 막상 스크린샷을 찍어보니 아래와 같은 결과가 나옵니다.
<add>
<add><div class="threejs_center"><img src="resources/images/screencapture-413x313.png"></div>
<add>
<add>그냥 텅 빈 이미지네요.
<add>
<add>물론 브라우저나/OS에 따라 잘 나오는 경우도 있을 수 있지만 대게의 경우 텅 빈 이미지가 나올 겁니다.
<add>
<add>이건 성능 관련 문제입니다. 기본적으로 브라우저는 화면을 렌더링한 후 WebGL 캔버스의 드로잉 버퍼를 바로 비웁니다.
<add>
<add>이 문제를 해결하려면 화면을 캡쳐하기 직전에 화면을 렌더링하는 함수를 호출해야 합니다.
<add>
<add>예제에서 몇 가지를 수정해야 합니다. 먼저 렌더링 함수를 분리합시다.
<add>
<add>```js
<add>+const state = {
<add>+ time: 0,
<add>+};
<add>
<add>-function render(time) {
<add>- time *= 0.001;
<add>+function render() {
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add> }
<add>
<add> cubes.forEach((cube, ndx) => {
<add> const speed = 1 + ndx * .1;
<add>- const rot = time * speed;
<add>+ const rot = state.time * speed;
<add> cube.rotation.x = rot;
<add> cube.rotation.y = rot;
<add> });
<add>
<add> renderer.render(scene, camera);
<add>
<add>- requestAnimationFrame(render);
<add>}
<add>
<add>+function animate(time) {
<add>+ state.time = time * 0.001;
<add>+
<add>+ render();
<add>+
<add>+ requestAnimationFrame(animate);
<add>+}
<add>+requestAnimationFrame(animate);
<add>```
<add>
<add>이제 `render` 함수는 오직 화면을 렌더링하는 역할만 하기에, 화면을 캡쳐하기 직전에 `render` 함수를 호출하면 됩니다.
<add>
<add>```js
<add>const elem = document.querySelector('#screenshot');
<add>elem.addEventListener('click', () => {
<add>+ render();
<add> canvas.toBlob((blob) => {
<add> saveBlob(blob, `screencapture-${ canvas.width }x${ canvas.height }.png`);
<add> });
<add>});
<add>```
<add>
<add>이제 문제 없이 잘 작동할 겁니다.
<add>
<add>{{{example url="../threejs-tips-screenshot-good.html" }}}
<add>
<add>다른 방법에 대해서는 다음 글을 보기 바랍니다.
<add>
<add>---
<add>
<add><a id="preservedrawingbuffer" data-toc="캔버스 초기화 방지하기"></a>
<add>
<add># 캔버스 초기화 방지하기
<add>
<add>움직이는 물체로 사용자가 그림을 그리게 한다고 해봅시다. 이걸 구현하려면 `WebGLRenderer`를 생성할 때 `preserveDrawingBuffer: true`를 설정해야 합니다. 또한 Three.js가 캔버스를 초기화하지 않도록 해주어야 하죠.
<add>
<add>```js
<add>const canvas = document.querySelector('#c');
<add>-const renderer = new THREE.WebGLRenderer({ canvas });
<add>+const renderer = new THREE.WebGLRenderer({
<add>+ canvas,
<add>+ preserveDrawingBuffer: true,
<add>+ alpha: true,
<add>+});
<add>+renderer.autoClearColor = false;
<add>```
<add>
<add>{{{example url="../threejs-tips-preservedrawingbuffer.html" }}}
<add>
<add>만약 진짜 드로잉 프로그램을 만들 계획이라면 이 방법은 쓰지 않는 게 좋습니다. 해상도가 변경될 때마다 브라우저가 캔버스를 초기화할 테니까요. 현재 예제에서는 해상도를 캔버스 크기에 맞춰 변경합니다. 그리고 캔버스 크기는 화면 크기에 맞춰 조정되죠. 파일을 다운받거나, 탭을 바꾸거나, 상태표시줄이 추가되는 등 화면 크기가 바뀌는 경우는 다양합니다. 모바일 환경이라면 화면을 회전시키는 경우도 포함되겠죠.
<add>
<add>드로잉 프로그램을 만들려면 [렌더 타겟을 이용해 텍스처로 화면을 렌더링](threejs-rendertargets.html)하는 게 좋을 겁니다.
<add>
<add>---
<add>
<add><a id="tabindex" data-toc="캔버스에서 키 입력 받기"></a>
<add>
<add># 키 입력 받기
<add>
<add>이 시리즈에서는 대부분의 이벤트 리스너를 `canvas`에 추가했습니다. 다른 이벤트는 문제 없이 작동했지만, 딱 하나, 키보드 이벤트는 기본적으로 그냥 동작하지 않았습니다.
<add>
<add>키보드 이벤트를 받으려면 해당 요소의 [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/tabIndex)를 0 이상의 값으로 설정해야 합니다.
<add>
<add>```html
<add><canvas tabindex="0"></canvas>
<add>```
<add>
<add>하지만 이 속성을 적용하면 새로운 문제가 생깁니다. `tabindex`가 있는 요소는 focus 상태일 때 강조 표시가 적용되거든요. 이 문제를 해결하려면 CSS의 `outline` 속성을 `none`으로 설정해야 합니다.
<add>
<add>```css
<add>canvas:focus {
<add> outline: none;
<add>}
<add>```
<add>
<add>간단한 테스트를 위해 캔버스 3개를 만들겠습니다.
<add>
<add>```html
<add><canvas id="c1"></canvas>
<add><canvas id="c2" tabindex="0"></canvas>
<add><canvas id="c3" tabindex="1"></canvas>
<add>```
<add>
<add>마지막 캔버스에만 CSS를 추가합니다.
<add>
<add>```css
<add>#c3:focus {
<add> outline: none;
<add>}
<add>```
<add>
<add>그리고 모든 캔버스에 이벤트 리스너를 추가합니다.
<add>
<add>```js
<add>document.querySelectorAll('canvas').forEach((canvas) => {
<add> const ctx = canvas.getContext('2d');
<add>
<add> function draw(str) {
<add> ctx.clearRect(0, 0, canvas.width, canvas.height);
<add> ctx.textAlign = 'center';
<add> ctx.textBaseline = 'middle';
<add> ctx.fillText(str, canvas.width / 2, canvas.height / 2);
<add> }
<add> draw(canvas.id);
<add>
<add> canvas.addEventListener('focus', () => {
<add> draw('has focus press a key');
<add> });
<add>
<add> canvas.addEventListener('blur', () => {
<add> draw('lost focus');
<add> });
<add>
<add> canvas.addEventListener('keydown', (e) => {
<add> draw(`keyCode: ${e.keyCode}`);
<add> });
<add>});
<add>```
<add>
<add>첫 번째 캔버스에는 아무리 해도 키보드 이벤트가 발생하지 않을 겁니다. 두 번째 캔버스는 키보드 이벤트를 받긴 하지만 강조 표시가 생기죠. 대신 세 번째 캔버스에서는 두 문제가 발생하지 않습니다.
<add>
<add>{{{example url="../threejs-tips-tabindex.html"}}}
<add>
<add>---
<add>
<add><a id="transparent-canvas" data-toc="캔버스를 투명하게 만들기"></a>
<add>
<add># 캔버스를 투명하게 만들기
<add>
<add>아무런 설정을 하지 않는다면 Three.js는 기본적으로 캔버스를 불투명하게 렌더링합니다. 캔버스를 투명하게 만들려면 `WebGLRenderer`를 생성할 때 [`alpha: true`](WebGLRenderer.alpha)를 넘겨줘야 하죠.
<add>
<add>```js
<add>const canvas = document.querySelector('#c');
<add>-const renderer = new THREE.WebGLRenderer({ canvas });
<add>+const renderer = new THREE.WebGLRenderer({
<add>+ canvas,
<add>+ alpha: true,
<add>+});
<add>```
<add>
<add>또한 캔버스가 premultiplied 알파(미리 계산된 alpha 값, straight alpha 또는 associated alpha라고도 불림)를 사용하지 **않도록** 하게끔 하려면 아래처럼 값을 설정해줘야 합니다.
<add>
<add>```js
<add>const canvas = document.querySelector('#c');
<add>const renderer = new THREE.WebGLRenderer({
<add> canvas,
<add> alpha: true,
<add>+ premultipliedAlpha: false,
<add>});
<add>```
<add>
<add>Three.js는 기본적으로 캔버스에는 [`premultipliedAlpha: true`](WebGLRenderer.premultipliedAlpha)를 사용하지만 재질(material)에는 [`premultipliedAlpha: false`](Material.premultipliedAlpha)를 사용합니다.
<add>
<add>premultiplied alpha를 어떻게 사용해야 하는지 알고 싶다면 [여기 이 글](https://developer.nvidia.com/content/alpha-blending-pre-or-not-pre)\*을 참고하기 바랍니다.
<add>
<add>
<add>※ 영어이니 읽기가 어렵다면 그냥 구글에 premultiplied alpha를 검색하는 것을 추천합니다. 역주.
<add>
<add>어쨌든 이제 한 번 투명 캔버스 예제를 만들어보죠.
<add>
<add>[반응형 디자인](threejs-responsive.html)에서 가져온 예제에 저 설정을 적용했습니다. 추가로 재질도 똑같이 투명하게 만들어보죠.
<add>
<add>```js
<add>function makeInstance(geometry, color, x) {
<add>- const material = new THREE.MeshPhongMaterial({ color });
<add>+ const material = new THREE.MeshPhongMaterial({
<add>+ color,
<add>+ opacity: 0.5,
<add>+ });
<add>
<add>...
<add>
<add>```
<add>
<add>여기에 HTML로 텍스트를 추가합니다.
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add>+ <div id="content">
<add>+ <div>
<add>+ <h1>Cubes-R-Us!</h1>
<add>+ <p>We make the best cubes!</p>
<add>+ </div>
<add>+ </div>
<add></body>
<add>```
<add>
<add>캔버스를 앞에 둬야 하니 CSS도 추가합니다.
<add>
<add>```css
<add>body {
<add> margin: 0;
<add>}
<add>#c {
<add> width: 100vw;
<add> height: 100vh;
<add> display: block;
<add>+ position: fixed;
<add>+ left: 0;
<add>+ top: 0;
<add>+ z-index: 2;
<add>+ pointer-events: none;
<add>}
<add>+#content {
<add>+ font-size: 7vw;
<add>+ font-family: sans-serif;
<add>+ text-align: center;
<add>+ width: 100vw;
<add>+ height: 100vh;
<add>+ display: flex;
<add>+ justify-content: center;
<add>+ align-items: center;
<add>+}
<add>```
<add>
<add>`pointer-events: none`은 캔버스가 마우스나 터치 이벤트의 영향을 받지 않도록 해줍니다. 아래에 있는 텍스트를 바로 선택할 수 있도록 설정한 것이죠.
<add>
<add>{{{example url="../threejs-tips-transparent-canvas.html" }}}
<add>
<add>---
<add>
<add><a id="html-background" data-toc="Three.js를 HTML 요소의 배경으로 사용하기"></a>
<add>
<add># 배경에 Three.js 애니메이션 넣기
<add>
<add>많이 받은 질문 중에 하나가 Three.js 애니메이션을 웹 페이지의 배경으로 사용하는 방법이었습니다.
<add>
<add>가능한 방법은 2가지 정도겠네요.
<add>
<add>* 캔버스 요소의 CSS `position`을 `fixed`로 설정한다.
<add>
<add>```css
<add>#c {
<add> position: fixed;
<add> left: 0;
<add> top: 0;
<add> ...
<add>}
<add>```
<add>
<add>이전 예제에서 썼던 방법과 똑같은 방법을 적용할 수 있습니다. `z-index`를 -1 로 설정하면 정육면체들이 텍스트 뒤로 사라질 겁니다.
<add>
<add>이 방법의 단점은 자바스크립트 코드가 반드시 페이지와 통합되야 한다는 겁니다. 특히 복잡한 페이지라면 Three.js를 렌더링하는 코드가 다른 코드와 충돌하지 않도록 특별히 신경을 써야 하겠죠.
<add>
<add>* `iframe`을 쓴다.
<add>
<add>이 방법은 이 사이트의 [메인 페이지](/threejs/lessons/kr/)에서 사용한 방법입니다.
<add>
<add>해당 웹 페이지에 iframe만 추가하면 되죠.
<add>
<add>```html
<add><iframe id="background" src="threejs-responsive.html">
<add><div>
<add> 내용 내용 내용 내용
<add></div>
<add>```
<add>
<add>그런 다음 캔버스 요소를 활용했을 때와 마찬가지로 iframe이 창 전체를 채우도록 한 뒤, `z-index`를 이용해 배경으로 지정합니다. iframe에는 기본적으로 윤곽선이 있으니 추가로 `border`만 `none`으로 설정해주면 됩니다.
<add>
<add>```css
<add>#background {
<add> position: fixed;
<add> width: 100vw;
<add> height: 100vh;
<add> left: 0;
<add> top: 0;
<add> z-index: -1;
<add> border: none;
<add> pointer-events: none;
<add>}
<add>```
<add>
<add>{{{example url="../threejs-tips-html-background.html"}}}
<ide>\ No newline at end of file | 1 |
Text | Text | update russian localization | 7c186f3a501cbeb5f929a8e9184df7502bfd0741 | <ide><path>curriculum/challenges/russian/06-information-security-and-quality-assurance/advanced-node-and-express/registration-of-new-users.russian.md
<ide> localeTitle: Регистрация новых пользователей
<ide>
<ide> ## Description
<ide> <section id='description'>
<del>As a reminder, this project is being built upon the following starter project on <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/'>Glitch</a>, or cloned from <a href='https://github.com/freeCodeCamp/boilerplate-advancednode/'>GitHub</a>.
<del>Now we need to allow a new user on our site to register an account. On the res.render for the home page add a new variable to the object passed along- <code>showRegistration: true</code>. When you refresh your page, you should then see the registration form that was already created in your index.pug file! This form is set up to <b>POST</b> on <em>/register</em> so this is where we should set up to accept the POST and create the user object in the database.
<del>The logic of the registration route should be as follows: Register the new user > Authenticate the new user > Redirect to /profile
<del>The logic of step 1, registering the new user, should be as follows: Query database with a findOne command > if user is returned then it exists and redirect back to home <em>OR</em> if user is undefined and no error occurs then 'insertOne' into the database with the username and password and as long as no errors occur then call <em>next</em> to go to step 2, authenticating the new user, which we've already written the logic for in our POST /login route.
<add>Напомним, что этот проект строится на следующем стартовом проекте на <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/'>Glitch</a>, или клонированном из <a href='https://github.com/freeCodeCamp/boilerplate-advancednode/'>GitHub</a>.
<add>Теперь нам нужно разрешить новому пользователю на нашем сайте зарегистрировать учетную запись. На res.render для домашней страницы добавьте новую переменную к переданному объекту- <code>showRegistration: true</code>. При обновлении страницы вы должны увидеть регистрационную форму, которая уже была создана в файле index.pug ! Эта форма настроена на <b>POST</b> на <em>/register</em> поэтому здесь мы должны настроить прием POST и создать объект пользователя в базе данных.
<add>Логика регистрационного маршрута должна выглядеть следующим образом: Регистрация нового пользователя > аутентификация нового пользователя > перенаправление в /profile
<add>Логика шага 1, регистрация нового пользователя, должна быть следующей: Запрос базы данных с помощью команды findOne > если пользователь возвращается, то он существует и перенаправляется обратно на home <em>или</em> если пользователь не определен и не возникает ошибок, то 'insertOne' в базу данных с именем пользователя и паролем и до тех пор, пока не возникнет ошибок, затем вызовите <em>next</em> чтобы перейти к Шагу 2, аутентифицируя нового пользователя, для которого мы уже написали логику в нашем POST /login маршруте.
<ide>
<ide> ```js
<ide> app.route('/register') | 1 |
PHP | PHP | add config key | 44b427f771e76489db693034a1120b8b0f349dbf | <ide><path>src/Illuminate/Foundation/Console/ProviderMakeCommand.php
<ide> class ProviderMakeCommand extends GeneratorCommand {
<ide> */
<ide> protected $type = 'Provider';
<ide>
<add> /**
<add> * Set the configuration key for the namespace.
<add> *
<add> * @var string
<add> */
<add> protected $configKey = 'providers';
<add>
<ide> /**
<ide> * Get the controller class path.
<ide> * | 1 |
Javascript | Javascript | reduce duplication in `alternatecs.getrgbbuffer` | c5c0a00dcad7a1372e8aa3c1a0a6c644346ba87d | <ide><path>src/core/colorspace.js
<ide> var AlternateCS = (function AlternateCSClosure() {
<ide> var scaled = new Float32Array(numComps);
<ide> var tinted = new Float32Array(baseNumComps);
<ide> var i, j;
<del> if (usesZeroToOneRange) {
<del> for (i = 0; i < count; i++) {
<del> for (j = 0; j < numComps; j++) {
<del> scaled[j] = src[srcOffset++] * scale;
<del> }
<del> tintFn(scaled, 0, tinted, 0);
<add>
<add> for (i = 0; i < count; i++) {
<add> for (j = 0; j < numComps; j++) {
<add> scaled[j] = src[srcOffset++] * scale;
<add> }
<add> tintFn(scaled, 0, tinted, 0);
<add> if (usesZeroToOneRange) {
<ide> for (j = 0; j < baseNumComps; j++) {
<ide> baseBuf[pos++] = tinted[j] * 255;
<ide> }
<del> }
<del> } else {
<del> for (i = 0; i < count; i++) {
<del> for (j = 0; j < numComps; j++) {
<del> scaled[j] = src[srcOffset++] * scale;
<del> }
<del> tintFn(scaled, 0, tinted, 0);
<add> } else {
<ide> base.getRgbItem(tinted, 0, baseBuf, pos);
<ide> pos += baseNumComps;
<ide> }
<ide> }
<add>
<ide> if (!isPassthrough) {
<ide> base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
<ide> } | 1 |
Python | Python | add default values in docs | 6538c2568124fac7eb70220b06a6b13fd6823e4e | <ide><path>keras/layers/dense_attention.py
<ide> class Attention(BaseDenseAttention):
<ide> causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such
<ide> that position `i` cannot attend to positions `j > i`. This prevents the
<ide> flow of information from the future towards the past.
<add> Defaults to `False`.
<ide> dropout: Float between 0 and 1. Fraction of the units to drop for the
<del> attention scores.
<add> attention scores. Defaults to 0.0.
<ide>
<ide> Call Args:
<ide>
<ide> class AdditiveAttention(BaseDenseAttention):
<ide> causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such
<ide> that position `i` cannot attend to positions `j > i`. This prevents the
<ide> flow of information from the future towards the past.
<add> Defaults to `False`.
<ide> dropout: Float between 0 and 1. Fraction of the units to drop for the
<del> attention scores.
<add> attention scores. Defaults to 0.0.
<ide>
<ide> Call Args:
<ide> | 1 |
Javascript | Javascript | improve parserange, add test cases | 3b55455b26a933c51bed0c055c1c63aed59f45c8 | <ide><path>lib/util/semver.js
<ide> exports.versionLt = versionLt;
<ide> */
<ide> exports.parseRange = str => {
<ide> const splitAndConvert = str => {
<del> return str.split(".").map(item => (`${+item}` === item ? +item : item));
<add> return str
<add> .split(".")
<add> .map(item => (item !== "NaN" && `${+item}` === item ? +item : item));
<ide> };
<ide> // see https://docs.npmjs.com/misc/semver#range-grammar for grammar
<ide> const parsePartial = str => {
<ide> exports.parseRange = str => {
<ide> return [-range[0] - 1, ...range.slice(1)];
<ide> };
<ide> const parseSimple = str => {
<del> // simple ::= primitive | partial | tilde | caret
<del> // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
<del> // tilde ::= '~' partial
<del> // caret ::= '^' partial
<add> // simple ::= primitive | partial | tilde | caret
<add> // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | '!' ) ( ' ' ) * partial
<add> // tilde ::= '~' ( ' ' ) * partial
<add> // caret ::= '^' ( ' ' ) * partial
<ide> const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str);
<ide> const start = match ? match[0] : "";
<del> const remainder = parsePartial(str.slice(start.length));
<add> const remainder = parsePartial(
<add> start.length ? str.slice(start.length).trim() : str.trim()
<add> );
<ide> switch (start) {
<ide> case "^":
<ide> if (remainder.length > 1 && remainder[1] === 0) {
<ide> exports.parseRange = str => {
<ide> // eslint-disable-next-line no-sparse-arrays
<ide> return [, ...arr, ...items.slice(1).map(() => fn)];
<ide> };
<del> // remove whitespace characters after ^, ~, <=, <, >=, >, =
<del> const trimRangeOperators = str => {
<del> return str.replace(/(\^|~|<=|<|>=|>|=)\s*/g, "$1");
<del> };
<ide> const parseRange = str => {
<del> // range ::= hyphen | simple ( ' ' simple ) * | ''
<del> // hyphen ::= partial ' - ' partial
<del> const items = str.split(" - ");
<add> // range ::= hyphen | simple ( ' ' ( ' ' ) * simple ) * | ''
<add> // hyphen ::= partial ( ' ' ) * ' - ' ( ' ' ) * partial
<add> const items = str.split(/\s+-\s+/);
<ide> if (items.length === 1) {
<del> const items = trimRangeOperators(str)
<add> const items = str
<ide> .trim()
<del> .split(/\s+/g)
<add> .split(/(?<=[-0-9A-Za-z])\s+/g)
<ide> .map(parseSimple);
<ide> return combine(items, 2);
<ide> }
<ide><path>test/SemVer.unittest.js
<ide> describe("SemVer", () => {
<ide>
<ide> describe("parseRange", () => {
<ide> const cases = {
<add> "5 || 6 || 7.x.x": ["5.x.x || 6.x || 7"],
<add> "1 - 2": ["1 - 2"],
<ide> "=3": [
<ide> "3",
<ide> "v3",
<ide> describe("SemVer", () => {
<ide> "^3.4": ["^3.4.*", "^ 3.4"],
<ide> "3.4 - 6.5": [">=3.4 <=6.5", ">= 3.4 <= 6.5"],
<ide> "<=3.4": ["<3.4 || =3.4", "<= 3.4"],
<del> ">3.4": [">=3.4 !3.4", "> 3.4"]
<add> ">3.4": [">=3.4 !3.4", "> 3.4"],
<add> "1.2.3-alpha.x.x": ["1.2.3-alpha", "1.2.3-alpha+build.25"],
<add> "1.2.3-NaN": ["1.2.3-NaN"]
<ide> };
<ide> for (const key of Object.keys(cases)) {
<ide> describe(key, () => { | 2 |
Javascript | Javascript | fix failing switch e2e tests | bb09866cba11119336a5415ad79569eb4e4277e3 | <ide><path>RNTester/e2e/__tests__/Switch-test.js
<ide> const jestExpect = require('expect');
<ide>
<ide> describe('Switch', () => {
<del> beforeAll(async () => {
<add> beforeEach(async () => {
<ide> await device.reloadReactNative();
<ide> await element(by.id('explorer_search')).replaceText('<Switch>');
<ide> await element(by.label('<Switch> Native boolean input')).tap();
<ide> });
<ide>
<del> afterAll(async () => {
<del> await element(by.label('Back')).tap();
<del> });
<del>
<del> it('Switch that starts on should switch', async () => {
<add> it('Switch that starts off should switch', async () => {
<ide> const testID = 'on-off-initial-off';
<ide> const indicatorID = 'on-off-initial-off-indicator';
<ide>
<ide> describe('Switch', () => {
<ide> await expect(element(by.id(indicatorID))).toHaveText('On');
<ide> });
<ide>
<del> it('Switch that starts off should switch', async () => {
<add> it('Switch that starts on should switch', async () => {
<ide> const testID = 'on-off-initial-on';
<ide> const indicatorID = 'on-off-initial-on-indicator';
<ide> | 1 |
PHP | PHP | use facade so we dont break the signature | 66ce56a6605136110aeac3946020c8f55fbd4b65 | <ide><path>src/Illuminate/Foundation/Auth/ResetsPasswords.php
<ide> public function getReset($token = null)
<ide> *
<ide> * If no token is present, display the link request form.
<ide> *
<del> * @param string|null $token
<ide> * @param \Illuminate\Http\Request $request
<add> * @param string|null $token
<ide> * @return \Illuminate\Http\Response
<ide> */
<del> public function showResetForm($token = null, Request $request)
<add> public function showResetForm(Request $request, $token = null)
<ide> {
<ide> if (is_null($token)) {
<ide> return $this->getEmail(); | 1 |
Python | Python | fix infixes in spanish and portuguese | 41a4766c1c4b86f07a8cd2a038b2848329b1ae5e | <ide><path>spacy/es/language_data.py
<ide> '''.strip().split('\n')
<ide>
<ide>
<del>TOKENIZER_INFIXES = tuple()
<add>TOKENIZER_INFIXES = (r'''\.\.\.+ (?<=[a-z])\.(?=[A-Z]) (?<=[a-zA-Z])-(?=[a-zA-z]) '''
<add> r'''(?<=[a-zA-Z])--(?=[a-zA-z]) (?<=[0-9])-(?=[0-9]) '''
<add> r'''(?<=[A-Za-z]),(?=[A-Za-z])''').split()
<add>
<ide>
<ide>
<ide> TOKENIZER_EXCEPTIONS = {
<ide><path>spacy/pt/language_data.py
<ide> '''.strip().split('\n')
<ide>
<ide>
<del>TOKENIZER_INFIXES = tuple()
<add>TOKENIZER_INFIXES = (r'''\.\.\.+ (?<=[a-z])\.(?=[A-Z]) (?<=[a-zA-Z])-(?=[a-zA-z]) '''
<add> r'''(?<=[a-zA-Z])--(?=[a-zA-z]) (?<=[0-9])-(?=[0-9]) '''
<add> r'''(?<=[A-Za-z]),(?=[A-Za-z])''').split()
<add>
<ide>
<ide>
<ide> TOKENIZER_EXCEPTIONS = { | 2 |
Ruby | Ruby | add action view to active model api documentation | b970ade2520de0ae9723ba35b6b2038991610c24 | <ide><path>activemodel/lib/active_model/model.rb
<ide> module ActiveModel
<ide> # == Active \Model \Basic \Model
<ide> #
<ide> # Includes the required interface for an object to interact with
<del> # Action Pack, using different Active Model modules.
<add> # Action Pack and Action View, using different Active Model modules.
<ide> # It includes model name introspections, conversions, translations and
<ide> # validations. Besides that, it allows you to initialize the object with a
<ide> # hash of attributes, pretty much like Active Record does. | 1 |
Python | Python | add algorithm for creating hamming numbers | b3d9281591df03768fe062cc0517ee0d4cc387f0 | <ide><path>maths/hamming_numbers.py
<add>"""
<add>A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some
<add>non-negative integers i, j, and k. They are often referred to as regular numbers.
<add>More info at: https://en.wikipedia.org/wiki/Regular_number.
<add>"""
<add>
<add>
<add>def hamming(n_element: int) -> list:
<add> """
<add> This function creates an ordered list of n length as requested, and afterwards
<add> returns the last value of the list. It must be given a positive integer.
<add>
<add> :param n_element: The number of elements on the list
<add> :return: The nth element of the list
<add>
<add> >>> hamming(5)
<add> [1, 2, 3, 4, 5]
<add> >>> hamming(10)
<add> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12]
<add> >>> hamming(15)
<add> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
<add> """
<add> n_element = int(n_element)
<add> if n_element < 1:
<add> my_error = ValueError("a should be a positive number")
<add> raise my_error
<add>
<add> hamming_list = [1]
<add> i, j, k = (0, 0, 0)
<add> index = 1
<add> while index < n_element:
<add> while hamming_list[i] * 2 <= hamming_list[-1]:
<add> i += 1
<add> while hamming_list[j] * 3 <= hamming_list[-1]:
<add> j += 1
<add> while hamming_list[k] * 5 <= hamming_list[-1]:
<add> k += 1
<add> hamming_list.append(
<add> min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5)
<add> )
<add> index += 1
<add> return hamming_list
<add>
<add>
<add>if __name__ == "__main__":
<add> n = input("Enter the last number (nth term) of the Hamming Number Series: ")
<add> print("Formula of Hamming Number Series => 2^i * 3^j * 5^k")
<add> hamming_numbers = hamming(int(n))
<add> print("-----------------------------------------------------")
<add> print(f"The list with nth numbers is: {hamming_numbers}")
<add> print("-----------------------------------------------------") | 1 |
Javascript | Javascript | add react.timeout to getcomponentname | fe747a51c1fdedd87c4e9e281441f2d8d04e02b3 | <ide><path>packages/shared/getComponentName.js
<ide> import {
<ide> REACT_PROFILER_TYPE,
<ide> REACT_PROVIDER_TYPE,
<ide> REACT_STRICT_MODE_TYPE,
<add> REACT_TIMEOUT_TYPE,
<ide> } from 'shared/ReactSymbols';
<ide>
<ide> function getComponentName(fiber: Fiber): string | null {
<ide> function getComponentName(fiber: Fiber): string | null {
<ide> return 'Context.Provider';
<ide> case REACT_STRICT_MODE_TYPE:
<ide> return 'StrictMode';
<add> case REACT_TIMEOUT_TYPE:
<add> return 'Timeout';
<ide> }
<ide> if (typeof type === 'object' && type !== null) {
<ide> switch (type.$$typeof) { | 1 |
Javascript | Javascript | add test case for issue 12993 | 3b65860614a10b7ac1209e0a947d4693c84537f2 | <ide><path>test/configCases/issues/issue-12993/dynamic.js
<add>export default "dynamic";
<ide><path>test/configCases/issues/issue-12993/index.js
<add>import(/* webpackPrefetch: true */ "./dynamic.js");
<add>
<add>export const main = "main";
<add>
<add>it("library output should be accurate value", done => {
<add> expect(global.lib.main).toBe("main");
<add> done();
<add>});
<ide><path>test/configCases/issues/issue-12993/webpack.config.js
<add>module.exports = [
<add> {
<add> mode: "development",
<add> output: {
<add> library: "lib",
<add> libraryTarget: "global"
<add> }
<add> }
<add>]; | 3 |
Text | Text | fix markdown formatting | c718eb282b2d0d9479e566f1d8c3dd856eee8334 | <ide><path>README.md
<ide> are VMWare's vmdk, Oracle Virtualbox's vdi, and Amazon EC2's ami. In theory thes
<ide> automatically package their application into a "machine" for easy distribution and deployment. In practice, that almost never
<ide> happens, for a few reasons:
<ide>
<del> * *Size*: VMs are very large which makes them impractical to store and transfer.
<del> * *Performance*: running VMs consumes significant CPU and memory, which makes them impractical in many scenarios, for example local development of multi-tier applications, and
<del> large-scale deployment of cpu and memory-intensive applications on large numbers of machines.
<del> * *Portability*: competing VM environments don't play well with each other. Although conversion tools do exist, they are limited and add even more overhead.
<del> * *Hardware-centric*: VMs were designed with machine operators in mind, not software developers. As a result, they offer very limited tooling for what developers need most:
<del> building, testing and running their software. For example, VMs offer no facilities for application versioning, monitoring, configuration, logging or service discovery.
<add> * *Size*: VMs are very large which makes them impractical to store and transfer.
<add> * *Performance*: running VMs consumes significant CPU and memory, which makes them impractical in many scenarios, for example local development of multi-tier applications, and
<add> large-scale deployment of cpu and memory-intensive applications on large numbers of machines.
<add> * *Portability*: competing VM environments don't play well with each other. Although conversion tools do exist, they are limited and add even more overhead.
<add> * *Hardware-centric*: VMs were designed with machine operators in mind, not software developers. As a result, they offer very limited tooling for what developers need most:
<add> building, testing and running their software. For example, VMs offer no facilities for application versioning, monitoring, configuration, logging or service discovery.
<ide>
<ide> By contrast, Docker relies on a different sandboxing method known as *containerization*. Unlike traditional virtualization,
<ide> containerization takes place at the kernel level. Most modern operating system kernels now support the primitives necessary | 1 |
Text | Text | add solution to accessibility challenge | 0a2aa3dcfa0e232e52c2dd4269fc0753b734eb0c | <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/standardize-times-with-the-html5-datetime-attribute.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <header>
<add> <h1>Tournaments</h1>
<add> </header>
<add> <article>
<add> <h2>Mortal Kombat Tournament Survey Results</h2>
<add>
<add> <!-- Add your code below this line -->
<add>
<add> <p>Thank you to everyone for responding to Master Camper Cat's survey. The best day to host the vaunted Mortal Kombat tournament is <time datetime="2016-09-15">Thursday, September 15<sup>th</sup></time>. May the best ninja win!</p>
<add>
<add> <!-- Add your code above this line -->
<add>
<add> <section>
<add> <h3>Comments:</h3>
<add> <article>
<add> <p>Posted by: Sub-Zero on <time datetime="2016-08-13T20:01Z">August 13<sup>th</sup></time></p>
<add> <p>Johnny Cage better be there, I'll finish him!</p>
<add> </article>
<add> <article>
<add> <p>Posted by: Doge on <time datetime="2016-08-15T08:12Z">August 15<sup>th</sup></time></p>
<add> <p>Wow, much combat, so mortal.</p>
<add> </article>
<add> <article>
<add> <p>Posted by: The Grim Reaper on <time datetime="2016-08-16T00:00Z">August 16<sup>th</sup></time></p>
<add> <p>Looks like I'll be busy that day.</p>
<add> </article>
<add> </section>
<add> </article>
<add> <footer>© 2018 Camper Cat</footer>
<add></body>
<ide> ```
<ide> </section> | 1 |
Text | Text | fix deprecation number | 1bd32087eee4b7fc59732aeb6e1003737ac98f07 | <ide><path>doc/api/deprecations.md
<ide> Use [`asyncResource.runInAsyncScope()`][] API instead which provides a much
<ide> safer, and more convenient, alternative. See
<ide> https://github.com/nodejs/node/pull/18513 for more details.
<ide>
<del><a id="DEP0098"></a>
<del>### DEP0098: async context-unaware node::MakeCallback C++ APIs
<add><a id="DEP0099"></a>
<add>### DEP0099: async context-unaware node::MakeCallback C++ APIs
<ide>
<ide> Type: Compile-time
<ide> | 1 |
Javascript | Javascript | fix ability to add child after closure compiled | 93f8737fc79bb571d1b4595c4f952f078f2458b5 | <ide><path>src/js/component.js
<ide> vjs.Component.prototype.addChild = function(child, options){
<ide>
<ide> // Add the UI object's element to the container div (box)
<ide> // Having an element is not required
<del> if (typeof component.el === 'function' && component.el()) {
<del> this.el_.appendChild(component.el());
<add> if (typeof component['el'] === 'function' && component['el']()) {
<add> this.el_.appendChild(component['el']());
<ide> }
<ide>
<ide> // Return so it can stored on parent object if desired. | 1 |
Python | Python | send task_id and task_name to kwargs of task | a806fdd6ea8bc8142c80275a5eab09be47aaba16 | <ide><path>celery/worker.py
<ide> from celery.log import setup_logger
<ide> from celery.registry import tasks
<ide> from celery.process import ProcessQueue
<del>from celery.models import PeriodicTaskMeta
<add>from celery.models import RetryTask, PeriodicTaskMeta
<ide> import multiprocessing
<ide> import simplejson
<ide> import traceback
<ide> def from_message(cls, message):
<ide>
<ide> def extend_kwargs_with_logging(self, loglevel, logfile):
<ide> task_func_kwargs = {"logfile": logfile,
<del> "loglevel": loglevel}
<add> "loglevel": loglevel,
<add> "task_id": self.task_id,
<add> "task_name": self.task_name}
<ide> task_func_kwargs.update(self.kwargs)
<ide> return task_func_kwargs
<ide>
<ide> def run_periodic_tasks(self):
<ide> for waiting_task in waiting_tasks]
<ide> return waiting_tasks
<ide>
<add> def schedule_retry_tasks(self):
<add> """Reschedule all requeued tasks waiting for retry."""
<add> retry_tasks = RetryTask.objects.get_waiting_tasks()
<add> [retry_task.retry()
<add> for retry_task in retry_tasks]
<add> return retry_tasks
<add>
<ide> def run(self):
<ide> """The worker server's main loop."""
<ide> results = ProcessQueue(self.concurrency, logger=self.logger,
<ide> def run(self):
<ide> ev_msg_waiting = EventTimer(log_wait, self.empty_msg_emit_every)
<ide> events = [
<ide> EventTimer(self.run_periodic_tasks, 1),
<add> EventTimer(self.schedule_retry_tasks, 2),
<ide> EventTimer(self.connection_diagnostics, 3),
<ide> EventTimer(self.reset_connection, 60 * 5),
<ide> ] | 1 |
Java | Java | support "accept-patch" for unsupported media type | a2d91a562de7ab3e0d4ccbe2b1dbadb8f5324156 | <ide><path>spring-web/src/main/java/org/springframework/web/server/UnsupportedMediaTypeStatusException.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.ResolvableType;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.CollectionUtils;
<ide>
<ide> /**
<ide> * Exception for errors that fit response status 415 (unsupported media type).
<ide> public class UnsupportedMediaTypeStatusException extends ResponseStatusException
<ide> @Nullable
<ide> private final ResolvableType bodyType;
<ide>
<add> @Nullable
<add> private final HttpMethod method;
<add>
<ide>
<ide> /**
<ide> * Constructor for when the specified Content-Type is invalid.
<ide> public UnsupportedMediaTypeStatusException(@Nullable String reason) {
<ide> this.contentType = null;
<ide> this.supportedMediaTypes = Collections.emptyList();
<ide> this.bodyType = null;
<add> this.method = null;
<ide> }
<ide>
<ide> /**
<ide> * Constructor for when the Content-Type can be parsed but is not supported.
<ide> */
<ide> public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes) {
<del> this(contentType, supportedTypes, null);
<add> this(contentType, supportedTypes, null, null);
<ide> }
<ide>
<ide> /**
<ide> public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List
<ide> */
<ide> public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
<ide> @Nullable ResolvableType bodyType) {
<add> this(contentType, supportedTypes, bodyType, null);
<add> }
<add>
<add> /**
<add> * Constructor that provides the HTTP method.
<add> * @since 5.3.6
<add> */
<add> public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
<add> @Nullable HttpMethod method) {
<add> this(contentType, supportedTypes, null, method);
<add> }
<add>
<add> /**
<add> * Constructor for when trying to encode from or decode to a specific Java type.
<add> * @since 5.3.6
<add> */
<add> public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
<add> @Nullable ResolvableType bodyType, @Nullable HttpMethod method) {
<ide>
<ide> super(HttpStatus.UNSUPPORTED_MEDIA_TYPE, initReason(contentType, bodyType));
<ide> this.contentType = contentType;
<ide> this.supportedMediaTypes = Collections.unmodifiableList(supportedTypes);
<ide> this.bodyType = bodyType;
<add> this.method = method;
<ide> }
<ide>
<ide> private static String initReason(@Nullable MediaType contentType, @Nullable ResolvableType bodyType) {
<ide> public ResolvableType getBodyType() {
<ide> return this.bodyType;
<ide> }
<ide>
<add> @Override
<add> public HttpHeaders getResponseHeaders() {
<add> if (HttpMethod.PATCH != this.method || CollectionUtils.isEmpty(this.supportedMediaTypes) ) {
<add> return HttpHeaders.EMPTY;
<add> }
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.setAcceptPatch(this.supportedMediaTypes);
<add> return headers;
<add> }
<add>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMapping.java
<ide> protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos,
<ide> catch (InvalidMediaTypeException ex) {
<ide> throw new UnsupportedMediaTypeStatusException(ex.getMessage());
<ide> }
<del> throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes));
<add> throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes), exchange.getRequest().getMethod());
<ide> }
<ide>
<ide> if (helper.hasProducesMismatch()) {
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java
<ide> public void handleMatchMatrixVariablesDecoding() {
<ide> assertThat(uriVariables.get("cars")).isEqualTo("cars");
<ide> }
<ide>
<add> @Test
<add> public void handlePatchUnsupportedMediaType() {
<add> MockServerHttpRequest request = MockServerHttpRequest.patch("/qux")
<add> .header("content-type", "application/xml")
<add> .build();
<add> ServerWebExchange exchange = MockServerWebExchange.from(request);
<add> Mono<Object> mono = this.handlerMapping.getHandler(exchange);
<add>
<add> StepVerifier.create(mono)
<add> .expectErrorSatisfies(ex -> {
<add> assertThat(ex).isInstanceOf(UnsupportedMediaTypeStatusException.class);
<add> UnsupportedMediaTypeStatusException umtse = (UnsupportedMediaTypeStatusException) ex;
<add> MediaType mediaType = new MediaType("foo", "bar");
<add> assertThat(umtse.getSupportedMediaTypes()).containsExactly(mediaType);
<add> assertThat(umtse.getResponseHeaders().getAcceptPatch()).containsExactly(mediaType);
<add> })
<add> .verify();
<add>
<add> }
<add>
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private <T> void assertError(Mono<Object> mono, final Class<T> exceptionClass, final Consumer<T> consumer) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
<ide> List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
<ide> if (!CollectionUtils.isEmpty(mediaTypes)) {
<ide> headers.setAccept(mediaTypes);
<add> if (request instanceof ServletWebRequest) {
<add> ServletWebRequest servletWebRequest = (ServletWebRequest) request;
<add> if (HttpMethod.PATCH.equals(servletWebRequest.getHttpMethod())) {
<add> headers.setAcceptPatch(mediaTypes);
<add> }
<add> }
<ide> }
<ide>
<ide> return handleExceptionInternal(ex, null, headers, status, request);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java
<ide> protected ModelAndView handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupported
<ide> List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
<ide> if (!CollectionUtils.isEmpty(mediaTypes)) {
<ide> response.setHeader("Accept", MediaType.toString(mediaTypes));
<add> if (request.getMethod().equals("PATCH")) {
<add> response.setHeader("Accept-Patch", MediaType.toString(mediaTypes));
<add> }
<ide> }
<ide> response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
<ide> return new ModelAndView();
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void handleHttpMediaTypeNotSupported() {
<ide>
<ide> ResponseEntity<Object> responseEntity = testException(ex);
<ide> assertThat(responseEntity.getHeaders().getAccept()).isEqualTo(acceptable);
<add> assertThat(responseEntity.getHeaders().getAcceptPatch()).isEmpty();
<add> }
<add>
<add> @Test
<add> public void patchHttpMediaTypeNotSupported() {
<add> this.servletRequest = new MockHttpServletRequest("PATCH", "/");
<add> this.request = new ServletWebRequest(this.servletRequest, this.servletResponse);
<add>
<add> List<MediaType> acceptable = Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML);
<add> Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable);
<add>
<add> ResponseEntity<Object> responseEntity = testException(ex);
<add> assertThat(responseEntity.getHeaders().getAccept()).isEqualTo(acceptable);
<add> assertThat(responseEntity.getHeaders().getAcceptPatch()).isEqualTo(acceptable);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void unsupportedRequestBody(boolean usePathPatterns) throws Exception {
<ide> assertThat(response.getHeader("Accept")).isEqualTo("text/plain");
<ide> }
<ide>
<add> @PathPatternsParameterizedTest
<add> void unsupportedPatchBody(boolean usePathPatterns) throws Exception {
<add> initDispatcherServlet(RequestResponseBodyController.class, usePathPatterns, wac -> {
<add> RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
<add> StringHttpMessageConverter converter = new StringHttpMessageConverter();
<add> converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
<add> adapterDef.getPropertyValues().add("messageConverters", converter);
<add> wac.registerBeanDefinition("handlerAdapter", adapterDef);
<add> });
<add>
<add> MockHttpServletRequest request = new MockHttpServletRequest("PATCH", "/something");
<add> String requestBody = "Hello World";
<add> request.setContent(requestBody.getBytes(StandardCharsets.UTF_8));
<add> request.addHeader("Content-Type", "application/pdf");
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> getServlet().service(request, response);
<add> assertThat(response.getStatus()).isEqualTo(415);
<add> assertThat(response.getHeader("Accept-Patch")).isEqualTo("text/plain");
<add> }
<add>
<ide> @PathPatternsParameterizedTest
<ide> void responseBodyNoAcceptHeader(boolean usePathPatterns) throws Exception {
<ide> initDispatcherServlet(RequestResponseBodyController.class, usePathPatterns);
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java
<ide> public void handleHttpMediaTypeNotSupported() {
<ide> assertThat(response.getHeader("Accept")).as("Invalid Accept header").isEqualTo("application/pdf");
<ide> }
<ide>
<add> @Test
<add> public void patchHttpMediaTypeNotSupported() {
<add> HttpMediaTypeNotSupportedException ex = new HttpMediaTypeNotSupportedException(new MediaType("text", "plain"),
<add> Collections.singletonList(new MediaType("application", "pdf")));
<add> MockHttpServletRequest request = new MockHttpServletRequest("PATCH", "/");
<add> ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
<add> assertThat(mav).as("No ModelAndView returned").isNotNull();
<add> assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
<add> assertThat(response.getStatus()).as("Invalid status code").isEqualTo(415);
<add> assertThat(response.getHeader("Accept-Patch")).as("Invalid Accept header").isEqualTo("application/pdf");
<add> }
<add>
<ide> @Test
<ide> public void handleMissingPathVariable() throws NoSuchMethodException {
<ide> Method method = getClass().getMethod("handle", String.class); | 8 |
Text | Text | fix typo in worker_threads.md | 0577fe3f2690bff0f7cf1a60613cdc3d50b59e4a | <ide><path>doc/api/worker_threads.md
<ide> Depending on how a `Buffer` instance was created, it may or may
<ide> not own its underlying `ArrayBuffer`. An `ArrayBuffer` must not
<ide> be transferred unless it is known that the `Buffer` instance
<ide> owns it. In particular, for `Buffer`s created from the internal
<del>`Buffer` pool (using, for instance `Buffer.from()` or `Buffer.alloc()`),
<add>`Buffer` pool (using, for instance `Buffer.from()` or `Buffer.allocUnsafe()`),
<ide> transferring them is not possible and they are always cloned,
<ide> which sends a copy of the entire `Buffer` pool.
<ide> This behavior may come with unintended higher memory | 1 |
Text | Text | fix broken link | 3851d9065fd2cdf4b3dbef4a11667e4a224a5113 | <ide><path>docs/api-reference/next/server.md
<ide> description: Learn about the server-only helpers for Middleware and Edge API Rou
<ide>
<ide> The `NextRequest` object is an extension of the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) interface, with the following added methods and properties:
<ide>
<del>- `cookies` - A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with cookies from the `Request`. See [Using cookies in Edge Middleware](#using-cookies-in-edge-middleware)
<add>- `cookies` - A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with cookies from the `Request`. See [Using cookies in Middleware](/docs/advanced-features/middleware#using-cookies)
<ide> - `nextUrl`: Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as `pathname`, `basePath`, `trailingSlash` and `i18n`. Includes the following properties:
<ide> - `basePath` (`string`)
<ide> - `buildId` (`string || undefined`) | 1 |
Java | Java | promote lift implementations to top-level types. | c0e12e5f75d64e0cf65d5c8680b67e240a432dfd | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Flowable<T> doOnLifecycle(final Consumer<? super Subscription> onSu
<ide> Objects.requireNonNull(onSubscribe, "onSubscribe is null");
<ide> Objects.requireNonNull(onRequest, "onRequest is null");
<ide> Objects.requireNonNull(onCancel, "onCancel is null");
<del> return lift(new FlowableOperator<T, T>() {
<del> @Override
<del> public Subscriber<? super T> apply(Subscriber<? super T> s) {
<del> return new SubscriptionLambdaSubscriber<T>(s, onSubscribe, onRequest, onCancel);
<del> }
<del> });
<add> return new FlowableDoOnLifecycle<T>(this, onSubscribe, onRequest, onCancel);
<ide> }
<ide>
<ide> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<ide> public final <R> Flowable<R> scanWith(Callable<R> seedSupplier, BiFunction<R, ?
<ide> @BackpressureSupport(BackpressureKind.PASS_THROUGH)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Flowable<T> serialize() {
<del> return lift(new FlowableOperator<T, T>() {
<del> @Override
<del> public Subscriber<? super T> apply(Subscriber<? super T> s) {
<del> return new SerializedSubscriber<T>(s);
<del> }
<del> });
<add> return new FlowableSerialized<T>(this);
<ide> }
<ide>
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> public final TestSubscriber<T> test(long initialRequest, int fusionMode, boolean
<ide> subscribe(ts);
<ide> return ts;
<ide> }
<del>
<ide> }
<ide>\ No newline at end of file
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> doOnError(Consumer<? super Throwable> onError) {
<ide> public final Observable<T> doOnLifecycle(final Consumer<? super Disposable> onSubscribe, final Runnable onCancel) {
<ide> Objects.requireNonNull(onSubscribe, "onSubscribe is null");
<ide> Objects.requireNonNull(onCancel, "onCancel is null");
<del> return lift(new ObservableOperator<T, T>() {
<del> @Override
<del> public Observer<? super T> apply(Observer<? super T> s) {
<del> return new SubscriptionLambdaObserver<T>(s, onSubscribe, onCancel);
<del> }
<del> });
<add> return new ObservableDoOnLifecycle<T>(this, onSubscribe, onCancel);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final <R> Observable<R> scanWith(Callable<R> seedSupplier, BiFunction<R,
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Observable<T> serialize() {
<del> return lift(new ObservableOperator<T, T>() {
<del> @Override
<del> public Observer<? super T> apply(Observer<? super T> s) {
<del> return new SerializedObserver<T>(s);
<del> }
<del> });
<add> return new ObservableSerialized<T>(this);
<ide> }
<ide>
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnLifecycle.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance 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, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.operators.flowable;
<add>
<add>import io.reactivex.Flowable;
<add>import io.reactivex.functions.Consumer;
<add>import io.reactivex.functions.LongConsumer;
<add>import io.reactivex.internal.subscribers.flowable.SubscriptionLambdaSubscriber;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>
<add>public final class FlowableDoOnLifecycle<T> extends FlowableSource<T, T> {
<add> private final Consumer<? super Subscription> onSubscribe;
<add> private final LongConsumer onRequest;
<add> private final Runnable onCancel;
<add>
<add> public FlowableDoOnLifecycle(Flowable<T> source, Consumer<? super Subscription> onSubscribe,
<add> LongConsumer onRequest, Runnable onCancel) {
<add> super(source);
<add> this.onSubscribe = onSubscribe;
<add> this.onRequest = onRequest;
<add> this.onCancel = onCancel;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Subscriber<? super T> s) {
<add> source.subscribe(new SubscriptionLambdaSubscriber<T>(s, onSubscribe, onRequest, onCancel));
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableSerialized.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance 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, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.operators.flowable;
<add>
<add>import io.reactivex.Flowable;
<add>import io.reactivex.subscribers.SerializedSubscriber;
<add>import org.reactivestreams.Subscriber;
<add>
<add>public final class FlowableSerialized<T> extends FlowableSource<T, T> {
<add> public FlowableSerialized(Flowable<T> source) {
<add> super(source);
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Subscriber<? super T> s) {
<add> source.subscribe(new SerializedSubscriber<T>(s));
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDoOnLifecycle.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance 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, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.operators.observable;
<add>
<add>import io.reactivex.Observable;
<add>import io.reactivex.Observer;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.functions.Consumer;
<add>import io.reactivex.internal.subscribers.observable.SubscriptionLambdaObserver;
<add>
<add>public final class ObservableDoOnLifecycle<T> extends ObservableWithUpstream<T, T> {
<add> private final Consumer<? super Disposable> onSubscribe;
<add> private final Runnable onCancel;
<add>
<add> public ObservableDoOnLifecycle(Observable<T> upstream, Consumer<? super Disposable> onSubscribe,
<add> Runnable onCancel) {
<add> super(upstream);
<add> this.onSubscribe = onSubscribe;
<add> this.onCancel = onCancel;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super T> observer) {
<add> source.subscribe(new SubscriptionLambdaObserver<T>(observer, onSubscribe, onCancel));
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableSerialized.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance 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, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.internal.operators.observable;
<add>
<add>import io.reactivex.Observable;
<add>import io.reactivex.Observer;
<add>import io.reactivex.observers.SerializedObserver;
<add>
<add>public final class ObservableSerialized<T> extends ObservableWithUpstream<T, T> {
<add> public ObservableSerialized(Observable<T> upstream) {
<add> super(upstream);
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super T> observer) {
<add> source.subscribe(new SerializedObserver<T>(observer));
<add> }
<add>} | 6 |
Java | Java | fix concurrentmodificationexception on undertow | 2950958f35de1a6d5a265017c5111f640b9887aa | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequest.java
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<del>import java.util.Enumeration;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<ide> public boolean containsKey(Object key) {
<ide>
<ide> @Override
<ide> public void clear() {
<del> Enumeration<String> attributeNames = this.servletRequest.getAttributeNames();
<del> while (attributeNames.hasMoreElements()) {
<del> String name = attributeNames.nextElement();
<del> this.servletRequest.removeAttribute(name);
<del> }
<add> List<String> attributeNames = Collections.list(this.servletRequest.getAttributeNames());
<add> attributeNames.forEach(this.servletRequest::removeAttribute);
<ide> }
<ide>
<ide> @NotNull | 1 |
Javascript | Javascript | require externals plugin for node-webkit target | bbc46a6c0bb9ab0231937921d6365eb9c7284e37 | <ide><path>lib/WebpackOptionsApply.js
<ide> WebpackOptionsApply.prototype.process = function(options, compiler) {
<ide> case "node-webkit":
<ide> var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
<ide> var NodeTargetPlugin = require("./node/NodeTargetPlugin");
<add> var ExternalsPlugin = require("./ExternalsPlugin");
<ide> compiler.apply(
<ide> new JsonpTemplatePlugin(options.output),
<ide> new FunctionModulePlugin(options.output), | 1 |
Text | Text | add nodejs logo to guide | ea1f5c63bed30cdeffc931c955d716cd55669582 | <ide><path>guide/english/nodejs/index.md
<ide> ---
<ide> title: Node.js
<ide> ---
<add>
<add><img src="https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png" height="123" width="201">
<add>
<add>
<ide> ## Node.js
<ide>
<ide> Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world. | 1 |
Javascript | Javascript | use the new naming format for snapshots on macos | 6b696d632941c18a683d01eaf0bf3dc38daf6ca7 | <ide><path>script/lib/generate-startup-snapshot.js
<ide> module.exports = function(packagedAppPath) {
<ide>
<ide> const snapshotBinaries = ['v8_context_snapshot.bin', 'snapshot_blob.bin'];
<ide> for (let snapshotBinary of snapshotBinaries) {
<del> const destinationPath = path.join(
<add> let destinationPath = path.join(
<ide> startupBlobDestinationPath,
<ide> snapshotBinary
<ide> );
<add> if (
<add> process.platform === 'darwin' &&
<add> snapshotBinary === 'v8_context_snapshot.bin'
<add> ) {
<add> // TODO: check if we're building for arm64 and use the arm64 version of the binary
<add> destinationPath = path.join(
<add> startupBlobDestinationPath,
<add> 'v8_context_snapshot.x86_64.bin'
<add> );
<add> }
<ide> console.log(`Moving generated startup blob into "${destinationPath}"`);
<ide> try {
<ide> fs.unlinkSync(destinationPath); | 1 |
Text | Text | remove extraneous line | 06e1b218c990a681dba65a623f15cdb27f188a32 | <ide><path>docs/how-to-translate-files.md
<ide> The translation workflow is split into two main activities:
<ide>
<ide> - **Translating** curriculum files, documentation and UI elements like buttons, labels, etc.:
<ide>
<del> As a translator you can sign up on [our translation platform](https://translate.freecodecamp.org) and contribute translations in any of the 30+ languages enabled in there. If you do not see a language that you speak and are interested in translating, [visit this frequently asked question](/FAQ?id=can-i-translate-freecodecamp39s-resources).
<add> As a translator you can sign up on [our translation platform](https://translate.freecodecamp.org) and contribute translations in any of the 30+ languages enabled in there.
<ide>
<ide> - **Proofreading** the translations for all of the above.
<ide> | 1 |
Ruby | Ruby | add cleanup test | 61614d35294c8faffaeb5c7f0ec6dea78dbbc30f | <ide><path>Library/Homebrew/test/test_integration_cmds.rb
<ide> def test_cellar_formula
<ide> cmd("--cellar", testball)
<ide> end
<ide>
<add> def test_cleanup
<add> assert_equal HOMEBREW_CACHE.to_s,
<add> cmd("cleanup")
<add> end
<add>
<ide> def test_env
<ide> assert_match %r{CMAKE_PREFIX_PATH="#{HOMEBREW_PREFIX}[:"]},
<ide> cmd("--env") | 1 |
Javascript | Javascript | improve js logging | 8b2e79dc68c555ce9cdc874372a3e71ef1ba42ae | <ide><path>packager/react-packager/src/DependencyResolver/haste/polyfills/console.js
<ide> 'use strict';
<ide>
<ide> var OBJECT_COLUMN_NAME = '(index)';
<add> var LOG_LEVELS = {
<add> trace: 0,
<add> log: 1,
<add> info: 2,
<add> warn: 3,
<add> error: 4
<add> };
<ide>
<ide> function setupConsole(global) {
<ide>
<ide> if (!global.nativeLoggingHook) {
<ide> return;
<ide> }
<ide>
<del> function doNativeLog() {
<del> var str = Array.prototype.map.call(arguments, function(arg) {
<del> if (arg == null) {
<del> return arg === null ? 'null' : 'undefined';
<del> } else if (typeof arg === 'string') {
<del> return '"' + arg + '"';
<del> } else {
<del> // Perform a try catch, just in case the object has a circular
<del> // reference or stringify throws for some other reason.
<del> try {
<del> return JSON.stringify(arg);
<del> } catch (e) {
<del> if (typeof arg.toString === 'function') {
<del> try {
<del> return arg.toString();
<del> } catch (E) {
<del> return 'unknown';
<add> function getNativeLogFunction(level) {
<add> return function() {
<add> var str = Array.prototype.map.call(arguments, function(arg) {
<add> if (arg == null) {
<add> return arg === null ? 'null' : 'undefined';
<add> } else if (typeof arg === 'string') {
<add> return '"' + arg + '"';
<add> } else {
<add> // Perform a try catch, just in case the object has a circular
<add> // reference or stringify throws for some other reason.
<add> try {
<add> return JSON.stringify(arg);
<add> } catch (e) {
<add> if (typeof arg.toString === 'function') {
<add> try {
<add> return arg.toString();
<add> } catch (E) {
<add> return 'unknown';
<add> }
<ide> }
<ide> }
<ide> }
<del> }
<del> }).join(', ');
<del> global.nativeLoggingHook(str);
<add> }).join(', ');
<add> global.nativeLoggingHook(str, level);
<add> };
<ide> }
<ide>
<ide> var repeat = function(element, n) {
<ide> }
<ide> }
<ide> if (rows.length === 0) {
<del> global.nativeLoggingHook('');
<add> global.nativeLoggingHook('', LOG_LEVELS.log);
<ide> return;
<ide> }
<ide>
<ide> // Native logging hook adds "RCTLog >" at the front of every
<ide> // logged string, which would shift the header and screw up
<ide> // the table
<del> global.nativeLoggingHook('\n' + table.join('\n'));
<add> global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.log);
<ide> }
<ide>
<ide> global.console = {
<del> error: doNativeLog,
<del> info: doNativeLog,
<del> log: doNativeLog,
<del> warn: doNativeLog,
<add> error: getNativeLogFunction(LOG_LEVELS.error),
<add> info: getNativeLogFunction(LOG_LEVELS.info),
<add> log: getNativeLogFunction(LOG_LEVELS.log),
<add> warn: getNativeLogFunction(LOG_LEVELS.warn),
<add> trace: getNativeLogFunction(LOG_LEVELS.trace),
<ide> table: consoleTablePolyfill
<ide> };
<ide> | 1 |
PHP | PHP | address feedback from review | 62314dcbb700d3c085efebc9ff6d0ffe96f15794 | <ide><path>src/Core/functions.php
<ide> function deprecationWarning($message, $stackFrame = 2)
<ide> if (!(error_reporting() & E_USER_DEPRECATED)) {
<ide> return;
<ide> }
<add>
<ide> $trace = debug_backtrace();
<ide> if (isset($trace[$stackFrame])) {
<ide> $frame = $trace[$stackFrame];
<ide><path>tests/TestCase/Core/FunctionsTest.php
<ide> public function testEnv()
<ide> }
<ide>
<ide> /**
<del> * Test error messages coming out when debug is on
<add> * Test error messages coming out when debug is on, manually setting the stack frame
<ide> *
<ide> * @expectedException PHPUnit\Framework\Error\Deprecated
<ide> * @expectedExceptionMessage This is going away - [internal], line: ??
<ide> public function testDeprecationWarningEnabled()
<ide> }
<ide>
<ide> /**
<del> * Test error messages coming out when debug is on
<add> * Test error messages coming out when debug is on, not setting the stack frame manually
<ide> *
<ide> * @expectedException PHPUnit\Framework\Error\Deprecated
<ide> * @expectedExceptionMessageRegExp /This is going away - (.*?)\/TestCase.php, line\: \d+/ | 2 |
Javascript | Javascript | add todo about broken check | 548ba83d7ec9fbf2485a3a8d83f6534670e09ffa | <ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js
<ide> function setUpCollections(): void {
<ide> function setUpDevTools(): void {
<ide> if (__DEV__) {
<ide> // not when debugging in chrome
<add> // TODO(t12832058) This check is broken
<ide> if (!window.document) {
<ide> const setupDevtools = require('setupDevtools');
<ide> setupDevtools(); | 1 |
Go | Go | improve gettimestamp parsing | 48cfe3f0872647bf0f52e6ba65022e1859e808e8 | <ide><path>api/types/time/timestamp.go
<ide> func GetTimestamp(value string, reference time.Time) (string, error) {
<ide> }
<ide>
<ide> if err != nil {
<del> // if there is a `-` then it's an RFC3339 like timestamp otherwise assume unixtimestamp
<add> // if there is a `-` then it's an RFC3339 like timestamp
<ide> if strings.Contains(value, "-") {
<ide> return "", err // was probably an RFC3339 like timestamp but the parser failed with an error
<ide> }
<del> return value, nil // unixtimestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server)
<add> if _, _, err := parseTimestamp(value); err != nil {
<add> return "", fmt.Errorf("failed to parse value as time or duration: %q", value)
<add> }
<add> return value, nil // unix timestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server)
<ide> }
<ide>
<ide> return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil
<ide> func ParseTimestamps(value string, def int64) (int64, int64, error) {
<ide> if value == "" {
<ide> return def, 0, nil
<ide> }
<add> return parseTimestamp(value)
<add>}
<add>
<add>func parseTimestamp(value string) (int64, int64, error) {
<ide> sa := strings.SplitN(value, ".", 2)
<ide> s, err := strconv.ParseInt(sa[0], 10, 64)
<ide> if err != nil {
<ide><path>api/types/time/timestamp_test.go
<ide> func TestGetTimestamp(t *testing.T) {
<ide> {"1.5h", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix()), false},
<ide> {"1h30m", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix()), false},
<ide>
<del> // String fallback
<del> {"invalid", "invalid", false},
<add> {"invalid", "", true},
<add> {"", "", true},
<ide> }
<ide>
<ide> for _, c := range cases {
<ide><path>client/container_logs.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> timetypes "github.com/docker/docker/api/types/time"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // ContainerLogs returns the logs generated by a container in an io.ReadCloser.
<ide> func (cli *Client) ContainerLogs(ctx context.Context, container string, options
<ide> if options.Since != "" {
<ide> ts, err := timetypes.GetTimestamp(options.Since, time.Now())
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, `invalid value for "since"`)
<ide> }
<ide> query.Set("since", ts)
<ide> }
<ide>
<ide> if options.Until != "" {
<ide> ts, err := timetypes.GetTimestamp(options.Until, time.Now())
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, `invalid value for "until"`)
<ide> }
<ide> query.Set("until", ts)
<ide> }
<ide><path>client/container_logs_test.go
<ide> package client // import "github.com/docker/docker/client"
<ide>
<ide> import (
<ide> "bytes"
<add> "context"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<del> "context"
<del>
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/internal/testutil"
<add> "github.com/gotestyourself/gotestyourself/assert"
<add> is "github.com/gotestyourself/gotestyourself/assert/cmp"
<ide> )
<ide>
<ide> func TestContainerLogsNotFoundError(t *testing.T) {
<ide> func TestContainerLogsError(t *testing.T) {
<ide> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
<ide> }
<ide> _, err := client.ContainerLogs(context.Background(), "container_id", types.ContainerLogsOptions{})
<del> if err == nil || err.Error() != "Error response from daemon: Server error" {
<del> t.Fatalf("expected a Server Error, got %v", err)
<del> }
<add> assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
<ide> _, err = client.ContainerLogs(context.Background(), "container_id", types.ContainerLogsOptions{
<ide> Since: "2006-01-02TZ",
<ide> })
<del> testutil.ErrorContains(t, err, `parsing time "2006-01-02TZ"`)
<add> assert.Check(t, is.ErrorContains(err, `parsing time "2006-01-02TZ"`))
<ide> _, err = client.ContainerLogs(context.Background(), "container_id", types.ContainerLogsOptions{
<ide> Until: "2006-01-02TZ",
<ide> })
<del> testutil.ErrorContains(t, err, `parsing time "2006-01-02TZ"`)
<add> assert.Check(t, is.ErrorContains(err, `parsing time "2006-01-02TZ"`))
<ide> }
<ide>
<ide> func TestContainerLogs(t *testing.T) {
<ide> expectedURL := "/containers/container_id/logs"
<ide> cases := []struct {
<ide> options types.ContainerLogsOptions
<ide> expectedQueryParams map[string]string
<add> expectedError string
<ide> }{
<ide> {
<ide> expectedQueryParams: map[string]string{
<ide> func TestContainerLogs(t *testing.T) {
<ide> },
<ide> {
<ide> options: types.ContainerLogsOptions{
<del> // An complete invalid date, timestamp or go duration will be
<del> // passed as is
<del> Since: "invalid but valid",
<add> // timestamp will be passed as is
<add> Since: "1136073600.000000001",
<ide> },
<ide> expectedQueryParams: map[string]string{
<ide> "tail": "",
<del> "since": "invalid but valid",
<add> "since": "1136073600.000000001",
<ide> },
<ide> },
<ide> {
<ide> options: types.ContainerLogsOptions{
<del> // An complete invalid date, timestamp or go duration will be
<del> // passed as is
<del> Until: "invalid but valid",
<add> // timestamp will be passed as is
<add> Until: "1136073600.000000001",
<ide> },
<ide> expectedQueryParams: map[string]string{
<ide> "tail": "",
<del> "until": "invalid but valid",
<add> "until": "1136073600.000000001",
<add> },
<add> },
<add> {
<add> options: types.ContainerLogsOptions{
<add> // An complete invalid date will not be passed
<add> Since: "invalid value",
<ide> },
<add> expectedError: `invalid value for "since": failed to parse value as time or duration: "invalid value"`,
<add> },
<add> {
<add> options: types.ContainerLogsOptions{
<add> // An complete invalid date will not be passed
<add> Until: "invalid value",
<add> },
<add> expectedError: `invalid value for "until": failed to parse value as time or duration: "invalid value"`,
<ide> },
<ide> }
<ide> for _, logCase := range cases {
<ide> client := &Client{
<ide> client: newMockClient(func(r *http.Request) (*http.Response, error) {
<ide> if !strings.HasPrefix(r.URL.Path, expectedURL) {
<del> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL)
<add> return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, r.URL)
<ide> }
<ide> // Check query parameters
<ide> query := r.URL.Query()
<ide> func TestContainerLogs(t *testing.T) {
<ide> }),
<ide> }
<ide> body, err := client.ContainerLogs(context.Background(), "container_id", logCase.options)
<del> if err != nil {
<del> t.Fatal(err)
<add> if logCase.expectedError != "" {
<add> assert.Check(t, is.Error(err, logCase.expectedError))
<add> continue
<ide> }
<add> assert.NilError(t, err)
<ide> defer body.Close()
<ide> content, err := ioutil.ReadAll(body)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if string(content) != "response" {
<del> t.Fatalf("expected response to contain 'response', got %s", string(content))
<del> }
<add> assert.NilError(t, err)
<add> assert.Check(t, is.Contains(string(content), "response"))
<ide> }
<ide> }
<ide>
<ide><path>client/service_logs.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> timetypes "github.com/docker/docker/api/types/time"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // ServiceLogs returns the logs generated by a service in an io.ReadCloser.
<ide> func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options ty
<ide> if options.Since != "" {
<ide> ts, err := timetypes.GetTimestamp(options.Since, time.Now())
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.Wrap(err, `invalid value for "since"`)
<ide> }
<ide> query.Set("since", ts)
<ide> }
<ide><path>client/service_logs_test.go
<ide> package client // import "github.com/docker/docker/client"
<ide>
<ide> import (
<ide> "bytes"
<add> "context"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<del> "context"
<del>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/gotestyourself/gotestyourself/assert"
<add> is "github.com/gotestyourself/gotestyourself/assert/cmp"
<ide> )
<ide>
<ide> func TestServiceLogsError(t *testing.T) {
<ide> client := &Client{
<ide> client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
<ide> }
<ide> _, err := client.ServiceLogs(context.Background(), "service_id", types.ContainerLogsOptions{})
<del> if err == nil || err.Error() != "Error response from daemon: Server error" {
<del> t.Fatalf("expected a Server Error, got %v", err)
<del> }
<add> assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
<ide> _, err = client.ServiceLogs(context.Background(), "service_id", types.ContainerLogsOptions{
<ide> Since: "2006-01-02TZ",
<ide> })
<del> if err == nil || !strings.Contains(err.Error(), `parsing time "2006-01-02TZ"`) {
<del> t.Fatalf("expected a 'parsing time' error, got %v", err)
<del> }
<add> assert.Check(t, is.ErrorContains(err, `parsing time "2006-01-02TZ"`))
<ide> }
<ide>
<ide> func TestServiceLogs(t *testing.T) {
<ide> expectedURL := "/services/service_id/logs"
<ide> cases := []struct {
<ide> options types.ContainerLogsOptions
<ide> expectedQueryParams map[string]string
<add> expectedError string
<ide> }{
<ide> {
<ide> expectedQueryParams: map[string]string{
<ide> func TestServiceLogs(t *testing.T) {
<ide> },
<ide> {
<ide> options: types.ContainerLogsOptions{
<del> // An complete invalid date, timestamp or go duration will be
<del> // passed as is
<del> Since: "invalid but valid",
<add> // timestamp will be passed as is
<add> Since: "1136073600.000000001",
<ide> },
<ide> expectedQueryParams: map[string]string{
<ide> "tail": "",
<del> "since": "invalid but valid",
<add> "since": "1136073600.000000001",
<ide> },
<ide> },
<add> {
<add> options: types.ContainerLogsOptions{
<add> // An complete invalid date will not be passed
<add> Since: "invalid value",
<add> },
<add> expectedError: `invalid value for "since": failed to parse value as time or duration: "invalid value"`,
<add> },
<ide> }
<ide> for _, logCase := range cases {
<ide> client := &Client{
<ide> client: newMockClient(func(r *http.Request) (*http.Response, error) {
<ide> if !strings.HasPrefix(r.URL.Path, expectedURL) {
<del> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL)
<add> return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, r.URL)
<ide> }
<ide> // Check query parameters
<ide> query := r.URL.Query()
<ide> func TestServiceLogs(t *testing.T) {
<ide> }),
<ide> }
<ide> body, err := client.ServiceLogs(context.Background(), "service_id", logCase.options)
<del> if err != nil {
<del> t.Fatal(err)
<add> if logCase.expectedError != "" {
<add> assert.Check(t, is.Error(err, logCase.expectedError))
<add> continue
<ide> }
<add> assert.NilError(t, err)
<ide> defer body.Close()
<ide> content, err := ioutil.ReadAll(body)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if string(content) != "response" {
<del> t.Fatalf("expected response to contain 'response', got %s", string(content))
<del> }
<add> assert.NilError(t, err)
<add> assert.Check(t, is.Contains(string(content), "response"))
<ide> }
<ide> }
<ide> | 6 |
Go | Go | prefer windows over linux in a manifest list | ddcdb7255d960a4b2049439245a4f887b26af891 | <ide><path>distribution/pull_v2_windows.go
<ide> func filterManifests(manifests []manifestlist.ManifestDescriptor, p specs.Platfo
<ide> if (manifestDescriptor.Platform.Architecture == runtime.GOARCH) &&
<ide> ((p.OS != "" && manifestDescriptor.Platform.OS == p.OS) || // Explicit user request for an OS we know we support
<ide> (p.OS == "" && system.IsOSSupported(manifestDescriptor.Platform.OS))) { // No user requested OS, but one we can support
<del> matches = append(matches, manifestDescriptor)
<del> logrus.Debugf("found match %s/%s %s with media type %s, digest %s", manifestDescriptor.Platform.OS, runtime.GOARCH, manifestDescriptor.Platform.OSVersion, manifestDescriptor.MediaType, manifestDescriptor.Digest.String())
<ide> if strings.EqualFold("windows", manifestDescriptor.Platform.OS) {
<add> if err := checkImageCompatibility("windows", manifestDescriptor.Platform.OSVersion); err != nil {
<add> continue
<add> }
<ide> foundWindowsMatch = true
<ide> }
<add> matches = append(matches, manifestDescriptor)
<add> logrus.Debugf("found match %s/%s %s with media type %s, digest %s", manifestDescriptor.Platform.OS, runtime.GOARCH, manifestDescriptor.Platform.OSVersion, manifestDescriptor.MediaType, manifestDescriptor.Digest.String())
<ide> } else {
<ide> logrus.Debugf("ignoring %s/%s %s with media type %s, digest %s", manifestDescriptor.Platform.OS, manifestDescriptor.Platform.Architecture, manifestDescriptor.Platform.OSVersion, manifestDescriptor.MediaType, manifestDescriptor.Digest.String())
<ide> }
<ide> func (mbv manifestsByVersion) Less(i, j int) bool {
<ide> // TODO: Split version by parts and compare
<ide> // TODO: Prefer versions which have a greater version number
<ide> // Move compatible versions to the top, with no other ordering changes
<del> return versionMatch(mbv.list[i].Platform.OSVersion, mbv.version) && !versionMatch(mbv.list[j].Platform.OSVersion, mbv.version)
<add> return (strings.EqualFold("windows", mbv.list[i].Platform.OS) && !strings.EqualFold("windows", mbv.list[j].Platform.OS)) ||
<add> (versionMatch(mbv.list[i].Platform.OSVersion, mbv.version) && !versionMatch(mbv.list[j].Platform.OSVersion, mbv.version))
<ide> }
<ide>
<ide> func (mbv manifestsByVersion) Len() int { | 1 |
Ruby | Ruby | make variable names consistent with other code | ab0368cb3422648ed38d7d4dee183f3dd7dc66bb | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def single_commit? start_revision, end_revision
<ide> end
<ide> end
<ide>
<del> def skip formula
<del> puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula}#{Tty.reset}"
<add> def skip formula_name
<add> puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula_name}#{Tty.reset}"
<ide> end
<ide>
<del> def satisfied_requirements? formula_object, spec
<del> requirements = formula_object.send(spec).requirements
<add> def satisfied_requirements? formula, spec
<add> requirements = formula.send(spec).requirements
<ide>
<ide> unsatisfied_requirements = requirements.reject do |requirement|
<ide> requirement.satisfied? || requirement.default_formula?
<ide> def satisfied_requirements? formula_object, spec
<ide> if unsatisfied_requirements.empty?
<ide> true
<ide> else
<del> formula = formula_object.name
<del> formula += " (#{spec})" unless spec == :stable
<del> skip formula
<del> unsatisfied_requirements.each {|r| puts r.message}
<add> name = formula.name
<add> name += " (#{spec})" unless spec == :stable
<add> skip name
<add> puts unsatisfied_requirements.map(&:message)
<ide> false
<ide> end
<ide> end
<ide> def setup
<ide> test "brew", "config"
<ide> end
<ide>
<del> def formula formula
<del> @category = __method__.to_s + ".#{formula}"
<add> def formula formula_name
<add> @category = "#{__method__}.#{formula_name}"
<ide>
<del> test "brew", "uses", formula
<del> dependencies = `brew deps #{formula}`.split("\n")
<add> test "brew", "uses", formula_name
<add> dependencies = `brew deps #{formula_name}`.split("\n")
<ide> dependencies -= `brew list`.split("\n")
<ide> unchanged_dependencies = dependencies - @formulae
<ide> changed_dependences = dependencies - unchanged_dependencies
<del> formula_object = Formulary.factory(formula)
<del> return unless satisfied_requirements?(formula_object, :stable)
<add> formula = Formulary.factory(formula_name)
<add> return unless satisfied_requirements?(formula, :stable)
<ide>
<ide> installed_gcc = false
<del> deps = formula_object.stable.deps.to_a
<del> reqs = formula_object.stable.requirements.to_a
<del> if formula_object.devel && !ARGV.include?('--HEAD')
<del> deps |= formula_object.devel.deps.to_a
<del> reqs |= formula_object.devel.requirements.to_a
<add> deps = formula.stable.deps.to_a
<add> reqs = formula.stable.requirements.to_a
<add> if formula.devel && !ARGV.include?('--HEAD')
<add> deps |= formula.devel.deps.to_a
<add> reqs |= formula.devel.requirements.to_a
<ide> end
<ide>
<ide> begin
<ide> deps.each { |d| CompilerSelector.select_for(d.to_formula) }
<del> CompilerSelector.select_for(formula_object)
<add> CompilerSelector.select_for(formula)
<ide> rescue CompilerSelectionError => e
<ide> unless installed_gcc
<ide> test "brew", "install", "gcc"
<ide> installed_gcc = true
<ide> OS::Mac.clear_version_cache
<ide> retry
<ide> end
<del> skip formula
<add> skip formula_name
<ide> puts e.message
<ide> return
<ide> end
<ide> def formula formula
<ide> formula_fetch_options = []
<ide> formula_fetch_options << "--build-bottle" unless ARGV.include? "--no-bottle"
<ide> formula_fetch_options << "--force" if ARGV.include? "--cleanup"
<del> formula_fetch_options << formula
<add> formula_fetch_options << formula_name
<ide> test "brew", "fetch", "--retry", *formula_fetch_options
<del> test "brew", "uninstall", "--force", formula if formula_object.installed?
<add> test "brew", "uninstall", "--force", formula_name if formula.installed?
<ide> install_args = %w[--verbose]
<ide> install_args << "--build-bottle" unless ARGV.include? "--no-bottle"
<ide> install_args << "--HEAD" if ARGV.include? "--HEAD"
<del> install_args << formula
<add> install_args << formula_name
<ide> # Don't care about e.g. bottle failures for dependencies.
<ide> ENV["HOMEBREW_DEVELOPER"] = nil
<ide> test "brew", "install", "--only-dependencies", *install_args unless dependencies.empty?
<ide> ENV["HOMEBREW_DEVELOPER"] = "1"
<ide> test "brew", "install", *install_args
<ide> install_passed = steps.last.passed?
<del> test "brew", "audit", formula
<add> test "brew", "audit", formula_name
<ide> if install_passed
<ide> unless ARGV.include? '--no-bottle'
<del> test "brew", "bottle", "--rb", formula, :puts_output_on_success => true
<add> test "brew", "bottle", "--rb", formula_name, :puts_output_on_success => true
<ide> bottle_step = steps.last
<ide> if bottle_step.passed? and bottle_step.has_output?
<ide> bottle_filename =
<ide> bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1')
<del> test "brew", "uninstall", "--force", formula
<add> test "brew", "uninstall", "--force", formula_name
<ide> test "brew", "install", bottle_filename
<ide> end
<ide> end
<del> test "brew", "test", "--verbose", formula if formula_object.test_defined?
<del> test "brew", "uninstall", "--force", formula
<add> test "brew", "test", "--verbose", formula_name if formula.test_defined?
<add> test "brew", "uninstall", "--force", formula_name
<ide> end
<ide>
<del> if formula_object.devel && !ARGV.include?('--HEAD') \
<del> && satisfied_requirements?(formula_object, :devel)
<add> if formula.devel && !ARGV.include?('--HEAD') \
<add> && satisfied_requirements?(formula, :devel)
<ide> test "brew", "fetch", "--retry", "--devel", *formula_fetch_options
<del> test "brew", "install", "--devel", "--verbose", formula
<add> test "brew", "install", "--devel", "--verbose", formula_name
<ide> devel_install_passed = steps.last.passed?
<del> test "brew", "audit", "--devel", formula
<add> test "brew", "audit", "--devel", formula_name
<ide> if devel_install_passed
<del> test "brew", "test", "--devel", "--verbose", formula if formula_object.test_defined?
<del> test "brew", "uninstall", "--devel", "--force", formula
<add> test "brew", "test", "--devel", "--verbose", formula_name if formula.test_defined?
<add> test "brew", "uninstall", "--devel", "--force", formula_name
<ide> end
<ide> end
<ide> test "brew", "uninstall", "--force", *unchanged_dependencies unless unchanged_dependencies.empty? | 1 |
PHP | PHP | fix double encoding in jshelper request methods | 75f654b87bc91286baae58eb89f3f5d04cf20e13 | <ide><path>lib/Cake/Test/Case/View/Helper/JqueryEngineHelperTest.php
<ide> public function testRequest() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test that querystring arguments are not double escaped.
<add> *
<add> * @return void
<add> */
<add> public function testRequestWithQueryStringArguments() {
<add> $url = '/users/search/sort:User.name/direction:desc?nome=&cpm=&audience=public';
<add> $result = $this->Jquery->request($url);
<add> $expected = '$.ajax({url:"\\/users\\/search\\/sort:User.name\\/direction:desc?nome=&cpm=&audience=public"});';
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<ide> /**
<ide> * test that alternate jQuery object values work for request()
<ide> *
<ide><path>lib/Cake/View/Helper/JqueryEngineHelper.php
<ide> public function effect($name, $options = array()) {
<ide> * @see JsBaseEngineHelper::request() for options list.
<ide> */
<ide> public function request($url, $options = array()) {
<del> $url = $this->url($url);
<add> $url = html_entity_decode($this->url($url), ENT_COMPAT, Configure::read('App.encoding'));
<ide> $options = $this->_mapOptions('request', $options);
<ide> if (isset($options['data']) && is_array($options['data'])) {
<ide> $options['data'] = $this->_toQuerystring($options['data']);
<ide><path>lib/Cake/View/Helper/MootoolsEngineHelper.php
<ide> public function effect($name, $options = array()) {
<ide> * @return string The completed ajax call.
<ide> */
<ide> public function request($url, $options = array()) {
<del> $url = $this->url($url);
<add> $url = html_entity_decode($this->url($url), ENT_COMPAT, Configure::read('App.encoding'));
<ide> $options = $this->_mapOptions('request', $options);
<ide> $type = $data = null;
<ide> if (isset($options['type']) || isset($options['update'])) {
<ide><path>lib/Cake/View/Helper/PrototypeEngineHelper.php
<ide> public function effect($name, $options = array()) {
<ide> * @return string The completed ajax call.
<ide> */
<ide> public function request($url, $options = array()) {
<del> $url = '"' . $this->url($url) . '"';
<add> $url = html_entity_decode($this->url($url), ENT_COMPAT, Configure::read('App.encoding'));
<add> $url = '"' . $url . '"';
<ide> $options = $this->_mapOptions('request', $options);
<ide> $type = '.Request';
<ide> if (isset($options['type']) && strtolower($options['type']) == 'json') { | 4 |
Ruby | Ruby | create the tmpdir under test | e201b9d45514c310b8194b3f0d9b8d5d711a1216 | <ide><path>activesupport/test/file_update_checker_with_enumerable_test_cases.rb
<ide> def touch(files)
<ide> end
<ide>
<ide> def setup
<del> @tmpdir = Dir.mktmpdir
<add> @tmpdir = Dir.mktmpdir(nil, __dir__)
<ide>
<ide> @files = %w(foo.rb bar.rb baz.rb).map {|f| "#{@tmpdir}/#{f}"}
<ide> FileUtils.touch(@files) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.