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
|
---|---|---|---|---|---|
Java | Java | add doesnotexist match to headerresultmatchers | 4bf5a0234c6c5c5d6591eb0fa52db3bf09573d9f | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java
<ide>
<ide> package org.springframework.test.web.servlet.result;
<ide>
<del>import static org.springframework.test.util.AssertionErrors.assertEquals;
<del>import static org.springframework.test.util.AssertionErrors.assertTrue;
<del>import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
<del>
<ide> import org.hamcrest.Matcher;
<ide> import org.springframework.test.web.servlet.MvcResult;
<ide> import org.springframework.test.web.servlet.ResultMatcher;
<ide>
<add>import static org.springframework.test.util.AssertionErrors.*;
<add>import static org.springframework.test.util.MatcherAssertionErrors.*;
<add>
<ide> /**
<ide> * Factory for response header assertions. An instance of this
<ide> * class is usually accessed via {@link MockMvcResultMatchers#header()}.
<ide> public void match(MvcResult result) {
<ide> };
<ide> }
<ide>
<add> /**
<add> * Assert that the named response header does not exist.
<add> * @since 4.0
<add> */
<add> public ResultMatcher doesNotExist(final String name) {
<add> return new ResultMatcher() {
<add>
<add> @Override
<add> public void match(MvcResult result) {
<add> assertTrue("Response should not contain header " + name, !result.getResponse().containsHeader(name));
<add> }
<add> };
<add> }
<add>
<ide> /**
<ide> * Assert the primary value of the named response header as a {@code long}.
<ide> *
<ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java
<ide>
<ide> /**
<ide> * Examples of expectations on response header values.
<del> *
<add> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Sam Brannen
<ide> */
<ide> public void longValueWithMissingResponseHeader() throws Exception {
<ide> }
<ide> }
<ide>
<add> // SPR-10771
<add>
<add> @Test
<add> public void doesNotExist() throws Exception {
<add> this.mockMvc.perform(get("/persons/1"))
<add> .andExpect(header().doesNotExist("X-Custom-Header"));
<add> }
<add>
<add> // SPR-10771
<add>
<add> @Test(expected = AssertionError.class)
<add> public void doesNotExistFail() throws Exception {
<add> this.mockMvc.perform(get("/persons/1"))
<add> .andExpect(header().doesNotExist(LAST_MODIFIED));
<add> }
<add>
<ide> @Test
<ide> public void stringWithIncorrectResponseHeaderValue() throws Exception {
<ide> long unexpected = currentTime + 1; | 2 |
Go | Go | change the wording of image verification warning | c97d8b1233bc17a9e58ce97473329ab5de59969a | <ide><path>graph/pull.go
<ide> func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
<ide>
<ide> }
<ide>
<del> out.Write(sf.FormatStatus(repoInfo.CanonicalName+":"+tag, "The image you are pulling has been verified - This is a tech preview, don't rely on it for security yet."))
<add> out.Write(sf.FormatStatus(repoInfo.CanonicalName+":"+tag, "The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security."))
<ide>
<ide> if err = s.Set(repoInfo.LocalName, tag, downloads[0].img.ID, true); err != nil {
<ide> return false, err | 1 |
Python | Python | add a sqlite backend. one test passes! | d3d1e599211c31e05d095b878de517dbb6fc998c | <ide><path>django/db/backends/sqlite3/base.py
<ide> from django.db.backends.sqlite3.client import DatabaseClient
<ide> from django.db.backends.sqlite3.creation import DatabaseCreation
<ide> from django.db.backends.sqlite3.introspection import DatabaseIntrospection
<add>from django.db.backends.sqlite3.schema import DatabaseSchemaEditor
<ide> from django.utils.dateparse import parse_date, parse_datetime, parse_time
<ide> from django.utils.functional import cached_property
<ide> from django.utils.safestring import SafeString
<ide> def close(self):
<ide> if self.settings_dict['NAME'] != ":memory:":
<ide> BaseDatabaseWrapper.close(self)
<ide>
<add> def schema_editor(self):
<add> "Returns a new instance of this backend's SchemaEditor"
<add> return DatabaseSchemaEditor(self)
<add>
<ide> FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
<ide>
<ide> class SQLiteCursorWrapper(Database.Cursor):
<ide><path>django/db/backends/sqlite3/schema.py
<add>from django.db.backends.schema import BaseDatabaseSchemaEditor
<add>
<add>
<add>class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
<add>
<add> sql_delete_table = "DROP TABLE %(table)s"
<ide><path>tests/modeltests/schema/tests.py
<ide> def tearDown(self):
<ide> # Remove any M2M tables first
<ide> for field in model._meta.local_many_to_many:
<ide> try:
<del> cursor.execute("DROP TABLE %s CASCADE" % (
<del> connection.ops.quote_name(field.rel.through._meta.db_table),
<del> ))
<add> cursor.execute(connection.schema_editor().sql_delete_table % {
<add> "table": connection.ops.quote_name(field.rel.through._meta.db_table),
<add> })
<ide> except DatabaseError:
<ide> connection.rollback()
<ide> else:
<ide> connection.commit()
<ide> # Then remove the main tables
<ide> try:
<del> cursor.execute("DROP TABLE %s CASCADE" % (
<del> connection.ops.quote_name(model._meta.db_table),
<del> ))
<add> cursor.execute(connection.schema_editor().sql_delete_table % {
<add> "table": connection.ops.quote_name(model._meta.db_table),
<add> })
<ide> except DatabaseError:
<ide> connection.rollback()
<ide> else: | 3 |
Javascript | Javascript | use proper locale inheritance for the base locale | 9175f8256747ed8937c8197ba4575666e60020f3 | <ide><path>src/lib/locale/base-config.js
<add>import { defaultCalendar } from './calendar';
<add>import { defaultLongDateFormat } from './formats';
<add>import { defaultInvalidDate } from './invalid';
<add>import { defaultOrdinal, defaultOrdinalParse } from './ordinal';
<add>import { defaultRelativeTime } from './relative';
<add>
<add>// months
<add>import {
<add> defaultLocaleMonths,
<add> defaultLocaleMonthsShort,
<add> defaultMonthsRegex,
<add> defaultMonthsShortRegex,
<add>} from '../units/month';
<add>
<add>// week
<add>import { defaultLocaleWeek } from '../units/week';
<add>
<add>// weekdays
<add>import {
<add> defaultLocaleWeekdays,
<add> defaultLocaleWeekdaysMin,
<add> defaultLocaleWeekdaysShort,
<add>
<add> defaultWeekdaysRegex,
<add> defaultWeekdaysShortRegex,
<add> defaultWeekdaysMinRegex,
<add>} from '../units/day-of-week';
<add>
<add>// meridiem
<add>import { defaultLocaleMeridiemParse } from '../units/hour';
<add>
<add>export var baseConfig = {
<add> calendar: defaultCalendar,
<add> longDateFormat: defaultLongDateFormat,
<add> invalidDate: defaultInvalidDate,
<add> ordinal: defaultOrdinal,
<add> ordinalParse: defaultOrdinalParse,
<add> relativeTime: defaultRelativeTime,
<add>
<add> months: defaultLocaleMonths,
<add> monthsShort: defaultLocaleMonthsShort,
<add> monthsRegex: defaultMonthsRegex,
<add> monthsShortRegex: defaultMonthsShortRegex,
<add>
<add> week: defaultLocaleWeek,
<add>
<add> weekdays: defaultLocaleWeekdays,
<add> weekdaysMin: defaultLocaleWeekdaysMin,
<add> weekdaysShort: defaultLocaleWeekdaysShort,
<add>
<add> weekdaysRegex: defaultWeekdaysRegex,
<add> weekdaysShortRegex: defaultWeekdaysShortRegex,
<add> weekdaysMinRegex: defaultWeekdaysMinRegex,
<add>
<add> meridiemParse: defaultLocaleMeridiemParse
<add>};
<ide><path>src/lib/locale/locales.js
<ide> import isArray from '../utils/is-array';
<add>import hasOwnProp from '../utils/has-own-prop';
<ide> import isUndefined from '../utils/is-undefined';
<ide> import compareArrays from '../utils/compare-arrays';
<ide> import { deprecateSimple } from '../utils/deprecate';
<ide> import { mergeConfigs } from './set';
<ide> import { Locale } from './constructor';
<ide> import keys from '../utils/keys';
<ide>
<add>import { baseConfig } from './base-config';
<add>
<ide> // internal storage for locale config files
<ide> var locales = {};
<ide> var globalLocale;
<ide> export function getSetGlobalLocale (key, values) {
<ide> return globalLocale._abbr;
<ide> }
<ide>
<add>function sanitizeLocaleConfig(config) {
<add> if (!hasOwnProp(config, 'longDateFormat')) {
<add> config.longDateFormat = {};
<add> }
<add> return config;
<add>}
<add>
<ide> export function defineLocale (name, config) {
<ide> if (config !== null) {
<add> config = sanitizeLocaleConfig(config);
<add> var parentConfig = baseConfig;
<ide> config.abbr = name;
<ide> if (locales[name] != null) {
<ide> deprecateSimple('defineLocaleOverride',
<ide> 'use moment.updateLocale(localeName, config) to change ' +
<ide> 'an existing locale. moment.defineLocale(localeName, ' +
<ide> 'config) should only be used for creating a new locale ' +
<ide> 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
<del> config = mergeConfigs(locales[name]._config, config);
<add> parentConfig = locales[name]._config;
<ide> } else if (config.parentLocale != null) {
<ide> if (locales[config.parentLocale] != null) {
<del> config = mergeConfigs(locales[config.parentLocale]._config, config);
<add> parentConfig = locales[config.parentLocale]._config;
<ide> } else {
<ide> // treat as if there is no base config
<ide> deprecateSimple('parentLocaleUndefined',
<ide> 'specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/');
<ide> }
<ide> }
<del> locales[name] = new Locale(config);
<add> locales[name] = new Locale(mergeConfigs(parentConfig, config));
<ide>
<ide> // backwards compat for now: also set the locale
<ide> getSetGlobalLocale(name);
<ide> export function defineLocale (name, config) {
<ide>
<ide> export function updateLocale(name, config) {
<ide> if (config != null) {
<del> var locale;
<add> var locale, parentConfig = baseConfig;
<add> // MERGE
<ide> if (locales[name] != null) {
<del> config = mergeConfigs(locales[name]._config, config);
<add> parentConfig = locales[name]._config;
<ide> }
<add> config = mergeConfigs(parentConfig, config);
<ide> locale = new Locale(config);
<ide> locale.parentLocale = locales[name];
<ide> locales[name] = locale;
<ide><path>src/lib/locale/prototype.js
<ide> import { Locale } from './constructor';
<ide>
<ide> var proto = Locale.prototype;
<ide>
<del>import { defaultCalendar, calendar } from './calendar';
<del>import { defaultLongDateFormat, longDateFormat } from './formats';
<del>import { defaultInvalidDate, invalidDate } from './invalid';
<del>import { defaultOrdinal, ordinal, defaultOrdinalParse } from './ordinal';
<add>import { calendar } from './calendar';
<add>import { longDateFormat } from './formats';
<add>import { invalidDate } from './invalid';
<add>import { ordinal } from './ordinal';
<ide> import { preParsePostFormat } from './pre-post-format';
<del>import { defaultRelativeTime, relativeTime, pastFuture } from './relative';
<add>import { relativeTime, pastFuture } from './relative';
<ide> import { set } from './set';
<ide>
<del>proto._calendar = defaultCalendar;
<ide> proto.calendar = calendar;
<del>proto._longDateFormat = defaultLongDateFormat;
<ide> proto.longDateFormat = longDateFormat;
<del>proto._invalidDate = defaultInvalidDate;
<ide> proto.invalidDate = invalidDate;
<del>proto._ordinal = defaultOrdinal;
<ide> proto.ordinal = ordinal;
<del>proto._ordinalParse = defaultOrdinalParse;
<ide> proto.preparse = preParsePostFormat;
<ide> proto.postformat = preParsePostFormat;
<del>proto._relativeTime = defaultRelativeTime;
<ide> proto.relativeTime = relativeTime;
<ide> proto.pastFuture = pastFuture;
<ide> proto.set = set;
<ide>
<ide> // Month
<ide> import {
<ide> localeMonthsParse,
<del> defaultLocaleMonths, localeMonths,
<del> defaultLocaleMonthsShort, localeMonthsShort,
<del> defaultMonthsRegex, monthsRegex,
<del> defaultMonthsShortRegex, monthsShortRegex
<add> localeMonths,
<add> localeMonthsShort,
<add> monthsRegex,
<add> monthsShortRegex
<ide> } from '../units/month';
<ide>
<ide> proto.months = localeMonths;
<del>proto._months = defaultLocaleMonths;
<ide> proto.monthsShort = localeMonthsShort;
<del>proto._monthsShort = defaultLocaleMonthsShort;
<ide> proto.monthsParse = localeMonthsParse;
<del>proto._monthsRegex = defaultMonthsRegex;
<ide> proto.monthsRegex = monthsRegex;
<del>proto._monthsShortRegex = defaultMonthsShortRegex;
<ide> proto.monthsShortRegex = monthsShortRegex;
<ide>
<ide> // Week
<del>import { localeWeek, defaultLocaleWeek, localeFirstDayOfYear, localeFirstDayOfWeek } from '../units/week';
<add>import { localeWeek, localeFirstDayOfYear, localeFirstDayOfWeek } from '../units/week';
<ide> proto.week = localeWeek;
<del>proto._week = defaultLocaleWeek;
<ide> proto.firstDayOfYear = localeFirstDayOfYear;
<ide> proto.firstDayOfWeek = localeFirstDayOfWeek;
<ide>
<ide> // Day of Week
<ide> import {
<ide> localeWeekdaysParse,
<del> defaultLocaleWeekdays, localeWeekdays,
<del> defaultLocaleWeekdaysMin, localeWeekdaysMin,
<del> defaultLocaleWeekdaysShort, localeWeekdaysShort,
<add> localeWeekdays,
<add> localeWeekdaysMin,
<add> localeWeekdaysShort,
<ide>
<del> defaultWeekdaysRegex, weekdaysRegex,
<del> defaultWeekdaysShortRegex, weekdaysShortRegex,
<del> defaultWeekdaysMinRegex, weekdaysMinRegex
<add> weekdaysRegex,
<add> weekdaysShortRegex,
<add> weekdaysMinRegex
<ide> } from '../units/day-of-week';
<ide>
<ide> proto.weekdays = localeWeekdays;
<del>proto._weekdays = defaultLocaleWeekdays;
<ide> proto.weekdaysMin = localeWeekdaysMin;
<del>proto._weekdaysMin = defaultLocaleWeekdaysMin;
<ide> proto.weekdaysShort = localeWeekdaysShort;
<del>proto._weekdaysShort = defaultLocaleWeekdaysShort;
<ide> proto.weekdaysParse = localeWeekdaysParse;
<ide>
<del>proto._weekdaysRegex = defaultWeekdaysRegex;
<ide> proto.weekdaysRegex = weekdaysRegex;
<del>proto._weekdaysShortRegex = defaultWeekdaysShortRegex;
<ide> proto.weekdaysShortRegex = weekdaysShortRegex;
<del>proto._weekdaysMinRegex = defaultWeekdaysMinRegex;
<ide> proto.weekdaysMinRegex = weekdaysMinRegex;
<ide>
<ide> // Hours
<del>import { localeIsPM, defaultLocaleMeridiemParse, localeMeridiem } from '../units/hour';
<add>import { localeIsPM, localeMeridiem } from '../units/hour';
<ide>
<ide> proto.isPM = localeIsPM;
<del>proto._meridiemParse = defaultLocaleMeridiemParse;
<ide> proto.meridiem = localeMeridiem;
<ide><path>src/lib/units/day-of-week.js
<ide> export function weekdaysShortRegex (isStrict) {
<ide> export var defaultWeekdaysMinRegex = matchWord;
<ide> export function weekdaysMinRegex (isStrict) {
<ide> if (this._weekdaysParseExact) {
<del> if (!hasOwnProp(this, '_weekdaysRegex')) {
<add> if (!hasOwnProp(this, '_weekdaysRegex') ||
<add> this._weekdaysRegex === defaultWeekdaysRegex) {
<ide> computeWeekdaysParse.call(this);
<ide> }
<ide> if (isStrict) {
<ide><path>src/lib/units/month.js
<ide> export function getDaysInMonth () {
<ide> return daysInMonth(this.year(), this.month());
<ide> }
<ide>
<add>export var defaultMonthsRegex = matchWord;
<ide> export var defaultMonthsShortRegex = matchWord;
<ide> export function monthsShortRegex (isStrict) {
<ide> if (this._monthsParseExact) {
<del> if (!hasOwnProp(this, '_monthsRegex')) {
<add> if (!hasOwnProp(this, '_monthsRegex') ||
<add> this._monthsRegex === defaultMonthsRegex) {
<ide> computeMonthsParse.call(this);
<ide> }
<ide> if (isStrict) {
<ide> export function monthsShortRegex (isStrict) {
<ide> }
<ide> }
<ide>
<del>export var defaultMonthsRegex = matchWord;
<ide> export function monthsRegex (isStrict) {
<ide> if (this._monthsParseExact) {
<del> if (!hasOwnProp(this, '_monthsRegex')) {
<add> if (!hasOwnProp(this, '_monthsRegex') ||
<add> this._monthsRegex === defaultMonthsRegex) {
<ide> computeMonthsParse.call(this);
<ide> }
<ide> if (isStrict) {
<ide><path>src/test/helpers/common-locale.js
<ide> export function defineCommonLocaleTests(locale, options) {
<ide> return;
<ide> }
<ide> function tester(format) {
<del> var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format;
<add> var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format + ' ' + m.toISOString();
<ide> r = moment(m.format(format), format);
<ide> assert.equal(r.weekday(), m.weekday(), baseMsg);
<ide> r = moment(m.format(format).toLocaleUpperCase(), format);
<ide> export function defineCommonLocaleTests(locale, options) {
<ide> }
<ide>
<ide> for (i = 0; i < 7; ++i) {
<del> m = moment.utc([2015, i, 15, 18]);
<add> m = moment.utc([2015, 0, i + 1, 18]);
<ide> tester('dd');
<ide> tester('ddd');
<ide> tester('dddd');
<ide><path>src/test/moment/locale_inheritance.js
<ide> test('ordinal parse', function (assert) {
<ide>
<ide> assert.ok(moment.utc('2015-01-1y', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child');
<ide>
<del> moment.defineLocale('base-ordinal-parse-2', {
<del> ordinalParse : /\d{1,2}x/
<del> });
<del> moment.defineLocale('child-ordinal-parse-2', {
<del> parentLocale: 'base-ordinal-parse-2',
<del> ordinalParse : null
<del> });
<del>
<del> assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)');
<add> // moment.defineLocale('base-ordinal-parse-2', {
<add> // ordinalParse : /\d{1,2}x/
<add> // });
<add> // moment.defineLocale('child-ordinal-parse-2', {
<add> // parentLocale: 'base-ordinal-parse-2',
<add> // ordinalParse : null
<add> // });
<add>
<add> // assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)');
<ide> });
<ide>
<ide> test('months', function (assert) {
<ide><path>src/test/moment/locale_update.js
<ide> test('ordinal parse', function (assert) {
<ide>
<ide> assert.ok(moment.utc('2015-01-1y', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child');
<ide>
<del> moment.defineLocale('ordinal-parse-2', null);
<del> moment.defineLocale('ordinal-parse-2', {
<del> ordinalParse : /\d{1,2}x/
<del> });
<del> moment.updateLocale('ordinal-parse-2', {
<del> ordinalParse : null
<del> });
<del>
<del> assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)');
<add> // moment.defineLocale('ordinal-parse-2', null);
<add> // moment.defineLocale('ordinal-parse-2', {
<add> // ordinalParse : /\d{1,2}x/
<add> // });
<add> // moment.updateLocale('ordinal-parse-2', {
<add> // ordinalParse : null
<add> // });
<add>
<add> // assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)');
<ide> });
<ide>
<ide> test('months', function (assert) { | 8 |
Javascript | Javascript | fix various oversights with initial 176 deploy | 32b09dcb339861b9a6a9208ec2aa292682366670 | <ide><path>packages/ember-debug/lib/deprecate.js
<ide> import Logger from 'ember-console';
<ide> import { ENV } from 'ember-environment';
<ide>
<ide> import { registerHandler as genericRegisterHandler, invoke } from './handlers';
<del>
<add>/**
<add> @module @ember/debug
<add> @public
<add>*/
<ide> /**
<ide> Allows for runtime registration of handler functions that override the default deprecation behavior.
<ide> Deprecations are invoked by calls to [Ember.deprecate](https://emberjs.com/api/classes/Ember.html#method_deprecate).
<ide> import { registerHandler as genericRegisterHandler, invoke } from './handlers';
<ide> <li> <code>next</code> - A function that calls into the previously registered handler.</li>
<ide> </ul>
<ide>
<del> @module @ember/debug
<ide> @public
<ide> @static
<ide> @method registerDeprecationHandler
<ide> if (DEBUG) {
<ide> '`options` should include `id` and `until` properties.';
<ide> missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.';
<ide> missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.';
<del>
<add> /**
<add> @module @ember/application
<add> @public
<add> */
<ide> /**
<ide> Display a deprecation warning with the provided message and a stack trace
<ide> (Chrome and Firefox only).
<ide>
<ide> * In a production build, this method is defined as an empty function (NOP).
<ide> Uses of this method in Ember itself are stripped from the ember.prod.js build.
<ide>
<del> @module @ember/application
<ide> @method deprecate
<ide> @for @ember/application/deprecations
<ide> @param {String} message A description of the deprecation.
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> let ClassMixinProps = {
<ide> see `reopenClass`
<ide>
<ide> @method reopen
<add> @for @ember/object
<add> @static
<ide> @public
<ide> */
<ide> reopen() {
<ide> let ClassMixinProps = {
<ide> see `reopen`
<ide>
<ide> @method reopenClass
<add> @for @ember/object
<add> @static
<ide> @public
<ide> */
<ide> reopenClass() {
<ide><path>packages/ember-runtime/lib/system/native_array.js
<ide> /**
<del>@module @ember/array
<add>@module ember
<ide> */
<ide> import Ember, { // Ember.A circular
<ide> replace,
<ide> import copy from '../copy';
<ide> false, this will be applied automatically. Otherwise you can apply the mixin
<ide> at anytime by calling `Ember.NativeArray.apply(Array.prototype)`.
<ide>
<del> @class EmberArray
<add> @class Ember.EmberArray
<ide> @uses MutableArray
<del> @uses @ember/object/observable
<add> @uses Observable
<ide> @uses Ember.Copyable
<ide> @public
<ide> */
<ide><path>packages/ember-runtime/lib/system/object.js
<ide> let OVERRIDE_OWNER = symbol('OVERRIDE_OWNER');
<ide>
<ide> @class EmberObject
<ide> @extends CoreObject
<del> @uses Ember.Observable
<add> @uses Observable
<ide> @public
<ide> */
<ide> const EmberObject = CoreObject.extend(Observable, {
<ide><path>packages/ember-utils/lib/assign.js
<ide> @param {Object} ...args The objects to copy properties from
<ide> @return {Object}
<ide> @public
<add> @static
<ide> */
<ide> export function assign(original) {
<ide> for (let i = 1; i < arguments.length; i++) { | 5 |
Javascript | Javascript | enable portable mode | d620da33f2dd57ef574c6c76535fa45f46569b23 | <ide><path>static/index.js
<ide> }
<ide> }
<ide>
<add> function isPortableMode() {
<add> // No portable mode on non-Windows
<add> if (process.platform !== 'win32') return false
<add>
<add> // DevMode? Nope
<add> var devMode = loadSettings &&
<add> (loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep))
<add>
<add> if (devMode) return false
<add>
<add> // Compare our EXE's path to where it would normally be in an installed app
<add> var ourPath = process.execPath.toLowerCase()
<add> return (ourPath.indexOf(process.env.LOCALAPPDATA.toLowerCase()) === 0)
<add> }
<add>
<ide> function setLoadTime (loadTime) {
<ide> if (global.atom) {
<ide> global.atom.loadTime = loadTime
<ide> try {
<ide> atomHome = fs.realpathSync(atomHome)
<ide> } catch (error) {
<del> // Ignore since the path might just not exist yet.
<add> // If we're in portable mode *and* the user doesn't already have a .atom
<add> // folder in the normal place, we'll use the portable folder instead
<add> if (isPortableMode()) {
<add> atomHome = path.join(path.dirname(process.execPath), '.atom')
<add> }
<ide> }
<ide> process.env.ATOM_HOME = atomHome
<ide> } | 1 |
PHP | PHP | remove a useless isset | 46c8180b8e248fe18d7a39063080f25fd8874fec | <ide><path>src/Illuminate/Bus/Dispatcher.php
<ide> public function dispatchToQueue($command)
<ide> */
<ide> protected function pushCommandToQueue($queue, $command)
<ide> {
<del> if (isset($command->queue) && isset($command->delay)) {
<add> if (isset($command->queue, $command->delay)) {
<ide> return $queue->laterOn($command->queue, $command->delay, $command);
<ide> }
<ide> | 1 |
Javascript | Javascript | replace var with let and const | 722fc72fc29a8f19c0225532f4a2024f8377367d | <ide><path>lib/_tls_common.js
<ide> exports.SecureContext = SecureContext;
<ide> exports.createSecureContext = function createSecureContext(options) {
<ide> if (!options) options = {};
<ide>
<del> var secureOptions = options.secureOptions;
<add> let secureOptions = options.secureOptions;
<ide> if (options.honorCipherOrder)
<ide> secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE;
<ide>
<ide> const c = new SecureContext(options.secureProtocol, secureOptions,
<ide> options.minVersion, options.maxVersion);
<del> var i;
<del> var val;
<add> let i;
<add> let val;
<ide>
<ide> // Add CA before the cert to be able to load cert's issuer in C++ code.
<ide> const { ca } = options;
<ide> exports.translatePeerCertificate = function translatePeerCertificate(c) {
<ide> }
<ide> if (c.subject != null) c.subject = parseCertString(c.subject);
<ide> if (c.infoAccess != null) {
<del> var info = c.infoAccess;
<add> const info = c.infoAccess;
<ide> c.infoAccess = Object.create(null);
<ide>
<ide> // XXX: More key validation? | 1 |
Python | Python | add tests for log2, exp2, and logaddexp | 13f253448bad23e1aa2fe5322899fc281ac06f12 | <ide><path>numpy/core/tests/test_umath.py
<ide> def test_power_complex(self):
<ide> assert_almost_equal(x**14, [-76443+16124j, 23161315+58317492j,
<ide> 5583548873 + 2465133864j])
<ide>
<add>class TestLog2(TestCase):
<add> def test_log2_values(self) :
<add> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<add> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<add> for dt in ['f','d','g'] :
<add> xf = np.array(x, dtype=dt)
<add> assert_almost_equal(np.log2(xf), y)
<add>
<add>class TestExp2(TestCase):
<add> def test_exp2_values(self) :
<add> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
<add> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<add> for dt in ['f','d','g'] :
<add> yf = np.array(y, dtype=dt)
<add> assert_almost_equal(np.exp2(yf), x)
<add>
<add>class TestLogAddExp(TestCase):
<add> def test_logaddexp_values(self) :
<add> x = [1, 2, 3, 4, 5]
<add> y = [5, 4, 3, 2, 1]
<add> z = [6, 6, 6, 6, 6]
<add> for dt in ['f','d','g'] :
<add> logxf = np.log(np.array(x, dtype=dt))
<add> logyf = np.log(np.array(y, dtype=dt))
<add> logzf = np.log(np.array(z, dtype=dt))
<add> assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
<add>
<add> def test_logaddexp_range(self) :
<add> x = [1000000, -1000000, 2000000, -2000000]
<add> y = [2000000, -2000000, 1000000, -1000000]
<add> z = [2000000, -1000000, 2000000, -1000000]
<add> for dt in ['f','d','g'] :
<add> logxf = np.array(x, dtype=dt)
<add> logyf = np.array(y, dtype=dt)
<add> logzf = np.array(z, dtype=dt))
<add> assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
<add>
<add>class TestLogAddExp(TestCase):
<add> def test_logaddexp(self) :
<add> x = [1, 2, 3, 4, 5]
<add> y = [5, 4, 3, 2, 1]
<add> z = [6, 6, 6, 6, 6]
<add> for dt in ['f','d','g'] :
<add> logxf = np.log2(np.array(x, dtype=dt))
<add> logyf = np.log2(np.array(y, dtype=dt))
<add> logzf = np.log2(np.array(z, dtype=dt))
<add> assert_almost_equal(np.logaddexp2(logxf, logyf), logzf)
<add>
<ide> class TestLog1p(TestCase):
<ide> def test_log1p(self):
<ide> assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) | 1 |
Java | Java | support non-public anno. attr. values in annoutils | b830d7362df24ed0953009b8172a7d67f7b73fe9 | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
<ide> import org.springframework.core.BridgeMethodResolver;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ObjectUtils;
<add>import org.springframework.util.ReflectionUtils;
<ide>
<ide> /**
<ide> * General utility methods for working with annotations, handling bridge methods (which the compiler
<ide> public static Object getValue(Annotation annotation) {
<ide> public static Object getValue(Annotation annotation, String attributeName) {
<ide> try {
<ide> Method method = annotation.annotationType().getDeclaredMethod(attributeName, new Class[0]);
<add> ReflectionUtils.makeAccessible(method);
<ide> return method.invoke(annotation);
<ide> }
<ide> catch (Exception ex) {
<ide> public static Object getDefaultValue(Class<? extends Annotation> annotationType,
<ide>
<ide> private static class AnnotationCollector<A extends Annotation> {
<ide>
<del>
<ide> private final Class<? extends Annotation> containerAnnotationType;
<ide>
<ide> private final Class<A> annotationType;
<ide> else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, annotation.ann
<ide> private A[] getValue(Annotation annotation) {
<ide> try {
<ide> Method method = annotation.annotationType().getDeclaredMethod("value");
<add> ReflectionUtils.makeAccessible(method);
<ide> return (A[]) method.invoke(annotation);
<ide> }
<ide> catch (Exception ex) {
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide>
<ide> import org.junit.Test;
<ide> import org.springframework.core.Ordered;
<add>import org.springframework.core.annotation.subpackage.NonPublicAnnotatedClass;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> import static org.hamcrest.Matchers.*;
<del>
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.core.annotation.AnnotationUtils.*;
<ide>
<ide> public class AnnotationUtilsTests {
<ide>
<ide> @Test
<del> public void testFindMethodAnnotationOnLeaf() throws SecurityException, NoSuchMethodException {
<add> public void findMethodAnnotationOnLeaf() throws Exception {
<ide> Method m = Leaf.class.getMethod("annotatedOnLeaf", (Class[]) null);
<ide> assertNotNull(m.getAnnotation(Order.class));
<ide> assertNotNull(getAnnotation(m, Order.class));
<ide> assertNotNull(findAnnotation(m, Order.class));
<ide> }
<ide>
<ide> @Test
<del> public void testFindMethodAnnotationOnRoot() throws SecurityException, NoSuchMethodException {
<add> public void findMethodAnnotationOnRoot() throws Exception {
<ide> Method m = Leaf.class.getMethod("annotatedOnRoot", (Class[]) null);
<ide> assertNotNull(m.getAnnotation(Order.class));
<ide> assertNotNull(getAnnotation(m, Order.class));
<ide> assertNotNull(findAnnotation(m, Order.class));
<ide> }
<ide>
<ide> @Test
<del> public void testFindMethodAnnotationOnRootButOverridden() throws SecurityException, NoSuchMethodException {
<add> public void findMethodAnnotationOnRootButOverridden() throws Exception {
<ide> Method m = Leaf.class.getMethod("overrideWithoutNewAnnotation", (Class[]) null);
<ide> assertNull(m.getAnnotation(Order.class));
<ide> assertNull(getAnnotation(m, Order.class));
<ide> assertNotNull(findAnnotation(m, Order.class));
<ide> }
<ide>
<ide> @Test
<del> public void testFindMethodAnnotationNotAnnotated() throws SecurityException, NoSuchMethodException {
<add> public void findMethodAnnotationNotAnnotated() throws Exception {
<ide> Method m = Leaf.class.getMethod("notAnnotated", (Class[]) null);
<ide> assertNull(findAnnotation(m, Order.class));
<ide> }
<ide>
<ide> @Test
<del> public void testFindMethodAnnotationOnBridgeMethod() throws Exception {
<add> public void findMethodAnnotationOnBridgeMethod() throws Exception {
<ide> Method m = SimpleFoo.class.getMethod("something", Object.class);
<ide> assertTrue(m.isBridge());
<ide> assertNull(m.getAnnotation(Order.class));
<ide> public void testFindMethodAnnotationOnBridgeMethod() throws Exception {
<ide> }
<ide>
<ide> // TODO consider whether we want this to handle annotations on interfaces
<del> // public void testFindMethodAnnotationFromInterfaceImplementedByRoot()
<add> // public void findMethodAnnotationFromInterfaceImplementedByRoot()
<ide> // throws Exception {
<ide> // Method m = Leaf.class.getMethod("fromInterfaceImplementedByRoot",
<ide> // (Class[]) null);
<ide> public void testIsAnnotationInherited() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void testGetValueFromAnnotation() throws Exception {
<add> public void getValueFromAnnotation() throws Exception {
<ide> Method method = SimpleFoo.class.getMethod("something", Object.class);
<ide> Order order = findAnnotation(method, Order.class);
<ide>
<ide> public void testGetValueFromAnnotation() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void testGetDefaultValueFromAnnotation() throws Exception {
<add> public void getValueFromNonPublicAnnotation() throws Exception {
<add> Annotation[] declaredAnnotations = NonPublicAnnotatedClass.class.getDeclaredAnnotations();
<add> assertEquals(1, declaredAnnotations.length);
<add> Annotation annotation = declaredAnnotations[0];
<add> assertNotNull(annotation);
<add> assertEquals("NonPublicAnnotation", annotation.annotationType().getSimpleName());
<add> assertEquals(42, AnnotationUtils.getValue(annotation, AnnotationUtils.VALUE));
<add> assertEquals(42, AnnotationUtils.getValue(annotation));
<add> }
<add>
<add> @Test
<add> public void getDefaultValueFromAnnotation() throws Exception {
<ide> Method method = SimpleFoo.class.getMethod("something", Object.class);
<ide> Order order = findAnnotation(method, Order.class);
<ide>
<ide> public void testGetDefaultValueFromAnnotation() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void testGetDefaultValueFromAnnotationType() throws Exception {
<add> public void getDefaultValueFromNonPublicAnnotation() throws Exception {
<add> Annotation[] declaredAnnotations = NonPublicAnnotatedClass.class.getDeclaredAnnotations();
<add> assertEquals(1, declaredAnnotations.length);
<add> Annotation annotation = declaredAnnotations[0];
<add> assertNotNull(annotation);
<add> assertEquals("NonPublicAnnotation", annotation.annotationType().getSimpleName());
<add> assertEquals(-1, AnnotationUtils.getDefaultValue(annotation, AnnotationUtils.VALUE));
<add> assertEquals(-1, AnnotationUtils.getDefaultValue(annotation));
<add> }
<add>
<add> @Test
<add> public void getDefaultValueFromAnnotationType() throws Exception {
<ide> assertEquals(Ordered.LOWEST_PRECEDENCE, AnnotationUtils.getDefaultValue(Order.class, AnnotationUtils.VALUE));
<ide> assertEquals(Ordered.LOWEST_PRECEDENCE, AnnotationUtils.getDefaultValue(Order.class));
<ide> }
<ide>
<ide> @Test
<del> public void testFindAnnotationFromInterface() throws Exception {
<add> public void findAnnotationFromInterface() throws Exception {
<ide> Method method = ImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo");
<ide> Order order = findAnnotation(method, Order.class);
<ide> assertNotNull(order);
<ide> }
<ide>
<ide> @Test
<del> public void testFindAnnotationFromInterfaceOnSuper() throws Exception {
<add> public void findAnnotationFromInterfaceOnSuper() throws Exception {
<ide> Method method = SubOfImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo");
<ide> Order order = findAnnotation(method, Order.class);
<ide> assertNotNull(order);
<ide> }
<ide>
<ide> @Test
<del> public void testFindAnnotationFromInterfaceWhenSuperDoesNotImplementMethod() throws Exception {
<add> public void findAnnotationFromInterfaceWhenSuperDoesNotImplementMethod()
<add> throws Exception {
<ide> Method method = SubOfAbstractImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo");
<ide> Order order = findAnnotation(method, Order.class);
<ide> assertNotNull(order);
<ide> }
<ide>
<ide> @Test
<del> public void testGetRepeatableFromMethod() throws Exception {
<add> public void getRepeatableFromMethod() throws Exception {
<ide> Method method = InterfaceWithRepeated.class.getMethod("foo");
<ide> Set<MyRepeatable> annotions = AnnotationUtils.getRepeatableAnnotation(method,
<ide> MyRepeatableContainer.class, MyRepeatable.class);
<ide> static interface InterfaceWithMetaAnnotation {
<ide> static class ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface implements InterfaceWithMetaAnnotation {
<ide> }
<ide>
<add>
<ide> public static interface AnnotatedInterface {
<ide>
<ide> @Order(0)
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/subpackage/NonPublicAnnotatedClass.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.annotation.subpackage;
<add>
<add>/**
<add> * Class annotated with a non-public (i.e., package private) custom annotation.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.0
<add> */
<add>@NonPublicAnnotation(42)
<add>public class NonPublicAnnotatedClass {
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/subpackage/NonPublicAnnotation.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.annotation.subpackage;
<add>
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>
<add>/**
<add> * Non-public (i.e., package private) custom annotation.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.0
<add> */
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@interface NonPublicAnnotation {
<add>
<add> int value() default -1;
<add>} | 4 |
Javascript | Javascript | introduce queuemicrotask api | be189cd81905a735f08a8519c62a707658c7fb27 | <ide><path>Libraries/Core/Timers/queueMicrotask.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>let resolvedPromise;
<add>
<add>/**
<add> * Polyfill for the microtask queuening API defined by WHATWG HTMP spec.
<add> * https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
<add> *
<add> * The method must queue a microtask to invoke @param {function} callback, and
<add> * if the callback throws an exception, report the exception.
<add> */
<add>export default function queueMicrotask(callback: Function) {
<add> if (arguments.length < 1) {
<add> throw new TypeError(
<add> 'queueMicrotask must be called with at least one argument (a function to call)',
<add> );
<add> }
<add> if (typeof callback !== 'function') {
<add> throw new TypeError('The argument to queueMicrotask must be a function.');
<add> }
<add>
<add> // Try to reuse a lazily allocated resolved promise from closure.
<add> (resolvedPromise || (resolvedPromise = Promise.resolve()))
<add> .then(callback)
<add> .catch(error =>
<add> // Report the exception until the next tick.
<add> setTimeout(() => {
<add> throw error;
<add> }, 0),
<add> );
<add>}
<ide><path>Libraries/Core/setUpTimers.js
<ide>
<ide> 'use strict';
<ide>
<add>const {polyfillGlobal} = require('../Utilities/PolyfillFunctions');
<add>
<add>if (__DEV__) {
<add> if (typeof global.Promise !== 'function') {
<add> console.error('Promise should exist before setting up timers.');
<add> }
<add>}
<add>
<add>// Currently, Hermes `Promise` is implemented via Internal Bytecode.
<add>const hasHermesPromiseQueuedToJSVM =
<add> global?.HermesInternal?.hasPromise?.() &&
<add> global?.HermesInternal?.useEngineQueue?.();
<add>
<ide> // In bridgeless mode, timers are host functions installed from cpp.
<ide> if (!global.RN$Bridgeless) {
<del> const {polyfillGlobal} = require('../Utilities/PolyfillFunctions');
<del>
<ide> /**
<ide> * Set up timers.
<ide> * You can use this module directly, or just require InitializeCore.
<ide> if (!global.RN$Bridgeless) {
<ide> () => require('./Timers/JSTimers').clearReactNativeMicrotask,
<ide> );
<ide> }
<add>
<add>/**
<add> * Set up the microtask queueing API, which is required to use the same
<add> * microtask queue as the Promise.
<add> */
<add>if (hasHermesPromiseQueuedToJSVM) {
<add> // Fast path for Hermes.
<add> polyfillGlobal('queueMicrotask', () => global.HermesInternal.enqueueJob);
<add>} else {
<add> // Polyfill it with promise (regardless it's polyfiled or native) otherwise.
<add> polyfillGlobal(
<add> 'queueMicrotask',
<add> () => require('./Timers/queueMicrotask.js').default,
<add> );
<add>} | 2 |
Go | Go | treat systemd listeners as all other | 6f9fa64645cd67eb10a9c8bd903df518d572f50d | <ide><path>api/server/server.go
<ide> func (s *Server) ServeApi(protoAddrs []string) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> s.servers = append(s.servers, srv)
<add> s.servers = append(s.servers, srv...)
<ide>
<del> go func(proto, addr string) {
<del> logrus.Infof("Listening for HTTP on %s (%s)", proto, addr)
<del> if err := srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
<del> err = nil
<del> }
<del> chErrors <- err
<del> }(protoAddrParts[0], protoAddrParts[1])
<add> for _, s := range srv {
<add> logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
<add> go func(s serverCloser) {
<add> if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
<add> err = nil
<add> }
<add> chErrors <- err
<add> }(s)
<add> }
<ide> }
<ide>
<ide> for i := 0; i < len(protoAddrs); i++ {
<ide><path>api/server/server_linux.go
<ide> import (
<ide> "github.com/docker/docker/pkg/systemd"
<ide> )
<ide>
<del>// newServer sets up the required serverCloser and does protocol specific checking.
<del>func (s *Server) newServer(proto, addr string) (serverCloser, error) {
<add>// newServer sets up the required serverClosers and does protocol specific checking.
<add>func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
<ide> var (
<ide> err error
<del> l net.Listener
<add> ls []net.Listener
<ide> )
<ide> switch proto {
<ide> case "fd":
<del> ls, err := systemd.ListenFD(addr)
<add> ls, err = systemd.ListenFD(addr)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> chErrors := make(chan error, len(ls))
<ide> // We don't want to start serving on these sockets until the
<ide> // daemon is initialized and installed. Otherwise required handlers
<ide> // won't be ready.
<ide> <-s.start
<del> // Since ListenFD will return one or more sockets we have
<del> // to create a go func to spawn off multiple serves
<del> for i := range ls {
<del> listener := ls[i]
<del> go func() {
<del> httpSrv := http.Server{Handler: s.router}
<del> chErrors <- httpSrv.Serve(listener)
<del> }()
<del> }
<del> for i := 0; i < len(ls); i++ {
<del> if err := <-chErrors; err != nil {
<del> return nil, err
<del> }
<del> }
<del> return nil, nil
<ide> case "tcp":
<del> l, err = s.initTcpSocket(addr)
<add> l, err := s.initTcpSocket(addr)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> ls = append(ls, l)
<ide> case "unix":
<del> if l, err = sockets.NewUnixSocket(addr, s.cfg.SocketGroup, s.start); err != nil {
<add> l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup, s.start)
<add> if err != nil {
<ide> return nil, err
<ide> }
<add> ls = append(ls, l)
<ide> default:
<ide> return nil, fmt.Errorf("Invalid protocol format: %q", proto)
<ide> }
<del> return &HttpServer{
<del> &http.Server{
<del> Addr: addr,
<del> Handler: s.router,
<del> },
<del> l,
<del> }, nil
<add> var res []serverCloser
<add> for _, l := range ls {
<add> res = append(res, &HttpServer{
<add> &http.Server{
<add> Addr: addr,
<add> Handler: s.router,
<add> },
<add> l,
<add> })
<add> }
<add> return res, nil
<ide> }
<ide>
<ide> func (s *Server) AcceptConnections(d *daemon.Daemon) { | 2 |
Text | Text | remove invalid hash in link | ebc58d7a220011c6f067f12918adb583f2192859 | <ide><path>doc/api/net.md
<ide> If `allowHalfOpen` is set to `true`, when the other end of the socket
<ide> sends a FIN packet, the server will only send a FIN packet back when
<ide> [`socket.end()`][] is explicitly called, until then the connection is
<ide> half-closed (non-readable but still writable). See [`'end'`][] event
<del>and [RFC 1122][half-closed] for more information.
<add>and [RFC 1122][half-closed] (section 4.2.2.13) for more information.
<ide>
<ide> If `pauseOnConnect` is set to `true`, then the socket associated with each
<ide> incoming connection will be paused, and no data will be read from its handle.
<ide> Returns true if input is a version 6 IP address, otherwise returns false.
<ide> [Identifying paths for IPC connections]: #net_identifying_paths_for_ipc_connections
<ide> [Readable Stream]: stream.html#stream_class_stream_readable
<ide> [duplex stream]: stream.html#stream_class_stream_duplex
<del>[half-closed]: https://tools.ietf.org/html/rfc1122#section-4.2.2.13
<add>[half-closed]: https://tools.ietf.org/html/rfc1122
<ide> [socket(7)]: http://man7.org/linux/man-pages/man7/socket.7.html
<ide> [unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0
<ide> [unspecified IPv6 address]: https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address | 1 |
Python | Python | use simplejson if available | 72d1fec69a587ac23f27534fbbbc350021a6d179 | <ide><path>libcloud/dns/drivers/pointdns.py
<ide> 'PointDNSDriver'
<ide> ]
<ide>
<del>import json
<add>try:
<add> import simplejson as json
<add>except ImportError:
<add> import json
<ide>
<ide> from libcloud.common.types import MalformedResponseError
<ide> from libcloud.common.pointdns import PointDNSConnection
<ide><path>libcloud/dns/drivers/worldwidedns.py
<ide> __all__ = [
<ide> 'WorldWideDNSDriver'
<ide> ]
<add>
<ide> import re
<ide>
<ide> from libcloud.common.types import LibcloudError | 2 |
PHP | PHP | use newentity() to create session | ccec0ce00d11cbc9f4c0d4feabd95e313584a2af | <ide><path>src/Http/Session/DatabaseSession.php
<ide> */
<ide> namespace Cake\Http\Session;
<ide>
<del>use Cake\ORM\Entity;
<ide> use Cake\ORM\Locator\LocatorAwareTrait;
<ide> use SessionHandlerInterface;
<ide>
<ide> public function write($id, $data): bool
<ide> if (!$id) {
<ide> return false;
<ide> }
<del> $expires = time() + $this->_timeout;
<del> $record = compact('data', 'expires');
<add>
<ide> /** @var string $pkField */
<ide> $pkField = $this->_table->getPrimaryKey();
<del> $record[$pkField] = $id;
<del> $result = $this->_table->save(new Entity($record));
<add> $session = $this->_table->newEntity([
<add> $pkField => $id,
<add> 'data' => $data,
<add> 'expires' => time() + $this->_timeout,
<add> ], ['accessibleFields' => ['id' => true]]);
<ide>
<del> return (bool)$result;
<add> return (bool)$this->_table->save($session);
<ide> }
<ide>
<ide> /**
<ide> public function destroy($id): bool
<ide> {
<ide> /** @var string $pkField */
<ide> $pkField = $this->_table->getPrimaryKey();
<del> $this->_table->delete(new Entity(
<del> [$pkField => $id],
<del> ['markNew' => false]
<del> ));
<add> $this->_table->deleteAll([$pkField => $id]);
<ide>
<ide> return true;
<ide> }
<ide><path>tests/TestCase/Http/Session/DatabaseSessionTest.php
<ide> public function testRead()
<ide> */
<ide> public function testDestroy()
<ide> {
<del> $this->storage->write('foo', 'Some value');
<add> $this->assertTrue($this->storage->write('foo', 'Some value'));
<ide>
<ide> $this->assertTrue($this->storage->destroy('foo'), 'Destroy failed');
<ide> $this->assertSame('', $this->storage->read('foo'), 'Value still present.');
<ide><path>tests/test_app/TestApp/Model/Entity/Session.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>namespace TestApp\Model\Entity;
<add>
<add>use Cake\ORM\Entity;
<add>
<add>/**
<add> * Marks id as protected
<add> */
<add>class Session extends Entity
<add>{
<add> protected $_accessible = [
<add> 'id' => false,
<add> '*' => true,
<add> ];
<add>}
<ide><path>tests/test_app/TestApp/Model/Table/SessionsTable.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>namespace TestApp\Model\Table;
<add>
<add>use Cake\ORM\Table;
<add>
<add>class SessionsTable extends Table
<add>{
<add>} | 4 |
Javascript | Javascript | remove redandant second argument to `parsefloat()` | 56b9b209ca692c43bc81bacf7e98de5845bed2ee | <ide><path>src/ng/directive/input.js
<ide> function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide>
<ide> attr.$observe('min', function(val) {
<ide> if (isDefined(val) && !isNumber(val)) {
<del> val = parseFloat(val, 10);
<add> val = parseFloat(val);
<ide> }
<ide> minVal = isNumber(val) && !isNaN(val) ? val : undefined;
<ide> // TODO(matsko): implement validateLater to reduce number of validations
<ide> function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide>
<ide> attr.$observe('max', function(val) {
<ide> if (isDefined(val) && !isNumber(val)) {
<del> val = parseFloat(val, 10);
<add> val = parseFloat(val);
<ide> }
<ide> maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
<ide> // TODO(matsko): implement validateLater to reduce number of validations | 1 |
Python | Python | kafka key name needs to be bytes | 62dbeb369efe8bb6c09b719835463ba71d2cec09 | <ide><path>glances/exports/glances_kafka.py
<ide>
<ide> from kafka import KafkaProducer
<ide> import json
<add>import codecs
<ide>
<ide>
<ide> class Export(GlancesExport):
<ide> def export(self, name, columns, points):
<ide> # value=JSON dict
<ide> try:
<ide> self.client.send(self.topic,
<del> key=name,
<add> # Kafka key name needs to be bytes #1593
<add> key=name.encode('utf-8'),
<ide> value=data)
<ide> except Exception as e:
<ide> logger.error("Cannot export {} stats to Kafka ({})".format(name, e)) | 1 |
Ruby | Ruby | remove anemic indirection | 1029c49c32cf3b8c7a013753783ab37f364ad65d | <ide><path>lib/action_cable/connection/base.rb
<ide> def transmit(data)
<ide> @websocket.send data
<ide> end
<ide>
<del>
<del> def handle_exception
<del> close
<del> end
<del>
<ide> def close
<ide> logger.error "Closing connection"
<ide> @websocket.close
<ide><path>lib/action_cable/connection/internal_channel.rb
<ide> def process_internal_message(message)
<ide> logger.error "There was an exception - #{e.class}(#{e.message})"
<ide> logger.error e.backtrace.join("\n")
<ide>
<del> handle_exception
<add> close
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | fix partial path being set for non existent paths | a4d96ec74d3745669e0860db42b7070557186769 | <ide><path>src/Filesystem/File.php
<ide> public function md5($maxsize = 5)
<ide> public function pwd()
<ide> {
<ide> if ($this->path === null) {
<del> $this->path = $this->Folder->slashTerm($this->Folder->pwd()) . $this->name;
<add> $dir = $this->Folder->pwd();
<add> if (is_dir($dir)) {
<add> $this->path = $this->Folder->slashTerm($dir) . $this->name;
<add> }
<ide> }
<ide> return $this->path;
<ide> }
<ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> public function testReplaceText()
<ide>
<ide> $TmpFile->delete();
<ide> }
<add>
<add> /**
<add> * Tests that no path is being set for passed file paths that
<add> * do not exist.
<add> *
<add> * @return void
<add> */
<add> public function testNoPartialPathBeingSetForNonExistentPath()
<add> {
<add> $TmpFile = new File('/non/existent/file');
<add> $this->assertNull($TmpFile->pwd());
<add> $this->assertNull($TmpFile->path);
<add> }
<ide> } | 2 |
Javascript | Javascript | clarify examples of route parameters | fe84f7bef8b7c63158cf1699f3a62793b555fce8 | <ide><path>src/ngRoute/route.js
<ide> function $RouteProvider(){
<ide> * `$location.path` will be updated to add or drop the trailing slash to exactly match the
<ide> * route definition.
<ide> *
<del> * * `path` can contain named groups starting with a colon (`:name`). All characters up
<add> * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
<ide> * to the next slash are matched and stored in `$routeParams` under the given `name`
<ide> * when the route matches.
<del> * * `path` can contain named groups starting with a colon and ending with a star (`:name*`).
<add> * * `path` can contain named groups starting with a colon and ending with a star: e.g.`:name*`.
<ide> * All characters are eagerly stored in `$routeParams` under the given `name`
<ide> * when the route matches.
<del> * * `path` can contain optional named groups with a question mark (`:name?`).
<add> * * `path` can contain optional named groups with a question mark: e.g.`:name?`.
<ide> *
<ide> * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
<ide> * `/color/brown/largecode/code/with/slashs/edit` and extract: | 1 |
Text | Text | use single quotes in --tls-cipher-list | cf32b4c74d84774e5465f6307acbbdb85846a634 | <ide><path>doc/api/tls.md
<ide> instance, the following makes `ECDHE-RSA-AES128-GCM-SHA256:!RC4` the default TLS
<ide> cipher suite:
<ide>
<ide> ```bash
<del>node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4" server.js
<add>node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js
<ide>
<del>export NODE_OPTIONS=--tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"
<add>export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
<ide> node server.js
<ide> ```
<ide> | 1 |
Python | Python | reimplement function with_metaclass() | c8f19f0afc8d49a68ec969097e6127d17706b6dc | <ide><path>flask/_compat.py
<ide> def implements_to_string(cls):
<ide> def with_metaclass(meta, *bases):
<ide> # This requires a bit of explanation: the basic idea is to make a
<ide> # dummy metaclass for one level of class instantiation that replaces
<del> # itself with the actual metaclass. Because of internal type checks
<del> # we also need to make sure that we downgrade the custom metaclass
<del> # for one level to something closer to type (that's why __call__ and
<del> # __init__ comes back from type etc.).
<add> # itself with the actual metaclass.
<ide> #
<ide> # This has the advantage over six.with_metaclass in that it does not
<ide> # introduce dummy classes into the final MRO.
<del> class metaclass(meta):
<del> __call__ = type.__call__
<del> __init__ = type.__init__
<del> def __new__(cls, name, this_bases, d):
<del> if this_bases is None:
<del> return type.__new__(cls, name, (), d)
<del> return meta(name, bases, d)
<del> return metaclass('temporary_class', None, {})
<add> constructor = lambda c, name, b, dct: meta(name, bases, dct)
<add> metaclass = type('with_metaclass', (type,), {'__new__': constructor})
<add> return type.__new__(metaclass, 'temporary_class', (object,), {})
<ide>
<ide>
<ide> # Certain versions of pypy have a bug where clearing the exception stack | 1 |
Python | Python | add exception when trying to reuse regularizers | 2a319c72552381a98c7a11b339c623cb999164b6 | <ide><path>keras/regularizers.py
<ide>
<ide> class Regularizer(object):
<ide> def set_param(self, p):
<add> if hasattr(self, 'p'):
<add> raise Exception('Regularizers cannot be reused')
<ide> self.p = p
<ide>
<ide> def set_layer(self, layer):
<add> if hasattr(self, 'layer'):
<add> raise Exception('Regularizers cannot be reused')
<ide> self.layer = layer
<ide>
<ide> def __call__(self, loss):
<ide> def __init__(self, k):
<ide> self.uses_learning_phase = True
<ide>
<ide> def set_param(self, p):
<add> if hasattr(self, 'p'):
<add> raise Exception('Regularizers cannot be reused')
<ide> self.p = p
<ide>
<ide> def __call__(self, loss):
<ide> def __init__(self, l1=0., l2=0.):
<ide> self.uses_learning_phase = True
<ide>
<ide> def set_param(self, p):
<add> if hasattr(self, 'p'):
<add> raise Exception('Regularizers cannot be reused')
<ide> self.p = p
<ide>
<ide> def __call__(self, loss):
<ide> def __init__(self, l1=0., l2=0.):
<ide> self.uses_learning_phase = True
<ide>
<ide> def set_layer(self, layer):
<add> if hasattr(self, 'layer'):
<add> raise Exception('Regularizers cannot be reused')
<ide> self.layer = layer
<ide>
<ide> def __call__(self, loss): | 1 |
Javascript | Javascript | move module.hash and .renderedhash into chunkgraph | 3aa22804985c8174d0dc1a7ba4a707dd787fa8ea | <ide><path>lib/BannerPlugin.js
<ide>
<ide> "use strict";
<ide>
<add>const validateOptions = require("schema-utils");
<ide> const { ConcatSource } = require("webpack-sources");
<ide> const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
<ide> const Template = require("./Template");
<ide>
<del>const validateOptions = require("schema-utils");
<ide> const schema = require("../schemas/plugins/BannerPlugin.json");
<ide>
<add>/** @typedef {import("./Compiler")} Compiler */
<add>
<ide> const wrapComment = str => {
<ide> if (!str.includes("\n")) {
<ide> return Template.toComment(str);
<ide> class BannerPlugin {
<ide> }
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler webpack compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> const options = this.options;
<ide> const banner = this.banner;
<ide><path>lib/Chunk.js
<ide> class Chunk {
<ide> this.rendered = false;
<ide> /** @type {string=} */
<ide> this.hash = undefined;
<del> /** @type {Object} */
<add> /** @type {Record<string, string>} */
<ide> this.contentHash = Object.create(null);
<ide> /** @type {string=} */
<ide> this.renderedHash = undefined;
<ide> class Chunk {
<ide> this,
<ide> compareModulesById(compilation.moduleGraph)
<ide> )) {
<del> hash.update(m.hash);
<add> hash.update(compilation.chunkGraph.getModuleHash(m));
<ide> }
<ide> const entryModules = compilation.chunkGraph.getChunkEntryModulesWithChunkGroupIterable(
<ide> this
<ide> );
<ide> for (const [m, chunkGroup] of entryModules) {
<ide> hash.update("entry");
<del> hash.update(m.hash);
<add> hash.update(compilation.chunkGraph.getModuleHash(m));
<ide> hash.update(chunkGroup.id);
<ide> }
<ide> }
<ide><path>lib/ChunkGraph.js
<ide> class ChunkGraphModule {
<ide> this.chunks = new SortableSet();
<ide> /** @type {Set<Chunk>} */
<ide> this.entryInChunks = new Set();
<add> /** @type {string} */
<add> this.hash = undefined;
<add> /** @type {string} */
<add> this.renderedHash = undefined;
<ide> }
<ide> }
<ide>
<ide> class ChunkGraph {
<ide> chunkModuleIdMap[asyncChunk.id] = array;
<ide> }
<ide> array.push(module.id);
<del> chunkModuleHashMap[module.id] = module.renderedHash;
<add> chunkModuleHashMap[module.id] = this.getRenderedModuleHash(module);
<ide> }
<ide> }
<ide> if (array !== undefined) {
<ide> class ChunkGraph {
<ide> return cgc.entryModules;
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {string} hash
<add> */
<add> getModuleHash(module) {
<add> const cgm = this._getChunkGraphModule(module);
<add> return cgm.hash;
<add> }
<add>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {string} hash
<add> */
<add> getRenderedModuleHash(module) {
<add> const cgm = this._getChunkGraphModule(module);
<add> return cgm.renderedHash;
<add> }
<add>
<add> /**
<add> * @param {Module} module the module
<add> * @param {string} hash the full hash
<add> * @param {string} renderedHash the shortened hash for rendering
<add> * @returns {void}
<add> */
<add> setModuleHashes(module, hash, renderedHash) {
<add> const cgm = this._getChunkGraphModule(module);
<add> cgm.hash = hash;
<add> cgm.renderedHash = renderedHash;
<add> }
<add>
<ide> // TODO remove in webpack 6
<ide> /**
<ide> * @param {Module} module the module
<ide><path>lib/Compilation.js
<ide> const createHash = require("./util/createHash");
<ide> * @property {AsyncDependenciesBlock[]} blocks
<ide> */
<ide>
<add>/**
<add> * @typedef {Object} ChunkPathData
<add> * @property {string|number} id
<add> * @property {string=} name
<add> * @property {string} hash
<add> * @property {string} renderedHash
<add> * @property {function(number): string=} hashWithLength
<add> * @property {(Record<string, string>)=} contentHash
<add> * @property {(Record<string, (length: number) => string>)=} contentHashWithLength
<add> */
<add>
<add>/**
<add> * @typedef {Object} ModulePathData
<add> * @property {string|number} id
<add> * @property {string} hash
<add> * @property {string} renderedHash
<add> * @property {function(number): string=} hashWithLength
<add> */
<add>
<add>/**
<add> * @typedef {Object} PathData
<add> * @property {ChunkGraph=} chunkGraph
<add> * @property {string=} hash
<add> * @property {function(number): string=} hashWithLength
<add> * @property {(Chunk|ChunkPathData)=} chunk
<add> * @property {(Module|ModulePathData)=} module
<add> * @property {string=} filename
<add> * @property {string=} basename
<add> * @property {string=} query
<add> * @property {string=} contentHashType
<add> * @property {string=} contentHash
<add> * @property {function(number): string=} contentHashWithLength
<add> * @property {boolean=} noChunkHash
<add> */
<add>
<ide> /**
<ide> * @param {Chunk} a first chunk to sort by id
<ide> * @param {Chunk} b second chunk to sort by id
<ide> class Compilation {
<ide> }
<ide>
<ide> createHash() {
<add> const chunkGraph = this.chunkGraph;
<ide> const outputOptions = this.outputOptions;
<ide> const hashFunction = outputOptions.hashFunction;
<ide> const hashDigest = outputOptions.hashDigest;
<ide> class Compilation {
<ide> const module = modules[i];
<ide> const moduleHash = createHash(hashFunction);
<ide> module.updateHash(moduleHash, this);
<del> module.hash = moduleHash.digest(hashDigest);
<del> module.renderedHash = module.hash.substr(0, hashDigestLength);
<add> const moduleHashDigest = moduleHash.digest(hashDigest);
<add> chunkGraph.setModuleHashes(
<add> module,
<add> moduleHashDigest,
<add> moduleHashDigest.substr(0, hashDigestLength)
<add> );
<ide> }
<ide> // clone needed as sort below is inplace mutation
<ide> const chunks = this.chunks.slice();
<ide> class Compilation {
<ide> const module = this.modules[i];
<ide> if (module.buildInfo.assets) {
<ide> for (const assetName of Object.keys(module.buildInfo.assets)) {
<del> const fileName = this.getPath(assetName);
<add> const fileName = this.getPath(assetName, {
<add> chunkGraph: this.chunkGraph,
<add> module
<add> });
<ide> this.assets[fileName] = module.buildInfo.assets[assetName];
<ide> this.hooks.moduleAsset.call(module, fileName);
<ide> }
<ide> class Compilation {
<ide>
<ide> /**
<ide> * @param {string} filename used to get asset path with hash
<del> * @param {TODO=} data // TODO: figure out this param type
<add> * @param {PathData} data context data
<ide> * @returns {string} interpolated path
<ide> */
<ide> getPath(filename, data) {
<del> data = data || {};
<ide> data.hash = data.hash || this.hash;
<ide> return this.mainTemplate.getAssetPath(filename, data);
<ide> }
<ide><path>lib/Compiler.js
<ide> class Compiler {
<ide>
<ide> this.hooks.emit.callAsync(compilation, err => {
<ide> if (err) return callback(err);
<del> outputPath = compilation.getPath(this.outputPath);
<add> outputPath = compilation.getPath(this.outputPath, {});
<ide> this.outputFileSystem.mkdirp(outputPath, emitFiles);
<ide> });
<ide> }
<ide><path>lib/HotModuleReplacementPlugin.js
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> records.moduleHashs = {};
<ide> for (const module of compilation.modules) {
<ide> const identifier = module.identifier();
<del> records.moduleHashs[identifier] = module.hash;
<add> records.moduleHashs[identifier] = chunkGraph.getModuleHash(
<add> module
<add> );
<ide> }
<ide> records.chunkHashs = {};
<ide> for (const chunk of compilation.chunks) {
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> const updatedModules = new Set();
<ide> for (const module of compilation.modules) {
<ide> const identifier = module.identifier();
<del> const hash = module.hash;
<add> const hash = chunkGraph.getModuleHash(module);
<ide> if (records.moduleHashs[identifier] !== hash) {
<ide> updatedModules.add(module);
<ide> }
<ide><path>lib/JavascriptModulesPlugin.js
<ide> class JavascriptModulesPlugin {
<ide> compareModulesById(moduleGraph)
<ide> )) {
<ide> if (typeof m.source === "function") {
<del> hash.update(m.hash);
<add> hash.update(chunkGraph.getModuleHash(m));
<ide> }
<ide> }
<ide> chunk.contentHash.javascript = hash
<ide><path>lib/LibManifestPlugin.js
<ide> const path = require("path");
<ide> const EntryDependency = require("./dependencies/EntryDependency");
<ide> const { compareModulesById } = require("./util/comparators");
<ide>
<add>/** @typedef {import("./Compiler")} Compiler */
<add>
<ide> class LibManifestPlugin {
<ide> constructor(options) {
<ide> this.options = options;
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler webpack compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> compiler.hooks.emit.tapAsync(
<ide> "LibManifestPlugin",
<ide><path>lib/Module.js
<ide> class Module extends DependenciesBlock {
<ide> /** @type {number} */
<ide> this.debugId = debugId++;
<ide>
<del> // Hash
<del> /** @type {string} */
<del> this.hash = undefined;
<del> /** @type {string} */
<del> this.renderedHash = undefined;
<del>
<ide> // Info from Factory
<ide> /** @type {TODO} */
<ide> this.resolveOptions = EMPTY_RESOLVE_OPTIONS;
<ide> class Module extends DependenciesBlock {
<ide>
<ide> // TODO remove in webpack 6
<ide> // BACKWARD-COMPAT START
<add> /**
<add> * @returns {string} the hash of the module
<add> */
<add> get hash() {
<add> return ChunkGraph.getChunkGraphForModule(this, "Module.hash").getModuleHash(
<add> this
<add> );
<add> }
<add>
<add> /**
<add> * @returns {string} the shortened hash of the module
<add> */
<add> get renderedHash() {
<add> return ChunkGraph.getChunkGraphForModule(
<add> this,
<add> "Module.renderedHash"
<add> ).getRenderedModuleHash(this);
<add> }
<add>
<ide> get profile() {
<ide> return ModuleGraph.getModuleGraphForModule(
<ide> this,
<ide> class Module extends DependenciesBlock {
<ide> * @returns {void}
<ide> */
<ide> disconnect() {
<del> this.hash = undefined;
<del> this.renderedHash = undefined;
<del>
<ide> this.id = null;
<ide>
<ide> super.disconnect();
<ide><path>lib/NormalModule.js
<ide> const createHash = require("./util/createHash");
<ide> const contextify = require("./util/identifier").contextify;
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<add>/** @typedef {import("./ChunkGraph")} ChunkGraph */
<ide> /** @typedef {import("./Compilation")} Compilation */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
<ide> class NormalModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {ChunkGraph} chunkGraph the chunk graph
<ide> * @param {DependencyTemplates} dependencyTemplates dependency templates
<ide> * @returns {string} hash
<ide> */
<del> getHashDigest(dependencyTemplates) {
<del> // TODO webpack 5 refactor
<del> let dtHash = dependencyTemplates.getHash();
<del> return `${this.hash}-${dtHash}`;
<add> getHashDigest(chunkGraph, dependencyTemplates) {
<add> const hash = chunkGraph.getModuleHash(this);
<add> const dtHash = dependencyTemplates.getHash();
<add> return `${hash}-${dtHash}`;
<ide> }
<ide>
<ide> /**
<ide> class NormalModule extends Module {
<ide> dependencyTemplates,
<ide> runtimeTemplate,
<ide> moduleGraph,
<add> chunkGraph,
<ide> type = "javascript"
<ide> }) {
<del> const hashDigest = this.getHashDigest(dependencyTemplates);
<add> const hashDigest = this.getHashDigest(chunkGraph, dependencyTemplates);
<ide> const cacheEntry = this._cachedSources.get(type);
<ide> if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) {
<ide> // We can reuse the cached source
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> "use strict";
<ide>
<ide> const path = require("path");
<add>const validateOptions = require("schema-utils");
<ide> const { ConcatSource, RawSource } = require("webpack-sources");
<ide> const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
<ide> const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
<ide> const createHash = require("./util/createHash");
<ide>
<del>const validateOptions = require("schema-utils");
<ide> const schema = require("../schemas/plugins/SourceMapDevToolPlugin.json");
<ide>
<add>/** @typedef {import("./Chunk")} Chunk */
<add>/** @typedef {import("./Compiler")} Compiler */
<add>
<ide> const assetsCache = new WeakMap();
<ide>
<ide> const getTaskForFile = (file, chunk, options, compilation) => {
<ide> class SourceMapDevToolPlugin {
<ide> this.options = options;
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler webpack compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> const sourceMapFilename = this.sourceMapFilename;
<ide> const sourceMappingURLComment = this.sourceMappingURLComment;
<ide> class SourceMapDevToolPlugin {
<ide> new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
<ide>
<ide> compilation.hooks.afterOptimizeChunkAssets.tap(
<del> {
<add> /** @type {TODO} */ ({
<ide> name: "SourceMapDevToolPlugin",
<ide> context: true
<del> },
<del> (context, chunks) => {
<add> }),
<add> /** @type {TODO} */
<add> /** @param {any} context @param {Chunk[]} chunks @returns {void} */
<add> ((context, chunks) => {
<ide> const moduleToSourceNameMapping = new Map();
<ide> const reportProgress =
<ide> context && context.reportProgress
<ide> class SourceMapDevToolPlugin {
<ide> }
<ide> });
<ide> reportProgress(1.0);
<del> }
<add> })
<ide> );
<ide> });
<ide> }
<ide><path>lib/Template.js
<ide> const HotUpdateChunk = require("./HotUpdateChunk");
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("./Chunk")} Chunk */
<ide> /** @typedef {import("./ChunkGraph")} ChunkGraph */
<add>/** @typedef {import("./Compilation").PathData} PathData */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Module")} Module */
<ide> /** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
<ide> * @typedef {Object} RenderManifestEntry
<ide> * @property {function(): Source} render
<ide> * @property {string=} filenameTemplate
<del> * @property {TODO=} pathOptions
<add> * @property {PathData=} pathOptions
<ide> * @property {TODO} identifier
<ide> * @property {TODO=} hash
<ide> */
<ide><path>lib/TemplatedPathPlugin.js
<ide>
<ide> "use strict";
<ide>
<add>const Module = require("./Module");
<add>
<add>/** @typedef {import("./Compilation").PathData} PathData */
<add>
<ide> const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi,
<ide> REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi,
<ide> REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi,
<ide> const getReplacer = (value, allowEmpty) => {
<ide> return fn;
<ide> };
<ide>
<add>/**
<add> * @param {string | function(PathData): string} path the raw path
<add> * @param {PathData} data context data
<add> * @returns {string} the interpolated path
<add> */
<ide> const replacePathVariables = (path, data) => {
<add> const chunkGraph = data.chunkGraph;
<ide> const chunk = data.chunk;
<ide> const chunkId = chunk && chunk.id;
<ide> const chunkName = chunk && (chunk.name || chunk.id);
<ide> const chunkHash = chunk && (chunk.renderedHash || chunk.hash);
<del> const chunkHashWithLength = chunk && chunk.hashWithLength;
<add> const chunkHashWithLength =
<add> chunk && "hashWithLength" in chunk && chunk.hashWithLength;
<ide> const contentHashType = data.contentHashType;
<ide> const contentHash =
<del> (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) ||
<del> data.contentHash;
<del> const contentHashWithLength =
<add> data.contentHash ||
<ide> (chunk &&
<del> chunk.contentHashWithLength &&
<del> chunk.contentHashWithLength[contentHashType]) ||
<del> data.contentHashWithLength;
<add> contentHashType &&
<add> chunk.contentHash &&
<add> chunk.contentHash[contentHashType]);
<add> const contentHashWithLength =
<add> data.contentHashWithLength ||
<add> (chunk && "contentHashWithLength" in chunk
<add> ? chunk.contentHashWithLength[contentHashType]
<add> : undefined);
<ide> const module = data.module;
<ide> const moduleId = module && module.id;
<del> const moduleHash = module && (module.renderedHash || module.hash);
<del> const moduleHashWithLength = module && module.hashWithLength;
<add> const moduleHash =
<add> module &&
<add> (module instanceof Module
<add> ? chunkGraph.getRenderedModuleHash(module)
<add> : module.renderedHash || module.hash);
<add> const moduleHashWithLength =
<add> module && "hashWithLength" in module && module.hashWithLength;
<ide>
<ide> if (typeof path === "function") {
<ide> path = path(data);
<ide><path>lib/wasm/WasmMainTemplatePlugin.js
<ide> class WasmMainTemplatePlugin {
<ide> mainTemplate.hooks.hashForChunk.tap(
<ide> "WasmMainTemplatePlugin",
<ide> (hash, chunk) => {
<del> const chunkModuleMaps = this.compilation.chunkGraph.getChunkModuleMaps(
<del> chunk,
<del> m => m.type.startsWith("webassembly")
<add> const chunkGraph = this.compilation.chunkGraph;
<add> const chunkModuleMaps = chunkGraph.getChunkModuleMaps(chunk, m =>
<add> m.type.startsWith("webassembly")
<ide> );
<ide> hash.update(JSON.stringify(chunkModuleMaps.id));
<del> const wasmModules = getAllWasmModules(
<del> moduleGraph,
<del> this.compilation.chunkGraph,
<del> chunk
<del> );
<add> const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk);
<ide> for (const module of wasmModules) {
<del> hash.update(module.hash);
<add> hash.update(chunkGraph.getModuleHash(module));
<ide> }
<ide> }
<ide> );
<ide><path>lib/wasm/WebAssemblyModulesPlugin.js
<ide> class WebAssemblyModulesPlugin {
<ide> dependencyTemplates,
<ide> runtimeTemplate: compilation.runtimeTemplate,
<ide> moduleGraph,
<del> chunkGraph: compilation.chunkGraph
<add> chunkGraph
<ide> }
<ide> ),
<ide> filenameTemplate,
<ide> pathOptions: {
<add> chunkGraph,
<ide> module
<ide> },
<ide> identifier: `webassemblyModule${module.id}`,
<del> hash: module.hash
<add> hash: chunkGraph.getModuleHash(module)
<ide> });
<ide> }
<ide> } | 15 |
Text | Text | update chinese translation of react and redux | 88ae7a5df88b1ff2a981ee734d52e6135bece9b8 | <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/connect-redux-to-react.chinese.md
<ide> id: 5a24c314108439a4d4036147
<ide> title: Connect Redux to React
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将Redux连接到React
<add>forumTopicId: 301426
<add>localeTitle: 连接 Redux 和 React
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在您已经编写了<code>mapStateToProps()</code>和<code>mapDispatchToProps()</code>函数,您可以使用它们将<code>state</code>和<code>dispatch</code>映射到您的某个React组件的<code>props</code> 。 React Redux的<code>connect</code>方法可以处理此任务。此方法采用两个可选参数: <code>mapStateToProps()</code>和<code>mapDispatchToProps()</code> 。它们是可选的,因为您可能拥有只需要访问<code>state</code>但不需要分派任何操作的组件,反之亦然。要使用此方法,请将函数作为参数传递,并立即使用组件调用结果。这种语法有点不寻常,看起来像: <code>connect(mapStateToProps, mapDispatchToProps)(MyComponent)</code> <strong>注意:</strong>如果要省略<code>connect</code>方法的其中一个参数,则在其位置传递<code>null</code> 。 </section>
<add><section id='description'>
<add>既然写了<code>mapStateToProps()</code>、<code>mapDispatchToProps()</code>两个函数,现在你可以用它们来把<code>state</code>和<code>dispatch</code>映射到 React 组件的<code>props</code>了。React Redux 的<code>connect</code>方法可以完成这个任务。此方法有<code>mapStateToProps()</code>、<code>mapDispatchToProps()</code>两个可选参数,它们是可选的,原因是你的组件可能仅需要访问<code>状态</code>但不需要分发任何 actions,反之亦然。
<add>为了使用此方法,需要传入函数参数并在调用时传入组件。这种语法有些不寻常,如下所示:
<add><code>connect(mapStateToProps, mapDispatchToProps)(MyComponent)</code>
<add><strong>注意:</strong> 如果要省略<code>connect</code>方法中的某个参数,则应当用<code>null</code>替换这个参数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器具有<code>mapStateToProps()</code>和<code>mapDispatchToProps()</code>函数以及一个名为<code>Presentational</code>的新React组件。使用<code>ReactRedux</code>全局对象中的<code>connect</code>方法将此组件连接到Redux,并立即在<code>Presentational</code>组件上调用它。将结果分配给名为<code>ConnectedComponent</code>的新<code>const</code> ,该<code>const</code>表示连接的组件。就是这样,现在你已经连接到Redux了!尝试将<code>connect</code>的参数更改为<code>null</code>并观察测试结果。 </section>
<add><section id='instructions'>
<add>在编辑器上有两个函数:<code>mapStateToProps()</code>、<code>mapDispatchToProps()</code>,还有一个叫<code>Presentational</code>的 React 组件。用<code>ReactRedux</code>全局对象中的<code>connect</code>方法将此组件连接到 Redux,并立即在<code>Presentational</code>组件中调用,把结果赋值给一个名为<code>ConnectedComponent</code>的代表已连接组件的新常量。大功告成!你已成功把 React 连接到 Redux!尝试更改任何一个<code>connect</code>参数为<code>null</code>并观察测试结果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>Presentational</code>组件应该呈现。
<add> - text: 应渲染<code>Presentational</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })());
<del> - text: <code>Presentational</code>组件应通过<code>connect</code>接收prop <code>messages</code> 。
<add> - text: <code>Presentational</code>组件应通过<code>connect</code>接收一个<code>messages</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return props.messages === '__INITIAL__STATE__'; })());
<del> - text: <code>Presentational</code>组件应通过<code>connect</code>接收prop <code>submitNewMessage</code> 。
<add> - text: <code>Presentational</code>组件应通过<code>connect</code>接收一个<code>submitNewMessage</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find('Presentational').props(); return typeof props.submitNewMessage === 'function'; })());
<ide>
<ide> ```
<ide> class Presentational extends React.Component {
<ide> };
<ide>
<ide> const connect = ReactRedux.connect;
<del>// change code below this line
<add>// 请在本行以下添加你的代码
<ide>
<ide> ```
<ide>
<ide> const connect = ReactRedux.connect;
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>
<add>const store = Redux.createStore(
<add> (state = '__INITIAL__STATE__', action) => state
<add>);
<add>class AppWrapper extends React.Component {
<add> render() {
<add> return (
<add> <ReactRedux.Provider store = {store}>
<add> <ConnectedComponent/>
<add> </ReactRedux.Provider>
<add> );
<add> }
<add>};
<add>ReactDOM.render(<AppWrapper />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const addMessage = (message) => {
<add> return {
<add> type: 'ADD',
<add> message: message
<add> }
<add>};
<add>
<add>const mapStateToProps = (state) => {
<add> return {
<add> messages: state
<add> }
<add>};
<add>
<add>const mapDispatchToProps = (dispatch) => {
<add> return {
<add> submitNewMessage: (message) => {
<add> dispatch(addMessage(message));
<add> }
<add> }
<add>};
<add>
<add>class Presentational extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return <h3>This is a Presentational Component</h3>
<add> }
<add>};
<add>
<add>const connect = ReactRedux.connect;
<add>// change code below this line
<add>
<add>const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(Presentational);
<add>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.chinese.md
<ide> id: 5a24c314108439a4d4036148
<ide> title: Connect Redux to the Messages App
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将Redux连接到消息应用程序
<add>forumTopicId: 301427
<add>localeTitle: 将 Redux 连接到 Messages App
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在您已了解如何使用<code>connect</code>将React连接到Redux,您可以将您学到的知识应用于处理消息的React组件。在上一课中,您连接到Redux的组件名为<code>Presentational</code> ,这不是任意的。该术语<i>通常</i>是指未直接连接到Redux的React组件。他们只负责UI的呈现,并根据他们收到的道具来执行此操作。相比之下,容器组件连接到Redux。这些通常负责将操作分派给商店,并且经常将商店状态作为道具传递给子组件。 </section>
<add><section id='description'>
<add>知道<code>connect</code>怎么实现 React 和 Redux 的连接后,我们可以在 React 组件中应用上面学到的内容。
<add>在上一课,连接到 Redux 的组件命名为<code>Presentational</code>,这个命名不是任意的,这样的术语通常是指未直接连接到 Redux 的 React 组件,他们只负责执行接收 props 的函数来实现 UI 的呈现。与上一挑战相比,本挑战需要把容器组件连接到 Redux。这些组件通常负责把 actions 分派给 store,且经常给子组件传入 store state 属性。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">到目前为止,代码编辑器包含了您在本节中编写的所有代码。唯一的变化是React组件被重命名为<code>Presentational</code> 。创建一个名为<code>Container</code>的常量中保存的新组件,该常量使用<code>connect</code>将<code>Presentational</code>组件连接到Redux。然后,在<code>AppWrapper</code> ,渲染React Redux <code>Provider</code>组件。将Redux <code>store</code> <code>Provider</code>作为道具传递,并将<code>Container</code>作为子项呈现。设置完所有内容后,您将再次看到应用程序呈现给页面的消息。 </section>
<add><section id='instructions'>
<add>到目前为止,我们的编辑器上已包含了整个章节的代码,唯一不同的是,React 组件被重新命名为<code>Presentational</code>,即展示层组件。创建一个新组件,保存在名为<code>Container</code>的常量中。这个常量用<code>connect</code>把<code>Presentational</code>组件和 Redux 连接起来。然后,在<code>AppWrapper</code>中渲染 React Redux 的<code>Provider</code>组件,给<code>Provider</code>传入 Redux<code>store</code>属性并渲染<code>Container</code>为子组件。完成这些,消息 app 应用会再次渲染页面。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>AppWrapper</code>应该呈现给页面。
<add> - text: <code>AppWrapper</code>应渲染该页面。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })());
<del> - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。
<add> - text: <code>Presentational</code>组件应渲染<code>h2</code>、<code>input</code>、<code>button</code>、<code>ul</code>四个元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })());
<del> - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。
<add> - text: <code>Presentational</code>组件应渲染<code>h2</code>、<code>input</code>、<code>button</code>、<code>ul</code>四个元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })());
<del> - text: <code>Presentational</code>组件应该从Redux商店接收<code>messages</code>作为道具。
<add> - text: <code>Presentational</code>组件应接收 Redux store 的<code>消息</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })());
<del> - text: <code>Presentational</code>组件应该接收<code>submitMessage</code>操作创建者作为prop。
<add> - text: <code>Presentational</code>组件应接收创建 action 的函数<code>submitMessage</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })());
<ide>
<ide> ```
<ide> class Presentational extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: ",
<add> input: '',
<ide> messages: []
<ide> }
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class Presentational extends React.Component {
<ide> submitMessage() {
<ide> const currentMessage = this.state.input;
<ide> this.setState({
<del> input: ",
<add> input: '',
<ide> messages: this.state.messages.concat(currentMessage)
<ide> });
<ide> }
<ide> const mapDispatchToProps = (dispatch) => {
<ide> const Provider = ReactRedux.Provider;
<ide> const connect = ReactRedux.connect;
<ide>
<del>// define the Container component here:
<add>// 在此定义 Container 组件:
<ide>
<ide>
<ide> class AppWrapper extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> }
<ide> render() {
<del> // complete the return statement:
<add> // 完成返回声明:
<ide> return (null);
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class AppWrapper extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<AppWrapper />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<del>```
<add>// Redux:
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message: message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>const store = Redux.createStore(messageReducer);
<add>
<add>// React:
<add>class Presentational extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> messages: []
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> const currentMessage = this.state.input;
<add> this.setState({
<add> input: '',
<add> messages: this.state.messages.concat(currentMessage)
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.state.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>// React-Redux:
<add>const mapStateToProps = (state) => {
<add> return { messages: state }
<add>};
<ide>
<del>/section>
<add>const mapDispatchToProps = (dispatch) => {
<add> return {
<add> submitNewMessage: (newMessage) => {
<add> dispatch(addMessage(newMessage))
<add> }
<add> }
<add>};
<add>
<add>const Provider = ReactRedux.Provider;
<add>const connect = ReactRedux.connect;
<add>
<add>// define the Container component here:
<add>const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
<add>
<add>class AppWrapper extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> // complete the return statement:
<add> return (
<add> <Provider store={store}>
<add> <Container/>
<add> </Provider>
<add> );
<add> }
<add>};
<add>```
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/extract-local-state-into-redux.chinese.md
<ide> id: 5a24c314108439a4d4036149
<ide> title: Extract Local State into Redux
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将本地状态提取到Redux
<add>forumTopicId: 301428
<add>localeTitle: 将局部状态提取到 Redux 中
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">你几乎完成!回想一下,您编写了所有Redux代码,以便Redux可以控制React消息应用程序的状态管理。现在Redux已连接,您需要从<code>Presentational</code>组件中提取状态管理并进入Redux。目前,您已连接Redux,但您正在<code>Presentational</code>组件中本地处理状态。 </section>
<add><section id='description'>
<add>胜利就在眼前了!请回顾一下为管理 React messages app 的状态写的 Redux 代码。现在有了连接好的 Redux,你还要从<code>Presentational</code>组件中提取状态管理到 Redux,在<code>Presentational</code>组件内处理本地状态。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>Presentational</code>组件中,首先,删除本地<code>state</code>中的<code>messages</code>属性。这些消息将由Redux管理。接下来,修改<code>submitMessage()</code>方法,以便从<code>this.props</code>调度<code>submitNewMessage()</code> ,并将当前消息输入作为参数传入本地<code>state</code> 。因为你删除<code>messages</code>从本地状态,删除<code>messages</code>从调用属性<code>this.setState()</code>在这里。最后,修改<code>render()</code>方法,使其映射到从<code>props</code>而不是<code>state</code>接收的消息。一旦做出这些更改,除了Redux管理状态之外,应用程序将继续运行相同的功能。这个例子也说明组件可以如何具有本地<code>state</code> :你的组件还是本地跟踪用户输入自己的<code>state</code> 。您可以看到Redux如何在React之上提供有用的状态管理框架。您最初仅使用React的本地状态获得了相同的结果,这通常可以通过简单的应用程序实现。但是,随着您的应用程序变得越来越大,越来越复杂,您的状态管理也是如此,这就是Redux解决的问题。 </section>
<add><section id='instructions'>
<add>在<code>Presentational</code>组件中,先删除本地<code>state</code>中的<code>messages</code>属性,被删的 messages 将由 Redux 管理。接着,修改<code>submitMessage()</code>方法,使该方法从<code>this.props</code>那里分发<code>submitNewMessage()</code>;从本地<code>state</code>中传入当前消息输入作为参数。因本地状态删除了<code>messages</code>属性,所以在调用<code>this.setState()</code>时也要删除该属性。最后,修改<code>render()</code>方法,使其所映射的消息是从<code>props</code>接收的,而不是<code>state</code>
<add>完成这些更改后,我们的应用会实现 Redux 管理应用的状态,但它继续运行着相同的功能。此示例还阐明了组件获得本地状态的方式,即在自己的状态中继续跟踪用户本地输入。由此可见,Redux 为 React 提供了很有用的状态管理框架。先前,你仅使用 React 的本地状态也实现了相同的结果,这在应付简单的应用时通常是可行的。但是,随着应用变得越来越大,越来越复杂,应用的状态管理也变得非常困难,Redux 就是为解决这样的问题而诞生的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>AppWrapper</code>应该呈现给页面。
<add> - text: <code>AppWrapper</code>应该渲染该到页面。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })());
<del> - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。
<add> - text: <code>Presentational</code> 应该渲染到页面上.
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })());
<del> - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。
<add> - text: <code>Presentational</code>组件应渲染<code>h2</code>、<code>input</code>、<code>button</code>、<code>ul</code>四个元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })());
<del> - text: <code>Presentational</code>组件应该从Redux商店接收<code>messages</code>作为道具。
<add> - text: <code>Presentational</code>组件应接收 Redux store 的<code>消息</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })());
<del> - text: <code>Presentational</code>组件应该接收<code>submitMessage</code>操作创建者作为prop。
<add> - text: <code>Presentational</code>组件应接收创建 action 的函数<code>submitMessage</code>属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })());
<del> - text: <code>Presentational</code>组件的状态应包含一个属性<code>input</code> ,该属性初始化为空字符串。
<add> - text: <code>Presentational</code>组件的状态应包含一个初始化为空字符串的input属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalState = mockedComponent.find('Presentational').instance().state; return typeof PresentationalState.input === 'string' && Object.keys(PresentationalState).length === 1; })());
<del> - text: 输入<code>input</code>元素应该更新<code>Presentational</code>组件的状态。
<add> - text: 键入<code>input</code>元素应更新<code>Presentational</code>组件的状态。
<ide> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const testValue = ''__MOCK__INPUT__''; const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); let initialInput = mockedComponent.find(''Presentational'').find(''input''); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); const updatedInput = updated.find(''Presentational'').find(''input''); assert(initialInput.props().value === '''' && updatedInput.props().value === ''__MOCK__INPUT__''); }; '
<del> - text: 在<code>Presentational</code>组件上调度<code>submitMessage</code>应更新Redux存储并清除本地状态的输入。
<add> - text: 在<code>Presentational</code>组件上 dispatch <code>submitMessage</code>应更新 Redux store 并清除本地状态中的输入。
<ide> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find(''Presentational'').props(); const testValue = ''__TEST__EVENT__INPUT__''; const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find(''input'').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find(''Presentational'').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find(''input'').props().value === ''''); }; '
<del> - text: <code>Presentational</code>组件应该呈现来自Redux存储的<code>messages</code> 。
<add> - text: <code>Presentational</code>组件应渲染 Redux store 中的<code>messages</code>
<ide> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find(''Presentational'').props(); const testValue = ''__TEST__EVENT__INPUT__''; const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find(''input'').props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find(''Presentational'').props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find(''input'').props().value === '''' && afterClick.find(''ul'').childAt(0).text() === testValue); }; '
<ide>
<ide> ```
<ide> const store = Redux.createStore(messageReducer);
<ide> const Provider = ReactRedux.Provider;
<ide> const connect = ReactRedux.connect;
<ide>
<del>// Change code below this line
<add>// 请在本行以下添加你的代码
<ide> class Presentational extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: ",
<add> input: '',
<ide> messages: []
<ide> }
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class Presentational extends React.Component {
<ide> }
<ide> submitMessage() {
<ide> this.setState({
<del> input: ",
<add> input: '',
<ide> messages: this.state.messages.concat(this.state.input)
<ide> });
<ide> }
<ide> class Presentational extends React.Component {
<ide> );
<ide> }
<ide> };
<del>// Change code above this line
<add>// 请在本行以上添加你的代码
<ide>
<ide> const mapStateToProps = (state) => {
<ide> return {messages: state}
<ide> class AppWrapper extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class AppWrapper extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<AppWrapper />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>// Redux:
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message: message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>const store = Redux.createStore(messageReducer);
<add>
<add>// React:
<add>const Provider = ReactRedux.Provider;
<add>const connect = ReactRedux.connect;
<add>
<add>// Change code below this line
<add>class Presentational extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: ''
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> this.props.submitNewMessage(this.state.input);
<add> this.setState({
<add> input: ''
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.props.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<add>// Change code above this line
<add>
<add>const mapStateToProps = (state) => {
<add> return {messages: state}
<add>};
<add>
<add>const mapDispatchToProps = (dispatch) => {
<add> return {
<add> submitNewMessage: (message) => {
<add> dispatch(addMessage(message))
<add> }
<add> }
<add>};
<add>
<add>const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
<add>
<add>class AppWrapper extends React.Component {
<add> render() {
<add> return (
<add> <Provider store={store}>
<add> <Container/>
<add> </Provider>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/extract-state-logic-to-redux.chinese.md
<ide> id: 5a24c314108439a4d4036143
<ide> title: Extract State Logic to Redux
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将状态逻辑提取到Redux
<add>forumTopicId: 301429
<add>localeTitle: 提取状态逻辑给 Redux
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在您已完成React组件,您需要将其在其<code>state</code>本地执行的逻辑移动到Redux中。这是将简单的React应用程序连接到Redux的第一步。您的应用程序的唯一功能是将用户的新消息添加到无序列表中。该示例很简单,以演示React和Redux如何协同工作。 </section>
<add><section id='description'>
<add>完成 React 组件后,我们需要把在本地<code>状态</code>执行的逻辑移到 Redux 中,这是为小规模 React 应用添加 Redux 的第一步。该应用的唯一功能是把用户的新消息添加到无序列表中。下面我们用简单的示例来演示 React 和 Redux 之间的配合。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">首先,定义一个动作类型'ADD'并将其设置为const <code>ADD</code> 。接下来,定义一个动作创建器<code>addMessage()</code> ,它创建添加消息的动作。您需要将<code>message</code>给此操作创建者,并在返回的<code>action</code>包含该消息。然后创建一个名为<code>messageReducer()</code>的reducer来处理消息的状态。初始状态应该等于空数组。此reducer应向状态中保存的消息数组添加消息,或返回当前状态。最后,创建Redux存储并将其传递给reducer。 </section>
<add><section id='instructions'>
<add>首先,定义 action 的类型 'ADD',将其设置为常量<code>ADD</code>。接着,定义创建 action 的函数<code>addMessage()</code>,用该函数创建添加消息的 action,把<code>message</code>传给创建 action 的函数并返回包含该消息的<code>action</code>
<add>接着,创建名为<code>messageReducer()</code>的 reducer 方法,为这些消息处理状态。初始状态应为空数组。reducer 向状态中的消息数组添加消息,或返回当前状态。最后,创建 Redux store 并传给 reducer。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: const <code>ADD</code>应该存在并保持一个等于字符串<code>ADD</code>的值
<add> - text: 应存在一个值为字符串<code>ADD</code>的常量<code>ADD</code>。
<ide> testString: assert(ADD === 'ADD');
<del> - text: 动作创建者<code>addMessage</code>应返回<code>type</code>等于<code>ADD</code>的对象,并且消息等于传入的消息。
<add> - text: 创建 action 的函数<code>addMessage</code>应返回<code>type</code>等于<code>ADD</code>的对象,其返回的消息即被传入的消息。
<ide> testString: assert((function() { const addAction = addMessage('__TEST__MESSAGE__'); return addAction.type === ADD && addAction.message === '__TEST__MESSAGE__'; })());
<del> - text: <code>messageReducer</code>应该是一个函数。
<add> - text: <code>messageReducer</code>应是一个函数。
<ide> testString: assert(typeof messageReducer === 'function');
<del> - text: 存储应该存在并且初始状态设置为空数组。
<add> - text: 存在一个 store 且其初始状态为空数组。
<ide> testString: assert((function() { const initialState = store.getState(); return typeof store === 'object' && initialState.length === 0; })());
<del> - text: 对商店调度<code>addMessage</code>应该<code>addMessage</code>向状态中保存的消息数组添加新消息。
<add> - text: 分发<code>addMessage</code>到 store 应添加新消息到状态中消息数组。
<ide> testString: assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addMessage('__A__TEST__MESSAGE')); const addState = store.getState(); return (isFrozen && addState[0] === '__A__TEST__MESSAGE'); })());
<del> - text: 如果使用任何其他操作调用, <code>messageReducer</code>应返回当前状态。
<add> - text: <code>messageReducer</code>被其它任何 actions 调用时应返回当前状态。
<ide> testString: 'assert((function() { const addState = store.getState(); store.dispatch({type: ''FAKE_ACTION''}); const testState = store.getState(); return (addState === testState); })());'
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<del>// define ADD, addMessage(), messageReducer(), and store here:
<add>// 请在此处定义 ADD、addMessage()、messageReducer()、store:
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>const store = Redux.createStore(messageReducer);
<ide> ```
<ide>
<del>/section>
<add></section>
<add>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/getting-started-with-react-redux.chinese.md
<ide> id: 5a24c314108439a4d4036141
<ide> title: Getting Started with React Redux
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: React Redux入门
<add>forumTopicId: 301430
<add>localeTitle: React 和 Redux 入门
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">这一系列挑战介绍了如何将Redux与React一起使用。首先,这里回顾一下每种技术的一些关键原则。 React是一个您提供数据的视图库,然后以高效,可预测的方式呈现视图。 Redux是一个状态管理框架,可用于简化应用程序状态的管理。通常,在React Redux应用程序中,您可以创建一个Redux存储库来管理整个应用程序的状态。您的React组件仅订阅商店中与其角色相关的数据。然后,直接从React组件调度操作,然后触发存储更新。虽然React组件可以在本地管理自己的状态,但是当您拥有复杂的应用程序时,通常最好将应用程序状态保存在Redux的单个位置。当单个组件可能仅具有特定于其的本地状态时,存在例外情况。最后,因为Redux不是设计用于开箱即用的React,所以你需要使用<code>react-redux</code>包。它为您提供了Redux的传递方式<code>state</code> ,并<code>dispatch</code>到你的反应的组分作为<code>props</code> 。在接下来的几个挑战中,首先,您将创建一个简单的React组件,允许您输入新的文本消息。这些将添加到视图中显示的数组中。这应该是您在React课程中学到的内容的一个很好的回顾。接下来,您将创建一个Redux存储和操作来管理messages数组的状态。最后,您将使用<code>react-redux</code>将Redux存储与您的组件连接,从而将本地状态提取到Redux存储中。 </section>
<add><section id='description'>
<add>这一系列挑战介绍的是 Redux 和 React 的配合,我们先来回顾一下这两种技术的关键原则是什么。React 是提供数据的视图库,能以高效、可预测的方式渲染视图。Redux 是状态管理框架,可用于简化 APP 应用状态的管理。在 React Redux app 应用中,通常可创建单一的 Redux store 来管理整个应用的状态。React 组件仅订阅 store 中与其角色相关的数据,你可直接从 React 组件中分发 actions 以触发 store 对象的更新。
<add>React 组件可以在本地管理自己的状态,但是对于复杂的应用来说,它的状态最好是用 Redux 保存在单一位置,有特定本地状态的独立组件例外。最后一点是,Redux 没有内置的 React,需要安装<code>react-redux</code>包,通过这个方式把 Redux 的<code>state</code>和<code>dispatch</code>作为<code>props</code>传给组件。
<add>在接下来的挑战中,先要创建一个可输入新文本消息的 React 组件,添加这些消息到数组里,在视图上显示数组。接着,创建 Redux store 和 actions 来管理消息数组的状态。最后,使用<code>react-redux</code>连接 Redux store 和组件,从而将本地状态提取到 Redux store 中。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">从<code>DisplayMessages</code>组件开始。一个构造添加到该组件,并使用具有两个属性的状态初始化: <code>input</code> ,其被设置为一个空字符串,和<code>messages</code> ,这是设置为空数组。 </section>
<add><section id='instructions'>
<add>创建<code>DisplayMessages</code>组件,把构造函数添加到此组件中,使用含两个属性的状态初始化该组件,这两个属性为:input(设置为空字符串),<code>messages</code>(设置为空数组)。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>DisplayMessages</code>组件应呈现一个空的<code>div</code>元素。
<add> - text: <code>DisplayMessages</code>组件应渲染空的<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); return mockedComponent.find('div').text() === '' })());
<del> - text: 应该使用<code>super</code>正确调用<code>DisplayMessages</code>构造函数,传入<code>props</code> 。
<add> - text: <code>DisplayMessages</code>组件的构造函数应调用<code>super</code>,传入<code>props</code>。
<ide> testString: getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/\s/g,''); return noWhiteSpace.includes('constructor(props)') && noWhiteSpace.includes('super(props'); })());
<del> - text: '<code>DisplayMessages</code>组件的初始状态应等于<code>{input: "", messages: []}</code> 。'
<add> - text: '<code>DisplayMessages</code>组件的初始状态应是<code>{input: "", messages: []}</code>。'
<ide> testString: "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return typeof initialState === 'object' && initialState.input === '' && Array.isArray(initialState.messages) && initialState.messages.length === 0; })());"
<ide>
<ide> ```
<ide> tests:
<ide>
<ide> ```jsx
<ide> class DisplayMessages extends React.Component {
<del> // change code below this line
<add>// 请在本行以下添加你的代码
<ide>
<del> // change code above this line
<add>// 请在本行以上添加你的代码
<ide> render() {
<ide> return <div />
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class DisplayMessages extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<DisplayMessages />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class DisplayMessages extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> messages: []
<add> }
<add> }
<add> render() {
<add> return <div/>
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<add>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/manage-state-locally-first.chinese.md
<ide> id: 5a24c314108439a4d4036142
<ide> title: Manage State Locally First
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 在当地管理国家
<add>forumTopicId: 301431
<add>localeTitle: 首先在本地管理状态
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在这里,您将完成创建<code>DisplayMessages</code>组件。 </section>
<add><section id='description'>
<add>这一关的任务是完成<code>DisplayMessages</code>组件的创建。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">首先,在<code>render()</code>方法中,让组件呈现<code>input</code>元素, <code>button</code>元素和<code>ul</code>元素。当<code>input</code>元素改变时,它应该触发<code>handleChange()</code>方法。此外, <code>input</code>元素应该呈现处于组件状态的<code>input</code>值。 <code>button</code>元素应在单击时触发<code>submitMessage()</code>方法。其次,写下这两种方法。该<code>handleChange()</code>方法应该更新<code>input</code>与用户正在打字。 <code>submitMessage()</code>方法应将当前消息(存储在<code>input</code> )连接到本地状态的<code>messages</code>数组,并清除<code>input</code>的值。最后,使用<code>ul</code>映射<code>messages</code>数组并将其作为<code>li</code>元素列表呈现给屏幕。 </section>
<add><section id='instructions'>
<add>首先,在<code>render()</code>方法中,让组件渲染<code>input</code>、<code>button</code>、<code>ul</code>三个元素。<code>input</code>元素的改变会触发<code>handleChange()</code>方法。此外,<code>input</code>元素会渲染组件状态中<code>input</code>的值。点击按钮<code>button</code>需触发<code>submitMessage()</code>方法。
<add>接着,写出这两种方法。<code>handleChange()</code>方法会更新<code>input</code>为用户正在输入的内容。<code>submitMessage()</code>方法把当前存储在<code>input</code>的消息与本地状态的<code>messages</code>数组连接起来,并清除<code>input</code>的值。
<add>最后,在<code>ul</code>中展示<code>messages</code>数组,其中每个元素内容需放到<code>li</code>元素内。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>DisplayMessages</code>组件应使用等于<code>{ input: "", messages: [] }</code>的状态进行初始化。'
<del> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return ( typeof initialState === "object" && initialState.input === "" && initialState.messages.length === 0); })());
<del> - text: <code>DisplayMessages</code>组件应该呈现包含<code>h2</code>元素, <code>button</code>元素, <code>ul</code>元素和<code>li</code>元素作为子元素的<code>div</code> 。
<del> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const state = () => { mockedComponent.setState({messages: ["__TEST__MESSAGE"]}); return waitForIt(() => mockedComponent )}; const updated = await state(); assert(updated.find("div").length === 1 && updated.find("h2").length === 1 && updated.find("button").length === 1 && updated.find("ul").length === 1, "The <code>DisplayMessages</code> component should render a <code>div</code> containing an <code>h2</code> element, a <code>button</code> element, a <code>ul</code> element, and <code>li</code> elements as children."); }; '
<del> - text: <code>input</code>元素应该以本地状态呈现<code>input</code>值。
<del> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const testValue = "__TEST__EVENT__INPUT"; const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); assert(updated.find("input").props().value === testValue, "The <code>input</code> element should render the value of <code>input</code> in local state."); }; '
<del> - text: 调用方法<code>handleChange</code>应该将状态中的<code>input</code>值更新为当前输入。
<del> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = "__TEST__EVENT__MESSAGE__"; const changed = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const afterInput = await changed(); assert(initialState.input === "" && afterInput.state().input === "__TEST__EVENT__MESSAGE__", "Calling the method <code>handleChange</code> should update the <code>input</code> value in state to the current input."); }; '
<del> - text: 单击“ <code>Add message</code>按钮应调用方法<code>submitMessage</code> ,该方法<code>submitMessage</code>当前<code>input</code>添加到状态中的<code>messages</code>数组。
<del> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage_1 = "__FIRST__MESSAGE__"; const firstChange = () => { causeChange(mockedComponent, testMessage_1); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit_1 = await firstSubmit(); const submitState_1 = afterSubmit_1.state(); const testMessage_2 = "__SECOND__MESSAGE__"; const secondChange = () => { causeChange(mockedComponent, testMessage_2); return waitForIt(() => mockedComponent )}; const secondResult = await secondChange(); const secondSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit_2 = await secondSubmit(); const submitState_2 = afterSubmit_2.state(); assert(initialState.messages.length === 0 && submitState_1.messages.length === 1 && submitState_2.messages.length === 2 && submitState_2.messages[1] === testMessage_2, "Clicking the <code>Add message</code> button should call the method <code>submitMessage</code> which should add the current <code>input</code> to the <code>messages</code> array in state."); }; '
<del> - text: <code>submitMessage</code>方法应该清除当前输入。
<del> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = "__FIRST__MESSAGE__"; const firstChange = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstState = firstResult.state(); const firstSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit = await firstSubmit(); const submitState = afterSubmit.state(); assert(firstState.input === testMessage && submitState.input === "", "The <code>submitMessage</code> method should clear the current input."); }; '
<add> - text: '<code>DisplayMessages</code>组件的初始状态应是<code>{ input: "", messages: [] }</code>。'
<add> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return ( typeof initialState === ''object'' && initialState.input === '''' && initialState.messages.length === 0); })());'
<add> - text: <code>DisplayMessages</code>组件应渲染含<code>h2</code>、<code>button</code>、<code>ul</code>、<code>li</code>四个子元素的<code>div</code>。
<add> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const state = () => { mockedComponent.setState({messages: [''__TEST__MESSAGE'']}); return waitForIt(() => mockedComponent )}; const updated = await state(); assert(updated.find(''div'').length === 1 && updated.find(''h2'').length === 1 && updated.find(''button'').length === 1 && updated.find(''ul'').length === 1 && updated.find(''li'').length > 0); }; '
<add> - text: <code>input</code>元素应渲染本地状态中的<code>input</code>值。
<add> testString: assert(code.match(/this\.state\.messages\.map/g));
<add> - text: 调用<code>handleChange</code>方法时应更新状态中的<code>input</code>值为当前输入。
<add> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const testValue = ''__TEST__EVENT__INPUT''; const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); assert(updated.find(''input'').props().value === testValue); }; '
<add> - text: 单击<code>Add message</code>按钮应调用<code>submitMessage</code>方法,添加当前<code>输入</code>到状态中的<code>消息</code>数组。
<add> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = ''__TEST__EVENT__MESSAGE__''; const changed = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const afterInput = await changed(); assert(initialState.input === '''' && afterInput.state().input === ''__TEST__EVENT__MESSAGE__''); }; '
<add> - text: <code>submitMessage</code>方法应清除当前输入。
<add> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage_1 = ''__FIRST__MESSAGE__''; const firstChange = () => { causeChange(mockedComponent, testMessage_1); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstSubmit = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent )}; const afterSubmit_1 = await firstSubmit(); const submitState_1 = afterSubmit_1.state(); const testMessage_2 = ''__SECOND__MESSAGE__''; const secondChange = () => { causeChange(mockedComponent, testMessage_2); return waitForIt(() => mockedComponent )}; const secondResult = await secondChange(); const secondSubmit = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent )}; const afterSubmit_2 = await secondSubmit(); const submitState_2 = afterSubmit_2.state(); assert(initialState.messages.length === 0 && submitState_1.messages.length === 1 && submitState_2.messages.length === 2 && submitState_2.messages[1] === testMessage_2); }; '
<add> - text: The <code>submitMessage</code> method should clear the current input.
<add> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find(''input'').simulate(''change'', { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = ''__FIRST__MESSAGE__''; const firstChange = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstState = firstResult.state(); const firstSubmit = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent )}; const afterSubmit = await firstSubmit(); const submitState = afterSubmit.state(); assert(firstState.input === testMessage && submitState.input === ''''); }; '
<ide>
<ide> ```
<ide>
<ide> class DisplayMessages extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: ",
<add> input: '',
<ide> messages: []
<ide> }
<ide> }
<del> // add handleChange() and submitMessage() methods here
<add>// 请把 handleChange()、submitMessage() 写在这里
<ide>
<ide> render() {
<ide> return (
<ide> <div>
<del> <h2>Type in a new Message:</h2>
<del> { /* render an input, button, and ul here */ }
<add> <h2>键入新 Message</h2>
<add> { /* 在此渲染 input、button、ul*/ }
<ide>
<del> { /* change code above this line */ }
<add> { /* 请在本行以上添加你的代码 */ }
<ide> </div>
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class DisplayMessages extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<DisplayMessages />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class DisplayMessages extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> messages: []
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> const currentMessage = this.state.input;
<add> this.setState({
<add> input: '',
<add> messages: this.state.messages.concat(currentMessage)
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.state.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/map-dispatch-to-props.chinese.md
<ide> id: 5a24c314108439a4d4036146
<ide> title: Map Dispatch to Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将调度映射到道具
<add>forumTopicId: 301432
<add>localeTitle: 映射 Dispatch 到 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>mapDispatchToProps()</code>函数用于为React组件提供特定的操作创建器,以便它们可以针对Redux存储分派操作。它的结构与您在上一次挑战中编写的<code>mapStateToProps()</code>函数类似。它返回一个对象,该对象将调度操作映射到属性名称,后者成为组件<code>props</code> 。但是,每个属性都返回一个函数,该函数使用动作创建者和任何相关的动作数据来调用<code>dispatch</code> ,而不是返回一个<code>state</code> 。您可以访问此<code>dispatch</code>因为它在您定义函数时作为参数传递给<code>mapDispatchToProps()</code> ,就像您将<code>state</code>传递给<code>mapStateToProps()</code> 。在幕后,阵营终极版使用终极版的<code>store.dispatch()</code>进行这些分派<code>mapDispatchToProps()</code>这类似于它将<code>store.subscribe()</code>用于映射到<code>state</code>组件。例如,您有一个<code>loginUser()</code>动作创建者,它将<code>username</code>作为动作有效负载。从<code>mapDispatchToProps()</code>为此动作创建者返回的对象看起来像: <blockquote> { <br> submitLoginUser:function(username){ <br>调度(loginUser(用户名)); <br> } <br> } </blockquote></section>
<add><section id='description'>
<add><code>mapDispatchToProps()</code>函数可为 React 组件提供特定的创建 action 的函数,以便组件可 dispatch actions,从而更改 Redux store 中的数据。该函数的结构跟上一挑战中的<code>mapStateToProps()</code>函数相似,它返回一个对象,把 dispatch actions 映射到属性名上,该属性名成为<code>props</code>。然而,每个属性都返回一个用 action creator 及与 action 相关的所有数据调用<code>dispatch</code>的函数,而不是返回<code>state</code>的一部分。你可以访问<code>dispatch</code>,因为在定义函数时,我们以参数形式把它传入<code>mapDispatchToProps()</code>了,这跟<code>state</code>传入<code>mapDispatchToProps()</code>是一样的。在幕后,React Redux 用 Redux 的<code>store.dispatch()</code>来管理这些含<code>mapDispatchToProps()</code>的dispatches,这跟它使用<code>store.subscribe()</code>来订阅映射到<code>state</code>的组件的方式类似。
<add>例如,创建 action 的函数<code>loginUser()</code>把<code>username</code>作为 action payload,<code>mapDispatchToProps()</code>返回给创建 action 的函数的对象如下:
<add>
<add>```jsx
<add>{
<add> submitLoginUser: function(username) {
<add> dispatch(loginUser(username));
<add> }
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器提供了一个名为<code>addMessage()</code>的动作创建器。编写函数<code>mapDispatchToProps()</code> ,将<code>dispatch</code>作为参数,然后返回一个对象。该对象应该将一个属性<code>submitNewMessage</code>设置为dispatch函数,该函数在调度<code>addMessage()</code>时为新消息添加一个参数。 </section>
<add><section id='instructions'>
<add>编辑器上提供的是创建 action 的函数<code>addMessage()</code>。写出接收<code>dispatch</code>为参数的函数<code>mapDispatchToProps()</code>,返回一个 dispatch 函数对象,其属性为<code>submitNewMessage</code>。该函数在 dispatch <code>addMessage()</code>时为新消息提供一个参数。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>addMessage</code>应该返回一个带有键<code>type</code>和<code>message</code>的对象。
<add> - text: <code>addMessage</code>应返回含<code>type</code>和<code>message</code>两个键的对象。
<ide> testString: assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty('type') && addMessageTest.hasOwnProperty('message')); })());
<del> - text: <code>mapDispatchToProps</code>应该是一个函数。
<add> - text: <code>mapDispatchToProps</code>应为函数。
<ide> testString: assert(typeof mapDispatchToProps === 'function');
<del> - text: <code>mapDispatchToProps</code>应该返回一个对象。
<add> - text: <code>mapDispatchToProps</code>应返回一个对象。
<ide> testString: assert(typeof mapDispatchToProps() === 'object');
<del> - text: 使用<code>submitNewMessage</code>的<code>mapDispatchToProps</code>调度<code>addMessage</code>应该向调度函数返回一条消息。
<add> - text: 从<code>mapDispatchToProps</code>通过<code>submitNewMessage</code>分发<code>addMessage</code>,应向 dispatch 函数返回一条消息。
<ide> testString: assert((function() { let testAction; const dispatch = (fn) => { testAction = fn; }; let dispatchFn = mapDispatchToProps(dispatch); dispatchFn.submitNewMessage('__TEST__MESSAGE__'); return (testAction.type === 'ADD' && testAction.message === '__TEST__MESSAGE__'); })());
<ide>
<ide> ```
<ide> const addMessage = (message) => {
<ide> }
<ide> };
<ide>
<del>// change code below this line
<add>// 请在本行以下添加你的代码
<add>
<ide>
<ide> ```
<ide>
<ide> const addMessage = (message) => {
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const addMessage = (message) => {
<add> return {
<add> type: 'ADD',
<add> message: message
<add> }
<add>};
<add>
<add>// change code below this line
<add>
<add>const mapDispatchToProps = (dispatch) => {
<add> return {
<add> submitNewMessage: function(message) {
<add> dispatch(addMessage(message));
<add> }
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/map-state-to-props.chinese.md
<ide> id: 5a24c314108439a4d4036145
<ide> title: Map State to Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将状态映射到道具
<add>forumTopicId: 301433
<add>localeTitle: 映射 State 到 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>Provider</code>组件允许您为React组件提供<code>state</code>和<code>dispatch</code> ,但您必须准确指定所需的状态和操作。这样,您可以确保每个组件只能访问所需的状态。您可以通过创建两个函数来完成此任务: <code>mapStateToProps()</code>和<code>mapDispatchToProps()</code> 。在这些函数中,您可以声明要访问的状态段以及需要分配的操作创建者。一旦这些功能到位,您将看到如何使用React Redux <code>connect</code>方法在另一个挑战中将它们连接到您的组件。 <strong>注意:</strong>在幕后,React Redux使用<code>store.subscribe()</code>方法实现<code>mapStateToProps()</code> 。 </section>
<add><section id='description'>
<add><code>Provider</code>可向 React 组件提供<code>state</code>和<code>dispatch</code>,但你必须确切地指定所需要的 state 和 actions,以确保每个组件只能访问所需的 state。完成这个任务,你需要创建两个函数:<code>mapStateToProps()</code>、<code>mapDispatchToProps()</code>。
<add>在这两个函数中,声明 state 中函数所要访问的部分及需要 dispatch 的创建 action 的函数。完成这些,我们就可以迎接下一个挑战,学习如何使用 React Redux 的<code>connect</code>方法来把函数连接到组件了。
<add><strong>注意:</strong> 在幕后,React Redux 用<code>store.subscribe()</code>方法来实现<code>mapStateToProps()</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个函数<code>mapStateToProps()</code> 。此函数应将<code>state</code>作为参数,然后返回将该状态映射到特定属性名称的对象。您可以通过<code>props</code>访问这些属性。由于此示例将应用程序的整个状态保存在单个数组中,因此您可以将整个状态传递给组件。在要返回的对象中创建属性<code>messages</code> ,并将其设置为<code>state</code> 。 </section>
<add><section id='instructions'>
<add>创建<code>mapStateToProps()</code>函数,以<code>state</code>为参数,然后返回一个对象,该对象把 state 映射到特定属性名上,这些属性能通过<code>props</code>访问组件。由于此示例把 app 应用的整个状态保存在单一数组中,你可把整个状态传给组件。在返回的对象中创建<code>messages</code>属性,并设置为<code>state</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: const <code>state</code>应该是一个空数组。
<add> - text: 常量<code>state</code>应为空数组。
<ide> testString: assert(Array.isArray(state) && state.length === 0);
<del> - text: <code>mapStateToProps</code>应该是一个函数。
<add> - text: <code>mapStateToProps</code>应为函数。
<ide> testString: assert(typeof mapStateToProps === 'function');
<del> - text: <code>mapStateToProps</code>应该返回一个对象。
<add> - text: <code>mapStateToProps</code>应返还一个对象。
<ide> testString: assert(typeof mapStateToProps() === 'object');
<del> - text: 将数组作为状态传递给<code>mapStateToProps</code>应该返回分配给<code>messages</code>键的数组。
<add> - text: 把 state 数组传入<code>mapStateToProps</code>后应返回赋值给<code>messages</code>键的数组。
<ide> testString: assert(mapStateToProps(['messages']).messages.pop() === 'messages');
<ide>
<ide> ```
<ide> tests:
<ide> ```jsx
<ide> const state = [];
<ide>
<del>// change code below this line
<add>// 请在本行以下添加你的代码
<ide>
<ide> ```
<ide>
<ide> const state = [];
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const state = [];
<add>
<add>// change code below this line
<add>
<add>const mapStateToProps = (state) => {
<add> return {
<add> messages: state
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/moving-forward-from-here.chinese.md
<ide> id: 5a24c314108439a4d403614a
<ide> title: Moving Forward From Here
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<add>forumTopicId: 301434
<ide> localeTitle: 从这里前进
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">恭喜!你完成了React和Redux的课程。在继续之前,最后一项值得指出。通常,您不会在这样的代码编辑器中编写React应用程序。如果您在自己的计算机上使用npm和文件系统,这个挑战可以让您一瞥语法的样子。代码看起来应该类似,除了使用<code>import</code>语句(这些语句提取了在挑战中为您提供的所有依赖项)。 “使用npm管理包”部分更详细地介绍了npm。最后,编写React和Redux代码通常需要一些配置。这可能很快变得复杂。如果您有兴趣在自己的机器上进行实验,可以配置<a id="CRA" target="_blank" href="https://github.com/facebookincubator/create-react-app">Create React App</a>并准备就绪。或者,您可以在CodePen中启用Babel作为JavaScript预处理器,将React和ReactDOM添加为外部JavaScript资源,并在那里工作。 </section>
<add><section id='description'>
<add>恭喜你完成了 React 和 Redux 的所有课程!在继续前进前,还有一点值得我们注意。通常,我们不会在这样的编辑器中编写 React 应用代码。如果你在自己的计算机上使用 npm 和文件系统,这个挑战可让你一瞥 React 应用的语法之貌。除了使用<code>import</code>语句(这些语句引入了各挑战中提供的所有依赖关系),其代码看起来类似。“管理包(含 npm)”这一节更详细地介绍了 npm。
<add>最后,写 React 和 Redux 的代码通常需要一些配置,且很快会变得复杂起来。如果你想在自己的机器上尝试写代码,点击链接
<add><a id='CRA' target ='_blank' href='https://github.com/facebookincubator/create-react-app'>创建 React App </a>可获取已配置好的现成代码。
<add>另一种做法是在 CodePen 中启用 Babel 作为 JavaScript 预处理器,将 React 和 ReactDOM 添加为外部 JavaScript 资源,在那里编写应用。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">记录消息<code>'Now I know React and Redux!'</code>到控制台。 </section>
<add><section id='instructions'>
<add>把<code>'Now I know React and Redux!'</code>这一消息输出到控制台。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 消息<code>Now I know React and Redux!</code>应该登录到控制台。
<add> - text: <code>Now I know React and Redux!</code>这一消息应输出到控制台。
<ide> testString: getUserInput => assert(/console\s*\.\s*log\s*\(\s*('|"|`)Now I know React and Redux!\1\s*\)/.test(getUserInput('index')));
<ide>
<ide> ```
<ide> tests:
<ide> // document.getElementById('root')
<ide> // );
<ide>
<del>// change code below this line
<add>// 请在本行以下添加你的代码
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>console.log('Now I know React and Redux!');
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react.chinese.md
<ide> id: 5a24c314108439a4d4036144
<ide> title: Use Provider to Connect Redux to React
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用Provider将Redux连接到React
<add>forumTopicId: 301435
<add>localeTitle: 使用 Provider 连接 Redux 和 React
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在上一个挑战中,您创建了一个Redux存储来处理messages数组并创建了一个用于添加新消息的操作。下一步是提供对Redux存储的React访问以及分派更新所需的操作。 React Redux提供了<code>react-redux</code>包来帮助完成这些任务。 React Redux提供了一个小API,它有两个关键特性: <code>Provider</code>和<code>connect</code> 。另一个挑战包括<code>connect</code> 。 <code>Provider</code>是React Redux的一个包装组件,它包装了你的React应用程序。然后,此包装器允许您访问整个组件树中的Redux <code>store</code>和<code>dispatch</code>功能。 <code>Provider</code>需要两个道具,Redux商店和应用程序的子组件。为App组件定义<code>Provider</code>可能如下所示: <blockquote> <Provider store = {store}> <br> <应用/> <br> </提供商> </blockquote></section>
<add><section id='description'>
<add>在上一挑战中,你创建了 Redux store 和 action,分别用于处理消息数组和添加新消息。下一步要为 React 提供访问 Redux store 及发起更新所需的 actions。<code>react-redux</code>包可帮助我们完成这些任务。
<add>React Redux 提供的 API 有两个关键的功能:<code>Provider</code>和<code>connect</code>。你会在另一个挑战中学<code>connect</code>。<code>Provider</code>是 React Redux 包装 React 应用的 wrapper 组件,它允许你访问整个组件树中的 Redux<code>store</code>及<code>dispatch(分发)</code>方法。<code>Provider</code>需要两个 props:Redux store 和 APP 应用的子组件。用于 APP 组件的<code>Provider</code>可这样定义:
<add>
<add>```jsx
<add><Provider store={store}>
<add> <App/>
<add></Provider>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器现在显示过去几个挑战中的所有Redux和React代码。它包括Redux存储,操作和<code>DisplayMessages</code>组件。唯一的新部分是底部的<code>AppWrapper</code>组件。使用此顶级组件从<code>ReactRedux</code>呈现<code>Provider</code> ,并将Redux存储作为prop传递。然后将<code>DisplayMessages</code>组件渲染为子级。完成后,您应该看到React组件呈现给页面。 <strong>注意:</strong> React Redux在此处可用作全局变量,因此您可以使用点表示法访问提供程序。编辑器中的代码利用了这一点并将其设置为一个常量<code>Provider</code>供您在<code>AppWrapper</code>渲染方法中使用。 </section>
<add><section id='instructions'>
<add>此时,编辑器上显示的是过去几个挑战中所有代码,包括 Redux store、actions、<code>DisplayMessages</code>组件。新出现的代码是底部的<code>AppWrapper</code>组件,这个顶级组件可用于渲染<code>ReactRedux</code>的<code>Provider</code>,并把 Redux 的 store 作为 props 传入。接着,渲染<code>DisplayMessages</code>为子组件。完成这些任务后,你会看到 React 组件渲染到页面上。
<add><strong>注意:</strong> React Redux 在此可作全局变量,因此你可通过点号表示法访问 Provider。利用这一点,编辑器上的代码把<code>Provider</code>设置为常量,便于你在<code>AppWrapper</code>渲染方法中使用。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>AppWrapper</code>应该渲染。
<add> - text: <code>AppWrapper</code>应渲染。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })());
<del> - text: <code>Provider</code>包装器组件应该具有传递给它的<code>store</code>支柱,等于Redux存储。
<add> - text: <code>Provider</code>组件应传入相当于 Redux store 的<code>store</code>参数。
<ide> testString: getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return getUserInput('index').replace(/\s/g,'').includes('<Providerstore={store}>'); })());
<del> - text: <code>DisplayMessages</code>应该呈现为<code>AppWrapper</code> 。
<add> - text: <code>DisplayMessages</code>应渲染为<code>AppWrapper</code>的子组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').find('DisplayMessages').length === 1; })());
<del> - text: <code>DisplayMessages</code>组件应该呈现h2,input,button和<code>ul</code>元素。
<add> - text: <code>DisplayMessages</code>组件应渲染 h2、input、button、<code>ul</code>四个元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h2').length === 1 && mockedComponent.find('button').length === 1 && mockedComponent.find('ul').length === 1; })());
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<del>// Redux Code:
<add>// Redux 代码:
<ide> const ADD = 'ADD';
<ide>
<ide> const addMessage = (message) => {
<ide> const messageReducer = (state = [], action) => {
<ide>
<ide> const store = Redux.createStore(messageReducer);
<ide>
<del>// React Code:
<add>// React 代码:
<ide>
<ide> class DisplayMessages extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: ",
<add> input: '',
<ide> messages: []
<ide> }
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class DisplayMessages extends React.Component {
<ide> submitMessage() {
<ide> const currentMessage = this.state.input;
<ide> this.setState({
<del> input: ",
<add> input: '',
<ide> messages: this.state.messages.concat(currentMessage)
<ide> });
<ide> }
<ide> class DisplayMessages extends React.Component {
<ide> const Provider = ReactRedux.Provider;
<ide>
<ide> class AppWrapper extends React.Component {
<del> // render the Provider here
<add> // 在此渲染 Provider
<ide>
<del> // change code above this line
<add> // 请在本行以上添加你的代码
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class AppWrapper extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<AppWrapper />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<del>```
<add>// Redux Code:
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>const store = Redux.createStore(messageReducer);
<add>
<add>// React Code:
<add>
<add>class DisplayMessages extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> messages: []
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> const currentMessage = this.state.input;
<add> this.setState({
<add> input: '',
<add> messages: this.state.messages.concat(currentMessage)
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.state.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<ide>
<del>/section>
<add>const Provider = ReactRedux.Provider;
<add>
<add>class AppWrapper extends React.Component {
<add> // change code below this line
<add> render() {
<add> return (
<add> <Provider store = {store}>
<add> <DisplayMessages/>
<add> </Provider>
<add> );
<add> }
<add> // change code above this line
<add>};
<add>```
<add></section> | 10 |
Ruby | Ruby | clarify application of homebrew_artifact_domain | b2796ec7fb9641becb8f8486b3695668447e2ee3 | <ide><path>Library/Homebrew/env_config.rb
<ide> module EnvConfig
<ide> description: "Prefix all download URLs, including those for bottles, with this value. " \
<ide> "For example, `HOMEBREW_ARTIFACT_DOMAIN=http://localhost:8080` will cause a " \
<ide> "formula with the URL `https://example.com/foo.tar.gz` to instead download from " \
<del> "`http://localhost:8080/example.com/foo.tar.gz`.",
<add> "`http://localhost:8080/https://example.com/foo.tar.gz`. " \
<add> "Bottle URLs however, have their domain replaced with this prefix. " \
<add> "Using the same value for example, would cause data hosted under " \
<add> "`https://ghcr.io/v2/homebrew/core/gettext/manifests/0.21` " \
<add> "to be instead downloaded from " \
<add> "`http://localhost:8080/v2/homebrew/core/gettext/manifests/0.21`",
<ide> },
<ide> HOMEBREW_AUTO_UPDATE_SECS: {
<ide> description: "Run `brew update` once every `HOMEBREW_AUTO_UPDATE_SECS` seconds before some commands, " \
<ide><path>Library/Homebrew/test/download_strategies/curl_spec.rb
<ide> let(:url) { "https://example.com/foo.tar.gz" }
<ide> let(:version) { "1.2.3" }
<ide> let(:specs) { { user: "download:123456" } }
<add> let(:artifact_domain) { nil }
<ide>
<ide> it "parses the opts and sets the corresponding args" do
<ide> expect(strategy.send(:_curl_args)).to eq(["--user", "download:123456"])
<ide> end
<ide>
<ide> describe "#fetch" do
<ide> before do
<add> allow(Homebrew::EnvConfig).to receive(:artifact_domain).and_return(artifact_domain)
<add>
<ide> strategy.temporary_path.dirname.mkpath
<ide> FileUtils.touch strategy.temporary_path
<ide> end
<ide> strategy.fetch
<ide> end
<ide> end
<add>
<add> context "with artifact_domain set" do
<add> let(:artifact_domain) { "https://mirror.example.com/oci" }
<add>
<add> context "with an asset hosted under example.com" do
<add> let(:status) { instance_double(Process::Status, success?: true, exitstatus: 0) }
<add>
<add> it "prefixes the URL unchanged" do
<add> expect(strategy).to receive(:system_command).with(
<add> /curl/,
<add> hash_including(args: array_including_cons("#{artifact_domain}/#{url}")),
<add> )
<add> .at_least(:once)
<add> .and_return(SystemCommand::Result.new(["curl"], [""], status, secrets: []))
<add>
<add> strategy.fetch
<add> end
<add> end
<add>
<add> context "with an asset hosted under #{GitHubPackages::URL_DOMAIN} (HTTP)" do
<add> let(:resource_path) { "v2/homebrew/core/spec/manifests/0.0" }
<add> let(:url) { "http://#{GitHubPackages::URL_DOMAIN}/#{resource_path}" }
<add> let(:status) { instance_double(Process::Status, success?: true, exitstatus: 0) }
<add>
<add> it "rewrites the URL correctly" do
<add> expect(strategy).to receive(:system_command).with(
<add> /curl/,
<add> hash_including(args: array_including_cons("#{artifact_domain}/#{resource_path}")),
<add> )
<add> .at_least(:once)
<add> .and_return(SystemCommand::Result.new(["curl"], [""], status, secrets: []))
<add>
<add> strategy.fetch
<add> end
<add> end
<add>
<add> context "with an asset hosted under #{GitHubPackages::URL_DOMAIN} (HTTPS)" do
<add> let(:resource_path) { "v2/homebrew/core/spec/manifests/0.0" }
<add> let(:url) { "https://#{GitHubPackages::URL_DOMAIN}/#{resource_path}" }
<add> let(:status) { instance_double(Process::Status, success?: true, exitstatus: 0) }
<add>
<add> it "rewrites the URL correctly" do
<add> expect(strategy).to receive(:system_command).with(
<add> /curl/,
<add> hash_including(args: array_including_cons("#{artifact_domain}/#{resource_path}")),
<add> )
<add> .at_least(:once)
<add> .and_return(SystemCommand::Result.new(["curl"], [""], status, secrets: []))
<add>
<add> strategy.fetch
<add> end
<add> end
<add> end
<ide> end
<ide>
<ide> describe "#cached_location" do | 2 |
Javascript | Javascript | avoid extra look for getting dependencies | 95702bd1ae6d169779f7085a7e69974571a8d557 | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> _processModuleDependencies(module, callback) {
<ide> const dependencies = new Map();
<ide>
<add> const sortedDependencies = [];
<add>
<ide> let currentBlock = module;
<ide>
<ide> let factoryCacheKey;
<ide> let factoryCacheValue;
<add> let factoryCacheValue2;
<ide> let listCacheKey;
<ide> let listCacheValue;
<ide>
<ide> class Compilation {
<ide> if (resourceIdent) {
<ide> const constructor = dep.constructor;
<ide> let innerMap;
<add> let factory;
<ide> if (factoryCacheKey === constructor) {
<ide> innerMap = factoryCacheValue;
<ide> if (listCacheKey === resourceIdent) {
<ide> listCacheValue.push(dep);
<ide> return;
<ide> }
<ide> } else {
<del> const factory = this.dependencyFactories.get(dep.constructor);
<add> factory = this.dependencyFactories.get(dep.constructor);
<ide> if (factory === undefined) {
<ide> throw new Error(
<ide> `No module factory available for dependency type: ${dep.constructor.name}`
<ide> class Compilation {
<ide> }
<ide> factoryCacheKey = constructor;
<ide> factoryCacheValue = innerMap;
<add> factoryCacheValue2 = factory;
<ide> }
<ide> let list = innerMap.get(resourceIdent);
<del> if (list === undefined) innerMap.set(resourceIdent, (list = []));
<add> if (list === undefined) {
<add> innerMap.set(resourceIdent, (list = []));
<add> sortedDependencies.push({
<add> factory: factoryCacheValue2,
<add> dependencies: list,
<add> originModule: module
<add> });
<add> }
<ide> list.push(dep);
<ide> listCacheKey = resourceIdent;
<ide> listCacheValue = list;
<ide> class Compilation {
<ide> return callback(e);
<ide> }
<ide>
<del> const sortedDependencies = [];
<del>
<del> for (const [factory, innerMap] of dependencies) {
<del> for (const dependencies of innerMap.values()) {
<del> sortedDependencies.push({
<del> factory,
<del> dependencies,
<del> originModule: module
<del> });
<del> }
<del> }
<del>
<ide> if (sortedDependencies.length === 0) {
<ide> callback();
<ide> return; | 1 |
Text | Text | update build badge | 45a709f16ecd1a17d36ffce80786aeb222036d14 | <ide><path>README.md
<ide> It helps you write applications that behave consistently, run in different envir
<ide> You can use Redux together with [React](https://reactjs.org), or with any other view library.
<ide> It is tiny (2kB, including dependencies), and has a rich ecosystem of addons.
<ide>
<del>
<add>
<ide> [](https://www.npmjs.com/package/redux)
<ide> [](https://www.npmjs.com/package/redux)
<ide> [](https://discord.gg/0ZcbPKXt5bZ6au5t) | 1 |
Text | Text | fix sentence in with-context-api example | 3d3855093a6e3d76c3aeb5cb385c8f2f6ef3788c | <ide><path>examples/with-context-api/README.md
<ide> now
<ide>
<ide> This example shows how to use react context api in our app.
<ide>
<del>It provides an example of using `pages/_app.js` to include include the context api provider and then shows how both the `pages/index.js` and `pages/about.js` can both share the same data using the context api consumer.
<add>It provides an example of using `pages/_app.js` to include the context api provider and then shows how both the `pages/index.js` and `pages/about.js` can both share the same data using the context api consumer.
<ide>
<ide> The `pages/index.js` shows how to, from the home page, increment and decrement the context data by 1 (a hard code value in the context provider itself).
<ide> | 1 |
Mixed | Javascript | remove unused parameter, improve docs | ba0b4e43e442926bfb9389a42aa7393f91e6748a | <ide><path>doc/api/crypto.md
<ide> otherwise `err` will be `null`. By default, the successfully generated
<ide> `derivedKey` will be passed to the callback as a [`Buffer`][]. An error will be
<ide> thrown if any of the input arguments specify invalid values or types.
<ide>
<add>If `digest` is `null`, `'sha1'` will be used. This behavior will be deprecated
<add>in a future version of Node.js.
<add>
<ide> The `iterations` argument must be a number set as high as possible. The
<ide> higher the number of iterations, the more secure the derived key will be,
<ide> but will take a longer amount of time to complete.
<ide> applied to derive a key of the requested byte length (`keylen`) from the
<ide> If an error occurs an `Error` will be thrown, otherwise the derived key will be
<ide> returned as a [`Buffer`][].
<ide>
<add>If `digest` is `null`, `'sha1'` will be used. This behavior will be deprecated
<add>in a future version of Node.js.
<add>
<ide> The `iterations` argument must be a number set as high as possible. The
<ide> higher the number of iterations, the more secure the derived key will be,
<ide> but will take a longer amount of time to complete.
<ide><path>lib/internal/crypto/pbkdf2.js
<ide> function pbkdf2(password, salt, iterations, keylen, digest, callback) {
<ide> }
<ide>
<ide> ({ password, salt, iterations, keylen, digest } =
<del> check(password, salt, iterations, keylen, digest, callback));
<add> check(password, salt, iterations, keylen, digest));
<ide>
<ide> if (typeof callback !== 'function')
<ide> throw new ERR_INVALID_CALLBACK();
<ide> function pbkdf2(password, salt, iterations, keylen, digest, callback) {
<ide>
<ide> function pbkdf2Sync(password, salt, iterations, keylen, digest) {
<ide> ({ password, salt, iterations, keylen, digest } =
<del> check(password, salt, iterations, keylen, digest, pbkdf2Sync));
<add> check(password, salt, iterations, keylen, digest));
<ide> const keybuf = Buffer.alloc(keylen);
<ide> handleError(keybuf, password, salt, iterations, digest);
<ide> const encoding = getDefaultEncoding();
<ide> if (encoding === 'buffer') return keybuf;
<ide> return keybuf.toString(encoding);
<ide> }
<ide>
<del>function check(password, salt, iterations, keylen, digest, callback) {
<add>function check(password, salt, iterations, keylen, digest) {
<ide> if (typeof digest !== 'string') {
<ide> if (digest !== null)
<ide> throw new ERR_INVALID_ARG_TYPE('digest', ['string', 'null'], digest); | 2 |
Python | Python | fix small use_cache typo in the docs | 942fa8ced860775e4fad556f5bc4fb99b1eef618 | <ide><path>src/transformers/generation_tf_utils.py
<ide> def generate(
<ide> [What are attention masks?](../glossary#attention-mask)
<ide> decoder_start_token_id (`int`, *optional*):
<ide> If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
<del> use_cache: (`bool`, *optional*, defaults to `True`):
<add> use_cache (`bool`, *optional*, defaults to `True`):
<ide> Whether or not the model should use the past last key/values attentions (if applicable to the model) to
<ide> speed up decoding.
<ide> output_attentions (`bool`, *optional*, defaults to `False`):
<ide><path>src/transformers/generation_utils.py
<ide> def generate(
<ide> as `input_ids` that masks the pad token. [What are attention masks?](../glossary#attention-mask)
<ide> decoder_start_token_id (`int`, *optional*):
<ide> If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
<del> use_cache: (`bool`, *optional*, defaults to `True`):
<add> use_cache (`bool`, *optional*, defaults to `True`):
<ide> Whether or not the model should use the past last key/values attentions (if applicable to the model) to
<ide> speed up decoding.
<ide> num_beam_groups (`int`, *optional*, defaults to `model.config.num_beam_groups` or 1 if the config does not set any value): | 2 |
Python | Python | add `is_decoder` attribute to `pretrainedconfig` | 488a6641513face9c03b537b6fe3210dbdb39f36 | <ide><path>transformers/configuration_utils.py
<ide> def __init__(self, **kwargs):
<ide> self.torchscript = kwargs.pop('torchscript', False)
<ide> self.use_bfloat16 = kwargs.pop('use_bfloat16', False)
<ide> self.pruned_heads = kwargs.pop('pruned_heads', {})
<add> self.is_decoder = kwargs.pop('is_decoder', False)
<ide>
<ide> def save_pretrained(self, save_directory):
<ide> """ Save a configuration object to the directory `save_directory`, so that it | 1 |
Go | Go | add instructions on how to get help on commands | d128d9e669d840160f9f2357324f710d59a7a7d7 | <ide><path>docker/flags.go
<ide> func init() {
<ide> } {
<ide> help += fmt.Sprintf(" %-10.10s%s\n", command[0], command[1])
<ide> }
<add> help += "\nRun 'docker COMMAND --help' for more information on a command."
<ide> fmt.Fprintf(os.Stderr, "%s\n", help)
<ide> }
<ide> } | 1 |
PHP | PHP | apply fixes from styleci | 2b5d80b51ec020641fdfb3d2be255385a9c337ea | <ide><path>src/Illuminate/Bus/PendingBatch.php
<ide> public function dispatchAfterResponse()
<ide> /**
<ide> * Dispatch an existing batch.
<ide> *
<del> * @param \Illuminate\Bus\Batch $batch
<add> * @param \Illuminate\Bus\Batch $batch
<ide> * @return void
<ide> *
<ide> * @throws \Throwable | 1 |
Ruby | Ruby | initialize ivars in tests | 3abd0593a62e2be118b783efe55f63ab3324a4d7 | <ide><path>actionpack/test/controller/caching_test.rb
<ide> def forbidden
<ide>
<ide> def with_layout
<ide> @cache_this = MockTime.now.to_f.to_s
<add> @title = nil
<ide> render :text => @cache_this, :layout => true
<ide> end
<ide>
<ide><path>actionpack/test/controller/render_other_test.rb
<ide> def render_simon_says
<ide>
<ide> private
<ide> def default_render
<add> @alternate_default_render ||= nil
<ide> if @alternate_default_render
<ide> @alternate_default_render.call
<ide> else
<ide><path>actionpack/test/controller/webservice_test.rb
<ide> def rescue_action(e) raise end
<ide>
<ide> def setup
<ide> @controller = TestController.new
<add> @integration_session = nil
<ide> end
<ide>
<ide> def test_check_parameters | 3 |
Ruby | Ruby | remove unneeded deprecation silence | d06d71bb54b17d9a7e1b9d1e7084c2bc1e7a38bc | <ide><path>actionview/test/template/render_test.rb
<ide> def test_render_does_not_use_unregistered_extension_and_template_handler
<ide> end
<ide>
<ide> def test_render_ignores_templates_with_malformed_template_handlers
<del> ActiveSupport::Deprecation.silence do
<del> %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name|
<del> assert File.exist?(File.expand_path("#{FIXTURE_LOAD_PATH}/test/malformed/#{name}~")), "Malformed file (#{name}~) which should be ignored does not exists"
<del> assert_raises(ActionView::MissingTemplate) { @view.render(file: "test/malformed/#{name}") }
<del> end
<add> %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name|
<add> assert File.exist?(File.expand_path("#{FIXTURE_LOAD_PATH}/test/malformed/#{name}~")), "Malformed file (#{name}~) which should be ignored does not exists"
<add> assert_raises(ActionView::MissingTemplate) { @view.render(file: "test/malformed/#{name}") }
<ide> end
<ide> end
<ide> | 1 |
Python | Python | fix decode error for ssh log | daedc998519f534f604fdecb86b101fa4eb5b5dd | <ide><path>airflow/providers/ssh/operators/ssh.py
<ide> def execute(self, context) -> Union[bytes, str, bool]:
<ide> if recv.recv_ready():
<ide> line = stdout.channel.recv(len(recv.in_buffer))
<ide> agg_stdout += line
<del> self.log.info(line.decode('utf-8').strip('\n'))
<add> self.log.info(line.decode('utf-8', 'replace').strip('\n'))
<ide> if recv.recv_stderr_ready():
<ide> line = stderr.channel.recv_stderr(len(recv.in_stderr_buffer))
<ide> agg_stderr += line
<del> self.log.warning(line.decode('utf-8').strip('\n'))
<add> self.log.warning(line.decode('utf-8', 'replace').strip('\n'))
<ide> if (
<ide> stdout.channel.exit_status_ready()
<ide> and not stderr.channel.recv_stderr_ready() | 1 |
Javascript | Javascript | add option to indicate bundle encoding | 15006cf0b482bedd20fa407971c26e450ca083da | <ide><path>local-cli/bundle/__tests__/saveBundleAndMap-test.js
<ide> describe('saveBundleAndMap', () => {
<ide> saveBundleAndMap(
<ide> codeWithMap,
<ide> 'ios',
<del> bundleOutput
<add> bundleOutput,
<add> 'utf8',
<ide> );
<ide>
<del> expect(fs.writeFileSync.mock.calls[0]).toEqual([bundleOutput, code]);
<add> expect(fs.writeFileSync.mock.calls[0]).toEqual([bundleOutput, code, 'utf8']);
<ide> });
<ide>
<ide> it('should save sourcemaps if required so', () => {
<ide> describe('saveBundleAndMap', () => {
<ide> codeWithMap,
<ide> 'ios',
<ide> bundleOutput,
<add> 'utf8',
<ide> sourceMapOutput
<ide> );
<ide>
<ide><path>local-cli/bundle/buildBundle.js
<ide> function buildBundle(args, config) {
<ide> outputBundle,
<ide> args.platform,
<ide> args['bundle-output'],
<add> args['bundle-encoding'],
<ide> args['sourcemap-output'],
<ide> args['assets-dest']
<ide> ));
<ide><path>local-cli/bundle/bundleCommandLineArgs.js
<ide> module.exports = [
<ide> description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
<ide> type: 'string',
<ide> required: true,
<add> }, {
<add> command: 'bundle-encoding',
<add> description: 'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).',
<add> type: 'string',
<add> default: 'utf8',
<ide> }, {
<ide> command: 'sourcemap-output',
<ide> description: 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map',
<ide><path>local-cli/bundle/saveBundleAndMap.js
<ide> function saveBundleAndMap(
<ide> codeWithMap,
<ide> platform,
<ide> bundleOutput,
<add> encoding,
<ide> sourcemapOutput,
<ide> assetsDest
<ide> ) {
<ide> log('Writing bundle output to:', bundleOutput);
<del> fs.writeFileSync(bundleOutput, sign(codeWithMap.code));
<add> fs.writeFileSync(bundleOutput, sign(codeWithMap.code), encoding);
<ide> log('Done writing bundle output');
<ide>
<ide> if (sourcemapOutput) { | 4 |
Python | Python | make like= in python functions strict | 1d7ad47a7bddfbdcdedbebe81ca87636f2e746ab | <ide><path>numpy/core/_asarray.py
<ide> """
<ide> from .overrides import (
<ide> array_function_dispatch,
<del> array_function_dispatch_like,
<ide> set_array_function_like_doc,
<ide> set_module,
<ide> )
<ide> def asarray(a, dtype=None, order=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _asarray_with_like, a, dtype=dtype, order=order, like=like
<del> )
<add> return _asarray_with_like(a, dtype=dtype, order=order, like=like)
<ide>
<ide> return array(a, dtype, copy=False, order=order)
<ide>
<ide> def asanyarray(a, dtype=None, order=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _asanyarray_with_like, a, dtype=dtype, order=order, like=like
<del> )
<add> return _asanyarray_with_like(a, dtype=dtype, order=order, like=like)
<ide>
<ide> return array(a, dtype, copy=False, order=order, subok=True)
<ide>
<ide> def ascontiguousarray(a, dtype=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _ascontiguousarray_with_like, a, dtype=dtype, like=like
<del> )
<add> return _ascontiguousarray_with_like(a, dtype=dtype, like=like)
<ide>
<ide> return array(a, dtype, copy=False, order='C', ndmin=1)
<ide>
<ide> def asfortranarray(a, dtype=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _asfortranarray_with_like, a, dtype=dtype, like=like
<del> )
<add> return _asfortranarray_with_like(a, dtype=dtype, like=like)
<ide>
<ide> return array(a, dtype, copy=False, order='F', ndmin=1)
<ide>
<ide> def require(a, dtype=None, requirements=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _require_with_like,
<add> return _require_with_like(
<ide> a,
<ide> dtype=dtype,
<ide> requirements=requirements,
<ide><path>numpy/core/numeric.py
<ide> from . import overrides
<ide> from . import umath
<ide> from . import shape_base
<del>from .overrides import (
<del> array_function_dispatch_like, set_array_function_like_doc, set_module
<del> )
<add>from .overrides import set_array_function_like_doc, set_module
<ide> from .umath import (multiply, invert, sin, PINF, NAN)
<ide> from . import numerictypes
<ide> from .numerictypes import longlong, intc, int_, float_, complex_, bool_
<ide> def ones(shape, dtype=None, order='C', *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _ones_with_like, shape, dtype=dtype, order=order, like=like
<del> )
<add> return _ones_with_like(shape, dtype=dtype, order=order, like=like)
<ide>
<ide> a = empty(shape, dtype, order)
<ide> multiarray.copyto(a, 1, casting='unsafe')
<ide> def full(shape, fill_value, dtype=None, order='C', *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _full_with_like,
<del> shape,
<del> fill_value,
<del> dtype=dtype,
<del> order=order,
<del> like=like,
<del> )
<add> return _full_with_like(shape, fill_value, dtype=dtype, order=order, like=like)
<ide>
<ide> if dtype is None:
<ide> fill_value = asarray(fill_value)
<ide> def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _fromfunction_with_like,
<del> function,
<del> shape,
<del> dtype=dtype,
<del> like=like,
<del> **kwargs,
<del> )
<add> return _fromfunction_with_like(function, shape, dtype=dtype, like=like, **kwargs)
<ide>
<ide> args = indices(shape, dtype=dtype)
<ide> return function(*args, **kwargs)
<ide> def identity(n, dtype=None, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _identity_with_like, n, dtype=dtype, like=like
<del> )
<add> return _identity_with_like(n, dtype=dtype, like=like)
<ide>
<ide> from numpy import eye
<ide> return eye(n, dtype=dtype, like=like)
<ide><path>numpy/lib/npyio.py
<ide> from ._datasource import DataSource
<ide> from numpy.core import overrides
<ide> from numpy.core.multiarray import packbits, unpackbits
<del>from numpy.core.overrides import (
<del> array_function_dispatch_like, set_array_function_like_doc, set_module
<del> )
<add>from numpy.core.overrides import set_array_function_like_doc, set_module
<ide> from numpy.core._internal import recursive
<ide> from ._iotools import (
<ide> LineSplitter, NameValidator, StringConverter, ConverterError,
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> """
<ide>
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _loadtxt_with_like, fname, dtype=dtype, comments=comments,
<del> delimiter=delimiter, converters=converters, skiprows=skiprows,
<del> usecols=usecols, unpack=unpack, ndmin=ndmin, encoding=encoding,
<add> return _loadtxt_with_like(
<add> fname, dtype=dtype, comments=comments, delimiter=delimiter,
<add> converters=converters, skiprows=skiprows, usecols=usecols,
<add> unpack=unpack, ndmin=ndmin, encoding=encoding,
<ide> max_rows=max_rows, like=like
<ide> )
<ide>
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> """
<ide>
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _genfromtxt_with_like, fname, dtype=dtype, comments=comments,
<del> delimiter=delimiter, skip_header=skip_header,
<del> skip_footer=skip_footer, converters=converters,
<del> missing_values=missing_values, filling_values=filling_values,
<del> usecols=usecols, names=names, excludelist=excludelist,
<del> deletechars=deletechars, replace_space=replace_space,
<del> autostrip=autostrip, case_sensitive=case_sensitive,
<del> defaultfmt=defaultfmt, unpack=unpack, usemask=usemask, loose=loose,
<add> return _genfromtxt_with_like(
<add> fname, dtype=dtype, comments=comments, delimiter=delimiter,
<add> skip_header=skip_header, skip_footer=skip_footer,
<add> converters=converters, missing_values=missing_values,
<add> filling_values=filling_values, usecols=usecols, names=names,
<add> excludelist=excludelist, deletechars=deletechars,
<add> replace_space=replace_space, autostrip=autostrip,
<add> case_sensitive=case_sensitive, defaultfmt=defaultfmt,
<add> unpack=unpack, usemask=usemask, loose=loose,
<ide> invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding,
<ide> like=like
<ide> )
<ide><path>numpy/lib/twodim_base.py
<ide> asarray, where, int8, int16, int32, int64, empty, promote_types, diagonal,
<ide> nonzero
<ide> )
<del>from numpy.core.overrides import (
<del> array_function_dispatch_like, set_array_function_like_doc, set_module
<del> )
<add>from numpy.core.overrides import set_array_function_like_doc, set_module
<ide> from numpy.core import overrides
<ide> from numpy.core import iinfo
<ide>
<ide> def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _eye_with_like,
<del> N,
<del> M=M,
<del> k=k,
<del> dtype=dtype,
<del> order=order,
<del> like=like
<del> )
<add> return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)
<ide> if M is None:
<ide> M = N
<ide> m = zeros((N, M), dtype=dtype, order=order)
<ide> def tri(N, M=None, k=0, dtype=float, *, like=None):
<ide>
<ide> """
<ide> if like is not None:
<del> return array_function_dispatch_like(
<del> _tri_with_like, N, M=M, k=k, dtype=dtype, like=like
<del> )
<add> return _tri_with_like(N, M=M, k=k, dtype=dtype, like=like)
<ide>
<ide> if M is None:
<ide> M = N | 4 |
Ruby | Ruby | pass the actual filter, not a string | 19b9f7ba334108bd669ec6ae3bdf11d707a7d689 | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def apply(next_callback)
<ide> result = user_callback.call target, value
<ide> env.halted = halted_lambda.call result
<ide> if env.halted
<del> target.send :halted_callback_hook, @filter.inspect
<add> target.send :halted_callback_hook, @filter
<ide> end
<ide> end
<ide> next_callback.call env
<ide><path>activesupport/test/callbacks_test.rb
<ide> def test_termination
<ide> def test_termination_invokes_hook
<ide> terminator = CallbackTerminator.new
<ide> terminator.save
<del> assert_equal ":second", terminator.halted
<add> assert_equal :second, terminator.halted
<ide> end
<ide>
<ide> def test_block_never_called_if_terminated | 2 |
PHP | PHP | fix cs errors | 5cb5c142b3165eb8d1d21e05724338e55352f76b | <ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> */
<ide> class ConnectionTest extends TestCase
<ide> {
<del>
<ide> public $fixtures = ['core.Things'];
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php
<ide> public function toDatabase($value, Driver $d)
<ide> */
<ide> class ExpressionTypeCastingIntegrationTest extends TestCase
<ide> {
<del>
<ide> public $fixtures = ['core.OrderedUuidItems'];
<ide>
<ide> public function setUp()
<ide><path>tests/TestCase/Database/Schema/CollectionTest.php
<ide> class CollectionTest extends TestCase
<ide> * @var array
<ide> */
<ide> public $fixtures = [
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php
<ide> class TableTest extends TestCase
<ide> 'core.Tags',
<ide> 'core.ArticlesTags',
<ide> 'core.Orders',
<del> 'core.Products'
<add> 'core.Products',
<ide> ];
<ide>
<ide> protected $_map;
<ide><path>tests/TestCase/Datasource/PaginatorTest.php
<ide> class PaginatorTest extends TestCase
<ide> */
<ide> public $fixtures = [
<ide> 'core.Posts', 'core.Articles', 'core.ArticlesTags',
<del> 'core.Authors', 'core.AuthorsTags', 'core.Tags'
<add> 'core.Authors', 'core.AuthorsTags', 'core.Tags',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function getContentTransferEncoding()
<ide> */
<ide> class EmailTest extends TestCase
<ide> {
<del>
<ide> public $fixtures = ['core.Users'];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/AssociationProxyTest.php
<ide> class AssociationProxyTest extends TestCase
<ide> * @var array
<ide> */
<ide> public $fixtures = [
<del> 'core.Articles', 'core.Authors', 'core.Comments'
<add> 'core.Articles', 'core.Authors', 'core.Comments',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/Behavior/BehaviorRegressionTest.php
<ide> class BehaviorRegressionTest extends TestCase
<ide> */
<ide> public $fixtures = [
<ide> 'core.NumberTrees',
<del> 'core.Translates'
<add> 'core.Translates',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/Behavior/CounterCacheBehaviorTest.php
<ide> class CounterCacheBehaviorTest extends TestCase
<ide> 'core.CounterCachePosts',
<ide> 'core.CounterCacheComments',
<ide> 'core.CounterCacheUsers',
<del> 'core.CounterCacheUserCategoryPosts'
<add> 'core.CounterCacheUserCategoryPosts',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/Behavior/TimestampBehaviorTest.php
<ide> class TimestampBehaviorTest extends TestCase
<ide> * @var array
<ide> */
<ide> public $fixtures = [
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php
<ide> class TranslateBehaviorTest extends TestCase
<ide> 'core.SpecialTags',
<ide> 'core.Tags',
<ide> 'core.Comments',
<del> 'core.Translates'
<add> 'core.Translates',
<ide> ];
<ide>
<ide> public function tearDown()
<ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php
<ide> class TreeBehaviorTest extends TestCase
<ide> */
<ide> public $fixtures = [
<ide> 'core.MenuLinkTrees',
<del> 'core.NumberTrees'
<add> 'core.NumberTrees',
<ide> ];
<ide>
<ide> public function setUp()
<ide><path>tests/TestCase/ORM/BindingKeyTest.php
<ide> class BindingKeyTest extends TestCase
<ide> public $fixtures = [
<ide> 'core.AuthUsers',
<ide> 'core.SiteAuthors',
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/CompositeKeysTest.php
<ide> class CompositeKeyTest extends TestCase
<ide> 'core.SiteArticles',
<ide> 'core.SiteArticlesTags',
<ide> 'core.SiteAuthors',
<del> 'core.SiteTags'
<add> 'core.SiteTags',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> class MarshallerTest extends TestCase
<ide> 'core.Comments',
<ide> 'core.SpecialTags',
<ide> 'core.Tags',
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> class QueryRegressionTest extends TestCase
<ide> 'core.SpecialTags',
<ide> 'core.TagsTranslations',
<ide> 'core.Translates',
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> public $autoFixtures = false;
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> class QueryTest extends TestCase
<ide> 'core.Comments',
<ide> 'core.Datatypes',
<ide> 'core.Posts',
<del> 'core.Tags'
<add> 'core.Tags',
<ide> ];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/ResultSetTest.php
<ide> */
<ide> class ResultSetTest extends TestCase
<ide> {
<del>
<ide> public $fixtures = ['core.Articles', 'core.Authors', 'core.Comments'];
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> class TableTest extends TestCase
<ide> 'core.Members',
<ide> 'core.PolymorphicTagged',
<ide> 'core.SiteArticles',
<del> 'core.Users'
<add> 'core.Users',
<ide> ];
<ide>
<ide> /** | 19 |
Javascript | Javascript | remove indexof, using reverse map instead | 683a8f0de8d9155a34f1ba422cc5d12ee4133b9b | <ide><path>src/fonts.js
<ide> var Font = (function Font() {
<ide> tables.push(cmap);
<ide> }
<ide>
<add> var cidToGidMap = properties.cidToGidMap || [];
<add> var gidToCidMap = [0];
<add> for (var j = cidToGidMap.length - 1; j >= 0; j--) {
<add> var gid = cidToGidMap[j];
<add> if (gid)
<add> gidToCidMap[gid] = j;
<add> }
<add>
<ide> var glyphs = [], ids = [];
<ide> var usedUnicodes = [];
<del> var cidToGidMap = properties.cidToGidMap;
<ide> var unassignedUnicodeItems = [];
<ide> for (var i = 1; i < numGlyphs; i++) {
<del> var cid = cidToGidMap ? cidToGidMap.indexOf(i) : i;
<add> var cid = gidToCidMap[i] || i;
<ide> var unicode = this.toUnicode[cid];
<ide> if (!unicode || isSpecialUnicode(unicode) ||
<ide> unicode in usedUnicodes) {
<ide> var Font = (function Font() {
<ide> glyphs.push({ unicode: unicode, code: cid });
<ide> ids.push(i);
<ide> }
<del> // checking if unassigned symbols will fit the user defined symbols
<del> // if those symbols too many, probably they will not be used anyway
<del> if (unassignedUnicodeItems.length <= kSizeOfGlyphArea) {
<del> var unusedUnicode = kCmapGlyphOffset;
<del> for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) {
<del> var i = unassignedUnicodeItems[j];
<del> var cid = cidToGidMap ? cidToGidMap.indexOf(i) : i;
<del> while (unusedUnicode in usedUnicodes)
<del> unusedUnicode++;
<del> var unicode = unusedUnicode++;
<del> this.toUnicode[cid] = unicode;
<del> usedUnicodes[unicode] = true;
<del> glyphs.push({ unicode: unicode, code: cid });
<del> ids.push(i);
<del> }
<add> // trying to fit as many unassigned symbols as we can
<add> // in the range allocated for the user defined symbols
<add> var unusedUnicode = kCmapGlyphOffset;
<add> for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) {
<add> var i = unassignedUnicodeItems[j];
<add> var cid = gidToCidMap[i] || i;
<add> while (unusedUnicode in usedUnicodes)
<add> unusedUnicode++;
<add> if (unusedUnicode >= kCmapGlyphOffset + kSizeOfGlyphArea)
<add> break;
<add> var unicode = unusedUnicode++;
<add> this.toUnicode[cid] = unicode;
<add> usedUnicodes[unicode] = true;
<add> glyphs.push({ unicode: unicode, code: cid });
<add> ids.push(i);
<ide> }
<ide> cmap.data = createCMapTable(glyphs, ids);
<ide> } else { | 1 |
Ruby | Ruby | fix typo in constraints method documentation | 5f4550889dcab7def4122d37a3379d57627f68e2 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def namespace(path, options = {})
<ide> # if the user should be given access to that route, or +false+ if the user should not.
<ide> #
<ide> # class Iphone
<del> # def self.matches(request)
<add> # def self.matches?(request)
<ide> # request.env["HTTP_USER_AGENT"] =~ /iPhone/
<ide> # end
<ide> # end | 1 |
Java | Java | decrease allocation rate for cacheoperation | c73e52412acd7cb50c229d5c273760843bc97188 | <ide><path>spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java
<ide> private <T extends Annotation> Collection<CacheOperation> lazyInit(Collection<Ca
<ide> }
<ide>
<ide> CacheableOperation parseCacheableAnnotation(AnnotatedElement ae, DefaultCacheConfig defaultConfig, Cacheable cacheable) {
<del> CacheableOperation op = new CacheableOperation();
<del>
<del> op.setCacheNames(cacheable.cacheNames());
<del> op.setCondition(cacheable.condition());
<del> op.setUnless(cacheable.unless());
<del> op.setKey(cacheable.key());
<del> op.setKeyGenerator(cacheable.keyGenerator());
<del> op.setCacheManager(cacheable.cacheManager());
<del> op.setCacheResolver(cacheable.cacheResolver());
<del> op.setSync(cacheable.sync());
<del> op.setName(ae.toString());
<del>
<del> defaultConfig.applyDefault(op);
<add> CacheableOperation.Builder opBuilder = new CacheableOperation.Builder();
<add>
<add> opBuilder.setCacheNames(cacheable.cacheNames());
<add> opBuilder.setCondition(cacheable.condition());
<add> opBuilder.setUnless(cacheable.unless());
<add> opBuilder.setKey(cacheable.key());
<add> opBuilder.setKeyGenerator(cacheable.keyGenerator());
<add> opBuilder.setCacheManager(cacheable.cacheManager());
<add> opBuilder.setCacheResolver(cacheable.cacheResolver());
<add> opBuilder.setSync(cacheable.sync());
<add> opBuilder.setName(ae.toString());
<add>
<add> defaultConfig.applyDefault(opBuilder);
<add> CacheableOperation op = opBuilder.build();
<ide> validateCacheOperation(ae, op);
<ide>
<ide> return op;
<ide> }
<ide>
<ide> CacheEvictOperation parseEvictAnnotation(AnnotatedElement ae, DefaultCacheConfig defaultConfig, CacheEvict cacheEvict) {
<del> CacheEvictOperation op = new CacheEvictOperation();
<del>
<del> op.setCacheNames(cacheEvict.cacheNames());
<del> op.setCondition(cacheEvict.condition());
<del> op.setKey(cacheEvict.key());
<del> op.setKeyGenerator(cacheEvict.keyGenerator());
<del> op.setCacheManager(cacheEvict.cacheManager());
<del> op.setCacheResolver(cacheEvict.cacheResolver());
<del> op.setCacheWide(cacheEvict.allEntries());
<del> op.setBeforeInvocation(cacheEvict.beforeInvocation());
<del> op.setName(ae.toString());
<del>
<del> defaultConfig.applyDefault(op);
<add> CacheEvictOperation.Builder opBuilder = new CacheEvictOperation.Builder();
<add>
<add> opBuilder.setCacheNames(cacheEvict.cacheNames());
<add> opBuilder.setCondition(cacheEvict.condition());
<add> opBuilder.setKey(cacheEvict.key());
<add> opBuilder.setKeyGenerator(cacheEvict.keyGenerator());
<add> opBuilder.setCacheManager(cacheEvict.cacheManager());
<add> opBuilder.setCacheResolver(cacheEvict.cacheResolver());
<add> opBuilder.setCacheWide(cacheEvict.allEntries());
<add> opBuilder.setBeforeInvocation(cacheEvict.beforeInvocation());
<add> opBuilder.setName(ae.toString());
<add>
<add> defaultConfig.applyDefault(opBuilder);
<add> CacheEvictOperation op = opBuilder.build();
<ide> validateCacheOperation(ae, op);
<ide>
<ide> return op;
<ide> }
<ide>
<ide> CacheOperation parsePutAnnotation(AnnotatedElement ae, DefaultCacheConfig defaultConfig, CachePut cachePut) {
<del> CachePutOperation op = new CachePutOperation();
<del>
<del> op.setCacheNames(cachePut.cacheNames());
<del> op.setCondition(cachePut.condition());
<del> op.setUnless(cachePut.unless());
<del> op.setKey(cachePut.key());
<del> op.setKeyGenerator(cachePut.keyGenerator());
<del> op.setCacheManager(cachePut.cacheManager());
<del> op.setCacheResolver(cachePut.cacheResolver());
<del> op.setName(ae.toString());
<del>
<del> defaultConfig.applyDefault(op);
<add> CachePutOperation.Builder opBuilder = new CachePutOperation.Builder();
<add>
<add> opBuilder.setCacheNames(cachePut.cacheNames());
<add> opBuilder.setCondition(cachePut.condition());
<add> opBuilder.setUnless(cachePut.unless());
<add> opBuilder.setKey(cachePut.key());
<add> opBuilder.setKeyGenerator(cachePut.keyGenerator());
<add> opBuilder.setCacheManager(cachePut.cacheManager());
<add> opBuilder.setCacheResolver(cachePut.cacheResolver());
<add> opBuilder.setName(ae.toString());
<add>
<add> defaultConfig.applyDefault(opBuilder);
<add> CachePutOperation op = opBuilder.build();
<ide> validateCacheOperation(ae, op);
<ide>
<ide> return op;
<ide> private DefaultCacheConfig(String[] cacheNames, String keyGenerator, String cach
<ide> * Apply the defaults to the specified {@link CacheOperation}.
<ide> * @param operation the operation to update
<ide> */
<del> public void applyDefault(CacheOperation operation) {
<add> public void applyDefault(CacheOperation.Builder operation) {
<ide> if (operation.getCacheNames().isEmpty() && this.cacheNames != null) {
<ide> operation.setCacheNames(this.cacheNames);
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java
<ide> private RootBeanDefinition parseDefinitionSource(Element definition, ParserConte
<ide> String name = prop.merge(opElement, parserContext.getReaderContext());
<ide> TypedStringValue nameHolder = new TypedStringValue(name);
<ide> nameHolder.setSource(parserContext.extractSource(opElement));
<del> CacheableOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CacheableOperation());
<add> CacheableOperation.Builder op = prop.merge(opElement, parserContext.getReaderContext(), new CacheableOperation.Builder());
<ide> op.setUnless(getAttributeValue(opElement, "unless", ""));
<ide> op.setSync(Boolean.valueOf(getAttributeValue(opElement, "sync", "false")));
<ide>
<ide> private RootBeanDefinition parseDefinitionSource(Element definition, ParserConte
<ide> col = new ArrayList<CacheOperation>(2);
<ide> cacheOpMap.put(nameHolder, col);
<ide> }
<del> col.add(op);
<add> col.add(op.build());
<ide> }
<ide>
<ide> List<Element> evictCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_EVICT_ELEMENT);
<ide> private RootBeanDefinition parseDefinitionSource(Element definition, ParserConte
<ide> String name = prop.merge(opElement, parserContext.getReaderContext());
<ide> TypedStringValue nameHolder = new TypedStringValue(name);
<ide> nameHolder.setSource(parserContext.extractSource(opElement));
<del> CacheEvictOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CacheEvictOperation());
<add> CacheEvictOperation.Builder op = prop.merge(opElement, parserContext.getReaderContext(), new CacheEvictOperation.Builder());
<ide>
<ide> String wide = opElement.getAttribute("all-entries");
<ide> if (StringUtils.hasText(wide)) {
<ide> private RootBeanDefinition parseDefinitionSource(Element definition, ParserConte
<ide> col = new ArrayList<CacheOperation>(2);
<ide> cacheOpMap.put(nameHolder, col);
<ide> }
<del> col.add(op);
<add> col.add(op.build());
<ide> }
<ide>
<ide> List<Element> putCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_PUT_ELEMENT);
<ide> private RootBeanDefinition parseDefinitionSource(Element definition, ParserConte
<ide> String name = prop.merge(opElement, parserContext.getReaderContext());
<ide> TypedStringValue nameHolder = new TypedStringValue(name);
<ide> nameHolder.setSource(parserContext.extractSource(opElement));
<del> CachePutOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CachePutOperation());
<add> CachePutOperation.Builder op = prop.merge(opElement, parserContext.getReaderContext(), new CachePutOperation.Builder());
<ide> op.setUnless(getAttributeValue(opElement, "unless", ""));
<ide>
<ide> Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
<ide> if (col == null) {
<ide> col = new ArrayList<CacheOperation>(2);
<ide> cacheOpMap.put(nameHolder, col);
<ide> }
<del> col.add(op);
<add> col.add(op.build());
<ide> }
<ide>
<ide> RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(NameMatchCacheOperationSource.class);
<ide> private static class Props {
<ide> }
<ide> }
<ide>
<del> <T extends CacheOperation> T merge(Element element, ReaderContext readerCtx, T op) {
<add> <T extends CacheOperation.Builder> T merge(Element element, ReaderContext readerCtx, T op) {
<ide> String cache = element.getAttribute("cache");
<ide>
<ide> // sanity check
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java
<ide> */
<ide> public class CacheEvictOperation extends CacheOperation {
<ide>
<del> private boolean cacheWide = false;
<add> private final boolean cacheWide;
<ide>
<del> private boolean beforeInvocation = false;
<add> private final boolean beforeInvocation;
<ide>
<add> public boolean isCacheWide() {
<add> return this.cacheWide;
<add> }
<ide>
<del> public void setCacheWide(boolean cacheWide) {
<del> this.cacheWide = cacheWide;
<del> }
<add> public boolean isBeforeInvocation() {
<add> return this.beforeInvocation;
<add> }
<ide>
<del> public boolean isCacheWide() {
<del> return this.cacheWide;
<del> }
<add> public CacheEvictOperation(CacheEvictOperation.Builder b) {
<add> super(b);
<add> this.cacheWide = b.cacheWide;
<add> this.beforeInvocation = b.beforeInvocation;
<add> }
<ide>
<del> public void setBeforeInvocation(boolean beforeInvocation) {
<del> this.beforeInvocation = beforeInvocation;
<del> }
<add> public static class Builder extends CacheOperation.Builder {
<add> private boolean cacheWide = false;
<ide>
<del> public boolean isBeforeInvocation() {
<del> return this.beforeInvocation;
<del> }
<add> private boolean beforeInvocation = false;
<ide>
<del> @Override
<del> protected StringBuilder getOperationDescription() {
<del> StringBuilder sb = super.getOperationDescription();
<del> sb.append(",");
<del> sb.append(this.cacheWide);
<del> sb.append(",");
<del> sb.append(this.beforeInvocation);
<del> return sb;
<del> }
<add> public void setCacheWide(boolean cacheWide) {
<add> this.cacheWide = cacheWide;
<add> }
<add>
<add> public void setBeforeInvocation(boolean beforeInvocation) {
<add> this.beforeInvocation = beforeInvocation;
<add> }
<add>
<add> @Override
<add> protected StringBuilder getOperationDescription() {
<add> StringBuilder sb = super.getOperationDescription();
<add> sb.append(",");
<add> sb.append(this.cacheWide);
<add> sb.append(",");
<add> sb.append(this.beforeInvocation);
<add> return sb;
<add> }
<add>
<add> public CacheEvictOperation build() {
<add> return new CacheEvictOperation(this);
<add> }
<add> }
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java
<ide> */
<ide> public abstract class CacheOperation implements BasicOperation {
<ide>
<del> private String name = "";
<add> private final String name;
<ide>
<del> private Set<String> cacheNames = Collections.emptySet();
<del>
<del> private String key = "";
<add> private final Set<String> cacheNames;
<ide>
<del> private String keyGenerator = "";
<del>
<del> private String cacheManager = "";
<del>
<del> private String cacheResolver = "";
<del>
<del> private String condition = "";
<del>
<del>
<del> public void setName(String name) {
<del> Assert.hasText(name);
<del> this.name = name;
<del> }
<del>
<del> public String getName() {
<del> return this.name;
<del> }
<del>
<del> public void setCacheName(String cacheName) {
<del> Assert.hasText(cacheName);
<del> this.cacheNames = Collections.singleton(cacheName);
<del> }
<del>
<del> public void setCacheNames(String... cacheNames) {
<del> this.cacheNames = new LinkedHashSet<String>(cacheNames.length);
<del> for (String cacheName : cacheNames) {
<del> Assert.hasText(cacheName, "Cache name must be non-null if specified");
<del> this.cacheNames.add(cacheName);
<del> }
<del> }
<del>
<del> @Override
<del> public Set<String> getCacheNames() {
<del> return this.cacheNames;
<del> }
<del>
<del> public void setKey(String key) {
<del> Assert.notNull(key);
<del> this.key = key;
<del> }
<del>
<del> public String getKey() {
<del> return this.key;
<del> }
<del>
<del> public void setKeyGenerator(String keyGenerator) {
<del> Assert.notNull(keyGenerator);
<del> this.keyGenerator = keyGenerator;
<del> }
<del>
<del> public String getKeyGenerator() {
<del> return this.keyGenerator;
<del> }
<del>
<del> public void setCacheManager(String cacheManager) {
<del> Assert.notNull(cacheManager);
<del> this.cacheManager = cacheManager;
<del> }
<del>
<del> public String getCacheManager() {
<del> return this.cacheManager;
<del> }
<del>
<del> public void setCacheResolver(String cacheResolver) {
<del> Assert.notNull(this.cacheManager);
<del> this.cacheResolver = cacheResolver;
<del> }
<del>
<del> public String getCacheResolver() {
<del> return this.cacheResolver;
<del> }
<del>
<del> public void setCondition(String condition) {
<del> Assert.notNull(condition);
<del> this.condition = condition;
<del> }
<del>
<del> public String getCondition() {
<del> return this.condition;
<del> }
<del>
<del>
<del> /**
<del> * This implementation compares the {@code toString()} results.
<del> * @see #toString()
<del> */
<del> @Override
<del> public boolean equals(Object other) {
<del> return (other instanceof CacheOperation && toString().equals(other.toString()));
<del> }
<del>
<del> /**
<del> * This implementation returns {@code toString()}'s hash code.
<del> * @see #toString()
<del> */
<del> @Override
<del> public int hashCode() {
<del> return toString().hashCode();
<del> }
<del>
<del> /**
<del> * Return an identifying description for this cache operation.
<del> * <p>Has to be overridden in subclasses for correct {@code equals}
<del> * and {@code hashCode} behavior. Alternatively, {@link #equals}
<del> * and {@link #hashCode} can be overridden themselves.
<del> */
<del> @Override
<del> public String toString() {
<del> return getOperationDescription().toString();
<del> }
<del>
<del> /**
<del> * Return an identifying description for this caching operation.
<del> * <p>Available to subclasses, for inclusion in their {@code toString()} result.
<del> */
<del> protected StringBuilder getOperationDescription() {
<del> StringBuilder result = new StringBuilder(getClass().getSimpleName());
<del> result.append("[").append(this.name);
<del> result.append("] caches=").append(this.cacheNames);
<del> result.append(" | key='").append(this.key);
<del> result.append("' | keyGenerator='").append(this.keyGenerator);
<del> result.append("' | cacheManager='").append(this.cacheManager);
<del> result.append("' | cacheResolver='").append(this.cacheResolver);
<del> result.append("' | condition='").append(this.condition).append("'");
<del> return result;
<del> }
<add> private final String key;
<add>
<add> private final String keyGenerator;
<add>
<add> private final String cacheManager;
<add>
<add> private final String cacheResolver;
<add>
<add> private final String condition;
<add>
<add> private final String toString;
<add>
<add> protected CacheOperation(Builder b) {
<add> this.name = b.name;
<add> this.cacheNames = b.cacheNames;
<add> this.key = b.key;
<add> this.keyGenerator = b.keyGenerator;
<add> this.cacheManager = b.cacheManager;
<add> this.cacheResolver = b.cacheResolver;
<add> this.condition = b.condition;
<add> this.toString = b.getOperationDescription().toString();
<add> }
<add>
<add> public String getName() {
<add> return this.name;
<add> }
<add>
<add>
<add> @Override
<add> public Set<String> getCacheNames() {
<add> return this.cacheNames;
<add> }
<add>
<add>
<add> public String getKey() {
<add> return this.key;
<add> }
<add>
<add>
<add> public String getKeyGenerator() {
<add> return this.keyGenerator;
<add> }
<add>
<add>
<add> public String getCacheManager() {
<add> return this.cacheManager;
<add> }
<add>
<add>
<add> public String getCacheResolver() {
<add> return this.cacheResolver;
<add> }
<add>
<add>
<add> public String getCondition() {
<add> return this.condition;
<add> }
<add>
<add>
<add> /**
<add> * This implementation compares the {@code toString()} results.
<add> *
<add> * @see #toString()
<add> */
<add> @Override
<add> public boolean equals(Object other) {
<add> return (other instanceof CacheOperation && toString().equals(other.toString()));
<add> }
<add>
<add> /**
<add> * This implementation returns {@code toString()}'s hash code.
<add> *
<add> * @see #toString()
<add> */
<add> @Override
<add> public int hashCode() {
<add> return toString().hashCode();
<add> }
<add>
<add> /**
<add> * Return an identifying description for this cache operation.
<add> * <p>Returned value is produced by calling {@link Builder#getOperationDescription()}
<add> * during object construction. This method is used in {#hashCode} and {#equals}.
<add> *
<add> * @see Builder#getOperationDescription()
<add> */
<add> @Override
<add> public final String toString() {
<add> return toString;
<add> }
<add>
<add> public abstract static class Builder {
<add>
<add> private String name = "";
<add>
<add> private Set<String> cacheNames = Collections.emptySet();
<add>
<add> private String key = "";
<add>
<add> private String keyGenerator = "";
<add>
<add> private String cacheManager = "";
<add>
<add> private String cacheResolver = "";
<add>
<add> private String condition = "";
<add>
<add> public void setName(String name) {
<add> Assert.hasText(name);
<add> this.name = name;
<add> }
<add>
<add> public void setCacheName(String cacheName) {
<add> Assert.hasText(cacheName);
<add> this.cacheNames = Collections.singleton(cacheName);
<add> }
<add>
<add> public void setCacheNames(String... cacheNames) {
<add> this.cacheNames = new LinkedHashSet<String>(cacheNames.length);
<add> for (String cacheName : cacheNames) {
<add> Assert.hasText(cacheName, "Cache name must be non-null if specified");
<add> this.cacheNames.add(cacheName);
<add> }
<add> }
<add>
<add> public Set<String> getCacheNames() {
<add> return cacheNames;
<add> }
<add>
<add> public void setKey(String key) {
<add> Assert.notNull(key);
<add> this.key = key;
<add> }
<add>
<add> public String getKey() {
<add> return key;
<add> }
<add>
<add> public String getKeyGenerator() {
<add> return keyGenerator;
<add> }
<add>
<add> public String getCacheManager() {
<add> return cacheManager;
<add> }
<add>
<add> public String getCacheResolver() {
<add> return cacheResolver;
<add> }
<add>
<add> public void setKeyGenerator(String keyGenerator) {
<add> Assert.notNull(keyGenerator);
<add> this.keyGenerator = keyGenerator;
<add> }
<add>
<add> public void setCacheManager(String cacheManager) {
<add> Assert.notNull(cacheManager);
<add> this.cacheManager = cacheManager;
<add> }
<add>
<add> public void setCacheResolver(String cacheResolver) {
<add> Assert.notNull(cacheManager);
<add> this.cacheResolver = cacheResolver;
<add> }
<add>
<add> public void setCondition(String condition) {
<add> Assert.notNull(condition);
<add> this.condition = condition;
<add> }
<add>
<add> /**
<add> * Return an identifying description for this caching operation.
<add> * <p>Available to subclasses, for inclusion in their {@code toString()} result.
<add> */
<add> protected StringBuilder getOperationDescription() {
<add> StringBuilder result = new StringBuilder(getClass().getSimpleName());
<add> result.append("[").append(this.name);
<add> result.append("] caches=").append(this.cacheNames);
<add> result.append(" | key='").append(this.key);
<add> result.append("' | keyGenerator='").append(this.keyGenerator);
<add> result.append("' | cacheManager='").append(this.cacheManager);
<add> result.append("' | cacheResolver='").append(this.cacheResolver);
<add> result.append("' | condition='").append(this.condition).append("'");
<add> return result;
<add> }
<add>
<add> public abstract CacheOperation build();
<add> }
<ide>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java
<ide> */
<ide> public class CachePutOperation extends CacheOperation {
<ide>
<del> private String unless;
<add> private final String unless;
<ide>
<add> public CachePutOperation(CachePutOperation.Builder b) {
<add> super(b);
<add> this.unless = b.unless;
<add> }
<ide>
<ide> public String getUnless() {
<ide> return this.unless;
<ide> }
<ide>
<del> public void setUnless(String unless) {
<del> this.unless = unless;
<del> }
<add> public static class Builder extends CacheOperation.Builder {
<ide>
<del> @Override
<del> protected StringBuilder getOperationDescription() {
<del> StringBuilder sb = super.getOperationDescription();
<del> sb.append(" | unless='");
<del> sb.append(this.unless);
<del> sb.append("'");
<del> return sb;
<del> }
<add> private String unless;
<add>
<add> public void setUnless(String unless) {
<add> this.unless = unless;
<add> }
<add>
<add> @Override
<add> protected StringBuilder getOperationDescription() {
<add> StringBuilder sb = super.getOperationDescription();
<add> sb.append(" | unless='");
<add> sb.append(this.unless);
<add> sb.append("'");
<add> return sb;
<add> }
<add>
<add> public CachePutOperation build() {
<add> return new CachePutOperation(this);
<add> }
<add> }
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheableOperation.java
<ide> */
<ide> public class CacheableOperation extends CacheOperation {
<ide>
<del> private String unless;
<add> private final String unless;
<ide>
<del> private boolean sync;
<add> private boolean sync;
<ide>
<add> public CacheableOperation(CacheableOperation.Builder b) {
<add> super(b);
<add> this.unless = b.unless;
<add> this.sync = b.sync;
<add> }
<ide>
<ide> public String getUnless() {
<ide> return this.unless;
<ide> }
<ide>
<del> public void setUnless(String unless) {
<del> this.unless = unless;
<del> }
<del>
<ide> public boolean isSync() {
<ide> return this.sync;
<ide> }
<ide>
<del> public void setSync(boolean sync) {
<del> this.sync = sync;
<del> }
<ide>
<del> @Override
<del> protected StringBuilder getOperationDescription() {
<del> StringBuilder sb = super.getOperationDescription();
<del> sb.append(" | unless='");
<del> sb.append(this.unless);
<del> sb.append("'");
<del> sb.append(" | sync='");
<del> sb.append(this.sync);
<del> sb.append("'");
<del> return sb;
<del> }
<add> public static class Builder extends CacheOperation.Builder {
<add>
<add> private String unless;
<add>
<add> private boolean sync;
<add> public void setUnless(String unless) {
<add> this.unless = unless;
<add> }
<add>
<add> public void setSync(boolean sync) {
<add> this.sync = sync;
<add> }
<add>
<add> @Override
<add> protected StringBuilder getOperationDescription() {
<add> StringBuilder sb = super.getOperationDescription();
<add> sb.append(" | unless='");
<add> sb.append(this.unless);
<add> sb.append("'");
<add> sb.append(" | sync='");
<add> sb.append(this.sync);
<add> sb.append("'");
<add> return sb;
<add> }
<add>
<add> @Override
<add> public CacheableOperation build() {
<add> return new CacheableOperation(this);
<add> }
<add> }
<ide> } | 6 |
Javascript | Javascript | add getcachekey() to the open source transformer | 8fe24da6c21b2d1514e207799f062bc555d9eb70 | <ide><path>packager/src/Bundler/index.js
<ide> class Bundler {
<ide> /* $FlowFixMe: in practice it's always here. */
<ide> this._transformer = new Transformer(opts.transformModulePath, maxWorkerCount);
<ide>
<del> const getTransformCacheKey = (src, filename, options) => {
<del> return transformCacheKey + getCacheKey(src, filename, options);
<add> const getTransformCacheKey = (options) => {
<add> return transformCacheKey + getCacheKey(options);
<ide> };
<ide>
<ide> this._resolverPromise = Resolver.load({
<ide><path>packager/src/lib/GlobalTransformCache.js
<ide> class URIBasedGlobalTransformCache {
<ide> const hash = crypto.createHash('sha1');
<ide> const {sourceCode, filePath, transformOptions} = props;
<ide> hash.update(this._optionsHasher.getTransformWorkerOptionsDigest(transformOptions));
<del> const cacheKey = props.getTransformCacheKey(sourceCode, filePath, transformOptions);
<add> const cacheKey = props.getTransformCacheKey(transformOptions);
<ide> hash.update(JSON.stringify(cacheKey));
<ide> hash.update(crypto.createHash('sha1').update(sourceCode).digest('hex'));
<ide> const digest = hash.digest('hex');
<ide><path>packager/src/lib/TransformCache.js
<ide> import type {MappingsMap} from './SourceMap';
<ide> import type {Reporter} from './reporting';
<ide>
<ide> type CacheFilePaths = {transformedCode: string, metadata: string};
<del>export type GetTransformCacheKey = (sourceCode: string, filename: string, options: {}) => string;
<add>export type GetTransformCacheKey = (options: {}) => string;
<ide>
<ide> const CACHE_NAME = 'react-native-packager-cache';
<ide> const CACHE_SUB_DIR = 'cache';
<ide> function hashSourceCode(props: {
<ide> transformOptionsKey: string,
<ide> }): string {
<ide> return crypto.createHash('sha1')
<del> .update(props.getTransformCacheKey(
<del> props.sourceCode,
<del> props.filePath,
<del> props.transformOptions,
<del> ))
<add> .update(props.getTransformCacheKey(props.transformOptions))
<ide> .update(props.sourceCode)
<ide> .digest('hex');
<ide> }
<ide><path>packager/transformer.js
<ide> 'use strict';
<ide>
<ide> const babel = require('babel-core');
<add>const crypto = require('crypto');
<ide> const externalHelpersPlugin = require('babel-plugin-external-helpers');
<ide> const fs = require('fs');
<ide> const generate = require('babel-generator').default;
<ide> const resolvePlugins = require('babel-preset-react-native/lib/resolvePlugins');
<ide>
<ide> const {compactMapping} = require('./src/Bundler/source-map');
<ide>
<add>const cacheKeyParts = [
<add> fs.readFileSync(__filename),
<add> require('babel-plugin-external-helpers/package.json').version,
<add> require('babel-preset-fbjs/package.json').version,
<add> require('babel-preset-react-native/package.json').version,
<add>];
<add>
<ide> /**
<ide> * Return a memoized function that checks for the existence of a
<ide> * project level .babelrc file, and if it doesn't exist, reads the
<ide> function transform(src, filename, options) {
<ide> }
<ide> }
<ide>
<del>module.exports.transform = transform;
<add>function getCacheKey(options) {
<add> var key = crypto.createHash('md5');
<add> cacheKeyParts.forEach(part => key.update(part));
<add> return key.digest('hex');
<add>}
<add>
<add>module.exports = {
<add> transform,
<add> getCacheKey,
<add>}; | 4 |
Java | Java | fix flaky maybefromcallabletest.noerrorloss | f61b2299d03baf16b5838510c42e1b4345db4a6e | <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java
<ide> public void noErrorLoss() throws Exception {
<ide> @Override
<ide> public void run() throws Exception {
<ide> cdl1.countDown();
<del> cdl2.await();
<add> cdl2.await(5, TimeUnit.SECONDS);
<ide> }
<ide> }).subscribeOn(Schedulers.single()).test();
<ide>
<ide> assertTrue(cdl1.await(5, TimeUnit.SECONDS));
<ide>
<ide> to.cancel();
<ide>
<del> cdl2.countDown();
<del>
<ide> int timeout = 10;
<ide>
<ide> while (timeout-- > 0 && errors.isEmpty()) {
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromCallableTest.java
<ide> public void noErrorLoss() throws Exception {
<ide> @Override
<ide> public Integer call() throws Exception {
<ide> cdl1.countDown();
<del> cdl2.await();
<add> cdl2.await(5, TimeUnit.SECONDS);
<ide> return 1;
<ide> }
<ide> }).subscribeOn(Schedulers.single()).test();
<ide> public Integer call() throws Exception {
<ide>
<ide> to.cancel();
<ide>
<del> cdl2.countDown();
<del>
<ide> int timeout = 10;
<ide>
<ide> while (timeout-- > 0 && errors.isEmpty()) {
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java
<ide> public void noErrorLoss() throws Exception {
<ide> public void run() {
<ide> cdl1.countDown();
<ide> try {
<del> cdl2.await();
<add> cdl2.await(5, TimeUnit.SECONDS);
<ide> } catch (InterruptedException ex) {
<ide> throw new RuntimeException(ex);
<ide> }
<ide> public void run() {
<ide>
<ide> to.cancel();
<ide>
<del> cdl2.countDown();
<del>
<ide> int timeout = 10;
<ide>
<ide> while (timeout-- > 0 && errors.isEmpty()) { | 3 |
Javascript | Javascript | remove redundant regexp flag | e2fa5a7e04ce961be81306e8095e65a911b7af7b | <ide><path>tools/doc/preprocess.js
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> const includeExpr = /^@include\s+([\w-]+)(?:\.md)?$/gmi;
<del>const commentExpr = /^@\/\/.*$/gmi;
<add>const commentExpr = /^@\/\/.*$/gm;
<ide>
<ide> function processIncludes(inputFile, input, cb) {
<ide> const includes = input.match(includeExpr); | 1 |
Javascript | Javascript | preserve env in test cases | c879c9a5c6481df313bc90529588de44cf1e55f0 | <ide><path>test/parallel/test-benchmark-crypto.js
<ide> const argv = ['--set', 'algo=sha256',
<ide> '--set', 'v=crypto',
<ide> '--set', 'writes=1',
<ide> 'crypto'];
<del>
<del>const child = fork(runjs, argv, { env: { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } });
<add>const env = Object.assign({}, process.env,
<add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
<add>const child = fork(runjs, argv, { env });
<ide> child.on('exit', (code, signal) => {
<ide> assert.strictEqual(code, 0);
<ide> assert.strictEqual(signal, null);
<ide><path>test/parallel/test-benchmark-timers.js
<ide> const argv = ['--set', 'type=depth',
<ide> '--set', 'thousands=0.001',
<ide> 'timers'];
<ide>
<del>const child = fork(runjs, argv, { env: { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } });
<add>const env = Object.assign({}, process.env,
<add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
<add>
<add>const child = fork(runjs, argv, { env });
<ide> child.on('exit', (code, signal) => {
<ide> assert.strictEqual(code, 0);
<ide> assert.strictEqual(signal, null);
<ide><path>test/parallel/test-env-var-no-warnings.js
<ide> const cp = require('child_process');
<ide> if (process.argv[2] === 'child') {
<ide> process.emitWarning('foo');
<ide> } else {
<del> function test(env) {
<add> function test(newEnv) {
<add> const env = Object.assign({}, process.env, newEnv);
<ide> const cmd = `"${process.execPath}" "${__filename}" child`;
<ide>
<ide> cp.exec(cmd, { env }, common.mustCall((err, stdout, stderr) => {
<ide><path>test/parallel/test-tls-env-bad-extra-ca.js
<ide> if (process.env.CHILD) {
<ide> return tls.createServer({});
<ide> }
<ide>
<del>const env = {
<add>const env = Object.assign({}, process.env, {
<ide> CHILD: 'yes',
<ide> NODE_EXTRA_CA_CERTS: `${common.fixturesDir}/no-such-file-exists`,
<del>};
<add>});
<ide>
<ide> const opts = {
<ide> env: env,
<ide><path>test/parallel/test-tls-env-extra-ca.js
<ide> const server = tls.createServer(options, common.mustCall(function(s) {
<ide> s.end('bye');
<ide> server.close();
<ide> })).listen(0, common.mustCall(function() {
<del> const env = {
<add> const env = Object.assign({}, process.env, {
<ide> CHILD: 'yes',
<ide> PORT: this.address().port,
<ide> NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'ca1-cert.pem')
<del> };
<add> });
<ide>
<ide> fork(__filename, { env: env }).on('exit', common.mustCall(function(status) {
<ide> assert.strictEqual(status, 0, 'client did not succeed in connecting');
<ide><path>test/sequential/test-benchmark-child-process.js
<ide> const path = require('path');
<ide>
<ide> const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js');
<ide>
<del>const child = fork(runjs, ['--set', 'dur=0',
<del> '--set', 'n=1',
<del> '--set', 'len=1',
<del> '--set', 'params=1',
<del> '--set', 'methodName=execSync',
<del> 'child_process'],
<del> { env: { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } });
<add>const env = Object.assign({}, process.env,
<add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
<add>
<add>const child = fork(
<add> runjs,
<add> [
<add> '--set', 'dur=0',
<add> '--set', 'n=1',
<add> '--set', 'len=1',
<add> '--set', 'params=1',
<add> '--set', 'methodName=execSync',
<add> 'child_process'
<add> ],
<add> { env }
<add>);
<add>
<ide> child.on('exit', (code, signal) => {
<ide> assert.strictEqual(code, 0);
<ide> assert.strictEqual(signal, null);
<ide><path>test/sequential/test-benchmark-net.js
<ide> const path = require('path');
<ide>
<ide> const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js');
<ide>
<add>const env = Object.assign({}, process.env,
<add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
<ide> const child = fork(runjs,
<ide> ['--set', 'dur=0',
<ide> '--set', 'len=1024',
<ide> '--set', 'type=buf',
<ide> 'net'],
<del> { env: { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } });
<add> { env });
<ide> child.on('exit', (code, signal) => {
<ide> assert.strictEqual(code, 0);
<ide> assert.strictEqual(signal, null); | 7 |
Python | Python | set version to 2.0.18 | 413530b269638327ed1321e6755af9a486e3c002 | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy'
<del>__version__ = '2.0.18.dev0'
<add>__version__ = '2.0.18'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI'
<ide> __email__ = '[email protected]'
<ide> __license__ = 'MIT'
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
<ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json' | 1 |
Text | Text | fix typos in contributing.md | 5bda05548bcfd473b3b112fe388ae64f862af86d | <ide><path>CONTRIBUTING.md
<ide> functional guidelines of the Node.js project.
<ide>
<ide> ## Pull Requests
<ide>
<del>Pull Requests are the way in which concrete changes are made to the code,
<del>documentation, dependencies, and tools contained with the `nodejs/node`
<del>repository.
<add>Pull Requests are the way concrete changes are made to the code, documentation,
<add>dependencies, and tools contained in the `nodejs/node` repository.
<ide>
<ide> There are two fundamental components of the Pull Request process: one concrete
<ide> and technical, and one more process oriented. The concrete and technical | 1 |
Python | Python | add non-cudnn lstm option and perfzero benchmarks. | 4d93d89408a7ef4947e6a853b03665e84f600f0d | <ide><path>official/staging/shakespeare/shakespeare_benchmark.py
<ide> def benchmark_1_gpu(self):
<ide> FLAGS.batch_size = 64
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_1_gpu_no_cudnn(self):
<add> """Benchmark 1 gpu with CuDNN disabled."""
<add> self._setup()
<add> FLAGS.num_gpus = 1
<add> FLAGS.batch_size = 64
<add> FLAGS.cudnn = False
<add> FLAGS.enable_eager = keras_utils.is_v2_0()
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_1_gpu_no_ds(self):
<ide> """Benchmark 1 gpu without distribution strategies."""
<ide> self._setup()
<ide> def benchmark_xla_1_gpu(self):
<ide> FLAGS.enable_xla = True
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_xla_1_gpu_no_cudnn(self):
<add> """Benchmark 1 gpu w/xla and CuDNN disabled."""
<add> self._setup()
<add> FLAGS.num_gpus = 1
<add> FLAGS.batch_size = 64
<add> FLAGS.cudnn = False
<add> FLAGS.enable_eager = keras_utils.is_v2_0()
<add> FLAGS.enable_xla = True
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_8_gpu(self):
<ide> """Benchmark 8 gpu."""
<ide> self._setup()
<ide> def benchmark_8_gpu(self):
<ide> FLAGS.log_steps = 10
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_8_gpu_no_cudnn(self):
<add> """Benchmark 8 gpu with CuDNN disabled."""
<add> self._setup()
<add> FLAGS.num_gpus = 8
<add> FLAGS.batch_size = 64 * 8
<add> FLAGS.cudnn = False
<add> FLAGS.enable_eager = keras_utils.is_v2_0()
<add> self._run_and_report_benchmark()
<add>
<ide> def benchmark_xla_8_gpu(self):
<ide> """Benchmark 8 gpu w/xla."""
<ide> self._setup()
<ide> def benchmark_xla_8_gpu(self):
<ide> FLAGS.enable_xla = True
<ide> self._run_and_report_benchmark()
<ide>
<add> def benchmark_xla_8_gpu_no_cudnn(self):
<add> """Benchmark 8 gpu w/xla and CuDNN disabled."""
<add> self._setup()
<add> FLAGS.num_gpus = 8
<add> FLAGS.batch_size = 64 * 8
<add> FLAGS.cudnn = False
<add> FLAGS.enable_eager = keras_utils.is_v2_0()
<add> FLAGS.enable_xla = True
<add> self._run_and_report_benchmark()
<add>
<ide> def _run_and_report_benchmark(self):
<ide> """Run and report benchmark."""
<ide> super(ShakespeareKerasBenchmarkReal, self)._run_and_report_benchmark(
<ide><path>official/staging/shakespeare/shakespeare_main.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import functools
<ide> import os
<ide>
<ide> # pylint: disable=wrong-import-order
<ide> def define_flags():
<ide> flags.DEFINE_string(
<ide> name='training_data', default=None,
<ide> help='Path to file containing the training data.')
<add> flags.DEFINE_boolean(name='cudnn', default=True, help='Use CuDNN LSTM.')
<ide>
<ide>
<ide> def get_dataset(path_to_file, batch_size=None, seq_length=SEQ_LENGTH):
<ide> def build_model(vocab_size,
<ide> embedding_dim=EMBEDDING_DIM,
<ide> rnn_units=RNN_UNITS,
<ide> batch_size=None,
<del> stateful=False):
<add> stateful=False,
<add> use_cudnn=True):
<ide> """Builds the Shakespeare model.
<ide>
<ide> Args:
<ide> def build_model(vocab_size,
<ide> Returns:
<ide> A Keras Model.
<ide> """
<add> # In V1 there is a separate class for CuDNN. In V2 the LSTM class will use
<add> # CuDNN automatically if applicable.
<add> if use_cudnn and not keras_utils.is_v2_0():
<add> LSTM = tf.compat.v1.CuDNNLSTM
<add> else:
<add> # The LSTM call was rewritten to be more efficient in 2.0. However because
<add> # we want to compare the performance of the two runtimes, we force both
<add> # V1 and V2 to use the more efficient implementation.
<add> LSTM = functools.partial(tf.keras.layers.LSTM, implementation=2)
<add>
<add> # By indirecting the activation through a lambda layer, the logic to dispatch
<add> # to CuDNN in V2 doesn't trigger and we force the LSTM to run in non-CuDNN
<add> # mode.
<add> lstm_activation = ('tanh' if use_cudnn else
<add> lambda x: tf.math.tanh(x))
<add>
<ide> batch_shape = [batch_size if stateful else None, None]
<ide> return tf.keras.Sequential([
<ide> tf.keras.layers.Embedding(vocab_size, embedding_dim,
<ide> batch_input_shape=batch_shape),
<del> tf.keras.layers.LSTM(rnn_units,
<del> return_sequences=True,
<del> stateful=stateful,
<del> recurrent_initializer='glorot_uniform'),
<add> LSTM(rnn_units,
<add> activation=lstm_activation,
<add> return_sequences=True,
<add> stateful=stateful,
<add> recurrent_initializer='glorot_uniform'),
<ide> tf.keras.layers.Dense(vocab_size, activation='softmax')])
<ide>
<ide>
<ide> def train_model(flags_obj, dataset, vocab_size, strategy, checkpoint_dir=None):
<ide> strategy_scope = distribution_utils.get_strategy_scope(strategy)
<ide>
<ide> with strategy_scope:
<del> model = build_model(vocab_size=vocab_size, batch_size=flags_obj.batch_size)
<add> model = build_model(vocab_size=vocab_size, batch_size=flags_obj.batch_size,
<add> use_cudnn=flags_obj.cudnn)
<ide> model.compile(
<ide> optimizer=tf.keras.optimizers.Adam(),
<ide> loss=tf.keras.losses.CategoricalCrossentropy(), | 2 |
Text | Text | fix some table problems in changelog.md | e44eb0e6cefbba77808f64a2adc514c28239753d | <ide><path>CHANGELOG.md
<ide> release.
<ide> <b><a href="doc/changelogs/CHANGELOG_V4.md#4.6.1">4.6.1</a></b><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V4.md#4.6.0">4.6.0</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V4.md#4.5.0">4.5.0</a><br/>
<del><a href="doc/changelogs/CHANGELOG_V4.md#4.4.7">4.4.7</a></b>
<del><a href="doc/changelogs/CHANGELOG_V4.md#4.4.6">4.4.6</a></b>
<del><a href="doc/changelogs/CHANGELOG_V4.md#4.4.5">4.4.5</a></b>
<add><a href="doc/changelogs/CHANGELOG_V4.md#4.4.7">4.4.7</a><br/>
<add><a href="doc/changelogs/CHANGELOG_V4.md#4.4.6">4.4.6</a><br/>
<add><a href="doc/changelogs/CHANGELOG_V4.md#4.4.5">4.4.5</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V4.md#4.4.4">4.4.4</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V4.md#4.4.3">4.4.3</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V4.md#4.4.2">4.4.2</a><br/>
<ide> release.
<ide> </td>
<ide> <td valign="top">
<ide> <b><a href="doc/changelogs/CHANGELOG_V010.md#0.10.48">0.10.48</a></b><br/>
<del>><a href="doc/changelogs/CHANGELOG_V010.md#0.10.47">0.10.47</a><br/>
<add><a href="doc/changelogs/CHANGELOG_V010.md#0.10.47">0.10.47</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V010.md#0.10.46">0.10.46</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V010.md#0.10.45">0.10.45</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V010.md#0.10.44">0.10.44</a><br/> | 1 |
Ruby | Ruby | drop unnecessary nil checks | da2a2ab74899a659ba8fe5e9c178fb3c409d8d37 | <ide><path>Library/Homebrew/formula.rb
<ide> def set_spec(name)
<ide>
<ide> def determine_active_spec
<ide> case
<del> when head && ARGV.build_head? then head # --HEAD
<del> when devel && ARGV.build_devel? then devel # --devel
<del> when stable then stable
<del> when devel && stable.nil? then devel # devel-only
<del> when head && stable.nil? then head # head-only
<add> when head && ARGV.build_head? then head # --HEAD
<add> when devel && ARGV.build_devel? then devel # --devel
<add> when stable then stable
<add> when devel then devel
<add> when head then head # head-only
<ide> else
<ide> raise FormulaSpecificationError, "formulae require at least a URL"
<ide> end | 1 |
Ruby | Ruby | remove unused require and unused model stub | b351061b839b005586b9ac3f08fa8dcd768e3428 | <ide><path>activemodel/test/cases/helper.rb
<ide> require 'active_model'
<del>require 'active_support/core_ext/string/access'
<ide>
<ide> # Show backtraces for deprecated behavior for quicker cleanup.
<ide> ActiveSupport::Deprecation.debug = true
<ide><path>activemodel/test/models/project.rb
<del>class Project
<del> include ActiveModel::DeprecatedMassAssignmentSecurity
<del>end | 2 |
Javascript | Javascript | fix chart resizing issue | 94763bff351236ff5936280737b594701f0528b8 | <ide><path>src/platform/platform.dom.js
<ide> function createResizeObserver(chart, type, listener) {
<ide> // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented
<ide> const observer = new ResizeObserver(entries => {
<ide> const entry = entries[0];
<del> resize(entry.contentRect.width, entry.contentRect.height);
<add> const width = entry.contentRect.width;
<add> const height = entry.contentRect.height;
<add> // When its container's display is set to 'none' the callback will be called with a
<add> // size of (0, 0), which will cause the chart to lost its original height, so skip
<add> // resizing in such case.
<add> if (width === 0 && height === 0) {
<add> return;
<add> }
<add> resize(width, height);
<ide> });
<ide> observer.observe(container);
<ide> return observer;
<ide><path>test/specs/core.controller.tests.js
<ide> describe('Chart', function() {
<ide> wrapper.style.width = '455px';
<ide> });
<ide>
<add> it('should restore the original size when parent became invisible', function(done) {
<add> var chart = acquireChart({
<add> options: {
<add> responsive: true,
<add> maintainAspectRatio: false
<add> }
<add> }, {
<add> canvas: {
<add> style: ''
<add> },
<add> wrapper: {
<add> style: 'width: 300px; height: 350px; position: relative'
<add> }
<add> });
<add>
<add> waitForResize(chart, function() {
<add> expect(chart).toBeChartOfSize({
<add> dw: 300, dh: 350,
<add> rw: 300, rh: 350,
<add> });
<add>
<add> var original = chart.resize;
<add> chart.resize = function() {
<add> fail('resize should not have been called');
<add> };
<add>
<add> var wrapper = chart.canvas.parentNode;
<add> wrapper.style.display = 'none';
<add>
<add> setTimeout(function() {
<add> expect(wrapper.clientWidth).toEqual(0);
<add> expect(wrapper.clientHeight).toEqual(0);
<add>
<add> expect(chart).toBeChartOfSize({
<add> dw: 300, dh: 350,
<add> rw: 300, rh: 350,
<add> });
<add>
<add> chart.resize = original;
<add>
<add> waitForResize(chart, function() {
<add> expect(chart).toBeChartOfSize({
<add> dw: 300, dh: 350,
<add> rw: 300, rh: 350,
<add> });
<add>
<add> done();
<add> });
<add> wrapper.style.display = 'block';
<add> }, 200);
<add> });
<add> });
<add>
<ide> it('should resize the canvas when parent is RTL and width changes', function(done) {
<ide> var chart = acquireChart({
<ide> options: { | 2 |
Python | Python | remove mention of `ipython -p numpy`. | 48b204b641e899ee649eb57ad0652312c083067e | <ide><path>numpy/__init__.py
<ide>
<ide> Viewing documentation using IPython
<ide> -----------------------------------
<del>Start IPython with the NumPy profile (``ipython -p numpy``), which will
<del>import `numpy` under the alias ``np``. Then, use the ``cpaste`` command to
<del>paste examples into the shell. To see which functions are available in
<del>`numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
<add>
<add>Start IPython and import `numpy` usually under the alias ``np``: `import
<add>numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
<add>examples into the shell. To see which functions are available in `numpy`,
<add>type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
<ide> ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
<ide> down the list. To view the docstring for a function, use
<ide> ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view | 1 |
PHP | PHP | has with dot notation | f71da22b7114d5ae0ea270a385bdec088d5a5f8c | <ide><path>src/Illuminate/Session/Store.php
<ide> protected function ageFlashData()
<ide> $this->put('flash.new', array());
<ide> }
<ide>
<add> /**
<add> * {@inheritdoc}
<add> */
<add> public function has($name)
<add> {
<add> return ! is_null($this->get($name));
<add> }
<add>
<ide> /**
<ide> * {@inheritdoc}
<ide> */ | 1 |
PHP | PHP | fix authcomponent tests for windows newlines | 26d526f6240239094aa714b86093cd36fbb9a1f3 | <ide><path>cake/tests/cases/libs/controller/components/auth.test.php
<ide> function testAjaxLogin() {
<ide> $Dispatcher =& new Dispatcher();
<ide> $Dispatcher->dispatch('/ajax_auth/add', array('return' => 1));
<ide> $result = ob_get_clean();
<del> $this->assertEqual("Ajax!\nthis is the test element", $result);
<add> $this->assertEqual("Ajax!\nthis is the test element", str_replace("\r\n", "\n", $result));
<ide> unset($_SERVER['HTTP_X_REQUESTED_WITH']);
<ide> }
<ide> | 1 |
Javascript | Javascript | sanitize the string tag passed to dom components | a4e923b7fcc0313a0894740ba0ef60ba12ba9573 | <ide><path>src/browser/ui/ReactDOMComponent.js
<ide> var omittedCloseTags = {
<ide> // NOTE: menuitem's close tag should be omitted, but that causes problems.
<ide> };
<ide>
<add>// We accept any tag to be rendered but since this gets injected into abitrary
<add>// HTML, we want to make sure that it's a safe tag.
<add>// http://www.w3.org/TR/REC-xml/#NT-Name
<add>
<add>var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
<add>var validatedTagCache = {};
<add>var hasOwnProperty = {}.hasOwnProperty;
<add>
<add>function validateDangerousTag(tag) {
<add> if (!hasOwnProperty.call(validatedTagCache, tag)) {
<add> invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
<add> validatedTagCache[tag] = true;
<add> }
<add>}
<add>
<ide> /**
<ide> * Creates a new React class that is idempotent and capable of containing other
<ide> * React components. It accepts event listeners and DOM properties that are
<ide> var omittedCloseTags = {
<ide> * @extends ReactMultiChild
<ide> */
<ide> function ReactDOMComponent(tag) {
<del> // TODO: DANGEROUS this tag should be sanitized.
<add> validateDangerousTag(tag);
<ide> this._tag = tag;
<ide> this.tagName = tag.toUpperCase();
<ide> }
<ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> });
<ide> });
<ide>
<add> describe('tag sanitization', function() {
<add> it('should throw when an invalid tag name is used', () => {
<add> var React = require('React');
<add> var ReactTestUtils = require('ReactTestUtils');
<add> var hackzor = React.createElement('script tag');
<add> expect(
<add> () => ReactTestUtils.renderIntoDocument(hackzor)
<add> ).toThrow(
<add> 'Invariant Violation: Invalid tag: script tag'
<add> );
<add> });
<add>
<add> it('should throw when an attack vector is used', () => {
<add> var React = require('React');
<add> var ReactTestUtils = require('ReactTestUtils');
<add> var hackzor = React.createElement('div><img /><div');
<add> expect(
<add> () => ReactTestUtils.renderIntoDocument(hackzor)
<add> ).toThrow(
<add> 'Invariant Violation: Invalid tag: div><img /><div'
<add> );
<add> });
<add>
<add> });
<ide> }); | 2 |
PHP | PHP | reduce scope of primitive typehints | 029d9ba3928e91f90a9ac131be7c9dea25a946ae | <ide><path>src/Controller/ControllerFactory.php
<ide> public function invoke($controller): ResponseInterface
<ide> }
<ide>
<ide> // Primitive types are passed args as they can't be looked up in the container.
<del> if (in_array($typeName, ['float', 'int', 'string', 'bool'], true)) {
<add> // We only handle strings currently.
<add> if ($typeName === 'string') {
<ide> if (count($passed) || !$type->allowsNull()) {
<ide> $args[$position] = array_shift($passed);
<ide> } else { | 1 |
Ruby | Ruby | increase timeout for some integration tests | bf9659423a0954482a0bd62f5130e41fe9831c39 | <ide><path>Library/Homebrew/test/cmd/reinstall_spec.rb
<ide> it_behaves_like "parseable arguments"
<ide> end
<ide>
<del>describe "brew reinstall", :integration_test do
<add>describe "brew reinstall", :integration_test, timeout: 120 do
<ide> it "reinstalls a Formula" do
<ide> install_test_formula "testball"
<ide> foo_dir = HOMEBREW_CELLAR/"testball/0.1/bin"
<ide><path>Library/Homebrew/test/dev-cmd/test_spec.rb
<ide> end
<ide>
<ide> # randomly segfaults on Linux with portable-ruby.
<del>describe "brew test", :integration_test, :needs_macos do
<add>describe "brew test", :integration_test, :needs_macos, timeout: 120 do
<ide> it "tests a given Formula" do
<ide> install_test_formula "testball", <<~'RUBY'
<ide> test do | 2 |
PHP | PHP | apply fixes from styleci | 89c093f86ba0916724713208ee3b21194fba3e78 | <ide><path>tests/Integration/Database/DatabaseCustomCastsTest.php
<ide> public function test_custom_casting()
<ide> $this->assertEquals(['name' => 'Taylor'], $model->array_object->toArray());
<ide> $this->assertEquals(['name' => 'Taylor'], $model->array_object_json->toArray());
<ide> $this->assertEquals(['name' => 'Taylor'], $model->collection->toArray());
<del> $this->assertSame('Taylor', (string)$model->stringable);
<add> $this->assertSame('Taylor', (string) $model->stringable);
<ide>
<ide> $model->array_object['age'] = 34;
<ide> $model->array_object['meta']['title'] = 'Developer';
<ide> public function test_custom_casting_nullable_values()
<ide> $model = new TestEloquentModelWithCustomCastsNullable();
<ide>
<ide> $model->array_object = null;
<del> $model->array_object_json = null;
<add> $model->array_object_json = null;
<ide> $model->collection = collect();
<ide> $model->stringable = null;
<ide>
<ide> public function test_custom_casting_nullable_values()
<ide> $this->assertEmpty($model->array_object);
<ide> $this->assertEmpty($model->array_object_json);
<ide> $this->assertEmpty($model->collection);
<del> $this->assertSame('', (string)$model->stringable);
<add> $this->assertSame('', (string) $model->stringable);
<ide>
<ide> $model->array_object['name'] = 'Taylor';
<ide> $model->array_object['meta']['title'] = 'Developer'; | 1 |
Text | Text | add changelogs for util | 2426aaf11c2b4f00e388633e84e12431e15ead3c | <ide><path>doc/api/util.md
<ide> util.format(1, 2, 3); // '1 2 3'
<ide> ## util.inherits(constructor, superConstructor)
<ide> <!-- YAML
<ide> added: v0.3.0
<add>changes:
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/3455
<add> description: The `constructor` parameter can refer to an ES6 class now.
<ide> -->
<ide>
<ide> _Note: usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
<ide> stream.write('With ES6');
<ide> ## util.inspect(object[, options])
<ide> <!-- YAML
<ide> added: v0.3.0
<add>changes:
<add> - version: v6.6.0
<add> pr-url: https://github.com/nodejs/node/pull/8174
<add> description: Custom inspection functions can now return `this`.
<add> - version: v6.3.0
<add> pr-url: https://github.com/nodejs/node/pull/7499
<add> description: The `breakLength` option is supported now.
<add> - version: v6.1.0
<add> pr-url: https://github.com/nodejs/node/pull/6334
<add> description: The `maxArrayLength` option is supported now; in particular,
<add> long arrays are truncated by default.
<add> - version: v6.1.0
<add> pr-url: https://github.com/nodejs/node/pull/6465
<add> description: The `showProxy` option is supported now.
<ide> -->
<ide>
<ide> * `object` {any} Any JavaScript primitive or Object. | 1 |
Python | Python | fix mypy providers | dad2f8103be954afaedf15e9d098ee417b0d5d02 | <ide><path>airflow/providers/apache/spark/hooks/spark_sql.py
<ide> def __init__(
<ide> yarn_queue: Optional[str] = None,
<ide> ) -> None:
<ide> super().__init__()
<add> options: Dict = {}
<add> conn: Optional[Connection] = None
<ide>
<ide> try:
<del> conn: "Optional[Connection]" = self.get_connection(conn_id)
<add> conn = self.get_connection(conn_id)
<ide> except AirflowNotFoundException:
<ide> conn = None
<ide> options: Dict = {}
<ide><path>airflow/providers/asana/example_dags/example_asana.py
<ide> AsanaUpdateTaskOperator,
<ide> )
<ide>
<del>ASANA_TASK_TO_UPDATE = os.environ.get("ASANA_TASK_TO_UPDATE")
<del>ASANA_TASK_TO_DELETE = os.environ.get("ASANA_TASK_TO_DELETE")
<add>ASANA_TASK_TO_UPDATE = os.environ.get("ASANA_TASK_TO_UPDATE", "update_task")
<add>ASANA_TASK_TO_DELETE = os.environ.get("ASANA_TASK_TO_DELETE", "delete_task")
<ide> # This example assumes a default project ID has been specified in the connection. If you
<ide> # provide a different id in ASANA_PROJECT_ID_OVERRIDE, it will override this default
<ide> # project ID in the AsanaFindTaskOperator example below
<del>ASANA_PROJECT_ID_OVERRIDE = os.environ.get("ASANA_PROJECT_ID_OVERRIDE")
<add>ASANA_PROJECT_ID_OVERRIDE = os.environ.get("ASANA_PROJECT_ID_OVERRIDE", "test_project")
<ide> # This connection should specify a personal access token and a default project ID
<ide> CONN_ID = os.environ.get("ASANA_CONNECTION_ID")
<ide>
<ide><path>airflow/providers/asana/hooks/asana.py
<ide> # under the License.
<ide>
<ide> """Connect to Asana."""
<del>from typing import Any, Dict
<add>import sys
<add>from typing import Any, Dict, Optional
<ide>
<ide> from asana import Client
<ide> from asana.error import NotFoundError
<ide>
<del>try:
<add>if sys.version_info >= (3, 8):
<ide> from functools import cached_property
<del>except ImportError:
<add>else:
<ide> from cached_property import cached_property
<ide>
<ide> from airflow.hooks.base import BaseHook
<ide> def client(self) -> Client:
<ide>
<ide> return Client.access_token(self.connection.password)
<ide>
<del> def create_task(self, task_name: str, params: dict) -> dict:
<add> def create_task(self, task_name: str, params: Optional[dict]) -> dict:
<ide> """
<ide> Creates an Asana task.
<ide>
<ide> def create_task(self, task_name: str, params: dict) -> dict:
<ide> response = self.client.tasks.create(params=merged_params)
<ide> return response
<ide>
<del> def _merge_create_task_parameters(self, task_name: str, task_params: dict) -> dict:
<add> def _merge_create_task_parameters(self, task_name: str, task_params: Optional[dict]) -> dict:
<ide> """
<ide> Merge create_task parameters with default params from the connection.
<ide>
<ide> def delete_task(self, task_id: str) -> dict:
<ide> self.log.info("Asana task %s not found for deletion.", task_id)
<ide> return {}
<ide>
<del> def find_task(self, params: dict) -> list:
<add> def find_task(self, params: Optional[dict]) -> list:
<ide> """
<ide> Retrieves a list of Asana tasks that match search parameters.
<ide>
<ide> def find_task(self, params: dict) -> list:
<ide> response = self.client.tasks.find_all(params=merged_params)
<ide> return list(response)
<ide>
<del> def _merge_find_task_parameters(self, search_parameters: dict) -> dict:
<add> def _merge_find_task_parameters(self, search_parameters: Optional[dict]) -> dict:
<ide> """
<ide> Merge find_task parameters with default params from the connection.
<ide>
<ide><path>airflow/providers/jira/hooks/jira.py
<ide> def __init__(self, jira_conn_id: str = default_conn_name, proxies: Optional[Any]
<ide> super().__init__()
<ide> self.jira_conn_id = jira_conn_id
<ide> self.proxies = proxies
<del> self.client = None
<add> self.client: Optional[JIRA] = None
<ide> self.get_conn()
<ide>
<ide> def get_conn(self) -> JIRA:
<ide><path>airflow/providers/postgres/hooks/postgres.py
<ide> def get_iam_token(self, conn: Connection) -> Tuple[str, str, int]:
<ide> token = aws_hook.conn.generate_db_auth_token(conn.host, port, conn.login)
<ide> return login, token, port
<ide>
<del> def get_table_primary_key(self, table: str, schema: Optional[str] = "public") -> List[str]:
<add> def get_table_primary_key(self, table: str, schema: Optional[str] = "public") -> Optional[List[str]]:
<ide> """
<ide> Helper method that returns the table primary key
<ide>
<ide> :param table: Name of the target table
<ide> :type table: str
<del> :param table: Name of the target schema, public by default
<add> :param schema: Name of the target schema, public by default
<ide> :type table: str
<ide> :return: Primary key columns list
<ide> :rtype: List[str]
<ide><path>airflow/providers/slack/operators/slack.py
<ide> def __init__(
<ide> self,
<ide> channel: str = '#general',
<ide> initial_comment: str = 'No message has been set!',
<del> filename: str = None,
<del> filetype: str = None,
<del> content: str = None,
<add> filename: Optional[str] = None,
<add> filetype: Optional[str] = None,
<add> content: Optional[str] = None,
<ide> **kwargs,
<ide> ) -> None:
<ide> self.method = 'files.upload'
<ide> def __init__(
<ide> self.filename = filename
<ide> self.filetype = filetype
<ide> self.content = content
<del> self.file_params = {}
<add> self.file_params: Dict = {}
<ide> super().__init__(method=self.method, **kwargs)
<ide>
<ide> def execute(self, **kwargs):
<ide><path>airflow/providers/telegram/hooks/telegram.py
<ide> def get_conn(self) -> telegram.bot.Bot:
<ide> """
<ide> return telegram.bot.Bot(token=self.token)
<ide>
<del> def __get_token(self, token: Optional[str], telegram_conn_id: str) -> str:
<add> def __get_token(self, token: Optional[str], telegram_conn_id: Optional[str]) -> str:
<ide> """
<ide> Returns the telegram API token
<ide>
<ide> def __get_token(self, token: Optional[str], telegram_conn_id: str) -> str:
<ide>
<ide> raise AirflowException("Cannot get token: No valid Telegram connection supplied.")
<ide>
<del> def __get_chat_id(self, chat_id: Optional[str], telegram_conn_id: str) -> Optional[str]:
<add> def __get_chat_id(self, chat_id: Optional[str], telegram_conn_id: Optional[str]) -> Optional[str]:
<ide> """
<ide> Returns the telegram chat ID for a chat/channel/group
<ide>
<ide><path>airflow/providers/telegram/operators/telegram.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> """Operator for Telegram"""
<del>from typing import Optional
<add>from typing import Dict, Optional
<ide>
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.models import BaseOperator
<ide> def __init__(
<ide>
<ide> super().__init__(**kwargs)
<ide>
<del> def execute(self, **kwargs) -> None:
<add> def execute(self, context: Dict) -> None:
<ide> """Calls the TelegramHook to post the provided Telegram message"""
<ide> if self.text:
<ide> self.telegram_kwargs['text'] = self.text
<ide><path>airflow/providers/trino/hooks/trino.py
<ide> def get_pandas_df(self, hql, parameters=None, **kwargs):
<ide> df = pandas.DataFrame(**kwargs)
<ide> return df
<ide>
<del> def run(
<del> self,
<del> hql,
<del> autocommit: bool = False,
<del> parameters: Optional[dict] = None,
<del> ) -> None:
<add> def run(self, hql, autocommit: bool = False, parameters: Optional[dict] = None, handler=None) -> None:
<ide> """Execute the statement against Trino. Can be used to create views."""
<ide> return super().run(sql=self._strip_sql(hql), parameters=parameters)
<ide>
<ide><path>tests/providers/telegram/operators/test_telegram.py
<ide> def test_should_send_message_when_all_parameters_are_provided(self, mock_telegra
<ide> task_id='telegram',
<ide> text="some non empty text",
<ide> )
<del> hook.execute()
<add> hook.execute(None)
<ide>
<ide> mock_telegram_hook.assert_called_once_with(
<ide> telegram_conn_id='telegram_default',
<ide> def side_effect(*args, **kwargs):
<ide> task_id='telegram',
<ide> text="some non empty text",
<ide> )
<del> hook.execute()
<add> hook.execute(None)
<ide>
<ide> assert "cosmic rays caused bit flips" == str(ctx.value)
<ide>
<ide> def test_should_forward_all_args_to_telegram(self, mock_telegram_hook):
<ide> text="some non empty text",
<ide> telegram_kwargs={"custom_arg": "value"},
<ide> )
<del> hook.execute()
<add> hook.execute(None)
<ide>
<ide> mock_telegram_hook.assert_called_once_with(
<ide> telegram_conn_id='telegram_default',
<ide> def test_should_give_precedence_to_text_passed_in_constructor(self, mock_telegra
<ide> text="some non empty text - higher precedence",
<ide> telegram_kwargs={"custom_arg": "value", "text": "some text, that will be ignored"},
<ide> )
<del> hook.execute()
<add> hook.execute(None)
<ide>
<ide> mock_telegram_hook.assert_called_once_with(
<ide> telegram_conn_id='telegram_default',
<ide> def test_should_return_templatized_text_field(self, mock_hook):
<ide> telegram_kwargs={"custom_arg": "value", "text": "should be ignored"},
<ide> )
<ide> operator.render_template_fields({"ds": "2021-02-04"})
<del> operator.execute()
<add>
<add> operator.execute(None)
<ide> assert operator.text == "execution date is 2021-02-04"
<ide> assert 'text' in operator.telegram_kwargs
<ide> assert operator.telegram_kwargs['text'] == "execution date is 2021-02-04" | 10 |
Python | Python | add basic tree structure and text display | a3f5dc51673278364b23c2e5b15d7439ac0a9924 | <ide><path>glances/core/glances_processes.py
<ide> import psutil
<ide> import re
<ide>
<add>PROCESS_TREE = True # TODO remove that and take command line parameter
<add>
<add>
<add>class ProcessTreeNode(object):
<add>
<add> def __init__(self, process=None):
<add> self.process = process # is None for tree root node
<add> self.children = []
<add>
<add> def __str__(self):
<add> """ Return the tree as text for debugging. """
<add> lines = []
<add> is_root = self.process is None
<add> if is_root:
<add> lines.append("#")
<add> else:
<add> lines.append("[%s]" % (self.process.name()))
<add> indent_str = " " * len(lines[-1])
<add> child_lines = []
<add> for child in self.children:
<add> for i, line in enumerate(str(child).splitlines()):
<add> if i == 0:
<add> if child is self.children[0]:
<add> if len(self.children) == 1:
<add> tree_char = "─"
<add> else:
<add> tree_char = "┌"
<add> elif child is self.children[-1]:
<add> tree_char = "└"
<add> else:
<add> tree_char = "├"
<add> child_lines.append(tree_char + "─ " + line)
<add> else:
<add> if is_root:
<add> child_lines.append("│ " + indent_str + line)
<add> else:
<add> child_lines.append(indent_str + line)
<add> if child_lines:
<add> lines[-1] += child_lines[0]
<add> for child_line in child_lines[1:]:
<add> lines.append(indent_str + child_line)
<add> return "\n".join(lines)
<add>
<add> def findProcess(self, process):
<add> """ Search in tree for the ProcessTreeNode owning process, and return it or None if not found. """
<add> assert(process is not None)
<add> if self.process is process:
<add> return self
<add> for child in self.children:
<add> node = child.findProcess(process)
<add> if node is not None:
<add> return node
<add>
<add> @staticmethod
<add> def buildTree(processes):
<add> """ Build a process tree using using parent/child relationships, and return the root node. """
<add> tree_root = ProcessTreeNode()
<add> for process in processes:
<add> assert(process is not None)
<add> new_node = ProcessTreeNode(process)
<add> parent_process = process.parent()
<add> if parent_process is None:
<add> # no parent, add this node at the top level
<add> tree_root.children.append(new_node)
<add> else:
<add> parent_node = tree_root.findProcess(parent_process)
<add> if parent_node is not None:
<add> # parent is already in the tree, add a new child
<add> parent_node.children.append(new_node) # marche pas
<add> else:
<add> # parent is not in tree, add this node at the top level
<add> tree_root.children.append(new_node)
<add> return tree_root
<add>
<add>
<ide>
<ide> class GlancesProcesses(object):
<ide>
<ide> def update(self):
<ide> except:
<ide> pass
<ide>
<add> if PROCESS_TREE:
<add> tree = ProcessTreeNode.buildTree(processdict.keys())
<add> print(tree)
<add> exit(0)
<add>
<ide> # Process optimization
<ide> # Only retreive stats for visible processes (get_max_processes)
<ide> if self.get_max_processes() is not None: | 1 |
Javascript | Javascript | remove unreachable code | 5c783ee75102da682519be14cd11260a04a42593 | <ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> function completeUnitOfWork(workInProgress: Fiber): Fiber | null {
<ide> nextRenderExpirationTime,
<ide> );
<ide> }
<del> let next = nextUnitOfWork;
<ide> stopWorkTimer(workInProgress);
<ide> resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
<ide> if (__DEV__) {
<ide> ReactCurrentFiber.resetCurrentFiber();
<ide> }
<ide>
<del> if (next !== null) {
<del> stopWorkTimer(workInProgress);
<del> if (__DEV__ && ReactFiberInstrumentation.debugTool) {
<del> ReactFiberInstrumentation.debugTool.onCompleteWork(workInProgress);
<del> }
<del> // If completing this work spawned new work, do that next. We'll come
<del> // back here again.
<del> return next;
<del> }
<del>
<ide> if (
<ide> returnFiber !== null &&
<ide> // Do not append effects to parents if a sibling failed to complete | 1 |
PHP | PHP | avoid boolean cast | f79d34ec7e8e65e5c342f8c77dc50468d47073c5 | <ide><path>src/Datasource/EntityTrait.php
<ide> public function dirty($property = null, $isDirty = null) {
<ide> return isset($this->_dirty[$property]);
<ide> }
<ide>
<del> if (!$isDirty) {
<add> if ($isDirty === false) {
<ide> unset($this->_dirty[$property]);
<ide> return false;
<ide> } | 1 |
Java | Java | update copyright header | bf6e7d0c26199d65d840a081cba4d20ada78dcc5 | <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2017 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. | 1 |
PHP | PHP | reduce code duplication | db3ce0f08be8c95a08d0b29fb401de87e2d55c28 | <ide><path>src/Error/Debugger.php
<ide> protected static function export($var, DebugContext $context): NodeInterface
<ide> {
<ide> $type = static::getType($var);
<ide> switch ($type) {
<add> case 'float':
<add> case 'string':
<add> case 'resource':
<add> case 'resource (closed)':
<add> case 'null':
<add> return new ScalarNode($type, $var);
<ide> case 'boolean':
<ide> return new ScalarNode('bool', $var);
<ide> case 'integer':
<ide> return new ScalarNode('int', $var);
<del> case 'float':
<del> case 'string':
<del> return new ScalarNode($type, $var);
<ide> case 'array':
<ide> return static::exportArray($var, $context->withAddedDepth());
<del> case 'resource':
<del> case 'resource (closed)':
<del> return new ScalarNode($type, $var);
<del> case 'null':
<del> return new ScalarNode('null', null);
<ide> case 'unknown':
<ide> return new SpecialNode('(unknown)');
<ide> default: | 1 |
Ruby | Ruby | install service after linking | 391b02f870e7db3d3208729ab636372f6677daf4 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def finish
<ide>
<ide> ohai "Finishing up" if verbose?
<ide>
<del> install_service
<del>
<ide> keg = Keg.new(formula.prefix)
<ide> link(keg)
<ide>
<add> install_service
<add>
<ide> fix_dynamic_linkage(keg) if !@poured_bottle || !formula.bottle_specification.skip_relocation?
<ide>
<ide> if build_bottle? | 1 |
PHP | PHP | fix whitespace errors | ccd33782dac71ddf4a758cae68282eadb3c0c0a3 | <ide><path>lib/Cake/Test/Case/Utility/FolderTest.php
<ide> public function testCopyWithSkip() {
<ide> *
<ide> * @return void
<ide> */
<del> function testCopyWithOverwrite() {
<add> public function testCopyWithOverwrite() {
<ide> extract($this->_setupFilesystem());
<ide>
<ide> $Folder = new Folder($folderOne);
<ide> public function testMove() {
<ide> $this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
<ide> $this->assertEquals('', file_get_contents($folderTwoB . DS . 'fileB.php'));
<ide> $this->assertFalse(file_exists($fileOne));
<del> $this->assertFalse(file_exists($folderOneA));
<add> $this->assertFalse(file_exists($folderOneA));
<ide> $this->assertFalse(file_exists($fileOneA));
<ide>
<ide> $Folder = new Folder($path); | 1 |
Go | Go | add a benchmark for taruntar | 76429cc11f6e2bd731e9ee77a2a538f15ef80eea | <ide><path>archive/archive_test.go
<ide> func TestUntarUstarGnuConflict(t *testing.T) {
<ide> t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
<ide> }
<ide> }
<add>
<add>func prepareUntarSourceDirectory(numberOfFiles int, targetPath string) (int, error) {
<add> fileData := []byte("fooo")
<add> for n := 0; n < numberOfFiles; n++ {
<add> fileName := fmt.Sprintf("file-%d", n)
<add> if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil {
<add> return 0, err
<add> }
<add> }
<add> totalSize := numberOfFiles * len(fileData)
<add> return totalSize, nil
<add>}
<add>
<add>func BenchmarkTarUntar(b *testing.B) {
<add> origin, err := ioutil.TempDir("", "docker-test-untar-origin")
<add> if err != nil {
<add> b.Fatal(err)
<add> }
<add> tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
<add> if err != nil {
<add> b.Fatal(err)
<add> }
<add> target := path.Join(tempDir, "dest")
<add> n, err := prepareUntarSourceDirectory(100, origin)
<add> if err != nil {
<add> b.Fatal(err)
<add> }
<add> b.ResetTimer()
<add> b.SetBytes(int64(n))
<add> defer os.RemoveAll(origin)
<add> defer os.RemoveAll(tempDir)
<add> for n := 0; n < b.N; n++ {
<add> err := TarUntar(origin, target)
<add> if err != nil {
<add> b.Fatal(err)
<add> }
<add> os.RemoveAll(target)
<add> }
<add>} | 1 |
Javascript | Javascript | fix diffiehellman `generator` validation | 88bc8645e733ee3f9b86272b6c1ae9c1da7790c9 | <ide><path>lib/internal/crypto/diffiehellman.js
<ide> function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) {
<ide> generator = DH_GENERATOR;
<ide> } else if (typeof generator === 'number') {
<ide> validateInt32(generator, 'generator');
<del> } else if (generator !== true) {
<add> } else if (typeof generator === 'string') {
<ide> generator = toBuf(generator, genEncoding);
<del> } else {
<add> } else if (!isArrayBufferView(generator) && !isAnyArrayBuffer(generator)) {
<ide> throw new ERR_INVALID_ARG_TYPE(
<ide> 'generator',
<ide> ['number', 'string', 'ArrayBuffer', 'Buffer', 'TypedArray', 'DataView'],
<ide><path>test/parallel/test-crypto-dh.js
<ide> assert.throws(
<ide> code: 'ERR_INVALID_ARG_TYPE'
<ide> }
<ide> );
<add>[true, Symbol(), {}, () => {}, []].forEach((generator) => assert.throws(
<add> () => crypto.createDiffieHellman('', 'base64', generator),
<add> { code: 'ERR_INVALID_ARG_TYPE' }
<add>)); | 2 |
Javascript | Javascript | add a `kind` property to gutters | dbace171df4c31a931997ef75fa1f451ba86dcbc | <ide><path>spec/text-editor-spec.js
<ide> describe('TextEditor', () => {
<ide> const gutter = editor.addGutter(options)
<ide> expect(editor.getGutters().length).toBe(2)
<ide> expect(editor.getGutters()[1]).toBe(gutter)
<add> expect(gutter.kind).toBe('decorated')
<add> })
<add>
<add> it('can add a custom line-number gutter', () => {
<add> expect(editor.getGutters().length).toBe(1)
<add> const options = {
<add> name: 'another-gutter',
<add> priority: 2,
<add> kind: 'line-number'
<add> }
<add> const gutter = editor.addGutter(options)
<add> expect(editor.getGutters().length).toBe(2)
<add> expect(editor.getGutters()[1]).toBe(gutter)
<add> expect(gutter.kind).toBe('line-number')
<ide> })
<ide>
<ide> it("does not allow a custom gutter with the 'line-number' name.", () => expect(editor.addGutter.bind(editor, {name: 'line-number'})).toThrow())
<ide><path>src/gutter-container.js
<ide> module.exports = class GutterContainer {
<ide>
<ide> // The public interface is Gutter::decorateMarker or TextEditor::decorateMarker.
<ide> addGutterDecoration (gutter, marker, options) {
<del> if (gutter.name === 'line-number') {
<add> if (gutter.kind === 'line-number') {
<ide> options.type = 'line-number'
<ide> } else {
<ide> options.type = 'gutter'
<ide><path>src/gutter.js
<ide> module.exports = class Gutter {
<ide> this.name = options && options.name
<ide> this.priority = (options && options.priority != null) ? options.priority : DefaultPriority
<ide> this.visible = (options && options.visible != null) ? options.visible : true
<add> this.kind = (options && options.kind != null) ? options.kind : 'decorated'
<add> this.labelFn = options && options.labelFn
<ide>
<ide> this.emitter = new Emitter()
<ide> }
<ide><path>src/text-editor.js
<ide> class TextEditor {
<ide> this.gutterContainer = new GutterContainer(this)
<ide> this.lineNumberGutter = this.gutterContainer.addGutter({
<ide> name: 'line-number',
<add> kind: 'line-number',
<ide> priority: 0,
<ide> visible: params.lineNumberGutterVisible
<ide> })
<ide> class TextEditor {
<ide> // window. (default: -100)
<ide> // * `visible` (optional) {Boolean} specifying whether the gutter is visible
<ide> // initially after being created. (default: true)
<add> // * `type` (optional) {String} specifying the type of gutter to create. `'decorated'`
<add> // gutters are useful as a destination for decorations created with {Gutter::decorateMarker}.
<add> // `'line-number'` gutters
<add> // * `labelFn` (optional) {Function} called by a `'line-number'` gutter to generate the label for each line number
<add> // element. Should return a {String} that will be used to label the corresponding line.
<add> // * `lineData` an {Object} containing information about each line to label.
<add> // * `bufferRow` {Number} indicating the zero-indexed buffer index of this line.
<add> // * `screenRow` {Number} indicating the zero-indexed screen index.
<add> // * `foldable` {Boolean} that is `true` if a fold may be created here.
<add> // * `softWrapped` {Boolean} if this screen row is the soft-wrapped continuation of the same buffer row.
<ide> //
<ide> // Returns the newly-created {Gutter}.
<ide> addGutter (options) { | 4 |
PHP | PHP | change method visibility | 46186ccbb8069514eac8b0dc5951f12afaa69dee | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function register(ServiceProvider $provider, $options = array())
<ide> *
<ide> * @return void
<ide> */
<del> protected function loadDeferredProviders()
<add> public function loadDeferredProviders()
<ide> {
<ide> // We will simply spin through each of the deferred providers and register each
<ide> // one and boot them if the application has booted. This should make each of | 1 |
Python | Python | add simple .dmg build to paver | 89d874eaa8a0c95fde53f705a9b17706f5567cf5 | <ide><path>pavement.py
<ide> import os
<ide> import sys
<ide> import subprocess
<add>import re
<ide> try:
<ide> from hash import md5
<ide> except ImportError:
<ide> import paver.doctools
<ide> import paver.path
<ide> from paver.easy import options, Bunch, task, needs, dry, sh, call_task
<del>from paver.setuputils import setup
<add>
<add>from setup import FULLVERSION
<ide>
<ide> # Wine config for win32 builds
<ide> WINE_SITE_CFG = ""
<ide> def _bdist_wininst(pyver):
<ide> if exists:
<ide> paver.path.path('site.cfg.bak').move(site)
<ide>
<add># Mac OS X installer
<add>def macosx_version():
<add> if not sys.platform == 'darwin':
<add> raise ValueError("Not darwin ??")
<add> st = subprocess.Popen(["sw_vers"], stdout=subprocess.PIPE)
<add> out = st.stdout.readlines()
<add> ver = re.compile("ProductVersion:\s+([0-9]+)\.([0-9]+)\.([0-9]+)")
<add> for i in out:
<add> m = ver.match(i)
<add> if m:
<add> return m.groups()
<add>
<add>def mpkg_name():
<add> maj, min = macosx_version()[:2]
<add> pyver = ".".join([str(i) for i in sys.version_info[:2]])
<add> return "numpy-%s-py%s-macosx%s.%s.mpkg" % \
<add> (FULLVERSION, pyver, maj, min)
<add>
<add>@task
<add>@needs("setuptools.bdist_mpkg", "doc")
<add>def dmg():
<add> pyver = ".".join([str(i) for i in sys.version_info[:2]])
<add> builddir = paver.path.path("build") / "dmg"
<add> builddir.rmtree()
<add> builddir.mkdir()
<add>
<add> # Copy mpkg into image source
<add> mpkg_n = mpkg_name()
<add> mpkg = paver.path.path("dist") / mpkg_n
<add> mpkg.copytree(builddir / mpkg_n)
<add> tmpkg = builddir / mpkg_n
<add> tmpkg.rename(builddir / ("numpy-%s-py%s.mpkg" % (FULLVERSION, pyver)))
<add>
<add> # Copy docs into image source
<add> doc_root = paver.path.path(builddir) / "docs"
<add> html_docs = paver.path.path("docs") / "html"
<add> #pdf_docs = paver.path.path("docs") / "pdf" / "numpy.pdf"
<add> html_docs.copytree(doc_root / "html")
<add> #pdf_docs.copy(doc_root / "numpy.pdf")
<add>
<add> # Build the dmg
<add> image_name = "numpy-%s.dmg" % FULLVERSION
<add> image = paver.path.path(image_name)
<add> image.remove()
<add> cmd = ["hdiutil", "create", image_name, "-srcdir", str(builddir)]
<add> sh(" ".join(cmd)) | 1 |
Go | Go | add quoted string flag value | e4c1f0772923c3069ce14a82d445cd55af3382bc | <ide><path>opts/quotedstring.go
<add>package opts
<add>
<add>// QuotedString is a string that may have extra quotes around the value. The
<add>// quotes are stripped from the value.
<add>type QuotedString string
<add>
<add>// Set sets a new value
<add>func (s *QuotedString) Set(val string) error {
<add> *s = QuotedString(trimQuotes(val))
<add> return nil
<add>}
<add>
<add>// Type returns the type of the value
<add>func (s *QuotedString) Type() string {
<add> return "string"
<add>}
<add>
<add>func (s *QuotedString) String() string {
<add> return string(*s)
<add>}
<add>
<add>func trimQuotes(value string) string {
<add> lastIndex := len(value) - 1
<add> for _, char := range []byte{'\'', '"'} {
<add> if value[0] == char && value[lastIndex] == char {
<add> return value[1:lastIndex]
<add> }
<add> }
<add> return value
<add>}
<ide><path>opts/quotedstring_test.go
<add>package opts
<add>
<add>import (
<add> "github.com/docker/docker/pkg/testutil/assert"
<add> "testing"
<add>)
<add>
<add>func TestQuotedStringSetWithQuotes(t *testing.T) {
<add> qs := QuotedString("")
<add> assert.NilError(t, qs.Set("\"something\""))
<add> assert.Equal(t, qs.String(), "something")
<add>}
<add>
<add>func TestQuotedStringSetWithMismatchedQuotes(t *testing.T) {
<add> qs := QuotedString("")
<add> assert.NilError(t, qs.Set("\"something'"))
<add> assert.Equal(t, qs.String(), "\"something'")
<add>}
<add>
<add>func TestQuotedStringSetWithNoQuotes(t *testing.T) {
<add> qs := QuotedString("")
<add> assert.NilError(t, qs.Set("something"))
<add> assert.Equal(t, qs.String(), "something")
<add>} | 2 |
Javascript | Javascript | copy jsm folder when getting new three.js | aa2db5e656e377ff0157ab21154246149267847c | <ide><path>Gruntfile.js
<ide> module.exports = function(grunt) {
<ide> { expand: true, cwd: `${threePath}/build/`, src: 'three.js', dest: `${basePath}/`, },
<ide> { expand: true, cwd: `${threePath}/build/`, src: 'three.min.js', dest: `${basePath}/`, },
<ide> { expand: true, cwd: `${threePath}/examples/js/`, src: '**', dest: `${basePath}/js/`, },
<add> { expand: true, cwd: `${threePath}/examples/jsm/`, src: '**', dest: `${basePath}/js/`, },
<ide> ],
<ide> },
<ide> }, | 1 |
Javascript | Javascript | use an apostrophe rather than a prime (#566) | 369bc873f8e41ac29ec844bb4dee532cb086daa5 | <ide><path>examples/nested-components/pages/index.js
<ide> export default () => (
<ide> <hr />
<ide>
<ide> <Post title='The final blog post'>
<del> <P>C'est fin</P>
<add> <P>C’est fin</P>
<ide> </Post>
<ide>
<ide> <style jsx>{` | 1 |
Ruby | Ruby | add url to #find_versions object | 077fb350a5c10aad93c3b01a5406dfdd3ad229ce | <ide><path>Library/Homebrew/livecheck/strategy/extract_plist.rb
<ide> def self.versions_from_items(items, regex = nil, &block)
<ide> # versions from `plist` files.
<ide> #
<ide> # @param cask [Cask::Cask] the cask to check for version information
<add> # @param url [String, nil] an alternative URL to check for version
<add> # information
<ide> # @param regex [Regexp, nil] a regex for use in a strategy block
<ide> # @return [Hash]
<ide> sig {
<ide> def self.find_versions(cask:, url: nil, regex: nil, **_unused, &block)
<ide> end
<ide> raise ArgumentError, "The #{T.must(name).demodulize} strategy only supports casks." unless T.unsafe(cask)
<ide>
<del> match_data = { matches: {}, regex: regex }
<add> match_data = { matches: {}, regex: regex, url: url }
<ide>
<ide> if url && url != cask.url.to_s
<ide> cask_object_for_livecheck = Cask::Cask.new("livecheck-cask", config: cask.config) do | 1 |
PHP | PHP | add notes to iterator unset calls | c485a4db6314a51f97fdd324ec1ecda497bb3eca | <ide><path>src/Cache/Engine/FileEngine.php
<ide> public function clear(): bool
<ide> $cleared[] = $path;
<ide> }
<ide>
<add> // possible inner iterators need to be unset too in order for locks on parents to be released
<ide> unset($fileInfo);
<ide> }
<ide>
<add> // unsetting iterators helps releasing possible locks in certain environments,
<add> // which could otherwise make `rmdir()` fail
<ide> unset($directory, $contents);
<ide>
<ide> return true;
<ide><path>src/Filesystem/Filesystem.php
<ide> public function deleteDir(string $path): bool
<ide>
<ide> // phpcs:ignore
<ide> $result = $result && @unlink($fileInfo->getPathname());
<add> // possible inner iterators need to be unset too in order for locks on parents to be released
<ide> unset($fileInfo);
<ide> }
<ide>
<add> // unsetting iterators helps releasing possible locks in certain environments,
<add> // which could otherwise make `rmdir()` fail
<ide> unset($iterator);
<ide>
<ide> // phpcs:ignore
<ide><path>src/Filesystem/Folder.php
<ide> public function tree(?string $path = null, $exceptions = false, ?string $type =
<ide> $directories[] = $itemPath;
<ide> }
<ide>
<add> // inner iterators need to be unset too in order for locks on parents to be released
<ide> unset($fsIterator, $item);
<ide> }
<ide>
<add> // unsetting iterators helps releasing possible locks in certain environments,
<add> // which could otherwise make `rmdir()` fail
<ide> unset($directory, $iterator);
<ide>
<ide> if ($type === null) {
<ide> public function delete(?string $path = null): bool
<ide> } else {
<ide> $this->_errors[] = sprintf('%s NOT removed', $filePath);
<ide>
<add> // inner iterators need to be unset too in order for locks on parents to be released
<ide> unset($directory, $iterator, $item);
<ide>
<ide> return false;
<ide> }
<ide> }
<ide> }
<ide>
<add> // unsetting iterators helps releasing possible locks in certain environments,
<add> // which could otherwise make `rmdir()` fail
<ide> unset($directory, $iterator);
<ide>
<ide> $path = rtrim($path, DIRECTORY_SEPARATOR); | 3 |
Javascript | Javascript | add test for watching prop | ad91fc63b3b09297eb1b0a410a1f63c75db63fa0 | <ide><path>test/Compiler.test.js
<ide> describe("Compiler", () => {
<ide> });
<ide> });
<ide> });
<add> it("should set compiler.watching correctly", function (done) {
<add> const compiler = webpack({
<add> context: __dirname,
<add> mode: "production",
<add> entry: "./c",
<add> output: {
<add> path: "/directory",
<add> filename: "bundle.js"
<add> }
<add> });
<add> compiler.outputFileSystem = createFsFromVolume(new Volume());
<add> const watching = compiler.watch({}, (err, stats) => {
<add> if (err) return done(err);
<add> done();
<add> });
<add> expect(compiler.watching).toBe(watching);
<add> });
<ide> it("should watch again correctly after first closed watch", function (done) {
<ide> const compiler = webpack({
<ide> context: __dirname, | 1 |
PHP | PHP | update flashcomponent to use flashmessage | e664b61dce341cb80b4c7aa3ed2d6700d8bc39e7 | <ide><path>src/Controller/Component/FlashComponent.php
<ide>
<ide> use Cake\Controller\Component;
<ide> use Cake\Http\Exception\InternalErrorException;
<del>use Cake\Http\Session;
<add>use Cake\Http\FlashMessage;
<ide> use Cake\Utility\Inflector;
<ide> use Throwable;
<ide>
<ide> class FlashComponent extends Component
<ide> */
<ide> public function set($message, array $options = []): void
<ide> {
<del> $options += (array)$this->getConfig();
<del>
<ide> if ($message instanceof Throwable) {
<del> if (!isset($options['params']['code'])) {
<del> $options['params']['code'] = $message->getCode();
<del> }
<del> $message = $message->getMessage();
<add> $this->flash()->setExceptionMessage($message, $options);
<add> } else {
<add> $this->flash()->set($message, $options);
<ide> }
<add> }
<ide>
<del> if (isset($options['escape']) && !isset($options['params']['escape'])) {
<del> $options['params']['escape'] = $options['escape'];
<del> }
<add> /**
<add> * Get flash message utility instance.
<add> *
<add> * @return \Cake\Http\FlashMessage
<add> */
<add> protected function flash(): FlashMessage
<add> {
<add> return $this->getController()->getRequest()->getFlash();
<add> }
<ide>
<del> [$plugin, $element] = pluginSplit($options['element']);
<add> /**
<add> * Proxy method to FlashMessage instance.
<add> *
<add> * @param string|array $key The key to set, or a complete array of configs.
<add> * @param mixed|null $value The value to set.
<add> * @param bool $merge Whether to recursively merge or overwrite existing config, defaults to true.
<add> * @return $this
<add> * @throws \Cake\Core\Exception\CakeException When trying to set a key that is invalid.
<add> */
<add> public function setConfig($key, $value = null, $merge = true)
<add> {
<add> $this->flash()->setConfig($key, $value, $merge);
<ide>
<del> if ($plugin) {
<del> $options['element'] = $plugin . '.flash/' . $element;
<del> } else {
<del> $options['element'] = 'flash/' . $element;
<del> }
<add> return $this;
<add> }
<ide>
<del> $messages = [];
<del> if (!$options['clear']) {
<del> $messages = (array)$this->getSession()->read('Flash.' . $options['key']);
<del> }
<add> /**
<add> * Proxy method to FlashMessage instance.
<add> *
<add> * @param string|null $key The key to get or null for the whole config.
<add> * @param mixed $default The return value when the key does not exist.
<add> * @return mixed Configuration data at the named key or null if the key does not exist.
<add> */
<add> public function getConfig(?string $key = null, $default = null)
<add> {
<add> return $this->flash()->getConfig($key, $default);
<add> }
<ide>
<del> if (!$options['duplicate']) {
<del> foreach ($messages as $existingMessage) {
<del> if ($existingMessage['message'] === $message) {
<del> return;
<del> }
<del> }
<del> }
<add> /**
<add> * Proxy method to FlashMessage instance.
<add> *
<add> * @param string $key The key to get.
<add> * @return mixed Configuration data at the named key
<add> * @throws \InvalidArgumentException
<add> */
<add> public function getConfigOrFail(string $key)
<add> {
<add> return $this->flash()->getConfigOrFail($key);
<add> }
<ide>
<del> $messages[] = [
<del> 'message' => $message,
<del> 'key' => $options['key'],
<del> 'element' => $options['element'],
<del> 'params' => $options['params'],
<del> ];
<add> /**
<add> * Proxy method to FlashMessage instance.
<add> *
<add> * @param string|array $key The key to set, or a complete array of configs.
<add> * @param mixed|null $value The value to set.
<add> * @return $this
<add> */
<add> public function configShallow($key, $value = null)
<add> {
<add> $this->flash()->configShallow($key, $value);
<ide>
<del> $this->getSession()->write('Flash.' . $options['key'], $messages);
<add> return $this;
<ide> }
<ide>
<ide> /**
<ide> public function __call(string $name, array $args)
<ide>
<ide> $this->set($args[0], $options);
<ide> }
<del>
<del> /**
<del> * Returns current session object from a controller request.
<del> *
<del> * @return \Cake\Http\Session
<del> */
<del> protected function getSession(): Session
<del> {
<del> return $this->getController()->getRequest()->getSession();
<del> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/FlashComponentTest.php
<ide> public function testSetWithException(): void
<ide> [
<ide> 'message' => 'This is a test message',
<ide> 'key' => 'flash',
<del> 'element' => 'flash/default',
<add> 'element' => 'flash/error',
<ide> 'params' => ['code' => 404],
<ide> ],
<ide> ]; | 2 |
Java | Java | avoid unnecessary wrapping for sqlparametervalue | 2fbfd8a5dbb32f74fee9c0a22dc4a402d3c6680f | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.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> *
<ide> * @author Thomas Risberg
<ide> * @author Juergen Hoeller
<add> * @author Yanming Zhou
<ide> * @since 2.0
<ide> */
<ide> public abstract class NamedParameterUtils {
<ide> public static Object[] buildValueArray(
<ide> String paramName = paramNames.get(i);
<ide> try {
<ide> SqlParameter param = findParameter(declaredParams, paramName, i);
<del> paramArray[i] = (param != null ? new SqlParameterValue(param, paramSource.getValue(paramName)) :
<del> SqlParameterSourceUtils.getTypedValue(paramSource, paramName));
<add> Object paramValue = paramSource.getValue(paramName);
<add> if (paramValue instanceof SqlParameterValue) {
<add> paramArray[i] = paramValue;
<add> }
<add> else {
<add> paramArray[i] = (param != null ? new SqlParameterValue(param, paramValue) :
<add> SqlParameterSourceUtils.getTypedValue(paramSource, paramName));
<add> }
<ide> }
<ide> catch (IllegalArgumentException ex) {
<ide> throw new InvalidDataAccessApiUsageException(
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.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> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.dao.InvalidDataAccessApiUsageException;
<add>import org.springframework.jdbc.core.SqlParameterValue;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
<ide> * @author Juergen Hoeller
<ide> * @author Rick Evans
<ide> * @author Artur Geraschenko
<add> * @author Yanming Zhou
<ide> */
<ide> public class NamedParameterUtilsTests {
<ide>
<ide> public void convertTypeMapToArray() {
<ide> .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]).isEqualTo(2);
<ide> }
<ide>
<add> @Test
<add> public void convertSqlParameterValueToArray() {
<add> SqlParameterValue sqlParameterValue = new SqlParameterValue(2, "b");
<add> Map<String, Object> paramMap = new HashMap<>();
<add> paramMap.put("a", "a");
<add> paramMap.put("b", sqlParameterValue);
<add> paramMap.put("c", "c");
<add> assertThat(NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]).isSameAs(sqlParameterValue);
<add> MapSqlParameterSource namedParams = new MapSqlParameterSource();
<add> namedParams.addValue("a", "a", 1).addValue("b", sqlParameterValue).addValue("c", "c", 3);
<add> assertThat(NamedParameterUtils
<add> .buildValueArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams, null)[4]).isSameAs(sqlParameterValue);
<add> }
<add>
<ide> @Test
<ide> public void convertTypeMapToSqlParameterList() {
<ide> MapSqlParameterSource namedParams = new MapSqlParameterSource(); | 2 |
Javascript | Javascript | remove duplicate from blacklisted usernames | c886ebfa92da54c362eff1babfab5bf0de2abada | <ide><path>server/utils/constants.js
<ide> export const blacklistedUsernames = [
<ide> 'completed-field-guide',
<ide> 'jobs',
<ide> 'nonprofits',
<del> 'api',
<ide> 'sitemap.xml',
<ide> 'get-help',
<ide> 'chat', | 1 |
Javascript | Javascript | adapt missed test to new expando name | c97c5cec2ff566d775c0f4996fa6647711c6fbab | <ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> elementName = parts.shift();
<ide> parts.sort();
<ide> parts.unshift(elementName);
<del> forEach(parts, function(value, key){
<del> if (value.substring(0,3) !== 'ng-') {
<add> forEach(parts, function(value){
<add> if (value.substring(0,2) !== 'ng') {
<ide> value = value.replace('=""', '');
<ide> var match = value.match(/=(.*)/);
<ide> if (match && match[1].charAt(0) != '"') { | 1 |
PHP | PHP | add assertions for cc, bcc & attachments | 23733853ffb2f65894ef434c7df1101a0112f931 | <ide><path>src/TestSuite/EmailAssertTrait.php
<ide> public function assertEmailSubject($expected, $message = null)
<ide> * @param string $message The failure message to define.
<ide> * @return void
<ide> */
<del> public function assertEmailFrom($email, $name, $message = null)
<add> public function assertEmailFrom($email, $name = null, $message = null)
<ide> {
<add> if ($name === null) {
<add> $name = $email;
<add> }
<add>
<ide> $expected = [$email => $name];
<ide> $result = $this->email()->from();
<ide> $this->assertSame($expected, $result, $message);
<ide> public function assertEmailFrom($email, $name, $message = null)
<ide> * @param string $message The failure message to define.
<ide> * @return void
<ide> */
<del> public function assertEmailTo($email, $name, $message = null)
<add> public function assertEmailCc($email, $name = null, $message = null)
<ide> {
<add> if ($name === null) {
<add> $name = $email;
<add> }
<add>
<add> $expected = [$email => $name];
<add> $result = $this->email()->cc();
<add> $this->assertSame($expected, $result, $message);
<add> }
<add>
<add> /**
<add> * @param string $email Sender's email address.
<add> * @param string $name Sender's name.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailCcContains($email, $name = null, $message = null)
<add> {
<add> $result = $this->email()->cc();
<add> $this->assertNotEmpty($result[$email], $message);
<add> if ($name !== null) {
<add> $this->assertEquals($result[$email], $name, $message);
<add> }
<add> }
<add>
<add> /**
<add> * @param string $email Sender's email address.
<add> * @param string $name Sender's name.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailBcc($email, $name = null, $message = null)
<add> {
<add> if ($name === null) {
<add> $name = $email;
<add> }
<add>
<add> $expected = [$email => $name];
<add> $result = $this->email()->bcc();
<add> $this->assertSame($expected, $result, $message);
<add> }
<add>
<add> /**
<add> * @param string $email Sender's email address.
<add> * @param string $name Sender's name.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailBccContains($email, $name = null, $message = null)
<add> {
<add> $result = $this->email()->bcc();
<add> $this->assertNotEmpty($result[$email], $message);
<add> if ($name !== null) {
<add> $this->assertEquals($result[$email], $name, $message);
<add> }
<add> }
<add>
<add> /**
<add> * @param string $email Sender's email address.
<add> * @param string $name Sender's name.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailTo($email, $name = null, $message = null)
<add> {
<add> if ($name === null) {
<add> $name = $email;
<add> }
<add>
<ide> $expected = [$email => $name];
<ide> $result = $this->email()->to();
<ide> $this->assertSame($expected, $result, $message);
<ide> }
<add>
<add> /**
<add> * @param string $email Sender's email address.
<add> * @param string $name Sender's name.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailToContains($email, $name = null, $message = null)
<add> {
<add> $result = $this->email()->to();
<add> $this->assertNotEmpty($result[$email], $message);
<add> if ($name !== null) {
<add> $this->assertEquals($result[$email], $name, $message);
<add> }
<add> }
<add>
<add> /**
<add> * @param string $expected Expected attachment.
<add> * @param string $message The failure message to define.
<add> * @return void
<add> */
<add> public function assertEmailAttachmentsContains($filename, array $file = null, $message = null)
<add> {
<add> $result = $this->email()->attachments();
<add> $this->assertNotEmpty($result[$filename], $message);
<add> if ($file === null) {
<add> return;
<add> }
<add> $this->assertContains($file, $result, $message);
<add> $this->assertEquals($file, $result[$filename], $message);
<add> }
<ide> } | 1 |
Java | Java | add support for multiple bridge listeners | 80bc07fd603b9ef27a1a2a977f03ee3e5a7b3e61 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarker.java
<ide>
<ide> package com.facebook.react.bridge;
<ide>
<add>import java.util.List;
<add>import java.util.ArrayList;
<add>
<ide> import javax.annotation.Nullable;
<ide>
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<ide> public interface MarkerListener {
<ide> void logMarker(ReactMarkerConstants name, @Nullable String tag, int instanceKey);
<ide> };
<ide>
<del> private static @Nullable MarkerListener sMarkerListener = null;
<add> // Use a list instead of a set here because we expect the number of listeners
<add> // to be very small, and we want listeners to be called in a deterministic
<add> // order.
<add> private static final List<MarkerListener> sListeners = new ArrayList<>();
<add>
<add> @DoNotStrip
<add> public static void addListener(MarkerListener listener) {
<add> synchronized(sListeners) {
<add> if (sListeners.indexOf(listener) == -1) {
<add> sListeners.add(listener);
<add> }
<add> }
<add> }
<ide>
<del> public static void initialize(MarkerListener listener) {
<del> if (sMarkerListener == null) {
<del> sMarkerListener = listener;
<add> @DoNotStrip
<add> public static void removeListener(MarkerListener listener) {
<add> synchronized(sListeners) {
<add> sListeners.remove(listener);
<ide> }
<ide> }
<ide>
<ide> @DoNotStrip
<del> public static void clearMarkerListener() {
<del> sMarkerListener = null;
<add> public static void clearMarkerListeners() {
<add> synchronized(sListeners) {
<add> sListeners.clear();
<add> }
<ide> }
<ide>
<ide> @DoNotStrip
<ide> public static void logMarker(String name, @Nullable String tag) {
<ide>
<ide> @DoNotStrip
<ide> public static void logMarker(String name, @Nullable String tag, int instanceKey) {
<del> if (sMarkerListener != null) {
<del> sMarkerListener.logMarker(ReactMarkerConstants.valueOf(name), tag, instanceKey);
<del> }
<add> ReactMarkerConstants marker = ReactMarkerConstants.valueOf(name);
<add> logMarker(marker, tag, instanceKey);
<ide> }
<ide>
<ide> @DoNotStrip
<ide> public static void logMarker(ReactMarkerConstants name, @Nullable String tag) {
<ide>
<ide> @DoNotStrip
<ide> public static void logMarker(ReactMarkerConstants name, @Nullable String tag, int instanceKey) {
<del> if (sMarkerListener != null) {
<del> sMarkerListener.logMarker(name, tag, instanceKey);
<add> synchronized(sListeners) {
<add> for (MarkerListener listener : sListeners) {
<add> listener.logMarker(name, tag, instanceKey);
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Java | Java | improve performance of some string operations | 260ebeca3ada9d0bd2d62c41256cafe81ac8ca03 | <ide><path>spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
<ide> Class<?> getBeanClass() {
<ide> PropertyDescriptor getPropertyDescriptor(String name) {
<ide> PropertyDescriptor pd = this.propertyDescriptorCache.get(name);
<ide> if (pd == null && StringUtils.hasLength(name)) {
<del> // Same lenient fallback checking as in PropertyTypeDescriptor...
<del> pd = this.propertyDescriptorCache.get(name.substring(0, 1).toLowerCase() + name.substring(1));
<add> // Same lenient fallback checking as in Property...
<add> pd = this.propertyDescriptorCache.get(StringUtils.uncapitalize(name));
<ide> if (pd == null) {
<del> pd = this.propertyDescriptorCache.get(name.substring(0, 1).toUpperCase() + name.substring(1));
<add> pd = this.propertyDescriptorCache.get(StringUtils.capitalize(name));
<ide> }
<ide> }
<ide> return (pd == null || pd instanceof GenericTypeAwarePropertyDescriptor ? pd :
<ide><path>spring-core/src/main/java/org/springframework/core/convert/Property.java
<ide> private Field getField() {
<ide> field = ReflectionUtils.findField(declaringClass, name);
<ide> if (field == null) {
<ide> // Same lenient fallback checking as in CachedIntrospectionResults...
<del> field = ReflectionUtils.findField(declaringClass,
<del> name.substring(0, 1).toLowerCase() + name.substring(1));
<add> field = ReflectionUtils.findField(declaringClass, StringUtils.uncapitalize(name));
<ide> if (field == null) {
<del> field = ReflectionUtils.findField(declaringClass,
<del> name.substring(0, 1).toUpperCase() + name.substring(1));
<add> field = ReflectionUtils.findField(declaringClass, StringUtils.capitalize(name));
<ide> }
<ide> }
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java
<ide> protected void addClassPathManifestEntries(Set<Resource> result) {
<ide> int prefixIndex = filePath.indexOf(':');
<ide> if (prefixIndex == 1) {
<ide> // Possibly "c:" drive prefix on Windows, to be upper-cased for proper duplicate detection
<del> filePath = filePath.substring(0, 1).toUpperCase() + filePath.substring(1);
<add> filePath = StringUtils.capitalize(filePath);
<ide> }
<ide> UrlResource jarResource = new UrlResource(ResourceUtils.JAR_URL_PREFIX +
<ide> ResourceUtils.FILE_URL_PREFIX + filePath + ResourceUtils.JAR_URL_SEPARATOR);
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java
<ide> public static String convertUnderscoreNameToPropertyName(@Nullable String name)
<ide> StringBuilder result = new StringBuilder();
<ide> boolean nextIsUpper = false;
<ide> if (name != null && name.length() > 0) {
<del> if (name.length() > 1 && name.substring(1, 2).equals("_")) {
<del> result.append(name.substring(0, 1).toUpperCase());
<add> if (name.length() > 1 && name.charAt(1) == '_') {
<add> result.append(Character.toUpperCase(name.charAt(0)));
<ide> }
<ide> else {
<del> result.append(name.substring(0, 1).toLowerCase());
<add> result.append(Character.toLowerCase(name.charAt(0)));
<ide> }
<ide> for (int i = 1; i < name.length(); i++) {
<del> String s = name.substring(i, i + 1);
<del> if (s.equals("_")) {
<add> char c = name.charAt(i);
<add> if (c == '_') {
<ide> nextIsUpper = true;
<ide> }
<ide> else {
<ide> if (nextIsUpper) {
<del> result.append(s.toUpperCase());
<add> result.append(Character.toUpperCase(c));
<ide> nextIsUpper = false;
<ide> }
<ide> else {
<del> result.append(s.toLowerCase());
<add> result.append(Character.toLowerCase(c));
<ide> }
<ide> }
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/StandardServletMultipartResolver.java
<ide>
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.util.StringUtils;
<ide> import org.springframework.web.multipart.MultipartException;
<ide> import org.springframework.web.multipart.MultipartHttpServletRequest;
<ide> import org.springframework.web.multipart.MultipartResolver;
<ide> public void setResolveLazily(boolean resolveLazily) {
<ide> @Override
<ide> public boolean isMultipart(HttpServletRequest request) {
<ide> // Same check as in Commons FileUpload...
<del> if (!"post".equals(request.getMethod().toLowerCase())) {
<add> if (!"post".equalsIgnoreCase(request.getMethod())) {
<ide> return false;
<ide> }
<ide> String contentType = request.getContentType();
<del> return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
<add> return StringUtils.startsWithIgnoreCase(contentType, "multipart/");
<ide> }
<ide>
<ide> @Override | 5 |
Python | Python | use short hand for security.utils | 7f5c81bd0a2e086ef7e607bf4352003c5bd996a1 | <ide><path>airflow/hooks/hive_hooks.py
<ide> from airflow.hooks.base_hook import BaseHook
<ide> from airflow.utils import TemporaryDirectory
<ide> from airflow.configuration import conf
<del>import airflow.security.utils
<add>import airflow.security.utils as utils
<ide>
<ide> class HiveCliHook(BaseHook):
<ide> """
<ide> def run_cli(self, hql, schema=None, verbose=True):
<ide> hive_bin = 'beeline'
<ide> if conf.get('security', 'enabled'):
<ide> template = conn.extra_dejson.get('principal',"hive/[email protected]")
<del> template = airflow.security.utils.replace_hostname_pattern(
<del> airflow.security.utils.get_components(template)
<del> )
<add> template = utils.replace_hostname_pattern(utils.get_components(template))
<ide>
<ide> proxy_user = ""
<ide> if conn.extra_dejson.get('proxy_user') == "login" and conn.login: | 1 |
Javascript | Javascript | require path after setting start time | b8285a00b0399d39891f26718b0c12d038887629 | <ide><path>static/index.js
<ide> window.onload = function() {
<ide> try {
<del> var path = require('path');
<del>
<ide> var startTime = Date.now();
<ide>
<add> var path = require('path');
<add>
<ide> // Skip "?loadSettings=".
<ide> var loadSettings = JSON.parse(decodeURIComponent(location.search.substr(14)));
<ide> | 1 |
Java | Java | fix issue with restoring included attributes | 0fb4b747c2f634ebcbbc2f4e37726234100e8367 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
<ide> private void triggerAfterCompletionWithError(HttpServletRequest request, HttpSer
<ide> * @param request current HTTP request
<ide> * @param attributesSnapshot the snapshot of the request attributes before the include
<ide> */
<add> @SuppressWarnings("unchecked")
<ide> private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?,?> attributesSnapshot) {
<ide> logger.debug("Restoring snapshot of request attributes after include");
<ide>
<ide> private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?,?>
<ide> }
<ide> }
<ide>
<add> // Add attributes that may have been removed
<add> attrsToCheck.addAll((Set<String>) attributesSnapshot.keySet());
<add>
<ide> // Iterate over the attributes to check, restoring the original value
<ide> // or removing the attribute, respectively, if appropriate.
<ide> for (String attrName : attrsToCheck) { | 1 |
Javascript | Javascript | remove custom message from assertion | 2054c66e7773e54a2f5a0844322b5e5752b6cff3 | <ide><path>test/addons/async-hooks-promise/test.js
<ide> const hook1 = async_hooks.createHook({
<ide> // Check that the internal field returns the same PromiseWrap passed to init().
<ide> assert.strictEqual(
<ide> binding.getPromiseField(Promise.resolve(1)),
<del> pwrap,
<del> 'Unexpected PromiseWrap');
<add> pwrap);
<ide>
<ide> hook1.disable();
<ide> | 1 |
Text | Text | remove unnecessary line from upgrade guide | ed7be09263be1c21a4a3e73fea362a2688fa0a8c | <ide><path>upgrade.md
<ide> - Edit `app/controllers/BaseController.php` change `use Illuminate\Routing\Controllers\Controller;` to `use Illuminate\Routing\Controller;
<ide> `
<ide> - If you are overriding `missingMethod` in your controllers, add $method as the first parameter.
<del>- If you are registering model observers in a "start" file, move them to the `App::booted` handler. | 1 |
Javascript | Javascript | add documentation for controllermixin | 032e874ba0dec3cec3eb1a9efcd5e5c9b77852ab | <ide><path>packages/ember-runtime/lib/controllers/controller.js
<ide> require('ember-runtime/system/object');
<ide> require('ember-runtime/system/string');
<ide>
<add>/**
<add> @class
<add>
<add> Ember.ControllerMixin provides a standard interface for all classes
<add> that compose Ember's controller layer: Ember.Controller, Ember.ArrayController,
<add> and Ember.ObjectController.
<add>
<add> Within an Ember.Router-managed application single shared instaces of every
<add> Controller object in your application's namespace will be added to the
<add> application's Ember.Router instance. See `Ember.Application#initialize`
<add> for additional information.
<add>
<add> ## Views
<add> By default a controller instance will be the rendering context
<add> for its associated Ember.View. This connection is made during calls to
<add> `Ember.ControllerMixin#connectOutlet`.
<add>
<add> Within the view's template, the Ember.View instance can be accessed
<add> through the controller with `{{view}}`.
<add>
<add> ## Target Forwarding
<add> By default a controller will target your application's Ember.Router instance.
<add> Calls to `{{action}}` within the template of a controller's view are forwarded
<add> to the router. See `Ember.Handlebars.helpers.action` for additional information.
<add>
<add> @extends Ember.Mixin
<add>*/
<ide> Ember.ControllerMixin = Ember.Mixin.create({
<ide> /**
<ide> The object to which events from the view should be sent.
<ide><path>packages/ember-views/lib/system/controller.js
<ide> var get = Ember.get, set = Ember.set;
<ide>
<del>Ember.ControllerMixin.reopen({
<add>// @class declaration and documentation in runtime/lib/controllers/controller.js
<add>Ember.ControllerMixin.reopen(/** @scope Ember.ControllerMixin.prototype */ {
<ide>
<ide> target: null,
<ide> controllers: null, | 2 |
Text | Text | add changelogs for tls | 0dc6ff70d2538e19f60627fbcc2cbbe2a48b1c89 | <ide><path>doc/api/tls.md
<ide> connection is open.
<ide> ### new tls.TLSSocket(socket[, options])
<ide> <!-- YAML
<ide> added: v0.11.4
<add>changes:
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2564
<add> description: ALPN options are supported now.
<ide> -->
<ide>
<ide> * `socket` {net.Socket} An instance of [`net.Socket`][]
<ide> decrease overall server throughput.
<ide> ## tls.connect(options[, callback])
<ide> <!-- YAML
<ide> added: v0.11.3
<add>changes:
<add> - version: v5.3.0, v4.7.0
<add> pr-url: https://github.com/nodejs/node/pull/4246
<add> description: The `secureContext` option is supported now.
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2564
<add> description: ALPN options are supported now.
<ide> -->
<ide>
<ide> * `options` {Object}
<ide> or host argument.
<ide> ## tls.createSecureContext(options)
<ide> <!-- YAML
<ide> added: v0.11.13
<add>changes:
<add> - version: v7.3.0
<add> pr-url: https://github.com/nodejs/node/pull/10294
<add> description: If the `key` option is an array, individual entries do not
<add> need a `passphrase` property anymore. Array entries can also
<add> just be `string`s or `Buffer`s now.
<add> - version: v5.2.0
<add> pr-url: https://github.com/nodejs/node/pull/4099
<add> description: The `ca` option can now be a single string containing multiple
<add> CA certificates.
<ide> -->
<ide>
<ide> * `options` {Object}
<ide> publicly trusted list of CAs as given in
<ide> ## tls.createServer([options][, secureConnectionListener])
<ide> <!-- YAML
<ide> added: v0.3.2
<add>changes:
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2564
<add> description: ALPN options are supported now.
<ide> -->
<ide>
<ide> * `options` {Object}
<ide> certificate used is properly authorized.
<ide> <!-- YAML
<ide> added: v0.3.2
<ide> deprecated: v0.11.3
<add>changes:
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2564
<add> description: ALPN options are supported now.
<ide> -->
<ide>
<ide> > Stability: 0 - Deprecated: Use [`tls.TLSSocket`][] instead. | 1 |
Ruby | Ruby | add test for build.include? having dashed args | dc4d10ff6a59ce0da1bfc7bc06dd819c442813ab | <ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> next unless match = regex_match_group(arg, %r{with(out)?-(.*)})
<ide> problem "Use build.with#{match[1]}? \"#{match[2]}\" instead of build.include? 'with#{match[1]}-#{match[2]}'"
<ide> end
<del> #
<del> # find_instance_method_call(body_node, :build, :include?) do |m|
<del> # arg = parameters(m).first
<del> # next unless match = regex_match_group(arg, %r{\-\-(.*)})
<del> # problem "Reference '#{match[1]}' without dashes"
<del> # end
<add>
<add> find_instance_method_call(body_node, :build, :include?) do |m|
<add> arg = parameters(m).first
<add> next unless match = regex_match_group(arg, %r{\-\-(.*)})
<add> problem "Reference '#{match[1]}' without dashes"
<add> end
<ide>
<ide> end
<ide>
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> def post_install
<ide> expect_offense(expected, actual)
<ide> end
<ide> end
<add>
<add> it "with build.include? with dashed args" do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> def post_install
<add> return if build.include? "--bar"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: "Reference 'bar' without dashes",
<add> severity: :convention,
<add> line: 5,
<add> column: 30,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<ide> end
<ide> def expect_offense(expected, actual)
<ide> expect(actual.message).to eq(expected[:message]) | 2 |
Ruby | Ruby | use start_with? when possible | 92a71a534f9aa956eecc7ebeac0bd5dbe0ca980f | <ide><path>Library/Homebrew/os/mac.rb
<ide> def gcc_42_build_version
<ide> @gcc_42_build_version ||=
<ide> begin
<ide> gcc = MacOS.locate("gcc-4.2") || HOMEBREW_PREFIX.join("opt/apple-gcc42/bin/gcc-4.2")
<del> if gcc.exist? && gcc.realpath.basename.to_s !~ /^llvm/
<add> if gcc.exist? && !gcc.realpath.basename.to_s.start_with?("llvm")
<ide> `#{gcc} --version`[/build (\d{4,})/, 1].to_i
<ide> end
<ide> end
<ide> def gcc_42_build_version
<ide>
<ide> def llvm_build_version
<ide> @llvm_build_version ||=
<del> if (path = locate("llvm-gcc")) && path.realpath.basename.to_s !~ /^clang/
<add> if (path = locate("llvm-gcc")) && !path.realpath.basename.to_s.start_with?("clang")
<ide> `#{path} --version`[/LLVM build (\d{4,})/, 1].to_i
<ide> end
<ide> end
<ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def provides_cvs?
<ide>
<ide> def default_prefix?
<ide> if version < "4.3"
<del> %r{^/Developer} === prefix
<add> prefix.to_s.start_with? "/Developer"
<ide> else
<del> %r{^/Applications/Xcode.app} === prefix
<add> prefix.to_s.start_with? "/Applications/Xcode.app"
<ide> end
<ide> end
<ide> end | 2 |
Text | Text | remove non existing samples folder mention | f8777524d3d833df08c43a0001ac5158c6deff68 | <ide><path>README.md
<ide> The [official models](official) are a collection of example models that use Tens
<ide>
<ide> The [research models](https://github.com/tensorflow/models/tree/master/research) are a large collection of models implemented in TensorFlow by researchers. They are not officially supported or available in release branches; it is up to the individual researchers to maintain the models and/or provide support on issues and pull requests.
<ide>
<del>The [samples folder](samples) contains code snippets and smaller models that demonstrate features of TensorFlow, including code presented in various blog posts.
<del>
<ide> The [tutorials folder](tutorials) is a collection of models described in the [TensorFlow tutorials](https://www.tensorflow.org/tutorials/).
<ide>
<ide> ## Contribution guidelines | 1 |
Javascript | Javascript | add support for patternunits attribute | 3f29d5d6cbbc8dc147c9e097187b7268b8b2d9fa | <ide><path>src/browser/ui/dom/SVGDOMPropertyConfig.js
<ide> var SVGDOMPropertyConfig = {
<ide> gradientTransform: MUST_USE_ATTRIBUTE,
<ide> gradientUnits: MUST_USE_ATTRIBUTE,
<ide> offset: MUST_USE_ATTRIBUTE,
<add> patternUnits: MUST_USE_ATTRIBUTE,
<ide> points: MUST_USE_ATTRIBUTE,
<ide> preserveAspectRatio: MUST_USE_ATTRIBUTE,
<ide> r: MUST_USE_ATTRIBUTE,
<ide> var SVGDOMPropertyConfig = {
<ide> DOMAttributeNames: {
<ide> gradientTransform: 'gradientTransform',
<ide> gradientUnits: 'gradientUnits',
<add> patternUnits: 'patternUnits',
<ide> preserveAspectRatio: 'preserveAspectRatio',
<ide> spreadMethod: 'spreadMethod',
<ide> stopColor: 'stop-color', | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.