content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | add v4.0.0-beta.8 to changelog | 4f99f42070bc12a122cc7f45686d02b467c7d661 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.0.0-beta.8 (November 5, 2021)
<add>
<add>- [#19823](https://github.com/emberjs/ember.js/pull/19823) / [#19828](https://github.com/emberjs/ember.js/pull/19828) [BUGFIX] Fix deprecation `until` and link for Component.reopenClass and Component.reopen
<add>- [#19825](https://github.com/emberjs/ember.js/pull/19825) [BUGFIX] Replace `assert.equal` in blueprints with `assert.strictEqual` to pass eslint-plugin-qunit v7 on generation
<add>- [#19808](https://github.com/emberjs/ember.js/pull/19808) [CLEANUP] Remove the `--test-type` option from the helper blueprint
<add>- [#19820](https://github.com/emberjs/ember.js/pull/19820) Fix memory leak when looking up non-instantiable objects from the owner
<add>
<ide> ### v4.0.0-beta.7 (November 1, 2021)
<ide>
<ide> - [#19677](https://github.com/emberjs/ember.js/pull/19677) [CLEANUP] Remove jQuery from build | 1 |
Ruby | Ruby | fix bad default_compiler reference | 86fa42b36c98e482490ca347849e041ee9316011 | <ide><path>Library/Homebrew/tab.rb
<ide> def unused_options
<ide> end
<ide>
<ide> def compiler
<del> super || MacOS.default_compiler
<add> super || DevelopmentTools.default_compiler
<ide> end
<ide>
<ide> def cxxstdlib | 1 |
Ruby | Ruby | move object allocation out of loop | dfbcfafd9af046b3e8c79fe7309d31af6f82f9b2 | <ide><path>railties/lib/rails/backtrace_cleaner.rb
<ide> module Rails
<ide> class BacktraceCleaner < ActiveSupport::BacktraceCleaner
<ide> APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
<ide> RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
<add> EMPTY_STRING = ''.freeze
<add> SLASH = '/'.freeze
<add> DOT_SLASH = './'.freeze
<ide>
<ide> def initialize
<ide> super
<del> add_filter { |line| line.sub("#{Rails.root}/", '') }
<del> add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, '') }
<del> add_filter { |line| line.sub('./', '/') } # for tests
<add> @root = "#{Rails.root}/".freeze
<add> add_filter { |line| line.sub(@root, EMPTY_STRING) }
<add> add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, EMPTY_STRING) }
<add> add_filter { |line| line.sub(DOT_SLASH, SLASH) } # for tests
<ide>
<ide> add_gem_filters
<ide> add_silencer { |line| line !~ APP_DIRS_PATTERN }
<ide> def add_gem_filters
<ide> return if gems_paths.empty?
<ide>
<ide> gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
<del> add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
<add> gems_result = '\2 (\3) \4'.freeze
<add> add_filter { |line| line.sub(gems_regexp, gems_result) }
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | handle scrolling of the dummy scrollbars directly | 0999d0bf02ef6004f8cdbe237c24c635801a38a3 | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> expect(element.querySelectorAll('.line-number').length).toBe(9)
<ide> expect(element.querySelectorAll('.line').length).toBe(9)
<ide>
<del> component.setScrollTop(5 * component.getLineHeight())
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, 5 * component.getLineHeight())
<ide>
<ide> // After scrolling down beyond > 3 rows, the order of line numbers and lines
<ide> // in the DOM is a bit weird because the first tile is recycled to the bottom
<ide> describe('TextEditorComponent', () => {
<ide> editor.lineTextForScreenRow(8)
<ide> ])
<ide>
<del> component.setScrollTop(2.5 * component.getLineHeight())
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, 2.5 * component.getLineHeight())
<ide> expect(Array.from(element.querySelectorAll('.line-number')).map(element => element.textContent.trim())).toEqual([
<ide> '1', '2', '3', '4', '5', '6', '7', '8', '9'
<ide> ])
<ide> describe('TextEditorComponent', () => {
<ide> await setEditorHeightInLines(component, 6)
<ide>
<ide> // scroll to end
<del> component.setScrollTop(scrollContainer.scrollHeight - scrollContainer.clientHeight)
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, scrollContainer.scrollHeight - scrollContainer.clientHeight)
<ide> expect(component.getFirstVisibleRow()).toBe(editor.getScreenLineCount() - 3)
<ide>
<ide> editor.update({scrollPastEnd: false})
<ide> describe('TextEditorComponent', () => {
<ide> // Always allows at least 3 lines worth of overscroll if the editor is short
<ide> await setEditorHeightInLines(component, 2)
<ide> await editor.update({scrollPastEnd: true})
<del> component.setScrollTop(scrollContainer.scrollHeight - scrollContainer.clientHeight)
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, scrollContainer.scrollHeight - scrollContainer.clientHeight)
<ide> expect(component.getFirstVisibleRow()).toBe(editor.getScreenLineCount() + 1)
<ide> })
<ide>
<ide> describe('TextEditorComponent', () => {
<ide> expect(gutterElement.firstChild.style.contain).toBe('strict')
<ide> })
<ide>
<add> it('renders dummy vertical and horizontal scrollbars when content overflows', async () => {
<add> const {component, element, editor} = buildComponent({height: 100, width: 100})
<add> const verticalScrollbar = component.refs.verticalScrollbar.element
<add> const horizontalScrollbar = component.refs.horizontalScrollbar.element
<add> expect(verticalScrollbar.scrollHeight).toBe(component.getContentHeight())
<add> expect(horizontalScrollbar.scrollWidth).toBe(component.getContentWidth())
<add> expect(getVerticalScrollbarWidth(component)).toBeGreaterThan(0)
<add> expect(getHorizontalScrollbarHeight(component)).toBeGreaterThan(0)
<add> expect(verticalScrollbar.style.bottom).toBe(getVerticalScrollbarWidth(component) + 'px')
<add> expect(horizontalScrollbar.style.right).toBe(getHorizontalScrollbarHeight(component) + 'px')
<add> expect(component.refs.scrollbarCorner).toBeDefined()
<add>
<add> setScrollTop(component, 100)
<add> await setScrollLeft(component, 100)
<add> expect(verticalScrollbar.scrollTop).toBe(100)
<add> expect(horizontalScrollbar.scrollLeft).toBe(100)
<add>
<add> verticalScrollbar.scrollTop = 120
<add> horizontalScrollbar.scrollLeft = 120
<add> await component.getNextUpdatePromise()
<add> expect(component.getScrollTop()).toBe(120)
<add> expect(component.getScrollLeft()).toBe(120)
<add>
<add> editor.setText('a\n'.repeat(15))
<add> await component.getNextUpdatePromise()
<add> expect(getVerticalScrollbarWidth(component)).toBeGreaterThan(0)
<add> expect(getHorizontalScrollbarHeight(component)).toBe(0)
<add> expect(verticalScrollbar.style.bottom).toBe('0px')
<add> expect(component.refs.scrollbarCorner).toBeUndefined()
<add>
<add> editor.setText('a'.repeat(100))
<add> await component.getNextUpdatePromise()
<add> expect(getVerticalScrollbarWidth(component)).toBe(0)
<add> expect(getHorizontalScrollbarHeight(component)).toBeGreaterThan(0)
<add> expect(horizontalScrollbar.style.right).toBe('0px')
<add> expect(component.refs.scrollbarCorner).toBeUndefined()
<add>
<add> editor.setText('')
<add> await component.getNextUpdatePromise()
<add> expect(getVerticalScrollbarWidth(component)).toBe(0)
<add> expect(getHorizontalScrollbarHeight(component)).toBe(0)
<add> expect(component.refs.scrollbarCorner).toBeUndefined()
<add> })
<add>
<add> it('updates the bottom/right of dummy scrollbars and client height/width measurements when scrollbar styles change', async () => {
<add> const {component, element, editor} = buildComponent({height: 100, width: 100})
<add> expect(getHorizontalScrollbarHeight(component)).toBeGreaterThan(10)
<add> expect(getVerticalScrollbarWidth(component)).toBeGreaterThan(10)
<add>
<add> const style = document.createElement('style')
<add> style.textContent = '::-webkit-scrollbar { height: 10px; width: 10px; }'
<add> jasmine.attachToDOM(style)
<add>
<add> TextEditor.didUpdateScrollbarStyles()
<add> await component.getNextUpdatePromise()
<add>
<add> expect(getHorizontalScrollbarHeight(component)).toBe(10)
<add> expect(getVerticalScrollbarWidth(component)).toBe(10)
<add> expect(component.refs.horizontalScrollbar.element.style.right).toBe('10px')
<add> expect(component.refs.verticalScrollbar.element.style.bottom).toBe('10px')
<add> expect(component.getScrollContainerClientHeight()).toBe(100 - 10)
<add> expect(component.getScrollContainerClientWidth()).toBe(100 - component.getGutterContainerWidth() - 10)
<add> })
<add>
<ide> it('renders cursors within the visible row range', async () => {
<ide> const {component, element, editor} = buildComponent({height: 40, rowsPerTile: 2})
<del> component.setScrollTop(100)
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, 100)
<ide>
<ide> expect(component.getRenderedStartRow()).toBe(4)
<ide> expect(component.getRenderedEndRow()).toBe(10)
<ide> describe('TextEditorComponent', () => {
<ide> it('places the hidden input element at the location of the last cursor if it is visible', async () => {
<ide> const {component, element, editor} = buildComponent({height: 60, width: 120, rowsPerTile: 2})
<ide> const {hiddenInput} = component.refs
<del> component.setScrollTop(100)
<del> component.setScrollLeft(40)
<del> await component.getNextUpdatePromise()
<add> setScrollTop(component, 100)
<add> await setScrollLeft(component, 40)
<ide>
<ide> expect(component.getRenderedStartRow()).toBe(4)
<ide> expect(component.getRenderedEndRow()).toBe(12)
<ide> describe('TextEditorComponent', () => {
<ide> )
<ide>
<ide> // Don't flash on next update if another flash wasn't requested
<del> component.setScrollTop(100)
<del> await component.getNextUpdatePromise()
<add> await setScrollTop(component, 100)
<ide> expect(highlights[0].classList.contains('b')).toBe(false)
<ide> expect(highlights[1].classList.contains('b')).toBe(false)
<ide>
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> const maxScrollTop = component.getMaxScrollTop()
<ide> const maxScrollLeft = component.getMaxScrollLeft()
<del> component.setScrollTop(maxScrollTop)
<del> component.setScrollLeft(maxScrollLeft)
<del> await component.getNextUpdatePromise()
<add> setScrollTop(component, maxScrollTop)
<add> await setScrollLeft(component, maxScrollLeft)
<ide>
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> const maxScrollTop = component.getMaxScrollTop()
<ide> const maxScrollLeft = component.getMaxScrollLeft()
<del> component.setScrollTop(maxScrollTop)
<del> component.setScrollLeft(maxScrollLeft)
<del> await component.getNextUpdatePromise()
<add> setScrollTop(component, maxScrollTop)
<add> await setScrollLeft(component, maxScrollLeft)
<ide>
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<ide> function textNodesForScreenRow (component, row) {
<ide> return component.textNodesByScreenLineId.get(screenLine.id)
<ide> }
<ide>
<add>function setScrollTop (component, scrollTop) {
<add> component.setScrollTop(scrollTop)
<add> component.scheduleUpdate()
<add> return component.getNextUpdatePromise()
<add>}
<add>
<add>function setScrollLeft (component, scrollTop) {
<add> component.setScrollLeft(scrollTop)
<add> component.scheduleUpdate()
<add> return component.getNextUpdatePromise()
<add>}
<add>
<add>function getHorizontalScrollbarHeight (component) {
<add> const element = component.refs.horizontalScrollbar.element
<add> return element.offsetHeight - element.clientHeight
<add>}
<add>
<add>function getVerticalScrollbarWidth (component) {
<add> const element = component.refs.verticalScrollbar.element
<add> return element.offsetWidth - element.clientWidth
<add>}
<add>
<ide> function assertDocumentFocused () {
<ide> if (!document.hasFocus()) {
<ide> throw new Error('The document needs to be focused to run this test')
<ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> this.horizontalPixelPositionsByScreenLineId = new Map() // Values are maps from column to horiontal pixel positions
<ide> this.lineNodesByScreenLineId = new Map()
<ide> this.textNodesByScreenLineId = new Map()
<add> this.didScrollDummyScrollbar = this.didScrollDummyScrollbar.bind(this)
<ide> this.scrollbarsVisible = true
<ide> this.refreshScrollbarStyling = false
<ide> this.pendingAutoscroll = null
<add> this.scrollTopPending = false
<add> this.scrollLeftPending = false
<ide> this.scrollTop = 0
<ide> this.scrollLeft = 0
<ide> this.previousScrollWidth = 0
<ide> class TextEditorComponent {
<ide> etch.updateSync(this)
<ide>
<ide> this.currentFrameLineNumberGutterProps = null
<del>
<add> this.scrollTopPending = false
<add> this.scrollLeftPending = false
<ide> if (this.refreshScrollbarStyling) {
<ide> this.measureScrollbarDimensions()
<ide> this.refreshScrollbarStyling = false
<ide> class TextEditorComponent {
<ide> $(DummyScrollbarComponent, {
<ide> ref: 'verticalScrollbar',
<ide> orientation: 'vertical',
<add> didScroll: this.didScrollDummyScrollbar,
<ide> scrollHeight, scrollTop, horizontalScrollbarHeight, forceScrollbarVisible
<ide> }),
<ide> $(DummyScrollbarComponent, {
<ide> ref: 'horizontalScrollbar',
<ide> orientation: 'horizontal',
<add> didScroll: this.didScrollDummyScrollbar,
<ide> scrollWidth, scrollLeft, verticalScrollbarWidth, forceScrollbarVisible
<ide> })
<ide> ]
<ide> class TextEditorComponent {
<ide> if (verticalScrollbarWidth > 0 && horizontalScrollbarHeight > 0) {
<ide> elements.push($.div(
<ide> {
<add> ref: 'scrollbarCorner',
<ide> style: {
<ide> position: 'absolute',
<ide> height: '20px',
<ide> class TextEditorComponent {
<ide> }
<ide> }
<ide>
<add> didScrollDummyScrollbar () {
<add> let scrollTopChanged = false
<add> let scrollLeftChanged = false
<add> if (!this.scrollTopPending) {
<add> scrollTopChanged = this.setScrollTop(this.refs.verticalScrollbar.element.scrollTop)
<add> }
<add> if (!this.scrollLeftPending) {
<add> scrollLeftChanged = this.setScrollLeft(this.refs.horizontalScrollbar.element.scrollLeft)
<add> }
<add> if (scrollTopChanged || scrollLeftChanged) this.updateSync()
<add> }
<add>
<ide> didUpdateScrollbarStyles () {
<ide> this.refreshScrollbarStyling = true
<ide> this.scheduleUpdate()
<ide> class TextEditorComponent {
<ide>
<ide> if (!options || options.reversed !== false) {
<ide> if (desiredScrollBottom > this.getScrollBottom()) {
<del> return this.setScrollBottom(desiredScrollBottom, true)
<add> this.setScrollBottom(desiredScrollBottom)
<ide> }
<ide> if (desiredScrollTop < this.getScrollTop()) {
<del> return this.setScrollTop(desiredScrollTop, true)
<add> this.setScrollTop(desiredScrollTop)
<ide> }
<ide> } else {
<ide> if (desiredScrollTop < this.getScrollTop()) {
<del> return this.setScrollTop(desiredScrollTop, true)
<add> this.setScrollTop(desiredScrollTop)
<ide> }
<ide> if (desiredScrollBottom > this.getScrollBottom()) {
<del> return this.setScrollBottom(desiredScrollBottom, true)
<add> this.setScrollBottom(desiredScrollBottom)
<ide> }
<ide> }
<ide>
<ide> class TextEditorComponent {
<ide>
<ide> if (!options || options.reversed !== false) {
<ide> if (desiredScrollRight > this.getScrollRight()) {
<del> this.setScrollRight(desiredScrollRight, true)
<add> this.setScrollRight(desiredScrollRight)
<ide> }
<ide> if (desiredScrollLeft < this.getScrollLeft()) {
<del> this.setScrollLeft(desiredScrollLeft, true)
<add> this.setScrollLeft(desiredScrollLeft)
<ide> }
<ide> } else {
<ide> if (desiredScrollLeft < this.getScrollLeft()) {
<del> this.setScrollLeft(desiredScrollLeft, true)
<add> this.setScrollLeft(desiredScrollLeft)
<ide> }
<ide> if (desiredScrollRight > this.getScrollRight()) {
<del> this.setScrollRight(desiredScrollRight, true)
<add> this.setScrollRight(desiredScrollRight)
<ide> }
<ide> }
<ide> }
<ide> class TextEditorComponent {
<ide> return this.scrollTop
<ide> }
<ide>
<del> setScrollTop (scrollTop, suppressUpdate = false) {
<add> setScrollTop (scrollTop) {
<ide> scrollTop = Math.round(Math.max(0, Math.min(this.getMaxScrollTop(), scrollTop)))
<ide> if (scrollTop !== this.scrollTop) {
<add> this.scrollTopPending = true
<ide> this.scrollTop = scrollTop
<del> if (!suppressUpdate) this.scheduleUpdate()
<ide> return true
<ide> } else {
<ide> return false
<ide> class TextEditorComponent {
<ide> return this.getScrollTop() + this.getScrollContainerClientHeight()
<ide> }
<ide>
<del> setScrollBottom (scrollBottom, suppressUpdate = false) {
<del> return this.setScrollTop(scrollBottom - this.getScrollContainerClientHeight(), suppressUpdate)
<add> setScrollBottom (scrollBottom) {
<add> return this.setScrollTop(scrollBottom - this.getScrollContainerClientHeight())
<ide> }
<ide>
<ide> getScrollLeft () {
<ide> // this.scrollLeft = Math.min(this.getMaxScrollLeft(), this.scrollLeft)
<ide> return this.scrollLeft
<ide> }
<ide>
<del> setScrollLeft (scrollLeft, suppressUpdate = false) {
<add> setScrollLeft (scrollLeft) {
<ide> scrollLeft = Math.round(Math.max(0, Math.min(this.getMaxScrollLeft(), scrollLeft)))
<ide> if (scrollLeft !== this.scrollLeft) {
<add> this.scrollLeftPending = true
<ide> this.scrollLeft = scrollLeft
<del> if (!suppressUpdate) this.scheduleUpdate()
<ide> return true
<ide> } else {
<ide> return false
<ide> class TextEditorComponent {
<ide> return this.getScrollLeft() + this.getScrollContainerClientWidth()
<ide> }
<ide>
<del> setScrollRight (scrollRight, suppressUpdate = false) {
<del> return this.setScrollLeft(scrollRight - this.getScrollContainerClientWidth(), suppressUpdate)
<add> setScrollRight (scrollRight) {
<add> return this.setScrollLeft(scrollRight - this.getScrollContainerClientWidth())
<ide> }
<ide>
<ide> // Ensure the spatial index is populated with rows that are currently
<ide> class DummyScrollbarComponent {
<ide> innerStyle.height = (this.props.scrollHeight || 0) + 'px'
<ide> }
<ide>
<del> return $.div({style: outerStyle, scrollTop, scrollLeft},
<add> return $.div(
<add> {
<add> style: outerStyle,
<add> scrollTop,
<add> scrollLeft,
<add> on: {scroll: this.props.didScroll}
<add> },
<ide> $.div({style: innerStyle})
<ide> )
<ide> } | 2 |
Javascript | Javascript | fix failing test added by e86e361. beautiful | 22473e7c0be0ac93c430496b516586fdd31e5e86 | <ide><path>dist/Immutable.dev.js
<ide> var Range = function Range(start, end, step) {
<ide> if (end == null) {
<ide> end = Infinity;
<ide> }
<add> if (start === end && __EMPTY_RANGE) {
<add> return __EMPTY_RANGE;
<add> }
<ide> step = step == null ? 1 : Math.abs(step);
<ide> if (end < start) {
<ide> step = -step;
<ide> var $Range = Range;
<ide> return possibleIndex >= 0 && possibleIndex < this.length && possibleIndex === Math.floor(possibleIndex);
<ide> },
<ide> slice: function(begin, end, maintainIndices) {
<add> if (wholeSlice(begin, end, this.length)) {
<add> return this;
<add> }
<ide> if (maintainIndices) {
<ide> return $traceurRuntime.superCall(this, $Range.prototype, "slice", [begin, end, maintainIndices]);
<ide> }
<del> begin = begin < 0 ? Math.max(0, this.length + begin) : Math.min(this.length, begin);
<del> end = end == null ? this.length : end > 0 ? Math.min(this.length, end) : Math.max(0, this.length + end);
<add> begin = resolveBegin(begin, this.length);
<add> end = resolveEnd(end, this.length);
<add> if (end <= begin) {
<add> return __EMPTY_RANGE;
<add> }
<ide> return new $Range(this.get(begin, this._end), this.get(end, this._end), this._step);
<ide> },
<ide> __deepEquals: function(other) {
<ide> var $Range = Range;
<ide> Range.prototype.__toJS = Range.prototype.toArray;
<ide> Range.prototype.first = Vector.prototype.first;
<ide> Range.prototype.last = Vector.prototype.last;
<add>var __EMPTY_RANGE = Range(0, 0);
<ide> function invariant(condition, error) {
<ide> if (!condition)
<ide> throw new Error(error);
<ide><path>dist/Immutable.js
<ide> if(i&&(i.value=!0),this.values.length>1){var u=this.ensureOwner(t);return u.keys
<ide> var ce,ne=5,ie=1<<ne,se=ie-1,K={},fe=new ae([]),_e=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return pe.from(t)},pe=_e;z.createClass(_e,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){if(null==t)return this;var e=this._map;return e||(e=F.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:pe._make(e)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:pe._make(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):pe.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++){var n=t[r];n=n.forEach?n:B(n),n.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return B(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.delete(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return B(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.delete(r)})})},isSubset:function(t){return t=B(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=B(t),t.every(function(t){return e.contains(t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?pe._make(e,t):(this.__ownerID=t,this._map=e,this)},__deepEquals:function(t){return!(this._map||t._map)||this._map.equals(t._map)},__iterate:function(t,e){var r=this;return this._map?this._map.__iterate(function(e,n){return t(n,n,r)
<ide> },e):0}},{empty:function(){return ve||(ve=pe._make())},from:function(t){return t&&t.constructor===pe?t:t&&0!==t.length?pe.empty().union(t):pe.empty()},fromKeys:function(t){return pe.from(B(t).flip())},_make:function(t,e){var r=Object.create(pe.prototype);return r.length=t?t.length:0,r._map=t,r.__ownerID=e,r}},B),_e.prototype.contains=_e.prototype.has,_e.prototype.withMutations=F.prototype.withMutations,_e.prototype.asMutable=F.prototype.asMutable,_e.prototype.asImmutable=F.prototype.asImmutable,_e.prototype.__toJS=J.prototype.__toJS,_e.prototype.__toStringMapper=J.prototype.__toStringMapper;var ve,ge=function(t){return t&&t.constructor===me?t:t&&0!==t.length?me.empty().merge(t):me.empty()},me=ge;z.createClass(ge,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){if(null!=t&&this._map){var r=this._map.get(t);if(null!=r)return this._vector.get(r)[1]}return e},clear:function(){return this.__ownerID?(this.length=0,this._map=this._vector=null,this):me.empty()},set:function(t,e){if(null==t)return this;var r=this._map,n=this._vector;if(r){var i=r.get(t);null==i?(r=r.set(t,n.length),n=n.push([t,e])):n.get(i)[1]!==e&&(n=n.set(i,[t,e]))}else n=ue.empty().__ensureOwner(this.__ownerID).set(0,[t,e]),r=F.empty().__ensureOwner(this.__ownerID).set(t,0);return this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):n===this._vector?this:me._make(r,n)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.get(t);if(null==e)return this;var r=this._map.delete(t),n=this._vector.delete(e);return 0===r.length?this.clear():this.__ownerID?(this.length=r.length,this._map=r,this._vector=n,this):r===this._map?this:me._make(r,n)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t),r=this._vector&&this._vector.__ensureOwner(t);return t?me._make(e,r,t):(this.__ownerID=t,this._map=e,this._vector=r,this)},__deepEqual:function(t){var e=this._vector.__iterator__();return t.every(function(t,r){var n=e.next();return n&&(n=n[1]),n&&w(r,n[0])&&w(t,n[1])
<ide> })},__iterate:function(t,e){return this._vector?this._vector.fromEntries().__iterate(t,e):0}},{empty:function(){return ye||(ye=me._make())},_make:function(t,e,r){var n=Object.create(me.prototype);return n.length=t?t.length:0,n._map=t,n._vector=e,n.__ownerID=r,n}},F),ge.from=ge;var ye,de=function(t,e){var r=function(t){this._map=F(t)};t=B(t),r.prototype=Object.create(we.prototype),r.prototype.constructor=r,r.prototype._name=e,r.prototype._defaultValues=t;var n=Object.keys(t);return r.prototype.length=n.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){if(!this.__ownerID)throw Error("Cannot set on an immutable record.");this.set(e,t)}})}),r},we=de;z.createClass(de,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){return this.__ownerID?(this._map.clear(),this):this._empty()},set:function(t,e){if(null==t||!this.has(t))return this;var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:this._make(r)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:this._make(e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?this._make(e,t):(this.__ownerID=t,this._map=e,this)},__iterate:function(t,e){var r=this;return this._defaultValues.map(function(t,e){return r.get(e)}).__iterate(t,e)},_empty:function(){Object.getPrototypeOf(this).constructor;return we._empty||(we._empty=this._make(F.empty()))},_make:function(t,e){var r=Object.create(Object.getPrototypeOf(this));return r._map=t,r.__ownerID=e,r}},{},B),de.prototype.__deepEqual=F.prototype.__deepEqual,de.prototype.merge=F.prototype.merge,de.prototype.mergeWith=F.prototype.mergeWith,de.prototype.mergeDeep=F.prototype.mergeDeep,de.prototype.mergeDeepWith=F.prototype.mergeDeepWith,de.prototype.update=F.prototype.update,de.prototype.updateIn=F.prototype.updateIn,de.prototype.withMutations=F.prototype.withMutations,de.prototype.asMutable=F.prototype.asMutable,de.prototype.asImmutable=F.prototype.asImmutable;
<del>var Ie=function(t,e,r){return this instanceof ke?(q(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1))):new ke(t,e,r)},ke=Ie;z.createClass(Ie,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return q(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return q(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,r){return r?z.superCall(this,ke.prototype,"slice",[t,e,r]):(t=0>t?Math.max(0,this.length+t):Math.min(this.length,t),e=null==e?this.length:e>0?Math.min(this.length,e):Math.max(0,this.length+e),new ke(this.get(t,this._end),this.get(e,this._end),this._step))},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.length>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?z.superCall(this,ke.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,r){for(var n=e^r,i=this.length-1,s=this._step,u=e?this._start+i*s:this._start,o=0;i>=o&&t(u,n?i-o:o,this)!==!1;o++)u+=e?-s:s;return n?this.length:o}},{},J),Ie.prototype.__toJS=Ie.prototype.toArray,Ie.prototype.first=ue.prototype.first,Ie.prototype.last=ue.prototype.last;var Oe=function(t,e){return 0===e&&be?be:this instanceof De?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new De(t,e)},De=Oe;z.createClass(Oe,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return q(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value
<del>},contains:function(t){return w(this._value,t)},__deepEquals:function(t){return w(this._value,t._value)},slice:function(t,e,r){if(r)return z.superCall(this,De.prototype,"slice",[t,e,r]);var n=this.length;return t=0>t?Math.max(0,n+t):Math.min(n,t),e=null==e?n:e>0?Math.min(n,e):Math.max(0,n+e),e>t?new De(this._value,e-t):be},reverse:function(t){return t?z.superCall(this,De.prototype,"reverse",[t]):this},indexOf:function(t){return w(this._value,t)?0:-1},lastIndexOf:function(t){return w(this._value,t)?this.length:-1},__iterate:function(t,e,r){var n=e^r;q(!n||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,s=0;i>=s&&t(this._value,n?i-s:s,this)!==!1;s++);return n?this.length:s}},{},J),Oe.prototype.last=Oe.prototype.first,Oe.prototype.has=Ie.prototype.has,Oe.prototype.take=Ie.prototype.take,Oe.prototype.skip=Ie.prototype.skip,Oe.prototype.__toJS=Ie.prototype.__toJS;var be=new Oe(void 0,0),Me={Sequence:B,Map:F,Vector:ue,Set:_e,OrderedMap:ge,Record:de,Range:Ie,Repeat:Oe,is:w,fromJS:j};return Me}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t();
<ide>\ No newline at end of file
<add>var Ie=function(t,e,r){return this instanceof ke?(q(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&Oe?Oe:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.length=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new ke(t,e,r)},ke=Ie;z.createClass(Ie,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return q(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return q(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,r){return u(t,e,this.length)?this:r?z.superCall(this,ke.prototype,"slice",[t,e,r]):(t=o(t,this.length),e=a(e,this.length),t>=e?Oe:new ke(this.get(t,this._end),this.get(e,this._end),this._step))},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.length>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?z.superCall(this,ke.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,r){for(var n=e^r,i=this.length-1,s=this._step,u=e?this._start+i*s:this._start,o=0;i>=o&&t(u,n?i-o:o,this)!==!1;o++)u+=e?-s:s;return n?this.length:o}},{},J),Ie.prototype.__toJS=Ie.prototype.toArray,Ie.prototype.first=ue.prototype.first,Ie.prototype.last=ue.prototype.last;var Oe=Ie(0,0),De=function(t,e){return 0===e&&Me?Me:this instanceof be?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new be(t,e)},be=De;z.createClass(De,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return q(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return w(this._value,t)
<add>},__deepEquals:function(t){return w(this._value,t._value)},slice:function(t,e,r){if(r)return z.superCall(this,be.prototype,"slice",[t,e,r]);var n=this.length;return t=0>t?Math.max(0,n+t):Math.min(n,t),e=null==e?n:e>0?Math.min(n,e):Math.max(0,n+e),e>t?new be(this._value,e-t):Me},reverse:function(t){return t?z.superCall(this,be.prototype,"reverse",[t]):this},indexOf:function(t){return w(this._value,t)?0:-1},lastIndexOf:function(t){return w(this._value,t)?this.length:-1},__iterate:function(t,e,r){var n=e^r;q(!n||1/0>this.length,"Cannot access end of infinite range.");for(var i=this.length-1,s=0;i>=s&&t(this._value,n?i-s:s,this)!==!1;s++);return n?this.length:s}},{},J),De.prototype.last=De.prototype.first,De.prototype.has=Ie.prototype.has,De.prototype.take=Ie.prototype.take,De.prototype.skip=Ie.prototype.skip,De.prototype.__toJS=Ie.prototype.__toJS;var Me=new De(void 0,0),Se={Sequence:B,Map:F,Vector:ue,Set:_e,OrderedMap:ge,Record:de,Range:Ie,Repeat:De,is:w,fromJS:j};return Se}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t();
<ide>\ No newline at end of file
<ide><path>src/Range.js
<ide>
<ide> import "Sequence"
<ide> import "Vector"
<del>/* global IndexedSequence, Vector */
<add>/* global IndexedSequence, wholeSlice, resolveBegin, resolveEnd, Vector */
<ide> /* exported Range */
<ide>
<ide>
<ide> class Range extends IndexedSequence {
<ide> if (end == null) {
<ide> end = Infinity;
<ide> }
<add> if (start === end && __EMPTY_RANGE) {
<add> return __EMPTY_RANGE;
<add> }
<ide> step = step == null ? 1 : Math.abs(step);
<ide> if (end < start) {
<ide> step = -step;
<ide> class Range extends IndexedSequence {
<ide> }
<ide>
<ide> slice(begin, end, maintainIndices) {
<add> if (wholeSlice(begin, end, this.length)) {
<add> return this;
<add> }
<ide> if (maintainIndices) {
<ide> return super.slice(begin, end, maintainIndices);
<ide> }
<del> begin = begin < 0 ? Math.max(0, this.length + begin) : Math.min(this.length, begin);
<del> end = end == null ? this.length : end > 0 ? Math.min(this.length, end) : Math.max(0, this.length + end);
<add> begin = resolveBegin(begin, this.length);
<add> end = resolveEnd(end, this.length);
<add> if (end <= begin) {
<add> return __EMPTY_RANGE;
<add> }
<ide> return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
<ide> }
<ide>
<ide> Range.prototype.__toJS = Range.prototype.toArray;
<ide> Range.prototype.first = Vector.prototype.first;
<ide> Range.prototype.last = Vector.prototype.last;
<ide>
<add>var __EMPTY_RANGE = Range(0, 0);
<ide>
<ide> function invariant(condition, error) {
<ide> if (!condition) throw new Error(error); | 3 |
PHP | PHP | add tests for session's save method | 78c19ef9a37e405e4e718e3723b3ec5458f872a0 | <ide><path>tests/Session/SessionStoreTest.php
<ide>
<ide> use Mockery as m;
<ide> use ReflectionClass;
<add>use Illuminate\Support\Str;
<ide> use SessionHandlerInterface;
<ide> use Illuminate\Session\Store;
<ide> use PHPUnit\Framework\TestCase;
<ide> public function testSessionInvalidate()
<ide> $this->assertCount(0, $session->all());
<ide> }
<ide>
<del> public function testSessionIsProperlySaved()
<add> public function testBrandNewSessionIsProperlySaved()
<ide> {
<ide> $session = $this->getSession();
<ide> $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([]));
<ide> public function testSessionIsProperlySaved()
<ide> $this->assertFalse($session->isStarted());
<ide> }
<ide>
<add> public function testSessionIsProperlyUpdated()
<add> {
<add> $session = $this->getSession();
<add> $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([
<add> '_token' => Str::random(40),
<add> 'foo' => 'bar',
<add> 'baz' => 'boom',
<add> '_flash' => [
<add> 'new' => [],
<add> 'old' => ['baz'],
<add> ],
<add> ]));
<add> $session->start();
<add>
<add> $session->getHandler()->shouldReceive('write')->once()->with(
<add> $this->getSessionId(),
<add> serialize([
<add> '_token' => $session->token(),
<add> 'foo' => 'bar',
<add> '_flash' => [
<add> 'new' => [],
<add> 'old' => [],
<add> ],
<add> ])
<add> );
<add>
<add> $session->save();
<add>
<add> $this->assertFalse($session->isStarted());
<add> }
<add>
<add> public function testSessionIsReSavedWhenNothingHasChanged()
<add> {
<add> $session = $this->getSession();
<add> $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([
<add> '_token' => Str::random(40),
<add> 'foo' => 'bar',
<add> 'baz' => 'boom',
<add> '_flash' => [
<add> 'new' => [],
<add> 'old' => [],
<add> ],
<add> ]));
<add> $session->start();
<add>
<add> $session->getHandler()->shouldReceive('write')->once()->with(
<add> $this->getSessionId(),
<add> serialize([
<add> '_token' => $session->token(),
<add> 'foo' => 'bar',
<add> 'baz' => 'boom',
<add> '_flash' => [
<add> 'new' => [],
<add> 'old' => [],
<add> ],
<add> ])
<add> );
<add>
<add> $session->save();
<add>
<add> $this->assertFalse($session->isStarted());
<add> }
<add>
<ide> public function testOldInputFlashing()
<ide> {
<ide> $session = $this->getSession(); | 1 |
Text | Text | add missing docs for | 271f54aea375158b808aa50db58711e7c1d3eef5 | <ide><path>docs/sources/reference/api/docker_remote_api.md
<ide> You can still call an old version of the API using
<ide> total memory available (`MemTotal`).
<ide>
<ide> `POST /containers/create`
<add>
<ide> **New!**
<ide> You can set the new container's MAC address explicitly.
<ide>
<ide> You can set the new container's MAC address explicitly.
<ide> Passing the container's `HostConfig` on start is now deprecated. You should
<ide> set this when creating the container.
<ide>
<add>`POST /containers/(id)/copy`
<add>
<add>**New!**
<add>You can now copy data which is contained in a volume.
<add>
<ide> ## v1.15
<ide>
<ide> ### Full Documentation | 1 |
Ruby | Ruby | remove dead code | 348c29100c63e09f8af7dc7b08e137f2ebd243a4 | <ide><path>activerecord/lib/active_record/tasks/database_tasks.rb
<ide> def schema_file(format = ActiveRecord::Base.schema_format)
<ide> end
<ide> end
<ide>
<del> def load_schema_current_if_exists(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
<del> if File.exist?(file || schema_file(format))
<del> load_schema_current(format, file, environment)
<del> end
<del> end
<del>
<ide> def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
<ide> each_current_configuration(environment) { |configuration|
<ide> load_schema configuration, format, file | 1 |
Ruby | Ruby | add support for private registry | b8954030e36b69508f3aa6747b9af04f1efaad92 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def resolve_url_basename_time_file_size(url, timeout: nil)
<ide> return @resolved_info_cache[url] if @resolved_info_cache.include?(url)
<ide>
<ide> if (domain = Homebrew::EnvConfig.artifact_domain)
<del> url = url.sub(%r{^((ht|f)tps?://)?}, "#{domain.chomp("/")}/")
<add> url = url.sub(%r{^((ht|f)tps?://ghcr.io/)?}, "#{domain.chomp("/")}/")
<ide> end
<ide>
<ide> out, _, status= curl_output("--location", "--silent", "--head", "--request", "GET", url.to_s, timeout: timeout)
<ide> def _fetch(url:, resolved_url:, timeout:)
<ide> def _curl_args
<ide> args = []
<ide>
<add> args += ["-L"] if Homebrew::EnvConfig.artifact_domain
<add>
<ide> args += ["-b", meta.fetch(:cookies).map { |k, v| "#{k}=#{v}" }.join(";")] if meta.key?(:cookies)
<ide>
<ide> args += ["-e", meta.fetch(:referer)] if meta.key?(:referer)
<ide> class CurlGitHubPackagesDownloadStrategy < CurlDownloadStrategy
<ide> def initialize(url, name, version, **meta)
<ide> meta ||= {}
<ide> meta[:headers] ||= []
<del> meta[:headers] << ["Authorization: Bearer QQ=="]
<add> token = ENV.fetch("HOMEBREW_REGISTRY_ACCESS_TOKEN", "QQ==")
<add> meta[:headers] << ["Authorization: Bearer #{token}"]
<ide> super(url, name, version, meta)
<ide> end
<ide>
<ide><path>Library/Homebrew/env_config.rb
<ide> module EnvConfig
<ide> description: "Use this GitHub personal access token when accessing the GitHub Packages Registry "\
<ide> "(where bottles may be stored).",
<ide> },
<add> HOMEBREW_REGISTRY_ACCESS_TOKEN: {
<add> description: "Use this bearer token for authenticating with a private registry proxying GitHub "\
<add> "Packages Registry.",
<add> },
<ide> HOMEBREW_GITHUB_PACKAGES_USER: {
<ide> description: "Use this username when accessing the GitHub Packages Registry (where bottles may be stored).",
<ide> }, | 2 |
Ruby | Ruby | favor compound if over compound unless | eee5a0920297dafaeb51007add4be2052c31d4db | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def remove_macosxsdk version=MacOS.version
<ide> delete('MACOSX_DEPLOYMENT_TARGET')
<ide> delete('CPATH')
<ide> remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib"
<del> unless (sdk = MacOS.sdk_path(version)).nil? or MacOS::CLT.installed?
<add>
<add> if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
<ide> delete('SDKROOT')
<ide> remove_from_cflags "-isysroot #{sdk}"
<ide> remove 'CPPFLAGS', "-isysroot #{sdk}"
<ide> def macosxsdk version=MacOS.version
<ide> self['MACOSX_DEPLOYMENT_TARGET'] = version
<ide> self['CPATH'] = "#{HOMEBREW_PREFIX}/include"
<ide> prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib"
<del> unless (sdk = MacOS.sdk_path(version)).nil? or MacOS::CLT.installed?
<add>
<add> if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
<ide> # Extra setup to support Xcode 4.3+ without CLT.
<ide> self['SDKROOT'] = sdk
<ide> # Tell clang/gcc where system include's are: | 1 |
Ruby | Ruby | enforce http for gnu ftpmirror | a047fc08d6353949441f65b1efd5b0359ce027a9 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_urls
<ide> problem "Please use \"http://ftpmirror.gnu.org\" instead of #{url}."
<ide> end
<ide>
<add> # GNU's ftpmirror does NOT support SSL/TLS.
<add> if url =~ %r[^https://ftpmirror\.gnu\.org/]
<add> problem "Please use http:// for #{url}"
<add> end
<add>
<ide> if mirrors.include?(url)
<ide> problem "URL should not be duplicated as a mirror: #{url}"
<ide> end
<ide> def audit_urls
<ide> # Check a variety of SSL/TLS URLs that don't consistently auto-redirect
<ide> # or are overly common errors that need to be reduced & fixed over time.
<ide> urls.each do |p|
<del> # Skip the main url link, as it can't be made SSL/TLS yet.
<del> next if p =~ %r[/ftpmirror\.gnu\.org]
<del>
<ide> case p
<ide> when %r[^http://ftp\.gnu\.org/],
<ide> %r[^http://[^/]*\.apache\.org/], | 1 |
Python | Python | add __str__ and __repr__ to periodic_event.event | 3f5cef69faafae4ec49e8fad9fbfa9efc0f17436 | <ide><path>research/astronet/light_curve_util/periodic_event.py
<ide> def __init__(self, period, duration, t0):
<ide> self._duration = duration
<ide> self._t0 = t0
<ide>
<add> def __str__(self):
<add> return "<period={}, duration={}, t0={}>".format(self.period, self.duration,
<add> self.t0)
<add>
<add> def __repr__(self):
<add> return "Event({})".format(str(self))
<add>
<ide> @property
<ide> def period(self):
<ide> return self._period
<ide><path>research/astronet/light_curve_util/periodic_event_test.py
<ide>
<ide> class EventTest(absltest.TestCase):
<ide>
<add> def testStr(self):
<add> self.assertEqual(str(Event(1, 2, 3)), "<period=1, duration=2, t0=3>")
<add>
<add> def testRepr(self):
<add> self.assertEqual(
<add> repr(Event(1, 2, 3)), "Event(<period=1, duration=2, t0=3>)")
<add>
<ide> def testEquals(self):
<ide> event = Event(period=100, duration=5, t0=2)
<ide>
<ide> def testEquals(self):
<ide> event.equals(Event(period=100, duration=5, t0=10), t0_durations=2))
<ide>
<ide>
<del>if __name__ == '__main__':
<add>if __name__ == "__main__":
<ide> absltest.main() | 2 |
Python | Python | set version to v2.3.3.dev0 | cd61d264ef4dbae642713169ade41404c24335df | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.3.2"
<add>__version__ = "2.3.3.dev0"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Ruby | Ruby | test some of the rc specification | 3060dfce5a45dac0d19ec3d73af3cdebdf0bb20e | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def prepare!
<ide> argv
<ide> end
<ide>
<add> def self.default_rc_file
<add> File.join(File.expand_path('~'), '.railsrc')
<add> end
<add>
<ide> private
<ide>
<ide> def handle_version_request!(argument)
<ide> def railsrc
<ide> if (customrc = argv.index{ |x| x.include?("--rc=") })
<ide> File.expand_path(argv.delete_at(customrc).gsub(/--rc=/, ""))
<ide> else
<del> File.join(File.expand_path("~"), '.railsrc')
<add> self.class.default_rc_file
<ide> end
<ide> end
<ide>
<ide><path>railties/test/generators/argv_scrubber_test.rb
<ide> require 'active_support/test_case'
<ide> require 'active_support/testing/autorun'
<ide> require 'rails/generators/rails/app/app_generator'
<add>require 'tempfile'
<ide>
<ide> module Rails
<ide> module Generators
<ide> def test_version
<ide> define_method(:puts) { |str| output = str }
<ide> define_method(:exit) { |code| exit_code = code }
<ide> })
<del> scrubber.prepare
<add> scrubber.prepare!
<ide> assert_equal "Rails #{Rails::VERSION::STRING}", output
<ide> assert_equal 0, exit_code
<ide> end
<ide> end
<ide>
<ide> def test_prepare_returns_args
<ide> scrubber = ARGVScrubber.new ['hi mom']
<del> args = scrubber.prepare
<add> args = scrubber.prepare!
<ide> assert_equal '--help', args.first
<ide> end
<ide>
<ide> def test_no_mutations
<ide> scrubber = ARGVScrubber.new ['hi mom'].freeze
<del> args = scrubber.prepare
<add> args = scrubber.prepare!
<ide> assert_equal '--help', args.first
<ide> end
<add>
<add> def test_new_command_no_rc
<add> scrubber = Class.new(ARGVScrubber) {
<add> def self.default_rc_file
<add> File.join(Dir.tmpdir, 'whatever')
<add> end
<add> }.new ['new']
<add> args = scrubber.prepare!
<add> assert_nil args.first
<add> assert_equal [], args
<add> end
<add>
<add> def test_new_homedir_rc
<add> file = Tempfile.new 'myrcfile'
<add> file.puts '--hello-world'
<add> file.flush
<add>
<add> message = nil
<add> scrubber = Class.new(ARGVScrubber) {
<add> define_singleton_method(:default_rc_file) do
<add> file.path
<add> end
<add> define_method(:puts) { |msg| message = msg }
<add> }.new ['new']
<add> args = scrubber.prepare!
<add> assert_nil args.first
<add> assert_equal [nil, '--hello-world'], args
<add> assert_match 'hello-world', message
<add> assert_match file.path, message
<add> ensure
<add> file.close
<add> file.unlink
<add> end
<add>
<add> def test_no_rc
<add> scrubber = ARGVScrubber.new ['new', '--no-rc']
<add> args = scrubber.prepare!
<add> assert_equal [], args
<add> end
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | remove unused property | d4f1b423350607582d33bbd9710747ea7558fd38 | <ide><path>src/Illuminate/Cache/NullStore.php
<ide> class NullStore extends TaggableStore
<ide> {
<ide> use RetrievesMultipleKeys;
<ide>
<del> /**
<del> * The array of stored values.
<del> *
<del> * @var array
<del> */
<del> protected $storage = [];
<del>
<ide> /**
<ide> * Retrieve an item from the cache by key.
<ide> * | 1 |
PHP | PHP | fix tests on windows | c7687561da4216ce94ef11e969dc489193adb77e | <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public function testCreateSql() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide> }
<ide>
<ide> /**
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide>
<ide> $table = (new Table('composite_key'))
<ide> ->addColumn('id', [
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public function testConstraintSql($name, $data, $expected) {
<ide> 'type' => 'integer',
<ide> ])->addConstraint($name, $data);
<ide>
<del> $this->assertEquals($expected, $schema->constraintSql($table, $name));
<add> $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
<ide> }
<ide>
<ide> /**
<ide> public function testCreateSql() {
<ide> $result = $table->createSql($connection);
<ide>
<ide> $this->assertCount(3, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide> $this->assertEquals(
<ide> 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
<ide> $result[1]
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide>
<ide> $table = (new Table('composite_key'))
<ide> ->addColumn('id', [
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide>
<ide> // Sqlite only supports AUTO_INCREMENT on single column primary
<ide> // keys. Ensure that schema data follows the limitations of Sqlite.
<ide> public function testCreateSqlCompositeIntegerKey() {
<ide> SQL;
<ide> $result = $table->createSql($connection);
<ide> $this->assertCount(1, $result);
<del> $this->assertEquals($expected, $result[0]);
<add> $this->assertTextEquals($expected, $result[0]);
<ide> }
<ide>
<ide> /** | 3 |
Text | Text | fix spelling errors | 7506631c77e236dc43626d2c5441be2142ddcf28 | <ide><path>guide/english/c/Dinamic Memory Management/index.md
<ide> title: Dynamic Memory Management
<ide> ---
<ide> # Dynamic Memory Management
<del>Sometimes you will need to allocate memory spaces in the heap also known as the dinamic memory. This is particulary usefull when you do not know during compile time how large a data structure (like an array) will be.
<add>Sometimes you will need to allocate memory spaces in the heap also known as the dynamic memory. This is particulary usefull when you do not know during compile time how large a data structure (like an array) will be.
<ide> ## An Example
<ide> Here's a simple example where we allocate an array asking the user to choose the dimension
<ide> ```C
<ide> int main(void) {
<ide> }
<ide> ```
<ide>
<del>As you can see in order to allocate a space in the dinamic memory you need to know how pointers work in C.
<add>As you can see in order to allocate a space in the dynamic memory you need to know how pointers work in C.
<ide> The magic function here is the `malloc` which will return as output a void pointer (it is a pointer to a region of unknown data type) to the new memory space we've just allocated.
<ide> Let's see how to use this function step by step:
<ide> | 1 |
Ruby | Ruby | fix the indentation | 2f6cc48b34f892d7608cb68e4cd0b7f5aabb5d03 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def polymorphic?
<ide>
<ide> protected
<ide>
<del> def actual_source_reflection # FIXME: this is a horrible name
<del> self
<del> end
<add> def actual_source_reflection # FIXME: this is a horrible name
<add> self
<add> end
<ide>
<ide> private
<del> def calculate_constructable(macro, options)
<del> case macro
<del> when :belongs_to
<del> !options[:polymorphic]
<del> when :has_one
<del> !options[:through]
<del> else
<del> true
<add>
<add> def calculate_constructable(macro, options)
<add> case macro
<add> when :belongs_to
<add> !options[:polymorphic]
<add> when :has_one
<add> !options[:through]
<add> else
<add> true
<add> end
<ide> end
<del> end
<ide>
<ide> # Attempts to find the inverse association name automatically.
<ide> # If it cannot find a suitable inverse association name, it returns | 1 |
Go | Go | improve error message | 6a9fb81c5794166fc62e8fc5c638127d69f13eee | <ide><path>runtime.go
<ide> func (runtime *Runtime) Create(config *Config, name string) (*Container, []strin
<ide>
<ide> // Set the enitity in the graph using the default name specified
<ide> if _, err := runtime.containerGraph.Set(name, id); err != nil {
<add> if strings.HasSuffix(err.Error(), "name are not unique") {
<add> return nil, nil, fmt.Errorf("Conflict, %s already exists.", name)
<add> }
<ide> return nil, nil, err
<ide> }
<ide> | 1 |
Text | Text | finish the working with styles section | be229d374e1dd93e7bccac5bd904b6ec93d98cea | <ide><path>docs/packages/creating_a_package.md
<ide> Let's get started!
<ide> ## Changing Keybindings and Commands
<ide>
<ide> Since Changer is primarily concerned with the file tree, let's write a keybinding
<del>that works only when the tree is active. Instead of using the default `toggle`,
<add>that works only when the tree is focused. Instead of using the default `toggle`,
<ide> our keybinding executes a new command called `magic`.
<ide>
<ide> _keymaps/changer.cson_ can easily become this:
<ide> _keymaps/changer.cson_ can easily become this:
<ide> 'ctrl-V': 'changer:magic'
<ide> ```
<ide>
<del>`.tree-view-scroller` represents the parent container for the tree view. Also,
<del>notice that the keybinding is called `ctrl-V`--that's actually `ctrl-shift-v`.
<add>Notice that the keybinding is called `ctrl-V`--that's actually `ctrl-shift-v`.
<ide> You can use capital letters to denote using `shift` for your binding.
<ide>
<add>`.tree-view-scroller` represents the parent container for the tree view. Keybindings
<add>only work within the context of where they're entered. For example, hitting `ctrl-V`
<add>anywhere other than tree won't do anything. You can map to `body` if you want
<add>to scope to anywhere in Atom, or just `.editor` for the editor portion.
<add>
<ide> To bind keybindings to a command, we'll use the `rootView.command` method. This
<ide> takes a command name and executes a function in the code. For example:
<ide>
<ide> Hitting the key binding on the tree now works!
<ide> ## Working with styles
<ide>
<ide> The next step is to hide elements in the tree that aren't modified. To do that,
<del>we'll first (obviously) try and get a list of files that have not changed.
<add>we'll first try and get a list of files that have not changed.
<add>
<add>All packages are able to use jQuery in their code. In fact, we have [a list of
<add>some of the bundled libraries Atom provides by default](./included_libraries.md).
<ide>
<del>All packages are able to use jQuery in their code. So let's include that at the top:
<add>Let's bring in jQuery:
<ide>
<ide> ```coffeescript
<ide> $ = require 'jquery'
<ide> ```
<ide>
<del>Now, we can query the tree to get us a list of every file that _wasn't_ modified
<del>using some jQuery syntax.
<add>Now, we can query the tree to get us a list of every file that _wasn't_ modified:
<add>
<add>```coffeescript
<add>magic: ->
<add> $('ol.entries li').each (i, el) ->
<add> if !$(el).hasClass("modified")
<add> console.log el
<add>```
<add>
<add>You can access the dev console by hitting `alt-meta-i`. When we execute the
<add>`changer:magic` command, the browser console lists the items that are not being
<add>modified. Let's add a class to each of these elements called `hide-me`:
<add>
<add>``coffeescript
<add>magic: ->
<add> $('ol.entries li').each (i, el) ->
<add> if !$(el).hasClass("modified")
<add> $(el).addClass("hide-me")
<add>```
<add>
<add>With our newly added class, we can manipulate the visibility of the elements
<add>with a simple stylesheet. Open up _changer.css_ in the _stylesheets_ directory,
<add>and add a single entry:
<add>
<add>```css
<add>ol.entries .hide-me {
<add> display: none;
<add>}
<add>```
<add>
<add>Refresh atom, and run the `changer` command. You'll see all the non-changed files
<add>disappear from the tree. There are a number of ways you can get the list back;
<add>let's just naively iterate over the same elements and remove the class:
<add>
<add> ``coffeescript
<add>magic: ->
<add> $('ol.entries li').each (i, el) ->
<add> if !$(el).hasClass("modified")
<add> if !$(el).hasClass("hide-me")
<add> $(el).addClass("hide-me")
<add> else
<add> $(el).removeClass("hide-me")
<add> ```
<add>
<add>## Creating a New Pane
<ide>\ No newline at end of file | 1 |
Text | Text | fix yaml syntax in fs.md | 0c49038f88086dd4ad79e471aa730d3891acc443 | <ide><path>doc/api/fs.md
<ide> and `fs.unwatchFile()` when possible.
<ide> <!-- YAML
<ide> added: v0.4.2
<ide> changes:
<del> - version: v8.0.0
<add> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/11919
<del> description: `NaN`, `Infinity`, and `-Infinity` are no longer valid time
<del> specifiers.
<add> description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
<add> specifiers."
<ide> - version: v7.6.0
<ide> pr-url: https://github.com/nodejs/node/pull/10739
<ide> description: The `path` parameter can be a WHATWG `URL` object using `file:`
<ide> added: v0.4.2
<ide> changes:
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/11919
<del> description: `NaN`, `Infinity`, and `-Infinity` are no longer valid time
<del> specifiers.
<add> description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
<add> specifiers."
<ide> - version: v7.6.0
<ide> pr-url: https://github.com/nodejs/node/pull/10739
<ide> description: The `path` parameter can be a WHATWG `URL` object using `file:` | 1 |
Python | Python | combine ma.sort and maskedarray.sort | 9c865d565e10fa7461560fa3d99eadaa4feebcad | <ide><path>numpy/ma/core.py
<ide> def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None):
<ide>
<ide> def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None):
<ide> "Function version of the eponymous method."
<del> a = narray(a, copy=True, subok=True)
<add> a = np.array(a, copy=True, subok=True)
<ide> if axis is None:
<ide> a = a.flatten()
<ide> axis = 0
<del> if fill_value is None:
<del> if endwith:
<del> # nan > inf
<del> if np.issubdtype(a.dtype, np.floating):
<del> filler = np.nan
<del> else:
<del> filler = minimum_fill_value(a)
<del> else:
<del> filler = maximum_fill_value(a)
<del> else:
<del> filler = fill_value
<ide>
<del> sindx = filled(a, filler).argsort(axis=axis, kind=kind, order=order)
<del>
<del> # save meshgrid memory for 1d arrays
<del> if a.ndim == 1:
<del> indx = sindx
<add> if isinstance(a, MaskedArray):
<add> a.sort(axis=axis, kind=kind, order=order,
<add> endwith=endwith, fill_value=fill_value)
<ide> else:
<del> indx = np.meshgrid(*[np.arange(x) for x in a.shape], sparse=True,
<del> indexing='ij')
<del> indx[axis] = sindx
<del> return a[indx]
<add> a.sort(axis=axis, kind=kind, order=order)
<add> return a
<ide> sort.__doc__ = MaskedArray.sort.__doc__
<ide>
<ide> | 1 |
Python | Python | pass a tuple of alternatives to str.endswith() | b25a73f26a6b61ad4eee24e47a1db3d00e528955 | <ide><path>configure.py
<ide> def glob_to_var(dir_base, dir_sub, patch_dir):
<ide> for ent in files:
<ide> (path, dirs, files) = ent
<ide> for file in files:
<del> if file.endswith('.cpp') or file.endswith('.c') or file.endswith('.h'):
<add> if file.endswith(('.cpp', '.c', '.h')):
<ide> # srcfile uses "slash" as dir separator as its output is consumed by gyp
<ide> srcfile = '%s/%s' % (dir_sub, file)
<ide> if patch_dir: | 1 |
Javascript | Javascript | delay some requires in animated | 482b4b6bfaeedecbf155be835aa57ce7923dd6d1 | <ide><path>Libraries/Animated/src/AnimatedImplementation.js
<ide> */
<ide> 'use strict';
<ide>
<del>var Easing = require('Easing');
<ide> var InteractionManager = require('InteractionManager');
<ide> var Interpolation = require('Interpolation');
<ide> var React = require('React');
<ide> type TimingAnimationConfigSingle = AnimationConfig & {
<ide> delay?: number;
<ide> };
<ide>
<del>var easeInOut = Easing.inOut(Easing.ease);
<add>let _easeInOut;
<add>function easeInOut() {
<add> if (!_easeInOut) {
<add> const Easing = require('Easing');
<add> _easeInOut = Easing.inOut(Easing.ease);
<add> }
<add> return _easeInOut;
<add>}
<ide>
<ide> class TimingAnimation extends Animation {
<ide> _startTime: number;
<ide> class TimingAnimation extends Animation {
<ide> ) {
<ide> super();
<ide> this._toValue = config.toValue;
<del> this._easing = config.easing !== undefined ? config.easing : easeInOut;
<add> this._easing = config.easing !== undefined ? config.easing : easeInOut();
<ide> this._duration = config.duration !== undefined ? config.duration : 500;
<ide> this._delay = config.delay !== undefined ? config.delay : 0;
<ide> this.__isInteraction = config.isInteraction !== undefined ? config.isInteraction : true;
<ide><path>Libraries/Animated/src/Easing.js
<ide> */
<ide> 'use strict';
<ide>
<del>var _bezier = require('bezier');
<add>let ease;
<ide>
<ide> /**
<ide> * This class implements common easing functions. The math is pretty obscure,
<ide> class Easing {
<ide> }
<ide>
<ide> static ease(t: number): number {
<add> if (!ease) {
<add> ease = Easing.bezier(0.42, 0, 1, 1);
<add> }
<ide> return ease(t);
<ide> }
<ide>
<ide> class Easing {
<ide> * http://tiny.cc/elastic_b_3 (bounciness = 3)
<ide> */
<ide> static elastic(bounciness: number = 1): (t: number) => number {
<del> var p = bounciness * Math.PI;
<add> const p = bounciness * Math.PI;
<ide> return (t) => 1 - Math.pow(Math.cos(t * Math.PI / 2), 3) * Math.cos(t * p);
<ide> }
<ide>
<ide> class Easing {
<ide> x2: number,
<ide> y2: number
<ide> ): (t: number) => number {
<add> const _bezier = require('bezier');
<ide> return _bezier(x1, y1, x2, y2);
<ide> }
<ide>
<ide> class Easing {
<ide> }
<ide> }
<ide>
<del>var ease = Easing.bezier(0.42, 0, 1, 1);
<del>
<del>
<del>
<ide> module.exports = Easing; | 2 |
Go | Go | fix tty copy for driver | 172260a49be6c3516edc6869d58957e844f9c69b | <ide><path>execdriver/namespaces/driver.go
<ide> import (
<ide> "github.com/dotcloud/docker/execdriver/lxc"
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/nsinit"
<add> "io"
<ide> "io/ioutil"
<ide> "os"
<ide> "os/exec"
<ide> type dockerTtyTerm struct {
<ide> }
<ide>
<ide> func (t *dockerTtyTerm) Attach(cmd *exec.Cmd) error {
<del> return t.AttachPipes(cmd, t.pipes)
<add> go io.Copy(t.pipes.Stdout, t.MasterPty)
<add> if t.pipes.Stdin != nil {
<add> go io.Copy(t.MasterPty, t.pipes.Stdin)
<add> }
<add> return nil
<ide> }
<ide>
<ide> func (t *dockerTtyTerm) SetMaster(master *os.File) { | 1 |
Java | Java | fix typo in javadoc | 5a0b768a3d81c7f3190b64162f96f69f91ee90c6 | <ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java
<ide> protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttp
<ide> * Format the request for logging purposes including HTTP method and URL.
<ide> * <p>By default this prints the HTTP method, the URL path, and the query.
<ide> * @param request the request to format
<del> * @return the String to display, never empty or @code null}
<add> * @return the String to display, never empty or {@code null}
<ide> */
<ide> protected String formatRequest(ServerHttpRequest request) {
<ide> String rawQuery = request.getURI().getRawQuery(); | 1 |
PHP | PHP | add documentation on additional options | 176ec2df0c562bf79c3b072514a2e90db6db0a08 | <ide><path>lib/Cake/View/Helper/TimeHelper.php
<ide> public function toRSS($dateString, $timezone = null) {
<ide> /**
<ide> * @see CakeTime::timeAgoInWords()
<ide> *
<add> * ## Addition options
<add> *
<add> * - `element` - The element to wrap the formatted time in.
<add> * Has a few additional options:
<add> * - `tag` - The tag to use, defaults to 'span'.
<add> * - `class` - The classname to use, defaults to `time-ago-in-words`.
<add> * - `title` - Defaults to the $dateTime input.
<add> *
<ide> * @param string $dateTime Datetime string or Unix timestamp
<ide> * @param array $options Default format if timestamp is used in $dateString
<ide> * @return string Relative time string. | 1 |
Python | Python | branch a run_squad.py for albert | 02d78796a206fb4e9a207eb3800e2ec5d18d9663 | <ide><path>official/nlp/albert/run_squad.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Run ALBERT on SQuAD 1.1 and SQuAD 2.0 in TF 2.x."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import json
<add>
<add>from absl import app
<add>from absl import flags
<add>import tensorflow as tf
<add>
<add>from official.nlp.albert import configs as albert_configs
<add>from official.nlp.bert import run_squad_helper
<add>from official.nlp.bert import tokenization
<add>from official.nlp.data import squad_lib_sp
<add>from official.utils.misc import distribution_utils
<add>
<add>flags.DEFINE_string(
<add> 'sp_model_file', None,
<add> 'The path to the sentence piece model. Used by sentence piece tokenizer '
<add> 'employed by ALBERT.')
<add>
<add># More flags can be found in run_squad_helper.
<add>run_squad_helper.define_common_squad_flags()
<add>
<add>FLAGS = flags.FLAGS
<add>
<add>
<add>def train_squad(strategy,
<add> input_meta_data,
<add> custom_callbacks=None,
<add> run_eagerly=False):
<add> """Runs bert squad training."""
<add> bert_config = albert_configs.AlbertConfig.from_json_file(
<add> FLAGS.bert_config_file)
<add> run_squad_helper.train_squad(strategy, input_meta_data, bert_config,
<add> custom_callbacks, run_eagerly)
<add>
<add>
<add>def predict_squad(strategy, input_meta_data):
<add> """Makes predictions for a squad dataset."""
<add> bert_config = albert_configs.AlbertConfig.from_json_file(
<add> FLAGS.bert_config_file)
<add> tokenizer = tokenization.FullSentencePieceTokenizer(
<add> sp_model_file=FLAGS.sp_model_file)
<add>
<add> run_squad_helper.predict_squad(strategy, input_meta_data, tokenizer,
<add> bert_config, squad_lib_sp)
<add>
<add>
<add>def export_squad(model_export_path, input_meta_data):
<add> """Exports a trained model as a `SavedModel` for inference.
<add>
<add> Args:
<add> model_export_path: a string specifying the path to the SavedModel directory.
<add> input_meta_data: dictionary containing meta data about input and model.
<add>
<add> Raises:
<add> Export path is not specified, got an empty string or None.
<add> """
<add> bert_config = albert_configs.AlbertConfig.from_json_file(
<add> FLAGS.bert_config_file)
<add> run_squad_helper.export_squad(model_export_path, input_meta_data, bert_config)
<add>
<add>
<add>def main(_):
<add> # Users should always run this script under TF 2.x
<add> assert tf.version.VERSION.startswith('2.')
<add>
<add> with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader:
<add> input_meta_data = json.loads(reader.read().decode('utf-8'))
<add>
<add> if FLAGS.mode == 'export_only':
<add> export_squad(FLAGS.model_export_path, input_meta_data)
<add> return
<add>
<add> # Configures cluster spec for multi-worker distribution strategy.
<add> if FLAGS.num_gpus > 0:
<add> _ = distribution_utils.configure_cluster(FLAGS.worker_hosts,
<add> FLAGS.task_index)
<add> strategy = distribution_utils.get_distribution_strategy(
<add> distribution_strategy=FLAGS.distribution_strategy,
<add> num_gpus=FLAGS.num_gpus,
<add> all_reduce_alg=FLAGS.all_reduce_alg,
<add> tpu_address=FLAGS.tpu)
<add> if FLAGS.mode in ('train', 'train_and_predict'):
<add> train_squad(strategy, input_meta_data, run_eagerly=FLAGS.run_eagerly)
<add> if FLAGS.mode in ('predict', 'train_and_predict'):
<add> predict_squad(strategy, input_meta_data)
<add>
<add>
<add>if __name__ == '__main__':
<add> flags.mark_flag_as_required('bert_config_file')
<add> flags.mark_flag_as_required('model_dir')
<add> app.run(main)
<ide><path>official/nlp/bert/common_flags.py
<ide> def define_common_bert_flags():
<ide> flags.DEFINE_string(
<ide> 'hub_module_url', None, 'TF-Hub path/url to Bert module. '
<ide> 'If specified, init_checkpoint flag should not be used.')
<del> flags.DEFINE_enum(
<del> 'model_type', 'bert', ['bert', 'albert'],
<del> 'Specifies the type of the model. '
<del> 'If "bert", will use canonical BERT; if "albert", will use ALBERT model.')
<ide> flags.DEFINE_bool('hub_module_trainable', True,
<ide> 'True to make keras layers in the hub module trainable.')
<ide>
<ide><path>official/nlp/bert/run_squad.py
<ide> from __future__ import print_function
<ide>
<ide> import json
<del>import os
<ide>
<ide> from absl import app
<ide> from absl import flags
<del>from absl import logging
<ide> import tensorflow as tf
<ide>
<del>from official.modeling import model_training_utils
<del>from official.nlp import optimization
<del>from official.nlp.albert import configs as albert_configs
<del>from official.nlp.bert import bert_models
<del>from official.nlp.bert import common_flags
<ide> from official.nlp.bert import configs as bert_configs
<del>from official.nlp.bert import input_pipeline
<del>from official.nlp.bert import model_saving_utils
<add>from official.nlp.bert import run_squad_helper
<ide> from official.nlp.bert import tokenization
<del># word-piece tokenizer based squad_lib
<ide> from official.nlp.data import squad_lib as squad_lib_wp
<del># sentence-piece tokenizer based squad_lib
<del>from official.nlp.data import squad_lib_sp
<ide> from official.utils.misc import distribution_utils
<del>from official.utils.misc import keras_utils
<ide>
<del>flags.DEFINE_enum(
<del> 'mode', 'train_and_predict',
<del> ['train_and_predict', 'train', 'predict', 'export_only'],
<del> 'One of {"train_and_predict", "train", "predict", "export_only"}. '
<del> '`train_and_predict`: both train and predict to a json file. '
<del> '`train`: only trains the model. '
<del> '`predict`: predict answers from the squad json file. '
<del> '`export_only`: will take the latest checkpoint inside '
<del> 'model_dir and export a `SavedModel`.')
<del>flags.DEFINE_string('train_data_path', '',
<del> 'Training data path with train tfrecords.')
<del>flags.DEFINE_string(
<del> 'input_meta_data_path', None,
<del> 'Path to file that contains meta data about input '
<del> 'to be used for training and evaluation.')
<del># Model training specific flags.
<del>flags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.')
<del># Predict processing related.
<del>flags.DEFINE_string('predict_file', None,
<del> 'Prediction data path with train tfrecords.')
<add>
<ide> flags.DEFINE_string('vocab_file', None,
<ide> 'The vocabulary file that the BERT model was trained on.')
<del>flags.DEFINE_bool(
<del> 'do_lower_case', True,
<del> 'Whether to lower case the input text. Should be True for uncased '
<del> 'models and False for cased models.')
<del>flags.DEFINE_float(
<del> 'null_score_diff_threshold', 0.0,
<del> 'If null_score - best_non_null is greater than the threshold, '
<del> 'predict null. This is only used for SQuAD v2.')
<del>flags.DEFINE_bool(
<del> 'verbose_logging', False,
<del> 'If true, all of the warnings related to data processing will be printed. '
<del> 'A number of warnings are expected for a normal SQuAD evaluation.')
<del>flags.DEFINE_integer('predict_batch_size', 8,
<del> 'Total batch size for prediction.')
<del>flags.DEFINE_integer(
<del> 'n_best_size', 20,
<del> 'The total number of n-best predictions to generate in the '
<del> 'nbest_predictions.json output file.')
<del>flags.DEFINE_integer(
<del> 'max_answer_length', 30,
<del> 'The maximum length of an answer that can be generated. This is needed '
<del> 'because the start and end predictions are not conditioned on one another.')
<del>flags.DEFINE_string(
<del> 'sp_model_file', None,
<del> 'The path to the sentence piece model. Used by sentence piece tokenizer '
<del> 'employed by ALBERT.')
<del>
<ide>
<del>common_flags.define_common_bert_flags()
<add># More flags can be found in run_squad_helper.
<add>run_squad_helper.define_common_squad_flags()
<ide>
<ide> FLAGS = flags.FLAGS
<ide>
<del>MODEL_CLASSES = {
<del> 'bert': (bert_configs.BertConfig, squad_lib_wp, tokenization.FullTokenizer),
<del> 'albert': (albert_configs.AlbertConfig, squad_lib_sp,
<del> tokenization.FullSentencePieceTokenizer),
<del>}
<del>
<del>
<del>def squad_loss_fn(start_positions,
<del> end_positions,
<del> start_logits,
<del> end_logits,
<del> loss_factor=1.0):
<del> """Returns sparse categorical crossentropy for start/end logits."""
<del> start_loss = tf.keras.losses.sparse_categorical_crossentropy(
<del> start_positions, start_logits, from_logits=True)
<del> end_loss = tf.keras.losses.sparse_categorical_crossentropy(
<del> end_positions, end_logits, from_logits=True)
<del>
<del> total_loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2
<del> total_loss *= loss_factor
<del> return total_loss
<del>
<del>
<del>def get_loss_fn(loss_factor=1.0):
<del> """Gets a loss function for squad task."""
<del>
<del> def _loss_fn(labels, model_outputs):
<del> start_positions = labels['start_positions']
<del> end_positions = labels['end_positions']
<del> start_logits, end_logits = model_outputs
<del> return squad_loss_fn(
<del> start_positions,
<del> end_positions,
<del> start_logits,
<del> end_logits,
<del> loss_factor=loss_factor)
<del>
<del> return _loss_fn
<del>
<del>
<del>def get_raw_results(predictions):
<del> """Converts multi-replica predictions to RawResult."""
<del> squad_lib = MODEL_CLASSES[FLAGS.model_type][1]
<del> for unique_ids, start_logits, end_logits in zip(predictions['unique_ids'],
<del> predictions['start_logits'],
<del> predictions['end_logits']):
<del> for values in zip(unique_ids.numpy(), start_logits.numpy(),
<del> end_logits.numpy()):
<del> yield squad_lib.RawResult(
<del> unique_id=values[0],
<del> start_logits=values[1].tolist(),
<del> end_logits=values[2].tolist())
<del>
<del>
<del>def get_dataset_fn(input_file_pattern, max_seq_length, global_batch_size,
<del> is_training):
<del> """Gets a closure to create a dataset.."""
<del>
<del> def _dataset_fn(ctx=None):
<del> """Returns tf.data.Dataset for distributed BERT pretraining."""
<del> batch_size = ctx.get_per_replica_batch_size(
<del> global_batch_size) if ctx else global_batch_size
<del> dataset = input_pipeline.create_squad_dataset(
<del> input_file_pattern,
<del> max_seq_length,
<del> batch_size,
<del> is_training=is_training,
<del> input_pipeline_context=ctx)
<del> return dataset
<del>
<del> return _dataset_fn
<del>
<del>
<del>def predict_squad_customized(strategy, input_meta_data, bert_config,
<del> predict_tfrecord_path, num_steps):
<del> """Make predictions using a Bert-based squad model."""
<del> predict_dataset_fn = get_dataset_fn(
<del> predict_tfrecord_path,
<del> input_meta_data['max_seq_length'],
<del> FLAGS.predict_batch_size,
<del> is_training=False)
<del> predict_iterator = iter(
<del> strategy.experimental_distribute_datasets_from_function(
<del> predict_dataset_fn))
<del>
<del> with strategy.scope():
<del> # Prediction always uses float32, even if training uses mixed precision.
<del> tf.keras.mixed_precision.experimental.set_policy('float32')
<del> squad_model, _ = bert_models.squad_model(
<del> bert_config,
<del> input_meta_data['max_seq_length'],
<del> hub_module_url=FLAGS.hub_module_url)
<del>
<del> checkpoint_path = tf.train.latest_checkpoint(FLAGS.model_dir)
<del> logging.info('Restoring checkpoints from %s', checkpoint_path)
<del> checkpoint = tf.train.Checkpoint(model=squad_model)
<del> checkpoint.restore(checkpoint_path).expect_partial()
<del>
<del> @tf.function
<del> def predict_step(iterator):
<del> """Predicts on distributed devices."""
<del>
<del> def _replicated_step(inputs):
<del> """Replicated prediction calculation."""
<del> x, _ = inputs
<del> unique_ids = x.pop('unique_ids')
<del> start_logits, end_logits = squad_model(x, training=False)
<del> return dict(
<del> unique_ids=unique_ids,
<del> start_logits=start_logits,
<del> end_logits=end_logits)
<del>
<del> outputs = strategy.experimental_run_v2(
<del> _replicated_step, args=(next(iterator),))
<del> return tf.nest.map_structure(strategy.experimental_local_results, outputs)
<del>
<del> all_results = []
<del> for _ in range(num_steps):
<del> predictions = predict_step(predict_iterator)
<del> for result in get_raw_results(predictions):
<del> all_results.append(result)
<del> if len(all_results) % 100 == 0:
<del> logging.info('Made predictions for %d records.', len(all_results))
<del> return all_results
<del>
<ide>
<ide> def train_squad(strategy,
<ide> input_meta_data,
<ide> custom_callbacks=None,
<ide> run_eagerly=False):
<ide> """Run bert squad training."""
<del> if strategy:
<del> logging.info('Training using customized training loop with distribution'
<del> ' strategy.')
<del> # Enables XLA in Session Config. Should not be set for TPU.
<del> keras_utils.set_config_v2(FLAGS.enable_xla)
<del>
<del> use_float16 = common_flags.use_float16()
<del> if use_float16:
<del> tf.keras.mixed_precision.experimental.set_policy('mixed_float16')
<del>
<del> bert_config = MODEL_CLASSES[FLAGS.model_type][0].from_json_file(
<del> FLAGS.bert_config_file)
<del> epochs = FLAGS.num_train_epochs
<del> num_train_examples = input_meta_data['train_data_size']
<del> max_seq_length = input_meta_data['max_seq_length']
<del> steps_per_epoch = int(num_train_examples / FLAGS.train_batch_size)
<del> warmup_steps = int(epochs * num_train_examples * 0.1 / FLAGS.train_batch_size)
<del> train_input_fn = get_dataset_fn(
<del> FLAGS.train_data_path,
<del> max_seq_length,
<del> FLAGS.train_batch_size,
<del> is_training=True)
<del>
<del> def _get_squad_model():
<del> """Get Squad model and optimizer."""
<del> squad_model, core_model = bert_models.squad_model(
<del> bert_config,
<del> max_seq_length,
<del> hub_module_url=FLAGS.hub_module_url,
<del> hub_module_trainable=FLAGS.hub_module_trainable)
<del> squad_model.optimizer = optimization.create_optimizer(
<del> FLAGS.learning_rate, steps_per_epoch * epochs, warmup_steps)
<del> if use_float16:
<del> # Wraps optimizer with a LossScaleOptimizer. This is done automatically
<del> # in compile() with the "mixed_float16" policy, but since we do not call
<del> # compile(), we must wrap the optimizer manually.
<del> squad_model.optimizer = (
<del> tf.keras.mixed_precision.experimental.LossScaleOptimizer(
<del> squad_model.optimizer, loss_scale=common_flags.get_loss_scale()))
<del> if FLAGS.fp16_implementation == 'graph_rewrite':
<del> # Note: when flags_obj.fp16_implementation == "graph_rewrite", dtype as
<del> # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32'
<del> # which will ensure tf.compat.v2.keras.mixed_precision and
<del> # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double
<del> # up.
<del> squad_model.optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(
<del> squad_model.optimizer)
<del> return squad_model, core_model
<del>
<del> # The original BERT model does not scale the loss by
<del> # 1/num_replicas_in_sync. It could be an accident. So, in order to use
<del> # the same hyper parameter, we do the same thing here by keeping each
<del> # replica loss as it is.
<del> loss_fn = get_loss_fn(
<del> loss_factor=1.0 /
<del> strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0)
<del>
<del> model_training_utils.run_customized_training_loop(
<del> strategy=strategy,
<del> model_fn=_get_squad_model,
<del> loss_fn=loss_fn,
<del> model_dir=FLAGS.model_dir,
<del> steps_per_epoch=steps_per_epoch,
<del> steps_per_loop=FLAGS.steps_per_loop,
<del> epochs=epochs,
<del> train_input_fn=train_input_fn,
<del> init_checkpoint=FLAGS.init_checkpoint,
<del> run_eagerly=run_eagerly,
<del> custom_callbacks=custom_callbacks)
<add> bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<add> run_squad_helper.train_squad(strategy, input_meta_data, bert_config,
<add> custom_callbacks, run_eagerly)
<ide>
<ide>
<ide> def predict_squad(strategy, input_meta_data):
<ide> """Makes predictions for a squad dataset."""
<del> config_cls, squad_lib, tokenizer_cls = MODEL_CLASSES[FLAGS.model_type]
<del> bert_config = config_cls.from_json_file(FLAGS.bert_config_file)
<del> if tokenizer_cls == tokenization.FullTokenizer:
<del> tokenizer = tokenizer_cls(
<del> vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
<del> else:
<del> assert tokenizer_cls == tokenization.FullSentencePieceTokenizer
<del> tokenizer = tokenizer_cls(sp_model_file=FLAGS.sp_model_file)
<del> doc_stride = input_meta_data['doc_stride']
<del> max_query_length = input_meta_data['max_query_length']
<del> # Whether data should be in Ver 2.0 format.
<del> version_2_with_negative = input_meta_data.get('version_2_with_negative',
<del> False)
<del> eval_examples = squad_lib.read_squad_examples(
<del> input_file=FLAGS.predict_file,
<del> is_training=False,
<del> version_2_with_negative=version_2_with_negative)
<del>
<del> eval_writer = squad_lib.FeatureWriter(
<del> filename=os.path.join(FLAGS.model_dir, 'eval.tf_record'),
<del> is_training=False)
<del> eval_features = []
<del>
<del> def _append_feature(feature, is_padding):
<del> if not is_padding:
<del> eval_features.append(feature)
<del> eval_writer.process_feature(feature)
<del>
<del> # TPU requires a fixed batch size for all batches, therefore the number
<del> # of examples must be a multiple of the batch size, or else examples
<del> # will get dropped. So we pad with fake examples which are ignored
<del> # later on.
<del> kwargs = dict(
<del> examples=eval_examples,
<del> tokenizer=tokenizer,
<del> max_seq_length=input_meta_data['max_seq_length'],
<del> doc_stride=doc_stride,
<del> max_query_length=max_query_length,
<del> is_training=False,
<del> output_fn=_append_feature,
<del> batch_size=FLAGS.predict_batch_size)
<del>
<del> # squad_lib_sp requires one more argument 'do_lower_case'.
<del> if squad_lib == squad_lib_sp:
<del> kwargs['do_lower_case'] = FLAGS.do_lower_case
<del> dataset_size = squad_lib.convert_examples_to_features(**kwargs)
<del> eval_writer.close()
<del>
<del> logging.info('***** Running predictions *****')
<del> logging.info(' Num orig examples = %d', len(eval_examples))
<del> logging.info(' Num split examples = %d', len(eval_features))
<del> logging.info(' Batch size = %d', FLAGS.predict_batch_size)
<del>
<del> num_steps = int(dataset_size / FLAGS.predict_batch_size)
<del> all_results = predict_squad_customized(strategy, input_meta_data, bert_config,
<del> eval_writer.filename, num_steps)
<del>
<del> output_prediction_file = os.path.join(FLAGS.model_dir, 'predictions.json')
<del> output_nbest_file = os.path.join(FLAGS.model_dir, 'nbest_predictions.json')
<del> output_null_log_odds_file = os.path.join(FLAGS.model_dir, 'null_odds.json')
<del>
<del> squad_lib.write_predictions(
<del> eval_examples,
<del> eval_features,
<del> all_results,
<del> FLAGS.n_best_size,
<del> FLAGS.max_answer_length,
<del> FLAGS.do_lower_case,
<del> output_prediction_file,
<del> output_nbest_file,
<del> output_null_log_odds_file,
<del> version_2_with_negative=version_2_with_negative,
<del> null_score_diff_threshold=FLAGS.null_score_diff_threshold,
<del> verbose=FLAGS.verbose_logging)
<add> bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<add> tokenizer = tokenization.FullTokenizer(
<add> vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
<add> run_squad_helper.predict_squad(strategy, input_meta_data, tokenizer,
<add> bert_config, squad_lib_wp)
<ide>
<ide>
<ide> def export_squad(model_export_path, input_meta_data):
<ide> def export_squad(model_export_path, input_meta_data):
<ide> Raises:
<ide> Export path is not specified, got an empty string or None.
<ide> """
<del> if not model_export_path:
<del> raise ValueError('Export path is not specified: %s' % model_export_path)
<del> bert_config = MODEL_CLASSES[FLAGS.model_type][0].from_json_file(
<del> FLAGS.bert_config_file)
<del> # Export uses float32 for now, even if training uses mixed precision.
<del> tf.keras.mixed_precision.experimental.set_policy('float32')
<del> squad_model, _ = bert_models.squad_model(bert_config,
<del> input_meta_data['max_seq_length'])
<del> model_saving_utils.export_bert_model(
<del> model_export_path, model=squad_model, checkpoint_dir=FLAGS.model_dir)
<add> bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)
<add> run_squad_helper.export_squad(model_export_path, input_meta_data, bert_config)
<ide>
<ide>
<ide> def main(_):
<ide><path>official/nlp/bert/run_squad_helper.py
<add># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Library for running BERT family models on SQuAD 1.1/2.0 in TF 2.x."""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import collections
<add>import os
<add>from absl import flags
<add>from absl import logging
<add>import tensorflow as tf
<add>
<add>from official.modeling import model_training_utils
<add>from official.nlp import optimization
<add>from official.nlp.bert import bert_models
<add>from official.nlp.bert import common_flags
<add>from official.nlp.bert import input_pipeline
<add>from official.nlp.bert import model_saving_utils
<add>from official.nlp.data import squad_lib_sp
<add>from official.utils.misc import keras_utils
<add>
<add>
<add>def define_common_squad_flags():
<add> """Defines common flags used by SQuAD tasks."""
<add> flags.DEFINE_enum(
<add> 'mode', 'train_and_predict',
<add> ['train_and_predict', 'train', 'predict', 'export_only'],
<add> 'One of {"train_and_predict", "train", "predict", "export_only"}. '
<add> '`train_and_predict`: both train and predict to a json file. '
<add> '`train`: only trains the model. '
<add> '`predict`: predict answers from the squad json file. '
<add> '`export_only`: will take the latest checkpoint inside '
<add> 'model_dir and export a `SavedModel`.')
<add> flags.DEFINE_string('train_data_path', '',
<add> 'Training data path with train tfrecords.')
<add> flags.DEFINE_string(
<add> 'input_meta_data_path', None,
<add> 'Path to file that contains meta data about input '
<add> 'to be used for training and evaluation.')
<add> # Model training specific flags.
<add> flags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.')
<add> # Predict processing related.
<add> flags.DEFINE_string('predict_file', None,
<add> 'Prediction data path with train tfrecords.')
<add> flags.DEFINE_bool(
<add> 'do_lower_case', True,
<add> 'Whether to lower case the input text. Should be True for uncased '
<add> 'models and False for cased models.')
<add> flags.DEFINE_float(
<add> 'null_score_diff_threshold', 0.0,
<add> 'If null_score - best_non_null is greater than the threshold, '
<add> 'predict null. This is only used for SQuAD v2.')
<add> flags.DEFINE_bool(
<add> 'verbose_logging', False,
<add> 'If true, all of the warnings related to data processing will be '
<add> 'printed. A number of warnings are expected for a normal SQuAD '
<add> 'evaluation.')
<add> flags.DEFINE_integer('predict_batch_size', 8,
<add> 'Total batch size for prediction.')
<add> flags.DEFINE_integer(
<add> 'n_best_size', 20,
<add> 'The total number of n-best predictions to generate in the '
<add> 'nbest_predictions.json output file.')
<add> flags.DEFINE_integer(
<add> 'max_answer_length', 30,
<add> 'The maximum length of an answer that can be generated. This is needed '
<add> 'because the start and end predictions are not conditioned on one '
<add> 'another.')
<add>
<add> common_flags.define_common_bert_flags()
<add>
<add>
<add>FLAGS = flags.FLAGS
<add>
<add>
<add>def squad_loss_fn(start_positions,
<add> end_positions,
<add> start_logits,
<add> end_logits,
<add> loss_factor=1.0):
<add> """Returns sparse categorical crossentropy for start/end logits."""
<add> start_loss = tf.keras.losses.sparse_categorical_crossentropy(
<add> start_positions, start_logits, from_logits=True)
<add> end_loss = tf.keras.losses.sparse_categorical_crossentropy(
<add> end_positions, end_logits, from_logits=True)
<add>
<add> total_loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2
<add> total_loss *= loss_factor
<add> return total_loss
<add>
<add>
<add>def get_loss_fn(loss_factor=1.0):
<add> """Gets a loss function for squad task."""
<add>
<add> def _loss_fn(labels, model_outputs):
<add> start_positions = labels['start_positions']
<add> end_positions = labels['end_positions']
<add> start_logits, end_logits = model_outputs
<add> return squad_loss_fn(
<add> start_positions,
<add> end_positions,
<add> start_logits,
<add> end_logits,
<add> loss_factor=loss_factor)
<add>
<add> return _loss_fn
<add>
<add>
<add>RawResult = collections.namedtuple('RawResult',
<add> ['unique_id', 'start_logits', 'end_logits'])
<add>
<add>
<add>def get_raw_results(predictions):
<add> """Converts multi-replica predictions to RawResult."""
<add> for unique_ids, start_logits, end_logits in zip(predictions['unique_ids'],
<add> predictions['start_logits'],
<add> predictions['end_logits']):
<add> for values in zip(unique_ids.numpy(), start_logits.numpy(),
<add> end_logits.numpy()):
<add> yield RawResult(
<add> unique_id=values[0],
<add> start_logits=values[1].tolist(),
<add> end_logits=values[2].tolist())
<add>
<add>
<add>def get_dataset_fn(input_file_pattern, max_seq_length, global_batch_size,
<add> is_training):
<add> """Gets a closure to create a dataset.."""
<add>
<add> def _dataset_fn(ctx=None):
<add> """Returns tf.data.Dataset for distributed BERT pretraining."""
<add> batch_size = ctx.get_per_replica_batch_size(
<add> global_batch_size) if ctx else global_batch_size
<add> dataset = input_pipeline.create_squad_dataset(
<add> input_file_pattern,
<add> max_seq_length,
<add> batch_size,
<add> is_training=is_training,
<add> input_pipeline_context=ctx)
<add> return dataset
<add>
<add> return _dataset_fn
<add>
<add>
<add>def predict_squad_customized(strategy, input_meta_data, bert_config,
<add> predict_tfrecord_path, num_steps):
<add> """Make predictions using a Bert-based squad model."""
<add> predict_dataset_fn = get_dataset_fn(
<add> predict_tfrecord_path,
<add> input_meta_data['max_seq_length'],
<add> FLAGS.predict_batch_size,
<add> is_training=False)
<add> predict_iterator = iter(
<add> strategy.experimental_distribute_datasets_from_function(
<add> predict_dataset_fn))
<add>
<add> with strategy.scope():
<add> # Prediction always uses float32, even if training uses mixed precision.
<add> tf.keras.mixed_precision.experimental.set_policy('float32')
<add> squad_model, _ = bert_models.squad_model(
<add> bert_config,
<add> input_meta_data['max_seq_length'],
<add> hub_module_url=FLAGS.hub_module_url)
<add>
<add> checkpoint_path = tf.train.latest_checkpoint(FLAGS.model_dir)
<add> logging.info('Restoring checkpoints from %s', checkpoint_path)
<add> checkpoint = tf.train.Checkpoint(model=squad_model)
<add> checkpoint.restore(checkpoint_path).expect_partial()
<add>
<add> @tf.function
<add> def predict_step(iterator):
<add> """Predicts on distributed devices."""
<add>
<add> def _replicated_step(inputs):
<add> """Replicated prediction calculation."""
<add> x, _ = inputs
<add> unique_ids = x.pop('unique_ids')
<add> start_logits, end_logits = squad_model(x, training=False)
<add> return dict(
<add> unique_ids=unique_ids,
<add> start_logits=start_logits,
<add> end_logits=end_logits)
<add>
<add> outputs = strategy.experimental_run_v2(
<add> _replicated_step, args=(next(iterator),))
<add> return tf.nest.map_structure(strategy.experimental_local_results, outputs)
<add>
<add> all_results = []
<add> for _ in range(num_steps):
<add> predictions = predict_step(predict_iterator)
<add> for result in get_raw_results(predictions):
<add> all_results.append(result)
<add> if len(all_results) % 100 == 0:
<add> logging.info('Made predictions for %d records.', len(all_results))
<add> return all_results
<add>
<add>
<add>def train_squad(strategy,
<add> input_meta_data,
<add> bert_config,
<add> custom_callbacks=None,
<add> run_eagerly=False):
<add> """Run bert squad training."""
<add> if strategy:
<add> logging.info('Training using customized training loop with distribution'
<add> ' strategy.')
<add> # Enables XLA in Session Config. Should not be set for TPU.
<add> keras_utils.set_config_v2(FLAGS.enable_xla)
<add>
<add> use_float16 = common_flags.use_float16()
<add> if use_float16:
<add> tf.keras.mixed_precision.experimental.set_policy('mixed_float16')
<add>
<add> epochs = FLAGS.num_train_epochs
<add> num_train_examples = input_meta_data['train_data_size']
<add> max_seq_length = input_meta_data['max_seq_length']
<add> steps_per_epoch = int(num_train_examples / FLAGS.train_batch_size)
<add> warmup_steps = int(epochs * num_train_examples * 0.1 / FLAGS.train_batch_size)
<add> train_input_fn = get_dataset_fn(
<add> FLAGS.train_data_path,
<add> max_seq_length,
<add> FLAGS.train_batch_size,
<add> is_training=True)
<add>
<add> def _get_squad_model():
<add> """Get Squad model and optimizer."""
<add> squad_model, core_model = bert_models.squad_model(
<add> bert_config,
<add> max_seq_length,
<add> hub_module_url=FLAGS.hub_module_url,
<add> hub_module_trainable=FLAGS.hub_module_trainable)
<add> squad_model.optimizer = optimization.create_optimizer(
<add> FLAGS.learning_rate, steps_per_epoch * epochs, warmup_steps)
<add> if use_float16:
<add> # Wraps optimizer with a LossScaleOptimizer. This is done automatically
<add> # in compile() with the "mixed_float16" policy, but since we do not call
<add> # compile(), we must wrap the optimizer manually.
<add> squad_model.optimizer = (
<add> tf.keras.mixed_precision.experimental.LossScaleOptimizer(
<add> squad_model.optimizer, loss_scale=common_flags.get_loss_scale()))
<add> if FLAGS.fp16_implementation == 'graph_rewrite':
<add> # Note: when flags_obj.fp16_implementation == "graph_rewrite", dtype as
<add> # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32'
<add> # which will ensure tf.compat.v2.keras.mixed_precision and
<add> # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double
<add> # up.
<add> squad_model.optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(
<add> squad_model.optimizer)
<add> return squad_model, core_model
<add>
<add> # The original BERT model does not scale the loss by
<add> # 1/num_replicas_in_sync. It could be an accident. So, in order to use
<add> # the same hyper parameter, we do the same thing here by keeping each
<add> # replica loss as it is.
<add> loss_fn = get_loss_fn(
<add> loss_factor=1.0 /
<add> strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0)
<add>
<add> model_training_utils.run_customized_training_loop(
<add> strategy=strategy,
<add> model_fn=_get_squad_model,
<add> loss_fn=loss_fn,
<add> model_dir=FLAGS.model_dir,
<add> steps_per_epoch=steps_per_epoch,
<add> steps_per_loop=FLAGS.steps_per_loop,
<add> epochs=epochs,
<add> train_input_fn=train_input_fn,
<add> init_checkpoint=FLAGS.init_checkpoint,
<add> run_eagerly=run_eagerly,
<add> custom_callbacks=custom_callbacks)
<add>
<add>
<add>def predict_squad(strategy, input_meta_data, tokenizer, bert_config, squad_lib):
<add> """Makes predictions for a squad dataset."""
<add> doc_stride = input_meta_data['doc_stride']
<add> max_query_length = input_meta_data['max_query_length']
<add> # Whether data should be in Ver 2.0 format.
<add> version_2_with_negative = input_meta_data.get('version_2_with_negative',
<add> False)
<add> eval_examples = squad_lib.read_squad_examples(
<add> input_file=FLAGS.predict_file,
<add> is_training=False,
<add> version_2_with_negative=version_2_with_negative)
<add>
<add> eval_writer = squad_lib.FeatureWriter(
<add> filename=os.path.join(FLAGS.model_dir, 'eval.tf_record'),
<add> is_training=False)
<add> eval_features = []
<add>
<add> def _append_feature(feature, is_padding):
<add> if not is_padding:
<add> eval_features.append(feature)
<add> eval_writer.process_feature(feature)
<add>
<add> # TPU requires a fixed batch size for all batches, therefore the number
<add> # of examples must be a multiple of the batch size, or else examples
<add> # will get dropped. So we pad with fake examples which are ignored
<add> # later on.
<add> kwargs = dict(
<add> examples=eval_examples,
<add> tokenizer=tokenizer,
<add> max_seq_length=input_meta_data['max_seq_length'],
<add> doc_stride=doc_stride,
<add> max_query_length=max_query_length,
<add> is_training=False,
<add> output_fn=_append_feature,
<add> batch_size=FLAGS.predict_batch_size)
<add>
<add> # squad_lib_sp requires one more argument 'do_lower_case'.
<add> if squad_lib == squad_lib_sp:
<add> kwargs['do_lower_case'] = FLAGS.do_lower_case
<add> dataset_size = squad_lib.convert_examples_to_features(**kwargs)
<add> eval_writer.close()
<add>
<add> logging.info('***** Running predictions *****')
<add> logging.info(' Num orig examples = %d', len(eval_examples))
<add> logging.info(' Num split examples = %d', len(eval_features))
<add> logging.info(' Batch size = %d', FLAGS.predict_batch_size)
<add>
<add> num_steps = int(dataset_size / FLAGS.predict_batch_size)
<add> all_results = predict_squad_customized(strategy, input_meta_data, bert_config,
<add> eval_writer.filename, num_steps)
<add>
<add> output_prediction_file = os.path.join(FLAGS.model_dir, 'predictions.json')
<add> output_nbest_file = os.path.join(FLAGS.model_dir, 'nbest_predictions.json')
<add> output_null_log_odds_file = os.path.join(FLAGS.model_dir, 'null_odds.json')
<add>
<add> squad_lib.write_predictions(
<add> eval_examples,
<add> eval_features,
<add> all_results,
<add> FLAGS.n_best_size,
<add> FLAGS.max_answer_length,
<add> FLAGS.do_lower_case,
<add> output_prediction_file,
<add> output_nbest_file,
<add> output_null_log_odds_file,
<add> version_2_with_negative=version_2_with_negative,
<add> null_score_diff_threshold=FLAGS.null_score_diff_threshold,
<add> verbose=FLAGS.verbose_logging)
<add>
<add>
<add>def export_squad(model_export_path, input_meta_data, bert_config):
<add> """Exports a trained model as a `SavedModel` for inference.
<add>
<add> Args:
<add> model_export_path: a string specifying the path to the SavedModel directory.
<add> input_meta_data: dictionary containing meta data about input and model.
<add> bert_config: Bert configuration file to define core bert layers.
<add>
<add> Raises:
<add> Export path is not specified, got an empty string or None.
<add> """
<add> if not model_export_path:
<add> raise ValueError('Export path is not specified: %s' % model_export_path)
<add> # Export uses float32 for now, even if training uses mixed precision.
<add> tf.keras.mixed_precision.experimental.set_policy('float32')
<add> squad_model, _ = bert_models.squad_model(bert_config,
<add> input_meta_data['max_seq_length'])
<add> model_saving_utils.export_bert_model(
<add> model_export_path, model=squad_model, checkpoint_dir=FLAGS.model_dir)
<ide><path>official/nlp/data/squad_lib.py
<ide> def _check_is_max_context(doc_spans, cur_span_index, position):
<ide> return cur_span_index == best_span_index
<ide>
<ide>
<del>RawResult = collections.namedtuple("RawResult",
<del> ["unique_id", "start_logits", "end_logits"])
<del>
<del>
<ide> def write_predictions(all_examples,
<ide> all_features,
<ide> all_results,
<ide><path>official/nlp/data/squad_lib_sp.py
<ide> def _check_is_max_context(doc_spans, cur_span_index, position):
<ide> return cur_span_index == best_span_index
<ide>
<ide>
<del>RawResult = collections.namedtuple("RawResult",
<del> ["unique_id", "start_logits", "end_logits"])
<del>
<del>
<ide> def write_predictions(all_examples,
<ide> all_features,
<ide> all_results, | 6 |
Text | Text | add blank lines on empty seeds | 65cc8006891080569196c2689534c5309172eb9c | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.md
<ide> assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.md
<ide> if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.md
<ide> if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(fun
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator.md
<ide> if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (fun
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md
<ide> if (typeof functionWithArgs !== "function") {
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.md
<ide> assert(timesFive(0) === 0);
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.md
<ide> if (typeof reusableFunction !== "function") {
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.md
<ide> assert(
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.md
<ide> assert(typeof new Dog().numLegs === 'number');
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/03-front-end-libraries/bootstrap/create-a-bootstrap-headline.md
<ide> assert.isTrue(/jquery(\s)+playground/gi.test($('h3').text()));
<ide> ## --seed-contents--
<ide>
<ide> ```html
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/create-a-complex-jsx-element.md
<ide> ReactDOM.render(JSX, document.getElementById('root'))
<ide> ## --seed-contents--
<ide>
<ide> ```jsx
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/metric-imperial-converter.md
<ide> getUserInput => {
<ide> You can `GET` `/api/convert` with a single parameter containing an accepted number and unit and have it converted. (Hint: Split the input by looking for the index of the first character which will mark the start of the unit)
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> You can convert `'gal'` to `'L'` and vice versa. (1 gal to 3.78541 L)
<ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/create-an-es6-javascript-map.md
<ide> assert(myMap.get('freeCodeCamp') === 'Awesome!');
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>
<ide> ```
<ide>
<ide> # --solutions-- | 13 |
Javascript | Javascript | replace non-ascii whitespace in source code | f3c5776b826169de26ff58e6616b99427d5b8db0 | <ide><path>test/unit/wrap.js
<ide> QUnit.module( "wrap", {
<ide> } );
<ide>
<ide> // See test/unit/manipulation.js for explanation about these 2 functions
<del>function manipulationBareObj( value ) {
<add>function manipulationBareObj( value ) {
<ide> return value;
<ide> }
<ide> | 1 |
Python | Python | add six as a requirement | e60680b12c30ad053f37488a398292b9cb2774aa | <ide><path>setup.py
<ide> url='https://github.com/fchollet/keras',
<ide> download_url='https://github.com/fchollet/keras/tarball/0.2.0',
<ide> license='MIT',
<del> install_requires=['theano', 'pyyaml'],
<add> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={
<ide> 'h5py': ['h5py'],
<ide> }, | 1 |
Ruby | Ruby | add warnings for permission exceptions | dca5dc817617717ff7843ac969f23d83b73d079f | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_cache_entries_to_double_dashes(initial_version)
<ide> target = HOMEBREW_CACHE/"#{prefix}--#{suffix}"
<ide>
<ide> if target.exist?
<del> FileUtils.rm_rf child
<add> begin
<add> FileUtils.rm_rf child
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{child}, please do so manually."
<add> end
<ide> else
<del> FileUtils.mv child, target, force: true
<add> begin
<add> FileUtils.mv child, target
<add> rescue Errno::EACCES
<add> opoo "Could not move #{child} to #{target}, please do so manually."
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | update doc with sample_weight and class_weight | e3d3d622189aa19d077ea2fec46bb9da67d85e9e | <ide><path>docs/sources/models.md
<ide> model = keras.models.Sequential()
<ide> - __batch_size__: int. Number of samples per gradient update.
<ide> - __nb_epoch__: int.
<ide> - __verbose__: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch.
<add> - __callbacks__: `keras.callbacks.Callback` list. List of callbacks to apply during training. See [callbacks](callbacks.md).
<ide> - __validation_split__: float (0. < x < 1). Fraction of the data to use as held-out validation data.
<ide> - __validation_data__: tuple (X, y) to be used as held-out validation data. Will override validation_split.
<ide> - __shuffle__: boolean. Whether to shuffle the samples at each epoch.
<ide> - __show_accuracy__: boolean. Whether to display class accuracy in the logs to stdout at each epoch.
<del> - __callbacks__: `keras.callbacks.Callback` list. List of callbacks to apply during training. See [callbacks](callbacks.md).
<add> - __class_weight__: dictionary mapping classes to a weight value, used for scaling the loss function (during training only).
<add> - __sample_weight__: list or numpy array with 1:1 mapping to the training samples, used for scaling the loss function (during training only).
<ide> - __evaluate__(X, y, batch_size=128, show_accuracy=False, verbose=1): Show performance of the model over some validation data.
<ide> - __Return__: The loss score over the data.
<ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). | 1 |
Go | Go | add scheme to fluentd-address | cb176c848e0731f77fa48b4e1a90ae74d1f2deae | <ide><path>daemon/logger/fluentd/fluentd.go
<ide> import (
<ide> "fmt"
<ide> "math"
<ide> "net"
<add> "net/url"
<ide> "strconv"
<ide> "strings"
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/loggerutils"
<add> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/docker/go-units"
<ide> "github.com/fluent/fluent-logger-golang/fluent"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> type fluentd struct {
<ide> type fluentd struct {
<ide> extra map[string]string
<ide> }
<ide>
<add>type location struct {
<add> protocol string
<add> host string
<add> port int
<add> path string
<add>}
<add>
<ide> const (
<ide> name = "fluentd"
<ide>
<add> defaultProtocol = "tcp"
<ide> defaultHost = "127.0.0.1"
<ide> defaultPort = 24224
<ide> defaultBufferLimit = 1024 * 1024
<ide> func init() {
<ide> // the context. The supported context configuration variable is
<ide> // fluentd-address.
<ide> func New(ctx logger.Context) (logger.Logger, error) {
<del> host, port, err := parseAddress(ctx.Config[addressKey])
<add> loc, err := parseAddress(ctx.Config[addressKey])
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func New(ctx logger.Context) (logger.Logger, error) {
<ide> }
<ide>
<ide> fluentConfig := fluent.Config{
<del> FluentPort: port,
<del> FluentHost: host,
<del> BufferLimit: bufferLimit,
<del> RetryWait: retryWait,
<del> MaxRetry: maxRetries,
<del> AsyncConnect: asyncConnect,
<add> FluentPort: loc.port,
<add> FluentHost: loc.host,
<add> FluentNetwork: loc.protocol,
<add> FluentSocketPath: loc.path,
<add> BufferLimit: bufferLimit,
<add> RetryWait: retryWait,
<add> MaxRetry: maxRetries,
<add> AsyncConnect: asyncConnect,
<ide> }
<ide>
<ide> logrus.WithField("container", ctx.ContainerID).WithField("config", fluentConfig).
<ide> func ValidateLogOpt(cfg map[string]string) error {
<ide> }
<ide> }
<ide>
<del> if _, _, err := parseAddress(cfg["fluentd-address"]); err != nil {
<add> if _, err := parseAddress(cfg["fluentd-address"]); err != nil {
<ide> return err
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<del>func parseAddress(address string) (string, int, error) {
<add>func parseAddress(address string) (*location, error) {
<ide> if address == "" {
<del> return defaultHost, defaultPort, nil
<add> return &location{
<add> protocol: defaultProtocol,
<add> host: defaultHost,
<add> port: defaultPort,
<add> path: "",
<add> }, nil
<add> }
<add>
<add> protocol := defaultProtocol
<add> givenAddress := address
<add> if urlutil.IsTransportURL(address) {
<add> url, err := url.Parse(address)
<add> if err != nil {
<add> return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
<add> }
<add> // unix and unixgram socket
<add> if url.Scheme == "unix" || url.Scheme == "unixgram" {
<add> return &location{
<add> protocol: url.Scheme,
<add> host: "",
<add> port: 0,
<add> path: url.Path,
<add> }, nil
<add> }
<add> // tcp|udp
<add> protocol = url.Scheme
<add> address = url.Host
<ide> }
<ide>
<ide> host, port, err := net.SplitHostPort(address)
<ide> if err != nil {
<ide> if !strings.Contains(err.Error(), "missing port in address") {
<del> return "", 0, fmt.Errorf("invalid fluentd-address %s: %s", address, err)
<add> return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
<ide> }
<del> return host, defaultPort, nil
<add> return &location{
<add> protocol: protocol,
<add> host: host,
<add> port: defaultPort,
<add> path: "",
<add> }, nil
<ide> }
<ide>
<ide> portnum, err := strconv.Atoi(port)
<ide> if err != nil {
<del> return "", 0, fmt.Errorf("invalid fluentd-address %s: %s", address, err)
<add> return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
<ide> }
<del> return host, portnum, nil
<add> return &location{
<add> protocol: protocol,
<add> host: host,
<add> port: portnum,
<add> path: "",
<add> }, nil
<ide> } | 1 |
Python | Python | perform model validation on worker init. closes | 32558fba578171b0eeaf9fbee1060fa104f31c23 | <ide><path>celery/fixups/django.py
<ide> from __future__ import absolute_import
<ide>
<add>import io
<ide> import os
<ide> import sys
<ide> import warnings
<ide> def __init__(self, app):
<ide> _oracle_database_errors
<ide> )
<ide>
<add> def validate_models(self):
<add> from django.core.management.validation import get_validation_errors
<add> s = io.StringIO()
<add> num_errors = get_validation_errors(s, None)
<add> if num_errors:
<add> raise RuntimeError(
<add> 'One or more Django models did not validate:\n{0}'.format(
<add> s.getvalue()))
<add>
<ide> def install(self):
<ide> signals.beat_embedded_init.connect(self.close_database)
<ide> signals.worker_ready.connect(self.on_worker_ready)
<ide> signals.task_prerun.connect(self.on_task_prerun)
<ide> signals.task_postrun.connect(self.on_task_postrun)
<ide> signals.worker_process_init.connect(self.on_worker_process_init)
<add> self.validate_models()
<ide> self.close_database()
<ide> self.close_cache()
<ide> return self | 1 |
PHP | PHP | remove deprecated parameters and update tests | 45fe7eb709692024cd7b134392adda06e7746190 | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _domId($value) {
<ide> * In addition to controller fields output, `$fields` can be used to control legend
<ide> * and fieldset rendering.
<ide> * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
<del> * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
<del> * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
<ide> *
<ide> * @param array $fields An array of fields to generate inputs for, or null.
<ide> * @param array $blacklist A simple array of fields to not create inputs for.
<ide> public function inputs($fields = null, $blacklist = null, $options = array()) {
<ide>
<ide> $modelFields = $context->fieldNames();
<ide>
<del> if (is_array($fields)) {
<del> if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
<del> $legend = $fields['legend'];
<del> unset($fields['legend']);
<del> }
<del>
<del> if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
<del> $fieldset = $fields['fieldset'];
<del> unset($fields['fieldset']);
<del> }
<del> } elseif ($fields !== null) {
<add> if (is_string($fields)) {
<add> $legend = $fields;
<add> $fields = [];
<add> } elseif (is_bool($fields)) {
<ide> $fieldset = $legend = $fields;
<del> if (!is_bool($fieldset)) {
<del> $fieldset = true;
<del> }
<del> $fields = array();
<add> $fields = [];
<ide> }
<ide>
<ide> if (empty($fields)) {
<ide> public function inputs($fields = null, $blacklist = null, $options = array()) {
<ide> foreach ($fields as $name => $options) {
<ide> if (is_numeric($name) && !is_array($options)) {
<ide> $name = $options;
<del> $options = array();
<add> $options = [];
<ide> }
<ide> $entity = explode('.', $name);
<ide> $blacklisted = (
<ide> public function inputs($fields = null, $blacklist = null, $options = array()) {
<ide> if ($blacklisted) {
<ide> continue;
<ide> }
<del> $out .= $this->input($name, $options);
<add> $out .= $this->input($name, (array)$options);
<ide> }
<ide>
<ide> if ($fieldset) {
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormInputsLegendFieldset() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $result = $this->Form->inputs(array('legend' => 'Field of Dreams', 'fieldset' => true));
<del> $expected = array(
<del> '<fieldset',
<del> '<legend',
<del> 'Field of Dreams',
<del> '/legend',
<del> '*/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<ide> $result = $this->Form->inputs(null, null, array('legend' => 'Field of Dreams', 'fieldset' => true));
<del> $this->assertTags($result, $expected);
<add> $this->assertContains('<legend>Field of Dreams</legend>', $result);
<add> $this->assertContains('<fieldset>', $result);
<ide>
<ide> $result = $this->Form->inputs('Field of Dreams', null, array('fieldset' => true));
<del> $this->assertTags($result, $expected);
<add> $this->assertContains('<legend>Field of Dreams</legend>', $result);
<add> $this->assertContains('<fieldset>', $result);
<add>
<add> $result = $this->Form->inputs(null, null, array('fieldset' => false, 'legend' => false));
<add> $this->assertNotContains('<legend>', $result);
<add> $this->assertNotContains('<fieldset>', $result);
<add>
<add> $result = $this->Form->inputs(null, null, array('fieldset' => false, 'legend' => 'Hello'));
<add> $this->assertNotContains('<legend>', $result);
<add> $this->assertNotContains('<fieldset>', $result);
<ide>
<ide> $this->Form->create($this->article);
<ide> $this->Form->request->params['prefix'] = 'admin';
<ide> public function testFormInputs() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $this->Form->create($this->article);
<del> $result = $this->Form->inputs(['id', 'title', 'body'], null, array('fieldset' => false, 'legend' => false));
<del> $expected = array(
<del> 'input' => array('type' => 'hidden', 'name' => 'id', 'id' => 'id'),
<del> array('div' => array('class' => 'input text required')),
<del> '*/div',
<del> array('div' => array('class' => 'input text')),
<del> '*/div',
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $this->Form->create($this->article);
<del> $result = $this->Form->inputs(array('fieldset' => true, 'legend' => false));
<del> $expected = array(
<del> 'fieldset' => array(),
<del> 'input' => array('type' => 'hidden', 'name' => 'id', 'id' => 'id'),
<del> array('div' => array('class' => 'input select required')),
<del> '*/div',
<del> array('div' => array('class' => 'input text required')),
<del> '*/div',
<del> array('div' => array('class' => 'input text')),
<del> '*/div',
<del> array('div' => array('class' => 'input text')),
<del> '*/div',
<del> '/fieldset'
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $this->Form->create($this->article);
<del> $result = $this->Form->inputs(array('fieldset' => false, 'legend' => 'Hello'));
<del> $expected = array(
<del> 'input' => array('type' => 'hidden', 'name' => 'id', 'id' => 'id'),
<del> array('div' => array('class' => 'input select required')),
<del> '*/div',
<del> array('div' => array('class' => 'input text required')),
<del> '*/div',
<del> array('div' => array('class' => 'input text')),
<del> '*/div',
<del> array('div' => array('class' => 'input text')),
<del> '*/div',
<del> );
<del> $this->assertTags($result, $expected);
<del>
<del> $this->Form->create($this->article);
<del> $result = $this->Form->inputs(null, null, array('fieldset' => false, 'legend' => 'Hello'));
<del> $this->assertTags($result, $expected);
<del>
<ide> $this->Form->create($this->article);
<ide> $result = $this->Form->inputs('Hello');
<ide> $expected = array(
<ide> public function testFormInputs() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> $result = $this->Form->inputs(array('legend' => 'Hello'));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->inputs(null, null, array('legend' => 'Hello'));
<del> $this->assertTags($result, $expected);
<del>
<ide> $this->Form->create(false);
<ide> $expected = array(
<ide> 'fieldset' => array(), | 2 |
Javascript | Javascript | convert the annotation layer builder to es6 syntax | 3554a93c2b1d2abd4e63540641a67b7c213afe98 | <ide><path>web/annotation_layer_builder.js
<ide> import { SimpleLinkService } from './pdf_link_service';
<ide> * @property {DownloadManager} downloadManager
<ide> */
<ide>
<del>/**
<del> * @class
<del> */
<del>var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
<add>class AnnotationLayerBuilder {
<ide> /**
<ide> * @param {AnnotationLayerBuilderOptions} options
<del> * @constructs AnnotationLayerBuilder
<ide> */
<del> function AnnotationLayerBuilder(options) {
<add> constructor(options) {
<ide> this.pageDiv = options.pageDiv;
<ide> this.pdfPage = options.pdfPage;
<ide> this.renderInteractiveForms = options.renderInteractiveForms;
<ide> var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
<ide> this.div = null;
<ide> }
<ide>
<del> AnnotationLayerBuilder.prototype =
<del> /** @lends AnnotationLayerBuilder.prototype */ {
<del>
<del> /**
<del> * @param {PageViewport} viewport
<del> * @param {string} intent (default value is 'display')
<del> */
<del> render: function AnnotationLayerBuilder_render(viewport, intent) {
<del> var self = this;
<add> /**
<add> * @param {PageViewport} viewport
<add> * @param {string} intent (default value is 'display')
<add> */
<add> render(viewport, intent = 'display') {
<add> this.pdfPage.getAnnotations({ intent }).then((annotations) => {
<ide> var parameters = {
<del> intent: (intent === undefined ? 'display' : intent),
<add> viewport: viewport.clone({ dontFlip: true }),
<add> div: this.div,
<add> annotations,
<add> page: this.pdfPage,
<add> renderInteractiveForms: this.renderInteractiveForms,
<add> linkService: this.linkService,
<add> downloadManager: this.downloadManager,
<ide> };
<ide>
<del> this.pdfPage.getAnnotations(parameters).then(function (annotations) {
<del> viewport = viewport.clone({ dontFlip: true });
<del> parameters = {
<del> viewport: viewport,
<del> div: self.div,
<del> annotations: annotations,
<del> page: self.pdfPage,
<del> renderInteractiveForms: self.renderInteractiveForms,
<del> linkService: self.linkService,
<del> downloadManager: self.downloadManager,
<del> };
<del>
<del> if (self.div) {
<del> // If an annotationLayer already exists, refresh its children's
<del> // transformation matrices.
<del> AnnotationLayer.update(parameters);
<del> } else {
<del> // Create an annotation layer div and render the annotations
<del> // if there is at least one annotation.
<del> if (annotations.length === 0) {
<del> return;
<del> }
<add> if (this.div) {
<add> // If an annotationLayer already exists, refresh its children's
<add> // transformation matrices.
<add> AnnotationLayer.update(parameters);
<add> } else {
<add> // Create an annotation layer div and render the annotations
<add> // if there is at least one annotation.
<add> if (annotations.length === 0) {
<add> return;
<add> }
<ide>
<del> self.div = document.createElement('div');
<del> self.div.className = 'annotationLayer';
<del> self.pageDiv.appendChild(self.div);
<del> parameters.div = self.div;
<add> this.div = document.createElement('div');
<add> this.div.className = 'annotationLayer';
<add> this.pageDiv.appendChild(this.div);
<add> parameters.div = this.div;
<ide>
<del> AnnotationLayer.render(parameters);
<del> if (typeof mozL10n !== 'undefined') {
<del> mozL10n.translate(self.div);
<del> }
<add> AnnotationLayer.render(parameters);
<add> if (typeof mozL10n !== 'undefined') {
<add> mozL10n.translate(this.div);
<ide> }
<del> });
<del> },
<del>
<del> hide: function AnnotationLayerBuilder_hide() {
<del> if (!this.div) {
<del> return;
<ide> }
<del> this.div.setAttribute('hidden', 'true');
<del> }
<del> };
<add> });
<add> }
<ide>
<del> return AnnotationLayerBuilder;
<del>})();
<add> hide() {
<add> if (!this.div) {
<add> return;
<add> }
<add> this.div.setAttribute('hidden', 'true');
<add> }
<add>}
<ide>
<ide> /**
<del> * @constructor
<ide> * @implements IPDFAnnotationLayerFactory
<ide> */
<del>function DefaultAnnotationLayerFactory() {}
<del>DefaultAnnotationLayerFactory.prototype = {
<add>class DefaultAnnotationLayerFactory {
<ide> /**
<ide> * @param {HTMLDivElement} pageDiv
<ide> * @param {PDFPage} pdfPage
<ide> * @param {boolean} renderInteractiveForms
<ide> * @returns {AnnotationLayerBuilder}
<ide> */
<del> createAnnotationLayerBuilder: function (pageDiv, pdfPage,
<del> renderInteractiveForms) {
<add> createAnnotationLayerBuilder(pageDiv, pdfPage,
<add> renderInteractiveForms = false) {
<ide> return new AnnotationLayerBuilder({
<del> pageDiv: pageDiv,
<del> pdfPage: pdfPage,
<del> renderInteractiveForms: renderInteractiveForms,
<add> pageDiv,
<add> pdfPage,
<add> renderInteractiveForms,
<ide> linkService: new SimpleLinkService(),
<ide> });
<ide> }
<del>};
<add>}
<ide>
<ide> export {
<ide> AnnotationLayerBuilder,
<ide><path>web/interfaces.js
<ide> IPDFTextLayerFactory.prototype = {
<ide> /**
<ide> * @interface
<ide> */
<del>function IPDFAnnotationLayerFactory() {}
<del>IPDFAnnotationLayerFactory.prototype = {
<add>class IPDFAnnotationLayerFactory { // eslint-disable-line no-unused-vars
<ide> /**
<ide> * @param {HTMLDivElement} pageDiv
<ide> * @param {PDFPage} pdfPage
<ide> * @param {boolean} renderInteractiveForms
<ide> * @returns {AnnotationLayerBuilder}
<ide> */
<del> createAnnotationLayerBuilder: function (pageDiv, pdfPage,
<del> renderInteractiveForms) {}
<del>};
<add> createAnnotationLayerBuilder(pageDiv, pdfPage,
<add> renderInteractiveForms = false) {}
<add>} | 2 |
Java | Java | fix checkstyle warning | bad87be30630b9a3283e092ea70b5579a8c6a9ad | <ide><path>spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java
<ide> public void handleError(ClientHttpResponse response) throws IOException {
<ide> }
<ide>
<ide> /**
<del> * Return error message with details from the response body:
<add> * Return error message with details from the response body. For example:
<ide> * <pre>
<ide> * 404 Not Found: [{'id': 123, 'message': 'my message'}]
<ide> * </pre> | 1 |
Text | Text | add a changelog entry for [ci skip] | 5ece2e4a4459065b5efd976aebd209bbf0cab89b | <ide><path>activerecord/CHANGELOG.md
<ide>
<ide> *DHH*
<ide>
<add>* Add `Relation#pick` as short-hand for single-value plucks.
<add>
<add> *DHH*
<add>
<ide>
<ide> Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/activerecord/CHANGELOG.md) for previous changes. | 1 |
Javascript | Javascript | fix typo in code comment | c4d8ef643002a2b181029ffed22abd451fb326df | <ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> function makeSimulator(eventType) {
<ide>
<ide> ReactDOM.unstable_batchedUpdates(function() {
<ide> // Normally extractEvent enqueues a state restore, but we'll just always
<del> // do that since we we're by-passing it here.
<add> // do that since we're by-passing it here.
<ide> enqueueStateRestore(domNode);
<ide> runEventsInBatch(event);
<ide> }); | 1 |
Python | Python | run openai example running | 777459b471f4b6b97b633a4ca6de21d5dce96202 | <ide><path>examples/run_openai_gpt.py
<ide> def load_rocstories_dataset(dataset_path):
<ide> output.append((' '.join(line[1:5]), line[5], line[6], int(line[-1])-1))
<ide> return output
<ide>
<del>def pre_process_datasets(encoded_datasets, max_len, start_token, delimiter_token, clf_token):
<del> """ Pre-process datasets containing lists of
<del> tuples(story, 1st continuation, 2nd continuation, label)
<del>
<del> In Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:
<del> input_ids[batch, alternative, :] = [start_token] + story[:max_len] + [delimiter_token] + cont1[:max_len] + [clf_token]
<add>def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token):
<add> """ Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)
<add>
<add> To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:
<add> input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]
<ide> """
<ide> tensor_datasets = []
<ide> for dataset in encoded_datasets:
<ide> n_batch = len(dataset)
<del> input_ids = np.zeros((n_batch, 2, max_len), dtype=np.int32)
<del> mc_token_mask = np.zeros((n_batch, 2, max_len), dtype=np.int32)
<del> lm_labels = np.full((n_batch, 2, max_len), -1, dtype=np.float32)
<del> mc_labels = np.zeros((n_batch,), dtype=np.float32)
<add> input_ids = np.zeros((n_batch, 2, input_len), dtype=np.int64)
<add> mc_token_mask = np.zeros((n_batch, 2, input_len), dtype=np.int64)
<add> lm_labels = np.full((n_batch, 2, input_len), -1, dtype=np.int64)
<add> mc_labels = np.zeros((n_batch,), dtype=np.int64)
<ide> for i, (story, cont1, cont2, mc_label), in enumerate(dataset):
<del> with_cont1 = [start_token] + story[:max_len] + [delimiter_token] + cont1[:max_len] + [clf_token]
<del> with_cont2 = [start_token] + story[:max_len] + [delimiter_token] + cont2[:max_len] + [clf_token]
<add> with_cont1 = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]
<add> with_cont2 = [start_token] + story[:cap_length] + [delimiter_token] + cont2[:cap_length] + [clf_token]
<ide> input_ids[i, 0, :len(with_cont1)] = with_cont1
<ide> input_ids[i, 1, :len(with_cont2)] = with_cont2
<ide> mc_token_mask[i, 0, len(with_cont1) - 1] = 1
<ide> lm_labels[i, 0, :len(with_cont1)-1] = with_cont1[1:]
<ide> lm_labels[i, 1, :len(with_cont2)-1] = with_cont2[1:]
<ide> mc_labels[i] = mc_label
<del> all_inputs = tuple(input_ids, mc_token_mask, lm_labels, mc_labels)
<add> all_inputs = (input_ids, mc_token_mask, lm_labels, mc_labels)
<ide> tensor_datasets.append(tuple(torch.tensor(t) for t in all_inputs))
<ide> return tensor_datasets
<ide>
<ide> def main():
<ide> parser = argparse.ArgumentParser()
<ide> parser.add_argument('--model_name', type=str, default='openai-gpt',
<ide> help='pretrained model name')
<add> parser.add_argument("--do_train", action='store_true', help="Whether to run training.")
<add> parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.")
<add> parser.add_argument("--output_dir", default=None, type=str, required=True,
<add> help="The output directory where the model predictions and checkpoints will be written.")
<ide> parser.add_argument('--train_dataset', type=str, default='cloze_test_val__spring2016 - cloze_test_ALL_val.tsv')
<ide> parser.add_argument('--eval_dataset', type=str, default='test_spring2016.tsv')
<ide> parser.add_argument('--seed', type=int, default=42)
<ide> def main():
<ide> parser.add_argument('--max_grad_norm', type=int, default=1)
<ide> parser.add_argument('--learning_rate', type=float, default=6.25e-5)
<ide> parser.add_argument('--warmup_proportion', type=float, default=0.002)
<del> parser.add_argument('--max_grad_norm', type=float, default=1)
<ide> parser.add_argument('--lr_schedule', type=str, default='warmup_linear')
<ide> parser.add_argument('--weight_decay', type=float, default=0.01)
<ide> parser.add_argument('--lm_coef', type=float, default=0.5)
<ide> def main():
<ide> n_gpu = torch.cuda.device_count()
<ide> logger.info("device: {}, n_gpu {}".format(device, n_gpu))
<ide>
<add> if not args.do_train and not args.do_eval:
<add> raise ValueError("At least one of `do_train` or `do_eval` must be True.")
<add>
<add> if not os.path.exists(args.output_dir):
<add> os.makedirs(args.output_dir)
<add>
<ide> # Load tokenizer and model
<ide> # This loading functions also add new tokens and embeddings called `special tokens`
<ide> # These new embeddings will be fine-tuned on the RocStories dataset
<ide> def main():
<ide> model = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name, num_special_tokens=len(special_tokens))
<ide>
<ide> # Load and encode the datasets
<add> def tokenize_and_encode(obj):
<add> """ Tokenize and encode a nested object """
<add> if isinstance(obj, str):
<add> return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj))
<add> elif isinstance(obj, int):
<add> return obj
<add> return list(tokenize_and_encode(o) for o in obj)
<add>
<ide> logger.info("Encoding dataset...")
<ide> train_dataset = load_rocstories_dataset(args.train_dataset)
<del> eval_datset = load_rocstories_dataset(args.eval_datset)
<del> datasets = (train_dataset, eval_datset)
<del> tokenized_datasets = tuple(list(list(tokenizer.tokenize(x) for x in instance)
<del> for instance in dataset) for dataset in datasets)
<del> encoded_datasets = tuple(list(list(tokenizer.convert_tokens_to_ids(x) for x in instance)
<del> for instance in dataset) for dataset in tokenized_datasets)
<add> eval_dataset = load_rocstories_dataset(args.eval_dataset)
<add> datasets = (train_dataset, eval_dataset)
<add> encoded_datasets = tokenize_and_encode(datasets)
<ide>
<ide> # Compute the mex input length for the Transformer
<del> max_input_length = max(len(story) + max(len(cont1), len(cont2)) + 3 \
<add> input_length = max(len(story) + max(len(cont1), len(cont2)) + 3 \
<ide> for dataset in encoded_datasets for story, cont1, cont2, _ in dataset)
<del> max_input_length = min(max_input_length, model.config.n_positions) # Max size of input for the pre-trained model
<del> max_sub_part_length = max_input_length // 2 - 2
<add> input_length = min(input_length, model.config.n_positions) # Max size of input for the pre-trained model
<add> max_sub_part_length = input_length // 2 - 2
<ide>
<ide> # Prepare inputs tensors and dataloaders
<del> tensor_datasets = pre_process_datasets(encoded_datasets, max_sub_part_length, *special_tokens_ids)
<add> tensor_datasets = pre_process_datasets(encoded_datasets, input_length, max_sub_part_length, *special_tokens_ids)
<ide> train_tensor_dataset, eval_tensor_dataset = tensor_datasets[0], tensor_datasets[1]
<ide>
<ide> train_data = TensorDataset(*train_tensor_dataset)
<ide><path>pytorch_pretrained_bert/modeling_openai.py
<ide> logger = logging.getLogger(__name__)
<ide>
<ide> PRETRAINED_MODEL_ARCHIVE_MAP = {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-pytorch_model.bin"}
<del>PRETRAINED_CONFIG_ARCHIVE_MAP = {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-openai_gpt_config.json"}
<add>PRETRAINED_CONFIG_ARCHIVE_MAP = {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-config.json"}
<ide>
<del>CONFIG_NAME = "openai_gpt_config.json"
<add>CONFIG_NAME = "config.json"
<ide> WEIGHTS_NAME = "pytorch_model.bin"
<ide>
<ide> def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path):
<ide> def from_pretrained(
<ide> archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]
<ide> config_file = PRETRAINED_CONFIG_ARCHIVE_MAP[pretrained_model_name_or_path]
<ide> else:
<del> archive_file = pretrained_model_name_or_path
<add> archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)
<ide> config_file = os.path.join(pretrained_model_name_or_path, CONFIG_NAME)
<ide> # redirect to the cache, if necessary
<ide> try:
<ide><path>pytorch_pretrained_bert/modeling_transfo_xl.py
<ide> 'transfo-xl-wt103': "https://s3.amazonaws.com/models.huggingface.co/bert/transfo-xl-wt103-pytorch_model.bin",
<ide> }
<ide> PRETRAINED_CONFIG_ARCHIVE_MAP = {
<del> 'transfo-xl-wt103': "https://s3.amazonaws.com/models.huggingface.co/bert/transfo-xl-wt103-transfo_xl_config.json",
<add> 'transfo-xl-wt103': "https://s3.amazonaws.com/models.huggingface.co/bert/transfo-xl-wt103-config.json",
<ide> }
<del>CONFIG_NAME = 'transfo_xl_config.json'
<add>CONFIG_NAME = 'config.json'
<ide> WEIGHTS_NAME = 'pytorch_model.bin'
<ide> TF_WEIGHTS_NAME = 'model.ckpt'
<ide> | 3 |
Python | Python | add missing init of schema_fields var | 8d5ffef5990c8ae5780fa84c1a1f083fe925537c | <ide><path>airflow/contrib/operators/gcs_to_bq.py
<ide> def execute(self, context):
<ide> elif self.schema_object is None and self.autodetect is False:
<ide> raise ValueError('At least one of `schema_fields`, `schema_object`, '
<ide> 'or `autodetect` must be passed.')
<add> else:
<add> schema_fields = None
<ide>
<ide> else:
<ide> schema_fields = self.schema_fields | 1 |
PHP | PHP | use push method | 8dc112f61d2e90a0d83d0367bc11b1e4306d0f02 | <ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function pop($queue = null)
<ide> public function bulk($jobs, $data = '', $queue = null)
<ide> {
<ide> foreach ($this->jobs as $job) {
<del> $this->jobs[get_class($job)][] = [
<del> 'job' => $job,
<del> 'queue' => $queue,
<del> ];
<add> $this->push($job);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | remove the habtm preloader | a03ea3ff97b43340d0904525083bf8bc7a1c6ebc | <ide><path>activerecord/lib/active_record/associations/preloader.rb
<ide> class Preloader #:nodoc:
<ide> autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
<ide> autoload :HasOne, 'active_record/associations/preloader/has_one'
<ide> autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
<del> autoload :HasAndBelongsToMany, 'active_record/associations/preloader/has_and_belongs_to_many'
<ide> autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
<ide> end
<ide>
<ide> def preloader_for(reflection, owners, rhs_klass)
<ide> reflection.options[:through] ? HasManyThrough : HasMany
<ide> when :has_one
<ide> reflection.options[:through] ? HasOneThrough : HasOne
<del> when :has_and_belongs_to_many
<del> HasAndBelongsToMany
<ide> when :belongs_to
<ide> BelongsTo
<ide> end
<ide><path>activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
<del>module ActiveRecord
<del> module Associations
<del> class Preloader
<del> class HasAndBelongsToMany < CollectionAssociation #:nodoc:
<del> attr_reader :join_table
<del>
<del> def initialize(klass, records, reflection, preload_options)
<del> super
<del> @join_table = Arel::Table.new(reflection.join_table).alias('t0')
<del> end
<del>
<del> # Unlike the other associations, we want to get a raw array of rows so that we can
<del> # access the aliased column on the join table
<del> def records_for(ids)
<del> scope = query_scope ids
<del> klass.connection.select_all(scope.arel, 'SQL', scope.bind_values)
<del> end
<del>
<del> def owner_key_name
<del> reflection.active_record_primary_key
<del> end
<del>
<del> def association_key_name
<del> 'ar_association_key_name'
<del> end
<del>
<del> def association_key
<del> join_table[reflection.foreign_key]
<del> end
<del>
<del> private
<del>
<del> # Once we have used the join table column (in super), we manually instantiate the
<del> # actual records, ensuring that we don't create more than one instances of the same
<del> # record
<del> def load_slices(slices)
<del> identity_map = {}
<del> caster = nil
<del> name = association_key_name
<del>
<del> records_to_keys = slices.flat_map { |slice|
<del> records = records_for(slice)
<del> caster ||= records.column_types.fetch(name, records.identity_type)
<del> records.map! { |row|
<del> record = identity_map[row[klass.primary_key]] ||= klass.instantiate(row)
<del> [record, caster.type_cast(row[name])]
<del> }
<del> }
<del> @preloaded_records = records_to_keys.map(&:first)
<del>
<del> records_to_keys
<del> end
<del>
<del> def build_scope
<del> super.joins(join).select(join_select)
<del> end
<del>
<del> def join_select
<del> association_key.as(Arel.sql(association_key_name))
<del> end
<del>
<del> def join
<del> condition = table[reflection.association_primary_key].eq(
<del> join_table[reflection.association_foreign_key])
<del>
<del> table.create_join(join_table, table.create_on(condition))
<del> end
<del> end
<del> end
<del> end
<del>end | 2 |
Javascript | Javascript | remove 3rd argument from assert.strictequal | 28b622cb08602d77512fa3d659451cd317dfcc41 | <ide><path>test/parallel/test-http-res-write-after-end.js
<ide> const server = http.Server(common.mustCall(function(req, res) {
<ide> res.end();
<ide>
<ide> const r = res.write('This should raise an error.');
<del> assert.strictEqual(r, true, 'write after end should return true');
<add> // write after end should return true
<add> assert.strictEqual(r, true);
<ide> }));
<ide>
<ide> server.listen(0, function() { | 1 |
Ruby | Ruby | remove stale methods constructing joins | 394c05ed82c1fbfc1c5d27f223b49975f439729c | <ide><path>activerecord/lib/active_record/base.rb
<ide> def construct_finder_arel(options = {}, scope = nil)
<ide> relation
<ide> end
<ide>
<del> def construct_join(joins)
<del> case joins
<del> when Symbol, Hash, Array
<del> if array_of_strings?(joins)
<del> joins.join(' ') + " "
<del> else
<del> build_association_joins(joins)
<del> end
<del> when String
<del> " #{joins} "
<del> else
<del> ""
<del> end
<del> end
<del>
<del> def build_association_joins(joins)
<del> join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, joins, nil)
<del> relation = unscoped.table
<del> join_dependency.join_associations.map { |association|
<del> if (association_relation = association.relation).is_a?(Array)
<del> [Arel::InnerJoin.new(relation, association_relation.first, *association.association_join.first).joins(relation),
<del> Arel::InnerJoin.new(relation, association_relation.last, *association.association_join.last).joins(relation)].join()
<del> else
<del> Arel::InnerJoin.new(relation, association_relation, *association.association_join).joins(relation)
<del> end
<del> }.join(" ")
<del> end
<del>
<ide> def array_of_strings?(o)
<ide> o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
<ide> end | 1 |
Python | Python | use future builtins | 43fb28f769446c02f6cb4cbf5652080e05dff34c | <ide><path>celery/__compat__.py
<ide> import sys
<ide>
<ide> from functools import reduce
<add>from future_builtins import map
<ide> from importlib import import_module
<ide> from types import ModuleType
<ide>
<ide><path>celery/__init__.py
<ide>
<ide> from __future__ import absolute_import
<ide>
<add>from future_builtins import map
<add>
<ide> SERIES = 'DEVEL'
<ide> VERSION = (3, 1, 0, 'a1')
<ide> __version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
<ide><path>celery/app/annotations.py
<ide> """
<ide> from __future__ import absolute_import
<ide>
<add>from future_builtins import filter
<add>
<ide> from celery.utils.functional import firstmethod, mpromise
<ide> from celery.utils.imports import instantiate
<ide>
<ide> def expand_annotation(annotation):
<ide> return ()
<ide> elif not isinstance(annotations, (list, tuple)):
<ide> annotations = (annotations, )
<del> return map(expand_annotation, annotations)
<add> return [expand_annotation(a) for a in annotations]
<ide><path>celery/app/base.py
<ide> from contextlib import contextmanager
<ide> from copy import deepcopy
<ide> from functools import reduce, wraps
<add>from operator import attrgetter
<ide> from threading import Lock
<ide>
<ide> from billiard.util import register_after_fork
<ide> def __reduce__(self):
<ide> return type(name or Class.__name__, (Class, ), attrs)
<ide>
<ide> def _rgetattr(self, path):
<del> return reduce(getattr, [self] + path.split('.'))
<add> return attrgetter(path)(self)
<ide>
<ide> def __repr__(self):
<ide> return '<{0} {1}:0x{2:x}>'.format(
<ide><path>celery/app/builtins.py
<ide> from __future__ import absolute_import
<ide>
<ide> from collections import deque
<add>from future_builtins import map, zip
<ide> from itertools import starmap
<ide>
<ide> from celery._state import get_current_worker_task
<ide> def add_unlock_chord_task(app):
<ide> @app.task(name='celery.chord_unlock', max_retries=None)
<ide> def unlock_chord(group_id, callback, interval=1, propagate=False,
<ide> max_retries=None, result=None):
<del> result = _res.GroupResult(group_id, map(_res.AsyncResult, result))
<add> AR = _res.AsyncResult
<add> result = _res.GroupResult(group_id, [AR(r) for r in result])
<ide> j = result.join_native if result.supports_native_join else result.join
<ide> if result.ready():
<ide> subtask(callback).delay(j(propagate=propagate))
<ide> def prepare_member(task):
<ide> tid = opts['task_id'] = uuid()
<ide> return task, self.AsyncResult(tid)
<ide>
<del> tasks, results = zip(*[prepare_member(task) for task in tasks])
<del> return (tasks, self.app.GroupResult(group_id, results),
<del> group_id, args)
<add> tasks, res = list(zip(*[prepare_member(task) for task in tasks]))
<add> return (tasks, self.app.GroupResult(group_id, res), group_id, args)
<ide>
<ide> def apply_async(self, partial_args=(), kwargs={}, **options):
<ide> if self.app.conf.CELERY_ALWAYS_EAGER:
<ide> def run(self, header, body, partial_args=(), interval=1,
<ide>
<ide> # - convert back to group if serialized
<ide> if not isinstance(header, group):
<del> header = group(map(maybe_subtask, header))
<add> header = group([maybe_subtask(t) for t in header])
<ide> # - eager applies the group inline
<ide> if eager:
<ide> return header.apply(args=partial_args, task_id=group_id)
<ide><path>celery/app/log.py
<ide> def setup_logging_subsystem(self, loglevel=None, logfile=None,
<ide> if self.app.conf.CELERYD_HIJACK_ROOT_LOGGER:
<ide> root.handlers = []
<ide>
<del> for logger in filter(None, (root, get_multiprocessing_logger())):
<del> self.setup_handlers(logger, logfile, format,
<del> colorize, **kwargs)
<del> if loglevel:
<del> logger.setLevel(loglevel)
<del> signals.after_setup_logger.send(sender=None, logger=logger,
<add> for logger in root, get_multiprocessing_logger():
<add> if logger is not None:
<add> self.setup_handlers(logger, logfile, format,
<add> colorize, **kwargs)
<add> if loglevel:
<add> logger.setLevel(loglevel)
<add> signals.after_setup_logger.send(sender=None, logger=logger,
<ide> loglevel=loglevel, logfile=logfile,
<ide> format=format, colorize=colorize)
<ide> # then setup the root task logger.
<ide><path>celery/app/routes.py
<ide> def expand_route(route):
<ide> return ()
<ide> if not isinstance(routes, (list, tuple)):
<ide> routes = (routes, )
<del> return map(expand_route, routes)
<add> return [expand_route(route) for route in routes]
<ide><path>celery/app/utils.py
<ide> def get_by_parts(self, *parts):
<ide> False
<ide>
<ide> """
<del> return self['_'.join(filter(None, parts))]
<add> return self['_'.join(part for part in parts if part)]
<ide>
<ide> def humanize(self):
<ide> """Returns a human readable string showing changes to the
<ide> def bugreport(app):
<ide>
<ide> return BUGREPORT_INFO.format(
<ide> system=_platform.system(),
<del> arch=', '.join(filter(None, _platform.architecture())),
<add> arch=', '.join(x for x in _platform.architecture() if x),
<ide> py_i=platforms.pyimplementation(),
<ide> celery_v=celery.VERSION_BANNER,
<ide> kombu_v=kombu.__version__,
<ide><path>celery/apps/worker.py
<ide> def purge_messages(self):
<ide> def tasklist(self, include_builtins=True):
<ide> tasks = self.app.tasks.keys()
<ide> if not include_builtins:
<del> tasks = filter(lambda s: not s.startswith('celery.'), tasks)
<add> tasks = [t for t in tasks if not t.startswith('celery.')]
<ide> return '\n'.join(' . {0}'.format(task) for task in sorted(tasks))
<ide>
<ide> def extra_info(self):
<ide><path>celery/backends/base.py
<ide> import sys
<ide>
<ide> from datetime import timedelta
<add>from future_builtins import map
<ide>
<ide> from kombu import serialization
<ide> from kombu.utils.encoding import bytes_to_str, ensure_bytes, from_utf8
<ide><path>celery/bin/base.py
<ide> import warnings
<ide>
<ide> from collections import defaultdict
<add>from future_builtins import zip
<ide> from optparse import OptionParser, IndentedHelpFormatter, make_option as Option
<ide> from types import ModuleType
<ide>
<ide> def prepare_args(self, options, args):
<ide> options = dict((k, self.expanduser(v))
<ide> for k, v in vars(options).iteritems()
<ide> if not k.startswith('_'))
<del> args = map(self.expanduser, args)
<add> args = [self.expanduser(arg) for arg in args]
<ide> self.check_args(args)
<ide> return options, args
<ide>
<ide><path>celery/bin/celery.py
<ide> import warnings
<ide>
<ide> from billiard import freeze_support
<add>from future_builtins import map
<ide> from importlib import import_module
<ide> from pprint import pformat
<ide>
<ide> def do_call_method(self, args, **kwargs):
<ide> destination = kwargs.get('destination')
<ide> timeout = kwargs.get('timeout') or self.choices[method][0]
<ide> if destination and isinstance(destination, basestring):
<del> destination = map(str.strip, destination.split(','))
<add> destination = list(map(str.strip, destination.split(',')))
<ide>
<ide> try:
<ide> handler = getattr(self, method)
<ide><path>celery/bin/celeryd_multi.py
<ide> import sys
<ide>
<ide> from collections import defaultdict
<add>from future_builtins import map
<ide> from subprocess import Popen
<ide> from time import sleep
<ide>
<ide> def multi_args(p, cmd='celeryd', append='', prefix='', suffix=''):
<ide> except ValueError:
<ide> pass
<ide> else:
<del> names = map(str, range(1, noderange + 1))
<add> names = list(map(str, range(1, noderange + 1)))
<ide> prefix = 'celery'
<ide> cmd = options.pop('--cmd', cmd)
<ide> append = options.pop('--append', append)
<ide> def parse_ns_range(ns, ranges=False):
<ide> for space in ',' in ns and ns.split(',') or [ns]:
<ide> if ranges and '-' in space:
<ide> start, stop = space.split('-')
<del> x = map(str, range(int(start), int(stop) + 1))
<add> x = list(map(str, range(int(start), int(stop) + 1)))
<ide> ret.extend(x)
<ide> else:
<ide> ret.append(space)
<ide><path>celery/canvas.py
<ide> """
<ide> from __future__ import absolute_import
<ide>
<add>from future_builtins import map
<ide> from operator import itemgetter
<ide> from itertools import chain as _chain
<ide>
<ide> def from_dict(self, d):
<ide>
<ide> def __call__(self, *partial_args, **options):
<ide> tasks, result, gid, args = self.type.prepare(options,
<del> map(Signature.clone, self.tasks), partial_args)
<add> [Signature.clone(t) for t in self.tasks], partial_args)
<ide> return self.type(tasks, result, gid, args)
<ide>
<ide> def skew(self, start=1.0, stop=None, step=1.0):
<ide><path>celery/contrib/rdb.py
<ide> def add(x, y):
<ide> import socket
<ide> import sys
<ide>
<add>from future_builtins import map
<ide> from pdb import Pdb
<ide>
<ide> from billiard import current_process
<ide><path>celery/loaders/base.py
<ide> import os
<ide> import re
<ide>
<add>from future_builtins import map
<ide> from datetime import datetime
<ide>
<ide> from kombu.utils.encoding import safe_str
<ide><path>celery/platforms.py
<ide> import sys
<ide>
<ide> from contextlib import contextmanager
<add>from future_builtins import map
<ide>
<ide> from .local import try_import
<ide>
<ide> def open(self):
<ide> os.chdir(self.workdir)
<ide> os.umask(self.umask)
<ide>
<del> for fd in reversed(range(get_fdmax(default=2048))):
<del> with ignore_EBADF():
<del> os.close(fd)
<del>
<add> os.closerange(1, get_fdmax(default=2048))
<ide> os.open(DAEMON_REDIRECT_TO, os.O_RDWR)
<ide> os.dup2(0, 1)
<ide> os.dup2(0, 2)
<ide><path>celery/result.py
<ide>
<ide> from collections import deque
<ide> from copy import copy
<del>from itertools import imap
<add>from future_builtins import map
<ide>
<ide> from . import current_app
<ide> from . import states
<ide> def supports_native_join(self):
<ide> def children(self):
<ide> children = self.backend.get_children(self.id)
<ide> if children:
<del> return map(from_serializable, children)
<add> return [from_serializable(child) for child in children]
<ide>
<ide> @property
<ide> def result(self):
<ide> def completed_count(self):
<ide> :returns: the number of tasks completed.
<ide>
<ide> """
<del> return sum(imap(int, (result.successful() for result in self.results)))
<add> return sum(map(int, (result.successful() for result in self.results)))
<ide>
<ide> def forget(self):
<ide> """Forget about (and possible remove the result of) all the tasks."""
<ide><path>celery/security/serialization.py
<ide>
<ide> import base64
<ide>
<add>from future_builtins import zip
<ide> from kombu.serialization import registry, encode, decode
<ide> from kombu.utils.encoding import bytes_to_str, str_to_bytes
<ide>
<ide><path>celery/tests/utilities/test_platforms.py
<ide> class test_DaemonContext(Case):
<ide> @patch('os.chdir')
<ide> @patch('os.umask')
<ide> @patch('os.close')
<add> @patch('os.closerange')
<ide> @patch('os.open')
<ide> @patch('os.dup2')
<del> def test_open(self, dup2, open, close, umask, chdir, _exit, setsid,
<del> fork):
<add> def test_open(self, dup2, open, close, closer, umask, chdir,
<add> _exit, setsid, fork):
<ide> x = DaemonContext(workdir='/opt/workdir')
<ide>
<ide> fork.return_value = 0
<ide><path>celery/utils/__init__.py
<ide> """
<ide> from __future__ import absolute_import, print_function
<ide>
<del>import operator
<ide> import os
<ide> import sys
<ide> import threading
<ide> def fun_takes_kwargs(fun, kwlist=[]):
<ide> ['logfile', 'loglevel', 'task_id']
<ide>
<ide> """
<del> argspec = getattr(fun, 'argspec', getargspec(fun))
<del> args, _varargs, keywords, _defaults = argspec
<del> if keywords != None:
<add> S = getattr(fun, 'argspec', getargspec(fun))
<add> if S.keywords != None:
<ide> return kwlist
<del> return filter(partial(operator.contains, args), kwlist)
<add> return [kw for kw in kwlist if kw in S.args]
<ide>
<ide>
<ide> def isatty(fh):
<ide> def jsonify(obj):
<ide> if isinstance(obj, (int, float, basestring, types.NoneType)):
<ide> return obj
<ide> elif isinstance(obj, (tuple, list)):
<del> return map(jsonify, obj)
<add> return [jsonify(o) for o in obj]
<ide> elif isinstance(obj, dict):
<del> return dict([(k, jsonify(v)) for k, v in obj.iteritems()])
<add> return dict((k, jsonify(v)) for k, v in obj.iteritems())
<ide> # See "Date Time String Format" in the ECMA-262 specification.
<ide> elif isinstance(obj, datetime.datetime):
<ide> r = obj.isoformat()
<ide><path>celery/utils/debug.py
<ide> def memdump(samples=10):
<ide> if ps() is None:
<ide> print('- rss: (psutil not installed).')
<ide> return
<del> if filter(None, _mem_sample):
<add> if any(_mem_sample):
<ide> print('- rss (sample):')
<ide> for mem in sample(_mem_sample, samples):
<ide> print('- > {0},'.format(mem))
<ide><path>celery/utils/log.py
<ide> def handleError(self, record):
<ide>
<ide> handler.handleError = WithSafeHandleError().handleError
<ide>
<del> return map(wrap_handler, self.logger.handlers)
<add> return [wrap_handler(l) for l in self.logger.handlers]
<ide>
<ide> def write(self, data):
<ide> """Write message to logging object."""
<ide><path>celery/utils/mail.py
<ide> import warnings
<ide>
<ide> from email.mime.text import MIMEText
<add>from future_builtins import map
<ide>
<ide> from .functional import maybe_list
<ide> from .imports import symbol_by_name
<ide><path>celery/utils/text.py
<ide> """
<ide> from __future__ import absolute_import
<ide>
<del>import textwrap
<add>from future_builtins import filter, map
<add>from textwrap import fill
<ide>
<ide> from pprint import pformat
<ide>
<ide> def dedent(s, n=4):
<ide>
<ide>
<ide> def fill_paragraphs(s, width):
<del> return '\n'.join(textwrap.fill(p, width) for p in s.split('\n'))
<add> return '\n'.join(fill(p, width) for p in s.split('\n'))
<ide>
<ide>
<ide> def join(l):
<ide><path>celery/utils/threads.py
<ide>
<ide> from kombu.syn import detect_environment
<ide>
<del>active_count = (getattr(threading, 'active_count', None) or
<del> threading.activeCount)
<ide> USE_PURE_LOCALS = os.environ.get("USE_PURE_LOCALS")
<ide>
<ide>
<ide><path>celery/utils/timer2.py
<ide> import sys
<ide>
<ide> from functools import wraps
<add>from future_builtins import map
<ide> from itertools import count
<ide> from threading import Condition, Event, Lock, Thread
<ide> from time import time, sleep, mktime
<ide> def __repr__(self):
<ide> if sys.version_info[0] == 3: # pragma: no cover
<ide>
<ide> def __hash__(self):
<del> return hash('|'.join(map(repr, (self.fun, self.args,
<del> self.kwargs))))
<add> return hash('{0.fun!r}|{0.args!r}|{0.kwargs!r}'.format(self))
<ide>
<ide> def __lt__(self, other):
<ide> return hash(self) < hash(other)
<ide> def cancel(self, tref):
<ide> @property
<ide> def queue(self):
<ide> events = list(self._queue)
<del> return map(heapq.heappop, [events] * len(events))
<add> return [heapq.heappop(x) for x in [events] * len(events)]
<ide>
<ide>
<ide> class Timer(Thread):
<ide><path>celery/utils/timeutils.py
<ide> from datetime import datetime, timedelta
<ide> from dateutil import tz
<ide> from dateutil.parser import parse as parse_iso8601
<add>from future_builtins import zip
<ide>
<ide> from celery.exceptions import ImproperlyConfigured
<ide>
<ide>
<ide>
<ide> DAYNAMES = 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
<del>WEEKDAYS = dict((name, dow) for name, dow in zip(DAYNAMES, range(7)))
<add>WEEKDAYS = dict(zip(DAYNAMES, range(7)))
<ide>
<ide> RATE_MODIFIER_MAP = {'s': lambda n: n,
<ide> 'm': lambda n: n / 60.0,
<ide><path>celery/worker/buckets.py
<ide> def items(self):
<ide> """Flattens the data in all of the buckets into a single list."""
<ide> # for queues with contents [(1, 2), (3, 4), (5, 6), (7, 8)]
<ide> # zips and flattens to [1, 3, 5, 7, 2, 4, 6, 8]
<del> return filter(None, chain.from_iterable(izip_longest(*[bucket.items
<del> for bucket in self.buckets.values()])))
<add> return [x for x in chain.from_iterable(izip_longest(*[bucket.items
<add> for bucket in self.buckets.values()])) if x]
<ide>
<ide>
<ide> class FastQueue(Queue):
<ide><path>celery/worker/control.py
<ide> """
<ide> from __future__ import absolute_import
<ide>
<add>from future_builtins import map
<ide> from datetime import datetime
<ide>
<ide> from kombu.utils.encoding import safe_repr
<ide> def dump_schedule(panel, safe=False, **kwargs):
<ide> from celery.worker.job import Request
<ide> schedule = panel.consumer.timer.schedule
<ide> if not schedule.queue:
<del> logger.debug('--Empty schedule--')
<ide> return []
<ide>
<del> formatitem = lambda (i, item): '{0}. {1} pri{2} {3!r}'.format(i,
<del> datetime.utcfromtimestamp(item['eta']),
<del> item['priority'], item['item'])
<del> info = map(formatitem, enumerate(schedule.info()))
<del> logger.debug('* Dump of current schedule:\n%s', '\n'.join(info))
<del> scheduled_tasks = []
<del> for info in schedule.info():
<del> item = info['item']
<del> if item.args and isinstance(item.args[0], Request):
<del> scheduled_tasks.append({'eta': info['eta'],
<del> 'priority': info['priority'],
<del> 'request':
<del> item.args[0].info(safe=safe)})
<del> return scheduled_tasks
<add> def prepare_entries():
<add> for entry in schedule.info():
<add> item = entry['item']
<add> if item.args and isinstance(item.args[0], Request):
<add> yield {'eta': entry['eta'],
<add> 'priority': entry['priority'],
<add> 'request': item.args[0].info(safe=safe)}
<add> return list(prepare_entries())
<ide>
<ide>
<ide> @Panel.register
<ide> def _extract_info(task):
<ide> fields = dict((field, str(getattr(task, field, None)))
<ide> for field in taskinfoitems
<ide> if getattr(task, field, None) is not None)
<del> info = map('='.join, fields.items())
<del> if not info:
<del> return task.name
<del> return '{0} [{1}]'.format(task.name, ' '.join(info))
<add> if fields:
<add> info = map('='.join, fields.iteritems())
<add> return '{0} [{1}]'.format(task.name, ' '.join(info))
<add> return task.name
<ide>
<del> info = map(_extract_info, (tasks[task]
<del> for task in sorted(tasks.keys())))
<del> logger.debug('* Dump of currently registered tasks:\n%s', '\n'.join(info))
<del>
<del> return info
<add> return [_extract_info(tasks[task]) for task in sorted(tasks)]
<ide>
<ide>
<ide> @Panel.register | 30 |
Javascript | Javascript | remove leftover code for tmppublishingfolder | 7e17d2606021c556479442c60e3814017d32de3d | <ide><path>scripts/publish-npm.js
<ide> const {
<ide> publishAndroidArtifactsToMaven,
<ide> } = require('./release-utils');
<ide> const fs = require('fs');
<del>const os = require('os');
<ide> const path = require('path');
<ide> const yargs = require('yargs');
<ide>
<ide> const buildTag = process.env.CIRCLE_TAG;
<ide> const otp = process.env.NPM_CONFIG_OTP;
<del>const tmpPublishingFolder = fs.mkdtempSync(
<del> path.join(os.tmpdir(), 'rn-publish-'),
<del>);
<ide>
<ide> const argv = yargs
<ide> .option('n', {
<ide> const buildType = releaseBuild
<ide> ? 'nightly'
<ide> : 'dry-run';
<ide>
<del>if (!argv.help) {
<del> echo(`The temp publishing folder is ${tmpPublishingFolder}`);
<del>}
<del>
<ide> // 34c034298dc9cad5a4553964a5a324450fda0385
<ide> const currentCommit = getCurrentCommit();
<ide> const shortCommit = currentCommit.slice(0, 9);
<ide> if (isCommitly) {
<ide> }
<ide> }
<ide>
<del>generateAndroidArtifacts(releaseVersion, tmpPublishingFolder);
<add>generateAndroidArtifacts(releaseVersion);
<ide>
<ide> // Write version number to the build folder
<ide> const releaseVersionFile = path.join('build', '.version');
<ide><path>scripts/release-utils.js
<ide> const {exec, echo, exit, test, env, pushd, popd} = require('shelljs');
<ide> const {createHermesPrebuiltArtifactsTarball} = require('./hermes/hermes-utils');
<ide>
<del>function generateAndroidArtifacts(releaseVersion, tmpPublishingFolder) {
<add>function generateAndroidArtifacts(releaseVersion) {
<ide> // -------- Generating Android Artifacts
<ide> echo('Generating Android artifacts inside /tmp/maven-local');
<ide> if (exec('./gradlew publishAllToMavenTempLocal').code) {
<ide><path>scripts/test-e2e-local.js
<ide> const {exec, exit, pushd, popd, pwd, cd, cp} = require('shelljs');
<ide> const yargs = require('yargs');
<ide> const fs = require('fs');
<del>const path = require('path');
<del>const os = require('os');
<ide> const {getBranchName} = require('./scm-utils');
<ide>
<ide> const {
<ide> const {
<ide>
<ide> const {
<ide> generateAndroidArtifacts,
<del> saveFilesToRestore,
<ide> generateiOSArtifacts,
<ide> } = require('./release-utils');
<ide>
<ide> if (argv.target === 'RNTester') {
<ide> // create the local npm package to feed the CLI
<ide>
<ide> // base setup required (specular to publish-npm.js)
<del> const tmpPublishingFolder = fs.mkdtempSync(
<del> path.join(os.tmpdir(), 'rn-publish-'),
<del> );
<del> console.info(`The temp publishing folder is ${tmpPublishingFolder}`);
<del>
<del> saveFilesToRestore(tmpPublishingFolder);
<ide>
<ide> // we need to add the unique timestamp to avoid npm/yarn to use some local caches
<ide> const baseVersion = require('../package.json').version;
<ide> if (argv.target === 'RNTester') {
<ide> ).code;
<ide>
<ide> // Generate native files for Android
<del> generateAndroidArtifacts(releaseVersion, tmpPublishingFolder);
<add> generateAndroidArtifacts(releaseVersion);
<ide>
<ide> // Setting up generating native iOS (will be done later)
<ide> const repoRoot = pwd();
<ide> if (argv.target === 'RNTester') {
<ide> exec('yarn android');
<ide> }
<ide> popd();
<del>
<del> // just cleaning up the temp folder, the rest is done by the test clean script
<del> exec(`rm -rf ${tmpPublishingFolder}`);
<ide> }
<ide>
<ide> exit(0); | 3 |
Javascript | Javascript | implement automatic mutable bindings ("auto-mut") | eabf61d42fcfaa6dde82f7f16304f08a0d5a61d0 | <ide><path>packages/ember-glimmer-template-compiler/lib/plugins/transform-attrs-into-props.js
<add>/**
<add> @module ember
<add> @submodule ember-glimmer
<add>*/
<add>
<add>/**
<add> A Glimmer2 AST transformation that replaces all instances of
<add>
<add> ```handlebars
<add> {{attrs.foo.bar}}
<add> ```
<add>
<add> to
<add>
<add> ```handlebars
<add> {{foo.bar}}
<add> ```
<add>
<add> as well as `{{#if attrs.foo}}`, `{{deeply (nested attrs.foobar.baz)}}` etc
<add>
<add> @private
<add> @class TransformAttrsToProps
<add>*/
<add>
<add>export default function TransformAttrsToProps() {
<add> // set later within Glimmer2 to the syntax package
<add> this.syntax = null;
<add>}
<add>
<add>/**
<add> @private
<add> @method transform
<add> @param {AST} ast The AST to be transformed.
<add>*/
<add>TransformAttrsToProps.prototype.transform = function TransformAttrsToProps_transform(ast) {
<add> let { traverse, builders: b } = this.syntax;
<add>
<add> traverse(ast, {
<add> PathExpression(node) {
<add> if (node.parts[0] === 'attrs') {
<add> return b.path(node.original.substr(6));
<add> }
<add> }
<add> });
<add>
<add> return ast;
<add>};
<ide><path>packages/ember-glimmer-template-compiler/lib/system/compile-options.js
<ide> import defaultPlugins from 'ember-template-compiler/plugins';
<del>import TransformHasBlockSyntax from '../plugins/transform-has-block-syntax';
<ide> import TransformActionSyntax from '../plugins/transform-action-syntax';
<add>import TransformAttrsIntoProps from '../plugins/transform-attrs-into-props';
<ide> import TransformEachInIntoEach from '../plugins/transform-each-in-into-each';
<add>import TransformHasBlockSyntax from '../plugins/transform-has-block-syntax';
<ide> import assign from 'ember-metal/assign';
<ide>
<ide> export const PLUGINS = [
<ide> ...defaultPlugins,
<ide> // the following are ember-glimmer specific
<del> TransformHasBlockSyntax,
<ide> TransformActionSyntax,
<del> TransformEachInIntoEach
<add> TransformAttrsIntoProps,
<add> TransformEachInIntoEach,
<add> TransformHasBlockSyntax
<ide> ];
<ide>
<ide> let USER_PLUGINS = [];
<ide><path>packages/ember-glimmer/lib/utils/process-args.js
<ide> import symbol from 'ember-metal/symbol';
<ide> import { assert } from 'ember-metal/debug';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide> import { ARGS } from '../component';
<del>import { isMut } from '../helpers/mut';
<ide> import { UPDATE } from './references';
<ide>
<ide> export default function processArgs(args, positionalParamsDefinition) {
<ide> class SimpleArgs {
<ide> let ref = namedArgs.get(name);
<ide> let value = attrs[name];
<ide>
<del> if (isMut(ref)) {
<add> if (ref[UPDATE]) {
<ide> attrs[name] = new MutableCell(ref, value);
<ide> }
<ide>
<ide><path>packages/ember-glimmer/tests/integration/components/dynamic-components-test.js
<ide> moduleFor('Components test: dynamic components', class extends RenderingTest {
<ide>
<ide> ['@test component helper properly invalidates hash params inside an {{each}} invocation #11044'](assert) {
<ide> this.registerComponent('foo-bar', {
<del> template: '[{{internalName}} - {{attrs.name}}]',
<add> template: '[{{internalName}} - {{name}}]',
<ide> ComponentClass: Component.extend({
<ide> willRender() {
<ide> // store internally available name to ensure that the name available in `this.attrs.name`
<ide> // matches the template lookup name
<del> set(this, 'internalName', this.attrs.name);
<add> set(this, 'internalName', this.get('name'));
<ide> }
<ide> })
<ide> });
<ide><path>packages/ember-glimmer/tests/integration/helpers/mut-test.js
<ide> moduleFor('Helpers test: {{mut}}', class extends RenderingTest {
<ide> this.assertText('12');
<ide> }
<ide>
<del> ['@htmlbars automatic mutable bindings tolerate undefined non-stream inputs and attempts to set them']() {
<add> ['@test automatic mutable bindings exposes a mut cell in attrs']() {
<add> let inner;
<add>
<add> this.registerComponent('x-inner', {
<add> ComponentClass: Component.extend({
<add> didInsertElement() {
<add> inner = this;
<add> }
<add> }),
<add> template: '{{foo}}'
<add> });
<add>
<add> this.registerComponent('x-outer', {
<add> template: '{{x-inner foo=bar}}'
<add> });
<add>
<add> this.render('{{x-outer bar=baz}}', { baz: 'foo' });
<add>
<add> this.assertText('foo');
<add>
<add> this.assertStableRerender();
<add>
<add> this.runTask(() => inner.attrs.foo.update('bar'));
<add>
<add> this.assert.equal(inner.attrs.foo.value, 'bar');
<add> this.assert.equal(get(inner, 'foo'), 'bar');
<add> this.assertText('bar');
<add>
<add> this.runTask(() => inner.attrs.foo.update('foo'));
<add>
<add> this.assertText('foo');
<add> }
<add>
<add> ['@test automatic mutable bindings tolerate undefined non-stream inputs and attempts to set them']() {
<ide> let inner;
<ide>
<ide> this.registerComponent('x-inner', {
<ide> moduleFor('Helpers test: {{mut}}', class extends RenderingTest {
<ide> this.assertText('');
<ide> }
<ide>
<add> // TODO: This is not really consistent with how the rest of the system works. Investigate if we need to
<add> // support this, if not then this test can be deleted.
<ide> ['@htmlbars automatic mutable bindings tolerate constant non-stream inputs and attempts to set them']() {
<ide> let inner;
<ide> | 5 |
Python | Python | update time.py to solve the microsecond issues | bfee3a8999dd26a3b4001929371ec9d868f9bdff | <ide><path>celery/utils/time.py
<ide> def remaining(start, ends_in, now=None, relative=False):
<ide> start = start.replace(tzinfo=now.tzinfo)
<ide> end_date = start + ends_in
<ide> if relative:
<del> end_date = delta_resolution(end_date, ends_in)
<add> end_date = delta_resolution(end_date, ends_in).replace(microsecond=0)
<ide> ret = end_date - now
<ide> if C_REMDEBUG: # pragma: no cover
<ide> print('rem: NOW:%r START:%r ENDS_IN:%r END_DATE:%s REM:%s' % ( | 1 |
Python | Python | set docker api version | 795911eaf30c6f4cbe27b94b47a06196e9023c5c | <ide><path>libcloud/container/drivers/docker.py
<ide> def __init__(self, key='', secret='', secure=False, host='localhost',
<ide> port=port,
<ide> key_file=key_file,
<ide> cert_file=cert_file)
<del>
<add> # set API version
<add> self.version = self._get_api_version()
<ide> if host.startswith('https://'):
<ide> secure = True
<ide> | 1 |
Ruby | Ruby | use kwargs to avoid hash slicing | b635eea70f8d13c555f529cef328aafabc4113d3 | <ide><path>actionview/lib/action_view/digestor.rb
<ide> def compute_and_store_digest(cache_key, options) # called under @@digest_monitor
<ide>
<ide> attr_reader :name, :finder, :options
<ide>
<del> def initialize(options)
<del> @name, @finder = options.values_at(:name, :finder)
<del> @options = options.except(:name, :finder)
<add> def initialize(name:, finder:, **options)
<add> @name, @finder = name, finder
<add> @options = options
<ide> end
<ide>
<ide> def digest | 1 |
PHP | PHP | update doc blocks | 81611956f5f74d62785e625b15baa92a557fba42 | <ide><path>lib/Cake/TestSuite/Fixture/CakeFixtureManager.php
<ide> protected function _initDb() {
<ide> *
<ide> * @param array $fixtures the fixture names to load using the notation {type}.{name}
<ide> * @return void
<add> * @throws UnexpectedValueException when a referenced fixture does not exist.
<ide> */
<ide> protected function _loadFixtures($fixtures) {
<ide> foreach ($fixtures as $index => $fixture) { | 1 |
PHP | PHP | run facade script | f06af0cdac95815fc1d707c0762639aebf52a165 | <ide><path>src/Illuminate/Support/Facades/Auth.php
<ide> * @method static \Illuminate\Auth\SessionGuard setRequest(\Symfony\Component\HttpFoundation\Request $request)
<ide> * @method static \Illuminate\Support\Timebox getTimebox()
<ide> * @method static \Illuminate\Contracts\Auth\Authenticatable authenticate()
<add> * @method static \Illuminate\Auth\SessionGuard forgetUser()
<ide> * @method static \Illuminate\Contracts\Auth\UserProvider getProvider()
<ide> * @method static void setProvider(\Illuminate\Contracts\Auth\UserProvider $provider)
<ide> * @method static void macro(string $name, object|callable $macro) | 1 |
Javascript | Javascript | polyfill history.state for non-supporting browsers | 331d0c1d036274a00fc2d72dcb3c4783b7249949 | <ide><path>packages/ember-routing/lib/location/history_location.js
<ide>
<ide> var get = Ember.get, set = Ember.set;
<ide> var popstateFired = false;
<add>var supportsHistoryState = (function(){
<add> return !!(window.history && history.hasOwnProperty('state'));
<add>})();
<ide>
<ide> /**
<ide> Ember.HistoryLocation implements the location API using the browser's
<ide> Ember.HistoryLocation = Ember.Object.extend({
<ide> @param path {String}
<ide> */
<ide> setURL: function(path) {
<add> var state = this.getState();
<ide> path = this.formatURL(path);
<ide>
<del> if (this.getState() && this.getState().path !== path) {
<add> if (state && state.path !== path) {
<ide> this.pushState(path);
<ide> }
<ide> },
<ide> Ember.HistoryLocation = Ember.Object.extend({
<ide> @param path {String}
<ide> */
<ide> replaceURL: function(path) {
<add> var state = this.getState();
<ide> path = this.formatURL(path);
<ide>
<del> if (this.getState() && this.getState().path !== path) {
<add> if (state && state.path !== path) {
<ide> this.replaceState(path);
<ide> }
<ide> },
<ide> Ember.HistoryLocation = Ember.Object.extend({
<ide> @private
<ide>
<ide> Get the current `history.state`
<add> Polyfill checks for native browser support and falls back to retrieving
<add> from a private _historyState variable
<ide>
<ide> @method getState
<ide> */
<ide> getState: function() {
<del> return get(this, 'history').state;
<add> return supportsHistoryState ? get(this, 'history').state : this._historyState;
<ide> },
<ide>
<ide> /**
<ide> Ember.HistoryLocation = Ember.Object.extend({
<ide> @param path {String}
<ide> */
<ide> pushState: function(path) {
<del> get(this, 'history').pushState({ path: path }, null, path);
<add> var state = { path: path };
<add>
<add> get(this, 'history').pushState(state, null, path);
<add>
<add> // store state if browser doesn't support `history.state`
<add> if(!supportsHistoryState) {
<add> this._historyState = state;
<add> }
<add>
<ide> // used for webkit workaround
<ide> this._previousURL = this.getURL();
<ide> },
<ide> Ember.HistoryLocation = Ember.Object.extend({
<ide> @param path {String}
<ide> */
<ide> replaceState: function(path) {
<del> get(this, 'history').replaceState({ path: path }, null, path);
<add> var state = { path: path };
<add>
<add> get(this, 'history').replaceState(state, null, path);
<add>
<add> // store state if browser doesn't support `history.state`
<add> if(!supportsHistoryState) {
<add> this._historyState = state;
<add> }
<add>
<ide> // used for webkit workaround
<ide> this._previousURL = this.getURL();
<ide> }, | 1 |
Javascript | Javascript | add azimuthal "equalarea" projection mode | afe60a14e63fb2fc2f2ae9b77ce38bb84d9b4bba | <ide><path>d3.geo.js
<ide> var d3_radians = Math.PI / 180;
<ide> // TODO clip input coordinates on opposite hemisphere
<ide> d3.geo.azimuthal = function() {
<del> var mode = "orthographic", // or stereographic, gnomonic or equidistant
<add> var mode = "orthographic", // or stereographic, gnomonic, equidistant or equalarea
<ide> origin,
<ide> scale = 200,
<ide> translate = [480, 250],
<ide> d3.geo.azimuthal = function() {
<ide> k = mode === "stereographic" ? 1 / (1 + cc)
<ide> : mode === "gnomonic" ? 1 / cc
<ide> : mode === "equidistant" ? (c = Math.acos(cc), c / Math.sin(c))
<add> : mode === "equalarea" ? Math.sqrt(2 / (1 + cc))
<ide> : 1,
<ide> x = k * cy1 * sx1,
<ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1);
<ide> d3.geo.azimuthal = function() {
<ide> c = mode === "stereographic" ? 2 * Math.atan(p)
<ide> : mode === "gnomonic" ? Math.atan(p)
<ide> : mode === "equidistant" ? p
<add> : mode === "equalarea" ? 2 * Math.asin(.5 * p)
<ide> : Math.asin(p),
<ide> sc = Math.sin(c),
<ide> cc = Math.cos(c);
<ide><path>d3.geo.min.js
<del>(function(){function o(a){return a.target}function n(a){return a.source}function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={};var a=Math.PI/180;d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b!=="orthographic"?i*n+h*m*k:null,p,q=b==="stereographic"?1/(1+o):b==="gnomonic"?1/o:b==="equidistant"?(p=Math.acos(o),p/Math.sin(p)):1,r=q*m*l,s=q*(i*m*k-h*n);return[d*r+e[0],d*s+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.invert=function(c){var g=(c[0]-e[0])/d,j=(c[1]-e[1])/d,k=Math.sqrt(g*g+j*j),l=b==="stereographic"?2*Math.atan(k):b==="gnomonic"?Math.atan(k):b==="equidistant"?k:Math.asin(k),m=Math.sin(l),n=Math.cos(l);return[(f+Math.atan2(g*m,k*h*n+j*i*m))/a,Math.asin(n*i-j*m*h/k)/a]},j.mode=function(a){if(!arguments.length)return b;b=a+"";return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.invert=function(b){var c=(b[0]-e[0])/d,j=(b[1]-e[1])/d,k=i+j,l=Math.atan2(c,k),m=Math.sqrt(c*c+k*k);return[(f+l/g)/a,Math.asin((h-m*m*g*g)/(2*g))/a]},j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())},d3.geo.mercator=function(){function d(d){var e=d[0]/360,f=-(Math.log(Math.tan(Math.PI/4+d[1]*a/2))/a)/360;return[b*e+c[0],b*Math.max(-0.5,Math.min(.5,f))+c[1]]}var b=500,c=[480,250];d.invert=function(d){var e=(d[0]-c[0])/b,f=(d[1]-c[1])/b;return[360*e,2*Math.atan(Math.exp(-360*f*a))/a-90]},d.scale=function(a){if(!arguments.length)return b;b=+a;return d},d.translate=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return d};return d},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m};d3.geo.greatCircle=function(){function f(e,f){var g=b.call(this,e,f),h=c.call(this,e,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.cos(i),n=Math.sin(i),o=Math.cos(j),p=Math.sin(j),q=Math.cos(k),r=Math.sin(k),s=Math.cos(l),t=Math.sin(l),e=Math.acos(p*t+o*s*Math.cos(k-i)),u=Math.sin(e),v=e/(d-1),w=-v,x=[],f=-1;while(++f<d){w+=v;var y=Math.sin(e-w)/u,z=Math.sin(w)/u,A=y*o*m+z*s*q,B=y*o*n+z*s*r,C=y*p+z*t;x[f]=[Math.atan2(B,A)/a,Math.atan2(C,Math.sqrt(A*A+B*B))/a]}return x}var b=n,c=o,d=100,e=6371;f.source=function(a){if(!arguments.length)return b;b=a;return f},f.target=function(a){if(!arguments.length)return c;c=a;return f},f.n=function(a){if(!arguments.length)return d;d=+a;return f},f.radius=function(a){if(!arguments.length)return e;e=+a;return f},f.distance=function(d,f){var g=b.call(this,d,f),h=c.call(this,d,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.sin((l-j)/2),n=Math.sin((k-i)/2),o=m*m+Math.cos(j)*Math.cos(l)*n*n;return e*2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))};return f}})()
<ide>\ No newline at end of file
<add>(function(){function o(a){return a.target}function n(a){return a.source}function m(a,b){for(var c=a.coordinates[0],d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function l(a,b){b.apply(null,a.coordinates)}function k(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d][0],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function j(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)for(var f=c[d],g=0,h=f.length;g<h;g++)b.apply(null,f[g])}function i(a,b){for(var c=a.coordinates,d=0,e=c.length;d<e;d++)b.apply(null,c[d])}function h(a,b){for(var c=a.features,d=0,f=c.length;d<f;d++)e(c[d].geometry,b)}function g(a,b){e(a.geometry,b)}function e(a,b){a.type in f&&f[a.type](a,b)}function d(a,b){return b&&b.type in a?a[b.type](b):""}function c(){return 0}function b(a){return"m0,"+a+"a"+a+","+a+" 0 1,1 0,"+ -2*a+"a"+a+","+a+" 0 1,1 0,"+2*a+"z"}d3.geo={};var a=Math.PI/180;d3.geo.azimuthal=function(){function j(c){var g=c[0]*a-f,j=c[1]*a,k=Math.cos(g),l=Math.sin(g),m=Math.cos(j),n=Math.sin(j),o=b!=="orthographic"?i*n+h*m*k:null,p,q=b==="stereographic"?1/(1+o):b==="gnomonic"?1/o:b==="equidistant"?(p=Math.acos(o),p/Math.sin(p)):b==="equalarea"?Math.sqrt(2/(1+o)):1,r=q*m*l,s=q*(i*m*k-h*n);return[d*r+e[0],d*s+e[1]]}var b="orthographic",c,d=200,e=[480,250],f,g,h,i;j.invert=function(c){var g=(c[0]-e[0])/d,j=(c[1]-e[1])/d,k=Math.sqrt(g*g+j*j),l=b==="stereographic"?2*Math.atan(k):b==="gnomonic"?Math.atan(k):b==="equidistant"?k:b==="equalarea"?2*Math.asin(.5*k):Math.asin(k),m=Math.sin(l),n=Math.cos(l);return[(f+Math.atan2(g*m,k*h*n+j*i*m))/a,Math.asin(n*i-j*m*h/k)/a]},j.mode=function(a){if(!arguments.length)return b;b=a+"";return j},j.origin=function(b){if(!arguments.length)return c;c=b,f=c[0]*a,g=c[1]*a,h=Math.cos(g),i=Math.sin(g);return j},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return j.origin([0,0])},d3.geo.albers=function(){function k(){var d=a*c[0],e=a*c[1],k=a*b[1],l=Math.sin(d),m=Math.cos(d);f=a*b[0],g=.5*(l+Math.sin(e)),h=m*m+2*g*l,i=Math.sqrt(h-2*g*Math.sin(k))/g;return j}function j(b){var c=g*(a*b[0]-f),j=Math.sqrt(h-2*g*Math.sin(a*b[1]))/g;return[d*j*Math.sin(c)+e[0],d*(j*Math.cos(c)-i)+e[1]]}var b=[-98,38],c=[29.5,45.5],d=1e3,e=[480,250],f,g,h,i;j.invert=function(b){var c=(b[0]-e[0])/d,j=(b[1]-e[1])/d,k=i+j,l=Math.atan2(c,k),m=Math.sqrt(c*c+k*k);return[(f+l/g)/a,Math.asin((h-m*m*g*g)/(2*g))/a]},j.origin=function(a){if(!arguments.length)return b;b=[+a[0],+a[1]];return k()},j.parallels=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return k()},j.scale=function(a){if(!arguments.length)return d;d=+a;return j},j.translate=function(a){if(!arguments.length)return e;e=[+a[0],+a[1]];return j};return k()},d3.geo.albersUsa=function(){function e(e){var f=e[0],g=e[1];return(g>50?b:f<-140?c:g<21?d:a)(e)}var a=d3.geo.albers(),b=d3.geo.albers().origin([-160,60]).parallels([55,65]),c=d3.geo.albers().origin([-160,20]).parallels([8,18]),d=d3.geo.albers().origin([-60,10]).parallels([8,18]);e.scale=function(f){if(!arguments.length)return a.scale();a.scale(f),b.scale(f*.6),c.scale(f),d.scale(f*1.5);return e.translate(a.translate())},e.translate=function(f){if(!arguments.length)return a.translate();var g=a.scale()/1e3,h=f[0],i=f[1];a.translate(f),b.translate([h-400*g,i+170*g]),c.translate([h-190*g,i+200*g]),d.translate([h+580*g,i+430*g]);return e};return e.scale(a.scale())},d3.geo.mercator=function(){function d(d){var e=d[0]/360,f=-(Math.log(Math.tan(Math.PI/4+d[1]*a/2))/a)/360;return[b*e+c[0],b*Math.max(-0.5,Math.min(.5,f))+c[1]]}var b=500,c=[480,250];d.invert=function(d){var e=(d[0]-c[0])/b,f=(d[1]-c[1])/b;return[360*e,2*Math.atan(Math.exp(-360*f*a))/a-90]},d.scale=function(a){if(!arguments.length)return b;b=+a;return d},d.translate=function(a){if(!arguments.length)return c;c=[+a[0],+a[1]];return d};return d},d3.geo.path=function(){function n(a){return Math.abs(d3.geom.polygon(a.map(f)).area())}function l(a){var b=d3.geom.polygon(a[0].map(f)),c=b.centroid(1),d=c[0],e=c[1],g=Math.abs(b.area()),h=0,i=a.length;while(++h<i)b=d3.geom.polygon(a[h].map(f)),c=b.centroid(1),d-=c[0],e-=c[1],g-=Math.abs(b.area());return[d,e,6*g]}function k(a){var b=n(a[0]),c=0,d=a.length;while(++c<d)b-=n(a[c]);return b}function h(a){return f(a).join(",")}function g(c,f){typeof a=="function"&&(e=b(a.apply(this,arguments)));return d(i,c)}var a=4.5,e=b(a),f=d3.geo.albersUsa(),i={FeatureCollection:function(a){var b=[],c=a.features,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e].geometry));return b.join("")},Feature:function(a){return d(i,a.geometry)},Point:function(a){return"M"+h(a.coordinates)+e},MultiPoint:function(a){var b=[],c=a.coordinates,d=-1,f=c.length;while(++d<f)b.push("M",h(c[d]),e);return b.join("")},LineString:function(a){var b=["M"],c=a.coordinates,d=-1,e=c.length;while(++d<e)b.push(h(c[d]),"L");b.pop();return b.join("")},MultiLineString:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b.pop()}return b.join("")},Polygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i;while(++d<e){f=c[d],g=-1,i=f.length,b.push("M");while(++g<i)b.push(h(f[g]),"L");b[b.length-1]="Z"}return b.join("")},MultiPolygon:function(a){var b=[],c=a.coordinates,d=-1,e=c.length,f,g,i,j,k,l;while(++d<e){f=c[d],g=-1,i=f.length;while(++g<i){j=f[g],k=-1,l=j.length-1,b.push("M");while(++k<l)b.push(h(j[k]),"L");b[b.length-1]="Z"}}return b.join("")},GeometryCollection:function(a){var b=[],c=a.geometries,e=-1,f=c.length;while(++e<f)b.push(d(i,c[e]));return b.join("")}},j={FeatureCollection:function(a){var b=0,c=a.features,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b},Feature:function(a){return d(j,a.geometry)},Point:c,MultiPoint:c,LineString:c,MultiLineString:c,Polygon:function(a){return k(a.coordinates)},MultiPolygon:function(a){var b=0,c=a.coordinates,d=-1,e=c.length;while(++d<e)b+=k(c[d]);return b},GeometryCollection:function(a){var b=0,c=a.geometries,e=-1,f=c.length;while(++e<f)b+=d(j,c[e]);return b}},m={Feature:function(a){return d(m,a.geometry)},Polygon:function(a){var b=l(a.coordinates);return[b[0]/b[2],b[1]/b[2]]},MultiPolygon:function(a){var b=0,c=a.coordinates,d,e=0,f=0,g=0,h=-1,i=c.length;while(++h<i)d=l(c[h]),e+=d[0],f+=d[1],g+=d[2];return[e/g,f/g]}};g.projection=function(a){f=a;return g},g.area=function(a){return d(j,a)},g.centroid=function(a){return d(m,a)},g.pointRadius=function(c){typeof c=="function"?a=c:(a=+c,e=b(a));return g};return g},d3.geo.bounds=function(a){var b=Infinity,c=Infinity,d=-Infinity,f=-Infinity;e(a,function(a,e){a<b&&(b=a),a>d&&(d=a),e<c&&(c=e),e>f&&(f=e)});return[[b,c],[d,f]]};var f={Feature:g,FeatureCollection:h,LineString:i,MultiLineString:j,MultiPoint:i,MultiPolygon:k,Point:l,Polygon:m};d3.geo.greatCircle=function(){function f(e,f){var g=b.call(this,e,f),h=c.call(this,e,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.cos(i),n=Math.sin(i),o=Math.cos(j),p=Math.sin(j),q=Math.cos(k),r=Math.sin(k),s=Math.cos(l),t=Math.sin(l),e=Math.acos(p*t+o*s*Math.cos(k-i)),u=Math.sin(e),v=e/(d-1),w=-v,x=[],f=-1;while(++f<d){w+=v;var y=Math.sin(e-w)/u,z=Math.sin(w)/u,A=y*o*m+z*s*q,B=y*o*n+z*s*r,C=y*p+z*t;x[f]=[Math.atan2(B,A)/a,Math.atan2(C,Math.sqrt(A*A+B*B))/a]}return x}var b=n,c=o,d=100,e=6371;f.source=function(a){if(!arguments.length)return b;b=a;return f},f.target=function(a){if(!arguments.length)return c;c=a;return f},f.n=function(a){if(!arguments.length)return d;d=+a;return f},f.radius=function(a){if(!arguments.length)return e;e=+a;return f},f.distance=function(d,f){var g=b.call(this,d,f),h=c.call(this,d,f),i=g[0]*a,j=g[1]*a,k=h[0]*a,l=h[1]*a,m=Math.sin((l-j)/2),n=Math.sin((k-i)/2),o=m*m+Math.cos(j)*Math.cos(l)*n*n;return e*2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))};return f}})()
<ide>\ No newline at end of file
<ide><path>examples/azimuthal/azimuthal.js
<del>var xy = d3.geo.azimuthal().scale(240).mode("stereographic"),
<add>var xy = d3.geo.azimuthal().scale(240).mode("equalarea"),
<ide> path = d3.geo.path().projection(xy),
<ide> svg = d3.select("body").append("svg:svg");
<ide>
<ide><path>src/geo/azimuthal.js
<ide> // TODO clip input coordinates on opposite hemisphere
<ide> d3.geo.azimuthal = function() {
<del> var mode = "orthographic", // or stereographic, gnomonic or equidistant
<add> var mode = "orthographic", // or stereographic, gnomonic, equidistant or equalarea
<ide> origin,
<ide> scale = 200,
<ide> translate = [480, 250],
<ide> d3.geo.azimuthal = function() {
<ide> k = mode === "stereographic" ? 1 / (1 + cc)
<ide> : mode === "gnomonic" ? 1 / cc
<ide> : mode === "equidistant" ? (c = Math.acos(cc), c / Math.sin(c))
<add> : mode === "equalarea" ? Math.sqrt(2 / (1 + cc))
<ide> : 1,
<ide> x = k * cy1 * sx1,
<ide> y = k * (sy0 * cy1 * cx1 - cy0 * sy1);
<ide> d3.geo.azimuthal = function() {
<ide> c = mode === "stereographic" ? 2 * Math.atan(p)
<ide> : mode === "gnomonic" ? Math.atan(p)
<ide> : mode === "equidistant" ? p
<add> : mode === "equalarea" ? 2 * Math.asin(.5 * p)
<ide> : Math.asin(p),
<ide> sc = Math.sin(c),
<ide> cc = Math.cos(c);
<ide><path>test/geo/azimuthal-test.js
<ide> suite.addBatch({
<ide> assert.inDelta(lonlat[0], 0, 1e-6);
<ide> assert.inDelta(lonlat[1], 85, 1e-6);
<ide> }
<add> },
<add> "azimuthal.equalarea": {
<add> topic: function() {
<add> return d3.geo.azimuthal().mode("equalarea").translate([0, 0]).scale(100);
<add> },
<add> "Arctic": function(azimuthal) {
<add> var coords = azimuthal([0, 85]);
<add> assert.inDelta(coords[0], 0, 1e-6);
<add> assert.inDelta(coords[1], -135.118041, 1e-6);
<add> var lonlat = azimuthal.invert(coords);
<add> assert.inDelta(lonlat[0], 0, 1e-6);
<add> assert.inDelta(lonlat[1], 85, 1e-6);
<add> },
<add> "Antarctic": function(azimuthal) {
<add> var coords = azimuthal([0, -85]);
<add> assert.inDelta(coords[0], 0, 1e-6);
<add> assert.inDelta(coords[1], 135.118041, 1e-6);
<add> var lonlat = azimuthal.invert(coords);
<add> assert.inDelta(lonlat[0], 0, 1e-6);
<add> assert.inDelta(lonlat[1], -85, 1e-6);
<add> },
<add> "Hawaii": function(azimuthal) {
<add> var coords = azimuthal([-180, 0]);
<add> assert.equal(coords[0], -Infinity);
<add> assert.isTrue(isNaN(coords[1]));
<add> },
<add> "Phillipines": function(azimuthal) {
<add> var coords = azimuthal([180, 0]);
<add> assert.equal(coords[0], Infinity);
<add> assert.isTrue(isNaN(coords[1]));
<add> },
<add> "Inversion works for non-zero translation": function() {
<add> var azimuthal = d3.geo.azimuthal().mode("stereographic").translate([123, 99]).scale(100),
<add> coords = azimuthal([0, 85]),
<add> lonlat = azimuthal.invert(coords);
<add> assert.inDelta(lonlat[0], 0, 1e-6);
<add> assert.inDelta(lonlat[1], 85, 1e-6);
<add> }
<ide> }
<ide> });
<ide> | 5 |
Ruby | Ruby | remove extra whitespace | fda1863e1a8c120294c56482631d8254ad6125ff | <ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
<ide> def test_creation_respects_hash_condition
<ide> # in Oracle '' is saved as null therefore need to save ' ' in not null column
<ide> post = categories(:general).post_with_conditions.build(body: " ")
<ide>
<del> assert post.save
<del> assert_equal "Yet Another Testing Title", post.title
<add> assert post.save
<add> assert_equal "Yet Another Testing Title", post.title
<ide>
<ide> # in Oracle '' is saved as null therefore need to save ' ' in not null column
<ide> another_post = categories(:general).post_with_conditions.create(body: " ")
<ide>
<del> assert_predicate another_post, :persisted?
<del> assert_equal "Yet Another Testing Title", another_post.title
<add> assert_predicate another_post, :persisted?
<add> assert_equal "Yet Another Testing Title", another_post.title
<ide> end
<ide>
<ide> def test_distinct_after_the_fact
<ide> def test_include_checks_if_record_exists_if_target_not_loaded
<ide> developer = project.developers.first
<ide>
<ide> project.reload
<del> assert_not_predicate project.developers, :loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> assert_queries(1) do
<ide> assert_includes project.developers, developer
<ide> end
<del> assert_not_predicate project.developers, :loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> end
<ide>
<ide> def test_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> project = projects(:active_record)
<ide> developer = Developer.create name: "Bryan", salary: 50_000
<ide>
<del> assert_not_predicate project.developers, :loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> assert ! project.developers.include?(developer)
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_find_all
<ide> def test_find_each
<ide> firm = companies(:first_firm)
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries(4) do
<ide> firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
<ide> end
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_each_with_conditions
<ide> def test_find_each_with_conditions
<ide> end
<ide> end
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_in_batches
<ide> firm = companies(:first_firm)
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries(2) do
<ide> firm.clients.find_in_batches(batch_size: 2) do |clients|
<ide> clients.each { |c| assert_equal firm.id, c.firm_id }
<ide> end
<ide> end
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_all_sanitized
<ide> def test_delete_all_association_with_primary_key_deletes_correct_records
<ide> def test_creation_respects_hash_condition
<ide> ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
<ide>
<del> assert ms_client.save
<del> assert_equal "Microsoft", ms_client.name
<add> assert ms_client.save
<add> assert_equal "Microsoft", ms_client.name
<ide>
<ide> another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
<ide>
<del> assert_predicate another_ms_client, :persisted?
<del> assert_equal "Microsoft", another_ms_client.name
<add> assert_predicate another_ms_client, :persisted?
<add> assert_equal "Microsoft", another_ms_client.name
<ide> end
<ide>
<ide> def test_clearing_without_initial_access
<ide> def test_include_checks_if_record_exists_if_target_not_loaded
<ide> client = firm.clients.first
<ide>
<ide> firm.reload
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> assert_queries(1) do
<ide> assert_equal true, firm.clients.include?(client)
<ide> end
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> firm = companies(:first_firm)
<ide> client = Client.create!(name: "Not Associated")
<ide>
<del> assert_not_predicate firm.clients, :loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> assert_equal false, firm.clients.include?(client)
<ide> end
<ide>
<ide> def test_calling_one_should_defer_to_collection_if_using_a_block
<ide>
<ide> def test_calling_one_should_return_false_if_zero
<ide> firm = companies(:another_firm)
<del> assert_not_predicate firm.clients_like_ms, :one?
<add> assert_not_predicate firm.clients_like_ms, :one?
<ide> assert_equal 0, firm.clients_like_ms.size
<ide> end
<ide>
<ide> def test_calling_one_should_return_true_if_one
<ide>
<ide> def test_calling_one_should_return_false_if_more_than_one
<ide> firm = companies(:first_firm)
<del> assert_not_predicate firm.clients, :one?
<add> assert_not_predicate firm.clients, :one?
<ide> assert_equal 3, firm.clients.size
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_build_respects_hash_condition
<ide>
<ide> def test_create_respects_hash_condition
<ide> account = companies(:first_firm).create_account_limit_500_with_hash_conditions
<del> assert_predicate account, :persisted?
<add> assert_predicate account, :persisted?
<ide> assert_equal 500, account.credit_limit
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/join_model_test.rb
<ide> def test_has_many_through_include_checks_if_record_exists_if_target_not_loaded
<ide> category = david.categories.first
<ide>
<ide> david.reload
<del> assert_not_predicate david.categories, :loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> assert_queries(1) do
<ide> assert_includes david.categories, category
<ide> end
<del> assert_not_predicate david.categories, :loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> end
<ide>
<ide> def test_has_many_through_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> david = authors(:david)
<ide> category = Category.create!(name: "Not Associated")
<ide>
<del> assert_not_predicate david.categories, :loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> assert ! david.categories.include?(category)
<ide> end
<ide>
<ide><path>activerecord/test/cases/enum_test.rb
<ide> def self.name; "Book"; end
<ide> end
<ide>
<ide> test "query state by predicate with custom suffix" do
<del> assert_predicate @book, :medium_to_read?
<add> assert_predicate @book, :medium_to_read?
<ide> assert_not_predicate @book, :easy_to_read?
<ide> assert_not_predicate @book, :hard_to_read?
<ide> end
<ide> def self.name; "Book"; end
<ide> test "update enum attributes with custom suffix" do
<ide> @book.medium_to_read!
<ide> assert_not_predicate @book, :easy_to_read?
<del> assert_predicate @book, :medium_to_read?
<add> assert_predicate @book, :medium_to_read?
<ide> assert_not_predicate @book, :hard_to_read?
<ide>
<ide> @book.easy_to_read!
<del> assert_predicate @book, :easy_to_read?
<add> assert_predicate @book, :easy_to_read?
<ide> assert_not_predicate @book, :medium_to_read?
<ide> assert_not_predicate @book, :hard_to_read?
<ide>
<ide> @book.hard_to_read!
<ide> assert_not_predicate @book, :easy_to_read?
<ide> assert_not_predicate @book, :medium_to_read?
<del> assert_predicate @book, :hard_to_read?
<add> assert_predicate @book, :hard_to_read?
<ide> end
<ide>
<ide> test "uses default status when no status is provided in fixtures" do
<ide><path>activerecord/test/cases/nested_attributes_test.rb
<ide> def test_should_take_a_hash_and_assign_the_attributes_to_the_associated_models
<ide> def test_should_not_load_association_when_updating_existing_records
<ide> @pirate.reload
<ide> @pirate.send(association_setter, [{ id: @child_1.id, name: "Grace OMalley" }])
<del> assert_not_predicate @pirate.send(@association_name), :loaded?
<add> assert_not_predicate @pirate.send(@association_name), :loaded?
<ide>
<ide> @pirate.save
<del> assert_not_predicate @pirate.send(@association_name), :loaded?
<add> assert_not_predicate @pirate.send(@association_name), :loaded?
<ide> assert_equal "Grace OMalley", @child_1.reload.name
<ide> end
<ide>
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> def test_increment_updates_timestamps
<ide> def test_destroy_all
<ide> conditions = "author_name = 'Mary'"
<ide> topics_by_mary = Topic.all.merge!(where: conditions, order: "id").to_a
<del> assert_not_empty topics_by_mary
<add> assert_not_empty topics_by_mary
<ide>
<ide> assert_difference("Topic.count", -topics_by_mary.size) do
<ide> destroyed = Topic.where(conditions).destroy_all.sort_by(&:id)
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_scoped_first
<ide> 2.times { assert_equal "The First Topic", topics.first.title }
<ide> end
<ide>
<del> assert_not_predicate topics, :loaded?
<add> assert_not_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_loaded_first
<ide> def test_delete_all
<ide> davids = Author.where(name: "David")
<ide>
<ide> assert_difference("Author.count", -1) { davids.delete_all }
<del> assert_not_predicate davids, :loaded?
<add> assert_not_predicate davids, :loaded?
<ide> end
<ide>
<ide> def test_delete_all_loaded
<ide> def test_size
<ide> posts = Post.all
<ide>
<ide> assert_queries(1) { assert_equal 11, posts.size }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_size_with_limit
<ide> posts = Post.limit(10)
<ide>
<ide> assert_queries(1) { assert_equal 10, posts.size }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_size_with_zero_limit
<ide> posts = Post.limit(0)
<ide>
<ide> assert_no_queries { assert_equal 0, posts.size }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> posts.load # force load
<ide> assert_no_queries { assert_equal 0, posts.size }
<ide> def test_empty_with_zero_limit
<ide> posts = Post.limit(0)
<ide>
<ide> assert_no_queries { assert_equal true, posts.empty? }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_count_complex_chained_relations
<ide> def test_empty
<ide> posts = Post.all
<ide>
<ide> assert_queries(1) { assert_equal false, posts.empty? }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> no_posts = posts.where(title: "")
<ide> assert_queries(1) { assert_equal true, no_posts.empty? }
<del> assert_not_predicate no_posts, :loaded?
<add> assert_not_predicate no_posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_empty_complex_chained_relations
<ide> posts = Post.select("comments_count").where("id is not null").group("author_id").where("comments_count > 0")
<ide>
<ide> assert_queries(1) { assert_equal false, posts.empty? }
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> no_posts = posts.where(title: "")
<ide> assert_queries(1) { assert_equal true, no_posts.empty? }
<del> assert_not_predicate no_posts, :loaded?
<add> assert_not_predicate no_posts, :loaded?
<ide> end
<ide>
<ide> def test_any
<ide> def test_any
<ide>
<ide> assert_queries(3) do
<ide> assert posts.any? # Uses COUNT()
<del> assert_not_predicate posts.where(id: nil), :any?
<add> assert_not_predicate posts.where(id: nil), :any?
<ide>
<ide> assert posts.any? { |p| p.id > 0 }
<ide> assert ! posts.any? { |p| p.id <= 0 }
<ide> def test_many_with_limits
<ide> posts = Post.all
<ide>
<ide> assert_predicate posts, :many?
<del> assert_not_predicate posts.limit(1), :many?
<add> assert_not_predicate posts.limit(1), :many?
<ide> end
<ide>
<ide> def test_none?
<ide> def test_none?
<ide> assert ! posts.none? # Uses COUNT()
<ide> end
<ide>
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> assert_queries(1) do
<ide> assert posts.none? { |p| p.id < 0 }
<ide> def test_one
<ide> assert ! posts.one? # Uses COUNT()
<ide> end
<ide>
<del> assert_not_predicate posts, :loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> assert_queries(1) do
<ide> assert ! posts.one? { |p| p.id < 3 }
<ide><path>activesupport/test/cache/behaviors/cache_store_version_behavior.rb
<ide> def test_exist_with_model_supporting_cache_version
<ide> m1v2 = ModelWithKeyAndVersion.new("model/1", 2)
<ide>
<ide> @cache.write(m1v1, "bar")
<del> assert @cache.exist?(m1v1)
<add> assert @cache.exist?(m1v1)
<ide> assert_not @cache.fetch(m1v2)
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/date_time_ext_test.rb
<ide> def test_formatted_offset_with_local
<ide> end
<ide>
<ide> def test_compare_with_time
<del> assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59)
<del> assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59)
<add> assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1))
<ide> end
<ide>
<ide> def test_compare_with_datetime
<del> assert_equal 1, DateTime.civil(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<del> assert_equal 0, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, DateTime.civil(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<add> assert_equal 0, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
<ide> end
<ide>
<ide> def test_compare_with_time_with_zone
<del> assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<del> assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<ide> assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
<ide> end
<ide>
<ide> def test_compare_with_string
<del> assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59).to_s
<del> assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
<add> assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59).to_s
<add> assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
<ide> assert_equal(-1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1).to_s)
<ide> assert_nil DateTime.civil(2000) <=> "Invalid as Time"
<ide> end
<ide>
<ide> def test_compare_with_integer
<del> assert_equal 1, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440587
<del> assert_equal 0, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440588
<add> assert_equal 1, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440587
<add> assert_equal 0, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440588
<ide> assert_equal(-1, DateTime.civil(1970, 1, 1, 12, 0, 0) <=> 2440589)
<ide> end
<ide>
<ide> def test_compare_with_float
<del> assert_equal 1, DateTime.civil(1970) <=> 2440586.5
<del> assert_equal 0, DateTime.civil(1970) <=> 2440587.5
<add> assert_equal 1, DateTime.civil(1970) <=> 2440586.5
<add> assert_equal 0, DateTime.civil(1970) <=> 2440587.5
<ide> assert_equal(-1, DateTime.civil(1970) <=> 2440588.5)
<ide> end
<ide>
<ide> def test_compare_with_rational
<del> assert_equal 1, DateTime.civil(1970) <=> Rational(4881173, 2)
<del> assert_equal 0, DateTime.civil(1970) <=> Rational(4881175, 2)
<add> assert_equal 1, DateTime.civil(1970) <=> Rational(4881173, 2)
<add> assert_equal 0, DateTime.civil(1970) <=> Rational(4881175, 2)
<ide> assert_equal(-1, DateTime.civil(1970) <=> Rational(4881177, 2))
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_formatted_offset_with_local
<ide> end
<ide>
<ide> def test_compare_with_time
<del> assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999)
<del> assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999)
<add> assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0, 001))
<ide> end
<ide>
<ide> def test_compare_with_datetime
<del> assert_equal 1, Time.utc(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<del> assert_equal 0, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, Time.utc(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<add> assert_equal 0, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
<ide> end
<ide>
<ide> def test_compare_with_time_with_zone
<del> assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<del> assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<ide> assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
<ide> end
<ide>
<ide> def test_compare_with_string
<del> assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999).to_s
<del> assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
<add> assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999).to_s
<add> assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0).to_s
<ide> assert_equal(-1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1, 0).to_s)
<ide> assert_nil Time.utc(2000) <=> "Invalid as Time"
<ide> end
<ide> def test_eql?
<ide> end
<ide>
<ide> def test_minus_with_time_with_zone
<del> assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone["UTC"])
<ide> end
<ide>
<ide> def test_minus_with_datetime
<del> assert_equal 86_400.0, Time.utc(2000, 1, 2) - DateTime.civil(2000, 1, 1)
<add> assert_equal 86_400.0, Time.utc(2000, 1, 2) - DateTime.civil(2000, 1, 1)
<ide> end
<ide>
<ide> def test_time_created_with_local_constructor_cannot_represent_times_during_hour_skipped_by_dst
<ide><path>activesupport/test/core_ext/time_with_zone_test.rb
<ide> def test_rfc2822
<ide> end
<ide>
<ide> def test_compare_with_time
<del> assert_equal 1, @twz <=> Time.utc(1999, 12, 31, 23, 59, 59)
<del> assert_equal 0, @twz <=> Time.utc(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, @twz <=> Time.utc(1999, 12, 31, 23, 59, 59)
<add> assert_equal 0, @twz <=> Time.utc(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, @twz <=> Time.utc(2000, 1, 1, 0, 0, 1))
<ide> end
<ide>
<ide> def test_compare_with_datetime
<del> assert_equal 1, @twz <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<del> assert_equal 0, @twz <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<add> assert_equal 1, @twz <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
<add> assert_equal 0, @twz <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
<ide> assert_equal(-1, @twz <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
<ide> end
<ide>
<ide> def test_compare_with_time_with_zone
<del> assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<del> assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone["UTC"])
<add> assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone["UTC"])
<ide> assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone["UTC"]))
<ide> end
<ide>
<ide> def test_minus_with_duration
<ide> end
<ide>
<ide> def test_minus_with_time
<del> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 1)
<del> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 1)
<add> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 1)
<add> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 1)
<ide> end
<ide>
<ide> def test_minus_with_time_precision
<del> assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
<del> assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
<add> assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
<add> assert_equal 86_399.999999998, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["Hawaii"]) - Time.utc(2000, 1, 2, 0, 0, 0, Rational(1, 1000))
<ide> end
<ide>
<ide> def test_minus_with_time_with_zone
<ide> def test_minus_with_time_with_zone
<ide> def test_minus_with_time_with_zone_precision
<ide> twz1 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0, Rational(1, 1000)), ActiveSupport::TimeZone["UTC"])
<ide> twz2 = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"])
<del> assert_equal 86_399.999999998, twz2 - twz1
<add> assert_equal 86_399.999999998, twz2 - twz1
<ide> end
<ide>
<ide> def test_minus_with_datetime
<del> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<add> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<ide> end
<ide>
<ide> def test_minus_with_datetime_precision
<del> assert_equal 86_399.999999999, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<add> assert_equal 86_399.999999999, ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 23, 59, 59, Rational(999999999, 1000)), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<ide> end
<ide>
<ide> def test_minus_with_wrapped_datetime
<del> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 1)
<del> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<add> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - Time.utc(2000, 1, 1)
<add> assert_equal 86_400.0, ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone["UTC"]) - DateTime.civil(2000, 1, 1)
<ide> end
<ide>
<ide> def test_plus_and_minus_enforce_spring_dst_rules
<ide><path>activesupport/test/notifications_test.rb
<ide> def test_events_are_initialized_with_details
<ide> time = Time.now
<ide> event = event(:foo, time, time + 0.01, random_id, {})
<ide>
<del> assert_equal :foo, event.name
<del> assert_equal time, event.time
<add> assert_equal :foo, event.name
<add> assert_equal time, event.time
<ide> assert_in_delta 10.0, event.duration, 0.00001
<ide> end
<ide>
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> test "Rails.application#env_config exists and include some existing parameters" do
<ide> make_basic_app
<ide>
<del> assert_equal app.env_config["action_dispatch.parameter_filter"], app.config.filter_parameters
<del> assert_equal app.env_config["action_dispatch.show_exceptions"], app.config.action_dispatch.show_exceptions
<del> assert_equal app.env_config["action_dispatch.logger"], Rails.logger
<del> assert_equal app.env_config["action_dispatch.backtrace_cleaner"], Rails.backtrace_cleaner
<del> assert_equal app.env_config["action_dispatch.key_generator"], Rails.application.key_generator
<add> assert_equal app.env_config["action_dispatch.parameter_filter"], app.config.filter_parameters
<add> assert_equal app.env_config["action_dispatch.show_exceptions"], app.config.action_dispatch.show_exceptions
<add> assert_equal app.env_config["action_dispatch.logger"], Rails.logger
<add> assert_equal app.env_config["action_dispatch.backtrace_cleaner"], Rails.backtrace_cleaner
<add> assert_equal app.env_config["action_dispatch.key_generator"], Rails.application.key_generator
<ide> end
<ide>
<ide> test "config.colorize_logging default is true" do
<ide><path>railties/test/application/middleware/cache_test.rb
<ide> def test_cache_works_with_etags_private
<ide> etag = last_response.headers["ETag"]
<ide>
<ide> get "/expires/expires_etag", { private: true }, { "HTTP_IF_NONE_MATCH" => etag }
<del> assert_equal "miss", last_response.headers["X-Rack-Cache"]
<add> assert_equal "miss", last_response.headers["X-Rack-Cache"]
<ide> assert_not_equal body, last_response.body
<ide> end
<ide>
<ide> def test_cache_works_with_last_modified_private
<ide> last = last_response.headers["Last-Modified"]
<ide>
<ide> get "/expires/expires_last_modified", { private: true }, { "HTTP_IF_MODIFIED_SINCE" => last }
<del> assert_equal "miss", last_response.headers["X-Rack-Cache"]
<add> assert_equal "miss", last_response.headers["X-Rack-Cache"]
<ide> assert_not_equal body, last_response.body
<ide> end
<ide> end | 15 |
PHP | PHP | use getcookies() and add test for emitting cookies | 30fc50028d7da38ea88e0a6a4b50e6d97ad803d4 | <ide><path>src/Http/ResponseEmitter.php
<ide> protected function emitStatusLine(ResponseInterface $response)
<ide> protected function emitHeaders(ResponseInterface $response)
<ide> {
<ide> $cookies = [];
<del> if (method_exists($response, 'cookie')) {
<del> $cookies = $response->cookie();
<add> if (method_exists($response, 'getCookies')) {
<add> $cookies = $response->getCookies();
<ide> }
<ide>
<ide> foreach ($response->getHeaders() as $name => $values) {
<ide><path>tests/TestCase/Http/ResponseEmitterTest.php
<ide> namespace Cake\Test\TestCase;
<ide>
<ide> use Cake\Http\CallbackStream;
<add>use Cake\Http\Response;
<ide> use Cake\Http\ResponseEmitter;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\Response;
<ide> use Zend\Diactoros\ServerRequestFactory;
<ide> use Zend\Diactoros\Stream;
<ide>
<ide> public function testEmitNoContentResponse()
<ide> $this->assertEquals($expected, $GLOBALS['mockedHeaders']);
<ide> }
<ide>
<add> /**
<add> * Test emitting responses with array cookes
<add> *
<add> * @return void
<add> */
<add> public function testEmitResponseArrayCookies()
<add> {
<add> $response = (new Response())
<add> ->withCookie('simple', ['value' => 'val', 'secure' => true])
<add> ->withAddedHeader('Set-Cookie', 'google=not=nice;Path=/accounts; HttpOnly')
<add> ->withHeader('Content-Type', 'text/plain');
<add> $response->getBody()->write('ok');
<add>
<add> ob_start();
<add> $this->emitter->emit($response);
<add> $out = ob_get_clean();
<add>
<add> $this->assertEquals('ok', $out);
<add> $expected = [
<add> 'HTTP/1.1 200 OK',
<add> 'Content-Type: text/plain'
<add> ];
<add> $this->assertEquals($expected, $GLOBALS['mockedHeaders']);
<add> $expected = [
<add> [
<add> 'name' => 'simple',
<add> 'value' => 'val',
<add> 'path' => '/',
<add> 'expire' => 0,
<add> 'domain' => '',
<add> 'secure' => true,
<add> 'httponly' => false
<add> ],
<add> [
<add> 'name' => 'google',
<add> 'value' => 'not=nice',
<add> 'path' => '/accounts',
<add> 'expire' => 0,
<add> 'domain' => '',
<add> 'secure' => false,
<add> 'httponly' => true
<add> ],
<add> ];
<add> $this->assertEquals($expected, $GLOBALS['mockedCookies']);
<add> }
<add>
<ide> /**
<ide> * Test emitting responses with cookies
<ide> * | 2 |
PHP | PHP | let a collection a macroable | 073ac37b33dec850627363a6ab950ac9f2fd6474 | <ide><path>src/Illuminate/Support/Collection.php
<ide> use JsonSerializable;
<ide> use IteratorAggregate;
<ide> use InvalidArgumentException;
<add>use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide>
<ide> class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
<ide> {
<add> use Macroable;
<add>
<ide> /**
<ide> * The items contained in the collection.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testTakeLast()
<ide> $this->assertEquals(['dayle', 'shawn'], $data->all());
<ide> }
<ide>
<add> public function testMacroable()
<add> {
<add> // Foo() macro : unique values starting with A
<add> Collection::macro('foo', function () {
<add> return $this->filter(function ($item) {
<add> return strpos($item, 'a') === 0;
<add> })
<add> ->unique()
<add> ->values();
<add> });
<add>
<add> $c = new Collection(['a', 'a', 'aa', 'aaa', 'bar']);
<add>
<add> $this->assertSame(['a', 'aa', 'aaa'], $c->foo()->all());
<add> }
<add>
<ide> public function testMakeMethod()
<ide> {
<ide> $collection = Collection::make('foo'); | 2 |
Text | Text | fix typo in new experimental relay support docs | 834546a74fe0db9728cd7d85c264bb652209228e | <ide><path>docs/advanced-features/compiler.md
<ide> module.exports = {
<ide> relay: {
<ide> // This should match relay.config.js
<ide> src: './',
<del> artifactDirectory: './__generated__'
<add> artifactDirectory: './__generated__',
<ide> language: 'typescript',
<ide> },
<ide> }, | 1 |
Text | Text | add some corrections to the translation | dd45e34083aa3521a8ce69ccb2e75897fbb56fd8 | <ide><path>guide/russian/working-in-tech/remote-versus-onsite/index.md
<ide> ---
<ide> title: Remote Versus Onsite
<del>localeTitle: Удаленный пользовательский интерфейс
<add>localeTitle: Удаленная работа или работа в офисе. Что лучше?
<ide> ---
<del>## Удаленный пользовательский интерфейс
<add>## Удаленная работа или работа в офисе. Что лучше?
<ide>
<del>Существуют две основные среды работы: на месте и удаленно.
<add>Существуют два основных типа рабочих мест: работа в офисе и удаленное рабочее место.
<ide>
<del>### Работа на месте
<add>### Работа в офисе
<ide>
<del>Работа на месте - это то, о чем вы могли подумать, когда думаете о работе 9-5. Когда вы находитесь на месте, вы можете находиться в офисе вашей компании или в офисе клиента. В любом случае, вы находитесь в том же физическом месте, что и остальные люди, с которыми вы работаете.
<add>Работа в офисе - это то, что можно назвать работой с 9 до 5. Когда вы работаете на официальном рабочем месте, вы можете находиться в офисе вашей компании или в офисе клиента. В любом случае, вы находитесь в том же физическом месте, что и остальные люди, с которыми вы работаете.
<ide>
<ide> ### Удаленная работа
<ide>
<del>Удаленная работа возникает, когда члены команды работают в разных физических местах. Вы можете работать в любом месте: в вашем доме (без коммутирования!), В совместном рабочем пространстве (иногда оплачивается вашим работодателем) или даже в Таиланде. Часто ваше единственное ограничение заключается в том, что у вас есть доступ в Интернет.
<add>Удаленная работа это форма занятости, когда члены команды работают в разных физических местах. Вы можете работать в любом месте: в вашем доме (не нужно никуда ехать!), в коворкинге (иногда оплачивается вашим работодателем) или даже в Таиланде. Зачастую ваше единственное ограничение - доступ к интернету.
<ide>
<del>Поскольку личное общение происходит реже (если вообще), удаленные команды часто больше полагаются на коммуникационное программное обеспечение, такое как [Slack](https://slack.com/) и [Skype](https://www.skype.com/) .
<add>Поскольку личное общение происходит реже, если вообще происходит, то удаленные команды часто больше полагаются на коммуникационное программное обеспечение, такое как [Slack](https://slack.com/) и [Skype](https://www.skype.com/) .
<ide>
<del>Удаленные команды могут проводить регулярные отступления компаний, чтобы члены команды могли встретиться и пообщаться.
<add>Удаленные команды иногда проводят корпоративы и тренинги, чтобы члены команды могли встретиться и пообщаться.
<ide>
<ide> ### «В промежутке»
<ide>
<del>Некоторые компании работают на 100%, а некоторые из них на 100% удалены. Но нет ничего необычного в том, чтобы найти компании или команды, которые позволяют вам работать удаленно через день или два из недели. Это позволяет вам испытать некоторые преимущества удаленной работы, не будучи постоянно удаленными.
<add>Некоторые компании работают на 100% из офиса, а некоторые из них работают на 100% удаленно. Но нет ничего необычного в том, чтобы найти компанию или команду, которая позволит день или два в неделю работать удаленно. Это предоставляет возможность узнать преимущества удаленной работы, не будучи постоянно на удаленке.
<ide>
<ide> Удаленная работа может стать отличным инструментом для бизнеса как план на случай непредвиденных обстоятельств в случае ненастной погоды или стихийного бедствия.
<ide>
<del>Некоторые компании также имеют физический офис, где вы можете работать, если хотите, но позволяете вам работать везде. В последнее время от крупных компаний, таких как IBM, появилось больше движений, направленных на возвращение сотрудников на место работы. Тем не менее, многие крупные организации по-прежнему очень гибкие и готовы позволить вам работать дома или в другом удобном месте.
<add>Некоторые компании также имеют физический офис, где вы можете работать, если хотите, но позволяет вам работать где угодно. В последнее время от крупных компаний, таких как IBM, появилось больше движений, направленных на возвращение сотрудников в офисы. Тем не менее, многие крупные организации по-прежнему очень гибкие и готовы дать вам возможность работать дома или в другом удобном месте.
<ide>
<ide> ### Несколько команд
<ide>
<del>Более крупные компании могут иметь разную версию «промежуточный», где у них есть несколько разных команд, работающих на месте, но в разных местах. Например, команда, работающая на месте в Нью-Йорке и другая команда, работающая на месте в Чикаго. Вы можете общаться с другими членами команды в офисе, но вы также используете удаленные рабочие методы (Slack, Skype и т. Д.), Чтобы оставаться в контакте и в синхронизации с другими командами. Все команды могут работать над одним и тем же проектом или разрабатывать что-то независимо от того же приложения или платформы.
<add>Более крупные компании могут иметь тип «смешанных» команд, где сотрудники работают в офисах, но в разных местах. Например, команда, работающая в офисе в Нью-Йорке и другая команда, работающая в Чикагском офисе. Можно общаться с другими членами команды в офисе, но также используются методы удаленной работы (Slack, Skype и т. Д.), Чтобы оставаться в контакте и в синхронизации с другими командами. Все команды могут работать над одним и тем же проектом или разрабатывать что-то независимо от того же приложения или платформы.
<ide>
<ide> ### Дополнительная информация:
<ide>
<del>Куинси Ларсон по экономике работы удаленно: [средний](https://medium.freecodecamp.org/the-economics-of-working-remotely-28d4173e16e2)
<ide>\ No newline at end of file
<add>Куинси Ларсон по экономике удаленной работы: [средний](https://medium.freecodecamp.org/the-economics-of-working-remotely-28d4173e16e2) | 1 |
PHP | PHP | fix error with postgres | b3cd6ac682daeac2a37fb460b0a89707748062ba | <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function testBelongsToManyAssociationWithExpressionConditions()
<ide> $table->belongsToMany('Tags', [
<ide> 'foreignKey' => 'article_id',
<ide> 'associationForeignKey' => 'tag_id',
<del> 'conditions' => [new QueryExpression('Tags.name LIKE "tag%"')],
<add> 'conditions' => [new QueryExpression("Tags.name LIKE 'tag%'")],
<ide> 'through' => 'SpecialTags'
<ide> ]);
<ide> $query = $table->find()->matching('Tags', function ($q) { | 1 |
Ruby | Ruby | convert create test to spec | dcb206dd1ef1be09f75774c0f86692ad3e31c679 | <add><path>Library/Homebrew/cask/spec/cask/cli/create_spec.rb
<del><path>Library/Homebrew/cask/test/cask/cli/create_test.rb
<del>require "test_helper"
<add>require "spec_helper"
<ide>
<ide> # monkeypatch for testing
<ide> module Hbc
<ide> def self.editor_commands
<ide> end
<ide>
<ide> describe Hbc::CLI::Create do
<del> before do
<add> before(:each) do
<ide> Hbc::CLI::Create.reset!
<ide> end
<ide>
<del> after do
<add> after(:each) do
<ide> %w[new-cask additional-cask another-cask yet-another-cask local-caff].each do |cask|
<ide> path = Hbc.path(cask)
<ide> path.delete if path.exist?
<ide> def self.editor_commands
<ide>
<ide> it "opens the editor for the specified Cask" do
<ide> Hbc::CLI::Create.run("new-cask")
<del> Hbc::CLI::Create.editor_commands.must_equal [
<add> expect(Hbc::CLI::Create.editor_commands).to eq [
<ide> [Hbc.path("new-cask")],
<ide> ]
<ide> end
<ide>
<ide> it "drops a template down for the specified Cask" do
<ide> Hbc::CLI::Create.run("new-cask")
<ide> template = File.read(Hbc.path("new-cask"))
<del> template.must_equal <<-EOS.undent
<add> expect(template).to eq <<-EOS.undent
<ide> cask 'new-cask' do
<ide> version ''
<ide> sha256 ''
<ide> def self.editor_commands
<ide>
<ide> it "throws away additional Cask arguments and uses the first" do
<ide> Hbc::CLI::Create.run("additional-cask", "another-cask")
<del> Hbc::CLI::Create.editor_commands.must_equal [
<add> expect(Hbc::CLI::Create.editor_commands).to eq [
<ide> [Hbc.path("additional-cask")],
<ide> ]
<ide> end
<ide>
<ide> it "throws away stray options" do
<ide> Hbc::CLI::Create.run("--notavalidoption", "yet-another-cask")
<del> Hbc::CLI::Create.editor_commands.must_equal [
<add> expect(Hbc::CLI::Create.editor_commands).to eq [
<ide> [Hbc.path("yet-another-cask")],
<ide> ]
<ide> end
<ide>
<ide> it "raises an exception when the Cask already exists" do
<del> lambda {
<add> expect {
<ide> Hbc::CLI::Create.run("basic-cask")
<del> }.must_raise Hbc::CaskAlreadyCreatedError
<add> }.to raise_error(Hbc::CaskAlreadyCreatedError)
<ide> end
<ide>
<ide> it "allows creating Casks that are substrings of existing Casks" do
<ide> Hbc::CLI::Create.run("local-caff")
<del> Hbc::CLI::Create.editor_commands.must_equal [
<add> expect(Hbc::CLI::Create.editor_commands).to eq [
<ide> [Hbc.path("local-caff")],
<ide> ]
<ide> end
<ide>
<ide> describe "when no Cask is specified" do
<ide> it "raises an exception" do
<del> lambda {
<add> expect {
<ide> Hbc::CLI::Create.run
<del> }.must_raise Hbc::CaskUnspecifiedError
<add> }.to raise_error(Hbc::CaskUnspecifiedError)
<ide> end
<ide> end
<ide>
<ide> describe "when no Cask is specified, but an invalid option" do
<ide> it "raises an exception" do
<del> lambda {
<add> expect {
<ide> Hbc::CLI::Create.run("--notavalidoption")
<del> }.must_raise Hbc::CaskUnspecifiedError
<add> }.to raise_error(Hbc::CaskUnspecifiedError)
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix missing `onlongpress` gestures | 5ca1d8f260bfb64111a6ba39f76a0a935829c0f2 | <ide><path>Libraries/Pressability/Pressability.js
<ide> export default class Pressability {
<ide> event: PressEvent,
<ide> ): void {
<ide> if (isTerminalSignal(signal)) {
<add> this._touchActivatePosition = null;
<ide> this._cancelLongPressDelayTimeout();
<ide> }
<ide>
<ide><path>Libraries/Pressability/__tests__/Pressability-test.js
<ide> describe('Pressability', () => {
<ide> jest.advanceTimersByTime(1);
<ide> expect(config.onLongPress).toBeCalled();
<ide> });
<del> });
<ide>
<del> // TODO: onLongPressShouldCancelPress tests
<add> it('is called if touch moves within 10dp', () => {
<add> mockUIManagerMeasure();
<add> const {config, handlers} = createMockPressability();
<add>
<add> handlers.onStartShouldSetResponder();
<add> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderMove(
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> pageX: 0,
<add> pageY: 0,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(130);
<add> handlers.onResponderMove(
<add> // NOTE: Delta from (0, 0) is ~9.9 < 10.
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> pageX: 7,
<add> pageY: 7,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(370);
<add> expect(config.onLongPress).toBeCalled();
<add> });
<add>
<add> it('is not called if touch moves beyond 10dp', () => {
<add> mockUIManagerMeasure();
<add> const {config, handlers} = createMockPressability();
<add>
<add> handlers.onStartShouldSetResponder();
<add> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderMove(
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> pageX: 0,
<add> pageY: 0,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(130);
<add> handlers.onResponderMove(
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> // NOTE: Delta from (0, 0) is ~10.6 > 10.
<add> pageX: 7,
<add> pageY: 8,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(370);
<add> expect(config.onLongPress).not.toBeCalled();
<add> });
<add>
<add> it('is called independent of preceding long touch gesture', () => {
<add> mockUIManagerMeasure();
<add> const {config, handlers} = createMockPressability();
<add>
<add> handlers.onStartShouldSetResponder();
<add> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderMove(
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> pageX: 0,
<add> pageY: 0,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(500);
<add> expect(config.onLongPress).toHaveBeenCalledTimes(1);
<add> handlers.onResponderRelease(createMockPressEvent('onResponderRelease'));
<add>
<add> // Subsequent long touch gesture should not carry over previous state.
<add> handlers.onStartShouldSetResponder();
<add> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderMove(
<add> // NOTE: Delta from (0, 0) is ~10.6 > 10, but should not matter.
<add> createMockPressEvent({
<add> registrationName: 'onResponderMove',
<add> pageX: 7,
<add> pageY: 8,
<add> }),
<add> );
<add>
<add> jest.advanceTimersByTime(500);
<add> expect(config.onLongPress).toHaveBeenCalledTimes(2);
<add> });
<add> });
<ide>
<ide> describe('onPress', () => {
<ide> it('is called even when `measure` does not finish', () => { | 2 |
PHP | PHP | remove valid password | 8734c47fff3fe51cd80d48cfde65bedfbc14a81f | <ide><path>tests/Validation/ValidationPasswordRuleTest.php
<ide> public function testUncompromised()
<ide> '123456',
<ide> 'password',
<ide> 'welcome',
<del> 'ninja',
<ide> 'abc123',
<ide> '123456789',
<ide> '12345678', | 1 |
PHP | PHP | fix tests for postgres | bbb829a2a7cc8715fdbf2ea51afc77ad3d3c47ac | <ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testCountWithSubselect()
<ide> $counter->select([
<ide> 'total' => $counter->func()->count('*')
<ide> ])
<del> ->where(['ArticlesTags.tag_id' => 1])
<del> ->where(['ArticlesTags.article_id = Articles.id']);
<add> ->where([
<add> 'ArticlesTags.tag_id' => 1,
<add> 'ArticlesTags.article_id' => new IdentifierExpression('Articles.id')
<add> ]);
<ide>
<ide> $result = $table->find('all')
<ide> ->select([
<ide> public function testCountWithExpressions()
<ide> $table = TableRegistry::get('Articles');
<ide> $query = $table->find();
<ide> $query->select([
<del> 'admin' => $query->func()->concat(
<del> ['Articles.title' => 'literal', 'test'],
<add> 'title' => $query->func()->concat(
<add> ['title' => 'literal', 'test'],
<ide> ['string']
<ide> ),
<ide> ]);
<del> $query->where(['Articles.id' => 1]);
<add> $query->where(['id' => 1]);
<ide> $this->assertCount(1, $query->all());
<ide> $this->assertEquals(1, $query->count());
<ide> } | 1 |
Go | Go | move some integration tests to integration-cli | 69f9d488dc915d8b02827658ccc5a7c48136dc03 | <ide><path>integration-cli/docker_cli_rm_test.go
<ide> package main
<ide> import (
<ide> "os"
<ide> "os/exec"
<add> "strings"
<ide> "testing"
<ide> )
<ide>
<ide> func TestRemoveContainerWithStopAndKill(t *testing.T) {
<ide> logDone("rm - with --stop=true and --kill=true")
<ide> }
<ide>
<add>func TestContainerOrphaning(t *testing.T) {
<add> dockerfile1 := `FROM busybox:latest
<add> ENTRYPOINT ["/bin/true"]`
<add> img := "test-container-orphaning"
<add> dockerfile2 := `FROM busybox:latest
<add> ENTRYPOINT ["/bin/true"]
<add> MAINTAINER Integration Tests`
<add>
<add> // build first dockerfile
<add> img1, err := buildImage(img, dockerfile1, true)
<add> if err != nil {
<add> t.Fatalf("Could not build image %s: %v", img, err)
<add> }
<add> // run container on first image
<add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", img)); err != nil {
<add> t.Fatalf("Could not run image %s: %v: %s", img, err, out)
<add> }
<add> // rebuild dockerfile with a small addition at the end
<add> if _, err := buildImage(img, dockerfile2, true); err != nil {
<add> t.Fatalf("Could not rebuild image %s: %v", img, err)
<add> }
<add> // try to remove the image, should error out.
<add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rmi", img)); err == nil {
<add> t.Fatalf("Expected to error out removing the image, but succeeded: %s", out)
<add> }
<add> // check if we deleted the first image
<add> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "images", "-q", "--no-trunc"))
<add> if err != nil {
<add> t.Fatalf("%v: %s", err, out)
<add> }
<add> if !strings.Contains(out, img1) {
<add> t.Fatal("Orphaned container (could not find '%s' in docker images): %s", img1, out)
<add> }
<add>
<add> deleteAllContainers()
<add>
<add> logDone("rm - container orphaning")
<add>}
<add>
<add>func TestDeleteTagWithExistingContainers(t *testing.T) {
<add> container := "test-delete-tag"
<add> newtag := "busybox:newtag"
<add> bb := "busybox:latest"
<add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "tag", bb, newtag)); err != nil {
<add> t.Fatalf("Could not tag busybox: %v: %s", err, out)
<add> }
<add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", container, bb, "/bin/true")); err != nil {
<add> t.Fatalf("Could not run busybox: %v: %s", err, out)
<add> }
<add> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rmi", newtag))
<add> if err != nil {
<add> t.Fatalf("Could not remove tag %s: %v: %s", newtag, err, out)
<add> }
<add> if d := strings.Count(out, "Untagged: "); d != 1 {
<add> t.Fatalf("Expected 1 untagged entry got %d: %q", d, out)
<add> }
<add>
<add> deleteAllContainers()
<add>
<add> logDone("rm - delete tag with existing containers")
<add>
<add>}
<add>
<ide> func createRunningContainer(t *testing.T, name string) {
<ide> cmd := exec.Command(dockerBinary, "run", "-dt", "--name", name, "busybox", "top")
<ide> if _, err := runCommand(cmd); err != nil {
<ide><path>integration/commands_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/client"
<ide> "github.com/docker/docker/daemon"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/term"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide> func TestRunCidFileCleanupIfEmpty(t *testing.T) {
<ide> <-c
<ide> })
<ide> }
<del>
<del>func TestContainerOrphaning(t *testing.T) {
<del>
<del> // setup a temporary directory
<del> tmpDir, err := ioutil.TempDir("", "project")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tmpDir)
<del>
<del> // setup a CLI and server
<del> cli := client.NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr, nil)
<del> defer cleanup(globalEngine, t)
<del> srv := mkServerFromEngine(globalEngine, t)
<del>
<del> // closure to build something
<del> buildSomething := func(template string, image string) string {
<del> dockerfile := path.Join(tmpDir, "Dockerfile")
<del> replacer := strings.NewReplacer("{IMAGE}", unitTestImageID)
<del> contents := replacer.Replace(template)
<del> ioutil.WriteFile(dockerfile, []byte(contents), 0x777)
<del> if err := cli.CmdBuild("-t", image, tmpDir); err != nil {
<del> t.Fatal(err)
<del> }
<del> job := globalEngine.Job("image_get", image)
<del> info, _ := job.Stdout.AddEnv()
<del> if err := job.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del> return info.Get("Id")
<del> }
<del>
<del> // build an image
<del> imageName := "orphan-test"
<del> template1 := `
<del> from {IMAGE}
<del> cmd ["/bin/echo", "holla"]
<del> `
<del> img1 := buildSomething(template1, imageName)
<del>
<del> // create a container using the fist image
<del> if err := cli.CmdRun(imageName); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> // build a new image that splits lineage
<del> template2 := `
<del> from {IMAGE}
<del> cmd ["/bin/echo", "holla"]
<del> expose 22
<del> `
<del> buildSomething(template2, imageName)
<del>
<del> // remove the second image by name
<del> resp := engine.NewTable("", 0)
<del> if err := srv.DeleteImage(imageName, resp, true, false, false); err == nil {
<del> t.Fatal("Expected error, got none")
<del> }
<del>
<del> // see if we deleted the first image (and orphaned the container)
<del> for _, i := range resp.Data {
<del> if img1 == i.Get("Deleted") {
<del> t.Fatal("Orphaned image with container")
<del> }
<del> }
<del>
<del>}
<ide><path>integration/server_test.go
<ide> func TestImagesFilter(t *testing.T) {
<ide> t.Fatal("incorrect number of matches returned")
<ide> }
<ide> }
<del>
<del>// Regression test for being able to untag an image with an existing
<del>// container
<del>func TestDeleteTagWithExistingContainers(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> defer nuke(mkDaemonFromEngine(eng, t))
<del>
<del> srv := mkServerFromEngine(eng, t)
<del>
<del> // Tag the image
<del> if err := eng.Job("tag", unitTestImageID, "utest", "tag1").Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> // Create a container from the image
<del> config, _, _, err := runconfig.Parse([]string{unitTestImageID, "echo test"}, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> id := createNamedTestContainer(eng, config, t, "testingtags")
<del> if id == "" {
<del> t.Fatal("No id returned")
<del> }
<del>
<del> job := srv.Eng.Job("containers")
<del> job.SetenvBool("all", true)
<del> outs, err := job.Stdout.AddListTable()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := job.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if len(outs.Data) != 1 {
<del> t.Fatalf("Expected 1 container got %d", len(outs.Data))
<del> }
<del>
<del> // Try to remove the tag
<del> imgs := engine.NewTable("", 0)
<del> if err := srv.DeleteImage("utest:tag1", imgs, true, false, false); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if len(imgs.Data) != 1 {
<del> t.Fatalf("Should only have deleted one untag %d", len(imgs.Data))
<del> }
<del>
<del> if untag := imgs.Data[0].Get("Untagged"); untag != "utest:tag1" {
<del> t.Fatalf("Expected %s got %s", unitTestImageID, untag)
<del> }
<del>} | 3 |
Javascript | Javascript | add multielement tag to appropriate directives | e7662ebc311be71a8511eb5c519c5008afc58f2a | <ide><path>src/ng/directive/ngIf.js
<ide> * @ngdoc directive
<ide> * @name ngIf
<ide> * @restrict A
<add> * @multiElement
<ide> *
<ide> * @description
<ide> * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
<ide><path>src/ng/directive/ngRepeat.js
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ngRepeat
<add> * @multiElement
<ide> *
<ide> * @description
<ide> * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
<ide><path>src/ng/directive/ngShowHide.js
<ide> var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ngShow
<add> * @multiElement
<ide> *
<ide> * @description
<ide> * The `ngShow` directive shows or hides the given HTML element based on the expression
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> /**
<ide> * @ngdoc directive
<ide> * @name ngHide
<add> * @multiElement
<ide> *
<ide> * @description
<ide> * The `ngHide` directive shows or hides the given HTML element based on the expression | 3 |
PHP | PHP | use mb_strlen instead of strlen | b5761c5c9918bd4070c9566654f7cdfe387dcbc0 | <ide><path>src/Utility/Security.php
<ide> protected static function _constantEquals($hmac, $compare)
<ide> if (function_exists('hash_equals')) {
<ide> return hash_equals($hmac, $compare);
<ide> }
<del> $hashLength = strlen($hmac);
<del> $compareLength = strlen($compare);
<add> $hashLength = mb_strlen($hmac, '8bit');
<add> $compareLength = mb_strlen($compare, '8bit');
<ide> if ($hashLength !== $compareLength) {
<ide> return false;
<ide> } | 1 |
Java | Java | move noopcache to a top-level public class | ffa728c23c2b9b1d5630e879680e46dc54ed9f93 | <ide><path>spring-context/src/main/java/org/springframework/cache/support/NoOpCache.java
<add>/*
<add> * Copyright 2002-2016 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.cache.support;
<add>
<add>import java.util.concurrent.Callable;
<add>
<add>import org.springframework.cache.Cache;
<add>
<add>/**
<add> * A no operation {@link Cache} implementation suitable
<add> * for disabling caching.
<add> *
<add> * <p>Will simply accept any items into the cache not actually storing them.
<add> *
<add> * @author Costin Leau
<add> * @author Stephane Nicoll
<add> * @since 4.3.4
<add> */
<add>public class NoOpCache implements Cache {
<add>
<add> private final String name;
<add>
<add> /**
<add> * Create a {@link NoOpCache} instance with the specified name
<add> * @param name the name of the cache
<add> */
<add> public NoOpCache(String name) {
<add> this.name = name;
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> }
<add>
<add> @Override
<add> public void evict(Object key) {
<add> }
<add>
<add> @Override
<add> public ValueWrapper get(Object key) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public <T> T get(Object key, Class<T> type) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public <T> T get(Object key, Callable<T> valueLoader) {
<add> try {
<add> return valueLoader.call();
<add> }
<add> catch (Exception ex) {
<add> throw new ValueRetrievalException(key, valueLoader, ex);
<add> }
<add> }
<add>
<add> @Override
<add> public String getName() {
<add> return this.name;
<add> }
<add>
<add> @Override
<add> public Object getNativeCache() {
<add> return null;
<add> }
<add>
<add> @Override
<add> public void put(Object key, Object value) {
<add> }
<add>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, Object value) {
<add> return null;
<add> }
<add>
<add>}
<ide><path>spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.java
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.Set;
<del>import java.util.concurrent.Callable;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.ConcurrentMap;
<ide>
<ide> public Collection<String> getCacheNames() {
<ide> }
<ide> }
<ide>
<del>
<del> private static class NoOpCache implements Cache {
<del>
<del> private final String name;
<del>
<del> public NoOpCache(String name) {
<del> this.name = name;
<del> }
<del>
<del> @Override
<del> public void clear() {
<del> }
<del>
<del> @Override
<del> public void evict(Object key) {
<del> }
<del>
<del> @Override
<del> public ValueWrapper get(Object key) {
<del> return null;
<del> }
<del>
<del> @Override
<del> public <T> T get(Object key, Class<T> type) {
<del> return null;
<del> }
<del>
<del> @Override
<del> public <T> T get(Object key, Callable<T> valueLoader) {
<del> try {
<del> return valueLoader.call();
<del> }
<del> catch (Exception ex) {
<del> throw new ValueRetrievalException(key, valueLoader, ex);
<del> }
<del> }
<del>
<del> @Override
<del> public String getName() {
<del> return this.name;
<del> }
<del>
<del> @Override
<del> public Object getNativeCache() {
<del> return null;
<del> }
<del>
<del> @Override
<del> public void put(Object key, Object value) {
<del> }
<del>
<del> @Override
<del> public ValueWrapper putIfAbsent(Object key, Object value) {
<del> return null;
<del> }
<del> }
<del>
<ide> } | 2 |
Python | Python | remove old unused pickle test | 0cdb6ea61df487f3622dc1ebb0a222571b7ddfc0 | <ide><path>spacy/tests/parser/test_parser_pickle.py
<del>import pytest
<del>
<del>import pickle
<del>import cloudpickle
<del>
<del>import io
<del>
<del>
<del>#@pytest.mark.models
<del>#def test_pickle(EN):
<del># file_ = io.BytesIO()
<del># cloudpickle.dump(EN.parser, file_)
<del>#
<del># file_.seek(0)
<del>#
<del># loaded = pickle.load(file_)
<del># | 1 |
Text | Text | fix typo in plugins doc | b20d11133d18dad09f2778c9ac0c3ee362221e39 | <ide><path>guides/source/plugins.md
<ide> $ bin/rails plugin new yaffle
<ide> See usage and options by asking for help:
<ide>
<ide> ```bash
<del>$ bin/rails plugin --help
<add>$ bin/rails plugin new --help
<ide> ```
<ide>
<ide> Testing Your Newly Generated Plugin | 1 |
Text | Text | remove conflict line [ci skip] | e317e5e1e198147aa86dc04da5962c7277601967 | <ide><path>actioncable/README.md
<ide> The Ruby side of things is built on top of [websocket-driver](https://github.com
<ide>
<ide>
<ide> ## Deployment
<del>>>>>>>> b94b04b1d11b1d095918b8bae2b6b5f76f092cf7
<ide>
<ide> $ gem install actioncable
<ide> | 1 |
Python | Python | remove incorrect comment about flattening | 18eb65228d0e3eca03796e9c30744974e53e2997 | <ide><path>numpy/lib/recfunctions.py
<ide> def zip_dtype(seqarrays, flatten=False):
<ide> else:
<ide> for a in seqarrays:
<ide> current = a.dtype
<del> if current.names and len(current.names) <= 1:
<del> # special case - dtypes of 0 or 1 field are flattened
<add> if current.names is not None and len(current.names) == 1:
<add> # special case - dtypes of 1 field are flattened
<ide> newdtype.extend(get_fieldspec(current))
<ide> else:
<ide> newdtype.append(('', current)) | 1 |
Javascript | Javascript | fix cache invalidation in httpuriplugin | a6099c4ff96d25f2475c7e92f1d7e6ef991ac7d7 | <ide><path>lib/schemes/HttpUriPlugin.js
<ide> class HttpUriPlugin {
<ide> logger.debug(
<ide> `GET ${url} [${res.statusCode}] -> ${partialResult.location}`
<ide> );
<add> // we should follow redirect and not store partial result
<add> return callback(null, {
<add> ...partialResult,
<add> storeLock,
<add> storeCache,
<add> fresh: true,
<add> etag: undefined,
<add> validUntil: undefined
<add> });
<ide> } else {
<ide> logger.debug(
<ide> `GET ${url} [${res.statusCode}] ${Math.ceil(
<ide><path>test/ConfigCacheTestCases.longtest.js
<ide> describeCases({
<ide> // Pack got invalid because of write to: TerserWebpackPlugin|bundle0.js
<ide> category: "assets",
<ide> test: "delete-asset"
<del> },
<del> {
<del> // Pack got invalid because of write to: webpack.HttpUriPlugin|https://raw.githubusercontent.com//webpack//webpack//main/CODE_OF_CONDUCT.md
<del> category: "asset-modules",
<del> test: "http-url"
<ide> }
<ide> ],
<ide> filter: [logErrors.PERSISTENCE_CACHE_INVALIDATE_ERROR] | 2 |
Mixed | Ruby | handle invalid utf-8 strings when html escaping | 05a2a6a0c5ac2384e52df9b8c2aa81352a51d7c7 | <ide><path>activesupport/CHANGELOG.md
<add>* Handle invalid UTF-8 strings when HTML escaping
<add>
<add> Use `ActiveSupport::Multibyte::Unicode.tidy_bytes` to handle invalid UTF-8
<add> strings in `ERB::Util.unwrapped_html_escape` and `ERB::Util.html_escape_once`.
<add> Prevents user-entered input passed from a querystring into a form field from
<add> causing invalid byte sequence errors.
<add>
<add> *Grey Baker*
<add>
<ide> * Fix a range of values for parameters of the Time#change
<ide>
<ide> *Nikolay Kondratyev*
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> def unwrapped_html_escape(s) # :nodoc:
<ide> if s.html_safe?
<ide> s
<ide> else
<del> s.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
<add> ActiveSupport::Multibyte::Unicode.tidy_bytes(s).gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
<ide> end
<ide> end
<ide> module_function :unwrapped_html_escape
<ide> def unwrapped_html_escape(s) # :nodoc:
<ide> # html_escape_once('<< Accept & Checkout')
<ide> # # => "<< Accept & Checkout"
<ide> def html_escape_once(s)
<del> result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
<add> result = ActiveSupport::Multibyte::Unicode.tidy_bytes(s.to_s).gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
<ide> s.html_safe? ? result.html_safe : result
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def to_s
<ide> end
<ide>
<ide> test "ERB::Util.html_escape should correctly handle invalid UTF-8 strings" do
<del> string = [192, 60].pack('CC')
<del> expected = 192.chr + "<"
<add> string = "\251 <"
<add> expected = "© <"
<ide> assert_equal expected, ERB::Util.html_escape(string)
<ide> end
<ide>
<ide> def to_s
<ide> assert_equal escaped_string, ERB::Util.html_escape_once(string)
<ide> assert_equal escaped_string, ERB::Util.html_escape_once(escaped_string)
<ide> end
<add>
<add> test "ERB::Util.html_escape_once should correctly handle invalid UTF-8 strings" do
<add> string = "\251 <"
<add> expected = "© <"
<add> assert_equal expected, ERB::Util.html_escape_once(string)
<add> end
<ide> end
<ide>
<ide> class StringExcludeTest < ActiveSupport::TestCase | 3 |
Javascript | Javascript | remove useless function declaration | e515a0eced1d3d9a91d760fd8e538e0e7d3fbd04 | <ide><path>tools/doc/preprocess.js
<ide> const includeData = {};
<ide>
<ide> function preprocess(inputFile, input, cb) {
<ide> input = stripComments(input);
<del> processIncludes(inputFile, input, function(err, data) {
<del> if (err) return cb(err);
<del>
<del> cb(null, data);
<del> });
<add> processIncludes(inputFile, input, cb);
<ide> }
<ide>
<ide> function stripComments(input) { | 1 |
Go | Go | implement docker start with standalone client lib | 962b2d8b9b0201db2132ec17f06513e33ad419d0 | <ide><path>api/client/client.go
<ide> type apiClient interface {
<ide> ContainerRename(containerID, newContainerName string) error
<ide> ContainerRestart(containerID string, timeout int) error
<ide> ContainerStatPath(containerID, path string) (types.ContainerPathStat, error)
<add> ContainerStart(containerID string) error
<ide> ContainerStop(containerID string, timeout int) error
<ide> ContainerTop(containerID string, arguments []string) (types.ContainerProcessList, error)
<ide> ContainerUnpause(containerID string) error
<ide><path>api/client/lib/container_start.go
<add>package lib
<add>
<add>// ContainerStart sends a request to the docker daemon to start a container.
<add>func (cli *Client) ContainerStart(containerID string) error {
<add> resp, err := cli.post("/containers/"+containerID+"/start", nil, nil, nil)
<add> ensureReaderClosed(resp)
<add> return err
<add>}
<ide><path>api/client/start.go
<ide> package client
<ide>
<ide> import (
<del> "encoding/json"
<ide> "fmt"
<ide> "io"
<del> "net/url"
<ide> "os"
<add> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/types"
<ide> func (cli *DockerCli) CmdStart(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> var (
<del> cErr chan error
<del> tty bool
<del> )
<del>
<ide> if *attach || *openStdin {
<add> // We're going to attach to a container.
<add> // 1. Ensure we only have one container.
<ide> if cmd.NArg() > 1 {
<ide> return fmt.Errorf("You cannot start and attach multiple containers at once.")
<ide> }
<ide>
<del> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
<add> // 2. Attach to the container.
<add> containerID := cmd.Arg(0)
<add> c, err := cli.client.ContainerInspect(containerID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> defer serverResp.body.Close()
<del>
<del> var c types.ContainerJSON
<del> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil {
<del> return err
<add> if !c.Config.Tty {
<add> sigc := cli.forwardAllSignals(containerID)
<add> defer signal.StopCatch(sigc)
<ide> }
<ide>
<del> tty = c.Config.Tty
<del>
<del> if !tty {
<del> sigc := cli.forwardAllSignals(cmd.Arg(0))
<del> defer signal.StopCatch(sigc)
<add> options := types.ContainerAttachOptions{
<add> ContainerID: containerID,
<add> Stream: true,
<add> Stdin: *openStdin && c.Config.OpenStdin,
<add> Stdout: true,
<add> Stderr: true,
<ide> }
<ide>
<ide> var in io.ReadCloser
<del>
<del> v := url.Values{}
<del> v.Set("stream", "1")
<del>
<del> if *openStdin && c.Config.OpenStdin {
<del> v.Set("stdin", "1")
<add> if options.Stdin {
<ide> in = cli.in
<ide> }
<ide>
<del> v.Set("stdout", "1")
<del> v.Set("stderr", "1")
<add> resp, err := cli.client.ContainerAttach(options)
<add> if err != nil {
<add> return err
<add> }
<add> defer resp.Close()
<ide>
<del> hijacked := make(chan io.Closer)
<del> // Block the return until the chan gets closed
<del> defer func() {
<del> logrus.Debugf("CmdStart() returned, defer waiting for hijack to finish.")
<del> if _, ok := <-hijacked; ok {
<del> fmt.Fprintln(cli.err, "Hijack did not finish (chan still open)")
<del> }
<del> cli.in.Close()
<del> }()
<del> cErr = promise.Go(func() error {
<del> return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, hijacked, nil)
<add> cErr := promise.Go(func() error {
<add> return cli.holdHijackedConnection(c.Config.Tty, in, cli.out, cli.err, resp)
<ide> })
<ide>
<del> // Acknowledge the hijack before starting
<ide> select {
<del> case closer := <-hijacked:
<del> // Make sure that the hijack gets closed when returning (results
<del> // in closing the hijack chan and freeing server's goroutines)
<del> if closer != nil {
<del> defer closer.Close()
<del> }
<ide> case err := <-cErr:
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<del> }
<ide>
<del> var encounteredError error
<del> var errNames []string
<del> for _, name := range cmd.Args() {
<del> _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, nil))
<del> if err != nil {
<del> if !*attach && !*openStdin {
<del> // attach and openStdin is false means it could be starting multiple containers
<del> // when a container start failed, show the error message and start next
<del> fmt.Fprintf(cli.err, "%s\n", err)
<del> errNames = append(errNames, name)
<del> } else {
<del> encounteredError = err
<del> }
<del> } else {
<del> if !*attach && !*openStdin {
<del> fmt.Fprintf(cli.out, "%s\n", name)
<del> }
<add> // 3. Start the container.
<add> if err := cli.client.ContainerStart(containerID); err != nil {
<add> return err
<ide> }
<del> }
<ide>
<del> if len(errNames) > 0 {
<del> encounteredError = fmt.Errorf("Error: failed to start containers: %v", errNames)
<del> }
<del> if encounteredError != nil {
<del> return encounteredError
<del> }
<del>
<del> if *openStdin || *attach {
<del> if tty && cli.isTerminalOut {
<del> if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
<add> // 4. Wait for attachement to break.
<add> if c.Config.Tty && cli.isTerminalOut {
<add> if err := cli.monitorTtySize(containerID, false); err != nil {
<ide> fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err)
<ide> }
<ide> }
<ide> if attchErr := <-cErr; attchErr != nil {
<ide> return attchErr
<ide> }
<del> _, status, err := getExitCode(cli, cmd.Arg(0))
<add> _, status, err := getExitCode(cli, containerID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if status != 0 {
<ide> return Cli.StatusError{StatusCode: status}
<ide> }
<add> } else {
<add> // We're not going to attach to anything.
<add> // Start as many containers as we want.
<add> return cli.startContainersWithoutAttachments(cmd.Args())
<add> }
<add>
<add> return nil
<add>}
<add>
<add>func (cli *DockerCli) startContainersWithoutAttachments(containerIDs []string) error {
<add> var failedContainers []string
<add> for _, containerID := range containerIDs {
<add> if err := cli.client.ContainerStart(containerID); err != nil {
<add> fmt.Fprintf(cli.err, "%s\n", err)
<add> failedContainers = append(failedContainers, containerID)
<add> } else {
<add> fmt.Fprintf(cli.out, "%s\n", containerID)
<add> }
<add> }
<add>
<add> if len(failedContainers) > 0 {
<add> return fmt.Errorf("Error: failed to start containers: %v", strings.Join(failedContainers, ", "))
<ide> }
<ide> return nil
<ide> } | 3 |
PHP | PHP | fix invalid value of htmlspecialchars argument | c2fac8f2c2bbb1473a2f4a29089eeff127424834 | <ide><path>src/Core/functions.php
<ide> function h($text, $double = true, $charset = null)
<ide> 'Use the 3rd argument instead.'
<ide> );
<ide> $charset = $double;
<add> $double = true;
<ide> }
<ide>
<ide> return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset ?: $defaultCharset, $double); | 1 |
Text | Text | add html5up to recommended design links | 0c3f1aa846e8d04398fc7b93af462430d080c2be | <ide><path>README.md
<ide> Recommended Design
<ide> - [3D Dropdown Menu](http://soulwire.github.io/Makisu/) - CSS3 3D Dropdown Menu that folds and unfolds.
<ide> - [Creative Link Effects](http://tympanus.net/Development/CreativeLinkEffects/) - Beautiful link effects in CSS.
<ide> - [Medium Scroll Effect](http://codepen.io/andreasstorm/pen/pyjEh) - Fade in/out header background image as you scroll.
<add>- [HTML5UP](http://html5up.net/) - Beautifully designed HTML templates.
<ide>
<ide> Recommended Node.js Libraries
<ide> ----------------------------- | 1 |
PHP | PHP | remove unnecessary return | 09e452923604c6c5e622bf3e4305ce711d02b763 | <ide><path>src/Cache/Engine/FileEngine.php
<ide> protected function _clearDirectory(string $path): void
<ide> *
<ide> * @param string $key The key to decrement
<ide> * @param int $offset The number to offset
<del> * @return false
<add> * @return void
<ide> * @throws \LogicException
<ide> */
<ide> public function decrement(string $key, int $offset = 1)
<ide> {
<ide> throw new LogicException('Files cannot be atomically decremented.');
<del>
<del> // phpcs:ignore
<del> return false;
<ide> }
<ide>
<ide> /**
<ide> * Not implemented
<ide> *
<ide> * @param string $key The key to increment
<ide> * @param int $offset The number to offset
<del> * @return false
<add> * @return void
<ide> * @throws \LogicException
<ide> */
<ide> public function increment(string $key, int $offset = 1)
<ide> {
<ide> throw new LogicException('Files cannot be atomically incremented.');
<del>
<del> // phpcs:ignore
<del> return false;
<ide> }
<ide>
<ide> /** | 1 |
Java | Java | fix checkstyle violations | e80a23d6ad93eaab11a1869ef1407e729138e672 | <ide><path>spring-web/src/main/java/org/springframework/web/util/ServletRequestPathUtils.java
<ide> public static boolean hasCachedPath(ServletRequest request) {
<ide> * supports a servletPath as an additional prefix to be omitted from
<ide> * {@link #pathWithinApplication()}.
<ide> */
<del> private static class ServletRequestPath implements RequestPath {
<add> private static final class ServletRequestPath implements RequestPath {
<ide>
<ide> private final RequestPath requestPath;
<ide>
<ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletMapping.java
<ide> public String toString() {
<ide> "mappingMatch=" + mappingMatch + "]";
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>} | 2 |
Python | Python | raise error on single input | 4e571172a210612bdeba1db0135b7d5fbc44ee0c | <ide><path>numpy/lib/function_base.py
<ide> def meshgrid(*xi, **kwargs):
<ide>
<ide> """
<ide> copy_ = kwargs.get('copy', True)
<add>
<add> if len(xi) < 2:
<add> msg = 'meshgrid() takes 2 or more arguments (%d given)' % int(len(xi) > 0)
<add> raise ValueError(msg)
<add>
<ide> args = np.atleast_1d(*xi)
<ide> ndim = len(args)
<ide>
<del> if ndim < 2:
<del> msg = 'meshgrid() takes 2 or more arguments (%d given)' % int(ndim > 0)
<del> raise TypeError(msg)
<del>
<ide> sparse = kwargs.get('sparse', False)
<ide> indexing = kwargs.get('indexing', 'xy')
<ide>
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_simple(self):
<ide> [5, 5, 5],
<ide> [6, 6, 6],
<ide> [7, 7, 7]])))
<add>
<add> def test_single_input(self):
<add> assert_raises(ValueError, meshgrid, np.arange(5))
<add>
<ide> def test_indexing(self):
<ide> [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], indexing='ij')
<ide> assert_(all(X == array([[1, 1, 1, 1], | 2 |
Ruby | Ruby | move logic from leaves to formula | f95e1729a2d95d8dc80dadc8c05851d534a72f74 | <ide><path>Library/Homebrew/cmd/leaves.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "formula"
<del>require "tab"
<ide> require "cli/parser"
<ide>
<ide> module Homebrew
<ide> def leaves_args
<ide> def leaves
<ide> leaves_args.parse
<ide>
<del> installed = Formula.installed.sort
<del> deps_of_installed = installed.flat_map(&:runtime_formula_dependencies)
<del> leaves = installed.map(&:full_name) - deps_of_installed.map(&:full_name)
<add> leaves = Formula.installed_non_deps.map(&:full_name).sort
<ide> leaves.each(&method(:puts))
<ide> end
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def self.installed
<ide> end.uniq(&:name)
<ide> end
<ide>
<add> # An array of installed {Formula} that are dependencies of other installed {Formula}
<add> # @private
<add> def self.installed_deps(formulae=installed)
<add> formulae.flat_map(&:runtime_formula_dependencies).uniq(&:name)
<add> end
<add>
<add> # An array of all installed {Formula} that are not dependencies of other installed {Formula}
<add> # @private
<add> def self.installed_non_deps(formulae=installed)
<add> formulae - installed_deps(formulae)
<add> end
<add>
<ide> def self.installed_with_alias_path(alias_path)
<ide> return [] if alias_path.nil?
<ide>
<ide><path>Library/Homebrew/test/cmd/leaves_spec.rb
<ide> end
<ide>
<ide> describe "brew leaves", :integration_test do
<del> it "prints all Formulae that are not dependencies of other Formulae" do
<del> setup_test_formula "foo"
<del> setup_test_formula "bar"
<del> (HOMEBREW_CELLAR/"foo/0.1/somedir").mkpath
<add> context "when there are no installed Formulae" do
<add> it "prints nothing" do
<add> setup_test_formula "foo"
<add> setup_test_formula "bar"
<add>
<add> expect { brew "leaves" }
<add> .to not_to_output.to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<add> end
<add> end
<add>
<add> context "when there are only installed Formulae without dependencies" do
<add> it "prints all installed Formulae" do
<add> setup_test_formula "foo"
<add> setup_test_formula "bar"
<add> (HOMEBREW_CELLAR/"foo/0.1/somedir").mkpath
<add>
<add> expect { brew "leaves" }
<add> .to output("foo\n").to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<add> end
<add> end
<ide>
<del> expect { brew "leaves" }
<del> .to output("foo\n").to_stdout
<del> .and not_to_output.to_stderr
<del> .and be_a_success
<add> context "when there are installed Formulae" do
<add> it "prints all installed Formulae that are not dependencies of another installed Formula" do
<add> setup_test_formula "foo"
<add> setup_test_formula "bar"
<add> (HOMEBREW_CELLAR/"foo/0.1/somedir").mkpath
<add> (HOMEBREW_CELLAR/"bar/0.1/somedir").mkpath
<add>
<add> expect { brew "leaves" }
<add> .to output("bar\n").to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<add> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/formula_spec.rb
<ide> end
<ide> end
<ide>
<add> describe "::installed_deps" do
<add> let(:formula_is_dep) do
<add> formula "foo" do
<add> url "foo-1.1"
<add> end
<add> end
<add>
<add> let(:formula_with_deps) do
<add> formula "bar" do
<add> url "bar-1.0"
<add> end
<add> end
<add>
<add> let(:formulae) do
<add> [
<add> formula_with_deps,
<add> formula_is_dep
<add> ]
<add> end
<add>
<add> before do
<add> allow(formula_with_deps).to receive(:runtime_formula_dependencies).and_return([ formula_is_dep ])
<add> end
<add>
<add> specify "without formulae parameter" do
<add> allow(described_class).to receive(:installed).and_return(formulae)
<add>
<add> expect(described_class.installed_deps)
<add> .to eq([formula_is_dep])
<add> end
<add>
<add> specify "with formulae parameter" do
<add> expect(described_class.installed_deps(formulae))
<add> .to eq([formula_is_dep])
<add> end
<add> end
<add>
<add> describe "::installed_non_deps" do
<add> let(:formula_is_dep) do
<add> formula "foo" do
<add> url "foo-1.1"
<add> end
<add> end
<add>
<add> let(:formula_with_deps) do
<add> formula "bar" do
<add> url "bar-1.0"
<add> end
<add> end
<add>
<add> let(:formulae) do
<add> [
<add> formula_with_deps,
<add> formula_is_dep
<add> ]
<add> end
<add>
<add> before do
<add> allow(formula_with_deps).to receive(:runtime_formula_dependencies).and_return([ formula_is_dep ])
<add> end
<add>
<add> specify "without formulae parameter" do
<add> allow(described_class).to receive(:installed).and_return(formulae)
<add>
<add> expect(described_class.installed_non_deps)
<add> .to eq([formula_with_deps])
<add> end
<add>
<add> specify "with formulae parameter" do
<add> expect(described_class.installed_non_deps(formulae))
<add> .to eq([formula_with_deps])
<add> end
<add> end
<add>
<ide> describe "::installed_with_alias_path" do
<ide> specify "with alias path with nil" do
<ide> expect(described_class.installed_with_alias_path(nil)).to be_empty | 4 |
Javascript | Javascript | fix internal breakages | f741d338406d518c4f81fada723991b2938b8cc5 | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> if (Platform.OS === 'android') {
<ide> RCTScrollContentView = requireNativeComponent('RCTScrollContentView');
<ide> }
<ide>
<add>export type ScrollResponderType = {
<add> ...ScrollView,
<add> ...typeof ScrollResponder.Mixin,
<add>};
<add>
<ide> type TouchableProps = $ReadOnly<{|
<ide> onTouchStart?: (event: PressEvent) => void,
<ide> onTouchMove?: (event: PressEvent) => void,
<ide> export type Props = $ReadOnly<{|
<ide> * - `false`, deprecated, use 'never' instead
<ide> * - `true`, deprecated, use 'always' instead
<ide> */
<del> keyboardShouldPersistTaps?: ?('always' | 'never' | 'handled' | false | true),
<add> keyboardShouldPersistTaps?: ?('always' | 'never' | 'handled' | true | false),
<ide> /**
<ide> * Called when the momentum scroll starts (scroll which occurs as the ScrollView glides to a stop).
<ide> */
<ide> class ScrollView extends React.Component<Props, State> {
<ide> * implement this method so that they can be composed while providing access
<ide> * to the underlying scroll responder's methods.
<ide> */
<del> getScrollResponder(): {
<del> ...typeof ScrollView,
<del> ...typeof ScrollResponder.Mixin,
<del> } {
<add> getScrollResponder(): ScrollResponderType {
<ide> // $FlowFixMe - overriding type to include ScrollResponder.Mixin
<del> return ((this: any): {
<del> ...typeof ScrollView,
<del> ...typeof ScrollResponder.Mixin,
<del> });
<add> return ((this: any): ScrollResponderType);
<ide> }
<ide>
<ide> getScrollableNode(): ?number {
<ide> class ScrollView extends React.Component<Props, State> {
<ide> * `scrollToEnd({animated: false})` for immediate scrolling.
<ide> * If no options are passed, `animated` defaults to true.
<ide> */
<del> scrollToEnd(options?: {animated?: boolean}) {
<add> scrollToEnd(options?: ?{animated?: boolean}) {
<ide> // Default to true
<ide> const animated = (options && options.animated) !== false;
<ide> this._scrollResponder.scrollResponderScrollToEnd({ | 1 |
Javascript | Javascript | replace string concatenation with template | 438c877fc7e27b48e33f5d412a34d2526dea5842 | <ide><path>test/parallel/test-https-unix-socket-self-signed.js
<ide> common.refreshTmpDir();
<ide> const fs = require('fs');
<ide> const https = require('https');
<ide> const options = {
<del> cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'),
<del> key: fs.readFileSync(common.fixturesDir + '/test_key.pem')
<add> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`),
<add> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`)
<ide> };
<ide>
<ide> const server = https.createServer(options, common.mustCall((req, res) => { | 1 |
Go | Go | fix deadlock on v1 plugin with activate error | f2d384fca6fa08da13fdc01c7991e8e35b081198 | <ide><path>pkg/plugins/plugin_test.go
<ide> package plugins
<ide>
<ide> import (
<add> "errors"
<ide> "path/filepath"
<ide> "runtime"
<ide> "sync"
<ide> func TestPluginAddHandler(t *testing.T) {
<ide> testActive(t, p)
<ide> }
<ide>
<add>func TestPluginWaitBadPlugin(t *testing.T) {
<add> p := &Plugin{activateWait: sync.NewCond(&sync.Mutex{})}
<add> p.activateErr = errors.New("some junk happened")
<add> testActive(t, p)
<add>}
<add>
<ide> func testActive(t *testing.T, p *Plugin) {
<ide> done := make(chan struct{})
<ide> go func() {
<ide><path>pkg/plugins/plugins.go
<ide> func (p *Plugin) activateWithLock() error {
<ide>
<ide> func (p *Plugin) waitActive() error {
<ide> p.activateWait.L.Lock()
<del> for !p.activated() {
<add> for !p.activated() && p.activateErr == nil {
<ide> p.activateWait.Wait()
<ide> }
<ide> p.activateWait.L.Unlock() | 2 |
Java | Java | update spel test to reflect native float support | 59fb67e38dc8781db52a4ac1bc5e96b77e9ddc58 | <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java
<ide> public void numerics() {
<ide>
<ide> checkNumberError("3.4L", SpelMessage.REAL_CANNOT_BE_LONG);
<ide>
<del> // Number is parsed as a float, but immediately promoted to a double
<del> checkNumber("3.5f", 3.5d, Double.class);
<add> checkNumber("3.5f", 3.5f, Float.class);
<ide>
<ide> checkNumber("1.2e3", 1.2e3d, Double.class);
<ide> checkNumber("1.2e+3", 1.2e3d, Double.class); | 1 |
Javascript | Javascript | change build from babylon to babel | 42918f40aabd41a324b5dd10652e078dd2c411e6 | <ide><path>scripts/rollup/build.js
<ide> function getPlugins(
<ide> // Note that this plugin must be called after closure applies DCE.
<ide> isProduction && stripUnusedImports(pureExternalModules),
<ide> // Add the whitespace back if necessary.
<del> shouldStayReadable && prettier({parser: 'babylon'}),
<add> shouldStayReadable && prettier({parser: 'babel'}),
<ide> // License and haste headers, top-level `if` blocks.
<ide> {
<ide> transformBundle(source) {
<ide><path>scripts/shared/__tests__/evalToString-test.js
<ide> 'use strict';
<ide>
<ide> const evalToString = require('../evalToString');
<del>const babylon = require('babylon');
<add>const parser = require('@babel/parser');
<ide>
<del>const parse = source =>
<del> babylon.parse(`(${source});`).program.body[0].expression; // quick way to get an exp node
<add>const parse = source => parser.parse(`(${source});`).program.body[0].expression; // quick way to get an exp node
<ide>
<ide> const parseAndEval = source => evalToString(parse(source));
<ide> | 2 |
Text | Text | add hint to return early pattern for functions | 892232b70e00177d8d4d822186eff0628e19483f | <ide><path>client/src/pages/guide/english/certifications/javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions/index.md
<del>---
<del>title: Return Early Pattern for Functions
<del>---
<add>
<ide> ## Return Early Pattern for Functions
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>Here’s a setup:
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>```javascript
<add>// Setup
<add>function abTest(a, b) {
<add> // Only change code below this line
<add>
<add> // Only change code above this line
<add> return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
<add>}
<add>// Change values below to test your code
<add>abTest(2,2);
<add>```
<add>
<add>We need to modify the function ```abTest``` so that if ```a``` or ```b``` are less than ```0``` the function will immediately exit with a value of ```undefined```.
<add>
<add>We add in body of function simple ```if``` statement, which, under the conditions "if ```a``` or ```b``` are less than ```0``` - immediately exit with a value of ```undefined```":
<add>
<add>```javascript
<add> if (a < 0 || b < 0) {
<add> return undefined;
<add> }
<add>```
<add>
<add>Now, if ```a``` or ```b``` are less than ```0``` - function exit with a value of ```undefined```, in other cases -
<add>
<add>```javascript
<add> return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
<add> }
<add>```
<add>
<add> Here’s a full solution:
<add>
<add> ```javascript
<add> // Setup
<add>function abTest(a, b) {
<add> // Only change code below this line
<add> if (a < 0 || b < 0) {
<add> return undefined;
<add> }
<add>
<add> // Only change code above this line
<add>
<add> return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
<add>}
<add>
<add>// Change values below to test your code
<add>abTest(2,2);
<add> ``` | 1 |
Python | Python | add test for _upload_data | 2a98590120ce4394ed6c34f6f0e32365120330f2 | <ide><path>test/storage/test_base.py
<ide> class BaseStorageTests(unittest.TestCase):
<ide> def setUp(self):
<ide> self.send_called = 0
<ide> StorageDriver.connectionCls.conn_classes = (None, StorageMockHttp)
<del> self.driver = StorageDriver('username', 'key', host='localhost')
<add>
<add> self.driver1 = StorageDriver('username', 'key', host='localhost')
<add> self.driver1.supports_chunked_encoding = True
<add> self.driver2 = StorageDriver('username', 'key', host='localhost')
<add> self.driver2.supports_chunked_encoding = False
<ide>
<ide> def test__upload_object_iterator_must_have_next_method(self):
<ide> class Iterator(object):
<ide> def upload_func(*args, **kwargs):
<ide>
<ide> for value in valid_iterators:
<ide> kwargs['iterator'] = value
<del> self.driver._upload_object(**kwargs)
<add> self.driver1._upload_object(**kwargs)
<ide>
<ide> for value in invalid_iterators:
<ide> kwargs['iterator'] = value
<ide>
<ide> try:
<del> self.driver._upload_object(**kwargs)
<add> self.driver1._upload_object(**kwargs)
<ide> except AttributeError:
<ide> pass
<ide> else:
<ide> def mock_send(data):
<ide>
<ide> # Normal
<ide> success, data_hash, bytes_transferred = \
<del> self.driver._stream_data(response=response, iterator=iterator,
<add> self.driver1._stream_data(response=response, iterator=iterator,
<ide> chunked=False, calculate_hash=True)
<ide>
<ide> self.assertTrue(success)
<ide> def mock_send(data):
<ide>
<ide> # Chunked
<ide> success, data_hash, bytes_transferred = \
<del> self.driver._stream_data(response=response, iterator=iterator,
<add> self.driver1._stream_data(response=response, iterator=iterator,
<ide> chunked=True, calculate_hash=True)
<ide>
<ide> self.assertTrue(success)
<ide> self.assertEqual(data_hash, hashlib.md5('').hexdigest())
<ide> self.assertEqual(bytes_transferred, 0)
<ide> self.assertEqual(self.send_called, 5)
<ide>
<add> def test__upload_data(self):
<add> def mock_send(data):
<add> self.send_called += 1
<add>
<add> response = Mock()
<add> response.connection.connection.send = mock_send
<add>
<add> data = '123456789901234567'
<add> success, data_hash, bytes_transferred = \
<add> self.driver1._upload_data(response=response, data=data,
<add> calculate_hash=True)
<add>
<add> self.assertTrue(success)
<add> self.assertEqual(data_hash, hashlib.md5(data).hexdigest())
<add> self.assertEqual(bytes_transferred, (len(data)))
<add> self.assertEqual(self.send_called, 1)
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 1 |
Java | Java | fix compilation errors when using java 8 | fedb543ceebec02e89c7babec384c1c7c208dae4 | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeou
<ide> * @return a Flowable that emits the item from the source {@link Future}
<ide> * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a>
<ide> */
<add> @SuppressWarnings({ "unchecked", "cast" })
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<ide> public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit, Scheduler scheduler) {
<ide> ObjectHelper.requireNonNull(scheduler, "scheduler is null");
<del> return fromFuture(future, timeout, unit).subscribeOn(scheduler);
<add> return fromFuture((Future<T>)future, timeout, unit).subscribeOn(scheduler);
<ide> }
<ide>
<ide> /**
<ide> public static <T> Flowable<T> fromFuture(Future<? extends T> future, long timeou
<ide> * @return a Flowable that emits the item from the source {@link Future}
<ide> * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a>
<ide> */
<add> @SuppressWarnings({ "cast", "unchecked" })
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<ide> public static <T> Flowable<T> fromFuture(Future<? extends T> future, Scheduler scheduler) {
<ide> ObjectHelper.requireNonNull(scheduler, "scheduler is null");
<del> return fromFuture(future).subscribeOn(scheduler);
<add> return fromFuture((Future<T>)future).subscribeOn(scheduler);
<ide> }
<ide>
<ide> /**
<ide> public static <T, R> Flowable<R> zip(Iterable<? extends Publisher<? extends T>>
<ide> * @return a Flowable that emits the zipped results
<ide> * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
<ide> */
<add> @SuppressWarnings({ "rawtypes", "unchecked", "cast" })
<ide> @CheckReturnValue
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public static <T, R> Flowable<R> zip(Publisher<? extends Publisher<? extends T>> sources,
<ide> final Function<? super Object[], ? extends R> zipper) {
<ide> ObjectHelper.requireNonNull(zipper, "zipper is null");
<del> return fromPublisher(sources).toList().flatMapPublisher(FlowableInternalHelper.<T, R>zipIterable(zipper));
<add> return fromPublisher(sources).toList().flatMapPublisher((Function)FlowableInternalHelper.<T, R>zipIterable(zipper));
<ide> }
<ide>
<ide> /**
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java
<ide> public void accept(GroupedFlowable<Integer, Integer> g) {
<ide> @Test
<ide> public void keySelectorAndDelayError() {
<ide> Flowable.just(1).concatWith(Flowable.<Integer>error(new TestException()))
<del> .groupBy(Functions.identity(), true)
<del> .flatMap(new Function<GroupedFlowable<Object, Integer>, Flowable<Integer>>() {
<add> .groupBy(Functions.<Integer>identity(), true)
<add> .flatMap(new Function<GroupedFlowable<Integer, Integer>, Flowable<Integer>>() {
<ide> @Override
<del> public Flowable<Integer> apply(GroupedFlowable<Object, Integer> g) throws Exception {
<add> public Flowable<Integer> apply(GroupedFlowable<Integer, Integer> g) throws Exception {
<ide> return g;
<ide> }
<ide> })
<ide> public Flowable<Integer> apply(GroupedFlowable<Object, Integer> g) throws Except
<ide> @Test
<ide> public void keyAndValueSelectorAndDelayError() {
<ide> Flowable.just(1).concatWith(Flowable.<Integer>error(new TestException()))
<del> .groupBy(Functions.identity(), Functions.<Integer>identity(), true)
<del> .flatMap(new Function<GroupedFlowable<Object, Integer>, Flowable<Integer>>() {
<add> .groupBy(Functions.<Integer>identity(), Functions.<Integer>identity(), true)
<add> .flatMap(new Function<GroupedFlowable<Integer, Integer>, Flowable<Integer>>() {
<ide> @Override
<del> public Flowable<Integer> apply(GroupedFlowable<Object, Integer> g) throws Exception {
<add> public Flowable<Integer> apply(GroupedFlowable<Integer, Integer> g) throws Exception {
<ide> return g;
<ide> }
<ide> })
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableGroupByTest.java
<ide> public Integer apply(Integer i) {
<ide> @Test
<ide> public void keySelectorAndDelayError() {
<ide> Observable.just(1).concatWith(Observable.<Integer>error(new TestException()))
<del> .groupBy(Functions.identity(), true)
<del> .flatMap(new Function<GroupedObservable<Object, Integer>, ObservableSource<Integer>>() {
<add> .groupBy(Functions.<Integer>identity(), true)
<add> .flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<Integer>>() {
<ide> @Override
<del> public ObservableSource<Integer> apply(GroupedObservable<Object, Integer> g) throws Exception {
<add> public ObservableSource<Integer> apply(GroupedObservable<Integer, Integer> g) throws Exception {
<ide> return g;
<ide> }
<ide> })
<ide> public ObservableSource<Integer> apply(GroupedObservable<Object, Integer> g) thr
<ide> @Test
<ide> public void keyAndValueSelectorAndDelayError() {
<ide> Observable.just(1).concatWith(Observable.<Integer>error(new TestException()))
<del> .groupBy(Functions.identity(), Functions.<Integer>identity(), true)
<del> .flatMap(new Function<GroupedObservable<Object, Integer>, ObservableSource<Integer>>() {
<add> .groupBy(Functions.<Integer>identity(), Functions.<Integer>identity(), true)
<add> .flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<Integer>>() {
<ide> @Override
<del> public ObservableSource<Integer> apply(GroupedObservable<Object, Integer> g) throws Exception {
<add> public ObservableSource<Integer> apply(GroupedObservable<Integer, Integer> g) throws Exception {
<ide> return g;
<ide> }
<ide> }) | 3 |
Python | Python | fix optimizer to work with horovod | 81e1e2489f71e9f0250034492b0d52616a450c77 | <ide><path>pytorch_pretrained_bert/optimization.py
<ide> import math
<ide> import torch
<ide> from torch.optim import Optimizer
<add>from torch.optim.optimizer import required
<ide> from torch.nn.utils import clip_grad_norm_
<ide>
<ide> def warmup_cosine(x, warmup=0.002):
<ide> class BertAdam(Optimizer):
<ide> weight_decay_rate: Weight decay. Default: 0.01
<ide> max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0
<ide> """
<del> def __init__(self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear',
<add> def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear',
<ide> b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01,
<ide> max_grad_norm=1.0):
<del> if not lr >= 0.0:
<add> if lr is not required and lr < 0.0:
<ide> raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
<ide> if schedule not in SCHEDULES:
<ide> raise ValueError("Invalid schedule parameter: {}".format(schedule)) | 1 |
PHP | PHP | remove default routes | 566e768cae2abf0f1123b604149da3aede4431ed | <ide><path>src/Config/routes.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 2.0.0
<del> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<del> */
<del>use Cake\Core\Plugin;
<del>use Cake\Routing\Router;
<del>use Cake\Utility\Inflector;
<del>
<del>/**
<del> * Connects the default, built-in routes, including prefix and plugin routes. The following routes are created
<del> * in the order below:
<del> *
<del> * For each of the Routing.prefixes the following routes are created. Routes containing `:plugin` are only
<del> * created when your application has one or more plugins.
<del> *
<del> * - `/:prefix/:plugin` a plugin shortcut route.
<del> * - `/:prefix/:plugin/:controller`
<del> * - `/:prefix/:plugin/:controller/:action/*`
<del> * - `/:prefix/:controller`
<del> * - `/:prefix/:controller/:action/*`
<del> *
<del> * If plugins are found in your application the following routes are created:
<del> *
<del> * - `/:plugin` a plugin shortcut route.
<del> * - `/:plugin/:controller`
<del> * - `/:plugin/:controller/:action/*`
<del> *
<del> * And lastly the following catch-all routes are connected.
<del> *
<del> * - `/:controller'
<del> * - `/:controller/:action/*'
<del> *
<del> * You can disable the connection of default routes by deleting the require inside APP/Config/routes.php.
<del> */
<del>
<del>$prefixes = Router::prefixes();
<del>$prefixPattern = implode('|', $prefixes);
<del>$plugins = Plugin::loaded();
<del>foreach ($plugins as $key => $value) {
<del> $plugins[$key] = Inflector::underscore($value);
<del>}
<del>$pluginPattern = implode('|', $plugins);
<del>$indexParams = ['action' => 'index'];
<del>$pluginShortMatch = [
<del> 'routeClass' => 'Cake\Routing\Route\PluginShortRoute',
<del> '_name' => '_plugin._controller:index',
<del> 'defaultRoute' => true
<del>];
<del>
<del>if ($prefixPattern && $pluginPattern) {
<del> $match = [
<del> 'prefix' => $prefixPattern,
<del> 'plugin' => $pluginPattern,
<del> 'defaultRoute' => true,
<del> 'routeClass' => 'Cake\Routing\Route\InflectedRoute'
<del> ];
<del> Router::connect('/:prefix/:plugin', $indexParams, $pluginShortMatch + $match);
<del> Router::connect('/:prefix/:plugin/:controller', $indexParams, $match);
<del> Router::connect('/:prefix/:plugin/:controller/:action/*', [], $match);
<del>}
<del>if ($pluginPattern) {
<del> $match = [
<del> 'plugin' => $pluginPattern,
<del> 'defaultRoute' => true,
<del> 'routeClass' => 'Cake\Routing\Route\InflectedRoute'
<del> ];
<del> Router::connect('/:plugin', $indexParams, $pluginShortMatch + $match);
<del> Router::connect('/:plugin/:controller', $indexParams, $match);
<del> Router::connect('/:plugin/:controller/:action/*', [], $match);
<del>}
<del>if ($prefixPattern) {
<del> $match = [
<del> 'prefix' => $prefixPattern,
<del> 'defaultRoute' => true,
<del> 'routeClass' => 'Cake\Routing\Route\InflectedRoute'
<del> ];
<del> Router::connect('/:prefix/:controller', $indexParams, $match);
<del> Router::connect('/:prefix/:controller/:action/*', [], $match);
<del>}
<del>Router::connect('/:controller', ['action' => 'index'], [
<del> 'defaultRoute' => true,
<del> 'routeClass' => 'Cake\Routing\Route\InflectedRoute'
<del>]);
<del>Router::connect('/:controller/:action/*', [], [
<del> 'defaultRoute' => true,
<del> 'routeClass' => 'Cake\Routing\Route\InflectedRoute'
<del>]);
<del>
<del>unset($prefixes, $prefixPattern, $plugins, $pluginPattern, $indexParams, $match);
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> class AuthComponentTest extends TestCase {
<ide> */
<ide> public $fixtures = ['core.user', 'core.auth_user'];
<ide>
<del>/**
<del> * initialized property
<del> *
<del> * @var bool
<del> */
<del> public $initialized = false;
<del>
<ide> /**
<ide> * setUp method
<ide> *
<ide> public function setUp() {
<ide> Configure::write('Security.salt', 'YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
<ide> Configure::write('App.namespace', 'TestApp');
<ide>
<add> Router::scope('/', function($routes) {
<add> $routes->fallbacks();
<add> });
<add>
<ide> $request = new Request();
<ide> $response = $this->getMock('Cake\Network\Response', array('stop'));
<ide>
<ide> public function setUp() {
<ide>
<ide> $this->Auth = new TestAuthComponent($this->Controller->components());
<ide>
<del> $this->initialized = true;
<del> Router::reload();
<del> Router::connect('/:controller/:action/*');
<del>
<ide> $Users = TableRegistry::get('AuthUsers');
<ide> $Users->updateAll(['password' => Security::hash('cake', 'blowfish', false)], []);
<ide> }
<ide> public function testLoginRedirect() {
<ide> 'AuthUsers' => array('id' => '1', 'username' => 'nate')
<ide> ));
<ide>
<del> $this->Auth->request->addParams(Router::parse('Users/login'));
<del> $this->Auth->request->url = 'Users/login';
<add> $this->Auth->request->addParams(Router::parse('users/login'));
<add> $this->Auth->request->url = 'users/login';
<ide> $this->Auth->request->env('HTTP_REFERER', false);
<ide>
<ide> $this->Auth->config('loginRedirect', [
<del> 'controller' => 'pages', 'action' => 'display', 'welcome'
<add> 'controller' => 'pages',
<add> 'action' => 'display',
<add> 'welcome'
<ide> ]);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->Auth->startup($event);
<ide> public function testLoginRedirect() {
<ide> ]);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->Auth->startup($event);
<del> $expected = Router::normalize('/AuthTest/login');
<add> $expected = Router::normalize('/auth_test/login');
<ide> $this->assertEquals($expected, $this->Controller->testUrl);
<ide>
<ide> $this->Auth->session->delete('Auth');
<ide> public function testLoginRedirect() {
<ide>
<ide> // External Direct Login Link
<ide> $this->Auth->session->delete('Auth');
<del> $url = '/AuthTest/login';
<add> $url = '/auth_test/login';
<ide> $this->Auth->request = $this->Controller->request = new Request($url);
<ide> $this->Auth->request->env('HTTP_REFERER', 'http://webmail.example.com/view/message');
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> public function testNoRedirectOn404() {
<ide> */
<ide> public function testAdminRoute() {
<ide> $event = new Event('Controller.startup', $this->Controller);
<del> $pref = Configure::read('Routing.prefixes');
<del> Configure::write('Routing.prefixes', array('admin'));
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<add> Router::prefix('admin', function($routes) {
<add> $routes->fallbacks();
<add> });
<ide>
<ide> $url = '/admin/auth_test/add';
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> public function testAdminRoute() {
<ide> Router::setRequestInfo($this->Auth->request);
<ide>
<ide> $this->Auth->config('loginAction', [
<del> 'prefix' => 'admin', 'controller' => 'auth_test', 'action' => 'login'
<add> 'prefix' => 'admin',
<add> 'controller' => 'auth_test',
<add> 'action' => 'login'
<ide> ]);
<ide>
<ide> $this->Auth->startup($event);
<ide> $this->assertEquals('/admin/auth_test/login', $this->Controller->testUrl);
<del>
<del> Configure::write('Routing.prefixes', $pref);
<ide> }
<ide>
<ide> /**
<ide> public function testAjaxLogin() {
<ide> */
<ide> public function testLoginActionRedirect() {
<ide> $event = new Event('Controller.startup', $this->Controller);
<del> Configure::write('Routing.prefixes', array('admin'));
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<add> Router::prefix('admin', function($routes) {
<add> $routes->fallbacks();
<add> });
<ide>
<ide> $url = '/admin/auth_test/login';
<ide> $request = $this->Auth->request;
<ide> public function testStatelessFollowedByStatefulAuth() {
<ide>
<ide> $this->assertInstanceOf('Cake\Network\Response', $this->Auth->startup($event));
<ide>
<del> $this->assertEquals('/Users/login', $this->Controller->testUrl);
<add> $this->assertEquals('/users/login', $this->Controller->testUrl);
<ide> }
<ide> }
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlParsing() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Router::reload();
<del> require CAKE . 'Config/routes.php';
<add> $this->_connectDefaultRoutes();
<ide> $result = Router::parse('/pages/display/home');
<ide> $expected = array(
<ide> 'plugin' => null,
<ide> public function testParseError() {
<ide> * @dataProvider parseReverseSymmetryData
<ide> */
<ide> public function testParseReverseSymmetry($url) {
<del> require CAKE . 'Config/routes.php';
<add> $this->_connectDefaultRoutes();
<ide> $this->assertSame($url, Router::reverse(Router::parse($url) + array('url' => [])));
<ide> }
<ide>
<ide> public function testRoutingPrefixesSetting() {
<ide> Configure::write('Routing', $restore);
<ide> }
<ide>
<del>/**
<del> * Test prefix routing and plugin combinations
<del> *
<del> * @return void
<del> */
<del> public function testPrefixRoutingAndPlugins() {
<del> Configure::write('Routing.prefixes', array('admin'));
<del> $paths = App::path('Plugin');
<del> Plugin::load(array('TestPlugin'));
<del>
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<del> $request = new Request();
<del> Router::setRequestInfo(
<del> $request->addParams(array(
<del> 'controller' => 'controller',
<del> 'action' => 'action',
<del> 'plugin' => null,
<del> 'prefix' => 'admin'
<del> ))->addPaths(array(
<del> 'base' => '/',
<del> 'here' => '/',
<del> 'webroot' => '/base/',
<del> ))
<del> );
<del>
<del> $result = Router::url(array(
<del> 'plugin' => 'test_plugin',
<del> 'controller' => 'test_plugin',
<del> 'action' => 'index'
<del> ));
<del> $expected = '/admin/test_plugin';
<del> $this->assertEquals($expected, $result);
<del>
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<del> $request = new Request();
<del> Router::setRequestInfo(
<del> $request->addParams(array(
<del> 'plugin' => 'test_plugin',
<del> 'controller' => 'show_tickets',
<del> 'action' => 'edit',
<del> 'pass' => array('6'),
<del> 'prefix' => 'admin',
<del> ))->addPaths(array(
<del> 'base' => '/',
<del> 'here' => '/admin/shows/show_tickets/edit/6',
<del> 'webroot' => '/',
<del> ))
<del> );
<del>
<del> $result = Router::url(array(
<del> 'plugin' => 'test_plugin',
<del> 'controller' => 'show_tickets',
<del> 'action' => 'edit',
<del> 6,
<del> 'prefix' => 'admin'
<del> ));
<del> $expected = '/admin/test_plugin/show_tickets/edit/6';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::url(array(
<del> 'plugin' => 'test_plugin',
<del> 'controller' => 'show_tickets',
<del> 'action' => 'index',
<del> 'prefix' => 'admin'
<del> ));
<del> $expected = '/admin/test_plugin/show_tickets';
<del> $this->assertEquals($expected, $result);
<del> }
<del>
<ide> /**
<ide> * testParseExtensions method
<ide> *
<ide> public function testSetExtensions() {
<ide> Router::parseExtensions('rss', false);
<ide> $this->assertContains('rss', Router::extensions());
<ide>
<del> require CAKE . 'Config/routes.php';
<add> $this->_connectDefaultRoutes();
<ide>
<ide> $result = Router::parse('/posts.rss');
<ide> $this->assertEquals('rss', $result['_ext']);
<ide> public function testSetExtensions() {
<ide> */
<ide> public function testExtensionParsing() {
<ide> Router::parseExtensions('rss', false);
<del> require CAKE . 'Config/routes.php';
<add> $this->_connectDefaultRoutes();
<ide>
<ide> $result = Router::parse('/posts.rss');
<ide> $expected = array(
<ide> public function testExtensionParsing() {
<ide>
<ide> Router::reload();
<ide> Router::parseExtensions(['rss', 'xml'], false);
<del> require CAKE . 'Config/routes.php';
<add> $this->_connectDefaultRoutes();
<ide>
<ide> $result = Router::parse('/posts.xml');
<ide> $expected = array(
<ide> public function testPagesUrlParsing() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Router::reload();
<del> require CAKE . 'Config/routes.php';
<ide> Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
<ide>
<ide> $result = Router::parse('/');
<ide> public function testRegexRouteMatchUrl() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>/**
<del> * test that the required default routes are connected.
<del> *
<del> * @return void
<del> */
<del> public function testConnectDefaultRoutes() {
<del> Plugin::load(array('TestPlugin', 'PluginJs'));
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<del>
<del> $result = Router::url(array('plugin' => 'PluginJs', 'controller' => 'JsFile', 'action' => 'index'));
<del> $this->assertEquals('/plugin_js/js_file', $result);
<del>
<del> $result = Router::parse('/plugin_js/js_file');
<del> $expected = array(
<del> 'plugin' => 'PluginJs', 'controller' => 'JsFile', 'action' => 'index',
<del> 'pass' => []
<del> );
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::url(array('plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index'));
<del> $this->assertEquals('/test_plugin', $result, 'Plugin shortcut route generation failed.');
<del>
<del> $result = Router::parse('/test_plugin');
<del> $expected = array(
<del> 'plugin' => 'TestPlugin',
<del> 'controller' => 'TestPlugin',
<del> 'action' => 'index',
<del> 'pass' => []
<del> );
<del>
<del> $this->assertEquals($expected, $result, 'Plugin shortcut route broken.');
<del> }
<del>
<ide> /**
<ide> * test using a custom route class for route connection
<ide> *
<ide> public function testPluginOptions() {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Connect some fallback routes for testing router behavior.
<add> *
<add> * @return void
<add> */
<add> protected function _connectDefaultRoutes() {
<add> Router::scope('/', function($routes) {
<add> $routes->fallbacks();
<add> });
<add> }
<add>
<ide> }
<ide><path>tests/TestCase/TestSuite/ControllerTestCaseTest.php
<ide> public function setUp() {
<ide> Plugin::load(array('TestPlugin', 'TestPluginTwo'));
<ide>
<ide> $this->Case = $this->getMockForAbstractClass('Cake\TestSuite\ControllerTestCase');
<add> $this->Case->loadRoutes = false;
<add>
<ide> DispatcherFactory::add('Routing');
<ide> DispatcherFactory::add('ControllerFactory');
<del> Router::reload();
<del> require CAKE . 'Config/routes.php';
<add> Router::scope('/', function($routes) {
<add> $routes->fallbacks();
<add> });
<add> Router::prefix('admin', function($routes) {
<add> $routes->plugin('TestPlugin', function ($routes) {
<add> $routes->fallbacks();
<add> });
<add> $routes->fallbacks();
<add> });
<add> Router::plugin('TestPlugin', function($routes) {
<add> $routes->fallbacks();
<add> });
<add> Router::plugin('TestPluginTwo', function($routes) {
<add> $routes->fallbacks();
<add> });
<ide> TableRegistry::clear();
<ide> }
<ide>
<ide> public function testTestAction() {
<ide> * @return void
<ide> */
<ide> public function testActionWithPrefix() {
<del> Configure::write('Routing.prefixes', ['admin']);
<del> Plugin::load('TestPlugin');
<del>
<ide> $result = $this->Case->testAction('/admin/posts/index', ['return' => 'view']);
<ide> $expected = '<h1>Admin Post Index</h1>';
<ide> $this->assertContains($expected, $result);
<ide><path>tests/TestCase/Utility/FolderTest.php
<ide> public function testFind() {
<ide> $this->assertSame(array_diff($expected, $result), array());
<ide>
<ide> $result = $Folder->find('.*', true);
<del> $expected = array('cacert.pem', 'config.php', 'routes.php');
<add> $expected = array('cacert.pem', 'config.php');
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $result = $Folder->find('.*\.php');
<ide> public function testFind() {
<ide> $this->assertSame(array_diff($expected, $result), array());
<ide>
<ide> $result = $Folder->find('.*\.php', true);
<del> $expected = array('config.php', 'routes.php');
<add> $expected = array('config.php');
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $result = $Folder->find('.*ig\.php');
<ide><path>tests/test_app/TestApp/Config/routes.php
<ide> <?php
<ide> /**
<del> * Routes file
<del> *
<del> * Routes for test app
<del> *
<ide> * CakePHP : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide>
<ide> use Cake\Routing\Router;
<ide>
<del>// Configure::write('Routing.prefixes', array());
<ide>
<ide> Router::parseExtensions('json');
<del>Router::connect('/some_alias', array('controller' => 'tests_apps', 'action' => 'some_method'));
<del>
<del>Router::connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
<del>
<del>require CAKE . 'Config/routes.php';
<add>Router::scope('/', function($routes) {
<add> $routes->connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
<add> $routes->connect('/some_alias', array('controller' => 'tests_apps', 'action' => 'some_method'));
<add> $routes->fallbacks();
<add>}); | 6 |
Javascript | Javascript | introduce shouldcomponentupdate in fiber | 94ed00740b191617420f3736dba8df3c0bbeac96 | <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> workInProgress.pendingWorkPriority = NoWork;
<ide> }
<ide>
<del> function updateClassComponent(current, workInProgress) {
<add> function updateClassComponent(current : ?Fiber, workInProgress : Fiber) {
<ide> var props = workInProgress.pendingProps;
<del> if (!workInProgress.stateNode) {
<add> var instance = workInProgress.stateNode;
<add> if (!instance) {
<ide> var ctor = workInProgress.type;
<del> workInProgress.stateNode = new ctor(props);
<add> workInProgress.stateNode = instance = new ctor(props);
<add> } else if (typeof instance.shouldComponentUpdate === 'function') {
<add> if (current && current.memoizedProps) {
<add> // Revert to the last flushed props, incase we aborted an update.
<add> instance.props = current.memoizedProps;
<add> if (!instance.shouldComponentUpdate(props)) {
<add> return bailoutOnCurrent(current, workInProgress);
<add> }
<add> }
<add> if (!workInProgress.hasWorkInProgress && workInProgress.memoizedProps) {
<add> // Reset the props, in case this is a ping-pong case rather than a
<add> // completed update case. For the completed update case, the instance
<add> // props will already be the memoizedProps.
<add> instance.props = workInProgress.memoizedProps;
<add> if (!instance.shouldComponentUpdate(props)) {
<add> return bailoutOnAlreadyFinishedWork(workInProgress);
<add> }
<add> }
<ide> }
<del> var instance = workInProgress.stateNode;
<ide> instance.props = props;
<ide> var nextChildren = instance.render();
<ide> reconcileChildren(current, workInProgress, nextChildren);
<ide> workInProgress.pendingWorkPriority = NoWork;
<add> return workInProgress.child;
<ide> }
<ide>
<ide> function updateHostComponent(current, workInProgress) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> } while (child = child.sibling);
<ide> }
<ide>
<add> function bailoutOnCurrent(current : Fiber, workInProgress : Fiber) : ?Fiber {
<add> // The most likely scenario is that the previous copy of the tree contains
<add> // the same props as the new one. In that case, we can just copy the output
<add> // and children from that node.
<add> workInProgress.memoizedProps = workInProgress.pendingProps;
<add> workInProgress.output = current.output;
<add> const priorityLevel = workInProgress.pendingWorkPriority;
<add> workInProgress.pendingProps = null;
<add> workInProgress.pendingWorkPriority = NoWork;
<add> workInProgress.stateNode = current.stateNode;
<add> if (current.child) {
<add> // If we bail out but still has work with the current priority in this
<add> // subtree, we need to go find it right now. If we don't, we won't flush
<add> // it until the next tick.
<add> workInProgress.child = current.child;
<add> reuseChildren(workInProgress, workInProgress.child);
<add> if (workInProgress.pendingWorkPriority !== NoWork && workInProgress.pendingWorkPriority <= priorityLevel) {
<add> // TODO: This passes the current node and reads the priority level and
<add> // pending props from that. We want it to read our priority level and
<add> // pending props from the work in progress. Needs restructuring.
<add> return findNextUnitOfWorkAtPriority(current, priorityLevel);
<add> } else {
<add> return null;
<add> }
<add> } else {
<add> workInProgress.child = null;
<add> return null;
<add> }
<add> }
<add>
<add> function bailoutOnAlreadyFinishedWork(workInProgress : Fiber) : ?Fiber {
<add> // If we started this work before, and finished it, or if we're in a
<add> // ping-pong update scenario, this version could already be what we're
<add> // looking for. In that case, we should be able to just bail out.
<add> const priorityLevel = workInProgress.pendingWorkPriority;
<add> workInProgress.pendingProps = null;
<add> workInProgress.pendingWorkPriority = NoWork;
<add>
<add> workInProgress.firstEffect = null;
<add> workInProgress.nextEffect = null;
<add> workInProgress.lastEffect = null;
<add>
<add> if (workInProgress.child && workInProgress.child.alternate) {
<add> // On the way up here, we reset the child node to be the current one.
<add> // Therefore we have to reuse the alternate. This is super weird.
<add> let child = workInProgress.child.alternate;
<add> workInProgress.child = child;
<add> // Ensure that the effects of reused work are preserved.
<add> reuseChildrenEffects(workInProgress, child);
<add> // If we bail out but still has work with the current priority in this
<add> // subtree, we need to go find it right now. If we don't, we won't flush
<add> // it until the next tick.
<add> reuseChildren(workInProgress, child);
<add> if (workInProgress.pendingWorkPriority !== NoWork &&
<add> workInProgress.pendingWorkPriority <= priorityLevel) {
<add> // TODO: This passes the current node and reads the priority level and
<add> // pending props from that. We want it to read our priority level and
<add> // pending props from the work in progress. Needs restructuring.
<add> return findNextUnitOfWorkAtPriority(workInProgress, priorityLevel);
<add> }
<add> }
<add> return null;
<add> }
<add>
<ide> function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber {
<ide> // The current, flushed, state of this fiber is the alternate.
<ide> // Ideally nothing should rely on this, but relying on it here
<ide> // means that we don't need an additional field on the work in
<ide> // progress.
<ide> if (current && workInProgress.pendingProps === current.memoizedProps) {
<del> // The most likely scenario is that the previous copy of the tree contains
<del> // the same props as the new one. In that case, we can just copy the output
<del> // and children from that node.
<del> workInProgress.memoizedProps = workInProgress.pendingProps;
<del> workInProgress.output = current.output;
<del> const priorityLevel = workInProgress.pendingWorkPriority;
<del> workInProgress.pendingProps = null;
<del> workInProgress.pendingWorkPriority = NoWork;
<del> workInProgress.stateNode = current.stateNode;
<del> if (current.child) {
<del> // If we bail out but still has work with the current priority in this
<del> // subtree, we need to go find it right now. If we don't, we won't flush
<del> // it until the next tick.
<del> workInProgress.child = current.child;
<del> reuseChildren(workInProgress, workInProgress.child);
<del> if (workInProgress.pendingWorkPriority !== NoWork && workInProgress.pendingWorkPriority <= priorityLevel) {
<del> // TODO: This passes the current node and reads the priority level and
<del> // pending props from that. We want it to read our priority level and
<del> // pending props from the work in progress. Needs restructuring.
<del> return findNextUnitOfWorkAtPriority(workInProgress.alternate, priorityLevel);
<del> } else {
<del> return null;
<del> }
<del> } else {
<del> workInProgress.child = null;
<del> return null;
<del> }
<add> return bailoutOnCurrent(current, workInProgress);
<ide> }
<ide>
<ide> if (!workInProgress.hasWorkInProgress &&
<ide> workInProgress.pendingProps === workInProgress.memoizedProps) {
<del> // If we started this work before, and finished it, or if we're in a
<del> // ping-pong update scenario, this version could already be what we're
<del> // looking for. In that case, we should be able to just bail out.
<del> const priorityLevel = workInProgress.pendingWorkPriority;
<del> workInProgress.pendingProps = null;
<del> workInProgress.pendingWorkPriority = NoWork;
<del>
<del> workInProgress.firstEffect = null;
<del> workInProgress.nextEffect = null;
<del> workInProgress.lastEffect = null;
<del>
<del> if (workInProgress.child && workInProgress.child.alternate) {
<del> // On the way up here, we reset the child node to be the current one.
<del> // Therefore we have to reuse the alternate. This is super weird.
<del> workInProgress.child = workInProgress.child.alternate;
<del> // Ensure that the effects of reused work are preserved.
<del> reuseChildrenEffects(workInProgress, workInProgress.child);
<del> // If we bail out but still has work with the current priority in this
<del> // subtree, we need to go find it right now. If we don't, we won't flush
<del> // it until the next tick.
<del> reuseChildren(workInProgress, workInProgress.child);
<del> if (workInProgress.pendingWorkPriority !== NoWork && workInProgress.pendingWorkPriority <= priorityLevel) {
<del> // TODO: This passes the current node and reads the priority level and
<del> // pending props from that. We want it to read our priority level and
<del> // pending props from the work in progress. Needs restructuring.
<del> return findNextUnitOfWorkAtPriority(workInProgress, priorityLevel);
<del> }
<del> }
<del> return null;
<add> return bailoutOnAlreadyFinishedWork(workInProgress);
<ide> }
<ide>
<del> workInProgress.hasWorkInProgress = true;
<del>
<add> let nextWork;
<ide> switch (workInProgress.tag) {
<ide> case IndeterminateComponent:
<ide> mountIndeterminateComponent(current, workInProgress);
<add> workInProgress.hasWorkInProgress = true;
<ide> return workInProgress.child;
<ide> case FunctionalComponent:
<ide> updateFunctionalComponent(current, workInProgress);
<add> workInProgress.hasWorkInProgress = true;
<ide> return workInProgress.child;
<ide> case ClassComponent:
<del> updateClassComponent(current, workInProgress);
<del> return workInProgress.child;
<add> nextWork = updateClassComponent(current, workInProgress);
<add> workInProgress.hasWorkInProgress = true;
<add> return nextWork;
<ide> case HostContainer:
<ide> reconcileChildren(current, workInProgress, workInProgress.pendingProps);
<ide> // A yield component is just a placeholder, we can just run through the
<ide> // next one immediately.
<add> workInProgress.hasWorkInProgress = true;
<ide> workInProgress.pendingWorkPriority = NoWork;
<ide> if (workInProgress.child) {
<ide> return beginWork(
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide> return null;
<ide> case HostComponent:
<del> return updateHostComponent(current, workInProgress);
<add> nextWork = updateHostComponent(current, workInProgress);
<add> workInProgress.hasWorkInProgress = true;
<add> return nextWork;
<ide> case CoroutineHandlerPhase:
<ide> // This is a restart. Reset the tag to the initial phase.
<ide> workInProgress.tag = CoroutineComponent;
<ide> // Intentionally fall through since this is now the same.
<ide> case CoroutineComponent:
<ide> updateCoroutineComponent(current, workInProgress);
<add> workInProgress.hasWorkInProgress = true;
<ide> // This doesn't take arbitrary time so we could synchronously just begin
<ide> // eagerly do the work of workInProgress.child as an optimization.
<ide> if (workInProgress.child) {
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', function() {
<ide> return <div>{props.children}</div>;
<ide> }
<ide>
<del> function Tester() {
<del> // This component is just here to ensure that the bail out is
<del> // in fact in effect in the expected place for this test.
<del> ops.push('Tester');
<del> return <div />;
<add> class Tester extends React.Component {
<add> shouldComponentUpdate() {
<add> return false;
<add> }
<add> render() {
<add> // This component is just here to ensure that the bail out is
<add> // in fact in effect in the expected place for this test.
<add> ops.push('Tester');
<add> return <div />;
<add> }
<ide> }
<ide>
<ide> function Middle(props) {
<ide> ops.push('Middle');
<ide> return <span>{props.children}</span>;
<ide> }
<ide>
<del> var middleContent = (
<del> <aaa>
<del> <Tester />
<del> <bbb hidden={true}>
<del> <ccc>
<del> <Middle>Hi</Middle>
<del> </ccc>
<del> </bbb>
<del> </aaa>
<del> );
<add> class Content extends React.Component {
<add> shouldComponentUpdate() {
<add> return false;
<add> }
<add> render() {
<add> return [
<add> <Tester unused={this.props.unused} />,
<add> <bbb hidden={true}>
<add> <ccc>
<add> <Middle>Hi</Middle>
<add> </ccc>
<add> </bbb>,
<add> ];
<add> }
<add> }
<ide>
<ide> function Foo(props) {
<ide> ops.push('Foo');
<ide> return (
<ide> <div hidden={props.text === 'bar'}>
<ide> <Bar>{props.text}</Bar>
<del> {middleContent}
<add> <Content unused={props.text} />
<ide> <Bar>{props.text}</Bar>
<ide> </div>
<ide> );
<ide> describe('ReactIncremental', function() {
<ide>
<ide> });
<ide>
<add> it('can reuse work if shouldComponentUpdate is false, after being preempted', function() {
<add>
<add> var ops = [];
<add>
<add> function Bar(props) {
<add> ops.push('Bar');
<add> return <div>{props.children}</div>;
<add> }
<add>
<add> class Middle extends React.Component {
<add> shouldComponentUpdate(nextProps) {
<add> return this.props.children !== nextProps.children;
<add> }
<add> render() {
<add> ops.push('Middle');
<add> return <span>{this.props.children}</span>;
<add> }
<add> }
<add>
<add> class Content extends React.Component {
<add> shouldComponentUpdate(nextProps) {
<add> return this.props.step !== nextProps.step;
<add> }
<add> render() {
<add> ops.push('Content');
<add> return (
<add> <div>
<add> <Middle>{this.props.step === 0 ? 'Hi' : 'Hello'}</Middle>
<add> <Bar>{this.props.step === 0 ? this.props.text : '-'}</Bar>
<add> <Middle>{this.props.step === 0 ? 'There' : 'World'}</Middle>
<add> </div>
<add> );
<add> }
<add> }
<add>
<add> function Foo(props) {
<add> ops.push('Foo');
<add> return (
<add> <div>
<add> <Bar>{props.text}</Bar>
<add> <div hidden={true}>
<add> <Content step={props.step} text={props.text} />
<add> </div>
<add> </div>
<add> );
<add> }
<add>
<add> // Init
<add> ReactNoop.render(<Foo text="foo" step={0} />);
<add> ReactNoop.flush();
<add>
<add> expect(ops).toEqual(['Foo', 'Bar', 'Content', 'Middle', 'Bar', 'Middle']);
<add>
<add> ops = [];
<add>
<add> // Make a quick update which will schedule low priority work to
<add> // update the middle content.
<add> ReactNoop.render(<Foo text="bar" step={1} />);
<add> ReactNoop.flushLowPri(30);
<add>
<add> expect(ops).toEqual(['Foo', 'Bar']);
<add>
<add> ops = [];
<add>
<add> // The middle content is now pending rendering...
<add> ReactNoop.flushLowPri(30);
<add> expect(ops).toEqual(['Content', 'Middle', 'Bar']); // One more Middle left.
<add>
<add> ops = [];
<add>
<add> // but we'll interupt it to render some higher priority work.
<add> // The middle content will bailout so it remains untouched.
<add> ReactNoop.render(<Foo text="foo" step={1} />);
<add> ReactNoop.flushLowPri(30);
<add>
<add> expect(ops).toEqual(['Foo', 'Bar']);
<add>
<add> ops = [];
<add>
<add> // Since we did nothing to the middle subtree during the interuption,
<add> // we should be able to reuse the reconciliation work that we already did
<add> // without restarting.
<add> ReactNoop.flush();
<add> // TODO: Content never fully completed its render so can't completely bail
<add> // out on the entire subtree. However, we could do a shallow bail out and
<add> // not rerender Content, but keep going down the incomplete tree.
<add> // Normally shouldComponentUpdate->false is not enough to determine that we
<add> // can safely reuse the old props, but I think in this case it would be ok,
<add> // since it is a resume of already started work.
<add> // Because of the above we can also not reuse the work of Bar because the
<add> // rerender of Content will generate a new element which will mean we don't
<add> // auto-bail out from Bar.
<add> expect(ops).toEqual(['Content', 'Bar', 'Middle']);
<add>
<add> });
<ide> });
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js
<ide> describe('ReactIncrementalSideEffects', function() {
<ide> ]);
<ide> });
<ide>
<add> it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', function() {
<add>
<add> class Bar extends React.Component {
<add> shouldComponentUpdate(nextProps) {
<add> return this.props.children !== nextProps.children;
<add> }
<add> render() {
<add> return <span prop={this.props.children} />;
<add> }
<add> }
<add>
<add> class Content extends React.Component {
<add> shouldComponentUpdate(nextProps) {
<add> return this.props.step !== nextProps.step;
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <Bar>{this.props.step === 0 ? 'Hi' : 'Hello'}</Bar>
<add> <Bar>{this.props.step === 0 ? this.props.text : 'World'}</Bar>
<add> </div>
<add> );
<add> }
<add> }
<add>
<add> function Foo(props) {
<add> return (
<add> <div hidden={true}>
<add> <Content step={props.step} text={props.text} />
<add> </div>
<add> );
<add> }
<add>
<add> // Init
<add> ReactNoop.render(<Foo text="foo" step={0} />);
<add> ReactNoop.flush();
<add>
<add> expect(ReactNoop.root.children).toEqual([
<add> div(div(span('Hi'), span('foo'))),
<add> ]);
<add>
<add> // Make a quick update which will schedule low priority work to
<add> // update the middle content.
<add> ReactNoop.render(<Foo text="bar" step={1} />);
<add> ReactNoop.flushLowPri(35);
<add>
<add> // The tree remains unchanged.
<add> expect(ReactNoop.root.children).toEqual([
<add> div(div(span('Hi'), span('foo'))),
<add> ]);
<add>
<add> // The first Bar has already completed its update but we'll interupt it to
<add> // render some higher priority work. The middle content will bailout so
<add> // it remains untouched which means that it should reuse it next time.
<add> ReactNoop.render(<Foo text="foo" step={1} />);
<add> ReactNoop.flush(30);
<add>
<add> // Since we did nothing to the middle subtree during the interuption,
<add> // we should be able to reuse the reconciliation work that we already did
<add> // without restarting. The side-effects should still be replayed.
<add>
<add> expect(ReactNoop.root.children).toEqual([
<add> div(div(span('Hello'), span('World'))),
<add> ]);
<add> });
<add>
<ide> it('updates a child even though the old props is empty', function() {
<ide> function Foo(props) {
<ide> return ( | 3 |
Python | Python | fix typo in examples/utils_ner.py | 2ba147ecffa28e5a4f96eebd09dcd642117dedae | <ide><path>examples/utils_ner.py
<ide> def read_examples_from_file(data_dir, mode):
<ide> # Examples could have no label for mode = "test"
<ide> labels.append("O")
<ide> if words:
<del> examples.append(InputExample(guid="%s-%d".format(mode, guid_index), words=words, labels=labels))
<add> examples.append(InputExample(guid="{}-{}".format(mode, guid_index), words=words, labels=labels))
<ide> return examples
<ide>
<ide> | 1 |
PHP | PHP | add alias method | a01e9edfadb140559d1bbf9999dda49148bfa5f7 | <ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php
<ide> class_basename(static::class), gettype($result)
<ide> return $result;
<ide> }
<ide>
<add> /**
<add> * Reduce the collection to multiple aggregate values.
<add> *
<add> * @param callable $callback
<add> * @param mixed ...$initial
<add> * @return array
<add> *
<add> * @throws \UnexpectedValueException
<add> */
<add> public function reduceSpread(callable $callback, ...$initial)
<add> {
<add> return $this->reduceMany($callback, ...$initial);
<add> }
<add>
<ide> /**
<ide> * Reduce an associative collection to a single value.
<ide> * | 1 |
PHP | PHP | improve notification testability | 8f5c8c4bd2513248133fb95d06c450b9cb4e5a59 | <ide><path>src/Illuminate/Contracts/Notifications/Factory.php
<ide> interface Factory
<ide> {
<ide> /**
<del> * Create a new notification for the given notifiable entities.
<add> * Dispatch the given notification instance to the given notifiable.
<ide> *
<del> * @param array $notifiables
<del> * @return \Illuminate\Notifications\Notification
<add> * @param mixed $notifiable
<add> * @param mixed $instance
<add> * @param array $channels
<add> * @return void
<ide> */
<del> public function to($notifiables);
<add> public function dispatch($notifiable, $instance, array $channels = []);
<ide> }
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php
<ide>
<ide> use Mockery;
<ide> use Exception;
<add>use Illuminate\Contracts\Notifications\Factory as NotificationFactory;
<ide>
<ide> trait MocksApplicationServices
<ide> {
<ide> trait MocksApplicationServices
<ide> */
<ide> protected $dispatchedJobs = [];
<ide>
<add> /**
<add> * All of the dispatched notifications.
<add> *
<add> * @var array
<add> */
<add> protected $dispatchedNotifications = [];
<add>
<ide> /**
<ide> * Specify a list of events that should be fired for the given operation.
<ide> *
<ide> protected function wasDispatched($needle, array $haystack)
<ide>
<ide> return false;
<ide> }
<add>
<add> /**
<add> * Mock the notification dispatcher so all notifications are silenced.
<add> *
<add> * @return $this
<add> */
<add> protected function withoutNotifications()
<add> {
<add> $mock = Mockery::mock(NotificationFactory::class);
<add>
<add> $mock->shouldReceive('dispatch')->andReturnUsing(function ($notifiable, $instance, $channels = []) {
<add> $this->dispatchedNotifications[] = compact(
<add> 'notifiable', 'instance', 'channels'
<add> );
<add> });
<add>
<add> $this->app->instance(NotificationFactory::class, $mock);
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Specify a notification that is expected to be dispatched.
<add> *
<add> * @param mixed $notifiable
<add> * @param string $notification
<add> * @return $this
<add> */
<add> protected function expectsNotification($notifiable, $notification)
<add> {
<add> $this->withoutNotifications();
<add>
<add> $this->beforeApplicationDestroyed(function () use ($notifiable, $notification) {
<add> foreach ($this->dispatchedNotifications as $dispatched) {
<add> if (($dispatched['notifiable'] === $notifiable ||
<add> $dispatched['notifiable']->getKey() == $notifiable->getKey()) &&
<add> get_class($dispatched['instance']) === $notification) {
<add>
<add> return $this;
<add> }
<add> }
<add>
<add> throw new Exception(
<add> 'The following expected notification were not dispatched: ['.$notification.']'
<add> );
<add> });
<add>
<add> return $this;
<add> }
<ide> }
<ide><path>src/Illuminate/Notifications/ChannelManager.php
<ide>
<ide> use Illuminate\Support\Manager;
<ide> use Nexmo\Client as NexmoClient;
<add>use Illuminate\Contracts\Queue\ShouldQueue;
<add>use Illuminate\Contracts\Bus\Dispatcher as Bus;
<ide> use Nexmo\Client\Credentials\Basic as NexmoCredentials;
<ide> use Illuminate\Contracts\Notifications\Factory as FactoryContract;
<ide>
<ide> public function to($notifiables)
<ide> return new Channels\Notification($this, $notifiables);
<ide> }
<ide>
<add> /**
<add> * Dispatch the given notification instance to the given notifiable.
<add> *
<add> * @param mixed $notifiable
<add> * @param mixed $instance
<add> * @param array $channels
<add> * @return void
<add> */
<add> public function dispatch($notifiable, $instance, array $channels = [])
<add> {
<add> $notifications = $this->notificationsFromInstance(
<add> $notifiable, $instance
<add> );
<add>
<add> if (count($channels) > 0) {
<add> foreach ($notifications as $notification) {
<add> $notification->via((array) $channels);
<add> }
<add> }
<add>
<add> if ($instance instanceof ShouldQueue) {
<add> return $this->queueNotifications($instance, $notifications);
<add> }
<add>
<add> foreach ($notifications as $notification) {
<add> $this->send($notification);
<add> }
<add> }
<add>
<add> /**
<add> * Queue the given notification instances.
<add> *
<add> * @param mixed $instance
<add> * @param array[\Illuminate\Notifcations\Channels\Notification]
<add> * @return void
<add> */
<add> protected function queueNotifications($instance, array $notifications)
<add> {
<add> $this->app->make(Bus::class)->dispatch(
<add> (new SendQueuedNotifications($notifications))
<add> ->onConnection($instance->connection)
<add> ->onQueue($instance->queue)
<add> ->delay($instance->delay)
<add> );
<add> }
<add>
<ide> /**
<ide> * Send the given notification.
<ide> *
<ide><path>src/Illuminate/Notifications/RoutesNotifications.php
<ide> namespace Illuminate\Notifications;
<ide>
<ide> use Illuminate\Support\Str;
<del>use Illuminate\Contracts\Queue\ShouldQueue;
<add>use Illuminate\Contracts\Notifications\Factory as NotificationFactory;
<ide>
<ide> trait RoutesNotifications
<ide> {
<ide> trait RoutesNotifications
<ide> */
<ide> public function notify($instance)
<ide> {
<del> $manager = app(ChannelManager::class);
<del>
<del> $notifications = $manager->notificationsFromInstance(
<del> $this, $instance
<del> );
<del>
<del> if ($instance instanceof ShouldQueue) {
<del> return $this->queueNotifications($instance, $notifications);
<del> }
<del>
<del> foreach ($notifications as $notification) {
<del> $manager->send($notification);
<del> }
<add> app(NotificationFactory::class)->dispatch($this, $instance);
<ide> }
<ide>
<ide> /**
<ide> public function notify($instance)
<ide> */
<ide> public function notifyVia($channels, $instance)
<ide> {
<del> $manager = app(ChannelManager::class);
<del>
<del> $notifications = $manager->notificationsFromInstance(
<del> $this, $instance, (array) $channels
<del> );
<del>
<del> foreach ($notifications as $notification) {
<del> $notification->via((array) $channels);
<del> }
<del>
<del> if ($instance instanceof ShouldQueue) {
<del> return $this->queueNotifications($instance, $notifications);
<del> }
<del>
<del> foreach ($notifications as $notification) {
<del> $manager->send($notification);
<del> }
<del> }
<del>
<del> /**
<del> * Queue the given notification instances.
<del> *
<del> * @param mixed $instance
<del> * @param array[\Illuminate\Notifcations\Channels\Notification]
<del> * @return void
<del> */
<del> protected function queueNotifications($instance, array $notifications)
<del> {
<del> dispatch(
<del> (new SendQueuedNotifications($notifications))
<del> ->onConnection($instance->connection)
<del> ->onQueue($instance->queue)
<del> ->delay($instance->delay)
<del> );
<add> app(NotificationFactory::class)->dispatch($this, $instance, $channels);
<ide> }
<ide>
<ide> /** | 4 |
Python | Python | fix unicode encoding issue | 6cd14bbfddd43f84ef2be0d39f8185a53db4363d | <ide><path>glances/glances.py
<ide> #!/usr/bin/env python
<add># -*- coding: utf-8 -*-
<ide> #
<ide> # Glances is a simple textual monitoring tool
<ide> # | 1 |
Ruby | Ruby | fix a faulty form_for test | 252660b886c8880fc8c43a1c4bc84f07c9a9aab7 | <ide><path>actionview/test/template/form_helper_test.rb
<ide> def test_auto_index_with_nil_id
<ide> end
<ide>
<ide> def test_form_for_requires_block
<del> assert_raises(ArgumentError) do
<del> form_for(:post, @post, html: { id: 'create-post' })
<add> error = assert_raises(ArgumentError) do
<add> form_for(@post, html: { id: 'create-post' })
<ide> end
<add> assert_equal "Missing block", error.message
<ide> end
<ide>
<ide> def test_form_for_requires_arguments | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.