content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | fix typo in time#change docs | fefa4018cb3c6ef731a80dc58587387ff75b224c | <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def seconds_until_end_of_day
<ide> # and minute is passed, then sec, usec and nsec is set to 0. The +options+
<ide> # parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
<ide> # <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>
<del> # <tt>:nsec</tt>. Path either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
<add> # <tt>:nsec</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
<ide> #
<ide> # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
<ide> # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0) | 1 |
Javascript | Javascript | improve the @usage example | 85c31e068821f412128d98265ed439a725400528 | <ide><path>src/ng/directive/ngSwitch.js
<ide> * ngSwitchWhen or ngSwitchDefault directives will be preserved at the location
<ide> * as specified in the template
<ide> *
<del> * @usageContent
<del> * <ANY ng-switch-when="matchValue1">...</ANY>
<add> * @usage
<add> * <ANY ng-switch="expression">
<add> * <ANY ng-switch-when="matchValue1">...</ANY>
<ide> * <ANY ng-switch-when="matchValue2">...</ANY>
<ide> * ...
<ide> * <ANY ng-switch-default>...</ANY>
<del> * <ANY>...</ANY>
<add> * </ANY>
<ide> *
<ide> * @scope
<ide> * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. | 1 |
Javascript | Javascript | remove most usage of innerhtml | eb8f802391392406ad9801a76934aa7a98dd1bdb | <ide><path>src/js/button.js
<ide> import Component from './component';
<ide> import log from './utils/log.js';
<ide> import {assign} from './utils/obj';
<ide> import keycode from 'keycode';
<add>import {createEl} from './utils/dom.js';
<ide>
<ide> /**
<ide> * Base class for all buttons.
<ide> class Button extends ClickableComponent {
<ide> tag = 'button';
<ide>
<ide> props = assign({
<del> innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>',
<ide> className: this.buildCSSClass()
<ide> }, props);
<ide>
<ide> class Button extends ClickableComponent {
<ide> type: 'button'
<ide> }, attributes);
<ide>
<del> const el = Component.prototype.createEl.call(this, tag, props, attributes);
<add> const el = createEl(tag, props, attributes);
<add>
<add> el.appendChild(createEl('span', {
<add> className: 'vjs-icon-placeholder'
<add> }, {
<add> 'aria-hidden': true
<add> }));
<ide>
<ide> this.createControlTextEl(el);
<ide>
<ide><path>src/js/clickable-component.js
<ide> class ClickableComponent extends Component {
<ide> */
<ide> createEl(tag = 'div', props = {}, attributes = {}) {
<ide> props = assign({
<del> innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>',
<ide> className: this.buildCSSClass(),
<ide> tabIndex: 0
<ide> }, props);
<ide> class ClickableComponent extends Component {
<ide>
<ide> this.tabIndex_ = props.tabIndex;
<ide>
<del> const el = super.createEl(tag, props, attributes);
<add> const el = Dom.createEl(tag, props, attributes);
<add>
<add> el.appendChild(Dom.createEl('span', {
<add> className: 'vjs-icon-placeholder'
<add> }, {
<add> 'aria-hidden': true
<add> }));
<ide>
<ide> this.createControlTextEl(el);
<ide>
<ide><path>src/js/control-bar/audio-track-controls/audio-track-menu-item.js
<ide> */
<ide> import MenuItem from '../../menu/menu-item.js';
<ide> import Component from '../../component.js';
<del>import {assign} from '../../utils/obj';
<ide>
<ide> /**
<ide> * An {@link AudioTrack} {@link MenuItem}
<ide> class AudioTrackMenuItem extends MenuItem {
<ide> }
<ide>
<ide> createEl(type, props, attrs) {
<del> let innerHTML = `<span class="vjs-menu-item-text">${this.localize(this.options_.label)}`;
<add> const el = super.createEl(type, props, attrs);
<add> const parentSpan = el.querySelector('.vjs-menu-item-text');
<ide>
<ide> if (this.options_.track.kind === 'main-desc') {
<del> innerHTML += `
<del> <span aria-hidden="true" class="vjs-icon-placeholder"></span>
<del> <span class="vjs-control-text"> ${this.localize('Descriptions')}</span>
<del> `;
<add> parentSpan.appendChild(super.createEl('span', {
<add> className: 'vjs-icon-placeholder'
<add> }, {
<add> 'aria-hidden': true
<add> }));
<add> parentSpan.appendChild(super.createEl('span', {
<add> className: 'vjs-control-text',
<add> textContent: this.localize('Descriptions')
<add> }));
<ide> }
<ide>
<del> innerHTML += '</span>';
<del>
<del> const el = super.createEl(type, assign({
<del> innerHTML
<del> }, props), attrs);
<del>
<ide> return el;
<ide> }
<ide>
<ide><path>src/js/control-bar/live-display.js
<ide> */
<ide> import Component from '../component';
<ide> import * as Dom from '../utils/dom.js';
<add>import document from 'global/document';
<ide>
<ide> // TODO - Future make it click to snap to live
<ide>
<ide> class LiveDisplay extends Component {
<ide> });
<ide>
<ide> this.contentEl_ = Dom.createEl('div', {
<del> className: 'vjs-live-display',
<del> innerHTML: `<span class="vjs-control-text">${this.localize('Stream Type')}\u00a0</span>${this.localize('LIVE')}`
<add> className: 'vjs-live-display'
<ide> }, {
<ide> 'aria-live': 'off'
<ide> });
<ide>
<add> this.contentEl_.appendChild(Dom.createEl('span', {
<add> className: 'vjs-control-text',
<add> textContent: `${this.localize('Stream Type')}\u00a0`
<add> }));
<add> this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
<add>
<ide> el.appendChild(this.contentEl_);
<ide> return el;
<ide> }
<ide><path>src/js/control-bar/playback-rate-menu/playback-rate-menu-button.js
<ide> class PlaybackRateMenuButton extends MenuButton {
<ide> this.labelEl_ = Dom.createEl('div', {
<ide> className: 'vjs-playback-rate-value',
<ide> id: this.labelElId_,
<del> innerHTML: '1x'
<add> textContent: '1x'
<ide> });
<ide>
<ide> el.appendChild(this.labelEl_);
<ide> class PlaybackRateMenuButton extends MenuButton {
<ide> */
<ide> updateLabel(event) {
<ide> if (this.playbackRateSupported()) {
<del> this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
<add> this.labelEl_.textContent = this.player().playbackRate() + 'x';
<ide> }
<ide> }
<ide>
<ide><path>src/js/control-bar/seek-to-live.js
<ide> class SeekToLive extends Button {
<ide>
<ide> this.textEl_ = Dom.createEl('span', {
<ide> className: 'vjs-seek-to-live-text',
<del> innerHTML: this.localize('LIVE')
<add> textContent: this.localize('LIVE')
<ide> }, {
<ide> 'aria-hidden': 'true'
<ide> });
<ide><path>src/js/control-bar/spacer-controls/custom-control-spacer.js
<ide> class CustomControlSpacer extends Spacer {
<ide> * The element that was created.
<ide> */
<ide> createEl() {
<del> const el = super.createEl({
<del> className: this.buildCSSClass()
<add> return super.createEl('div', {
<add> className: this.buildCSSClass(),
<add> // No-flex/table-cell mode requires there be some content
<add> // in the cell to fill the remaining space of the table.
<add> textContent: '\u00a0'
<ide> });
<del>
<del> // No-flex/table-cell mode requires there be some content
<del> // in the cell to fill the remaining space of the table.
<del> el.innerHTML = '\u00a0';
<del> return el;
<ide> }
<ide> }
<ide>
<ide><path>src/js/control-bar/spacer-controls/spacer.js
<ide> class Spacer extends Component {
<ide> * @return {Element}
<ide> * The element that was created.
<ide> */
<del> createEl() {
<del> return super.createEl('div', {
<del> className: this.buildCSSClass()
<del> });
<add> createEl(tag = 'div', props = {}, attributes = {}) {
<add> if (!props.className) {
<add> props.className = this.buildCSSClass();
<add> }
<add>
<add> return super.createEl(tag, props, attributes);
<ide> }
<ide> }
<ide>
<ide><path>src/js/control-bar/text-track-controls/subs-caps-menu-item.js
<ide> */
<ide> import TextTrackMenuItem from './text-track-menu-item.js';
<ide> import Component from '../../component.js';
<del>import {assign} from '../../utils/obj';
<add>import {createEl} from '../../utils/dom.js';
<ide>
<ide> /**
<ide> * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
<ide> import {assign} from '../../utils/obj';
<ide> class SubsCapsMenuItem extends TextTrackMenuItem {
<ide>
<ide> createEl(type, props, attrs) {
<del> let innerHTML = `<span class="vjs-menu-item-text">${this.localize(this.options_.label)}`;
<add> const el = super.createEl(type, props, attrs);
<add> const parentSpan = el.querySelector('.vjs-menu-item-text');
<ide>
<ide> if (this.options_.track.kind === 'captions') {
<del> innerHTML += `
<del> <span aria-hidden="true" class="vjs-icon-placeholder"></span>
<del> <span class="vjs-control-text"> ${this.localize('Captions')}</span>
<del> `;
<add> parentSpan.appendChild(createEl('span', {
<add> className: 'vjs-icon-placeholder'
<add> }, {
<add> 'aria-hidden': true
<add> }));
<add> parentSpan.appendChild(createEl('span', {
<add> className: 'vjs-control-text',
<add> // space added as the text will visually flow with the
<add> // label
<add> textContent: ` ${this.localize('Captions')}`
<add> }));
<ide> }
<ide>
<del> innerHTML += '</span>';
<del>
<del> const el = super.createEl(type, assign({
<del> innerHTML
<del> }, props), attrs);
<del>
<ide> return el;
<ide> }
<ide> }
<ide><path>src/js/control-bar/time-controls/time-display.js
<ide> class TimeDisplay extends Component {
<ide> createEl() {
<ide> const className = this.buildCSSClass();
<ide> const el = super.createEl('div', {
<del> className: `${className} vjs-time-control vjs-control`,
<del> innerHTML: `<span class="vjs-control-text" role="presentation">${this.localize(this.labelText_)}\u00a0</span>`
<add> className: `${className} vjs-time-control vjs-control`
<ide> });
<add> const span = Dom.createEl('span', {
<add> className: 'vjs-control-text',
<add> textContent: `${this.localize(this.labelText_)}\u00a0`
<add> }, {
<add> role: 'presentation'
<add> });
<add>
<add> el.appendChild(span);
<ide>
<ide> this.contentEl_ = Dom.createEl('span', {
<ide> className: `${className}-display`
<ide><path>src/js/control-bar/time-controls/time-divider.js
<ide> class TimeDivider extends Component {
<ide> * The element that was created.
<ide> */
<ide> createEl() {
<del> return super.createEl('div', {
<del> className: 'vjs-time-control vjs-time-divider',
<del> innerHTML: '<div><span>/</span></div>'
<add> const el = super.createEl('div', {
<add> className: 'vjs-time-control vjs-time-divider'
<ide> }, {
<ide> // this element and its contents can be hidden from assistive techs since
<ide> // it is made extraneous by the announcement of the control text
<ide> // for the current time and duration displays
<ide> 'aria-hidden': true
<ide> });
<add>
<add> const div = super.createEl('div');
<add> const span = super.createEl('span', {
<add> textContent: '/'
<add> });
<add>
<add> div.appendChild(span);
<add> el.appendChild(div);
<add>
<add> return el;
<ide> }
<ide>
<ide> }
<ide><path>src/js/control-bar/volume-control/volume-level.js
<ide> class VolumeLevel extends Component {
<ide> * The element that was created.
<ide> */
<ide> createEl() {
<del> return super.createEl('div', {
<del> className: 'vjs-volume-level',
<del> innerHTML: '<span class="vjs-control-text"></span>'
<add> const el = super.createEl('div', {
<add> className: 'vjs-volume-level'
<ide> });
<add>
<add> el.appendChild(super.createEl('span', {
<add> className: 'vjs-control-text'
<add> }));
<add>
<add> return el;
<ide> }
<ide>
<ide> }
<ide><path>src/js/loading-spinner.js
<ide> class LoadingSpinner extends Component {
<ide> const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
<ide> const controlText = dom.createEl('span', {
<ide> className: 'vjs-control-text',
<del> innerHTML: this.localize('{1} is loading.', [playerType])
<add> textContent: this.localize('{1} is loading.', [playerType])
<ide> });
<ide>
<ide> const el = super.createEl('div', {
<ide><path>src/js/menu/menu-button.js
<ide> class MenuButton extends Component {
<ide> if (this.options_.title) {
<ide> const titleEl = Dom.createEl('li', {
<ide> className: 'vjs-menu-title',
<del> innerHTML: toTitleCase(this.options_.title),
<add> textContent: toTitleCase(this.options_.title),
<ide> tabIndex: -1
<ide> });
<ide>
<ide><path>src/js/menu/menu-item.js
<ide> import Component from '../component.js';
<ide> import {assign} from '../utils/obj';
<ide> import {MenuKeys} from './menu-keys.js';
<ide> import keycode from 'keycode';
<add>import {createEl} from '../utils/dom.js';
<ide>
<ide> /**
<ide> * The component for a menu item. `<li>`
<ide> class MenuItem extends ClickableComponent {
<ide> // The control is textual, not just an icon
<ide> this.nonIconControl = true;
<ide>
<del> return super.createEl('li', assign({
<add> const el = super.createEl('li', assign({
<ide> className: 'vjs-menu-item',
<del> innerHTML: `<span class="vjs-menu-item-text">${this.localize(this.options_.label)}</span>`,
<ide> tabIndex: -1
<ide> }, props), attrs);
<add>
<add> // swap icon with menu item text.
<add> el.replaceChild(createEl('span', {
<add> className: 'vjs-menu-item-text',
<add> textContent: this.localize(this.options_.label)
<add> }), el.querySelector('.vjs-icon-placeholder'));
<add>
<add> return el;
<ide> }
<ide>
<ide> /** | 15 |
Python | Python | add test for hash consistency | 3fa5b40b5cace40a5b8fde8112354abce6488b77 | <ide><path>spacy/tests/stringstore/test_stringstore.py
<ide> import pytest
<ide>
<ide>
<add>def test_string_hash(stringstore):
<add> '''Test that string hashing is stable across platforms'''
<add> ss = stringstore
<add> assert ss.add('apple') == 8566208034543834098
<add> heart = '\U0001f499'
<add> print(heart)
<add> h = ss.add(heart)
<add> assert h == 11841826740069053588L
<add>
<add>
<ide> def test_stringstore_from_api_docs(stringstore):
<ide> apple_hash = stringstore.add('apple')
<ide> assert apple_hash == 8566208034543834098 | 1 |
Javascript | Javascript | run all tests | ca37eaeba4106f473da45510da10d474e8022f65 | <ide><path>test/Redux.spec.js
<ide> describe('Redux', () => {
<ide> expect(redux.dispatchFn).toBeA('function');
<ide> });
<ide>
<del> it.only('should subscribe to changes', done => {
<add> it('should subscribe to changes', done => {
<ide> let state = redux.getState();
<ide> expect(state.fakeStore).toEqual({});
<ide> redux.subscribe(() => { | 1 |
Text | Text | fix broken links in deprecations.md | 2f6bf7a79124e76792c7bbdf344009e214bd051b | <ide><path>doc/api/deprecations.md
<ide> The [`crypto.Certificate()` constructor][] is deprecated. Use
<ide> [`response.connection`]: http.html#http_response_connection
<ide> [`response.end()`]: http.html#http_response_end_data_encoding_callback
<ide> [`response.finished`]: http.html#http_response_finished
<del>[`response.writableFinished`]: #http_response_writablefinished
<del>[`response.writableEnded`]: #http_response_writableended
<add>[`response.writableFinished`]: http.html#http_response_writablefinished
<add>[`response.writableEnded`]: http.html#http_response_writableended
<ide> [`script.createCachedData()`]: vm.html#vm_script_createcacheddata
<ide> [`setInterval()`]: timers.html#timers_setinterval_callback_delay_args
<ide> [`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args | 1 |
PHP | PHP | add tests for testsession | 13926504497cd18dbbf9756531e954f5995d86bf | <ide><path>src/TestSuite/TestSession.php
<ide> public function check(?string $name = null): bool
<ide> return false;
<ide> }
<ide>
<add> if ($name === null) {
<add> return (bool)$this->session;
<add> }
<add>
<ide> return Hash::get($this->session, $name) !== null;
<ide> }
<ide>
<ide><path>tests/TestCase/TestSuite/TestSessionTest.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP Project
<add> * @since 4.0.5
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\TestSuite;
<add>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\TestSuite\TestSession;
<add>
<add>class TestSessionTest extends TestCase
<add>{
<add> /**
<add> * @var array
<add> */
<add> protected $sessionData;
<add>
<add> /**
<add> * @var \Cake\TestSuite\TestSession
<add> */
<add> protected $session;
<add>
<add> /**
<add> * @return void
<add> */
<add> public function setUp(): void
<add> {
<add> parent::setUp();
<add>
<add> $this->sessionData = [
<add> 'root' => [
<add> 'sub' => [
<add> 'subsub' => 'foo',
<add> ],
<add> ],
<add> ];
<add> $this->session = new TestSession($this->sessionData);
<add> }
<add>
<add> /**
<add> * Tests read()
<add> *
<add> * @return void
<add> */
<add> public function testRead(): void
<add> {
<add> $result = $this->session->read();
<add> $this->assertSame($this->sessionData, $result);
<add>
<add> $result = $this->session->read('root.sub');
<add> $this->assertSame(['subsub' => 'foo'], $result);
<add> }
<add>
<add> /**
<add> * Tests check()
<add> *
<add> * @return void
<add> */
<add> public function testCheck(): void
<add> {
<add> $result = $this->session->check();
<add> $this->assertTrue($result);
<add>
<add> $result = $this->session->check('root.sub');
<add> $this->assertTrue($result);
<add>
<add> $result = $this->session->check('root.nonexistent');
<add> $this->assertFalse($result);
<add> }
<add>} | 2 |
Javascript | Javascript | put everything else back | b18ca74e498c4e9e6d6e1eaf9ca9e91152e18620 | <ide><path>script/lib/include-path-in-packaged-app.js
<ide> const EXCLUDE_REGEXPS_SOURCES = [
<ide> escapeRegExp(path.join('build', 'Release', 'obj.target')),
<ide> escapeRegExp(path.join('build', 'Release', 'obj')),
<ide> escapeRegExp(path.join('build', 'Release', '.deps')),
<add> escapeRegExp(path.join('deps', 'libgit2')),
<ide> escapeRegExp(path.join('vendor', 'apm')),
<ide>
<ide> // These are only required in dev-mode, when pegjs grammars aren't precompiled
<ide> const EXCLUDE_REGEXPS_SOURCES = [
<ide> escapeRegExp(path.join('build', 'Release') + path.sep) + '.+\\.node\\.dSYM',
<ide> escapeRegExp(path.join('build', 'Release') + path.sep) + '.*\\.(pdb|lib|exp|map|ipdb|iobj)',
<ide>
<del> // Ignore test and example folders
<add> // Ignore node_module files we won't need at runtime
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + '_*te?sts?_*' + escapeRegExp(path.sep),
<del> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'examples?' + escapeRegExp(path.sep)
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'examples?' + escapeRegExp(path.sep),
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.md$',
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.d\\.ts$',
<add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.js\\.map$'
<ide> ]
<ide>
<ide> // Ignore spec directories in all bundled packages | 1 |
Text | Text | add v3.5.0-beta.1 to changelog | 428e41e864a2b109174b1c5111b2e10619a3c62d | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.5.0-beta.1 (August 28, 2018)
<add>
<add>- [#16877](https://github.com/emberjs/ember.js/pull/16877) [CLEANUP] Allow routes to be named "array" and "object"
<add>- [#16907](https://github.com/emberjs/ember.js/pull/16907) Upgrade to TypeScript 3.0
<add>
<ide> ### v3.4.0 (August 27, 2018)
<add>
<ide> - [#16603](https://github.com/emberjs/ember.js/pull/16603) [BUGFIX] Support mouseEnter/Leave events w/o jQuery
<ide> - [#16857](https://github.com/emberjs/ember.js/pull/16857) [BUGFIX] Prevents the recursive redefinition of root chains
<ide> - [#16854](https://github.com/emberjs/ember.js/pull/16854) [BUGFIX] Don't thread FactoryManager through createComponent | 1 |
Ruby | Ruby | fix a warning in prototype_helper_test, fixes | 984312cf85d40b9fae9e88dfc80ae61f085b36d1 | <ide><path>actionpack/lib/action_view/helpers/prototype_helper.rb
<ide> def update_page_tag(&block)
<ide>
<ide> protected
<ide> def loop_on_multiple_args(method, ids)
<del> record (if ids.size>1
<del> "#{javascript_object_for(ids)}.each(#{method})"
<del> else
<del> "#{method}(#{ids.first.to_json})"
<del> end)
<add> record (ids.size>1 ?
<add> "#{javascript_object_for(ids)}.each(#{method})" :
<add> "#{method}(#{ids.first.to_json})")
<ide> end
<ide>
<ide> def options_for_ajax(options) | 1 |
Ruby | Ruby | optimize active record batching | 2a42f444305a2413d1e3a78d5cecebe045901a94 | <ide><path>activerecord/lib/active_record/relation/batches.rb
<ide> def in_batches(of: 1000, start: nil, finish: nil, load: false, error_on_ignore:
<ide> end
<ide>
<ide> relation = relation.reorder(batch_order(order)).limit(batch_limit)
<del> relation = apply_limits(relation, start, finish, order)
<del> relation.skip_query_cache! # Retaining the results in the query cache would undermine the point of batching
<add> relation = apply_finish_limit(relation, finish, order) if finish
<ide> batch_relation = relation
<ide>
<ide> loop do
<add> batch_relation = apply_start_limit(relation, start, order) if start
<add>
<ide> if load
<del> records = batch_relation.records
<del> ids = records.map(&:id)
<del> yielded_relation = where(primary_key => ids)
<del> yielded_relation.load_records(records)
<add> records = batch_relation.uncached do
<add> batch_relation.limit(batch_limit + 1).records
<add> end
<add>
<add> start = records[batch_limit]&.id
<add> records = records.take(batch_limit)
<add>
<add> break if records.empty?
<add>
<add> raise ArgumentError.new("Primary key not included in the custom select clause") unless records.first.id
<add>
<add> batch_relation.load_records(records)
<ide> else
<del> ids = batch_relation.pluck(primary_key)
<del> yielded_relation = where(primary_key => ids)
<del> end
<add> stop = batch_relation.uncached do
<add> batch_relation.offset(batch_limit).pick(primary_key)
<add> end
<ide>
<del> break if ids.empty?
<add> if stop
<add> batch_relation = apply_finish_limit(batch_relation, stop, order, inclusive: false)
<add> end
<ide>
<del> primary_key_offset = ids.last
<del> raise ArgumentError.new("Primary key not included in the custom select clause") unless primary_key_offset
<add> start = stop
<add> end
<ide>
<del> yield yielded_relation
<add> yield batch_relation
<ide>
<del> break if ids.length < batch_limit
<add> break unless start
<ide>
<ide> if limit_value
<del> remaining -= ids.length
<add> remaining -= batch_relation.size
<ide>
<ide> if remaining == 0
<ide> # Saves a useless iteration when the limit is a multiple of the
<ide> # batch size.
<ide> break
<ide> elsif remaining < batch_limit
<add> batch_limit = remaining
<ide> relation = relation.limit(remaining)
<ide> end
<ide> end
<del>
<del> batch_relation = relation.where(
<del> predicate_builder[primary_key, primary_key_offset, order == :desc ? :lt : :gt]
<del> )
<ide> end
<ide> end
<ide>
<ide> def apply_start_limit(relation, start, order)
<ide> relation.where(predicate_builder[primary_key, start, order == :desc ? :lteq : :gteq])
<ide> end
<ide>
<del> def apply_finish_limit(relation, finish, order)
<del> relation.where(predicate_builder[primary_key, finish, order == :desc ? :gteq : :lteq])
<add> def apply_finish_limit(relation, finish, order, inclusive: true)
<add> operator = (order == :desc) ?
<add> (inclusive ? :gteq : :gt) :
<add> (inclusive ? :lteq : :lt)
<add>
<add> relation.where(predicate_builder[primary_key, finish, operator])
<ide> end
<ide>
<ide> def batch_order(order)
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_find_each
<ide>
<ide> assert_not_predicate firm.clients, :loaded?
<ide>
<del> assert_queries(4) do
<add> assert_queries(3) do
<ide> firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
<ide> end
<ide>
<ide> def test_find_each
<ide> def test_find_each_with_conditions
<ide> firm = companies(:first_firm)
<ide>
<del> assert_queries(2) do
<add> assert_queries(1) do
<ide> firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
<ide> assert_equal firm.id, c.firm_id
<ide> assert_equal "Microsoft", c.name
<ide><path>activerecord/test/cases/batches_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_each_should_execute_one_query_per_batch
<del> assert_queries(@total + 1) do
<add> assert_queries(@total) do
<ide> Post.find_each(batch_size: 1) do |post|
<ide> assert_kind_of Post, post
<ide> end
<ide> def test_each_should_return_a_sized_enumerator
<ide> end
<ide>
<ide> def test_each_enumerator_should_execute_one_query_per_batch
<del> assert_queries(@total + 1) do
<add> assert_queries(@total) do
<ide> Post.find_each(batch_size: 1).with_index do |post, index|
<ide> assert_kind_of Post, post
<ide> assert_kind_of Integer, index
<ide> def test_each_enumerator_should_execute_one_query_per_batch
<ide> end
<ide>
<ide> def test_each_should_raise_if_select_is_set_without_id
<del> assert_raise(ArgumentError) do
<add> error = assert_raise(ArgumentError) do
<ide> Post.select(:title).find_each(batch_size: 1) { |post|
<ide> flunk "should not call this block"
<ide> }
<ide> end
<add> assert_equal "Primary key not included in the custom select clause", error.message
<ide> end
<ide>
<ide> def test_each_should_execute_if_id_is_in_select
<ide> def test_logger_not_required
<ide> end
<ide>
<ide> def test_find_in_batches_should_return_batches
<del> assert_queries(@total + 1) do
<add> assert_queries(@total) do
<ide> Post.find_in_batches(batch_size: 1) do |batch|
<ide> assert_kind_of Array, batch
<ide> assert_kind_of Post, batch.first
<ide> def test_find_in_batches_should_return_batches
<ide> end
<ide>
<ide> def test_find_in_batches_should_start_from_the_start_option
<del> assert_queries(@total) do
<add> assert_queries(@total - 1) do
<ide> Post.find_in_batches(batch_size: 1, start: 2) do |batch|
<ide> assert_kind_of Array, batch
<ide> assert_kind_of Post, batch.first
<ide> def test_find_in_batches_should_start_from_the_start_option
<ide> end
<ide>
<ide> def test_find_in_batches_should_end_at_the_finish_option
<del> assert_queries(6) do
<add> assert_queries(5) do
<ide> Post.find_in_batches(batch_size: 1, finish: 5) do |batch|
<ide> assert_kind_of Array, batch
<ide> assert_kind_of Post, batch.first
<ide> def test_find_in_batches_should_end_at_the_finish_option
<ide> end
<ide>
<ide> def test_find_in_batches_shouldnt_execute_query_unless_needed
<del> assert_queries(2) do
<add> assert_queries(1) do
<ide> Post.find_in_batches(batch_size: @total) { |batch| assert_kind_of Array, batch }
<ide> end
<ide>
<ide> def test_find_in_batches_should_use_any_column_as_primary_key
<ide> end
<ide>
<ide> def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_specified
<del> assert_queries(Subscriber.count + 1) do
<add> assert_queries(Subscriber.count) do
<ide> Subscriber.find_in_batches(batch_size: 1) do |batch|
<ide> assert_kind_of Array, batch
<ide> assert_kind_of Subscriber, batch.first
<ide> def test_in_batches_should_be_loaded
<ide> end
<ide>
<ide> def test_in_batches_if_not_loaded_executes_more_queries
<del> assert_queries(@total + 1) do
<add> assert_queries(@total) do
<ide> Post.in_batches(of: 1, load: false) do |relation|
<ide> assert_not_predicate relation, :loaded?
<ide> end
<ide> end
<ide> end
<ide>
<ide> def test_in_batches_should_return_relations
<del> assert_queries(@total + 1) do
<add> assert_queries(@total) do
<ide> Post.in_batches(of: 1) do |relation|
<ide> assert_kind_of ActiveRecord::Relation, relation
<ide> end
<ide> def test_in_batches_should_start_from_the_start_option
<ide>
<ide> def test_in_batches_should_end_at_the_finish_option
<ide> post = Post.order("id DESC").where("id <= ?", 5).first
<del> assert_queries(7) do
<add> assert_queries(6) do
<ide> relation = Post.in_batches(of: 1, finish: 5, load: true).reverse_each.first
<ide> assert_equal post, relation.last
<ide> end
<ide> end
<ide>
<ide> def test_in_batches_shouldnt_execute_query_unless_needed
<del> assert_queries(2) do
<add> assert_queries(1) do
<ide> Post.in_batches(of: @total) { |relation| assert_kind_of ActiveRecord::Relation, relation }
<ide> end
<ide>
<ide> def test_in_batches_should_use_any_column_as_primary_key
<ide> end
<ide>
<ide> def test_in_batches_should_use_any_column_as_primary_key_when_start_is_not_specified
<del> assert_queries(Subscriber.count + 1) do
<add> assert_queries(Subscriber.count) do
<ide> Subscriber.in_batches(of: 1, load: true) do |relation|
<ide> assert_kind_of ActiveRecord::Relation, relation
<ide> assert_kind_of Subscriber, relation.first
<ide><path>activerecord/test/cases/scoping/named_scoping_test.rb
<ide> def test_nested_scoping
<ide> def test_scopes_batch_finders
<ide> assert_equal 4, Topic.approved.count
<ide>
<del> assert_queries(5) do
<add> assert_queries(4) do
<ide> Topic.approved.find_each(batch_size: 1) { |t| assert t.approved? }
<ide> end
<ide>
<del> assert_queries(3) do
<add> assert_queries(2) do
<ide> Topic.approved.find_in_batches(batch_size: 2) do |group|
<ide> group.each { |t| assert t.approved? }
<ide> end | 4 |
Javascript | Javascript | remove the callback from node.cat, node.fs.cat | e8a5d3d31141cca1bda02acd579da5a6eb5e4a44 | <ide><path>src/file.js
<ide> node.fs.exists = function (path, callback) {
<ide> p.addErrback(function () { callback(false); });
<ide> }
<ide>
<del>node.fs.cat = function (path, encoding, callback) {
<add>node.fs.cat = function (path, encoding) {
<ide> var open_promise = node.fs.open(path, node.O_RDONLY, 0666);
<ide> var cat_promise = new node.Promise();
<ide>
<ide> encoding = (encoding === "raw" ? node.RAW : node.UTF8);
<ide>
<ide> open_promise.addErrback(function () { cat_promise.emitError(); });
<ide> open_promise.addCallback(function (fd) {
<del> var content = (encoding == node.UTF8 ? "" : []);
<add> var content = (encoding === node.UTF8 ? "" : []);
<ide> var pos = 0;
<ide>
<ide> function readChunk () {
<ide><path>src/util.js
<ide> node.encodeUtf8 = function (array) {
<ide> return String.fromCharCode.apply(String, array);
<ide> };
<ide>
<del>node.cat = function(location, encoding, callback) {
<add>node.cat = function(location, encoding) {
<ide> var url_re = new RegExp("^http:\/\/");
<ide> var f = url_re.exec(location) ? node.http.cat : node.fs.cat;
<del> return f(location, encoding, callback);
<add> return f(location, encoding);
<ide> };
<ide>
<ide> node.path = new function () { | 2 |
Text | Text | fix ubuntu installation instructions page | eb0a208f4bad5623e360fa936bfd230cd72414c4 | <ide><path>docs/installation/ubuntulinux.md
<ide> your `apt` sources to the new Docker repository.
<ide> Docker's `apt` repository contains Docker 1.7.1 and higher. To set `apt` to use
<ide> packages from the new repository:
<ide>
<del>1. If you haven't already done so, log into your Ubuntu instance.
<add>1. If you haven't already done so, log into your Ubuntu instance as a privileged user.
<ide>
<ide> 2. Open a terminal window.
<ide> | 1 |
Python | Python | update build script | aa4bc9eb83d61f4c6bf62cf09c986ec11d8106df | <ide><path>tools/win32build/build.py
<ide> def build(arch, pyver):
<ide>
<ide> try:
<ide> try:
<del> print "Executing command %s" % cmd
<ide> subprocess.check_call(cmd, shell = True, stderr = subprocess.STDOUT, stdout = f)
<ide> finally:
<ide> f.close()
<ide> def build(arch, pyver):
<ide> Look at the build log (%s).""" % (cmd, str(e), build_log)
<ide> raise Exception(msg)
<ide>
<add> move_binary(arch, pyver)
<add>
<add>def move_binary(arch, pyver):
<add> if not os.path.exists("binaries"):
<add> os.makedirs("binaries")
<add>
<add> shutil.move(os.path.join('dist', get_windist_exec(pyver)),
<add> os.path.join("binaries", get_binary_name(arch)))
<add>
<ide> def get_numpy_version():
<ide> import __builtin__
<ide> __builtin__.__NUMPY_SETUP__ = True
<ide> from numpy.version import version
<ide> return version
<ide>
<add>def get_binary_name(arch):
<add> return "numpy-%s-%s.exe" % (get_numpy_version(), arch)
<add>
<ide> def get_windist_exec(pyver):
<ide> """Return the name of the installer built by wininst command."""
<ide> # Yeah, the name logic is harcoded in distutils. We have to reproduce it
<ide> # here
<del> name = "numpy-%s.win32-%s.exe" % (get_numpy_version(), pyver)
<add> name = "numpy-%s.win32-py%s.exe" % (get_numpy_version(), pyver)
<ide> return name
<ide>
<ide> USAGE = """build.py ARCH PYTHON_VERSION
<ide> def get_windist_exec(pyver):
<ide>
<ide> if __name__ == '__main__':
<ide> if len(sys.argv) < 3:
<del> raise ValueError(Usage)
<add> raise ValueError(USAGE)
<ide> sys.exit(-1)
<ide>
<del> #arch = sys.argv[1]
<add> arch = sys.argv[1]
<ide> pyver = sys.argv[2]
<add> #build(arch, pyver)
<ide> for arch in SITECFG.keys():
<ide> build(arch, pyver) | 1 |
Python | Python | add tests for 0-dim array | f9a3e177f8cb08aeac2cccdb1067871c97bbe065 | <ide><path>numpy/core/tests/test_ufunc.py
<ide> def test_inplace_fancy_indexing(self):
<ide> np.negative.at(a, [2,5,2])
<ide> assert_equal(a, [0, 1, 2, 3, 4, -5, 6, 7, 8, 9])
<ide>
<del> # test exception when indices dimensions < first operand dimensions
<del> a = np.arange(27).reshape(3,3,3)
<del> b = np.array([100,200,300])
<del> assert_raises(ValueError, np.add.at, a, [1,2,1], b)
<del> assert_raises(ValueError, np.add.at, a, ([1,2,1],), b)
<add> # Test 0-dim array
<add> a = np.array(0)
<add> np.add.at(a, (), 1)
<add> assert_equal(a, 1)
<add>
<add> assert_raises(IndexError, np.add.at, a, 0, 1)
<add> assert_raises(IndexError, np.add.at, a, [], 1)
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
Ruby | Ruby | add requires for mimemagic | f4aa54d48793339386d10ff9a3675d749e65a022 | <ide><path>activestorage/app/models/active_storage/blob/representable.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "mimemagic"
<add>
<ide> module ActiveStorage::Blob::Representable
<ide> extend ActiveSupport::Concern
<ide>
<ide><path>activestorage/app/models/active_storage/variation.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "mimemagic"
<add>
<ide> # A set of transformations that can be applied to a blob to create a variant. This class is exposed via
<ide> # the ActiveStorage::Blob#variant method and should rarely be used directly.
<ide> # | 2 |
Python | Python | add a keys method to bindingdict | 4248a6c499cf31d2e38199f05a42e7a131dc014e | <ide><path>rest_framework/serializers.py
<ide> def __delitem__(self, key):
<ide> def items(self):
<ide> return self.fields.items()
<ide>
<add> def keys(self):
<add> return self.fields.keys()
<add>
<ide> def values(self):
<ide> return self.fields.values()
<ide> | 1 |
Text | Text | apply suggestions from code review | c8554296125ad858ac1130e0ec5572007d67cb7a | <ide><path>docs/Manpage.md
<ide> Note that environment variables must have a value set to be detected. For exampl
<ide> *Default:* `15`.
<ide>
<ide> * `HOMEBREW_FORBIDDEN_LICENSES`:
<del> Use this environment variable to define a blacklist of space separated licenses and Homebrew will avoid installing the packages with those licenses.
<add> Use this environment variable to define a denylist of space separated licenses and Homebrew will refuse to install packages known to have those licenses.
<ide>
<ide> * `HOMEBREW_FORCE_BREWED_CURL`:
<ide> If set, always use a Homebrew-installed `curl`(1) rather than the system version. Automatically set if the system version of `curl` is too old. | 1 |
Javascript | Javascript | fix bug in getrawstack | d17ab332ec5d117e5849af935c9bfcaea19f828c | <ide><path>src/compile-cache.js
<ide> require('source-map-support').install({
<ide> })
<ide>
<ide> var sourceMapPrepareStackTrace = Error.prepareStackTrace
<del>var prepareStackTrace = sourceMapPrepareStackTrace
<add>
<add>// Enable Grim to access the raw stack by customizing Error.prepareStackTrace
<add>function prepareStackTraceWithRawStack (error, frames) {
<add> error.rawStack = frames
<add> return sourceMapPrepareStackTrace(error, frames)
<add>}
<ide>
<ide> // Prevent coffee-script from reassigning Error.prepareStackTrace
<ide> Object.defineProperty(Error, 'prepareStackTrace', {
<del> get: function () { return prepareStackTrace },
<add> get: function () { return prepareStackTraceWithRawStack },
<ide> set: function (newValue) {}
<ide> })
<ide>
<del>// Enable Grim to access the raw stack without reassigning Error.prepareStackTrace
<ide> Error.prototype.getRawStack = function () { // eslint-disable-line no-extend-native
<del> prepareStackTrace = getRawStack
<del> var result = this.stack
<del> prepareStackTrace = sourceMapPrepareStackTrace
<del> return result
<del>}
<del>
<del>function getRawStack (_, stack) {
<del> return stack
<add> // Call this.stack first to ensure rawStack is generated
<add> this.stack
<add> return this.rawStack
<ide> }
<ide>
<ide> Object.keys(COMPILERS).forEach(function (extension) { | 1 |
Text | Text | remove schema mention | be655b4742d175cf6b3ce19d2304d2059b68684e | <ide><path>docs/how-to-translate-the-website.md
<ide> To change text on the client side of things, go to the relevant `.json` file, fi
<ide>
<ide> If the text you want to add to the client exists in the relevant `.json` file, use the existing key. Otherwise, create a new key.
<ide>
<del>The matching filename`-schema.js` file is the "source of truth" for all of the `.json` files sharing the same name. If you need to add a new key, add it there. Then, add the key to **all** of the `translations.json` files.
<add>The English file is the "source of truth" for all of the `.json` files sharing the same name. If you need to add a new key, add it there. Then, add the key to **all** of the `translations.json` files.
<ide>
<ide> > [!NOTE]
<ide> > Use English text for all languages if the file is translated through Crowdin. The tests will fail if you don't. | 1 |
Python | Python | fix a bug with referencing an invalid variable | 90951ebaa277140a8ffeff4110aab77bebc753da | <ide><path>libcloud/compute/drivers/cloudstack.py
<ide> def create_node(self, name, size, image, location=None, extra_args=None,
<ide> location = self.list_locations()[0]
<ide>
<ide> if 'network_id' in kwargs:
<del> request_args['networkids'] = network_id
<add> request_args['networkids'] = kwargs['network_id']
<ide>
<ide> result = self._async_request(
<ide> 'deployVirtualMachine', name=name, displayname=name, | 1 |
Python | Python | fix documented return value of tostring/tobytes | ef269d55dfc11b9ca3a66b71c8d0e64703a8f359 | <ide><path>numpy/add_newdocs.py
<ide> def luf(lamdaexpr, *args, **kwargs):
<ide>
<ide>
<ide> tobytesdoc = """
<del> a.tostring(order='C')
<add> a.{name}(order='C')
<ide>
<del> Construct a Python string containing the raw data bytes in the array.
<add> Construct Python bytes containing the raw data bytes in the array.
<ide>
<del> Constructs a Python string showing a copy of the raw contents of
<del> data memory. The string can be produced in either 'C' or 'Fortran',
<add> Constructs Python bytes showing a copy of the raw contents of
<add> data memory. The bytes object can be produced in either 'C' or 'Fortran',
<ide> or 'Any' order (the default is 'C'-order). 'Any' order means C-order
<ide> unless the F_CONTIGUOUS flag in the array is set, in which case it
<ide> means 'Fortran' order.
<ide> def luf(lamdaexpr, *args, **kwargs):
<ide>
<ide> Returns
<ide> -------
<del> s : str
<del> A Python string exhibiting a copy of `a`'s raw data.
<add> s : bytes
<add> Python bytes exhibiting a copy of `a`'s raw data.
<ide>
<ide> Examples
<ide> --------
<ide> >>> x = np.array([[0, 1], [2, 3]])
<ide> >>> x.tobytes()
<del> '\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00'
<add> b'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00'
<ide> >>> x.tobytes('C') == x.tobytes()
<ide> True
<ide> >>> x.tobytes('F')
<del> '\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00'
<add> b'\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00'
<ide>
<ide> """
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray',
<del> ('tostring', tobytesdoc.format(deprecated=
<add> ('tostring', tobytesdoc.format(name='tostring',
<add> deprecated=
<ide> 'This function is a compatibility '
<ide> 'alias for tobytes. Despite its '
<ide> 'name it returns bytes not '
<ide> 'strings.')))
<ide> add_newdoc('numpy.core.multiarray', 'ndarray',
<del> ('tobytes', tobytesdoc.format(deprecated='.. versionadded:: 1.9.0')))
<add> ('tobytes', tobytesdoc.format(name='tobytes',
<add> deprecated='.. versionadded:: 1.9.0')))
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('trace',
<ide> """ | 1 |
PHP | PHP | remove extra space | 8444190a742d7d77818f3938b214a95a4585ea35 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function toArray()
<ide> {
<ide> return array_map(function ($value) {
<ide> return $value instanceof Arrayable ? $value->toArray() : $value;
<del>
<ide> }, $this->items);
<ide> }
<ide> | 1 |
Ruby | Ruby | push module building to the constructor | 71aba97d8d0c1b0264646c64aa3dc5661a90424c | <ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb
<ide> def valid_options
<ide>
<ide> attr_reader :block_extension
<ide>
<del> def initialize(*args, &extension)
<add> def initialize(*args)
<ide> super(*args)
<del> @block_extension = extension
<add> @mod = nil
<add> if block_given?
<add> @mod = Module.new(&Proc.new)
<add> @scope = wrap_scope @scope, @mod
<add> end
<ide> end
<ide>
<ide> def build
<ide> def define_callbacks(model, reflection)
<ide> end
<ide>
<ide> def define_extensions(model)
<del> if block_extension
<del> mod = Module.new(&block_extension)
<add> if @mod
<ide> extension_module_name = "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
<del>
<del> model.parent.const_set(extension_module_name, mod)
<del>
<del> prev_scope = @scope
<del>
<del> if prev_scope
<del> @scope = proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
<del> else
<del> @scope = proc { extending(mod) }
<del> end
<add> model.parent.const_set(extension_module_name, @mod)
<ide> end
<ide> end
<ide>
<ide> def #{name.to_s.singularize}_ids=(ids)
<ide> end
<ide> CODE
<ide> end
<add>
<add> private
<add>
<add> def wrap_scope(scope, mod)
<add> prev_scope = scope
<add>
<add> if prev_scope
<add> proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
<add> else
<add> proc { extending(mod) }
<add> end
<add> end
<ide> end
<ide> end | 1 |
Java | Java | fix padding with text on android | 7562f9d6f501ce2f57153e4f62aed15e7ae4c709 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTTextInput.java
<ide> public void setBackgroundColor(int backgroundColor) {
<ide> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {
<ide> super.onCollectExtraUpdates(uiViewOperationQueue);
<ide> if (mJsEventCount != UNSET) {
<del> ReactTextUpdate reactTextUpdate = new ReactTextUpdate(getText(), mJsEventCount, false);
<add> ReactTextUpdate reactTextUpdate =
<add> new ReactTextUpdate(getText(), mJsEventCount, false, getPadding());
<ide> uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate);
<ide> }
<ide> } | 1 |
Python | Python | simplify test settings | 76ede5beda74c1bb224f038d635ab586416bfca8 | <ide><path>tests/conftest.py
<ide> def pytest_configure():
<ide> MIDDLEWARE_CLASSES=(
<ide> 'django.middleware.common.CommonMiddleware',
<ide> 'django.contrib.sessions.middleware.SessionMiddleware',
<del> 'django.middleware.csrf.CsrfViewMiddleware',
<ide> 'django.contrib.auth.middleware.AuthenticationMiddleware',
<ide> 'django.contrib.messages.middleware.MessageMiddleware',
<ide> ),
<ide> def pytest_configure():
<ide> 'django.contrib.contenttypes',
<ide> 'django.contrib.sessions',
<ide> 'django.contrib.sites',
<del> 'django.contrib.messages',
<ide> 'django.contrib.staticfiles',
<ide>
<ide> 'rest_framework',
<ide> 'rest_framework.authtoken',
<ide> 'tests',
<ide> ),
<ide> PASSWORD_HASHERS=(
<del> 'django.contrib.auth.hashers.SHA1PasswordHasher',
<del> 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
<del> 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
<del> 'django.contrib.auth.hashers.BCryptPasswordHasher',
<ide> 'django.contrib.auth.hashers.MD5PasswordHasher',
<del> 'django.contrib.auth.hashers.CryptPasswordHasher',
<ide> ),
<ide> )
<ide> | 1 |
Ruby | Ruby | add sprockets environment to application | 3e7985c9c1a6899ac06857bd8e6f29b48ad87cea | <ide><path>railties/lib/rails/application.rb
<ide> def config
<ide> @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
<ide> end
<ide>
<add> def self.default_sprockets_paths
<add> [
<add> "app/assets",
<add> "app/javascripts",
<add> "app/stylesheets",
<add> "vendor/plugins/*/app/assets",
<add> "vendor/plugins/*/app/javascripts",
<add> "vendor/plugins/*/app/stylesheets",
<add> "vendor/plugins/*/assets",
<add> "vendor/plugins/*/javascripts",
<add> "vendor/plugins/*/stylesheets"
<add> ]
<add> end
<add>
<add> def assets
<add> @assets ||= build_asset_environment
<add> end
<add>
<add> def build_asset_environment
<add> require 'sprockets'
<add>
<add> env = Sprockets::Environment.new(root.to_s)
<add> env.logger = Rails.logger
<add> env.ensure_fresh_assets = !config.action_controller.perform_caching
<add>
<add> self.class.default_sprockets_paths.each do |pattern|
<add> Dir[root.join(pattern)].each do |dir|
<add> env.paths << dir
<add> end
<add> end
<add>
<add> env
<add> end
<add>
<ide> protected
<ide>
<ide> def default_asset_path | 1 |
Ruby | Ruby | avoid dupes add fallback logic for coders | 975c9c9d4498a4b4a00de713e932abe3299a4007 | <ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def read_attribute(attr_name)
<ide> # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
<ide> name = attr_name.to_s
<ide> @attributes_cache[name] || @attributes_cache.fetch(name) {
<del> column = @columns_hash.fetch(name) {
<del> return @attributes.fetch(name) {
<del> if name == 'id' && self.class.primary_key != name
<del> read_attribute(self.class.primary_key)
<del> end
<del> }
<del> }
<add> column = @column_types_override[name] if @column_types_override
<add> column ||= @column_types[name]
<add>
<add> return @attributes.fetch(name) {
<add> if name == 'id' && self.class.primary_key != name
<add> read_attribute(self.class.primary_key)
<add> end
<add> } unless column
<ide>
<ide> value = @attributes.fetch(name) {
<ide> return block_given? ? yield(name) : nil
<ide><path>activerecord/lib/active_record/core.rb
<ide> def initialize(attributes = nil)
<ide> defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
<ide>
<ide> @attributes = self.class.initialize_attributes(defaults)
<del> @columns_hash = self.class.column_types.dup
<add> @column_types_override = nil
<add> @column_types = self.class.column_types
<ide>
<ide> init_internals
<ide> init_changed_attributes
<ide> def initialize(attributes = nil)
<ide> # post.title # => 'hello world'
<ide> def init_with(coder)
<ide> @attributes = self.class.initialize_attributes(coder['attributes'])
<del> @columns_hash = self.class.column_types.merge(coder['column_types'] || {})
<add> @column_types_override = coder['column_types']
<add> @column_types = self.class.column_types
<ide>
<ide> init_internals
<ide>
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def reload(options = nil)
<ide> end
<ide>
<ide> @attributes.update(fresh_object.instance_variable_get('@attributes'))
<del> @columns_hash = fresh_object.instance_variable_get('@columns_hash')
<ide>
<del> @attributes_cache = {}
<add> @column_types = self.class.column_types
<add> @column_types_override = fresh_object.instance_variable_get('@columns_types_override')
<add> @attributes_cache = {}
<ide> self
<ide> end
<ide>
<ide><path>activerecord/test/cases/serialized_attribute_test.rb
<ide> def test_serialized_column_should_not_be_wrapped_twice
<ide> Topic.create(content: myobj)
<ide>
<ide> Topic.all.each do |topic|
<del> type = topic.instance_variable_get("@columns_hash")["content"]
<add> type = Topic.column_types["content"]
<ide> assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type)
<ide> end
<ide> end | 4 |
Text | Text | update quickstart to django 2.0 routing syntax | 0860ef9eeebf77e1780b0d86b3fdf01f5aaa5cc3 | <ide><path>docs/tutorial/quickstart.md
<ide> We can easily break these down into individual views if we need to, but using vi
<ide>
<ide> Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
<ide>
<del> from django.conf.urls import url, include
<add> from django.urls import include, path
<ide> from rest_framework import routers
<ide> from tutorial.quickstart import views
<ide>
<ide> Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
<ide> # Wire up our API using automatic URL routing.
<ide> # Additionally, we include login URLs for the browsable API.
<ide> urlpatterns = [
<del> url(r'^', include(router.urls)),
<del> url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
<add> path('', include(router.urls)),
<add> path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
<ide> ]
<ide>
<ide> Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. | 1 |
Javascript | Javascript | fix intersection uv for non-indexed buffergeometry | 6dffe4a2bf5213b4eb29d50b92f59f6d7656c3d5 | <ide><path>src/objects/Mesh.js
<ide> THREE.Mesh.prototype.raycast = ( function () {
<ide>
<ide> if ( distance < raycaster.near || distance > raycaster.far ) continue;
<ide>
<add> a = i / 3;
<add> b = a + 1;
<add> c = a + 2;
<add>
<ide> var uv;
<ide>
<ide> if ( attributes.uv !== undefined ) {
<ide>
<ide> var uvs = attributes.uv.array;
<del> uvA.fromArray( uvs, i );
<del> uvB.fromArray( uvs, i + 2 );
<del> uvC.fromArray( uvs, i + 4 );
<add> uvA.fromArray( uvs, a * 2 );
<add> uvB.fromArray( uvs, b * 2 );
<add> uvC.fromArray( uvs, c * 2 );
<ide> uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
<ide>
<ide> }
<ide>
<del> a = i / 3;
<del> b = a + 1;
<del> c = a + 2;
<del>
<ide> intersects.push( {
<ide>
<ide> distance: distance, | 1 |
Ruby | Ruby | log unnamed bind params | fe62bb5762edfc7ee4c3bc3048b77dcb5c4c8136 | <ide><path>activerecord/lib/active_record/log_subscriber.rb
<ide> def sql(event)
<ide>
<ide> binds = []
<ide> payload[:binds].each_with_index do |attr, i|
<del> attribute_name = attr.respond_to?(:name) ? attr.name : attr[i].name
<add> attribute_name = if attr.respond_to?(:name)
<add> attr.name
<add> elsif attr.respond_to?(:[]) && attr[i].respond_to?(:name)
<add> attr[i].name
<add> else
<add> nil
<add> end
<add>
<ide> filtered_params = filter(attribute_name, casted_params[i])
<ide>
<ide> binds << render_bind(attr, filtered_params) | 1 |
PHP | PHP | change config option in file driver | 1ca831d5f646e7985c5e4b8f2497a6f3b142fd5b | <ide><path>src/Illuminate/Session/SessionManager.php
<ide> protected function createCookieDriver()
<ide> */
<ide> protected function createFileDriver()
<ide> {
<del> $path = $this->app['config']['session.path'];
<add> $path = $this->app['config']['session.files'];
<ide>
<ide> return new FileStore($this->app['files'], $path);
<ide> } | 1 |
Text | Text | fix typo on line 47 "make" to "makes" | 7fbb46c31656e552a5b02c7dbc656b437f851136 | <ide><path>docs/Networking.md
<ide> Take a look at the [Fetch Request docs](https://developer.mozilla.org/en-US/docs
<ide>
<ide> The above examples show how you can make a request. In many cases, you will want to do something with the response.
<ide>
<del>Networking is an inherently asynchronous operation. Fetch methods will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that make it straightforward to write code that works in an asynchronous manner:
<add>Networking is an inherently asynchronous operation. Fetch methods will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that makes it straightforward to write code that works in an asynchronous manner:
<ide>
<ide> ```js
<ide> function getMoviesFromApiAsync() { | 1 |
Text | Text | improve build instructions | 2e9c1ead76aaae8fde004e3cacde1e36c5fd2104 | <ide><path>README.md
<ide> Environments in which to use jQuery
<ide> What you need to build your own jQuery
<ide> --------------------------------------
<ide>
<del>In order to build jQuery, you need to have Node.js/npm latest and git 1.7 or later.
<del>(Earlier versions might work OK, but are not tested.)
<add>In order to build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. Earlier versions might work, but are not supported.
<ide>
<del>For Windows you have to download and install [git](http://git-scm.com/downloads) and [Node.js](http://nodejs.org/download/).
<add>For Windows, you have to download and install [git](http://git-scm.com/downloads) and [Node.js](http://nodejs.org/download/).
<ide>
<ide> Mac OS users should install [Homebrew](http://mxcl.github.com/homebrew/). Once Homebrew is installed, run `brew install git` to install git,
<ide> and `brew install node` to install Node.js.
<ide> Make sure you have `grunt` installed by testing:
<ide> grunt -v
<ide> ```
<ide>
<del>Now by running `grunt` command, in the jquery directory, you could build full version of jQuery, just like with `npm run build` command:
<add>Now by running the `grunt` command, in the jquery directory, you can build a full version of jQuery, just like with a `npm run build` command:
<ide> ```
<ide> grunt
<ide> ``` | 1 |
Javascript | Javascript | add new rule disallownewlinebeforeblockstatements | fb210eb85e9a4baaefc20109a9b41e134c0568df | <ide><path>examples/js/Octree.js
<ide> tmin;
<ide>
<ide> // ray would intersect in reverse direction, i.e. this is behind ray
<del> if ( tmax < 0 )
<del> {
<add> if ( tmax < 0 ) {
<ide>
<ide> return false;
<ide>
<ide><path>examples/js/SimplexNoise.js
<ide> SimplexNoise.prototype.noise3d = function( xin, yin, zin ) {
<ide> var i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords
<ide> if ( x0 >= y0 ) {
<ide>
<del> if ( y0 >= z0 )
<del> {
<add> if ( y0 >= z0 ) {
<ide>
<ide> i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
<ide>
<ide><path>examples/js/Sparks.js
<ide> SPARKS.Emitter.prototype = {
<ide>
<ide> // Update activities
<ide> len = this._activities.length;
<del> for ( i = 0; i < len; i ++ )
<del> {
<add> for ( i = 0; i < len; i ++ ) {
<ide>
<ide> this._activities[ i ].update( this, time );
<ide>
<ide> SPARKS.Emitter.prototype = {
<ide> var action;
<ide> var len2 = this._particles.length;
<ide>
<del> for ( j = 0; j < len; j ++ )
<del> {
<add> for ( j = 0; j < len; j ++ ) {
<ide>
<ide> action = this._actions[ j ];
<del> for ( i = 0; i < len2; ++ i )
<del> {
<add> for ( i = 0; i < len2; ++ i ) {
<ide>
<ide> particle = this._particles[ i ];
<ide> action.update( this, particle, time );
<ide> SPARKS.Emitter.prototype = {
<ide>
<ide>
<ide> // remove dead particles
<del> for ( i = len2; i --; )
<del> {
<add> for ( i = len2; i --; ) {
<ide>
<ide> particle = this._particles[ i ];
<del> if ( particle.isDead )
<del> {
<add> if ( particle.isDead ) {
<ide>
<ide> //particle =
<ide> this._particles.splice( i, 1 );
<ide> SPARKS.Age = function( easing ) {
<ide> SPARKS.Age.prototype.update = function ( emitter, particle, time ) {
<ide>
<ide> particle.age += time;
<del> if ( particle.age >= particle.lifetime )
<del> {
<add> if ( particle.age >= particle.lifetime ) {
<ide>
<ide> particle.energy = 0;
<ide> particle.isDead = true;
<ide>
<ide> }
<del> else
<del> {
<add> else {
<ide>
<ide> var t = this._easing( particle.age / particle.lifetime );
<ide> particle.energy = - 1 * t + 1;
<ide> SPARKS.Utils = {
<ide>
<ide> },
<ide>
<del> getPerpendicular: function( v )
<del> {
<add> getPerpendicular: function( v ) {
<ide>
<del> if ( v.x == 0 )
<del> {
<add> if ( v.x == 0 ) {
<ide>
<ide> return new THREE.Vector3D( 1, 0, 0 );
<ide>
<ide> }
<del> else
<del> {
<add> else {
<ide>
<ide> var temp = new THREE.Vector3( v.y, - v.x, 0 );
<ide> return temp.normalize();
<ide><path>examples/js/WaterShader.js
<ide> THREE.Water = function ( renderer, camera, scene, options ) {
<ide>
<ide> if ( camera instanceof THREE.PerspectiveCamera )
<ide> this.camera = camera;
<del> else
<del> {
<add> else {
<ide>
<ide> this.camera = new THREE.PerspectiveCamera();
<ide> console.log( this.name + ': camera is not a Perspective Camera!' )
<ide> THREE.Water = function ( renderer, camera, scene, options ) {
<ide>
<ide> this.material.uniforms.eye.value = this.eye;
<ide>
<del> if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) )
<del> {
<add> if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
<ide>
<ide> this.texture.generateMipmaps = false;
<ide> this.texture.minFilter = THREE.LinearFilter;
<ide><path>examples/js/crossfade/scenes.js
<ide> function generateGeometry( objectType, numObjects ) {
<ide>
<ide> scale.x = Math.random() * 200 + 100;
<ide>
<del> if ( objectType == "cube" )
<del> {
<add> if ( objectType == "cube" ) {
<ide>
<ide> geom = new THREE.BoxGeometry( 1, 1, 1 );
<ide> scale.y = Math.random() * 200 + 100;
<ide> scale.z = Math.random() * 200 + 100;
<ide> color.setRGB( 0, 0, Math.random() + 0.1 );
<ide>
<ide> }
<del> else if ( objectType == "sphere" )
<del> {
<add> else if ( objectType == "sphere" ) {
<ide>
<ide> geom = new THREE.IcosahedronGeometry( 1, 1 );
<ide> scale.y = scale.z = scale.x;
<ide><path>examples/js/crossfade/transition.js
<ide> function Transition ( sceneA, sceneB ) {
<ide> this.render = function( delta ) {
<ide>
<ide> // Transition animation
<del> if ( transitionParams.animateTransition )
<del> {
<add> if ( transitionParams.animateTransition ) {
<ide>
<ide> var t = ( 1 + Math.sin( transitionParams.transitionSpeed * clock.getElapsedTime() / Math.PI ) ) / 2;
<ide> transitionParams.transition = THREE.Math.smoothstep( t, 0.3, 0.7 );
<ide>
<ide> // Change the current alpha texture after each transition
<del> if ( transitionParams.loopTexture && ( transitionParams.transition == 0 || transitionParams.transition == 1 ) )
<del> {
<add> if ( transitionParams.loopTexture && ( transitionParams.transition == 0 || transitionParams.transition == 1 ) ) {
<ide>
<del> if ( this.needChange )
<del> {
<add> if ( this.needChange ) {
<ide>
<ide> transitionParams.texture = ( transitionParams.texture + 1 ) % this.textures.length;
<ide> this.quadmaterial.uniforms.tMixTexture.value = this.textures[ transitionParams.texture ];
<ide><path>examples/js/loaders/AWDLoader.js
<ide> AWDProperties = function() {}
<ide>
<ide> AWDProperties.prototype = {
<del> set : function( key, value )
<del> {
<add> set : function( key, value ) {
<ide>
<ide> this[ key ] = value;
<ide>
<ide> },
<ide>
<del> get : function( key, fallback )
<del> {
<add> get : function( key, fallback ) {
<ide>
<ide> if ( this.hasOwnProperty( key ) )
<ide> return this[ key ];
<ide>
<ide> mtx_data = this.parseMatrix4();
<ide>
<del> } else
<del> {
<add> } else {
<ide>
<ide> mtx_data = new THREE.Matrix4();
<ide>
<ide><path>examples/js/loaders/AssimpJSONLoader.js
<ide> THREE.AssimpJSONLoader.prototype = {
<ide> // This header is used to disambiguate between
<ide> // different JSON-based file formats.
<ide> metadata = json.__metadata__;
<del> if ( typeof metadata !== 'undefined' )
<del> {
<add> if ( typeof metadata !== 'undefined' ) {
<ide>
<ide> // Check if assimp2json at all
<ide> if ( metadata.format !== 'assimp2json' ) {
<ide><path>examples/js/postprocessing/GlitchPass.js
<ide> THREE.GlitchPass = function ( dt_size ) {
<ide>
<ide> THREE.GlitchPass.prototype = {
<ide>
<del> render: function ( renderer, writeBuffer, readBuffer, delta )
<del> {
<add> render: function ( renderer, writeBuffer, readBuffer, delta ) {
<ide>
<ide> this.uniforms[ "tDiffuse" ].value = readBuffer;
<ide> this.uniforms[ 'seed' ].value = Math.random();//default seeding
<ide> this.uniforms[ 'byp' ].value = 0;
<ide>
<del> if ( this.curF % this.randX == 0 || this.goWild == true )
<del> {
<add> if ( this.curF % this.randX == 0 || this.goWild == true ) {
<ide>
<ide> this.uniforms[ 'amount' ].value = Math.random() / 30;
<ide> this.uniforms[ 'angle' ].value = THREE.Math.randFloat( - Math.PI, Math.PI );
<ide> THREE.GlitchPass.prototype = {
<ide> this.generateTrigger();
<ide>
<ide> }
<del> else if ( this.curF % this.randX < this.randX / 5 )
<del> {
<add> else if ( this.curF % this.randX < this.randX / 5 ) {
<ide>
<ide> this.uniforms[ 'amount' ].value = Math.random() / 90;
<ide> this.uniforms[ 'angle' ].value = THREE.Math.randFloat( - Math.PI, Math.PI );
<ide> THREE.GlitchPass.prototype = {
<ide> this.uniforms[ 'seed_y' ].value = THREE.Math.randFloat( - 0.3, 0.3 );
<ide>
<ide> }
<del> else if ( this.goWild == false )
<del> {
<add> else if ( this.goWild == false ) {
<ide>
<ide> this.uniforms[ 'byp' ].value = 1;
<ide>
<ide> }
<ide> this.curF ++;
<ide>
<ide> this.quad.material = this.material;
<del> if ( this.renderToScreen )
<del> {
<add> if ( this.renderToScreen ) {
<ide>
<ide> renderer.render( this.scene, this.camera );
<ide>
<ide> }
<del> else
<del> {
<add> else {
<ide>
<ide> renderer.render( this.scene, this.camera, writeBuffer, false );
<ide>
<ide> }
<ide>
<ide> },
<del> generateTrigger: function()
<del> {
<add> generateTrigger: function() {
<ide>
<ide> this.randX = THREE.Math.randInt( 120, 240 );
<ide>
<ide> },
<del> generateHeightmap: function( dt_size )
<del> {
<add> generateHeightmap: function( dt_size ) {
<ide>
<ide> var data_arr = new Float32Array( dt_size * dt_size * 3 );
<ide> console.log( dt_size );
<ide> var length = dt_size * dt_size;
<ide>
<del> for ( var i = 0; i < length; i ++ )
<del> {
<add> for ( var i = 0; i < length; i ++ ) {
<ide>
<ide> var val = THREE.Math.randFloat( 0, 1 );
<ide> data_arr[ i * 3 + 0 ] = val; | 9 |
Javascript | Javascript | simplify loop in parser | 26ce1ae647d75dfda2359412cc7add0c26f77484 | <ide><path>lib/url.js
<ide> Url.prototype.resolveObject = function resolveObject(relative) {
<ide>
<ide> // if the path is allowed to go above the root, restore leading ..s
<ide> if (!mustEndAbs && !removeAllDots) {
<del> for (; up--; up) {
<add> while (up--) {
<ide> srcPath.unshift('..');
<ide> }
<ide> } | 1 |
Ruby | Ruby | fuse the `rpath` loops | ffb3c9cff9bf56b9f920f6b8ae84d38c2bc34a2b | <ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb
<ide> def fix_dynamic_linkage
<ide> change_install_name(bad_name, new_name, file) unless new_name == bad_name
<ide> end
<ide>
<del> # Count duplicate rpaths. We need to keep track of this ourselves
<del> # because the MachO data is cached and this cache is not updated
<del> # after modification with #delete_rpath.
<del> rpath_dupe_count = Hash.new { |h, k| h[k] = -1 }
<del> file.rpaths.each do |rpath|
<del> rpath_dupe_count[rpath] += 1
<del> end
<add> # Keep track of the rpath counts for deletion of duplicates.
<add> # We need to track this here since we cache the MachO data [0]
<add> # and this cache is not updated after modification with #delete_rpath.
<add> #
<add> # [0] See os/mac/mach.rb.
<add> rpath_count = Hash.new { |h, k| h[k] = file.rpaths.count(k) }
<ide>
<ide> each_linkage_for(file, :rpaths) do |bad_name|
<del> # Strip duplicate rpaths and rpaths rooted in the build directory
<add> # Strip duplicate rpaths and rpaths rooted in the build directory.
<ide> next if !bad_name.start_with?(HOMEBREW_TEMP.to_s) &&
<ide> !bad_name.start_with?(HOMEBREW_TEMP.realpath.to_s) &&
<del> (rpath_dupe_count[bad_name] <= 0)
<add> (rpath_count[bad_name] == 1)
<ide>
<del> rpath_dupe_count[bad_name] -= 1
<add> rpath_count[bad_name] -= 1
<ide> delete_rpath(bad_name, file)
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix deopt for the field load of `.concat` | 9616516c95bf2c5a4c32b5269555b397897c4d6e | <ide><path>packages/ember-metal/lib/mixin.js
<ide> import {
<ide> function ROOT() {}
<ide> ROOT.__hasSuper = false;
<ide>
<del>const a_slice = [].slice;
<add>const a_slice = Array.prototype.slice;
<add>const a_concat = Array.prototype.concat;
<add>const isArray = Array.isArray;
<ide>
<ide> function isMethod(obj) {
<ide> return 'function' === typeof obj &&
<ide> function mixinProperties(mixinsMeta, mixin) {
<ide> }
<ide>
<ide> function concatenatedMixinProperties(concatProp, props, values, base) {
<del> let concats;
<del>
<ide> // reset before adding each new mixin to pickup concats from previous
<del> concats = values[concatProp] || base[concatProp];
<add> let concats = values[concatProp] || base[concatProp];
<ide> if (props[concatProp]) {
<del> concats = concats ? concats.concat(props[concatProp]) : props[concatProp];
<add> concats = concats ? a_concat.call(concats, props[concatProp]) : props[concatProp];
<ide> }
<del>
<ide> return concats;
<ide> }
<ide>
<ide> function applyConcatenatedProperties(obj, key, value, values) {
<ide> let baseValue = values[key] || obj[key];
<ide> let ret;
<ide>
<del> if (baseValue) {
<del> if ('function' === typeof baseValue.concat) {
<add> if (baseValue === null || baseValue === undefined) {
<add> ret = makeArray(value);
<add> } else {
<add> if (isArray(baseValue)) {
<ide> if (value === null || value === undefined) {
<ide> ret = baseValue;
<ide> } else {
<del> ret = baseValue.concat(value);
<add> ret = a_concat.call(baseValue, value);
<ide> }
<ide> } else {
<del> ret = makeArray(baseValue).concat(value);
<add> ret = a_concat.call(makeArray(baseValue), value);
<ide> }
<del> } else {
<del> ret = makeArray(value);
<ide> }
<ide>
<ide> runInDebug(() => {
<ide> function applyMergedProperties(obj, key, value, values) {
<ide> let baseValue = values[key] || obj[key];
<ide>
<ide> runInDebug(function() {
<del> if (Array.isArray(value)) { // use conditional to avoid stringifying every time
<add> if (isArray(value)) { // use conditional to avoid stringifying every time
<ide> assert(`You passed in \`${JSON.stringify(value)}\` as the value for \`${key}\` but \`${key}\` cannot be an Array`, false);
<ide> }
<ide> });
<ide><path>packages/ember-metal/tests/mixin/concatenated_properties_test.js
<ide> QUnit.test('adding a concatenable property that already has a defined value shou
<ide> });
<ide>
<ide> let obj = mixin({}, mixinA, mixinB);
<del> equal(get(obj, 'foobar'), 'foobar');
<add> deepEqual(get(obj, 'foobar'), ['foo', 'bar']);
<ide> });
<ide><path>packages/ember-utils/lib/make-array.js
<add>const isArray = Array.isArray;
<add>
<ide> /**
<ide> Forces the passed object to be part of an array. If the object is already
<ide> an array, it will return the object. Otherwise, it will add the object to
<ide> */
<ide> export default function makeArray(obj) {
<ide> if (obj === null || obj === undefined) { return []; }
<del> return Array.isArray(obj) ? obj : [obj];
<add> return isArray(obj) ? obj : [obj];
<ide> } | 3 |
PHP | PHP | use default cipher | 1ce080b131b643b9c91bb5f7f1a245f4735879e8 | <ide><path>src/Illuminate/Foundation/Console/EnvironmentDecryptCommand.php
<ide> public function handle()
<ide> return Command::FAILURE;
<ide> }
<ide>
<del> $cipher = $this->option('cipher') ?: 'aes-128-cbc';
<add> $cipher = $this->option('cipher') ?: 'AES-256-CBC';
<ide>
<ide> $key = $this->parseKey($key);
<ide>
<ide><path>src/Illuminate/Foundation/Console/EnvironmentEncryptCommand.php
<ide> public function __construct(Filesystem $files)
<ide> */
<ide> public function handle()
<ide> {
<del> $cipher = $this->option('cipher') ?: 'aes-128-cbc';
<add> $cipher = $this->option('cipher') ?: 'AES-256-CBC';
<ide>
<ide> $key = $this->option('key');
<ide> | 2 |
Javascript | Javascript | fix typo in docstring | e8a9ad9adeaeda88c7afea2bb15562dac2f72b43 | <ide><path>packages/ember-routing/lib/helpers/render.js
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide> Example:
<ide>
<ide> ```javascript
<del> App.NavigationController = Ember.Controller.extned({
<add> App.NavigationController = Ember.Controller.extend({
<ide> who: "world"
<ide> });
<ide> ``` | 1 |
PHP | PHP | add api docs for new countercache option | d768eef98b885b85effcff3634666fe745d79268 | <ide><path>src/ORM/Behavior/CounterCacheBehavior.php
<ide> * ]
<ide> * ]
<ide> * ```
<add> *
<add> * You can disable counter updates entirely by sending the `ignoreCounterCache` option
<add> * to your save operation:
<add> *
<add> * ```
<add> * $this->Articles->save($article, ['ignoreCounterCache' => true]);
<add> * ```
<ide> */
<ide> class CounterCacheBehavior extends Behavior
<ide> { | 1 |
Python | Python | fix flaky backfill test | 4746882e7b27c996047cff29bc831e0fa3c9b0f2 | <ide><path>tests/jobs/test_backfill_job.py
<ide> def test_backfill_skip_active_scheduled_dagrun(self, dag_maker, caplog):
<ide> start_date=DEFAULT_DATE,
<ide> end_date=DEFAULT_DATE + datetime.timedelta(days=2),
<ide> )
<del> job.run()
<del> error_log_records = [record for record in caplog.records if record.levelname == "ERROR"]
<del> assert "Backfill cannot be created for DagRun" in error_log_records[0].msg
<add> with caplog.at_level(logging.ERROR, logger="airflow.jobs.backfill_job.BackfillJob"):
<add> caplog.clear()
<add> job.run()
<add> assert "Backfill cannot be created for DagRun" in caplog.messages[0]
<ide>
<ide> ti = TI(
<ide> task=dag.get_task("test_backfill_skip_active_scheduled_dagrun-1"), execution_date=DEFAULT_DATE | 1 |
PHP | PHP | apply fixes from styleci | c3befd2a42222aa1c0760c72c4234ac4120ecc63 | <ide><path>tests/Validation/ValidationRuleParserTest.php
<ide> public function testExplodeHandlesArraysOfNestedRules()
<ide>
<ide> $results = $parser->explode([
<ide> 'users.*.name' => Rule::forEach(function ($value, $attribute, $data) {
<del> $this->assertEquals([
<del> 'users.0.name' => 'Taylor Otwell',
<del> 'users.1.name' => 'Abigail Otwell',
<del> ], $data);
<del>
<del> return [
<del> Rule::requiredIf(true),
<del> $value === 'Taylor Otwell'
<del> ? Rule::in('taylor')
<del> : Rule::in('abigail'),
<del> ];
<del> }),
<add> $this->assertEquals([
<add> 'users.0.name' => 'Taylor Otwell',
<add> 'users.1.name' => 'Abigail Otwell',
<add> ], $data);
<add>
<add> return [
<add> Rule::requiredIf(true),
<add> $value === 'Taylor Otwell'
<add> ? Rule::in('taylor')
<add> : Rule::in('abigail'),
<add> ];
<add> }),
<ide> ]);
<ide>
<ide> $this->assertEquals([ | 1 |
Text | Text | clarify the position argument for fs.read | 680285c3b427a698fa254e51d5bf2fba59af2f2a | <ide><path>doc/api/fs.md
<ide> Read data from the file specified by `fd`.
<ide> `length` is an integer specifying the number of bytes to read.
<ide>
<ide> `position` is an integer specifying where to begin reading from in the file.
<del>If `position` is `null`, data will be read from the current file position.
<add>If `position` is `null`, data will be read from the current file position,
<add>and the file position will be updated for subsequent reads.
<add>If `position` is an integer, the file position will remain unchanged.
<ide>
<ide> The callback is given the three arguments, `(err, bytesRead, buffer)`.
<ide> | 1 |
Python | Python | use tf.nn.relu6 when appropriate in k.relu | f8763efb371f355e65473e7c59a8715cb06bdd0c | <ide><path>keras/backend/tensorflow_backend.py
<ide> def relu(x, alpha=0., max_value=None):
<ide> # Returns
<ide> A tensor.
<ide> """
<add> if alpha == 0 and max_value == 6:
<add> return tf.nn.relu6(x)
<add>
<ide> if alpha != 0.:
<ide> x = tf.nn.leaky_relu(x, alpha)
<ide> else:
<ide><path>tests/keras/activations_test.py
<ide> def test_relu():
<ide> result = f([test_values])[0]
<ide> assert_allclose(result, test_values, rtol=1e-05)
<ide>
<add> # Test max_value
<add> test_values = [0.5, 1.5]
<add> f = K.function([x], [activations.relu(x, max_value=1.)])
<add> result = f([test_values])[0]
<add> assert np.max(result) <= 1.
<add>
<add> # Test max_value == 6.
<add> test_values = [0.5, 6.]
<add> f = K.function([x], [activations.relu(x, max_value=1.)])
<add> result = f([test_values])[0]
<add> assert np.max(result) <= 6.
<add>
<add>
<ide>
<ide> def test_elu():
<ide> x = K.placeholder(ndim=2) | 2 |
PHP | PHP | remove redundant class import | 86b67fa1982736a87a935ef1b33f471ffff5b5e7 | <ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php
<ide> namespace Illuminate\Support\Testing\Fakes;
<ide>
<ide> use InvalidArgumentException;
<del>use Illuminate\Contracts\Mail\Mailable;
<ide> use Illuminate\Contracts\Mail\Mailer;
<del>use Illuminate\Contracts\Mail\Mailable as MailableContract;
<add>use Illuminate\Contracts\Mail\Mailable;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<ide>
<ide> class MailFake implements Mailer
<ide> class MailFake implements Mailer
<ide> protected $mailables = [];
<ide>
<ide> /**
<del> * All of the mailables that have been queued;
<add> * All of the mailables that have been queued.
<ide> *
<ide> * @var array
<ide> */
<ide> public function send($view, array $data = [], $callback = null)
<ide> */
<ide> public function queue($view, array $data = [], $callback = null, $queue = null)
<ide> {
<del> if (! $view instanceof MailableContract) {
<add> if (! $view instanceof Mailable) {
<ide> throw new InvalidArgumentException('Only mailables may be queued.');
<ide> }
<del>
<add>
<ide> $this->queuedMailables[] = $view;
<ide> }
<ide> | 1 |
Mixed | Ruby | add reversible syntax for change_column_default | a4128725f5a2c6cbf3e963e2b78ba9382732728a | <ide><path>activerecord/CHANGELOG.md
<add>* Add alternate syntax to make `change_column_default` reversible.
<add>
<add> User can pass in `:from` and `:to` to make `change_column_default` command
<add> become reversible.
<add>
<add> Example:
<add>
<add> change_column_default :posts, :status, from: nil, to: "draft"
<add> change_column_default :users, authorized, from: true, to: false
<add>
<add> *Prem Sichanugrist*
<add>
<ide> * Prevent error when using `force_reload: true` on an unassigned polymorphic
<ide> belongs_to association.
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def change(column_name, type, options = {})
<ide> #
<ide> # t.change_default(:qualification, 'new')
<ide> # t.change_default(:authorized, 1)
<add> # t.change_default(:status, from: nil, to: "draft")
<ide> #
<ide> # See SchemaStatements#change_column_default
<del> def change_default(column_name, default)
<del> @base.change_column_default(name, column_name, default)
<add> def change_default(column_name, default_or_changes)
<add> @base.change_column_default(name, column_name, default_or_changes)
<ide> end
<ide>
<ide> # Removes the column(s) from the table definition.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def change_column(table_name, column_name, type, options = {})
<ide> #
<ide> # change_column_default(:users, :email, nil)
<ide> #
<del> def change_column_default(table_name, column_name, default)
<add> # Passing a hash containing +:from+ and +:to+ will make this change
<add> # reversible in migration:
<add> #
<add> # change_column_default(:posts, :state, from: nil, to: "draft")
<add> #
<add> def change_column_default(table_name, column_name, default_or_changes)
<ide> raise NotImplementedError, "change_column_default is not implemented"
<ide> end
<ide>
<ide> def validate_index_length!(table_name, new_name) # :nodoc:
<ide> raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
<ide> end
<ide> end
<add>
<add> def extract_new_default_value(default_or_changes)
<add> if default_or_changes.is_a?(Hash) && default_or_changes.has_key?(:from) && default_or_changes.has_key?(:to)
<add> default_or_changes[:to]
<add> else
<add> default_or_changes
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def rename_index(table_name, old_name, new_name)
<ide> end
<ide> end
<ide>
<del> def change_column_default(table_name, column_name, default) #:nodoc:
<add> def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
<add> default = extract_new_default_value(default_or_changes)
<ide> column = column_for(table_name, column_name)
<ide> change_column table_name, column_name, column.sql_type, :default => default
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def change_column(table_name, column_name, type, options = {}) #:nodoc:
<ide> end
<ide>
<ide> # Changes the default value of a table column.
<del> def change_column_default(table_name, column_name, default) # :nodoc:
<add> def change_column_default(table_name, column_name, default_or_changes) # :nodoc:
<ide> clear_cache!
<ide> column = column_for(table_name, column_name)
<ide> return unless column
<ide>
<add> default = extract_new_default_value(default_or_changes)
<ide> alter_column_query = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} %s"
<ide> if default.nil?
<ide> # <tt>DEFAULT NULL</tt> results in the same behavior as <tt>DROP DEFAULT</tt>. However, PostgreSQL will
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def remove_column(table_name, column_name, type = nil, options = {}) #:nodoc:
<ide> end
<ide> end
<ide>
<del> def change_column_default(table_name, column_name, default) #:nodoc:
<add> def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
<add> default = extract_new_default_value(default_or_changes)
<add>
<ide> alter_table(table_name) do |definition|
<ide> definition[column_name].default = default
<ide> end
<ide><path>activerecord/lib/active_record/migration/command_recorder.rb
<ide> def respond_to?(*args) # :nodoc:
<ide>
<ide> [:create_table, :create_join_table, :rename_table, :add_column, :remove_column,
<ide> :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps,
<del> :change_column_default, :add_reference, :remove_reference, :transaction,
<add> :add_reference, :remove_reference, :transaction,
<ide> :drop_join_table, :drop_table, :execute_block, :enable_extension,
<ide> :change_column, :execute, :remove_columns, :change_column_null,
<ide> :add_foreign_key, :remove_foreign_key
<ide> def invert_remove_index(args)
<ide> alias :invert_add_belongs_to :invert_add_reference
<ide> alias :invert_remove_belongs_to :invert_remove_reference
<ide>
<add> def invert_change_column_default(args)
<add> table, column, options = *args
<add>
<add> unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to)
<add> raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option."
<add> end
<add>
<add> [:change_column_default, [table, column, from: options[:to], to: options[:from]]]
<add> end
<add>
<ide> def invert_change_column_null(args)
<ide> args[2] = !args[2]
<ide> [:change_column_null, args]
<ide><path>activerecord/test/cases/migration/columns_test.rb
<ide> def test_change_column_default_to_null
<ide> assert_nil TestModel.new.first_name
<ide> end
<ide>
<add> def test_change_column_default_with_from_and_to
<add> add_column "test_models", "first_name", :string
<add> connection.change_column_default "test_models", "first_name", from: nil, to: "Tester"
<add>
<add> assert_equal "Tester", TestModel.new.first_name
<add> end
<add>
<ide> def test_remove_column_no_second_parameter_raises_exception
<ide> assert_raise(ArgumentError) { connection.remove_column("funny") }
<ide> end
<ide><path>activerecord/test/cases/migration/command_recorder_test.rb
<ide> def test_invert_change_column_default
<ide> end
<ide> end
<ide>
<add> def test_invert_change_column_default_with_from_and_to
<add> change = @recorder.inverse_of :change_column_default, [:table, :column, from: "old_value", to: "new_value"]
<add> assert_equal [:change_column_default, [:table, :column, from: "new_value", to: "old_value"]], change
<add> end
<add>
<add> def test_invert_change_column_default_with_from_and_to_with_boolean
<add> change = @recorder.inverse_of :change_column_default, [:table, :column, from: true, to: false]
<add> assert_equal [:change_column_default, [:table, :column, from: false, to: true]], change
<add> end
<add>
<ide> def test_invert_change_column_null
<ide> add = @recorder.inverse_of :change_column_null, [:table, :column, true]
<ide> assert_equal [:change_column_null, [:table, :column, false]], add | 9 |
Javascript | Javascript | unify another test | 2f5f485d15ea180e4f1733f8f7e06d8d29314f9e | <ide><path>packages/ember-glimmer/tests/integration/components/curly-components-test.js
<ide> moduleFor('Components test: curly components', class extends RenderingTest {
<ide> this.assertText('In layout - someProp: value set in instance');
<ide> }
<ide>
<del> // Note: Hooks are not re-run for idempotent re-renders
<del> ['@glimmer rerendering component with attrs from parent'](assert) {
<del> let willUpdate = 0;
<del> let didReceiveAttrs = 0;
<add> ['@test rerendering component with attrs from parent'](assert) {
<add> let willUpdateCount = 0;
<add> let didReceiveAttrsCount = 0;
<ide>
<del> this.registerComponent('non-block', {
<del> ComponentClass: Component.extend({
<del> didReceiveAttrs() {
<del> didReceiveAttrs++;
<del> },
<del>
<del> willUpdate() {
<del> willUpdate++;
<del> }
<del> }),
<del> template: 'In layout - someProp: {{someProp}}'
<del> });
<add> function expectHooks({ willUpdate, didReceiveAttrs }, callback) {
<add> willUpdateCount = 0;
<add> didReceiveAttrsCount = 0;
<ide>
<del> this.render('{{non-block someProp=someProp}}', {
<del> someProp: 'wycats'
<del> });
<del>
<del> assert.equal(didReceiveAttrs, 1, 'The didReceiveAttrs hook fired');
<del> this.assertText('In layout - someProp: wycats');
<del>
<del> this.runTask(() => this.rerender());
<del>
<del> this.assertText('In layout - someProp: wycats');
<del> assert.equal(didReceiveAttrs, 1, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 0, 'The willUpdate hook fired once');
<del>
<del> this.runTask(() => this.context.set('someProp', 'tomdale'));
<del>
<del> this.assertText('In layout - someProp: tomdale');
<del> assert.equal(didReceiveAttrs, 2, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 1, 'The willUpdate hook fired again');
<add> callback();
<ide>
<del> this.runTask(() => this.rerender());
<del>
<del> this.assertText('In layout - someProp: tomdale');
<del> assert.equal(didReceiveAttrs, 2, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 1, 'The willUpdate hook fired again');
<del>
<del> this.runTask(() => this.context.set('someProp', 'wycats'));
<del>
<del> this.assertText('In layout - someProp: wycats');
<del> assert.equal(didReceiveAttrs, 3, 'The didReceiveAttrs hook fired again in the R step');
<del> assert.equal(willUpdate, 2, 'The willUpdate hook fired again in the R step');
<del> }
<add> if (willUpdate) {
<add> assert.strictEqual(willUpdateCount, 1, 'The willUpdate hook was fired');
<add> } else {
<add> assert.strictEqual(willUpdateCount, 0, 'The willUpdate hook was not fired');
<add> }
<ide>
<del> ['@htmlbars rerendering component with attrs from parent'](assert) {
<del> let willUpdate = 0;
<del> let didReceiveAttrs = 0;
<add> if (didReceiveAttrs) {
<add> assert.strictEqual(didReceiveAttrsCount, 1, 'The didReceiveAttrs hook was fired');
<add> } else {
<add> assert.strictEqual(didReceiveAttrsCount, 0, 'The didReceiveAttrs hook was not fired');
<add> }
<add> }
<ide>
<ide> this.registerComponent('non-block', {
<ide> ComponentClass: Component.extend({
<ide> didReceiveAttrs() {
<del> didReceiveAttrs++;
<add> didReceiveAttrsCount++;
<ide> },
<ide>
<ide> willUpdate() {
<del> willUpdate++;
<add> willUpdateCount++;
<ide> }
<ide> }),
<ide> template: 'In layout - someProp: {{someProp}}'
<ide> });
<ide>
<del> this.render('{{non-block someProp=someProp}}', {
<del> someProp: 'wycats'
<add> expectHooks({ willUpdate: false, didReceiveAttrs: true }, () => {
<add> this.render('{{non-block someProp=someProp}}', {
<add> someProp: 'wycats'
<add> });
<ide> });
<ide>
<del> assert.equal(didReceiveAttrs, 1, 'The didReceiveAttrs hook fired');
<ide> this.assertText('In layout - someProp: wycats');
<ide>
<del> this.runTask(() => this.rerender());
<add> // Note: Hooks are not fired in Glimmer for idempotent re-renders
<add> expectHooks({ willUpdate: this.isHTMLBars, didReceiveAttrs: this.isHTMLBars }, () => {
<add> this.runTask(() => this.rerender());
<add> });
<ide>
<ide> this.assertText('In layout - someProp: wycats');
<del> assert.equal(didReceiveAttrs, 2, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 1, 'The willUpdate hook fired once');
<ide>
<del> this.runTask(() => this.context.set('someProp', 'tomdale'));
<add> expectHooks({ willUpdate: true, didReceiveAttrs: true }, () => {
<add> this.runTask(() => this.context.set('someProp', 'tomdale'));
<add> });
<ide>
<ide> this.assertText('In layout - someProp: tomdale');
<del> assert.equal(didReceiveAttrs, 3, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 2, 'The willUpdate hook fired again');
<ide>
<del> this.runTask(() => this.rerender());
<add> // Note: Hooks are not fired in Glimmer for idempotent re-renders
<add> expectHooks({ willUpdate: this.isHTMLBars, didReceiveAttrs: this.isHTMLBars }, () => {
<add> this.runTask(() => this.rerender());
<add> });
<ide>
<ide> this.assertText('In layout - someProp: tomdale');
<del> assert.equal(didReceiveAttrs, 4, 'The didReceiveAttrs hook fired again');
<del> assert.equal(willUpdate, 3, 'The willUpdate hook fired again');
<ide>
<del> this.runTask(() => this.context.set('someProp', 'wycats'));
<add> expectHooks({ willUpdate: true, didReceiveAttrs: true }, () => {
<add> this.runTask(() => this.context.set('someProp', 'wycats'));
<add> });
<ide>
<ide> this.assertText('In layout - someProp: wycats');
<del> assert.equal(didReceiveAttrs, 5, 'The didReceiveAttrs hook fired again in the R step');
<del> assert.equal(willUpdate, 4, 'The willUpdate hook fired again in the R step');
<ide> }
<ide>
<ide> ['@test non-block with properties on self']() { | 1 |
Python | Python | fix the test for numpy.ndindex() | dd146b6929f79fd6af27528dd4370eaebd5c57a6 | <ide><path>numpy/lib/tests/test_index_tricks.py
<ide> def test_ndindex():
<ide>
<ide> # Make sure size argument is optional
<ide> x = list(np.ndindex())
<del> assert_equal(x, [(0,)])
<add> assert_equal(x, [()])
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
Python | Python | implement sdbm hash algorithm | ec2d900b03dbc511504819caf353310b0a997fa6 | <ide><path>conversions/decimal_to_any.py
<ide> def decimal_to_any(num: int, base: int) -> str:
<ide> for base in range(2, 37):
<ide> for num in range(1000):
<ide> assert int(decimal_to_any(num, base), base) == num, (
<del> num, base, decimal_to_any(num, base),
<del> int(decimal_to_any(num, base), base)
<del> )
<add> num,
<add> base,
<add> decimal_to_any(num, base),
<add> int(decimal_to_any(num, base), base),
<add> )
<ide><path>hashes/sdbm.py
<add>"""
<add> This algorithm was created for sdbm (a public-domain reimplementation of ndbm) database library.
<add> It was found to do well in scrambling bits, causing better distribution of the keys and fewer splits.
<add> It also happens to be a good general hashing function with good distribution.
<add> The actual function (pseudo code) is:
<add> for i in i..len(str):
<add> hash(i) = hash(i - 1) * 65599 + str[i];
<add>
<add> What is included below is the faster version used in gawk. [there is even a faster, duff-device version]
<add> The magic constant 65599 was picked out of thin air while experimenting with different constants.
<add> It turns out to be a prime.
<add> This is one of the algorithms used in berkeley db (see sleepycat) and elsewhere.
<add>
<add> source: http://www.cse.yorku.ca/~oz/hash.html
<add>"""
<add>
<add>
<add>def sdbm(plain_text: str) -> str:
<add> """
<add> Function implements sdbm hash, easy to use, great for bits scrambling.
<add> iterates over each character in the given string and applies function to each of them.
<add>
<add> >>> sdbm('Algorithms')
<add> 1462174910723540325254304520539387479031000036
<add>
<add> >>> sdbm('scramble bits')
<add> 730247649148944819640658295400555317318720608290373040936089
<add> """
<add> hash = 0
<add> for plain_chr in plain_text:
<add> hash = ord(plain_chr) + (hash << 6) + (hash << 16) - hash
<add> return hash | 2 |
Javascript | Javascript | add azendoo to showcase | 63211596e37d7dabe946d88c8b8a9acdda2d2a1a | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> },
<ide> {
<ide> name: 'Zhopout',
<del> icon: 'http://zhopout.com/Content/Images/zhopout-logo-app-3.png',
<add> icon: 'http://zhopout.com/Content/Images/zhopout-logo-app-3.png',
<ide> link: 'https://play.google.com/store/apps/details?id=com.zhopout',
<ide> author: 'Jarvis Software Private Limited ',
<ide> blogs: [
<del> "https://medium.com/@murugandurai/how-we-developed-our-mobile-app-in-30-days-using-react-native-45affa6449e8#.29nnretsi",
<add> "https://medium.com/@murugandurai/how-we-developed-our-mobile-app-in-30-days-using-react-native-45affa6449e8#.29nnretsi",
<ide> ],
<ide> },
<ide> {
<ide> var apps = [
<ide> link: 'https://play.google.com/store/apps/details?id=com.arcchat',
<ide> author: 'Lukas Liesis',
<ide> },
<add> {
<add> name: 'Azendoo',
<add> icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/b8/d0/d6/b8d0d66e-1a87-8ff2-f843-0ddce8b535e1/icon175x175.png',
<add> linkAppStore: 'https://itunes.apple.com/us/app/azendoo-tasks-conversations/id581907820?mt=8',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.azendoo.azmobile',
<add> author: 'Azendoo',
<add> blogs: [
<add> "http://blog.azendoo.com/azendoo-mobile-v2-release/",
<add> ],
<add> },
<ide> {
<ide> name: 'Beetroot',
<ide> icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple5/v4/66/fd/dd/66fddd70-f848-4fc5-43ee-4d52197ccab8/pr_source.png',
<ide> var apps = [
<ide> icon: 'http://a5.mzstatic.com/us/r30/Purple7/v4/c1/9a/3f/c19a3f82-ecc3-d60b-f983-04acc203705f/icon175x175.jpeg',
<ide> link: 'https://itunes.apple.com/us/app/bionic-estore/id994537615?mt=8',
<ide> author: 'Digidemon',
<del> },
<add> },
<ide> {
<ide> name: 'Bitt Wallet',
<ide> icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/5b/00/34/5b003497-cc85-a0d0-0d3e-4fb3bc6f95cd/icon175x175.jpeg', | 1 |
Javascript | Javascript | add lorenz attractor | 88c17cd1cb75e92dbc052b13c93d054410062d03 | <ide><path>examples/files.js
<ide> var files = {
<ide> "webvr_cubes",
<ide> "webvr_daydream",
<ide> "webvr_gearvr",
<add> "webvr_lorenz_attractor",
<ide> "webvr_oculus-go",
<ide> "webvr_panorama",
<ide> "webvr_rollercoaster", | 1 |
Text | Text | fix wrong link in readme | c6a08f51b1ea0f0debdc7dbf1aa4192b3d67009d | <ide><path>examples/with-stripe-typescript/README.md
<ide> Once you have access to [the environment variables you'll need](#required-config
<ide> - Checkout payment result page that uses [SWR](https://github.com/vercel/swr) hooks to fetch the CheckoutSession status from the API route: [pages/result.tsx](pages/result.tsx).
<ide> - Stripe Elements
<ide> - Custom Amount Donation with Stripe Elements & PaymentIntents (no redirect):
<del> - Frontend: [pages/donate-with-elements.tsx](pages/donate-with-checkout.tsx)
<add> - Frontend: [pages/donate-with-elements.tsx](pages/donate-with-elements.tsx)
<ide> - Backend: [pages/api/payment_intents/](pages/api/payment_intents/)
<ide> - Webhook handling for [post-payment events](https://stripe.com/docs/payments/accept-a-payment#web-fulfillment)
<ide> - By default Next.js API routes are same-origin only. To allow Stripe webhook event requests to reach our API route, we need to add `micro-cors` and [verify the webhook signature](https://stripe.com/docs/webhooks/signatures) of the event. All of this happens in [pages/api/webhooks/index.ts](pages/api/webhooks/index.ts). | 1 |
Ruby | Ruby | fix example in flash middleware | 86b30c4347640965a6b3ae6a52c5ca9691a585c0 | <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> def flash
<ide> # def create
<ide> # # save post
<ide> # flash[:notice] = "Post successfully created"
<del> # redirect_to posts_path(@post)
<add> # redirect_to @post
<ide> # end
<ide> #
<ide> # def show | 1 |
Javascript | Javascript | fix comparison dagtz with localtz | fe0ee585d11474a0c99e51a4400dc16f643ea14b | <ide><path>airflow/www/static/js/task-instances.js
<ide> function generateTooltipDateTimes(startDate, endDate, dagTZ) {
<ide> }
<ide>
<ide> const tzFormat = 'z (Z)';
<del> const localTZ = moment.defaultZone.name;
<add> const localTZ = moment.defaultZone.name.toUpperCase();
<ide> startDate = moment.utc(startDate);
<ide> endDate = moment.utc(endDate);
<ide> dagTZ = dagTZ.toUpperCase(); | 1 |
Ruby | Ruby | prevent extra `sync_with_transaction_state` | f5f7ca57da2a486b4d2493cb70479174f2968ada | <ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb
<ide> module PrimaryKey
<ide> # Returns this record's primary key value wrapped in an array if one is
<ide> # available.
<ide> def to_key
<del> sync_with_transaction_state
<ide> key = id
<ide> [key] if key
<ide> end
<ide>
<ide> # Returns the primary key value.
<ide> def id
<del> if pk = self.class.primary_key
<del> sync_with_transaction_state
<del> _read_attribute(pk)
<del> end
<add> sync_with_transaction_state
<add> _read_attribute(self.class.primary_key) if self.class.primary_key
<ide> end
<ide>
<ide> # Sets the primary key value. | 1 |
Go | Go | remove some outdated comments | c523d6d25ce394046b2f0d057274adf7dac5b43c | <ide><path>libnetwork/sandbox.go
<ide> type sandbox struct {
<ide>
<ide> // These are the container configs used to customize container /etc/hosts file.
<ide> type hostsPathConfig struct {
<del> // Note(cpuguy83): The linter is drunk and says none of these fields are used while they are
<ide> hostName string
<ide> domainName string
<ide> hostsPath string
<ide> type extraHost struct {
<ide>
<ide> // These are the container configs used to customize container /etc/resolv.conf file.
<ide> type resolvConfPathConfig struct {
<del> // Note(cpuguy83): The linter is drunk and says none of these fields are used while they are
<ide> resolvConfPath string
<ide> originResolvConfPath string
<ide> resolvConfHashFile string | 1 |
PHP | PHP | log a warning when headers have been sent | 5c8a0ce361f008c24d70bc0d577148eb121aeb0a | <ide><path>src/Network/Response.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Filesystem\File;
<add>use Cake\Log\Log;
<ide> use Cake\Network\Exception\NotFoundException;
<ide> use DateTime;
<ide> use DateTimeZone;
<ide> public function send()
<ide> */
<ide> public function sendHeaders()
<ide> {
<del> if (headers_sent()) {
<add> $file = $line = null;
<add> if (headers_sent($file, $line)) {
<add> Log::warning("Headers already sent in {$file}:{$line}");
<add>
<ide> return;
<ide> }
<ide> | 1 |
Python | Python | use sb.array to handle the array interface | 0934daa01a823c3511511528586de2e9238c478f | <ide><path>numpy/core/records.py
<ide> def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None,
<ide> interface = getattr(obj, "__array_interface__", None)
<ide> if interface is None or not isinstance(interface, dict):
<ide> raise ValueError("Unknown input type")
<del> dtype = interface.get("descr", None) or interface.get("typestr")
<del> shape = interface.get("shape")
<del> strides = interface.get("strides", None)
<del> return recarray(shape, dtype, buf=obj, offset=offset, strides=strides)
<del>
<del>
<add> obj = sb.array(obj)
<add> if dtype is not None and (obj.dtype != dtype):
<add> obj = obj.view(dtype)
<add> res = obj.view(recarray)
<add> if issubclass(res.dtype.type, nt.void):
<add> res.dtype = sb.dtype((record, res.dtype))
<add> return res | 1 |
Ruby | Ruby | add test for nested model translation | 7a8031b578582e07dc11fa1f5c8977f049a313da | <ide><path>activemodel/test/cases/translation_test.rb
<ide> def test_translated_model_names_with_sti
<ide> assert_equal 'child model', Child.model_name.human
<ide> end
<ide>
<add> def test_translated_model_with_namespace
<add> I18n.backend.store_translations 'en', activemodel: { models: { 'person/gender': 'gender model' } }
<add> assert_equal 'gender model', Person::Gender.model_name.human
<add> end
<add>
<ide> def test_translated_model_names_with_ancestors_fallback
<ide> I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
<ide> assert_equal 'person model', Child.model_name.human | 1 |
Java | Java | ensure code compiles with eclipse jdt | 2bae0613a35251c03d56204a2927d200abf9a9ef | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/YamlMapFactoryBean.java
<ide> private void merge(Map<String, Object> output, Map<String, Object> map) {
<ide> Object value = entry.getValue();
<ide> Object existing = output.get(key);
<ide> if (value instanceof Map && existing instanceof Map) {
<del> Map<String, Object> result = new LinkedHashMap<>((Map) existing);
<add> // Inner cast required by Eclipse IDE.
<add> Map<String, Object> result = new LinkedHashMap<>((Map<String, Object>) existing);
<ide> merge(result, (Map) value);
<ide> output.put(key, result);
<ide> } | 1 |
Python | Python | fix pre-commit check | b3cc2f5d102214067c40b3c120364918556e7cca | <ide><path>airflow/providers/google/cloud/links/datastore.py
<ide> def persist(
<ide> value={
<ide> "project_id": task_instance.project_id,
<ide> },
<del> )
<ide>\ No newline at end of file
<add> )
<ide><path>airflow/providers/google/cloud/operators/datastore.py
<ide> from airflow.providers.google.cloud.hooks.datastore import DatastoreHook
<ide> from airflow.providers.google.cloud.hooks.gcs import GCSHook
<ide> from airflow.providers.google.cloud.links.datastore import (
<add> CloudDatastoreEntitiesLink,
<ide> CloudDatastoreExportEntitiesLink,
<ide> CloudDatastoreImportExportLink,
<del> CloudDatastoreEntitiesLink,
<ide> )
<ide>
<ide> if TYPE_CHECKING: | 2 |
Javascript | Javascript | remove dead code | ee050f46f6e5c94266db56292ad7a67d64af6333 | <ide><path>packages/ember-views/lib/system/platform.js
<del>import { environment } from 'ember-environment';
<del>
<del>// IE 6/7 have bugs around setting names on inputs during creation.
<del>// From http://msdn.microsoft.com/en-us/library/ie/ms536389(v=vs.85).aspx:
<del>// "To include the NAME attribute at run time on objects created with the createElement method, use the eTag."
<del>export let canSetNameOnInputs = environment.hasDOM && (function() {
<del> let div = document.createElement('div');
<del> let el = document.createElement('input');
<del>
<del> el.setAttribute('name', 'foo');
<del> div.appendChild(el);
<del>
<del> return !!div.innerHTML.match('foo');
<del>})(); | 1 |
Ruby | Ruby | add support for pending | 9744f687ccfe83bde52696985030225919c2e681 | <ide><path>actionpack/test/controller/render_test.rb
<ide> def test_explicitly_rendering_an_html_template_with_implicit_html_template_rende
<ide> end
<ide>
<ide> def test_should_implicitly_render_html_template_from_xhr_request
<del> get :render_implicit_html_template_from_xhr_request, :format => :js
<del> assert_equal "Hello HTML!", @response.body
<add> pending do
<add> get :render_implicit_html_template_from_xhr_request, :format => :js
<add> assert_equal "Hello HTML!", @response.body
<add> end
<ide> end
<ide>
<ide> def test_should_render_formatted_template
<ide><path>actionpack/test/template/render_test.rb
<ide> def test_render_file_without_specific_extension
<ide> end
<ide>
<ide> def test_render_file_with_localization
<del> old_locale = I18n.locale
<del> I18n.locale = :da
<del> assert_equal "Hey verden", @view.render(:file => "test/hello_world")
<del> ensure
<del> I18n.locale = old_locale
<add> pending do
<add> begin
<add> old_locale = I18n.locale
<add> I18n.locale = :da
<add> assert_equal "Hey verden", @view.render(:file => "test/hello_world")
<add> ensure
<add> I18n.locale = old_locale
<add> end
<add> end
<ide> end
<ide>
<ide> def test_render_file_at_top_level
<ide> def test_render_with_nested_layout
<ide> end
<ide> end
<ide>
<del>class CachedViewRenderTest < Test::Unit::TestCase
<add>class CachedViewRenderTest < ActiveSupport::TestCase
<ide> include RenderTestCases
<ide>
<ide> # Ensure view path cache is primed
<ide> def setup
<ide> end
<ide> end
<ide>
<del>class LazyViewRenderTest < Test::Unit::TestCase
<add>class LazyViewRenderTest < ActiveSupport::TestCase
<ide> include RenderTestCases
<ide>
<ide> # Test the same thing as above, but make sure the view path
<ide><path>activesupport/lib/active_support/test_case.rb
<ide> require 'active_support/testing/assertions'
<ide> require 'active_support/testing/deprecation'
<ide> require 'active_support/testing/declarative'
<add>require 'active_support/testing/pending'
<ide>
<ide> module ActiveSupport
<ide> class TestCase < ::Test::Unit::TestCase
<ide> class TestCase < ::Test::Unit::TestCase
<ide> include ActiveSupport::Testing::SetupAndTeardown
<ide> include ActiveSupport::Testing::Assertions
<ide> include ActiveSupport::Testing::Deprecation
<add> include ActiveSupport::Testing::Pending
<ide> extend ActiveSupport::Testing::Declarative
<ide> end
<ide> end | 3 |
Go | Go | remove unused method for dnetconnection struct | b5d09df0c388921fd4d32f002bd21150c258fa87 | <ide><path>libnetwork/cmd/dnet/dnet.go
<ide> func (d *dnetConnection) GetRemoteAddressList() []string {
<ide> return []string{d.Orchestration.Peer}
<ide> }
<ide>
<del>func (d *dnetConnection) GetNetworkKeys() []*types.EncryptionKey {
<del> return nil
<del>}
<del>
<del>func (d *dnetConnection) SetNetworkKeys([]*types.EncryptionKey) {
<del>}
<del>
<ide> func (d *dnetConnection) ListenClusterEvents() <-chan cluster.ConfigEventType {
<ide> return d.configEvent
<ide> } | 1 |
Text | Text | simplify usage example with pipelines | 72768b6b9c2083d9f2d075d80ef199a3eae881d8 | <ide><path>model_cards/dkleczek/bert-base-polish-uncased-v1/README.md
<ide> Polbert is released via [HuggingFace Transformers library](https://huggingface.c
<ide> For an example use as language model, see [this notebook](https://github.com/kldarek/polbert/blob/master/LM_testing.ipynb) file.
<ide>
<ide> ```python
<del>import numpy as np
<del>import torch
<del>import transformers as ppb
<del>
<del>tokenizer = ppb.BertTokenizer.from_pretrained('dkleczek/bert-base-polish-uncased-v1')
<del>bert_model = ppb.BertForMaskedLM.from_pretrained('dkleczek/bert-base-polish-uncased-v1')
<del>string1 = 'Adam mickiewicz wielkim polskim [MASK] był .'
<del>indices = tokenizer.encode(string1, add_special_tokens=True)
<del>masked_token = np.argwhere(np.array(indices) == 3).flatten()[0] # 3 is the vocab id for [MASK] token
<del>input_ids = torch.tensor([indices])
<del>with torch.no_grad():
<del> last_hidden_states = bert_model(input_ids)[0]
<del>more_words = np.argsort(np.asarray(last_hidden_states[0,masked_token,:]))[-4:]
<del>print(more_words)
<del>
<del># Output:
<del># poeta
<del># bohaterem
<del># człowiekiem
<del># pisarzem
<add>from transformers import *
<add>model = BertForMaskedLM.from_pretrained("dkleczek/bert-base-polish-uncased-v1")
<add>tokenizer = BertTokenizer.from_pretrained("dkleczek/bert-base-polish-uncased-v1")
<add>nlp = pipeline('fill-mask', model=model, tokenizer=tokenizer)
<add>for pred in nlp(f"Adam Mickiewicz wielkim polskim {nlp.tokenizer.mask_token} był."):
<add> print(pred)
<add>
<add># Output:
<add># {'sequence': '[CLS] adam mickiewicz wielkim polskim poeta był. [SEP]', 'score': 0.47196975350379944, 'token': 26596}
<add># {'sequence': '[CLS] adam mickiewicz wielkim polskim bohaterem był. [SEP]', 'score': 0.09127858281135559, 'token': 10953}
<add># {'sequence': '[CLS] adam mickiewicz wielkim polskim człowiekiem był. [SEP]', 'score': 0.0647173821926117, 'token': 5182}
<add># {'sequence': '[CLS] adam mickiewicz wielkim polskim pisarzem był. [SEP]', 'score': 0.05232388526201248, 'token': 24293}
<add># {'sequence': '[CLS] adam mickiewicz wielkim polskim politykiem był. [SEP]', 'score': 0.04554257541894913, 'token': 44095}
<ide> ```
<ide>
<ide> See the next section for an example usage of Polbert in downstream tasks. | 1 |
PHP | PHP | create a helper as a shortcut for method spoofing | 23c21e7958bdefc18c8b26a065f2feda48805adc | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function logger($message = null, array $context = [])
<ide> }
<ide> }
<ide>
<add>if (!function_exists('method_spoof')) {
<add> /**
<add> * Generate a method spoof form field for POST method's.
<add> *
<add> * @param string $method
<add> * @return string
<add> */
<add> function method_spoof($method = "")
<add> {
<add> return new Illuminate\View\Expression('<input type="hidden" name="_method" value="$method">');
<add> }
<add>}
<add>
<ide> if (!function_exists('old')) {
<ide> /**
<ide> * Retrieve an old input item. | 1 |
PHP | PHP | change exception message to actual model path | d4a4c802a4d57800af2f980ecee1d1ebcc318235 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function getRelation($name)
<ide> try {
<ide> return $this->getModel()->$name();
<ide> } catch (BadMethodCallException $e) {
<del> throw new RelationNotFoundException("Call to undefined relationship {$name} on Model {$this->getModel()}");
<add> $className = get_class($this->getModel());
<add> throw new RelationNotFoundException("Call to undefined relationship {$name} on Model {$className}");
<ide> }
<ide> });
<ide> | 1 |
PHP | PHP | remove trailing comma | f22333a7c0bb550a9bc9463f26695c256cbfb10e | <ide><path>src/Illuminate/Bus/BusServiceProvider.php
<ide> protected function registerBatchServices()
<ide> return new DatabaseBatchRepository(
<ide> $app->make(BatchFactory::class),
<ide> $app->make('db')->connection(config('queue.batching.database')),
<del> config('queue.batching.table', 'job_batches'),
<add> config('queue.batching.table', 'job_batches')
<ide> );
<ide> });
<ide> } | 1 |
Ruby | Ruby | modify strategy and tests | d173b57c4203915365b967d1c61fad49bd325536 | <ide><path>Library/Homebrew/livecheck/strategy/github_latest.rb
<ide> module Strategy
<ide> # The {GithubLatest} strategy identifies versions of software at
<ide> # github.com by checking a repository's latest release page.
<ide> #
<del> # GitHub URLs take a few differemt formats:
<add> # GitHub URLs take a few different formats:
<ide> #
<del> # * `https://github.com/example/example/releases/download/1.2.3/example-1.2.3.zip`
<add> # * `https://github.com/example/example/releases/download/1.2.3/example-1.2.3.tar.gz`
<ide> # * `https://github.com/example/example/archive/v1.2.3.tar.gz`
<add> # * `https://github.com/downloads/example/example/example-1.2.3.tar.gz`
<ide> #
<ide> # This strategy is used when latest releases are marked for software hosted
<ide> # on GitHub. It is necessary to use `strategy :github_latest` in a `livecheck`
<ide> module Strategy
<ide> #
<ide> # @api public
<ide> class GithubLatest
<del> NICE_NAME = "GitHub Latest"
<add> NICE_NAME = "GitHub - Latest"
<add>
<add> PRIORITY = 0
<ide>
<ide> # The `Regexp` used to determine if the strategy applies to the URL.
<del> URL_MATCH_REGEX = /github.com/i.freeze
<add> URL_MATCH_REGEX = %r{//github\.com(?:/downloads)?(?:/[^/]+){2}}i.freeze
<ide>
<ide> # Whether the strategy can be applied to the provided URL.
<ide> #
<ide> def self.match?(url)
<ide> # @param regex [Regexp] a regex used for matching versions in content
<ide> # @return [Hash]
<ide> def self.find_versions(url, regex = nil)
<del> %r{github\.com/(?<username>[\da-z\-]+)/(?<repository>[\da-z_\-]+)}i =~ url
<add> %r{github\.com/(?:downloads/)?(?<username>[^/]+)/(?<repository>[^/]+)}i =~ url.sub(/\.git$/i, "")
<ide>
<ide> # The page containing the latest release
<ide> page_url = "https://github.com/#{username}/#{repository}/releases/latest"
<ide><path>Library/Homebrew/test/livecheck/strategy/github_latest_spec.rb
<ide> describe Homebrew::Livecheck::Strategy::GithubLatest do
<ide> subject(:github_latest) { described_class }
<ide>
<del> let(:github_download_url) { "https://github.com/example/example/releases/download/1.2.3/example-1.2.3.zip" }
<del> let(:github_archive_url) { "https://github.com/example/example/archive/v1.2.3.tar.gz" }
<add> let(:github_release_artifact_url) {
<add> "https://github.com/example/example/releases/download/1.2.3/example-1.2.3.zip"
<add> }
<add> let(:github_tag_archive_url) { "https://github.com/example/example/archive/v1.2.3.tar.gz" }
<add> let(:github_repository_upload_url) { "https://github.com/downloads/example/example/example-1.2.3.tar.gz" }
<ide> let(:non_github_url) { "https://brew.sh/test" }
<ide>
<ide> describe "::match?" do
<del> it "returns true if the argument provided is a GitHub Download URL" do
<del> expect(github_latest.match?(github_download_url)).to be true
<add> it "returns true if the argument provided is a GitHub release artifact URL" do
<add> expect(github_latest.match?(github_release_artifact_url)).to be true
<ide> end
<ide>
<del> it "returns true if the argument provided is a GitHub Archive URL" do
<del> expect(github_latest.match?(github_archive_url)).to be true
<add> it "returns true if the argument provided is a GitHub tag archive URL" do
<add> expect(github_latest.match?(github_tag_archive_url)).to be true
<add> end
<add>
<add> it "returns true if the argument provided is a GitHub repository upload URL" do
<add> expect(github_latest.match?(github_repository_upload_url)).to be true
<ide> end
<ide>
<ide> it "returns false if the argument provided is not a GitHub URL" do | 2 |
Javascript | Javascript | remove unnecessary variable declaration | 8fd648b1754f2ab6c7c6c3e7a15023502189dc44 | <ide><path>controllers/user.js
<ide> exports.getAccount = function(req, res) {
<ide> res.render('account/profile', {
<ide> title: 'Manage your Free Code Camp Account',
<ide> c: c,
<del> u: req.user,
<ide> cc: req.user.challengesHash,
<ide> moment: moment
<ide> }); | 1 |
Ruby | Ruby | remove stray ( | caa8ab09f769b57bb06a333f5e81d6ad10be1495 | <ide><path>activemodel/lib/active_model/validations/length.rb
<ide> module HelperMethods
<ide> # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
<ide> # validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least 5 characters"
<ide> # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with 4 characters... don't play me."
<del> # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least 100 words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
<add> # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least 100 words.", :tokenizer => lambda { |str| str.scan(/\w+/) }
<ide> # end
<ide> #
<ide> # Configuration options: | 1 |
Python | Python | remove unsupported qa env | 8db131a743ee4a8940bc8687ec6b20a505872fa3 | <ide><path>libcloud/common/dimensiondata.py
<ide> 'name': 'Africa (AF)',
<ide> 'host': 'afapi.bsnlcloud.com',
<ide> 'vendor': 'BSNL'
<del> },
<del> 'dd-qa': {
<del> 'name': 'Test(QA)',
<del> 'host': 'apiqa1geo1.itaas.dimensiondata.com',
<del> 'vendor': 'DimensionData'
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | improve router test | 92120426317083ae90cb64cff07a7dd3a8acdc65 | <ide><path>actionpack/test/journey/router_test.rb
<ide> def test_recognize_head_request_as_get_route
<ide> def test_recognize_cares_about_verbs
<ide> path = Path::Pattern.from_string "/books(/:action(.:format))"
<ide> app = Object.new
<del> conditions = {
<del> :request_method => 'GET'
<del> }
<add> conditions = { request_method: 'GET' }
<ide> @router.routes.add_route(app, path, conditions, {})
<ide>
<add> env = rails_env 'PATH_INFO' => '/books/list.rss',
<add> "REQUEST_METHOD" => "POST"
<add>
<add> called = false
<add> @router.recognize(env) do |r, params|
<add> called = true
<add> end
<add>
<add> assert_not called
<add>
<ide> conditions = conditions.dup
<ide> conditions[:request_method] = 'POST'
<ide>
<ide> post = @router.routes.add_route(app, path, conditions, {})
<ide>
<del> env = rails_env 'PATH_INFO' => '/books/list.rss',
<del> "REQUEST_METHOD" => "POST"
<del>
<ide> called = false
<ide> @router.recognize(env) do |r, params|
<ide> assert_equal post, r | 1 |
Python | Python | remove default none value for required params | bbabe7316e6d5e02f46150bd6fb204e4c2588a67 | <ide><path>libcloud/compute/drivers/outscale.py
<ide> def ex_list_vpn_connections(
<ide>
<ide> def ex_create_certificate_authority(
<ide> self,
<del> ca_perm: str = None,
<add> ca_perm: str,
<ide> description: str = None,
<ide> dry_run: bool = False
<ide> ):
<ide> def ex_create_certificate_authority(
<ide> :param dry_run: If true, checks whether you have the required
<ide> permissions to perform the action.
<ide> :type dry_run: ``bool``
<add>
<add> :return: the created Ca.
<add> :rtype: ``dict``
<ide> """
<ide> action = "CreateCa"
<del> data = {"DryRun": dry_run}
<del> if ca_perm is not None:
<del> data.update({"CaPerm": ca_perm})
<add> data = {"DryRun": dry_run, "CaPerm": ca_perm}
<ide> if description is not None:
<ide> data.update({"Description": description})
<ide> response = self._call_api(action, json.dumps(data))
<ide> def ex_create_certificate_authority(
<ide>
<ide> def ex_delete_certificate_authority(
<ide> self,
<del> ca_id: str = None,
<add> ca_id: str,
<ide> dry_run: bool = False
<ide> ):
<ide> """
<ide> def ex_delete_certificate_authority(
<ide> :type dry_run: ``bool``
<ide> """
<ide> action = "DeleteCa"
<del> data = {"DryRun": dry_run}
<del> if ca_id is not None:
<del> data.update({"CaId": ca_id})
<add> data = {"DryRun": dry_run, "CaId": ca_id}
<ide> response = self._call_api(action, json.dumps(data))
<ide> if response.status_code == 200:
<ide> return True
<ide> def ex_read_certificate_authorities(
<ide> :param dry_run: If true, checks whether you have the required
<ide> permissions to perform the action.
<ide> :type dry_run: ``bool``
<add>
<add> :return: a list of all Ca matching filled filters.
<add> :rtype: ``list`` of ``dict``
<ide> """
<ide> action = "ReadCas"
<ide> data = {"DryRun": dry_run, "Filters": {}}
<ide> def ex_read_certificate_authorities(
<ide>
<ide> def ex_update_certificate_authority(
<ide> self,
<del> ca_id: str = None,
<add> ca_id: str,
<ide> description: str = None,
<ide> dry_run: bool = False
<ide> ):
<ide> def ex_update_certificate_authority(
<ide> :param dry_run: If true, checks whether you have the required
<ide> permissions to perform the action.
<ide> :type dry_run: ``bool``
<add>
<add> :return: a the created Ca or the request result.
<add> :rtype: ``dict``
<ide> """
<ide> action = "UpdateCa"
<del> data = {"DryRun": dry_run}
<del> if ca_id is not None:
<del> data.update({"CaId": ca_id})
<add> data = {"DryRun": dry_run, "CaId": ca_id}
<ide> if description is not None:
<ide> data.update({"Description": description})
<ide> response = self._call_api(action, json.dumps(data))
<ide> def ex_create_api_access_rule(
<ide>
<ide> def ex_delete_api_access_rule(
<ide> self,
<del> api_access_rule_id: str = None,
<add> api_access_rule_id: str,
<ide> dry_run: bool = False,
<ide> ):
<ide> """
<ide> Delete an API access rule.
<ide> You cannot delete the last remaining API access rule.
<ide>
<del> :param api_access_rule_id: The id of the targeted rule.
<add> :param api_access_rule_id: The id of the targeted rule
<add> (required).
<ide> :type api_access_rule_id: ``str``
<ide>
<ide> :param dry_run: If true, checks whether you have the required
<ide> def ex_read_api_access_rules(
<ide>
<ide> def ex_update_api_access_rule(
<ide> self,
<del> api_access_rule_id: str = None,
<add> api_access_rule_id: str,
<ide> ca_ids: List[str] = None,
<ide> cns: List[str] = None,
<ide> description: str = None,
<ide> def ex_update_api_access_rule(
<ide> for a parameter that is not specified, any previously set value
<ide> is deleted.
<ide>
<del> :param api_access_rule_id: The id of the rule we want to update.
<add> :param api_access_rule_id: The id of the rule we want to update
<add> (required).
<ide> :type api_access_rule_id: ``str``
<ide>
<ide> :param ca_ids: One or more IDs of Client Certificate Authorities | 1 |
Java | Java | improve initialization of assume class | 264edb3fb5de63051e6a66a533e40dadee253ae0 | <ide><path>spring-core/src/test/java/org/springframework/tests/Assume.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * conditions hold {@code true}. If the assumption fails, it means the test should be
<ide> * skipped.
<ide> *
<del> * Tests can be categorized into {@link TestGroup}s. Active groups are enabled using
<add> * <p>Tests can be categorized into {@link TestGroup}s. Active groups are enabled using
<ide> * the 'testGroups' system property, usually activated from the gradle command line:
<del> * <pre>
<add> *
<add> * <pre class="code">
<ide> * gradle test -PtestGroups="performance"
<ide> * </pre>
<ide> *
<del> * Groups can be specified as a comma separated list of values, or using the pseudo group
<add> * <p>Groups can be specified as a comma separated list of values, or using the pseudo group
<ide> * 'all'. See {@link TestGroup} for a list of valid groups.
<ide> *
<ide> * @author Rob Winch
<ide> */
<ide> public abstract class Assume {
<ide>
<del> private static final Set<TestGroup> GROUPS = TestGroup.parse(System.getProperty("testGroups"));
<add> static final String TEST_GROUPS_SYSTEM_PROPERTY = "testGroups";
<ide>
<ide>
<ide> /**
<ide> public abstract class Assume {
<ide> * @throws AssumptionViolatedException if the assumption fails
<ide> */
<ide> public static void group(TestGroup group) {
<del> if (!GROUPS.contains(group)) {
<del> throw new AssumptionViolatedException("Requires unspecified group " + group + " from " + GROUPS);
<add> Set<TestGroup> testGroups = loadTestGroups();
<add> if (!testGroups.contains(group)) {
<add> throw new AssumptionViolatedException("Requires unspecified group " + group + " from " + testGroups);
<ide> }
<ide> }
<ide>
<ide> public static void group(TestGroup group) {
<ide> * @since 4.2
<ide> */
<ide> public static void group(TestGroup group, Executable executable) throws Exception {
<del> if (GROUPS.contains(group)) {
<add> Set<TestGroup> testGroups = loadTestGroups();
<add> if (testGroups.contains(group)) {
<ide> executable.execute();
<ide> }
<ide> }
<ide> public static void notLogging(Log log) {
<ide> assumeFalse(log.isDebugEnabled());
<ide> }
<ide>
<add> /**
<add> * Load test groups dynamically instead of during static
<add> * initialization in order to avoid a {@link NoClassDefFoundError}
<add> * being thrown while attempting to load the {@code Assume} class.
<add> */
<add> private static Set<TestGroup> loadTestGroups() {
<add> try {
<add> return TestGroup.parse(System.getProperty(TEST_GROUPS_SYSTEM_PROPERTY));
<add> }
<add> catch (Exception ex) {
<add> throw new IllegalStateException("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY
<add> + "' system property: " + ex.getMessage(), ex);
<add> }
<add> }
<add>
<ide>
<ide> /**
<ide> * @since 4.2
<ide><path>spring-core/src/test/java/org/springframework/tests/AssumeTests.java
<add>/*
<add> * Copyright 2002-2017 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.tests;
<add>
<add>import java.util.Arrays;
<add>
<add>import org.junit.After;
<add>import org.junit.AssumptionViolatedException;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import static java.util.stream.Collectors.*;
<add>import static org.hamcrest.CoreMatchers.*;
<add>import static org.junit.Assert.*;
<add>import static org.springframework.tests.Assume.*;
<add>import static org.springframework.tests.TestGroup.*;
<add>
<add>/**
<add> * Tests for {@link Assume}.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> */
<add>public class AssumeTests {
<add>
<add> private String originalTestGroups;
<add>
<add>
<add> @Before
<add> public void trackOriginalTestGroups() {
<add> this.originalTestGroups = System.getProperty(TEST_GROUPS_SYSTEM_PROPERTY);
<add> }
<add>
<add> @After
<add> public void restoreOriginalTestGroups() {
<add> if (this.originalTestGroups != null) {
<add> setTestGroups(this.originalTestGroups);
<add> }
<add> else {
<add> setTestGroups("");
<add> }
<add> }
<add>
<add> @Test
<add> public void assumeGroupWithNoActiveTestGroups() {
<add> setTestGroups("");
<add> Assume.group(JMXMP);
<add> fail("assumption should have failed");
<add> }
<add>
<add> @Test
<add> public void assumeGroupWithNoMatchingActiveTestGroup() {
<add> setTestGroups(PERFORMANCE, CI);
<add> Assume.group(JMXMP);
<add> fail("assumption should have failed");
<add> }
<add>
<add> @Test
<add> public void assumeGroupWithMatchingActiveTestGroup() {
<add> setTestGroups(JMXMP);
<add> try {
<add> Assume.group(JMXMP);
<add> }
<add> catch (AssumptionViolatedException ex) {
<add> fail("assumption should NOT have failed");
<add> }
<add> }
<add>
<add> @Test
<add> public void assumeGroupWithBogusActiveTestGroup() {
<add> assertBogusActiveTestGroupBehavior("bogus");
<add> }
<add>
<add> @Test
<add> public void assumeGroupWithAllMinusBogusActiveTestGroup() {
<add> assertBogusActiveTestGroupBehavior("all-bogus");
<add> }
<add>
<add> private void assertBogusActiveTestGroupBehavior(String testGroups) {
<add> // Should result in something similar to the following:
<add> //
<add> // java.lang.IllegalStateException: Failed to parse 'testGroups' system property:
<add> // Unable to find test group 'bogus' when parsing testGroups value: 'all-bogus'.
<add> // Available groups include: [LONG_RUNNING,PERFORMANCE,JMXMP,CI]
<add>
<add> setTestGroups(testGroups);
<add> try {
<add> Assume.group(JMXMP);
<add> fail("assumption should have failed");
<add> }
<add> catch (IllegalStateException ex) {
<add> assertThat(ex.getMessage(),
<add> startsWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: "));
<add>
<add> assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class));
<add> assertThat(ex.getCause().getMessage(),
<add> equalTo("Unable to find test group 'bogus' when parsing testGroups value: '" + testGroups
<add> + "'. Available groups include: [LONG_RUNNING,PERFORMANCE,JMXMP,CI]"));
<add> }
<add> }
<add>
<add> private void setTestGroups(TestGroup... testGroups) {
<add> setTestGroups(Arrays.stream(testGroups).map(TestGroup::name).collect(joining(", ")));
<add> }
<add>
<add> private void setTestGroups(String testGroups) {
<add> System.setProperty(TEST_GROUPS_SYSTEM_PROPERTY, testGroups);
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/tests/TestGroup.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @see Assume#group(TestGroup)
<ide> * @author Phillip Webb
<ide> * @author Chris Beams
<add> * @author Sam Brannen
<ide> */
<ide> public enum TestGroup {
<ide>
<ide> public enum TestGroup {
<ide> * Parse the specified comma separated string of groups.
<ide> * @param value the comma separated string of groups
<ide> * @return a set of groups
<add> * @throws IllegalArgumentException if any specified group name is not a
<add> * valid {@link TestGroup}
<ide> */
<del> public static Set<TestGroup> parse(String value) {
<del> if (value == null || "".equals(value)) {
<add> public static Set<TestGroup> parse(String value) throws IllegalArgumentException {
<add> if (!StringUtils.hasText(value)) {
<ide> return Collections.emptySet();
<ide> }
<add> String originalValue = value;
<add> value = value.trim();
<ide> if ("ALL".equalsIgnoreCase(value)) {
<ide> return EnumSet.allOf(TestGroup.class);
<ide> }
<ide> if (value.toUpperCase().startsWith("ALL-")) {
<del> Set<TestGroup> groups = new HashSet<>(EnumSet.allOf(TestGroup.class));
<del> groups.removeAll(parseGroups(value.substring(4)));
<add> Set<TestGroup> groups = EnumSet.allOf(TestGroup.class);
<add> groups.removeAll(parseGroups(originalValue, value.substring(4)));
<ide> return groups;
<ide> }
<del> return parseGroups(value);
<add> return parseGroups(originalValue, value);
<ide> }
<ide>
<del> private static Set<TestGroup> parseGroups(String value) {
<add> private static Set<TestGroup> parseGroups(String originalValue, String value) throws IllegalArgumentException {
<ide> Set<TestGroup> groups = new HashSet<>();
<ide> for (String group : value.split(",")) {
<ide> try {
<ide> private static Set<TestGroup> parseGroups(String value) {
<ide> catch (IllegalArgumentException ex) {
<ide> throw new IllegalArgumentException(format(
<ide> "Unable to find test group '%s' when parsing testGroups value: '%s'. " +
<del> "Available groups include: [%s]", group.trim(), value,
<add> "Available groups include: [%s]", group.trim(), originalValue,
<ide> StringUtils.arrayToCommaDelimitedString(TestGroup.values())));
<ide> }
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/tests/TestGroupTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import java.util.Collections;
<ide> import java.util.EnumSet;
<del>import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<ide> import org.junit.Rule;
<ide> * Tests for {@link TestGroup}.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sam Brannen
<ide> */
<ide> public class TestGroupTests {
<ide>
<ide> public class TestGroupTests {
<ide>
<ide>
<ide> @Test
<del> public void parseNull() throws Exception {
<del> assertThat(TestGroup.parse(null), equalTo(Collections.<TestGroup> emptySet()));
<add> public void parseNull() {
<add> assertThat(TestGroup.parse(null), equalTo(Collections.emptySet()));
<ide> }
<ide>
<ide> @Test
<del> public void parseEmptyString() throws Exception {
<del> assertThat(TestGroup.parse(""), equalTo(Collections.<TestGroup> emptySet()));
<add> public void parseEmptyString() {
<add> assertThat(TestGroup.parse(""), equalTo(Collections.emptySet()));
<ide> }
<ide>
<ide> @Test
<del> public void parseWithSpaces() throws Exception {
<del> assertThat(TestGroup.parse("PERFORMANCE, PERFORMANCE"),
<del> equalTo((Set<TestGroup>) EnumSet.of(TestGroup.PERFORMANCE)));
<add> public void parseBlankString() {
<add> assertThat(TestGroup.parse(" "), equalTo(Collections.emptySet()));
<ide> }
<ide>
<ide> @Test
<del> public void parseInMixedCase() throws Exception {
<add> public void parseWithSpaces() {
<add> assertThat(TestGroup.parse(" PERFORMANCE, PERFORMANCE "),
<add> equalTo(EnumSet.of(TestGroup.PERFORMANCE)));
<add> }
<add>
<add> @Test
<add> public void parseInMixedCase() {
<ide> assertThat(TestGroup.parse("performance, PERFormaNCE"),
<del> equalTo((Set<TestGroup>) EnumSet.of(TestGroup.PERFORMANCE)));
<add> equalTo(EnumSet.of(TestGroup.PERFORMANCE)));
<ide> }
<ide>
<ide> @Test
<del> public void parseMissing() throws Exception {
<add> public void parseMissing() {
<ide> thrown.expect(IllegalArgumentException.class);
<ide> thrown.expectMessage("Unable to find test group 'missing' when parsing " +
<ide> "testGroups value: 'performance, missing'. Available groups include: " +
<ide> public void parseMissing() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void parseAll() throws Exception {
<del> assertThat(TestGroup.parse("all"), equalTo((Set<TestGroup>)EnumSet.allOf(TestGroup.class)));
<add> public void parseAll() {
<add> assertThat(TestGroup.parse("all"), equalTo(EnumSet.allOf(TestGroup.class)));
<ide> }
<ide>
<ide> @Test
<del> public void parseAllExcept() throws Exception {
<del> Set<TestGroup> expected = new HashSet<>(EnumSet.allOf(TestGroup.class));
<add> public void parseAllExceptPerformance() {
<add> Set<TestGroup> expected = EnumSet.allOf(TestGroup.class);
<ide> expected.remove(TestGroup.PERFORMANCE);
<ide> assertThat(TestGroup.parse("all-performance"), equalTo(expected));
<ide> }
<ide>
<add> @Test
<add> public void parseAllExceptMissing() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Unable to find test group 'missing' when parsing " +
<add> "testGroups value: 'all-missing'. Available groups include: " +
<add> "[LONG_RUNNING,PERFORMANCE,JMXMP,CI]");
<add> TestGroup.parse("all-missing");
<add> }
<add>
<ide> } | 4 |
Python | Python | add unit test to check if steps are updated | e4bf9498724fc472b124cf98ec11fac2b84098b8 | <ide><path>keras/engine/data_adapter_test.py
<ide> import tensorflow.compat.v2 as tf
<ide>
<ide> import math
<add>from typing import List, Union, Text, Optional, Any, Tuple, Dict, ItemsView, overload, DefaultDict
<ide>
<ide> from absl.testing import parameterized
<ide> import numpy as np
<ide> from keras.testing_infra import test_utils
<ide> from keras.engine import data_adapter
<ide> from keras.utils import data_utils
<add>from tensorflow.python.eager import context
<add>
<add>
<add>class TestBatchSequence(data_utils.Sequence):
<add>
<add> def __init__(
<add> self,
<add> batch_size: Union[int, List[int]],
<add> feature_shape,
<add> epochs: int = 2,
<add> ):
<add> print("TestBatchSequence.__init__")
<add> self.batch_size = batch_size
<add> self.feature_shape = feature_shape
<add>
<add> # if isinstance(batch_size, list):
<add> # logger.debug(
<add> # "The provided batch size is a list, this data generator will use a "
<add> # "linear increasing batch size."
<add> # )
<add>
<add> self._epochs = epochs
<add> # we use `on_epoch_end` method to prepare data for the next epoch
<add> # set current epoch to `-1`, so that `on_epoch_end` will increase it to `0`
<add> self._current_epoch = -1
<add> # actual batch size will be set inside `on_epoch_end`
<add> self._current_batch_size = 0
<add> # create separate data variable that will store modified data for each batch
<add> # self._data: Data = {}
<add>
<add> self.on_epoch_end()
<add>
<add> def __len__(self) -> int:
<add> """Number of batches in the Sequence.
<add>
<add> Returns:
<add> The number of batches in the Sequence.
<add> """
<add> # data was rebalanced, so need to recalculate number of examples
<add> num_examples = 20
<add> batch_size = self._current_batch_size
<add> return num_examples // batch_size + int(num_examples % batch_size > 0) # = math.ceil(num_examples / batch_size )
<add>
<add> def __getitem__(self, index: int) -> Tuple[Any, Any]:
<add> """Gets batch at position `index`.
<add>
<add> Arguments:
<add> index: position of the batch in the Sequence.
<add>
<add> Returns:
<add> A batch (tuple of input data and target data).
<add> """
<add> print(f"__getitem__ : self._current_epoch: {self._current_epoch}, self._current_batch_size: {self._current_batch_size}")
<add> # return input and target data, as our target data is inside the input
<add> # data return None for the target data
<add> return (np.zeros((self._current_batch_size, self.feature_shape)),
<add> np.ones((self._current_batch_size,)))
<add>
<add> def on_epoch_end(self) -> None:
<add> """Update the data after every epoch."""
<add> self._current_epoch += 1
<add> if self._current_epoch < self._epochs:
<add> self._current_batch_size = self._linearly_increasing_batch_size()
<add> print(f"on_epoch_end: self._current_epoch: {self._current_epoch}, self._current_batch_size: {self._current_batch_size}")
<add> # self._data = self._shuffle_and_balance(self._current_batch_size)
<add>
<add> def _linearly_increasing_batch_size(self) -> int:
<add> """Linearly increase batch size with every epoch.
<add>
<add> The idea comes from https://arxiv.org/abs/1711.00489.
<add>
<add> Returns:
<add> The batch size to use in this epoch.
<add> """
<add> if not isinstance(self.batch_size, list):
<add> return int(self.batch_size)
<add>
<add> if self._epochs > 1:
<add> return int(
<add> self.batch_size[0]
<add> + self._current_epoch
<add> * (self.batch_size[1] - self.batch_size[0])
<add> / (self._epochs - 1)
<add> )
<add> else:
<add> return int(self.batch_size[0])
<ide>
<ide>
<ide> class DummyArrayLike:
<ide> def generator():
<ide> self.iterator_input = data_utils.threadsafe_generator(generator)()
<ide> self.sequence_input = TestSequence(batch_size=self.batch_size,
<ide> feature_shape=10)
<add>
<add> self.increasing_batch_size = [5, 10]
<add> self.sequence_input_increasing_batch_size = TestBatchSequence(
<add> batch_size=self.increasing_batch_size,
<add> feature_shape=10,
<add> epochs=2,
<add> )
<add>
<ide> self.text_input = [['abc']]
<ide> self.bytes_input = [[b'abc']]
<ide> self.model = keras.models.Sequential(
<ide> def test_training_numpy_target(self):
<ide> self.model.evaluate(self.arraylike_input,
<ide> self.numpy_target, batch_size=5)
<ide>
<add> @test_combinations.run_all_keras_modes(always_skip_v1=True)
<add> def test_training_increasing_batch_size_fit_call(self):
<add> epochs = self.sequence_input_increasing_batch_size._epochs # 2
<add>
<add> self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd',
<add> run_eagerly=test_utils.should_run_eagerly())
<add>
<add> # Check state before fit()
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_epoch, 0)
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_batch_size, 5)
<add> my_data_handler = data_adapter.get_data_handler(
<add> self.sequence_input_increasing_batch_size,
<add> epochs=epochs,
<add> model=self.model,
<add> )
<add> self.assertEqual(my_data_handler.inferred_steps, 4) # 20 samples / 5 bs = 4
<add>
<add> self.model.fit(self.sequence_input_increasing_batch_size, epochs=epochs)
<add> # TODO call things inside fit step by step and see how data_handler behaves while doing this
<add>
<add> # Check state after fit()
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_epoch, 2)
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_batch_size, 10)
<add> my_new_data_handler = data_adapter.get_data_handler(
<add> self.sequence_input_increasing_batch_size,
<add> epochs=epochs,
<add> model=self.model,
<add> )
<add> self.assertEqual(my_data_handler.inferred_steps, 4) # 20 samples / 5 bs = 4
<add> self.assertEqual(my_new_data_handler.inferred_steps, 2) # 20 samples / 10 bs = 2
<add>
<add> @test_combinations.run_all_keras_modes(always_skip_v1=True)
<add> def test_training_increasing_batch_size_fit_internals(self):
<add> epochs = self.sequence_input_increasing_batch_size._epochs # 2
<add>
<add> self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd',
<add> run_eagerly=test_utils.should_run_eagerly())
<add> self.model.stop_training = False
<add> self.model.train_function = self.model.make_train_function()
<add>
<add> # Check state before fit()
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_epoch, 0)
<add> self.assertEqual(self.sequence_input_increasing_batch_size._current_batch_size, 5)
<add> data_handler = data_adapter.get_data_handler(
<add> self.sequence_input_increasing_batch_size,
<add> epochs=epochs,
<add> model=self.model,
<add> )
<add> self.assertEqual(data_handler.inferred_steps, 4) # 20 samples / 5 bs = 4
<add>
<add> # Execute fit()-loop and see how data_handler behaves while doing this
<add> for epoch, iterator in data_handler.enumerate_epochs():
<add> self.model.reset_metrics()
<add> with data_handler.catch_stop_iteration():
<add> for step in data_handler.steps():
<add> with tf.profiler.experimental.Trace(
<add> "train",
<add> epoch_num=epoch,
<add> step_num=step,
<add> batch_size=self.sequence_input_increasing_batch_size._current_batch_size,
<add> _r=1,
<add> ):
<add> tmp_logs = self.model.train_function(iterator)
<add> if data_handler.should_sync:
<add> context.async_wait()
<add> logs = tmp_logs # No error, now safe to assign to logs.
<add> end_step = step + data_handler.step_increment
<add> if self.model.stop_training:
<add> break
<add> self.assertEqual(data_handler.inferred_steps, 2) # 20 samples / 10 bs = 2
<add>
<ide> @test_combinations.run_all_keras_modes(always_skip_v1=True)
<ide> def test_training_tensor_target(self):
<ide> self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', | 1 |
PHP | PHP | update helpers to use urlhelper | 6cd3dcafa2c118a8d6f28b8045765c9a6fa3d1b6 | <ide><path>src/View/Helper/FormHelper.php
<ide> class FormHelper extends Helper {
<ide> *
<ide> * @var array
<ide> */
<del> public $helpers = array('Html');
<add> public $helpers = ['Url', 'Html'];
<ide>
<ide> /**
<ide> * The various pickers that make up a datetime picker.
<ide> public function create($model = null, $options = []) {
<ide> unset($options['templates']);
<ide>
<ide> $url = $this->_formUrl($context, $options);
<del> $action = $this->url($url);
<add> $action = $this->Url->url($url);
<ide> unset($options['url'], $options['action'], $options['idPrefix']);
<ide>
<ide> $this->_lastAction($url);
<ide> public function postLink($title, $url = null, array $options = array()) {
<ide>
<ide> $formName = str_replace('.', '', uniqid('post_', true));
<ide> $formOptions = array(
<del> 'action' => $this->url($url),
<add> 'action' => $this->Url->url($url),
<ide> 'name' => $formName,
<ide> 'style' => 'display:none;',
<ide> 'method' => 'post',
<ide> public function submit($caption = null, array $options = []) {
<ide> $options['src'] = $caption;
<ide> } elseif ($isImage) {
<ide> if ($caption{0} !== '/') {
<del> $url = $this->webroot(Configure::read('App.imageBaseUrl') . $caption);
<add> $url = $this->Url->webroot(Configure::read('App.imageBaseUrl') . $caption);
<ide> } else {
<del> $url = $this->webroot(trim($caption, '/'));
<add> $url = $this->Url->webroot(trim($caption, '/'));
<ide> }
<del> $url = $this->assetTimestamp($url);
<add> $url = $this->Url->assetTimestamp($url);
<ide> $options['src'] = $url;
<ide> } else {
<ide> $options['value'] = $caption;
<ide><path>src/View/Helper/HtmlHelper.php
<ide> class HtmlHelper extends Helper {
<ide>
<ide> use StringTemplateTrait;
<ide>
<add>/**
<add> * List of helpers used by this helper
<add> *
<add> * @var array
<add> */
<add> public $helpers = ['Url'];
<add>
<ide> /**
<ide> * Reference to the Response object
<ide> *
<ide> public function meta($type, $content = null, array $options = array()) {
<ide> $out = null;
<ide>
<ide> if (isset($options['link'])) {
<del> $options['link'] = $this->assetUrl($options['link']);
<add> $options['link'] = $this->Url->assetUrl($options['link']);
<ide> if (isset($options['rel']) && $options['rel'] === 'icon') {
<ide> $out = $this->formatTemplate('metalink', [
<ide> 'url' => $options['link'],
<ide> public function charset($charset = null) {
<ide> *
<ide> * If $url starts with "http://" this is treated as an external link. Else,
<ide> * it is treated as a path to controller/action and parsed with the
<del> * HtmlHelper::url() method.
<add> * UrlHelper::url() method.
<ide> *
<ide> * If the $url is empty, $title is used instead.
<ide> *
<ide> public function charset($charset = null) {
<ide> public function link($title, $url = null, array $options = array()) {
<ide> $escapeTitle = true;
<ide> if ($url !== null) {
<del> $url = $this->url($url);
<add> $url = $this->Url->url($url);
<ide> } else {
<del> $url = $this->url($title);
<add> $url = $this->Url->url($title);
<ide> $title = htmlspecialchars_decode($url, ENT_QUOTES);
<ide> $title = h(urldecode($title));
<ide> $escapeTitle = false;
<ide> public function css($path, array $options = array()) {
<ide> if (strpos($path, '//') !== false) {
<ide> $url = $path;
<ide> } else {
<del> $url = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.cssBaseUrl'), 'ext' => '.css'));
<add> $url = $this->Url->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.cssBaseUrl'), 'ext' => '.css'));
<ide> $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));
<ide> }
<ide>
<ide> public function script($url, array $options = array()) {
<ide> }
<ide>
<ide> if (strpos($url, '//') === false) {
<del> $url = $this->assetUrl($url, $options + array('pathPrefix' => Configure::read('App.jsBaseUrl'), 'ext' => '.js'));
<add> $url = $this->Url->assetUrl($url, $options + array('pathPrefix' => Configure::read('App.jsBaseUrl'), 'ext' => '.js'));
<ide> $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));
<ide> }
<ide>
<ide> protected function _prepareCrumbs($startText, $escape = true) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
<ide> */
<ide> public function image($path, array $options = array()) {
<del> $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
<add> $path = $this->Url->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
<ide> $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));
<ide>
<ide> if (!isset($options['alt'])) {
<ide> public function image($path, array $options = array()) {
<ide>
<ide> if ($url) {
<ide> return $this->formatTemplate('link', [
<del> 'url' => $this->url($url),
<add> 'url' => $this->Url->url($url),
<ide> 'attrs' => null,
<ide> 'content' => $image
<ide> ]);
<ide> public function media($path, array $options = array()) {
<ide> $ext = pathinfo($source['src'], PATHINFO_EXTENSION);
<ide> $source['type'] = $this->response->getMimeType($ext);
<ide> }
<del> $source['src'] = $this->assetUrl($source['src'], $options);
<add> $source['src'] = $this->Url->assetUrl($source['src'], $options);
<ide> $sourceTags .= $this->formatTemplate('tagselfclosing', [
<ide> 'tag' => 'source',
<ide> 'attrs' => $this->templater()->formatAttributes($source)
<ide> public function media($path, array $options = array()) {
<ide> if (empty($path) && !empty($options['src'])) {
<ide> $path = $options['src'];
<ide> }
<del> $options['src'] = $this->assetUrl($path, $options);
<add> $options['src'] = $this->Url->assetUrl($path, $options);
<ide> }
<ide>
<ide> if ($tag === null) {
<ide> public function media($path, array $options = array()) {
<ide> }
<ide>
<ide> if (isset($options['poster'])) {
<del> $options['poster'] = $this->assetUrl($options['poster'], array('pathPrefix' => Configure::read('App.imageBaseUrl')) + $options);
<add> $options['poster'] = $this->Url->assetUrl($options['poster'], array('pathPrefix' => Configure::read('App.imageBaseUrl')) + $options);
<ide> }
<ide> $text = $options['text'];
<ide>
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> class PaginatorHelper extends Helper {
<ide>
<ide> use StringTemplateTrait;
<ide>
<add>/**
<add> * List of helpers used by this helper
<add> *
<add> * @var array
<add> */
<add> public $helpers = ['Url'];
<add>
<ide> /**
<ide> * Defualt config for this class
<ide> *
<ide> public function generateUrl(array $options = array(), $model = null, $full = fal
<ide> ) {
<ide> $url['sort'] = $url['direction'] = null;
<ide> }
<del> return $this->url($url, $full);
<add> return $this->Url->url($url, $full);
<ide> }
<ide>
<ide> /**
<ide><path>src/View/Helper/RssHelper.php
<ide> class RssHelper extends Helper {
<ide> *
<ide> * @var array
<ide> */
<del> public $helpers = array('Time');
<add> public $helpers = ['Url', 'Time'];
<ide>
<ide> /**
<ide> * Base URL
<ide> public function channel($attrib = array(), $elements = array(), $content = null)
<ide> if (!isset($elements['description'])) {
<ide> $elements['description'] = '';
<ide> }
<del> $elements['link'] = $this->url($elements['link'], true);
<add> $elements['link'] = $this->Url->url($elements['link'], true);
<ide>
<ide> $elems = '';
<ide> foreach ($elements as $elem => $data) {
<ide> public function item($att = array(), $elements = array()) {
<ide> unset($attrib['url']);
<ide> $val = $val['url'];
<ide> }
<del> $val = $this->url($val, true);
<add> $val = $this->Url->url($val, true);
<ide> break;
<ide> case 'source':
<ide> if (is_array($val) && isset($val['url'])) {
<del> $attrib['url'] = $this->url($val['url'], true);
<add> $attrib['url'] = $this->Url->url($val['url'], true);
<ide> $val = $val['title'];
<ide> } elseif (is_array($val)) {
<del> $attrib['url'] = $this->url($val[0], true);
<add> $attrib['url'] = $this->Url->url($val[0], true);
<ide> $val = $val[1];
<ide> }
<ide> break;
<ide> public function item($att = array(), $elements = array()) {
<ide> $val['type'] = mime_content_type(WWW_ROOT . $val['url']);
<ide> }
<ide> }
<del> $val['url'] = $this->url($val['url'], true);
<add> $val['url'] = $this->Url->url($val['url'], true);
<ide> $attrib = $val;
<ide> $val = null;
<ide> break;
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function setUp() {
<ide> $this->View = new View();
<ide>
<ide> $this->Form = new FormHelper($this->View);
<del> $this->Form->request = new Request('articles/add');
<del> $this->Form->request->here = '/articles/add';
<del> $this->Form->request['controller'] = 'articles';
<del> $this->Form->request['action'] = 'add';
<del> $this->Form->request->webroot = '';
<del> $this->Form->request->base = '';
<add> $request = new Request('articles/add');
<add> $request->here = '/articles/add';
<add> $request['controller'] = 'articles';
<add> $request['action'] = 'add';
<add> $request->webroot = '';
<add> $request->base = '';
<add> $this->Form->Url->request = $this->Form->request = $request;
<ide>
<ide> $this->dateRegex = array(
<ide> 'daysRegex' => 'preg:/(?:<option value="0?([\d]+)">\\1<\/option>[\r\n]*)*/',
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function setUp() {
<ide> $this->Html = new HtmlHelper($this->View);
<ide> $this->Html->request = new Request();
<ide> $this->Html->request->webroot = '';
<add> $this->Html->Url->request = $this->Html->request;
<ide>
<ide> Configure::write('App.namespace', 'TestApp');
<ide> Plugin::load(['TestTheme']);
<ide> public function testImagePathPrefix() {
<ide> */
<ide> public function testImageWithFullBase() {
<ide> $result = $this->Html->image('test.gif', array('fullBase' => true));
<del> $here = $this->Html->url('/', true);
<add> $here = $this->Html->Url->url('/', true);
<ide> $expected = array('img' => array('src' => $here . 'img/test.gif', 'alt' => ''));
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Html->image('sub/test.gif', array('fullBase' => true));
<del> $here = $this->Html->url('/', true);
<add> $here = $this->Html->Url->url('/', true);
<ide> $expected = array('img' => array('src' => $here . 'img/sub/test.gif', 'alt' => ''));
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> public function testImageWithFullBase() {
<ide> Router::pushRequest($request);
<ide>
<ide> $result = $this->Html->image('sub/test.gif', array('fullBase' => true));
<del> $here = $this->Html->url('/', true);
<add> $here = $this->Html->Url->url('/', true);
<ide> $expected = array('img' => array('src' => $here . 'img/sub/test.gif', 'alt' => ''));
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide> public function testImageTagWithTheme() {
<ide> Configure::write('Asset.timestamp', true);
<ide> Configure::write('debug', true);
<ide>
<del> $this->Html->request->webroot = '/';
<del> $this->Html->theme = 'TestTheme';
<add> $this->Html->Url->request->webroot = '/';
<add> $this->Html->Url->theme = 'TestTheme';
<ide> $result = $this->Html->image('__cake_test_image.gif');
<ide> $expected = array(
<ide> 'img' => array(
<ide> public function testImageTagWithTheme() {
<ide> ));
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $this->Html->request->webroot = '/testing/';
<add> $this->Html->Url->request->webroot = '/testing/';
<ide> $result = $this->Html->image('__cake_test_image.gif');
<ide> $expected = array(
<ide> 'img' => array(
<ide> public function testThemeAssetsInMainWebrootPath() {
<ide> $webRoot = Configure::read('App.www_root');
<ide> Configure::write('App.www_root', TEST_APP . 'webroot/');
<ide>
<del> $this->Html->theme = 'TestTheme';
<add> $this->Html->Url->theme = 'TestTheme';
<ide> $result = $this->Html->css('webroot_test');
<ide> $expected = array(
<ide> 'link' => array('rel' => 'stylesheet', 'href' => 'preg:/.*test_theme\/css\/webroot_test\.css/')
<ide> public function testCssLinkOnce() {
<ide> */
<ide> public function testCssWithFullBase() {
<ide> Configure::write('Asset.filter.css', false);
<del> $here = $this->Html->url('/', true);
<add> $here = $this->Html->Url->url('/', true);
<ide>
<ide> $result = $this->Html->css('screen', array('fullBase' => true));
<ide> $expected = array(
<ide> public function testScriptWithBlocks() {
<ide> * @return void
<ide> */
<ide> public function testScriptWithFullBase() {
<del> $here = $this->Html->url('/', true);
<add> $here = $this->Html->Url->url('/', true);
<ide>
<ide> $result = $this->Html->script('foo', array('fullBase' => true));
<ide> $expected = array(
<ide> public function testScriptInTheme() {
<ide> $testfile = WWW_ROOT . '/test_theme/js/__test_js.js';
<ide> new File($testfile, true);
<ide>
<del> $this->Html->request->webroot = '/';
<del> $this->Html->theme = 'TestTheme';
<add> $this->Html->Url->request->webroot = '/';
<add> $this->Html->Url->theme = 'TestTheme';
<ide> $result = $this->Html->script('__test_js.js');
<ide> $expected = array(
<ide> 'script' => array('src' => '/test_theme/js/__test_js.js')
<ide><path>tests/TestCase/View/Helper/RssHelperTest.php
<ide> public function testChannel() {
<ide> 'Title',
<ide> '/title',
<ide> '<link',
<del> $this->Rss->url('/', true),
<add> $this->Rss->Url->url('/', true),
<ide> '/link',
<ide> '<description',
<ide> 'content',
<ide> public function testItemCdata() {
<ide> '<description',
<ide> '<![CDATA[descriptive words]]',
<ide> '/description',
<del> 'enclosure' => array('url' => $this->Rss->url('/test.flv', true)),
<add> 'enclosure' => array('url' => $this->Rss->Url->url('/test.flv', true)),
<ide> '<pubDate',
<ide> date('r', strtotime('2008-05-31 12:00:00')),
<ide> '/pubDate',
<ide> public function testItemEnclosureLength() {
<ide> '<![CDATA[descriptive words]]',
<ide> '/description',
<ide> 'enclosure' => array(
<del> 'url' => $this->Rss->url('/tests/cakephp.file.test.tmp', true),
<add> 'url' => $this->Rss->Url->url('/tests/cakephp.file.test.tmp', true),
<ide> 'length' => filesize($tmpFile),
<ide> 'type' => $type
<ide> ), | 7 |
Text | Text | add more info to benchmark/readme.md | 514b1d964b2e67d0594c6a44a22fbc29fe71454b | <ide><path>benchmark/README.md
<ide> This folder contains benchmark tests to measure the performance for certain
<ide> io.js APIs.
<ide>
<add>## prerequisites
<add>
<add>Most of the http benchmarks require `wrk` to be compiled beforehand.
<add>
<add>```sh
<add>make wrk
<add>```
<add>
<ide> ## How to run tests
<ide>
<ide> There are two ways to run benchmark tests:
<ide> buffers/buffer-read.js noAssert=false buffer=fast type=UInt16BE millions=1: 245.
<ide> ...
<ide> ```
<ide>
<add>3. Run tests with options
<add>
<add>This example will run only the first type of url test, with one iteration.
<add>(Note: benchmarks require __many__ iterations to be statistically accurate.)
<add>
<add>
<add>```sh
<add>iojs benchmark/url/url-parse.js type=one n=1
<add>```
<add>Output:
<add>```
<add>url/url-parse.js type=one n=1: 1663.74402
<add>```
<add>
<ide> ## How to write a benchmark test
<ide>
<ide> The benchmark tests are grouped by types. Each type corresponds to a subdirectory, | 1 |
PHP | PHP | apply fixes from styleci | fde66bfae0b37be4ff78f7aa1f1c15d6de602f77 | <ide><path>tests/Queue/RedisQueueIntegrationTest.php
<ide> <?php
<ide>
<ide> use Mockery as m;
<del>use Carbon\Carbon;
<ide> use Illuminate\Redis\Database;
<ide> use Illuminate\Queue\RedisQueue;
<ide> use Illuminate\Container\Container; | 1 |
Text | Text | use babelhook file instead the compilers option | ed322322e431e1b21d28f92244564c72742ac30d | <ide><path>docs/recipes/WritingTests.md
<ide> To use it together with [Babel](http://babeljs.io), add this to `scripts` in you
<ide> ...
<ide> "scripts": {
<ide> ...
<del> "test": "mocha --compilers js:babel/register --recursive",
<add> "test": "mocha --require babelhook --recursive",
<ide> "test:watch": "npm test -- --watch",
<ide> },
<ide> ...
<ide> }
<ide> ```
<ide>
<del>and run `npm test` to run it once, or `npm run test:watch` to test on every file change.
<add>Then create a file named `babelhook.js` beside it:
<add>
<add>```js
<add>require('babel/register')({
<add> // for options see https://babeljs.io/docs/usage/require/
<add>});
<add>```
<add>
<add>Run `npm test` to run it once, or `npm run test:watch` to test on every file change.
<ide>
<ide> ### Action Creators
<ide> | 1 |
PHP | PHP | remove unused namespace | df15753b6d42ac777527361aa206dfc7239138ee | <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Error\ExceptionRenderer;
<del>use Cake\Error\ExceptionRendererInterface;
<ide> use Cake\Log\Log;
<ide> use Exception;
<ide>
<ide><path>src/Http/Response.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Filesystem\File;
<del>use Cake\Http\CallbackStream;
<ide> use Cake\Log\Log;
<ide> use Cake\Network\CorsBuilder;
<ide> use Cake\Network\Exception\NotFoundException;
<ide><path>src/Http/Server.php
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Event\EventDispatcherTrait;
<del>use Cake\Http\Response;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use RuntimeException;
<del>use UnexpectedValueException;
<ide> use Zend\Diactoros\Response\EmitterInterface;
<ide>
<ide> /**
<ide><path>src/Http/ServerRequestFactory.php
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\Utility\Hash;
<ide> use Zend\Diactoros\ServerRequestFactory as BaseFactory;
<ide><path>src/I18n/I18n.php
<ide> use Cake\Cache\Cache;
<ide> use Cake\I18n\Formatter\IcuFormatter;
<ide> use Cake\I18n\Formatter\SprintfFormatter;
<del>use Cake\I18n\TranslatorFactory;
<ide> use Locale;
<ide>
<ide> /**
<ide><path>src/I18n/TranslatorRegistry.php
<ide> use Aura\Intl\PackageLocator;
<ide> use Aura\Intl\TranslatorLocator;
<ide> use Cake\Cache\CacheEngine;
<del>use Cake\I18n\TranslatorFactory;
<ide>
<ide> /**
<ide> * Constructs and stores instances of translators that can be
<ide><path>src/ORM/Association/Loader/SelectWithPivotLoader.php
<ide> */
<ide> namespace Cake\ORM\Association\Loader;
<ide>
<del>use InvalidArgumentException;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide><path>src/ORM/Behavior/CounterCacheBehavior.php
<ide> use Cake\Event\Event;
<ide> use Cake\ORM\Association;
<ide> use Cake\ORM\Behavior;
<del>use Cake\Utility\Hash;
<del>use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> * CounterCache behavior
<ide><path>tests/TestCase/Auth/WeakPasswordHasherTest.php
<ide> namespace Cake\Test\TestCase\Auth;
<ide>
<ide> use Cake\Auth\WeakPasswordHasher;
<del>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Security;
<ide>
<ide><path>tests/TestCase/BasicsTest.php
<ide> */
<ide> namespace Cake\Test\TestCase;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Http\Response;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Cache/Engine/ApcEngineTest.php
<ide> namespace Cake\Test\TestCase\Cache\Engine;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php
<ide>
<ide> use Cake\Cache\Cache;
<ide> use Cake\Cache\Engine\RedisEngine;
<del>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Cache/Engine/WincacheEngineTest.php
<ide> namespace Cake\Test\TestCase\Cache\Engine;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Cache/Engine/XcacheEngineTest.php
<ide> namespace Cake\Test\TestCase\Cache\Engine;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php
<ide> use Cake\Database\Driver\Sqlserver;
<ide> use Cake\Database\Expression\FunctionExpression;
<ide> use Cake\Database\Type;
<del>use Cake\Database\Type\BinaryType;
<ide> use Cake\Database\Type\ExpressionTypeInterface;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\Database\Expression\IdentifierExpression;
<ide> use Cake\Database\Query;
<ide> use Cake\Database\StatementInterface;
<ide><path>tests/TestCase/Database/Schema/CollectionTest.php
<ide> namespace Cake\Test\TestCase\Database\Schema;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\Database\Schema\Collection;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Http/BaseApplicationTest.php
<ide> namespace Cake\Test\TestCase;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Http\BaseApplication;
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Http/ResponseEmitterTest.php
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ResponseEmitter;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\ServerRequestFactory;
<del>use Zend\Diactoros\Stream;
<ide>
<ide> require_once __DIR__ . '/server_mocks.php';
<ide>
<ide><path>tests/TestCase/Http/ResponseTransformerTest.php
<ide>
<ide> use Cake\Http\Response as CakeResponse;
<ide> use Cake\Http\ResponseTransformer;
<del>use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide> use Zend\Diactoros\Response as PsrResponse;
<ide> use Zend\Diactoros\Stream;
<ide><path>tests/TestCase/Log/LogTraitTest.php
<ide> namespace Cake\Test\TestCase\Log;
<ide>
<ide> use Cake\Log\Log;
<del>use Cake\Log\LogInterface;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Network/Session/CacheSessionTest.php
<ide> namespace Cake\Test\TestCase\Network\Session;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<del>use Cake\Network\Session;
<ide> use Cake\Network\Session\CacheSession;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/ORM/SaveOptionsBuilderTest.php
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\ORM\Entity;
<ide> use Cake\ORM\SaveOptionsBuilder;
<ide> use Cake\ORM\Table;
<del>use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/TableRegressionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<del>use Cake\Core\Plugin;
<del>use Cake\I18n\Time;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/Routing/Middleware/AssetMiddlewareTest.php
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\Routing\Middleware\AssetMiddleware;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\Request;
<ide> use Zend\Diactoros\Response;
<ide>
<ide> /**
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> use Cake\Routing\Middleware\RoutingMiddleware;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\Request;
<ide> use Zend\Diactoros\Response;
<ide> use Zend\Diactoros\ServerRequestFactory;
<ide>
<ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Routing\Route;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\Routing\Router;
<ide> use Cake\Routing\Route\RedirectRoute;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/TestSuite/CookieEncryptedUsingControllerTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Controller;
<ide>
<del>use Cake\Controller\Component;
<ide> use Cake\Core\Configure;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> use Cake\I18n\I18n;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\Validation;
<del>use Cake\Validation\Validator;
<ide> use Locale;
<ide> use stdClass;
<ide> use Zend\Diactoros\UploadedFile;
<ide><path>tests/TestCase/View/Helper/TimeHelperTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View\Helper;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\I18n\I18n;
<ide> use Cake\I18n\Time;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/View/HelperTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper; | 31 |
Python | Python | fix failing tests, format responding csv | 5c27a9274e1d554c41b1efd8871b4941e185e387 | <ide><path>libcloud/common/base.py
<ide> def request(self, action, params=None, data=None, headers=None,
<ide> try:
<ide> # @TODO: Should we just pass File object as body to request method
<ide> # instead of dealing with splitting and sending the file ourselves?
<del> if raw and method.upper() in ['POST', 'PUT']:
<add> if raw:
<ide> self.connection.putrequest(method, url,
<ide> skip_host=1,
<ide> skip_accept_encoding=1)
<ide><path>libcloud/compute/drivers/dimensiondata.py
<ide> from libcloud.common.dimensiondata import API_ENDPOINTS, DEFAULT_REGION
<ide> from libcloud.common.dimensiondata import TYPES_URN
<ide> from libcloud.common.dimensiondata import SERVER_NS, NETWORK_NS, GENERAL_NS
<del>from libcloud.utils.py3 import urlencode
<add>from libcloud.utils.py3 import urlencode, ensure_string
<ide> from libcloud.utils.xml import fixxpath, findtext, findall
<ide> from libcloud.utils.py3 import basestring
<ide> from libcloud.compute.types import NodeState, Provider
<ide> def ex_summary_usage_report(self, start_date, end_date):
<ide> :param end_date: End date for the report
<ide> :type end_date: ``str`` in format YYYY-MM-DD
<ide>
<del> :rtype: :class:`io.StringIO`
<add> :rtype: ``list`` of ``list``
<ide> """
<ide> result = self.connection.raw_request_with_orgId_api_1(
<ide> 'report/usage?startDate=%s&endDate=%s' % (
<ide> start_date, end_date))
<del> return result.response.body
<add> return self._format_csv(result.response)
<ide>
<ide> def ex_detailed_usage_report(self, start_date, end_date):
<ide> """
<ide> def ex_detailed_usage_report(self, start_date, end_date):
<ide> :param end_date: End date for the report
<ide> :type end_date: ``str`` in format YYYY-MM-DD
<ide>
<del> :rtype: :class:`io.StringIO`
<add> :rtype: ``list`` of ``list``
<ide> """
<ide> result = self.connection.raw_request_with_orgId_api_1(
<ide> 'report/usageDetailed?startDate=%s&endDate=%s' % (
<ide> start_date, end_date))
<del> return result.response.body
<add> return self._format_csv(result.response)
<ide>
<ide> def ex_software_usage_report(self, start_date, end_date):
<ide> """
<ide> def ex_software_usage_report(self, start_date, end_date):
<ide> :param end_date: End date for the report
<ide> :type end_date: ``str`` in format YYYY-MM-DD
<ide>
<del> :rtype: :class:`io.StringIO`
<add> :rtype: ``list`` of ``list``
<ide> """
<ide> result = self.connection.raw_request_with_orgId_api_1(
<ide> 'report/usageSoftwareUnits?startDate=%s&endDate=%s' % (
<ide> start_date, end_date))
<del> return result.response.body
<add> return self._format_csv(result.response)
<ide>
<ide> def ex_audit_log_report(self, start_date, end_date):
<ide> """
<ide> def ex_audit_log_report(self, start_date, end_date):
<ide> :param end_date: End date for the report
<ide> :type end_date: ``str`` in format YYYY-MM-DD
<ide>
<del> :rtype: :class:`io.StringIO`
<add> :rtype: ``list`` of ``list``
<ide> """
<ide> result = self.connection.raw_request_with_orgId_api_1(
<ide> 'report/usageSoftwareUnits?startDate=%s&endDate=%s' % (
<ide> start_date, end_date))
<del> return result.response.body
<add> return self._format_csv(result.response)
<ide>
<ide> def ex_backup_usage_report(self, start_date, end_date, location):
<ide> """
<ide> def ex_backup_usage_report(self, start_date, end_date, location):
<ide> located in this location
<ide> :type location: :class:`NodeLocation` or ``str``
<ide>
<del> :rtype: :class:`io.StringIO`
<add> :rtype: ``list`` of ``list``
<ide> """
<ide> datacenter_id = self._location_to_location_id(location)
<ide> result = self.connection.raw_request_with_orgId_api_1(
<ide> 'backup/detailedUsageReport?datacenterId=%s&fromDate=%s&toDate=%s'
<ide> % (datacenter_id, start_date, end_date))
<del> return result.response.body
<add> return self._format_csv(result.response)
<add>
<add> def _format_csv(self, http_response):
<add> text = http_response.read()
<add> lines = str.splitlines(ensure_string(text))
<add> return [line.split(',') for line in lines]
<ide>
<ide> @staticmethod
<ide> def _get_tagging_asset_type(asset):
<add><path>libcloud/data/test_backblaze_b2.py
<del><path>libcloud/test/storage/test_backblaze_b2.py
<del># Licensed to the Apache Software Foundation (ASF) under one or more
<del># contributor license agreements. See the NOTICE file distributed with
<del># this work for additional information regarding copyright ownership.
<del># The ASF licenses this file to You under the Apache License, Version 2.0
<del># (the "License"); you may not use this file except in compliance with
<del># the License. You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del>
<del>import os
<del>import sys
<del>import tempfile
<del>
<del>import mock
<del>
<del>from libcloud.storage.drivers.backblaze_b2 import BackblazeB2StorageDriver
<del>from libcloud.utils.py3 import httplib
<del>from libcloud.test import unittest
<del>from libcloud.test import StorageMockHttp
<del>from libcloud.test import MockRawResponse
<del>from libcloud.test import MockHttpTestCase
<del>from libcloud.test.file_fixtures import StorageFileFixtures
<del>
<del>
<del>class MockAuthConn(mock.Mock):
<del> account_id = 'abcdefgh'
<del>
<del>
<del>class BackblazeB2StorageDriverTestCase(unittest.TestCase):
<del> driver_klass = BackblazeB2StorageDriver
<del> driver_args = ('a', 'b')
<del>
<del> def setUp(self):
<del> self.driver_klass.connectionCls.authCls = MockAuthConn()
<del> self.driver_klass.connectionCls.conn_classes = (
<del> None, BackblazeB2MockHttp)
<del> self.driver_klass.connectionCls.rawResponseCls = \
<del> BackblazeB2MockRawResponse
<del> BackblazeB2MockHttp.type = None
<del> BackblazeB2MockRawResponse.type = None
<del> self.driver = self.driver_klass(*self.driver_args)
<del>
<del> def test_list_containers(self):
<del> containers = self.driver.list_containers()
<del> self.assertEqual(len(containers), 3)
<del> self.assertEqual(containers[0].name, 'test00001')
<del> self.assertEqual(containers[0].extra['id'], '481c37de2e1ab3bf5e150710')
<del> self.assertEqual(containers[0].extra['bucketType'], 'allPrivate')
<del>
<del> def test_list_container_objects(self):
<del> container = self.driver.list_containers()[0]
<del> objects = self.driver.list_container_objects(container=container)
<del> self.assertEqual(len(objects), 4)
<del> self.assertEqual(objects[0].name, '2.txt')
<del> self.assertEqual(objects[0].size, 2)
<del> self.assertEqual(objects[0].extra['fileId'], 'abcd')
<del> self.assertEqual(objects[0].extra['uploadTimestamp'], 1450545966000)
<del>
<del> def test_get_container(self):
<del> container = self.driver.get_container('test00001')
<del> self.assertEqual(container.name, 'test00001')
<del> self.assertEqual(container.extra['id'], '481c37de2e1ab3bf5e150710')
<del> self.assertEqual(container.extra['bucketType'], 'allPrivate')
<del>
<del> def test_get_object(self):
<del> obj = self.driver.get_object('test00001', '2.txt')
<del> self.assertEqual(obj.name, '2.txt')
<del> self.assertEqual(obj.size, 2)
<del> self.assertEqual(obj.extra['fileId'], 'abcd')
<del> self.assertEqual(obj.extra['uploadTimestamp'], 1450545966000)
<del>
<del> def test_create_container(self):
<del> container = self.driver.create_container(container_name='test0005')
<del> self.assertEqual(container.name, 'test0005')
<del> self.assertEqual(container.extra['id'], '681c87aebeaa530f5e250710')
<del> self.assertEqual(container.extra['bucketType'], 'allPrivate')
<del>
<del> def test_delete_container(self):
<del> container = self.driver.list_containers()[0]
<del> result = self.driver.delete_container(container=container)
<del> self.assertTrue(result)
<del>
<del> def test_download_object(self):
<del> container = self.driver.list_containers()[0]
<del> obj = self.driver.list_container_objects(container=container)[0]
<del> _, destination_path = tempfile.mkstemp()
<del> result = self.driver.download_object(obj=obj, destination_path=destination_path,
<del> overwrite_existing=True)
<del> self.assertTrue(result)
<del>
<del> def test_download_object_as_stream(self):
<del> container = self.driver.list_containers()[0]
<del> obj = self.driver.list_container_objects(container=container)[0]
<del> result = self.driver.download_object_as_stream(obj=obj)
<del> result = ''.join([x.decode('utf-8') for x in list(result)])
<del> self.assertEqual(result, 'ab')
<del>
<del> def test_upload_object(self):
<del> file_path = os.path.abspath(__file__)
<del> container = self.driver.list_containers()[0]
<del> obj = self.driver.upload_object(file_path=file_path, container=container,
<del> object_name='test0007.txt')
<del> self.assertEqual(obj.name, 'test0007.txt')
<del> self.assertEqual(obj.size, 24)
<del> self.assertEqual(obj.extra['fileId'], 'abcde')
<del>
<del> def test_upload_object_via_stream(self):
<del> container = self.driver.list_containers()[0]
<del> file_path = os.path.abspath(__file__)
<del> file = open(file_path, 'rb')
<del> iterator = iter(file)
<del> obj = self.driver.upload_object_via_stream(iterator=iterator,
<del> container=container,
<del> object_name='test0007.txt')
<del> self.assertEqual(obj.name, 'test0007.txt')
<del> self.assertEqual(obj.size, 24)
<del> self.assertEqual(obj.extra['fileId'], 'abcde')
<del>
<del> def test_delete_object(self):
<del> container = self.driver.list_containers()[0]
<del> obj = self.driver.list_container_objects(container=container)[0]
<del> result = self.driver.delete_object(obj=obj)
<del> self.assertTrue(result)
<del>
<del> def test_ex_hide_object(self):
<del> container = self.driver.list_containers()[0]
<del> container_id = container.extra['id']
<del> obj = self.driver.ex_hide_object(container_id=container_id,
<del> object_name='2.txt')
<del> self.assertEqual(obj.name, '2.txt')
<del>
<del> def test_ex_list_object_versions(self):
<del> container = self.driver.list_containers()[0]
<del> container_id = container.extra['id']
<del> objects = self.driver.ex_list_object_versions(container_id=container_id)
<del> self.assertEqual(len(objects), 9)
<del>
<del> def test_ex_get_upload_data(self):
<del> container = self.driver.list_containers()[0]
<del> container_id = container.extra['id']
<del> data = self.driver.ex_get_upload_data(container_id=container_id)
<del> self.assertEqual(data['authorizationToken'], 'nope')
<del> self.assertEqual(data['bucketId'], '481c37de2e1ab3bf5e150710')
<del> self.assertEqual(data['uploadUrl'], 'https://podxxx.backblaze.com/b2api/v1/b2_upload_file/abcd/defg')
<del>
<del> def test_ex_get_upload_url(self):
<del> container = self.driver.list_containers()[0]
<del> container_id = container.extra['id']
<del> url = self.driver.ex_get_upload_url(container_id=container_id)
<del> self.assertEqual(url, 'https://podxxx.backblaze.com/b2api/v1/b2_upload_file/abcd/defg')
<del>
<del>
<del>class BackblazeB2MockHttp(StorageMockHttp, MockHttpTestCase):
<del> fixtures = StorageFileFixtures('backblaze_b2')
<del>
<del> def _b2api_v1_b2_list_buckets(self, method, url, body, headers):
<del> if method == 'GET':
<del> body = self.fixtures.load('b2_list_buckets.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_list_file_names(self, method, url, body, headers):
<del> if method == 'GET':
<del> body = self.fixtures.load('b2_list_file_names.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_create_bucket(self, method, url, body, headers):
<del> if method == 'POST':
<del> body = self.fixtures.load('b2_create_bucket.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_delete_bucket(self, method, url, body, headers):
<del> if method == 'POST':
<del> body = self.fixtures.load('b2_delete_bucket.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_delete_file_version(self, method, url, body, headers):
<del> if method == 'POST':
<del> body = self.fixtures.load('b2_delete_file_version.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_get_upload_url(self, method, url, body, headers):
<del> # test_upload_object
<del> if method == 'GET':
<del> body = self.fixtures.load('b2_get_upload_url.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_upload_file_abcd_defg(self, method, url, body, headers):
<del> # test_upload_object
<del> if method == 'POST':
<del> body = self.fixtures.load('b2_upload_file.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_list_file_versions(self, method, url, body, headers):
<del> if method == 'GET':
<del> body = self.fixtures.load('b2_list_file_versions.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _b2api_v1_b2_hide_file(self, method, url, body, headers):
<del> if method == 'POST':
<del> body = self.fixtures.load('b2_hide_file.json')
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del>
<del>class BackblazeB2MockRawResponse(MockRawResponse):
<del> def _file_test00001_2_txt(self, method, url, body, headers):
<del> # test_download_object
<del> if method == 'GET':
<del> body = 'ab'
<del> else:
<del> raise AssertionError('Unsupported method')
<del> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<del>
<del>if __name__ == '__main__':
<del> sys.exit(unittest.main())
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>import os
<add>import sys
<add>import tempfile
<add>
<add>import mock
<add>
<add>from libcloud.storage.drivers.backblaze_b2 import BackblazeB2StorageDriver
<add>from libcloud.utils.py3 import httplib
<add>from libcloud.test import unittest
<add>from libcloud.test import StorageMockHttp
<add>from libcloud.test import MockRawResponse
<add>from libcloud.test import MockHttpTestCase
<add>from libcloud.test.file_fixtures import StorageFileFixtures
<add>
<add>
<add>class MockAuthConn(mock.Mock):
<add> account_id = 'abcdefgh'
<add>
<add>
<add>class BackblazeB2StorageDriverTestCase(unittest.TestCase):
<add> driver_klass = BackblazeB2StorageDriver
<add> driver_args = ('a', 'b')
<add>
<add> def setUp(self):
<add> self.driver_klass.connectionCls.authCls = MockAuthConn()
<add> self.driver_klass.connectionCls.conn_classes = (
<add> None, BackblazeB2MockHttp)
<add> self.driver_klass.connectionCls.rawResponseCls = \
<add> BackblazeB2MockRawResponse
<add> BackblazeB2MockHttp.type = None
<add> BackblazeB2MockRawResponse.type = None
<add> self.driver = self.driver_klass(*self.driver_args)
<add>
<add> def test_list_containers(self):
<add> containers = self.driver.list_containers()
<add> self.assertEqual(len(containers), 3)
<add> self.assertEqual(containers[0].name, 'test00001')
<add> self.assertEqual(containers[0].extra['id'], '481c37de2e1ab3bf5e150710')
<add> self.assertEqual(containers[0].extra['bucketType'], 'allPrivate')
<add>
<add> def test_list_container_objects(self):
<add> container = self.driver.list_containers()[0]
<add> objects = self.driver.list_container_objects(container=container)
<add> self.assertEqual(len(objects), 4)
<add> self.assertEqual(objects[0].name, '2.txt')
<add> self.assertEqual(objects[0].size, 2)
<add> self.assertEqual(objects[0].extra['fileId'], 'abcd')
<add> self.assertEqual(objects[0].extra['uploadTimestamp'], 1450545966000)
<add>
<add> def test_get_container(self):
<add> container = self.driver.get_container('test00001')
<add> self.assertEqual(container.name, 'test00001')
<add> self.assertEqual(container.extra['id'], '481c37de2e1ab3bf5e150710')
<add> self.assertEqual(container.extra['bucketType'], 'allPrivate')
<add>
<add> def test_get_object(self):
<add> obj = self.driver.get_object('test00001', '2.txt')
<add> self.assertEqual(obj.name, '2.txt')
<add> self.assertEqual(obj.size, 2)
<add> self.assertEqual(obj.extra['fileId'], 'abcd')
<add> self.assertEqual(obj.extra['uploadTimestamp'], 1450545966000)
<add>
<add> def test_create_container(self):
<add> container = self.driver.create_container(container_name='test0005')
<add> self.assertEqual(container.name, 'test0005')
<add> self.assertEqual(container.extra['id'], '681c87aebeaa530f5e250710')
<add> self.assertEqual(container.extra['bucketType'], 'allPrivate')
<add>
<add> def test_delete_container(self):
<add> container = self.driver.list_containers()[0]
<add> result = self.driver.delete_container(container=container)
<add> self.assertTrue(result)
<add>
<add> def test_download_object(self):
<add> container = self.driver.list_containers()[0]
<add> obj = self.driver.list_container_objects(container=container)[0]
<add> _, destination_path = tempfile.mkstemp()
<add> result = self.driver.download_object(obj=obj, destination_path=destination_path,
<add> overwrite_existing=True)
<add> self.assertTrue(result)
<add>
<add> def test_download_object_as_stream(self):
<add> container = self.driver.list_containers()[0]
<add> obj = self.driver.list_container_objects(container=container)[0]
<add> result = self.driver.download_object_as_stream(obj=obj)
<add> result = ''.join([x.decode('utf-8') for x in list(result)])
<add> self.assertEqual(result, 'ab')
<add>
<add> def test_upload_object(self):
<add> file_path = os.path.abspath(__file__)
<add> container = self.driver.list_containers()[0]
<add> obj = self.driver.upload_object(file_path=file_path, container=container,
<add> object_name='test0007.txt')
<add> self.assertEqual(obj.name, 'test0007.txt')
<add> self.assertEqual(obj.size, 24)
<add> self.assertEqual(obj.extra['fileId'], 'abcde')
<add>
<add> def test_upload_object_via_stream(self):
<add> container = self.driver.list_containers()[0]
<add> file_path = os.path.abspath(__file__)
<add> file = open(file_path, 'rb')
<add> iterator = iter(file)
<add> obj = self.driver.upload_object_via_stream(iterator=iterator,
<add> container=container,
<add> object_name='test0007.txt')
<add> self.assertEqual(obj.name, 'test0007.txt')
<add> self.assertEqual(obj.size, 24)
<add> self.assertEqual(obj.extra['fileId'], 'abcde')
<add>
<add> def test_delete_object(self):
<add> container = self.driver.list_containers()[0]
<add> obj = self.driver.list_container_objects(container=container)[0]
<add> result = self.driver.delete_object(obj=obj)
<add> self.assertTrue(result)
<add>
<add> def test_ex_hide_object(self):
<add> container = self.driver.list_containers()[0]
<add> container_id = container.extra['id']
<add> obj = self.driver.ex_hide_object(container_id=container_id,
<add> object_name='2.txt')
<add> self.assertEqual(obj.name, '2.txt')
<add>
<add> def test_ex_list_object_versions(self):
<add> container = self.driver.list_containers()[0]
<add> container_id = container.extra['id']
<add> objects = self.driver.ex_list_object_versions(container_id=container_id)
<add> self.assertEqual(len(objects), 9)
<add>
<add> def test_ex_get_upload_data(self):
<add> container = self.driver.list_containers()[0]
<add> container_id = container.extra['id']
<add> data = self.driver.ex_get_upload_data(container_id=container_id)
<add> self.assertEqual(data['authorizationToken'], 'nope')
<add> self.assertEqual(data['bucketId'], '481c37de2e1ab3bf5e150710')
<add> self.assertEqual(data['uploadUrl'], 'https://podxxx.backblaze.com/b2api/v1/b2_upload_file/abcd/defg')
<add>
<add> def test_ex_get_upload_url(self):
<add> container = self.driver.list_containers()[0]
<add> container_id = container.extra['id']
<add> url = self.driver.ex_get_upload_url(container_id=container_id)
<add> self.assertEqual(url, 'https://podxxx.backblaze.com/b2api/v1/b2_upload_file/abcd/defg')
<add>
<add>
<add>class BackblazeB2MockHttp(StorageMockHttp, MockHttpTestCase):
<add> fixtures = StorageFileFixtures('backblaze_b2')
<add>
<add> def _b2api_v1_b2_list_buckets(self, method, url, body, headers):
<add> if method == 'GET':
<add> body = self.fixtures.load('b2_list_buckets.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_list_file_names(self, method, url, body, headers):
<add> if method == 'GET':
<add> body = self.fixtures.load('b2_list_file_names.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_create_bucket(self, method, url, body, headers):
<add> if method == 'POST':
<add> body = self.fixtures.load('b2_create_bucket.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_delete_bucket(self, method, url, body, headers):
<add> if method == 'POST':
<add> body = self.fixtures.load('b2_delete_bucket.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_delete_file_version(self, method, url, body, headers):
<add> if method == 'POST':
<add> body = self.fixtures.load('b2_delete_file_version.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_get_upload_url(self, method, url, body, headers):
<add> # test_upload_object
<add> if method == 'GET':
<add> body = self.fixtures.load('b2_get_upload_url.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_upload_file_abcd_defg(self, method, url, body, headers):
<add> # test_upload_object
<add> if method == 'POST':
<add> body = self.fixtures.load('b2_upload_file.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_list_file_versions(self, method, url, body, headers):
<add> if method == 'GET':
<add> body = self.fixtures.load('b2_list_file_versions.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _b2api_v1_b2_hide_file(self, method, url, body, headers):
<add> if method == 'POST':
<add> body = self.fixtures.load('b2_hide_file.json')
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add>
<add>class BackblazeB2MockRawResponse(MockRawResponse):
<add> def _file_test00001_2_txt(self, method, url, body, headers):
<add> # test_download_object
<add> if method == 'GET':
<add> body = 'ab'
<add> else:
<add> raise AssertionError('Unsupported method')
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<add>if __name__ == '__main__':
<add> sys.exit(unittest.main())
<ide><path>libcloud/test/compute/test_dimensiondata.py
<ide> from libcloud.common.dimensiondata import TYPES_URN
<ide> from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver as DimensionData
<ide> from libcloud.compute.base import Node, NodeAuthPassword, NodeLocation
<del>from libcloud.test import MockHttp, unittest
<add>from libcloud.test import MockHttp, unittest, MockRawResponse, StorageMockHttp
<ide> from libcloud.test.compute import TestCaseMixin
<ide> from libcloud.test.file_fixtures import ComputeFileFixtures
<ide> from libcloud.test.secrets import DIMENSIONDATA_PARAMS
<ide> class DimensionDataTests(unittest.TestCase, TestCaseMixin):
<ide>
<ide> def setUp(self):
<ide> DimensionData.connectionCls.conn_classes = (None, DimensionDataMockHttp)
<add> DimensionData.connectionCls.rawResponseCls = \
<add> DimensionDataMockRawResponse
<ide> DimensionDataMockHttp.type = None
<ide> self.driver = DimensionData(*DIMENSIONDATA_PARAMS)
<ide>
<ide> def test_priv_image_needs_auth_cust_img_linux_STR(self):
<ide>
<ide> def test_summary_usage_report(self):
<ide> report = self.driver.ex_summary_usage_report('2016-06-01', '2016-06-30')
<del> report_content = report.readlines()
<add> report_content = report
<ide> self.assertEqual(len(report_content), 13)
<del> self.assertEqual(len(report_content[0]), 67)
<add> self.assertEqual(len(report_content[0]), 6)
<ide>
<ide> def test_detailed_usage_report(self):
<ide> report = self.driver.ex_detailed_usage_report('2016-06-01', '2016-06-30')
<del> report_content = report.readlines()
<add> report_content = report
<ide> self.assertEqual(len(report_content), 42)
<del> self.assertEqual(len(report_content[0]), 30)
<add> self.assertEqual(len(report_content[0]), 4)
<ide>
<ide>
<ide> class InvalidRequestError(Exception):
<ide> def __init__(self, tag):
<ide> super(InvalidRequestError, self).__init__("Invalid Request - %s" % tag)
<ide>
<ide>
<del>class DimensionDataMockHttp(MockHttp):
<add>class DimensionDataMockRawResponse(MockRawResponse):
<add> fixtures = ComputeFileFixtures('dimensiondata')
<add>
<add> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usage(self, method, url, body, headers):
<add> body = self.fixtures.load(
<add> 'summary_usage_report.csv'
<add> )
<add> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<add>
<add> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usageDetailed(self, method, url, body, headers):
<add> body = self.fixtures.load(
<add> 'detailed_usage_report.csv'
<add> )
<add> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<add>
<add>
<add>class DimensionDataMockHttp(StorageMockHttp, MockHttp):
<ide>
<ide> fixtures = ComputeFileFixtures('dimensiondata')
<ide>
<ide> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_antiAffinityRule_07e3621a_a920
<ide> )
<ide> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<ide>
<del> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usage(self, method, url, body, headers):
<del> body = self.fixtures.load(
<del> 'summary_usage_report.csv'
<del> )
<del> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<del>
<del> def _oec_0_9_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_report_usageDetailed(self, method, url, body, headers):
<del> body = self.fixtures.load(
<del> 'detailed_usage_report.csv'
<del> )
<del> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.OK])
<del>
<ide> def _caas_2_2_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server(self, method, url, body, headers):
<ide> body = self.fixtures.load(
<ide> 'server.xml') | 4 |
PHP | PHP | ) | 791dcdbf9c250ad064cad5264bf29069406cfc5d | <ide><path>src/Illuminate/Redis/Database.php
<ide> public function subscribe($channels, Closure $callback, $connection = null, $met
<ide> call_user_func_array([$loop, $method], (array) $channels);
<ide>
<ide> foreach ($loop as $message) {
<del> echo $message->kind.PHP_EOL;
<ide> if ($message->kind === 'message' || $message->kind === 'pmessage') {
<ide> call_user_func($callback, $message->payload, $message->channel);
<ide> } | 1 |
Javascript | Javascript | fix usage suggestions for min and max | 6397a9e05f20ad94f891596e3453a98222c99422 | <ide><path>src/lib/moment/min-max.js
<ide> import { createLocal } from '../create/local';
<ide> import { createInvalid } from '../create/valid';
<ide>
<ide> export var prototypeMin = deprecate(
<del> 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
<add> 'moment().min is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
<ide> function () {
<ide> var other = createLocal.apply(null, arguments);
<ide> if (this.isValid() && other.isValid()) {
<ide> export var prototypeMin = deprecate(
<ide> );
<ide>
<ide> export var prototypeMax = deprecate(
<del> 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
<add> 'moment().max is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
<ide> function () {
<ide> var other = createLocal.apply(null, arguments);
<ide> if (this.isValid() && other.isValid()) { | 1 |
PHP | PHP | add test for content-type json and charset | 58df515a6dca61ea7f50d2a36372393831e89868 | <ide><path>lib/Cake/Test/Case/Network/CakeResponseTest.php
<ide> public function testSend() {
<ide> * Tests the send method and changing the content type
<ide> *
<ide> */
<del> public function testSendChangingContentYype() {
<add> public function testSendChangingContentType() {
<ide> $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies'));
<ide> $response->type('mp3');
<ide> $response->body('the response body');
<ide> public function testSendChangingContentYype() {
<ide> }
<ide>
<ide> /**
<del> * Tests the send method and changing the content type
<add> * Tests the send method and changing the content type to JSON
<ide> *
<ide> */
<del> public function testSendChangingContentType() {
<add> public function testSendChangingContentTypeJSON() {
<ide> $response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent', '_setCookies'));
<del> $response->type('mp3');
<add> $response->type('json');
<ide> $response->body('the response body');
<ide> $response->expects($this->once())->method('_sendContent')->with('the response body');
<ide> $response->expects($this->at(0))->method('_setCookies');
<ide> public function testSendChangingContentType() {
<ide> $response->expects($this->at(2))
<ide> ->method('_sendHeader')->with('Content-Length', 17);
<ide> $response->expects($this->at(3))
<del> ->method('_sendHeader')->with('Content-Type', 'audio/mpeg');
<add> ->method('_sendHeader')->with('Content-Type', 'application/json; charset=UTF-8');
<ide> $response->send();
<ide> }
<ide> | 1 |
Text | Text | add easy taxi to list of companies using airflow | cf05feb612d4690f2eab95949685e98b6afe03c6 | <ide><path>README.md
<ide> if you may.
<ide>
<ide> Currently **officially** using Airflow:
<ide>
<del>* Agari [@r39132](https://github.com/r39132)
<ide> * Airbnb [@mistercrunch]
<add>* Agari [@r39132](https://github.com/r39132)
<ide> * BlueApron [[@jasonjho](https://github.com/jasonjho) & [@matthewdavidhauser](https://github.com/matthewdavidhauser)]
<ide> * Chartboost [[@cgelman](https://github.com/cgelman) & [@dclubb](https://github.com/dclubb)]
<ide> * [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<del>* Easy Taxi [@caique-lima](https://github.com/caique-lima)
<add>* Easy Taxi [[@caique-lima](https://github.com/caique-lima)]
<ide> * [Jampp](https://github.com/jampp)
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)]
<ide> * Lyft
<ide> * Stripe [@jbalogh]
<del>* We[WeTransfer](https://github.com/WeTransfer) [[@jochem](https://github.com/jochem)]
<add>* [WeTransfer](https://github.com/WeTransfer) [[@jochem](https://github.com/jochem)]
<ide> * Wooga
<ide> * Xoom [[@gepser](https://github.com/gepser) & [@omarvides](https://github.com/omarvides)]
<ide> * Yahoo! | 1 |
Ruby | Ruby | fix nil outdated comparison | 90c696ea6714c4aad1a279e4e77b6811c08f0847 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide>
<ide> def outdated?
<ide> version = `/usr/bin/clang --version`[%r{clang-(\d+\.\d+\.\d+)}, 1]
<add> return true unless version
<ide> version < latest_version
<ide> end
<ide> | 1 |
Text | Text | improve docker man page | 29f379ea6e2a68d8ac4bf41d3559a52066a275a0 | <ide><path>docs/man/docker.1.md
<ide> unix://[/path/to/socket] to use.
<ide> Enable selinux support. Default is false. SELinux does not presently support the BTRFS storage driver.
<ide>
<ide> # COMMANDS
<del>**docker-attach(1)**
<add>**attach**
<ide> Attach to a running container
<add> See **docker-attach(1)** for full documentation on the **attach** command.
<ide>
<del>**docker-build(1)**
<add>**build**
<ide> Build an image from a Dockerfile
<add> See **docker-build(1)** for full documentation on the **build** command.
<ide>
<del>**docker-commit(1)**
<add>**commit**
<ide> Create a new image from a container's changes
<add> See **docker-commit(1)** for full documentation on the **commit** command.
<ide>
<del>**docker-cp(1)**
<add>**cp**
<ide> Copy files/folders from a container's filesystem to the host
<add> See **docker-cp(1)** for full documentation on the **cp** command.
<ide>
<del>**docker-create(1)**
<add>**create**
<ide> Create a new container
<add> See **docker-create(1)** for full documentation on the **create** command.
<ide>
<del>**docker-diff(1)**
<add>**diff**
<ide> Inspect changes on a container's filesystem
<add> See **docker-diff(1)** for full documentation on the **diff** command.
<ide>
<del>**docker-events(1)**
<add>**events**
<ide> Get real time events from the server
<add> See **docker-events(1)** for full documentation on the **events** command.
<ide>
<del>**docker-exec(1)**
<add>**exec**
<ide> Run a command in a running container
<add> See **docker-exec(1)** for full documentation on the **exec** command.
<ide>
<del>**docker-export(1)**
<add>**export**
<ide> Stream the contents of a container as a tar archive
<add> See **docker-export(1)** for full documentation on the **export** command.
<ide>
<del>**docker-history(1)**
<add>**history**
<ide> Show the history of an image
<add> See **docker-history(1)** for full documentation on the **history** command.
<ide>
<del>**docker-images(1)**
<add>**images**
<ide> List images
<add> See **docker-images(1)** for full documentation on the **images** command.
<ide>
<del>**docker-import(1)**
<add>**import**
<ide> Create a new filesystem image from the contents of a tarball
<add> See **docker-import(1)** for full documentation on the **import** command.
<ide>
<del>**docker-info(1)**
<add>**info**
<ide> Display system-wide information
<add> See **docker-info(1)** for full documentation on the **info** command.
<ide>
<del>**docker-inspect(1)**
<add>**inspect**
<ide> Return low-level information on a container or image
<add> See **docker-inspect(1)** for full documentation on the **inspect** command.
<ide>
<del>**docker-kill(1)**
<add>**kill**
<ide> Kill a running container (which includes the wrapper process and everything
<ide> inside it)
<add> See **docker-kill(1)** for full documentation on the **kill** command.
<ide>
<del>**docker-load(1)**
<add>**load**
<ide> Load an image from a tar archive
<add> See **docker-load(1)** for full documentation on the **load** command.
<ide>
<del>**docker-login(1)**
<add>**login**
<ide> Register or login to a Docker Registry
<add> See **docker-login(1)** for full documentation on the **login** command.
<ide>
<del>**docker-logout(1)**
<add>**logout**
<ide> Log the user out of a Docker Registry
<add> See **docker-logout(1)** for full documentation on the **logout** command.
<ide>
<del>**docker-logs(1)**
<add>**logs**
<ide> Fetch the logs of a container
<add> See **docker-logs(1)** for full documentation on the **logs** command.
<ide>
<del>**docker-pause(1)**
<add>**pause**
<ide> Pause all processes within a container
<add> See **docker-pause(1)** for full documentation on the **pause** command.
<ide>
<del>**docker-port(1)**
<add>**port**
<ide> Lookup the public-facing port which is NAT-ed to PRIVATE_PORT
<add> See **docker-port(1)** for full documentation on the **port** command.
<ide>
<del>**docker-ps(1)**
<add>**ps**
<ide> List containers
<add> See **docker-ps(1)** for full documentation on the **ps** command.
<ide>
<del>**docker-pull(1)**
<add>**pull**
<ide> Pull an image or a repository from a Docker Registry
<add> See **docker-pull(1)** for full documentation on the **pull** command.
<ide>
<del>**docker-push(1)**
<add>**push**
<ide> Push an image or a repository to a Docker Registry
<add> See **docker-push(1)** for full documentation on the **push** command.
<ide>
<del>**docker-restart(1)**
<add>**restart**
<ide> Restart a running container
<add> See **docker-restart(1)** for full documentation on the **restart** command.
<ide>
<del>**docker-rm(1)**
<add>**rm**
<ide> Remove one or more containers
<add> See **docker-rm(1)** for full documentation on the **rm** command.
<ide>
<del>**docker-rmi(1)**
<add>**rmi**
<ide> Remove one or more images
<add> See **docker-rmi(1)** for full documentation on the **rmi** command.
<ide>
<del>**docker-run(1)**
<add>**run**
<ide> Run a command in a new container
<add> See **docker-run(1)** for full documentation on the **run** command.
<ide>
<del>**docker-save(1)**
<add>**save**
<ide> Save an image to a tar archive
<add> See **docker-save(1)** for full documentation on the **save** command.
<ide>
<del>**docker-search(1)**
<add>**search**
<ide> Search for an image in the Docker index
<add> See **docker-search(1)** for full documentation on the **search** command.
<ide>
<del>**docker-start(1)**
<add>**start**
<ide> Start a stopped container
<add> See **docker-start(1)** for full documentation on the **start** command.
<ide>
<del>**docker-stats(1)**
<add>**stats**
<ide> Display a live stream of one or more containers' resource usage statistics
<add> See **docker-stats(1)** for full documentation on the **stats** command.
<ide>
<del>**docker-stop(1)**
<add>**stop**
<ide> Stop a running container
<add> See **docker-stop(1)** for full documentation on the **stop** command.
<ide>
<del>**docker-tag(1)**
<add>**tag**
<ide> Tag an image into a repository
<add> See **docker-tag(1)** for full documentation on the **tag** command.
<ide>
<del>**docker-top(1)**
<add>**top**
<ide> Lookup the running processes of a container
<add> See **docker-top(1)** for full documentation on the **top** command.
<ide>
<del>**docker-unpause(1)**
<add>**unpause**
<ide> Unpause all processes within a container
<add> See **docker-unpause(1)** for full documentation on the **unpause** command.
<ide>
<del>**docker-version(1)**
<add>**version**
<ide> Show the Docker version information
<add> See **docker-version(1)** for full documentation on the **version** command.
<ide>
<del>**docker-wait(1)**
<add>**wait**
<ide> Block until a container stops, then print its exit code
<add> See **docker-wait(1)** for full documentation on the **wait** command.
<ide>
<ide> # STORAGE DRIVER OPTIONS
<ide> | 1 |
Python | Python | add lfs flags to node addon script | aef0d8086b233f97535841c9ea91f7139f8fc3bb | <ide><path>tools/wafadmin/Tools/node_addon.py
<ide> def detect(conf):
<ide>
<ide> conf.env['LIBPATH_NODE'] = lib
<ide> conf.env['CPPPATH_NODE'] = join(prefix, 'include', 'node')
<del> conf.env['CPPFLAGS_NODE'] = '-D_GNU_SOURCE'
<del> conf.env['CPPFLAGS_NODE'] = '-DEV_MULTIPLICITY=0'
<add>
<add> conf.env.append_value('CPPFLAGS_NODE', '-D_GNU_SOURCE')
<add> conf.env.append_value('CPPFLAGS_NODE', '-DEV_MULTIPLICITY=0')
<add>
<add> conf.env.append_value('CCFLAGS_NODE', '-D_LARGEFILE_SOURCE')
<add> conf.env.append_value('CCFLAGS_NODE', '-D_FILE_OFFSET_BITS=64')
<add>
<add> conf.env.append_value('CXXFLAGS_NODE', '-D_LARGEFILE_SOURCE')
<add> conf.env.append_value('CXXFLAGS_NODE', '-D_FILE_OFFSET_BITS=64')
<ide>
<ide> # with symbols
<ide> conf.env.append_value('CCFLAGS', ['-g'])
<ide> def get_prefix():
<ide> prefix = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
<ide> else:
<ide> prefix = os.environ['PREFIX_NODE']
<del> return prefix
<ide>\ No newline at end of file
<add> return prefix | 1 |
PHP | PHP | fix postgres dump | 1c7cfe2b0b29b427d442e20b767e7b67fe5af2bb | <ide><path>src/Illuminate/Database/Console/DumpCommand.php
<ide> class DumpCommand extends Command
<ide> */
<ide> public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)
<ide> {
<del> $this->schemaState(
<del> $connection = $connections->connection($database = $this->input->getOption('database'))
<del> )->dump($path = $this->path($connection));
<add> $connection = $connections->connection($database = $this->input->getOption('database'));
<add>
<add> $this->schemaState($connection)->dump(
<add> $connection, $path = $this->path($connection)
<add> );
<ide>
<ide> $dispatcher->dispatch(new SchemaDumped($connection, $path));
<ide>
<ide><path>src/Illuminate/Database/Schema/MySqlSchemaState.php
<ide> namespace Illuminate\Database\Schema;
<ide>
<ide> use Exception;
<add>use Illuminate\Database\Connection;
<ide> use Illuminate\Support\Str;
<ide> use Symfony\Component\Process\Process;
<ide>
<ide> class MySqlSchemaState extends SchemaState
<ide> /**
<ide> * Dump the database's schema into a file.
<ide> *
<add> * @param \Illuminate\Database\Connection $connection
<ide> * @param string $path
<ide> * @return void
<ide> */
<del> public function dump($path)
<add> public function dump(Connection $connection, $path)
<ide> {
<ide> $this->executeDumpProcess($this->makeProcess(
<ide> $this->baseDumpCommand().' --routines --result-file="${:LARAVEL_LOAD_PATH}" --no-data'
<ide><path>src/Illuminate/Database/Schema/PostgresSchemaState.php
<ide>
<ide> namespace Illuminate\Database\Schema;
<ide>
<add>use Illuminate\Database\Connection;
<ide> use Illuminate\Support\Str;
<ide>
<ide> class PostgresSchemaState extends SchemaState
<ide> {
<ide> /**
<ide> * Dump the database's schema into a file.
<ide> *
<add> * @param \Illuminate\Database\Connection $connection
<ide> * @param string $path
<ide> * @return void
<ide> */
<del> public function dump($path)
<add> public function dump(Connection $connection, $path)
<ide> {
<add> $excludedTables = collect($connection->getSchemaBuilder()->getAllTables())
<add> ->map->tablename
<add> ->reject(function ($table) {
<add> return $table === 'migrations';
<add> })->map(function ($table) {
<add> return '--exclude-table-data='.$table;
<add> })->implode(' ');
<add>
<ide> $this->makeProcess(
<del> $this->baseDumpCommand().' --no-owner --file=$LARAVEL_LOAD_PATH --schema-only'
<add> $this->baseDumpCommand().' --no-owner --file=$LARAVEL_LOAD_PATH '.$excludedTables
<ide> )->mustRun($this->output, array_merge($this->baseVariables($this->connection->getConfig()), [
<ide> 'LARAVEL_LOAD_PATH' => $path,
<ide> ]));
<del>
<del> $this->appendMigrationData($path);
<del> }
<del>
<del> /**
<del> * Append the migration data to the schema dump.
<del> *
<del> * @param string $path
<del> * @return void
<del> */
<del> protected function appendMigrationData(string $path)
<del> {
<del> with($process = $this->makeProcess(
<del> $this->baseDumpCommand().' --table=migrations --data-only --inserts'
<del> ))->setTimeout(null)->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
<del> //
<del> ]));
<del>
<del> $migrations = collect(preg_split("/\r\n|\n|\r/", $process->getOutput()))->filter(function ($line) {
<del> return preg_match('/^\s*(--|SELECT\s|SET\s)/iu', $line) === 0 &&
<del> strlen($line) > 0;
<del> })->all();
<del>
<del> $this->files->append($path, implode(PHP_EOL, $migrations).PHP_EOL);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Schema/SchemaState.php
<ide> public function __construct(Connection $connection, Filesystem $files = null, ca
<ide> /**
<ide> * Dump the database's schema into a file.
<ide> *
<add> * @param \Illuminate\Database\Connection $connection
<ide> * @param string $path
<ide> * @return void
<ide> */
<del> abstract public function dump($path);
<add> abstract public function dump(Connection $connection, $path);
<ide>
<ide> /**
<ide> * Load the given schema file into the database.
<ide><path>src/Illuminate/Database/Schema/SqliteSchemaState.php
<ide>
<ide> namespace Illuminate\Database\Schema;
<ide>
<add>use Illuminate\Database\Connection;
<add>
<ide> class SqliteSchemaState extends SchemaState
<ide> {
<ide> /**
<ide> * Dump the database's schema into a file.
<ide> *
<del> * @param string $path
<del> *
<add> * @param \Illuminate\Database\Connection
<add> * @param string $path
<ide> * @return void
<ide> */
<del> public function dump($path)
<add> public function dump(Connection $connection, $path)
<ide> {
<ide> with($process = $this->makeProcess(
<ide> $this->baseCommand().' .schema'
<ide> protected function appendMigrationData(string $path)
<ide> /**
<ide> * Load the given schema file into the database.
<ide> *
<del> * @param string $path
<del> *
<add> * @param string $path
<ide> * @return void
<ide> */
<ide> public function load($path) | 5 |
Ruby | Ruby | define weblog controller for url helper test | 213c920e4f0b1efeaccc4377dfebb41a5873efcf | <ide><path>actionpack/test/lib/controller/fake_controllers.rb
<ide> class CController < ActionController::Base; end
<ide> class HiController < ActionController::Base; end
<ide> class BraveController < ActionController::Base; end
<ide> class ImageController < ActionController::Base; end
<add>class WeblogController < ActionController::Base; end
<ide>
<ide> # For speed test
<ide> class SpeedController < ActionController::Base; end
<ide><path>actionpack/test/template/url_helper_test.rb
<ide> # encoding: utf-8
<ide> require 'abstract_unit'
<add>require 'controller/fake_controllers'
<ide>
<ide> RequestMock = Struct.new("Request", :request_uri, :protocol, :host_with_port, :env)
<ide> | 2 |
Python | Python | fix crash on non-void structured array repr | 7a3344a461fdb25c55cd5e4fa52abda895f01e20 | <ide><path>numpy/core/arrayprint.py
<ide> def _get_format_function(data, **options):
<ide> find the right formatting function for the dtype_
<ide> """
<ide> dtype_ = data.dtype
<del> if dtype_.fields is not None:
<del> return StructureFormat.from_data(data, **options)
<del>
<ide> dtypeobj = dtype_.type
<ide> formatdict = _get_formatdict(data, **options)
<ide> if issubclass(dtypeobj, _nt.bool_):
<ide> def _get_format_function(data, **options):
<ide> elif issubclass(dtypeobj, _nt.object_):
<ide> return formatdict['object']()
<ide> elif issubclass(dtypeobj, _nt.void):
<del> return formatdict['void']()
<add> if dtype_.names is not None:
<add> return StructuredVoidFormat.from_data(data, **options)
<add> else:
<add> return formatdict['void']()
<ide> else:
<ide> return formatdict['numpystr']()
<ide>
<ide> def __call__(self, arr):
<ide> return "[" + ", ".join(self.__call__(a) for a in arr) + "]"
<ide>
<ide>
<del>class StructureFormat(object):
<add>class StructuredVoidFormat(object):
<add> """
<add> Formatter for structured np.void objects.
<add>
<add> This does not work on structured alias types like np.dtype(('i4', 'i2,i2')),
<add> as alias scalars lose their field information, and the implementation
<add> relies upon np.void.__getitem__.
<add> """
<ide> def __init__(self, format_functions):
<ide> self.format_functions = format_functions
<ide>
<ide> @classmethod
<ide> def from_data(cls, data, **options):
<ide> """
<del> This is a second way to initialize StructureFormat, using the raw data
<add> This is a second way to initialize StructuredVoidFormat, using the raw data
<ide> as input. Added to avoid changing the signature of __init__.
<ide> """
<ide> format_functions = []
<ide> def __call__(self, x):
<ide> else:
<ide> return "({})".format(", ".join(str_fields))
<ide>
<add>
<add># for backwards compatibility
<add>class StructureFormat(StructuredVoidFormat):
<add> def __init__(self, *args, **kwargs):
<add> # NumPy 1.14, 2018-02-14
<add> warnings.warn(
<add> "StructureFormat has been replaced by StructuredVoidFormat",
<add> DeprecationWarning, stacklevel=2)
<add> super(StructureFormat, self).__init__(*args, **kwargs)
<add>
<add>
<ide> def _void_scalar_repr(x):
<ide> """
<ide> Implements the repr for structured-void scalars. It is called from the
<ide> scalartypes.c.src code, and is placed here because it uses the elementwise
<ide> formatters defined above.
<ide> """
<del> return StructureFormat.from_data(array(x), **_format_options)(x)
<add> return StructuredVoidFormat.from_data(array(x), **_format_options)(x)
<ide>
<ide>
<ide> _typelessdata = [int_, float_, complex_, bool_]
<ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_structured_non_void(self):
<ide> dt_int = np.dtype(('i4', fields))
<ide> assert_equal(str(dt_int), "(numpy.int32, [('a', '<i2'), ('b', '<i2')])")
<ide>
<add> # gh-9821
<add> arr_int = np.zeros(4, dt_int)
<add> assert_equal(repr(arr_int), "array([0, 0, 0, 0])")
<add>
<ide>
<ide> class TestZeroRank(object):
<ide> def setup(self): | 2 |
Ruby | Ruby | add kaby lake to linux hardware list | ebb659af7da12771efe134e1f9386324423f4246 | <ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb
<ide> def family
<ide> :haswell
<ide> when 0x3d, 0x47, 0x4f, 0x56
<ide> :broadwell
<add> when 0x8e
<add> :kabylake
<ide> else
<ide> cpu_family_model
<ide> end
<ide><path>Library/Homebrew/test/hardware_test.rb
<ide> def test_hardware_cpu_type
<ide>
<ide> if Hardware::CPU.intel?
<ide> def test_hardware_intel_family
<del> families = [:core, :core2, :penryn, :nehalem, :arrandale, :sandybridge, :ivybridge, :haswell, :broadwell, :skylake, :dunno]
<add> families = [:core, :core2, :penryn, :nehalem, :arrandale, :sandybridge, :ivybridge, :haswell, :broadwell, :skylake, :kabylake, :dunno]
<ide> assert_includes families, Hardware::CPU.family
<ide> end
<ide> end | 2 |
PHP | PHP | remove config for workbench | 90f8e8bd9ce1c46db31ab63f31a9558b12fdc318 | <ide><path>config/workbench.php
<del><?php
<del>
<del>return [
<del>
<del> /*
<del> |--------------------------------------------------------------------------
<del> | Workbench Author Name
<del> |--------------------------------------------------------------------------
<del> |
<del> | When you create new packages via the Artisan "workbench" command your
<del> | name is needed to generate the composer.json file for your package.
<del> | You may specify it now so it is used for all of your workbenches.
<del> |
<del> */
<del>
<del> 'name' => '',
<del>
<del> /*
<del> |--------------------------------------------------------------------------
<del> | Workbench Author E-Mail Address
<del> |--------------------------------------------------------------------------
<del> |
<del> | Like the option above, your e-mail address is used when generating new
<del> | workbench packages. The e-mail is placed in your composer.json file
<del> | automatically after the package is created by the workbench tool.
<del> |
<del> */
<del>
<del> 'email' => '',
<del>
<del>]; | 1 |
Python | Python | add support for lvis metrics | 4437d7b4b17c5535d516bcb4038ff9397ae9eef9 | <ide><path>research/object_detection/core/standard_fields.py
<ide> class InputDataFields(object):
<ide> groundtruth_keypoint_visibilities: ground truth keypoint visibilities.
<ide> groundtruth_keypoint_weights: groundtruth weight factor for keypoints.
<ide> groundtruth_label_weights: groundtruth label weights.
<add> groundtruth_verified_negative_classes: groundtruth verified negative classes
<add> groundtruth_not_exhaustive_classes: groundtruth not-exhaustively labeled
<add> classes.
<ide> groundtruth_weights: groundtruth weight factor for bounding boxes.
<ide> groundtruth_dp_num_points: The number of DensePose sampled points for each
<ide> instance.
<ide> class InputDataFields(object):
<ide> groundtruth_keypoint_visibilities = 'groundtruth_keypoint_visibilities'
<ide> groundtruth_keypoint_weights = 'groundtruth_keypoint_weights'
<ide> groundtruth_label_weights = 'groundtruth_label_weights'
<add> groundtruth_verified_neg_classes = 'groundtruth_verified_neg_classes'
<add> groundtruth_not_exhaustive_classes = 'groundtruth_not_exhaustive_classes'
<ide> groundtruth_weights = 'groundtruth_weights'
<ide> groundtruth_dp_num_points = 'groundtruth_dp_num_points'
<ide> groundtruth_dp_part_ids = 'groundtruth_dp_part_ids'
<ide><path>research/object_detection/eval_util_test.py
<ide> def _make_evaluation_dict(self,
<ide> groundtruth_boxes = tf.constant([[0., 0., 1., 1.]])
<ide> groundtruth_classes = tf.constant([1])
<ide> groundtruth_instance_masks = tf.ones(shape=[1, 20, 20], dtype=tf.uint8)
<add> original_image_spatial_shapes = tf.constant([[20, 20]], dtype=tf.int32)
<add>
<ide> groundtruth_keypoints = tf.constant([[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]])
<ide> if resized_groundtruth_masks:
<ide> groundtruth_instance_masks = tf.ones(shape=[1, 10, 10], dtype=tf.uint8)
<ide> def _make_evaluation_dict(self,
<ide> groundtruth_keypoints = tf.tile(
<ide> tf.expand_dims(groundtruth_keypoints, 0),
<ide> multiples=[batch_size, 1, 1])
<add> original_image_spatial_shapes = tf.tile(original_image_spatial_shapes,
<add> multiples=[batch_size, 1])
<ide>
<ide> detections = {
<ide> detection_fields.detection_boxes: detection_boxes,
<ide> def _make_evaluation_dict(self,
<ide> input_data_fields.groundtruth_boxes: groundtruth_boxes,
<ide> input_data_fields.groundtruth_classes: groundtruth_classes,
<ide> input_data_fields.groundtruth_keypoints: groundtruth_keypoints,
<del> input_data_fields.groundtruth_instance_masks: groundtruth_instance_masks
<add> input_data_fields.groundtruth_instance_masks:
<add> groundtruth_instance_masks,
<add> input_data_fields.original_image_spatial_shape:
<add> original_image_spatial_shapes
<ide> }
<ide> if batch_size > 1:
<ide> return eval_util.result_dict_for_batched_example(
<ide><path>research/object_detection/metrics/coco_evaluation.py
<ide> def update_op(image_id_batched, groundtruth_boxes_batched,
<ide> groundtruth_instance_masks_batched,
<ide> groundtruth_is_crowd_batched, num_gt_boxes_per_image,
<ide> detection_scores_batched, detection_classes_batched,
<del> detection_masks_batched, num_det_boxes_per_image):
<add> detection_masks_batched, num_det_boxes_per_image,
<add> original_image_spatial_shape):
<ide> """Update op for metrics."""
<ide>
<ide> for (image_id, groundtruth_boxes, groundtruth_classes,
<ide> groundtruth_instance_masks, groundtruth_is_crowd, num_gt_box,
<ide> detection_scores, detection_classes,
<del> detection_masks, num_det_box) in zip(
<add> detection_masks, num_det_box, original_image_shape) in zip(
<ide> image_id_batched, groundtruth_boxes_batched,
<ide> groundtruth_classes_batched, groundtruth_instance_masks_batched,
<ide> groundtruth_is_crowd_batched, num_gt_boxes_per_image,
<ide> detection_scores_batched, detection_classes_batched,
<del> detection_masks_batched, num_det_boxes_per_image):
<add> detection_masks_batched, num_det_boxes_per_image,
<add> original_image_spatial_shape):
<ide> self.add_single_ground_truth_image_info(
<ide> image_id, {
<ide> 'groundtruth_boxes':
<ide> groundtruth_boxes[:num_gt_box],
<ide> 'groundtruth_classes':
<ide> groundtruth_classes[:num_gt_box],
<ide> 'groundtruth_instance_masks':
<del> groundtruth_instance_masks[:num_gt_box],
<add> groundtruth_instance_masks[:num_gt_box][
<add> :original_image_shape[0], :original_image_shape[1]],
<ide> 'groundtruth_is_crowd':
<ide> groundtruth_is_crowd[:num_gt_box]
<ide> })
<ide> self.add_single_detected_image_info(
<ide> image_id, {
<ide> 'detection_scores': detection_scores[:num_det_box],
<ide> 'detection_classes': detection_classes[:num_det_box],
<del> 'detection_masks': detection_masks[:num_det_box]
<add> 'detection_masks': detection_masks[:num_det_box][
<add> :original_image_shape[0], :original_image_shape[1]]
<ide> })
<ide>
<ide> # Unpack items from the evaluation dictionary.
<ide> input_data_fields = standard_fields.InputDataFields
<ide> detection_fields = standard_fields.DetectionResultFields
<ide> image_id = eval_dict[input_data_fields.key]
<add> original_image_spatial_shape = eval_dict[
<add> input_data_fields.original_image_spatial_shape]
<ide> groundtruth_boxes = eval_dict[input_data_fields.groundtruth_boxes]
<ide> groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]
<ide> groundtruth_instance_masks = eval_dict[
<ide> def update_op(image_id_batched, groundtruth_boxes_batched,
<ide> image_id, groundtruth_boxes, groundtruth_classes,
<ide> groundtruth_instance_masks, groundtruth_is_crowd,
<ide> num_gt_boxes_per_image, detection_scores, detection_classes,
<del> detection_masks, num_det_boxes_per_image
<add> detection_masks, num_det_boxes_per_image, original_image_spatial_shape
<ide> ], [])
<ide>
<ide> def get_estimator_eval_metric_ops(self, eval_dict):
<ide><path>research/object_detection/metrics/coco_evaluation_test.py
<ide> def testAddEvalDict(self):
<ide> groundtruth_boxes = tf.placeholder(tf.float32, shape=(None, 4))
<ide> groundtruth_classes = tf.placeholder(tf.float32, shape=(None))
<ide> groundtruth_masks = tf.placeholder(tf.uint8, shape=(None, None, None))
<add> original_image_spatial_shape = tf.placeholder(tf.int32, shape=(None, 2))
<ide> detection_scores = tf.placeholder(tf.float32, shape=(None))
<ide> detection_classes = tf.placeholder(tf.float32, shape=(None))
<ide> detection_masks = tf.placeholder(tf.uint8, shape=(None, None, None))
<ide> def testAddEvalDict(self):
<ide> input_data_fields.groundtruth_boxes: groundtruth_boxes,
<ide> input_data_fields.groundtruth_classes: groundtruth_classes,
<ide> input_data_fields.groundtruth_instance_masks: groundtruth_masks,
<add> input_data_fields.original_image_spatial_shape:
<add> original_image_spatial_shape,
<ide> detection_fields.detection_scores: detection_scores,
<ide> detection_fields.detection_classes: detection_classes,
<ide> detection_fields.detection_masks: detection_masks,
<ide> def testAddEvalDict(self):
<ide> np.ones([50, 50], dtype=np.uint8), ((0, 70), (0, 70)),
<ide> mode='constant')
<ide> ]),
<add> original_image_spatial_shape: np.array([[120, 120]]),
<ide> detection_scores:
<ide> np.array([.9, .8]),
<ide> detection_classes:
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<ide> groundtruth_boxes = tf.placeholder(tf.float32, shape=(None, 4))
<ide> groundtruth_classes = tf.placeholder(tf.float32, shape=(None))
<ide> groundtruth_masks = tf.placeholder(tf.uint8, shape=(None, None, None))
<add> original_image_spatial_shape = tf.placeholder(tf.int32, shape=(None, 2))
<ide> detection_scores = tf.placeholder(tf.float32, shape=(None))
<ide> detection_classes = tf.placeholder(tf.float32, shape=(None))
<ide> detection_masks = tf.placeholder(tf.uint8, shape=(None, None, None))
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<ide> input_data_fields.groundtruth_boxes: groundtruth_boxes,
<ide> input_data_fields.groundtruth_classes: groundtruth_classes,
<ide> input_data_fields.groundtruth_instance_masks: groundtruth_masks,
<add> input_data_fields.original_image_spatial_shape:
<add> original_image_spatial_shape,
<ide> detection_fields.detection_scores: detection_scores,
<ide> detection_fields.detection_classes: detection_classes,
<ide> detection_fields.detection_masks: detection_masks,
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<ide> np.ones([50, 50], dtype=np.uint8), ((0, 70), (0, 70)),
<ide> mode='constant')
<ide> ]),
<add> original_image_spatial_shape: np.array([[120, 120], [120, 120]]),
<ide> detection_scores:
<ide> np.array([.9, .8]),
<ide> detection_classes:
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<ide> dtype=np.uint8),
<ide> ((0, 0), (10, 10), (10, 10)),
<ide> mode='constant'),
<add> original_image_spatial_shape: np.array([[70, 70]]),
<ide> detection_scores: np.array([.8]),
<ide> detection_classes: np.array([1]),
<ide> detection_masks: np.pad(np.ones([1, 50, 50], dtype=np.uint8),
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<ide> dtype=np.uint8),
<ide> ((0, 0), (10, 10), (10, 10)),
<ide> mode='constant'),
<add> original_image_spatial_shape: np.array([[45, 45]]),
<ide> detection_scores: np.array([.8]),
<ide> detection_classes: np.array([1]),
<ide> detection_masks: np.pad(np.ones([1, 25, 25],
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetectionsBatched(self):
<ide> groundtruth_classes = tf.placeholder(tf.float32, shape=(batch_size, None))
<ide> groundtruth_masks = tf.placeholder(
<ide> tf.uint8, shape=(batch_size, None, None, None))
<add> original_image_spatial_shape = tf.placeholder(tf.int32, shape=(None, 2))
<ide> detection_scores = tf.placeholder(tf.float32, shape=(batch_size, None))
<ide> detection_classes = tf.placeholder(tf.float32, shape=(batch_size, None))
<ide> detection_masks = tf.placeholder(
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetectionsBatched(self):
<ide> input_data_fields.groundtruth_boxes: groundtruth_boxes,
<ide> input_data_fields.groundtruth_classes: groundtruth_classes,
<ide> input_data_fields.groundtruth_instance_masks: groundtruth_masks,
<add> input_data_fields.original_image_spatial_shape:
<add> original_image_spatial_shape,
<ide> detection_fields.detection_scores: detection_scores,
<ide> detection_fields.detection_classes: detection_classes,
<ide> detection_fields.detection_masks: detection_masks,
<ide> def testGetOneMAPWithMatchingGroundtruthAndDetectionsBatched(self):
<ide> mode='constant')
<ide> ],
<ide> axis=0),
<add> original_image_spatial_shape: np.array(
<add> [[100, 100], [100, 100], [100, 100]]),
<ide> detection_scores:
<ide> np.array([[.8], [.8], [.8]]),
<ide> detection_classes:
<ide><path>research/object_detection/metrics/lvis_evaluation.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>"""Class for evaluating object detections with LVIS metrics."""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import json
<add>import re
<add>
<add>from lvis import results as lvis_results
<add>
<add>import numpy as np
<add>from six.moves import zip
<add>import tensorflow.compat.v1 as tf
<add>
<add>from object_detection.core import standard_fields as fields
<add>from object_detection.metrics import lvis_tools
<add>from object_detection.utils import object_detection_evaluation
<add>
<add>
<add>def convert_masks_to_binary(masks):
<add> """Converts masks to 0 or 1 and uint8 type."""
<add> return (masks > 0).astype(np.uint8)
<add>
<add>
<add>class LVISMaskEvaluator(object_detection_evaluation.DetectionEvaluator):
<add> """Class to evaluate LVIS mask metrics."""
<add>
<add> def __init__(self,
<add> categories):
<add> """Constructor.
<add>
<add> Args:
<add> categories: A list of dicts, each of which has the following keys -
<add> 'id': (required) an integer id uniquely identifying this category.
<add> 'name': (required) string representing category name e.g., 'cat', 'dog'.
<add> """
<add> super(LVISMaskEvaluator, self).__init__(categories)
<add> self._image_ids_with_detections = set([])
<add> self._groundtruth_list = []
<add> self._detection_masks_list = []
<add> self._category_id_set = set([cat['id'] for cat in self._categories])
<add> self._annotation_id = 1
<add> self._image_id_to_mask_shape_map = {}
<add> self._image_id_to_verified_neg_classes = {}
<add> self._image_id_to_not_exhaustive_classes = {}
<add>
<add> def clear(self):
<add> """Clears the state to prepare for a fresh evaluation."""
<add> self._image_id_to_mask_shape_map.clear()
<add> self._image_ids_with_detections.clear()
<add> self._image_id_to_verified_neg_classes.clear()
<add> self._image_id_to_not_exhaustive_classes.clear()
<add> self._groundtruth_list = []
<add> self._detection_masks_list = []
<add>
<add> def add_single_ground_truth_image_info(self,
<add> image_id,
<add> groundtruth_dict):
<add> """Adds groundtruth for a single image to be used for evaluation.
<add>
<add> If the image has already been added, a warning is logged, and groundtruth is
<add> ignored.
<add>
<add> Args:
<add> image_id: A unique string/integer identifier for the image.
<add> groundtruth_dict: A dictionary containing -
<add> InputDataFields.groundtruth_boxes: float32 numpy array of shape
<add> [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format
<add> [ymin, xmin, ymax, xmax] in absolute image coordinates.
<add> InputDataFields.groundtruth_classes: integer numpy array of shape
<add> [num_boxes] containing 1-indexed groundtruth classes for the boxes.
<add> InputDataFields.groundtruth_instance_masks: uint8 numpy array of shape
<add> [num_masks, image_height, image_width] containing groundtruth masks.
<add> The elements of the array must be in {0, 1}.
<add> InputDataFields.groundtruth_verified_neg_classes: [num_classes]
<add> float indicator vector with values in {0, 1}.
<add> InputDataFields.groundtruth_not_exhaustive_classes: [num_classes]
<add> float indicator vector with values in {0, 1}.
<add> InputDataFields.groundtruth_area (optional): float numpy array of
<add> shape [num_boxes] containing the area (in the original absolute
<add> coordinates) of the annotated object.
<add> Raises:
<add> ValueError: if groundtruth_dict is missing a required field
<add> """
<add> if image_id in self._image_id_to_mask_shape_map:
<add> tf.logging.warning('Ignoring ground truth with image id %s since it was '
<add> 'previously added', image_id)
<add> return
<add> for key in [fields.InputDataFields.groundtruth_boxes,
<add> fields.InputDataFields.groundtruth_classes,
<add> fields.InputDataFields.groundtruth_instance_masks,
<add> fields.InputDataFields.groundtruth_verified_neg_classes,
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes]:
<add> if key not in groundtruth_dict.keys():
<add> raise ValueError('groundtruth_dict missing entry: {}'.format(key))
<add>
<add> groundtruth_instance_masks = groundtruth_dict[
<add> fields.InputDataFields.groundtruth_instance_masks]
<add> groundtruth_instance_masks = convert_masks_to_binary(
<add> groundtruth_instance_masks)
<add> verified_neg_classes_shape = groundtruth_dict[
<add> fields.InputDataFields.groundtruth_verified_neg_classes].shape
<add> not_exhaustive_classes_shape = groundtruth_dict[
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes].shape
<add> if verified_neg_classes_shape != (len(self._category_id_set),):
<add> raise ValueError('Invalid shape for verified_neg_classes_shape.')
<add> if not_exhaustive_classes_shape != (len(self._category_id_set),):
<add> raise ValueError('Invalid shape for not_exhaustive_classes_shape.')
<add> self._image_id_to_verified_neg_classes[image_id] = np.flatnonzero(
<add> groundtruth_dict[
<add> fields.InputDataFields.groundtruth_verified_neg_classes]
<add> == 1).tolist()
<add> self._image_id_to_not_exhaustive_classes[image_id] = np.flatnonzero(
<add> groundtruth_dict[
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes]
<add> == 1).tolist()
<add>
<add> # Drop optional fields if empty tensor.
<add> groundtruth_area = groundtruth_dict.get(
<add> fields.InputDataFields.groundtruth_area)
<add> if groundtruth_area is not None and not groundtruth_area.shape[0]:
<add> groundtruth_area = None
<add>
<add> self._groundtruth_list.extend(
<add> lvis_tools.ExportSingleImageGroundtruthToLVIS(
<add> image_id=image_id,
<add> next_annotation_id=self._annotation_id,
<add> category_id_set=self._category_id_set,
<add> groundtruth_boxes=groundtruth_dict[
<add> fields.InputDataFields.groundtruth_boxes],
<add> groundtruth_classes=groundtruth_dict[
<add> fields.InputDataFields.groundtruth_classes],
<add> groundtruth_masks=groundtruth_instance_masks,
<add> groundtruth_area=groundtruth_area)
<add> )
<add>
<add> self._annotation_id += groundtruth_dict[fields.InputDataFields.
<add> groundtruth_boxes].shape[0]
<add> self._image_id_to_mask_shape_map[image_id] = groundtruth_dict[
<add> fields.InputDataFields.groundtruth_instance_masks].shape
<add>
<add> def add_single_detected_image_info(self,
<add> image_id,
<add> detections_dict):
<add> """Adds detections for a single image to be used for evaluation.
<add>
<add> If a detection has already been added for this image id, a warning is
<add> logged, and the detection is skipped.
<add>
<add> Args:
<add> image_id: A unique string/integer identifier for the image.
<add> detections_dict: A dictionary containing -
<add> DetectionResultFields.detection_scores: float32 numpy array of shape
<add> [num_boxes] containing detection scores for the boxes.
<add> DetectionResultFields.detection_classes: integer numpy array of shape
<add> [num_boxes] containing 1-indexed detection classes for the boxes.
<add> DetectionResultFields.detection_masks: optional uint8 numpy array of
<add> shape [num_boxes, image_height, image_width] containing instance
<add> masks corresponding to the boxes. The elements of the array must be
<add> in {0, 1}.
<add> Raises:
<add> ValueError: If groundtruth for the image_id is not available.
<add> """
<add> if image_id not in self._image_id_to_mask_shape_map:
<add> raise ValueError('Missing groundtruth for image id: {}'.format(image_id))
<add>
<add> if image_id in self._image_ids_with_detections:
<add> tf.logging.warning('Ignoring detection with image id %s since it was '
<add> 'previously added', image_id)
<add> return
<add>
<add> groundtruth_masks_shape = self._image_id_to_mask_shape_map[image_id]
<add> detection_masks = detections_dict[fields.DetectionResultFields.
<add> detection_masks]
<add> if groundtruth_masks_shape[1:] != detection_masks.shape[1:]:
<add> raise ValueError('Spatial shape of groundtruth masks and detection masks '
<add> 'are incompatible: {} vs {}'.format(
<add> groundtruth_masks_shape,
<add> detection_masks.shape))
<add> detection_masks = convert_masks_to_binary(detection_masks)
<add>
<add> self._detection_masks_list.extend(
<add> lvis_tools.ExportSingleImageDetectionMasksToLVIS(
<add> image_id=image_id,
<add> category_id_set=self._category_id_set,
<add> detection_masks=detection_masks,
<add> detection_scores=detections_dict[
<add> fields.DetectionResultFields.detection_scores],
<add> detection_classes=detections_dict[
<add> fields.DetectionResultFields.detection_classes]))
<add> self._image_ids_with_detections.update([image_id])
<add>
<add> def evaluate(self):
<add> """Evaluates the detection boxes and returns a dictionary of coco metrics.
<add>
<add> Returns:
<add> A dictionary holding
<add> """
<add> tf.logging.info('Performing evaluation on %d images.',
<add> len(self._image_id_to_mask_shape_map.keys()))
<add> # pylint: disable=g-complex-comprehension
<add> groundtruth_dict = {
<add> 'annotations': self._groundtruth_list,
<add> 'images': [
<add> {
<add> 'id': image_id,
<add> 'height': shape[1],
<add> 'width': shape[2],
<add> 'neg_category_ids':
<add> self._image_id_to_verified_neg_classes[image_id],
<add> 'not_exhaustive_category_ids':
<add> self._image_id_to_not_exhaustive_classes[image_id]
<add> } for image_id, shape in self._image_id_to_mask_shape_map.items()],
<add> 'categories': self._categories
<add> }
<add> # pylint: enable=g-complex-comprehension
<add> lvis_wrapped_groundtruth = lvis_tools.LVISWrapper(groundtruth_dict)
<add> detections = lvis_results.LVISResults(lvis_wrapped_groundtruth,
<add> self._detection_masks_list)
<add> mask_evaluator = lvis_tools.LVISEvalWrapper(
<add> lvis_wrapped_groundtruth, detections, iou_type='segm')
<add> mask_metrics = mask_evaluator.ComputeMetrics()
<add> mask_metrics = {'DetectionMasks_'+ key: value
<add> for key, value in iter(mask_metrics.items())}
<add> return mask_metrics
<add>
<add> def add_eval_dict(self, eval_dict):
<add> """Observes an evaluation result dict for a single example.
<add>
<add> When executing eagerly, once all observations have been observed by this
<add> method you can use `.evaluate()` to get the final metrics.
<add>
<add> When using `tf.estimator.Estimator` for evaluation this function is used by
<add> `get_estimator_eval_metric_ops()` to construct the metric update op.
<add>
<add> Args:
<add> eval_dict: A dictionary that holds tensors for evaluating an object
<add> detection model, returned from
<add> eval_util.result_dict_for_single_example().
<add>
<add> Returns:
<add> None when executing eagerly, or an update_op that can be used to update
<add> the eval metrics in `tf.estimator.EstimatorSpec`.
<add> """
<add> def update_op(image_id_batched, groundtruth_boxes_batched,
<add> groundtruth_classes_batched,
<add> groundtruth_instance_masks_batched,
<add> groundtruth_verified_neg_classes_batched,
<add> groundtruth_not_exhaustive_classes_batched,
<add> num_gt_boxes_per_image,
<add> detection_scores_batched, detection_classes_batched,
<add> detection_masks_batched, num_det_boxes_per_image,
<add> original_image_spatial_shape):
<add> """Update op for metrics."""
<add>
<add> for (image_id, groundtruth_boxes, groundtruth_classes,
<add> groundtruth_instance_masks, groundtruth_verified_neg_classes,
<add> groundtruth_not_exhaustive_classes, num_gt_box,
<add> detection_scores, detection_classes,
<add> detection_masks, num_det_box, original_image_shape) in zip(
<add> image_id_batched, groundtruth_boxes_batched,
<add> groundtruth_classes_batched, groundtruth_instance_masks_batched,
<add> groundtruth_verified_neg_classes_batched,
<add> groundtruth_not_exhaustive_classes_batched,
<add> num_gt_boxes_per_image,
<add> detection_scores_batched, detection_classes_batched,
<add> detection_masks_batched, num_det_boxes_per_image,
<add> original_image_spatial_shape):
<add> self.add_single_ground_truth_image_info(
<add> image_id, {
<add> input_data_fields.groundtruth_boxes:
<add> groundtruth_boxes[:num_gt_box],
<add> input_data_fields.groundtruth_classes:
<add> groundtruth_classes[:num_gt_box],
<add> input_data_fields.groundtruth_instance_masks:
<add> groundtruth_instance_masks[:num_gt_box][
<add> :original_image_shape[0], :original_image_shape[1]],
<add> input_data_fields.groundtruth_verified_neg_classes:
<add> groundtruth_verified_neg_classes,
<add> input_data_fields.groundtruth_not_exhaustive_classes:
<add> groundtruth_not_exhaustive_classes
<add> })
<add> self.add_single_detected_image_info(
<add> image_id, {
<add> 'detection_scores': detection_scores[:num_det_box],
<add> 'detection_classes': detection_classes[:num_det_box],
<add> 'detection_masks': detection_masks[:num_det_box][
<add> :original_image_shape[0], :original_image_shape[1]]
<add> })
<add>
<add> # Unpack items from the evaluation dictionary.
<add> input_data_fields = fields.InputDataFields
<add> detection_fields = fields.DetectionResultFields
<add> image_id = eval_dict[input_data_fields.key]
<add> original_image_spatial_shape = eval_dict[
<add> input_data_fields.original_image_spatial_shape]
<add> groundtruth_boxes = eval_dict[input_data_fields.groundtruth_boxes]
<add> groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]
<add> groundtruth_instance_masks = eval_dict[
<add> input_data_fields.groundtruth_instance_masks]
<add> groundtruth_verified_neg_classes = eval_dict[
<add> input_data_fields.groundtruth_verified_neg_classes]
<add> groundtruth_not_exhaustive_classes = eval_dict[
<add> input_data_fields.groundtruth_not_exhaustive_classes]
<add>
<add> num_gt_boxes_per_image = eval_dict.get(
<add> input_data_fields.num_groundtruth_boxes, None)
<add> detection_scores = eval_dict[detection_fields.detection_scores]
<add> detection_classes = eval_dict[detection_fields.detection_classes]
<add> detection_masks = eval_dict[detection_fields.detection_masks]
<add> num_det_boxes_per_image = eval_dict.get(detection_fields.num_detections,
<add> None)
<add>
<add> if not image_id.shape.as_list():
<add> # Apply a batch dimension to all tensors.
<add> image_id = tf.expand_dims(image_id, 0)
<add> groundtruth_boxes = tf.expand_dims(groundtruth_boxes, 0)
<add> groundtruth_classes = tf.expand_dims(groundtruth_classes, 0)
<add> groundtruth_instance_masks = tf.expand_dims(groundtruth_instance_masks, 0)
<add> groundtruth_verified_neg_classes = tf.expand_dims(
<add> groundtruth_verified_neg_classes, 0)
<add> groundtruth_not_exhaustive_classes = tf.expand_dims(
<add> groundtruth_not_exhaustive_classes, 0)
<add> detection_scores = tf.expand_dims(detection_scores, 0)
<add> detection_classes = tf.expand_dims(detection_classes, 0)
<add> detection_masks = tf.expand_dims(detection_masks, 0)
<add>
<add> if num_gt_boxes_per_image is None:
<add> num_gt_boxes_per_image = tf.shape(groundtruth_boxes)[1:2]
<add> else:
<add> num_gt_boxes_per_image = tf.expand_dims(num_gt_boxes_per_image, 0)
<add>
<add> if num_det_boxes_per_image is None:
<add> num_det_boxes_per_image = tf.shape(detection_scores)[1:2]
<add> else:
<add> num_det_boxes_per_image = tf.expand_dims(num_det_boxes_per_image, 0)
<add> else:
<add> if num_gt_boxes_per_image is None:
<add> num_gt_boxes_per_image = tf.tile(
<add> tf.shape(groundtruth_boxes)[1:2],
<add> multiples=tf.shape(groundtruth_boxes)[0:1])
<add> if num_det_boxes_per_image is None:
<add> num_det_boxes_per_image = tf.tile(
<add> tf.shape(detection_scores)[1:2],
<add> multiples=tf.shape(detection_scores)[0:1])
<add>
<add> return tf.py_func(update_op, [
<add> image_id, groundtruth_boxes, groundtruth_classes,
<add> groundtruth_instance_masks, groundtruth_verified_neg_classes,
<add> groundtruth_not_exhaustive_classes,
<add> num_gt_boxes_per_image, detection_scores, detection_classes,
<add> detection_masks, num_det_boxes_per_image, original_image_spatial_shape
<add> ], [])
<add>
<add> def get_estimator_eval_metric_ops(self, eval_dict):
<add> """Returns a dictionary of eval metric ops.
<add>
<add> Note that once value_op is called, the detections and groundtruth added via
<add> update_op are cleared.
<add>
<add> Args:
<add> eval_dict: A dictionary that holds tensors for evaluating object detection
<add> performance. For single-image evaluation, this dictionary may be
<add> produced from eval_util.result_dict_for_single_example(). If multi-image
<add> evaluation, `eval_dict` should contain the fields
<add> 'num_groundtruth_boxes_per_image' and 'num_det_boxes_per_image' to
<add> properly unpad the tensors from the batch.
<add>
<add> Returns:
<add> a dictionary of metric names to tuple of value_op and update_op that can
<add> be used as eval metric ops in tf.estimator.EstimatorSpec. Note that all
<add> update ops must be run together and similarly all value ops must be run
<add> together to guarantee correct behaviour.
<add> """
<add> update_op = self.add_eval_dict(eval_dict)
<add> metric_names = ['DetectionMasks_Precision/mAP',
<add> 'DetectionMasks_Precision/[email protected]',
<add> 'DetectionMasks_Precision/[email protected]',
<add> 'DetectionMasks_Precision/mAP (small)',
<add> 'DetectionMasks_Precision/mAP (medium)',
<add> 'DetectionMasks_Precision/mAP (large)',
<add> 'DetectionMasks_Recall/AR@1',
<add> 'DetectionMasks_Recall/AR@10',
<add> 'DetectionMasks_Recall/AR@100',
<add> 'DetectionMasks_Recall/AR@100 (small)',
<add> 'DetectionMasks_Recall/AR@100 (medium)',
<add> 'DetectionMasks_Recall/AR@100 (large)']
<add> if self._include_metrics_per_category:
<add> for category_dict in self._categories:
<add> metric_names.append('DetectionMasks_PerformanceByCategory/mAP/' +
<add> category_dict['name'])
<add>
<add> def first_value_func():
<add> self._metrics = self.evaluate()
<add> self.clear()
<add> return np.float32(self._metrics[metric_names[0]])
<add>
<add> def value_func_factory(metric_name):
<add> def value_func():
<add> return np.float32(self._metrics[metric_name])
<add> return value_func
<add>
<add> # Ensure that the metrics are only evaluated once.
<add> first_value_op = tf.py_func(first_value_func, [], tf.float32)
<add> eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}
<add> with tf.control_dependencies([first_value_op]):
<add> for metric_name in metric_names[1:]:
<add> eval_metric_ops[metric_name] = (tf.py_func(
<add> value_func_factory(metric_name), [], np.float32), update_op)
<add> return eval_metric_ops
<add>
<add> def dump_detections_to_json_file(self, json_output_path):
<add> """Saves the detections into json_output_path in the format used by MS COCO.
<add>
<add> Args:
<add> json_output_path: String containing the output file's path. It can be also
<add> None. In that case nothing will be written to the output file.
<add> """
<add> if json_output_path and json_output_path is not None:
<add> pattern = re.compile(r'\d+\.\d{8,}')
<add> def mround(match):
<add> return '{:.2f}'.format(float(match.group()))
<add>
<add> with tf.io.gfile.GFile(json_output_path, 'w') as fid:
<add> json_string = json.dumps(self._detection_masks_list)
<add> fid.write(re.sub(pattern, mround, json_string))
<add>
<add> tf.logging.info('Dumping detections to output json file: %s',
<add> json_output_path)
<ide><path>research/object_detection/metrics/lvis_evaluation_test.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>"""Tests for tensorflow_models.object_detection.metrics.coco_evaluation."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import unittest
<add>import numpy as np
<add>import tensorflow.compat.v1 as tf
<add>from object_detection.core import standard_fields as fields
<add>from object_detection.metrics import lvis_evaluation
<add>from object_detection.utils import tf_version
<add>
<add>
<add>def _get_categories_list():
<add> return [{
<add> 'id': 1,
<add> 'name': 'person',
<add> 'frequency': 'f'
<add> }, {
<add> 'id': 2,
<add> 'name': 'dog',
<add> 'frequency': 'c'
<add> }, {
<add> 'id': 3,
<add> 'name': 'cat',
<add> 'frequency': 'r'
<add> }]
<add>
<add>
<add>class LvisMaskEvaluationTest(tf.test.TestCase):
<add>
<add> def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
<add> """Tests that mAP is calculated correctly on GT and Detections."""
<add> masks1 = np.expand_dims(np.pad(
<add> np.ones([100, 100], dtype=np.uint8),
<add> ((100, 56), (100, 56)), mode='constant'), axis=0)
<add> masks2 = np.expand_dims(np.pad(
<add> np.ones([50, 50], dtype=np.uint8),
<add> ((50, 156), (50, 156)), mode='constant'), axis=0)
<add> masks3 = np.expand_dims(np.pad(
<add> np.ones([25, 25], dtype=np.uint8),
<add> ((25, 206), (25, 206)), mode='constant'), axis=0)
<add>
<add> lvis_evaluator = lvis_evaluation.LVISMaskEvaluator(
<add> _get_categories_list())
<add> lvis_evaluator.add_single_ground_truth_image_info(
<add> image_id='image1',
<add> groundtruth_dict={
<add> fields.InputDataFields.groundtruth_boxes:
<add> np.array([[100., 100., 200., 200.]]),
<add> fields.InputDataFields.groundtruth_classes: np.array([1]),
<add> fields.InputDataFields.groundtruth_instance_masks: masks1,
<add> fields.InputDataFields.groundtruth_verified_neg_classes:
<add> np.array([0, 0, 0]),
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes:
<add> np.array([0, 0, 0])
<add> })
<add> lvis_evaluator.add_single_detected_image_info(
<add> image_id='image1',
<add> detections_dict={
<add> fields.DetectionResultFields.detection_masks: masks1,
<add> fields.DetectionResultFields.detection_scores:
<add> np.array([.8]),
<add> fields.DetectionResultFields.detection_classes:
<add> np.array([1])
<add> })
<add> lvis_evaluator.add_single_ground_truth_image_info(
<add> image_id='image2',
<add> groundtruth_dict={
<add> fields.InputDataFields.groundtruth_boxes:
<add> np.array([[50., 50., 100., 100.]]),
<add> fields.InputDataFields.groundtruth_classes: np.array([1]),
<add> fields.InputDataFields.groundtruth_instance_masks: masks2,
<add> fields.InputDataFields.groundtruth_verified_neg_classes:
<add> np.array([0, 0, 0]),
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes:
<add> np.array([0, 0, 0])
<add> })
<add> lvis_evaluator.add_single_detected_image_info(
<add> image_id='image2',
<add> detections_dict={
<add> fields.DetectionResultFields.detection_masks: masks2,
<add> fields.DetectionResultFields.detection_scores:
<add> np.array([.8]),
<add> fields.DetectionResultFields.detection_classes:
<add> np.array([1])
<add> })
<add> lvis_evaluator.add_single_ground_truth_image_info(
<add> image_id='image3',
<add> groundtruth_dict={
<add> fields.InputDataFields.groundtruth_boxes:
<add> np.array([[25., 25., 50., 50.]]),
<add> fields.InputDataFields.groundtruth_classes: np.array([1]),
<add> fields.InputDataFields.groundtruth_instance_masks: masks3,
<add> fields.InputDataFields.groundtruth_verified_neg_classes:
<add> np.array([0, 0, 0]),
<add> fields.InputDataFields.groundtruth_not_exhaustive_classes:
<add> np.array([0, 0, 0])
<add> })
<add> lvis_evaluator.add_single_detected_image_info(
<add> image_id='image3',
<add> detections_dict={
<add> fields.DetectionResultFields.detection_masks: masks3,
<add> fields.DetectionResultFields.detection_scores:
<add> np.array([.8]),
<add> fields.DetectionResultFields.detection_classes:
<add> np.array([1])
<add> })
<add> metrics = lvis_evaluator.evaluate()
<add> self.assertAlmostEqual(metrics['DetectionMasks_AP'], 1.0)
<add>
<add>
<add>@unittest.skipIf(tf_version.is_tf1(), 'Only Supported in TF2.X')
<add>class LVISMaskEvaluationPyFuncTest(tf.test.TestCase):
<add>
<add> def testAddEvalDict(self):
<add> lvis_evaluator = lvis_evaluation.LVISMaskEvaluator(_get_categories_list())
<add> image_id = tf.constant('image1', dtype=tf.string)
<add> groundtruth_boxes = tf.constant(
<add> np.array([[100., 100., 200., 200.], [50., 50., 100., 100.]]),
<add> dtype=tf.float32)
<add> groundtruth_classes = tf.constant(np.array([1, 2]), dtype=tf.float32)
<add> groundtruth_masks = tf.constant(np.stack([
<add> np.pad(np.ones([100, 100], dtype=np.uint8), ((10, 10), (10, 10)),
<add> mode='constant'),
<add> np.pad(np.ones([50, 50], dtype=np.uint8), ((0, 70), (0, 70)),
<add> mode='constant')
<add> ]), dtype=tf.uint8)
<add> original_image_spatial_shapes = tf.constant([[120, 120], [120, 120]],
<add> dtype=tf.int32)
<add> groundtruth_verified_neg_classes = tf.constant(np.array([0, 0, 0]),
<add> dtype=tf.float32)
<add> groundtruth_not_exhaustive_classes = tf.constant(np.array([0, 0, 0]),
<add> dtype=tf.float32)
<add> detection_scores = tf.constant(np.array([.9, .8]), dtype=tf.float32)
<add> detection_classes = tf.constant(np.array([2, 1]), dtype=tf.float32)
<add> detection_masks = tf.constant(np.stack([
<add> np.pad(np.ones([50, 50], dtype=np.uint8), ((0, 70), (0, 70)),
<add> mode='constant'),
<add> np.pad(np.ones([100, 100], dtype=np.uint8), ((10, 10), (10, 10)),
<add> mode='constant'),
<add> ]), dtype=tf.uint8)
<add>
<add> input_data_fields = fields.InputDataFields
<add> detection_fields = fields.DetectionResultFields
<add> eval_dict = {
<add> input_data_fields.key: image_id,
<add> input_data_fields.groundtruth_boxes: groundtruth_boxes,
<add> input_data_fields.groundtruth_classes: groundtruth_classes,
<add> input_data_fields.groundtruth_instance_masks: groundtruth_masks,
<add> input_data_fields.groundtruth_verified_neg_classes:
<add> groundtruth_verified_neg_classes,
<add> input_data_fields.groundtruth_not_exhaustive_classes:
<add> groundtruth_not_exhaustive_classes,
<add> input_data_fields.original_image_spatial_shape:
<add> original_image_spatial_shapes,
<add> detection_fields.detection_scores: detection_scores,
<add> detection_fields.detection_classes: detection_classes,
<add> detection_fields.detection_masks: detection_masks
<add> }
<add> lvis_evaluator.add_eval_dict(eval_dict)
<add> self.assertLen(lvis_evaluator._groundtruth_list, 2)
<add> self.assertLen(lvis_evaluator._detection_masks_list, 2)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
<ide><path>research/object_detection/metrics/lvis_tools.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>"""Wrappers for third party lvis to be used within object_detection.
<add>
<add>Usage example: given a set of images with ids in the list image_ids
<add>and corresponding lists of numpy arrays encoding groundtruth (boxes,
<add>masks and classes) and detections (masks, scores and classes), where
<add>elements of each list correspond to detections/annotations of a single image,
<add>then evaluation can be invoked as follows:
<add>
<add> groundtruth = lvis_tools.LVISWrapper(groundtruth_dict)
<add> detections = lvis_results.LVISResults(groundtruth, detections_list)
<add> evaluator = lvis_tools.LVISEvalWrapper(groundtruth, detections,
<add> iou_type='segm')
<add> summary_metrics = evaluator.ComputeMetrics()
<add>
<add>TODO(jonathanhuang): Add support for exporting to JSON.
<add>"""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import logging
<add>
<add>from lvis import eval as lvis_eval
<add>from lvis import lvis
<add>import numpy as np
<add>from pycocotools import mask
<add>import six
<add>from six.moves import range
<add>
<add>
<add>def RleCompress(masks):
<add> """Compresses mask using Run-length encoding provided by pycocotools.
<add>
<add> Args:
<add> masks: uint8 numpy array of shape [mask_height, mask_width] with values in
<add> {0, 1}.
<add>
<add> Returns:
<add> A pycocotools Run-length encoding of the mask.
<add> """
<add> rle = mask.encode(np.asfortranarray(masks))
<add> rle['counts'] = six.ensure_str(rle['counts'])
<add> return rle
<add>
<add>
<add>def _ConvertBoxToCOCOFormat(box):
<add> """Converts a box in [ymin, xmin, ymax, xmax] format to COCO format.
<add>
<add> This is a utility function for converting from our internal
<add> [ymin, xmin, ymax, xmax] convention to the convention used by the COCO API
<add> i.e., [xmin, ymin, width, height].
<add>
<add> Args:
<add> box: a [ymin, xmin, ymax, xmax] numpy array
<add>
<add> Returns:
<add> a list of floats representing [xmin, ymin, width, height]
<add> """
<add> return [float(box[1]), float(box[0]), float(box[3] - box[1]),
<add> float(box[2] - box[0])]
<add>
<add>
<add>class LVISWrapper(lvis.LVIS):
<add> """Wrapper for the lvis.LVIS class."""
<add>
<add> def __init__(self, dataset, detection_type='bbox'):
<add> """LVISWrapper constructor.
<add>
<add> See https://www.lvisdataset.org/dataset for a description of the format.
<add> By default, the coco.COCO class constructor reads from a JSON file.
<add> This function duplicates the same behavior but loads from a dictionary,
<add> allowing us to perform evaluation without writing to external storage.
<add>
<add> Args:
<add> dataset: a dictionary holding bounding box annotations in the COCO format.
<add> detection_type: type of detections being wrapped. Can be one of ['bbox',
<add> 'segmentation']
<add>
<add> Raises:
<add> ValueError: if detection_type is unsupported.
<add> """
<add> self.logger = logging.getLogger(__name__)
<add> self.logger.info('Loading annotations.')
<add> self.dataset = dataset
<add> self._create_index()
<add>
<add>
<add>class LVISEvalWrapper(lvis_eval.LVISEval):
<add> """LVISEval wrapper."""
<add>
<add> def __init__(self, groundtruth=None, detections=None, iou_type='bbox'):
<add> lvis_eval.LVISEval.__init__(
<add> self, groundtruth, detections, iou_type=iou_type)
<add> self._iou_type = iou_type
<add>
<add> def ComputeMetrics(self):
<add> self.run()
<add> summary_metrics = {}
<add> summary_metrics = self.results
<add> return summary_metrics
<add>
<add>
<add>def ExportSingleImageGroundtruthToLVIS(image_id,
<add> next_annotation_id,
<add> category_id_set,
<add> groundtruth_boxes,
<add> groundtruth_classes,
<add> groundtruth_masks=None,
<add> groundtruth_area=None):
<add> """Export groundtruth of a single image to LVIS format.
<add>
<add> This function converts groundtruth detection annotations represented as numpy
<add> arrays to dictionaries that can be ingested by the LVIS evaluation API. Note
<add> that the image_ids provided here must match the ones given to
<add> ExportSingleImageDetectionMasksToLVIS. We assume that boxes, classes and masks
<add> are in correspondence - that is, e.g., groundtruth_boxes[i, :], and
<add> groundtruth_classes[i] are associated with the same groundtruth annotation.
<add>
<add> In the exported result, "area" fields are always set to the area of the
<add> groundtruth bounding box.
<add>
<add> Args:
<add> image_id: a unique image identifier either of type integer or string.
<add> next_annotation_id: integer specifying the first id to use for the
<add> groundtruth annotations. All annotations are assigned a continuous integer
<add> id starting from this value.
<add> category_id_set: A set of valid class ids. Groundtruth with classes not in
<add> category_id_set are dropped.
<add> groundtruth_boxes: numpy array (float32) with shape [num_gt_boxes, 4]
<add> groundtruth_classes: numpy array (int) with shape [num_gt_boxes]
<add> groundtruth_masks: optional uint8 numpy array of shape [num_detections,
<add> image_height, image_width] containing detection_masks.
<add> groundtruth_area: numpy array (float32) with shape [num_gt_boxes]. If
<add> provided, then the area values (in the original absolute coordinates) will
<add> be populated instead of calculated from bounding box coordinates.
<add>
<add> Returns:
<add> a list of groundtruth annotations for a single image in the COCO format.
<add>
<add> Raises:
<add> ValueError: if (1) groundtruth_boxes and groundtruth_classes do not have the
<add> right lengths or (2) if each of the elements inside these lists do not
<add> have the correct shapes or (3) if image_ids are not integers
<add> """
<add>
<add> if len(groundtruth_classes.shape) != 1:
<add> raise ValueError('groundtruth_classes is '
<add> 'expected to be of rank 1.')
<add> if len(groundtruth_boxes.shape) != 2:
<add> raise ValueError('groundtruth_boxes is expected to be of '
<add> 'rank 2.')
<add> if groundtruth_boxes.shape[1] != 4:
<add> raise ValueError('groundtruth_boxes should have '
<add> 'shape[1] == 4.')
<add> num_boxes = groundtruth_classes.shape[0]
<add> if num_boxes != groundtruth_boxes.shape[0]:
<add> raise ValueError('Corresponding entries in groundtruth_classes, '
<add> 'and groundtruth_boxes should have '
<add> 'compatible shapes (i.e., agree on the 0th dimension).'
<add> 'Classes shape: %d. Boxes shape: %d. Image ID: %s' % (
<add> groundtruth_classes.shape[0],
<add> groundtruth_boxes.shape[0], image_id))
<add>
<add> groundtruth_list = []
<add> for i in range(num_boxes):
<add> if groundtruth_classes[i] in category_id_set:
<add> if groundtruth_area is not None and groundtruth_area[i] > 0:
<add> area = float(groundtruth_area[i])
<add> else:
<add> area = float((groundtruth_boxes[i, 2] - groundtruth_boxes[i, 0]) *
<add> (groundtruth_boxes[i, 3] - groundtruth_boxes[i, 1]))
<add> export_dict = {
<add> 'id':
<add> next_annotation_id + i,
<add> 'image_id':
<add> image_id,
<add> 'category_id':
<add> int(groundtruth_classes[i]),
<add> 'bbox':
<add> list(_ConvertBoxToCOCOFormat(groundtruth_boxes[i, :])),
<add> 'area': area,
<add> }
<add> if groundtruth_masks is not None:
<add> export_dict['segmentation'] = RleCompress(groundtruth_masks[i])
<add>
<add> groundtruth_list.append(export_dict)
<add> return groundtruth_list
<add>
<add>
<add>def ExportSingleImageDetectionMasksToLVIS(image_id,
<add> category_id_set,
<add> detection_masks,
<add> detection_scores,
<add> detection_classes):
<add> """Export detection masks of a single image to LVIS format.
<add>
<add> This function converts detections represented as numpy arrays to dictionaries
<add> that can be ingested by the LVIS evaluation API. We assume that
<add> detection_masks, detection_scores, and detection_classes are in correspondence
<add> - that is: detection_masks[i, :], detection_classes[i] and detection_scores[i]
<add> are associated with the same annotation.
<add>
<add> Args:
<add> image_id: unique image identifier either of type integer or string.
<add> category_id_set: A set of valid class ids. Detections with classes not in
<add> category_id_set are dropped.
<add> detection_masks: uint8 numpy array of shape [num_detections, image_height,
<add> image_width] containing detection_masks.
<add> detection_scores: float numpy array of shape [num_detections] containing
<add> scores for detection masks.
<add> detection_classes: integer numpy array of shape [num_detections] containing
<add> the classes for detection masks.
<add>
<add> Returns:
<add> a list of detection mask annotations for a single image in the COCO format.
<add>
<add> Raises:
<add> ValueError: if (1) detection_masks, detection_scores and detection_classes
<add> do not have the right lengths or (2) if each of the elements inside these
<add> lists do not have the correct shapes or (3) if image_ids are not integers.
<add> """
<add>
<add> if len(detection_classes.shape) != 1 or len(detection_scores.shape) != 1:
<add> raise ValueError('All entries in detection_classes and detection_scores'
<add> 'expected to be of rank 1.')
<add> num_boxes = detection_classes.shape[0]
<add> if not num_boxes == len(detection_masks) == detection_scores.shape[0]:
<add> raise ValueError('Corresponding entries in detection_classes, '
<add> 'detection_scores and detection_masks should have '
<add> 'compatible lengths and shapes '
<add> 'Classes length: %d. Masks length: %d. '
<add> 'Scores length: %d' % (
<add> detection_classes.shape[0], len(detection_masks),
<add> detection_scores.shape[0]
<add> ))
<add> detections_list = []
<add> for i in range(num_boxes):
<add> if detection_classes[i] in category_id_set:
<add> detections_list.append({
<add> 'image_id': image_id,
<add> 'category_id': int(detection_classes[i]),
<add> 'segmentation': RleCompress(detection_masks[i]),
<add> 'score': float(detection_scores[i])
<add> })
<add> return detections_list
<ide><path>research/object_detection/metrics/lvis_tools_test.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>"""Tests for tensorflow_model.object_detection.metrics.lvis_tools."""
<add>from lvis import results as lvis_results
<add>import numpy as np
<add>from pycocotools import mask
<add>import tensorflow.compat.v1 as tf
<add>from object_detection.metrics import lvis_tools
<add>
<add>
<add>class LVISToolsTest(tf.test.TestCase):
<add>
<add> def setUp(self):
<add> super(LVISToolsTest, self).setUp()
<add> mask1 = np.pad(
<add> np.ones([100, 100], dtype=np.uint8),
<add> ((100, 56), (100, 56)), mode='constant')
<add> mask2 = np.pad(
<add> np.ones([50, 50], dtype=np.uint8),
<add> ((50, 156), (50, 156)), mode='constant')
<add> mask1_rle = lvis_tools.RleCompress(mask1)
<add> mask2_rle = lvis_tools.RleCompress(mask2)
<add> groundtruth_annotations_list = [
<add> {
<add> 'id': 1,
<add> 'image_id': 'first',
<add> 'category_id': 1,
<add> 'bbox': [100., 100., 100., 100.],
<add> 'area': 100.**2,
<add> 'segmentation': mask1_rle
<add> },
<add> {
<add> 'id': 2,
<add> 'image_id': 'second',
<add> 'category_id': 1,
<add> 'bbox': [50., 50., 50., 50.],
<add> 'area': 50.**2,
<add> 'segmentation': mask2_rle
<add> },
<add> ]
<add> image_list = [
<add> {
<add> 'id': 'first',
<add> 'neg_category_ids': [],
<add> 'not_exhaustive_category_ids': [],
<add> 'height': 256,
<add> 'width': 256
<add> },
<add> {
<add> 'id': 'second',
<add> 'neg_category_ids': [],
<add> 'not_exhaustive_category_ids': [],
<add> 'height': 256,
<add> 'width': 256
<add> }
<add> ]
<add> category_list = [{'id': 0, 'name': 'person', 'frequency': 'f'},
<add> {'id': 1, 'name': 'cat', 'frequency': 'c'},
<add> {'id': 2, 'name': 'dog', 'frequency': 'r'}]
<add> self._groundtruth_dict = {
<add> 'annotations': groundtruth_annotations_list,
<add> 'images': image_list,
<add> 'categories': category_list
<add> }
<add>
<add> self._detections_list = [
<add> {
<add> 'image_id': 'first',
<add> 'category_id': 1,
<add> 'segmentation': mask1_rle,
<add> 'score': .8
<add> },
<add> {
<add> 'image_id': 'second',
<add> 'category_id': 1,
<add> 'segmentation': mask2_rle,
<add> 'score': .7
<add> },
<add> ]
<add>
<add> def testLVISWrappers(self):
<add> groundtruth = lvis_tools.LVISWrapper(self._groundtruth_dict)
<add> detections = lvis_results.LVISResults(groundtruth, self._detections_list)
<add> evaluator = lvis_tools.LVISEvalWrapper(groundtruth, detections,
<add> iou_type='segm')
<add> summary_metrics = evaluator.ComputeMetrics()
<add> self.assertAlmostEqual(1.0, summary_metrics['AP'])
<add>
<add> def testSingleImageDetectionMaskExport(self):
<add> masks = np.array(
<add> [[[1, 1,], [1, 1]],
<add> [[0, 0], [0, 1]],
<add> [[0, 0], [0, 0]]], dtype=np.uint8)
<add> classes = np.array([1, 2, 3], dtype=np.int32)
<add> scores = np.array([0.8, 0.2, 0.7], dtype=np.float32)
<add> lvis_annotations = lvis_tools.ExportSingleImageDetectionMasksToLVIS(
<add> image_id='first_image',
<add> category_id_set=set([1, 2, 3]),
<add> detection_classes=classes,
<add> detection_scores=scores,
<add> detection_masks=masks)
<add> expected_counts = ['04', '31', '4']
<add> for i, mask_annotation in enumerate(lvis_annotations):
<add> self.assertEqual(mask_annotation['segmentation']['counts'],
<add> expected_counts[i])
<add> self.assertTrue(np.all(np.equal(mask.decode(
<add> mask_annotation['segmentation']), masks[i])))
<add> self.assertEqual(mask_annotation['image_id'], 'first_image')
<add> self.assertEqual(mask_annotation['category_id'], classes[i])
<add> self.assertAlmostEqual(mask_annotation['score'], scores[i])
<add>
<add> def testSingleImageGroundtruthExport(self):
<add> masks = np.array(
<add> [[[1, 1,], [1, 1]],
<add> [[0, 0], [0, 1]],
<add> [[0, 0], [0, 0]]], dtype=np.uint8)
<add> boxes = np.array([[0, 0, 1, 1],
<add> [0, 0, .5, .5],
<add> [.5, .5, 1, 1]], dtype=np.float32)
<add> lvis_boxes = np.array([[0, 0, 1, 1],
<add> [0, 0, .5, .5],
<add> [.5, .5, .5, .5]], dtype=np.float32)
<add> classes = np.array([1, 2, 3], dtype=np.int32)
<add> next_annotation_id = 1
<add> expected_counts = ['04', '31', '4']
<add>
<add> lvis_annotations = lvis_tools.ExportSingleImageGroundtruthToLVIS(
<add> image_id='first_image',
<add> category_id_set=set([1, 2, 3]),
<add> next_annotation_id=next_annotation_id,
<add> groundtruth_boxes=boxes,
<add> groundtruth_classes=classes,
<add> groundtruth_masks=masks)
<add> for i, annotation in enumerate(lvis_annotations):
<add> self.assertEqual(annotation['segmentation']['counts'],
<add> expected_counts[i])
<add> self.assertTrue(np.all(np.equal(mask.decode(
<add> annotation['segmentation']), masks[i])))
<add> self.assertTrue(np.all(np.isclose(annotation['bbox'], lvis_boxes[i])))
<add> self.assertEqual(annotation['image_id'], 'first_image')
<add> self.assertEqual(annotation['category_id'], classes[i])
<add> self.assertEqual(annotation['id'], i + next_annotation_id)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
<ide><path>research/object_detection/packages/tf1/setup.py
<ide> from setuptools import setup
<ide>
<ide> REQUIRED_PACKAGES = ['pillow', 'lxml', 'matplotlib', 'Cython',
<del> 'contextlib2', 'tf-slim', 'six', 'pycocotools', 'scipy',
<del> 'pandas']
<add> 'contextlib2', 'tf-slim', 'six', 'pycocotools', 'lvis',
<add> 'scipy', 'pandas']
<ide>
<ide> setup(
<ide> name='object_detection',
<ide><path>research/object_detection/packages/tf2/setup.py
<ide> 'tf-slim',
<ide> 'six',
<ide> 'pycocotools',
<add> 'lvis',
<ide> 'scipy',
<ide> 'pandas',
<ide> 'tf-models-official' | 10 |
Ruby | Ruby | add tests for selecting aggregates | 05300be6351c988e9c30fa745ba645baec49de65 | <ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_group_by_attribute_with_custom_type
<ide> assert_equal({ "proposed" => 2, "published" => 2 }, Book.group(:status).count)
<ide> end
<ide>
<add> def test_select_avg_with_group_by_as_virtual_attribute_with_sql
<add> rails_core = companies(:rails_core)
<add>
<add> sql = <<~SQL
<add> SELECT firm_id, AVG(credit_limit) AS avg_credit_limit
<add> FROM accounts
<add> WHERE firm_id = ?
<add> GROUP BY firm_id
<add> LIMIT 1
<add> SQL
<add>
<add> account = Account.find_by_sql([sql, rails_core]).first
<add>
<add> # id was not selected, so it should be nil
<add> # (cannot select id because it wasn't used in the GROUP BY clause)
<add> assert_nil account.id
<add>
<add> # firm_id was explicitly selected, so it should be present
<add> assert_equal(rails_core, account.firm)
<add>
<add> # avg_credit_limit should be present as a virtual attribute
<add> assert_equal(52.5, account.avg_credit_limit)
<add> end
<add>
<add> def test_select_avg_with_group_by_as_virtual_attribute_with_ar
<add> rails_core = companies(:rails_core)
<add>
<add> account = Account
<add> .select(:firm_id, "AVG(credit_limit) AS avg_credit_limit")
<add> .where(firm: rails_core)
<add> .group(:firm_id)
<add> .take!
<add>
<add> # id was not selected, so it should be nil
<add> # (cannot select id because it wasn't used in the GROUP BY clause)
<add> assert_nil account.id
<add>
<add> # firm_id was explicitly selected, so it should be present
<add> assert_equal(rails_core, account.firm)
<add>
<add> # avg_credit_limit should be present as a virtual attribute
<add> assert_equal(52.5, account.avg_credit_limit)
<add> end
<add>
<add> def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_sql
<add> rails_core = companies(:rails_core)
<add>
<add> sql = <<~SQL
<add> SELECT companies.*, AVG(accounts.credit_limit) AS avg_credit_limit
<add> FROM companies
<add> INNER JOIN accounts ON companies.id = accounts.firm_id
<add> WHERE companies.id = ?
<add> GROUP BY companies.id
<add> LIMIT 1
<add> SQL
<add>
<add> firm = DependentFirm.find_by_sql([sql, rails_core]).first
<add>
<add> # all the DependentFirm attributes should be present
<add> assert_equal rails_core, firm
<add> assert_equal rails_core.name, firm.name
<add>
<add> # avg_credit_limit should be present as a virtual attribute
<add> assert_equal(52.5, firm.avg_credit_limit)
<add> end
<add>
<add> def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_ar
<add> rails_core = companies(:rails_core)
<add>
<add> firm = DependentFirm
<add> .select("companies.*", "AVG(accounts.credit_limit) AS avg_credit_limit")
<add> .where(id: rails_core)
<add> .joins(:account)
<add> .group(:id)
<add> .take!
<add>
<add> # all the DependentFirm attributes should be present
<add> assert_equal rails_core, firm
<add> assert_equal rails_core.name, firm.name
<add>
<add> # avg_credit_limit should be present as a virtual attribute
<add> assert_equal(52.5, firm.avg_credit_limit)
<add> end
<add>
<ide> def test_count_with_block_and_column_name_raises_an_error
<ide> assert_raises(ArgumentError) do
<ide> Account.count(:firm_id) { true } | 1 |
PHP | PHP | improve wording of variables | 20ad313598ad98b5a54a702169248e7f179efd89 | <ide><path>src/Command/RoutesCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $header[] = 'Defaults';
<ide> }
<ide>
<del> $routeCollection = Router::routes();
<add> $availableRoutes = Router::routes();
<ide> $output = $duplicateRoutesCounter = [];
<ide>
<del> foreach ($routeCollection as $route) {
<add> foreach ($availableRoutes as $route) {
<ide> $methods = $route->defaults['_method'] ?? '';
<ide>
<ide> $item = [
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide>
<ide> $duplicateRoutes = [];
<ide>
<del> // Check duplicate routes
<del> foreach ($routeCollection as $route) {
<add> foreach ($availableRoutes as $route) {
<ide> if ($duplicateRoutesCounter[$route->template] > 1) {
<ide> $methods = $route->defaults['_method'] ?? '';
<ide> | 1 |
Python | Python | use decimal (properly) everywhere | 1d054f95725e5bec7d4ba9d23717897ef80b7388 | <ide><path>rest_framework/tests/filterset.py
<ide> def test_get_filtered_fields_root_view(self):
<ide> self.assertEquals(response.data, self.data)
<ide>
<ide> # Tests that the decimal filter works.
<del> search_decimal = 2.25
<add> search_decimal = Decimal('2.25')
<ide> request = factory.get('/?decimal=%s' % search_decimal)
<ide> response = view(request).render()
<ide> self.assertEquals(response.status_code, status.HTTP_200_OK)
<ide> def test_get_filtered_class_root_view(self):
<ide> self.assertEquals(response.data, self.data)
<ide>
<ide> # Tests that the decimal filter set with 'lt' in the filter class works.
<del> search_decimal = 4.25
<add> search_decimal = Decimal('4.25')
<ide> request = factory.get('/?decimal=%s' % search_decimal)
<ide> response = view(request).render()
<ide> self.assertEquals(response.status_code, status.HTTP_200_OK)
<ide> def test_get_filtered_class_root_view(self):
<ide> self.assertEquals(response.data, expected_data)
<ide>
<ide> # Tests that multiple filters works.
<del> search_decimal = 5.25
<add> search_decimal = Decimal('5.25')
<ide> search_date = datetime.date(2012, 10, 2)
<ide> request = factory.get('/?decimal=%s&date=%s' % (search_decimal, search_date))
<ide> response = view(request).render()
<ide><path>rest_framework/tests/pagination.py
<ide> def setUp(self):
<ide> """
<ide> Create 50 FilterableItem instances.
<ide> """
<del> base_data = ('a', Decimal(0.25), datetime.date(2012, 10, 8))
<add> base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
<ide> for i in range(26):
<ide> text = chr(i + ord(base_data[0])) * 3 # Produces string 'aaa', 'bbb', etc.
<ide> decimal = base_data[1] + i | 2 |
Ruby | Ruby | reset callbacks after test | 5faf77fe7abffed40e3a4110cf33f83c99e90ce4 | <ide><path>actionpack/test/dispatch/reloader_test.rb
<ide> class ReloaderTest < ActiveSupport::TestCase
<ide> Reloader = ActionDispatch::Reloader
<ide>
<add> teardown do
<add> Reloader.reset_callbacks :prepare
<add> Reloader.reset_callbacks :cleanup
<add> end
<add>
<ide> def test_prepare_callbacks
<ide> a = b = c = nil
<ide> Reloader.to_prepare { |*args| a = b = c = 1 } | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.