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 signoff for linuxbrew-core | f01f3a9f5677e896b6b7a921ba491323efe5a23b | <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb
<ide> def signoff!(path, pr: nil, dry_run: false)
<ide> if pr
<ide> # This is a tap pull request and approving reviewers should also sign-off.
<ide> tap = Tap.from_path(path)
<del> trailers += GitHub.approved_reviews(tap.user, "homebrew-#{tap.repo}", pr).map do |r|
<add> trailers += GitHub.approved_reviews(tap.user, tap.full_name.split("/").last, pr).map do |r|
<ide> "Signed-off-by: #{r["name"]} <#{r["email"]}>"
<ide> end.join("\n")
<ide> | 1 |
Python | Python | fix import errors | 8845c0be88bf68fa0e42d05c7196cd52d897623b | <ide><path>rest_framework/compat.py
<ide> def apply_markdown(text):
<ide> # OAuth 2 support is optional
<ide> try:
<ide> import provider.oauth2 as oauth2_provider
<add>
<add> # Hack to fix submodule import issues
<add> submodules = ['backends', 'forms','managers','models','urls','views']
<add> for s in submodules:
<add> mod = __import__('provider.oauth2.%s.*' % s)
<add> setattr(oauth2_provider, s, mod)
<add>
<ide> except ImportError:
<ide> oauth2_provider = None
<ide><path>rest_framework/runtests/settings.py
<ide> 'provider',
<ide> 'provider.oauth2',
<ide> )
<del>except ImportError, inst:
<add>except ImportError:
<ide> import logging
<ide> logging.warning("django-oauth2-provider is not install, some tests will be skipped")
<ide>
<ide><path>rest_framework/tests/authentication.py
<ide> def put(self, request):
<ide> (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
<ide> (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
<ide> (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
<del> url(r'^oauth2/', include('provider.oauth2.urls', namespace = 'oauth2')),
<del> url(r'^oauth2-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication])),
<ide> )
<ide>
<add>if oauth2_provider is not None:
<add> urlpatterns += patterns('',
<add> url(r'^oauth2/', include('provider.oauth2.urls', namespace = 'oauth2')),
<add> url(r'^oauth2-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication])),
<add> )
<add>
<ide>
<ide> class BasicAuthTests(TestCase):
<ide> """Basic authentication""" | 3 |
Javascript | Javascript | replace the `xref.cache` array with a map instead | 1cd9a28c8126e8461b7fe8c8a253d6d7ee328236 | <ide><path>src/core/obj.js
<ide> var XRef = (function XRefClosure() {
<ide> this.pdfManager = pdfManager;
<ide> this.entries = [];
<ide> this.xrefstms = Object.create(null);
<del> // prepare the XRef cache
<del> this.cache = [];
<add> this._cacheMap = new Map(); // Prepare the XRef cache.
<ide> this.stats = {
<ide> streamTypes: Object.create(null),
<ide> fontTypes: Object.create(null),
<ide> var XRef = (function XRefClosure() {
<ide> if (!(ref instanceof Ref)) {
<ide> throw new Error('ref object is not a reference');
<ide> }
<del> var num = ref.num;
<del> if (num in this.cache) {
<del> var cacheEntry = this.cache[num];
<add> const num = ref.num;
<add>
<add> if (this._cacheMap.has(num)) {
<add> const cacheEntry = this._cacheMap.get(num);
<ide> // In documents with Object Streams, it's possible that cached `Dict`s
<ide> // have not been assigned an `objId` yet (see e.g. issue3115r.pdf).
<ide> if (cacheEntry instanceof Dict && !cacheEntry.objId) {
<ide> cacheEntry.objId = ref.toString();
<ide> }
<ide> return cacheEntry;
<ide> }
<add> let xrefEntry = this.getEntry(num);
<ide>
<del> var xrefEntry = this.getEntry(num);
<del>
<del> // the referenced entry can be free
<del> if (xrefEntry === null) {
<del> return (this.cache[num] = null);
<add> if (xrefEntry === null) { // The referenced entry can be free.
<add> this._cacheMap.set(num, xrefEntry);
<add> return xrefEntry;
<ide> }
<ide>
<ide> if (xrefEntry.uncompressed) {
<ide> var XRef = (function XRefClosure() {
<ide> xrefEntry = parser.getObj();
<ide> }
<ide> if (!isStream(xrefEntry)) {
<del> this.cache[num] = xrefEntry;
<add> this._cacheMap.set(num, xrefEntry);
<ide> }
<ide> return xrefEntry;
<ide> },
<ide> var XRef = (function XRefClosure() {
<ide> num = nums[i];
<ide> var entry = this.entries[num];
<ide> if (entry && entry.offset === tableOffset && entry.gen === i) {
<del> this.cache[num] = entries[i];
<add> this._cacheMap.set(num, entries[i]);
<ide> }
<ide> }
<ide> xrefEntry = entries[xrefEntry.gen]; | 1 |
Javascript | Javascript | insert description into editor | 1ee5e24d0f310bc68234589108b3720c977c4605 | <ide><path>client/src/templates/Challenges/classic/Editor.js
<ide> import isEqual from 'lodash/isEqual';
<ide>
<ide> import {
<ide> canFocusEditorSelector,
<add> consoleOutputSelector,
<ide> executeChallenge,
<ide> inAccessibilityModeSelector,
<ide> saveEditorContent,
<ide> const propTypes = {
<ide> challengeFiles: PropTypes.object,
<ide> containerRef: PropTypes.any.isRequired,
<ide> contents: PropTypes.string,
<add> description: PropTypes.string,
<ide> dimensions: PropTypes.object,
<ide> executeChallenge: PropTypes.func.isRequired,
<ide> ext: PropTypes.string,
<ide> fileKey: PropTypes.string,
<ide> inAccessibilityMode: PropTypes.bool.isRequired,
<ide> initialEditorContent: PropTypes.string,
<ide> initialExt: PropTypes.string,
<add> output: PropTypes.string,
<ide> saveEditorContent: PropTypes.func.isRequired,
<ide> setAccessibilityMode: PropTypes.func.isRequired,
<ide> setEditorFocusability: PropTypes.func,
<ide> const propTypes = {
<ide>
<ide> const mapStateToProps = createSelector(
<ide> canFocusEditorSelector,
<add> consoleOutputSelector,
<ide> inAccessibilityModeSelector,
<ide> isDonationModalOpenSelector,
<ide> userSelector,
<del> (canFocus, accessibilityMode, open, { theme = 'default' }) => ({
<add> (canFocus, output, accessibilityMode, open, { theme = 'default' }) => ({
<ide> canFocus: open ? false : canFocus,
<add> output,
<ide> inAccessibilityMode: accessibilityMode,
<ide> theme
<ide> })
<ide> class Editor extends Component {
<ide> this.data = {
<ide> indexjs: {
<ide> model: null,
<del> state: null
<add> state: null,
<add> viewZoneId: null,
<add> decId: null,
<add> viewZoneHeight: null
<ide> },
<ide> indexcss: {
<ide> model: null,
<del> state: null
<add> state: null,
<add> viewZoneId: null,
<add> decId: null,
<add> viewZoneHeight: null
<ide> },
<ide> indexhtml: {
<ide> model: null,
<del> state: null
<add> state: null,
<add> viewZoneId: null,
<add> decId: null,
<add> viewZoneHeight: null
<ide> },
<ide> indexjsx: {
<ide> model: null,
<del> state: null
<add> state: null,
<add> viewZoneId: null,
<add> decId: null,
<add> viewZoneHeight: null
<ide> }
<ide> };
<ide>
<ide> class Editor extends Component {
<ide> const editableRegion = [...challengeFiles[key].editableRegionBoundaries];
<ide>
<ide> if (editableRegion.length === 2)
<del> this.decorateForbiddenRanges(model, editableRegion);
<add> this.decorateForbiddenRanges(key, editableRegion);
<ide> });
<ide> return { model: this.data[this.state.fileKey].model };
<ide> };
<ide> class Editor extends Component {
<ide> const editableBoundaries = [
<ide> ...challengeFiles[fileKey].editableRegionBoundaries
<ide> ];
<del> this.showEditableRegion(editableBoundaries);
<add>
<add> if (editableBoundaries.length === 2) {
<add> this.showEditableRegion(editableBoundaries);
<add>
<add> // TODO: is there a nicer approach/way of organising everything that
<add> // avoids the binds? babel-plugin-transform-class-properties ?
<add> const getViewZoneTop = this.getViewZoneTop.bind(this);
<add> const createDescription = this.createDescription.bind(this);
<add> const getOutputZoneTop = this.getOutputZoneTop.bind(this);
<add> const createOutputNode = this.createOutputNode.bind(this);
<add>
<add> // TODO: take care that there's no race/ordering problems, with the
<add> // placement of domNode (shouldn't be once it's no longer used in the
<add> // view zone, but make sure!)
<add> this._overlayWidget = {
<add> domNode: null,
<add> getId: function() {
<add> return 'my.overlay.widget';
<add> },
<add> getDomNode: function() {
<add> if (!this.domNode) {
<add> this.domNode = createDescription();
<add>
<add> // make sure it's hidden from screenreaders.
<add> this.domNode.setAttribute('aria-hidden', true);
<add>
<add> this.domNode.style.background = 'yellow';
<add> this.domNode.style.left = editor.getLayoutInfo().contentLeft + 'px';
<add> this.domNode.style.width =
<add> editor.getLayoutInfo().contentWidth + 'px';
<add> this.domNode.style.top = getViewZoneTop();
<add> }
<add> return this.domNode;
<add> },
<add> getPosition: function() {
<add> if (this.domNode) {
<add> this.domNode.style.width =
<add> editor.getLayoutInfo().contentWidth + 'px';
<add> this.domNode.style.top = getViewZoneTop();
<add> }
<add> return null;
<add> }
<add> };
<add>
<add> this._editor.addOverlayWidget(this._overlayWidget);
<add>
<add> // TODO: create this and overlayWidget from the same factory.
<add> this._outputWidget = {
<add> domNode: null,
<add> getId: function() {
<add> return 'my.output.widget';
<add> },
<add> getDomNode: function() {
<add> if (!this.domNode) {
<add> this.domNode = createOutputNode();
<add>
<add> // make sure it's hidden from screenreaders.
<add> this.domNode.setAttribute('aria-hidden', true);
<add>
<add> this.domNode.style.background = 'red';
<add> this.domNode.style.left = editor.getLayoutInfo().contentLeft + 'px';
<add> this.domNode.style.width =
<add> editor.getLayoutInfo().contentWidth + 'px';
<add> this.domNode.style.top = getOutputZoneTop();
<add> }
<add> return this.domNode;
<add> },
<add> getPosition: function() {
<add> if (this.domNode) {
<add> this.domNode.style.width =
<add> editor.getLayoutInfo().contentWidth + 'px';
<add> this.domNode.style.top = getOutputZoneTop();
<add> }
<add> return null;
<add> }
<add> };
<add>
<add> this._editor.addOverlayWidget(this._overlayWidget);
<add> this._editor.addOverlayWidget(this._outputWidget);
<add> // TODO: if we keep using a single editor and switching content (rather
<add> // than having multiple open editors), this view zone needs to be
<add> // preserved when the tab changes.
<add>
<add> editor.changeViewZones(this.viewZoneCallback);
<add> editor.changeViewZones(this.outputZoneCallback);
<add>
<add> editor.onDidScrollChange(() => {
<add> editor.layoutOverlayWidget(this._overlayWidget);
<add> editor.layoutOverlayWidget(this._outputWidget);
<add> });
<add> }
<ide> };
<ide>
<add> viewZoneCallback = changeAccessor => {
<add> const { fileKey } = this.state;
<add> // TODO: is there any point creating this here? I know it's cached, but
<add> // would it not be better just sourced from the overlayWidget?
<add> const domNode = this.createDescription();
<add>
<add> // make sure the overlayWidget has resized before using it to set the height
<add> domNode.style.width = this._editor.getLayoutInfo().contentWidth + 'px';
<add> domNode.style.top = this.getViewZoneTop();
<add>
<add> // TODO: set via onComputedHeight?
<add> this.data[fileKey].viewZoneHeight = domNode.offsetHeight;
<add>
<add> var background = document.createElement('div');
<add> background.style.background = 'lightgreen';
<add>
<add> // We have to wait for the viewZone to finish rendering before adjusting the
<add> // position of the overlayWidget (i.e. trigger it via onComputedHeight). If
<add> // not the editor may report the wrong value for position of the lines.
<add> const viewZone = {
<add> afterLineNumber: this.getLineAfterViewZone() - 1,
<add> heightInPx: domNode.offsetHeight,
<add> domNode: background,
<add> onComputedHeight: () =>
<add> this._editor.layoutOverlayWidget(this._overlayWidget)
<add> };
<add>
<add> this.data[fileKey].viewZoneId = changeAccessor.addZone(viewZone);
<add> };
<add>
<add> // TODO: this is basically the same as viewZoneCallback, so DRY them out.
<add> outputZoneCallback = changeAccessor => {
<add> const { fileKey } = this.state;
<add> // TODO: is there any point creating this here? I know it's cached, but
<add> // would it not be better just sourced from the overlayWidget?
<add> const outputNode = this.createOutputNode();
<add>
<add> // make sure the overlayWidget has resized before using it to set the height
<add> outputNode.style.width = this._editor.getLayoutInfo().contentWidth + 'px';
<add> outputNode.style.top = this.getOutputZoneTop();
<add>
<add> // TODO: set via onComputedHeight?
<add> this.data[fileKey].outputZoneHeight = outputNode.offsetHeight;
<add>
<add> var background = document.createElement('div');
<add> background.style.background = 'lightpink';
<add>
<add> // We have to wait for the viewZone to finish rendering before adjusting the
<add> // position of the overlayWidget (i.e. trigger it via onComputedHeight). If
<add> // not the editor may report the wrong value for position of the lines.
<add> const viewZone = {
<add> afterLineNumber: this.getLineAfterEditableRegion() - 1,
<add> heightInPx: outputNode.offsetHeight,
<add> domNode: background,
<add> onComputedHeight: () =>
<add> this._editor.layoutOverlayWidget(this._outputWidget)
<add> };
<add>
<add> this.data[fileKey].outputZoneId = changeAccessor.addZone(viewZone);
<add> };
<add>
<add> createDescription() {
<add> if (this._domNode) return this._domNode;
<add> const { description } = this.props;
<add> var domNode = document.createElement('div');
<add> var desc = document.createElement('div');
<add> var button = document.createElement('button');
<add> button.innerHTML = 'Run the Tests (Ctrl + Enter)';
<add> button.onclick = () => {
<add> const { executeChallenge } = this.props;
<add> executeChallenge();
<add> };
<add>
<add> domNode.appendChild(desc);
<add> domNode.appendChild(button);
<add> desc.innerHTML = description;
<add>
<add> desc.style.background = 'white';
<add> domNode.style.background = 'lightgreen';
<add> // TODO: the solution is probably just to use an overlay that's forced to
<add> // follow the decorations.
<add> // TODO: this is enough for Firefox, but Chrome needs more before the
<add> // user can select text by clicking and dragging.
<add> domNode.style.userSelect = 'text';
<add> // The z-index needs increasing as ViewZones default to below the lines.
<add> domNode.style.zIndex = '10';
<add>
<add> this._domNode = domNode;
<add>
<add> return domNode;
<add> }
<add>
<add> createOutputNode() {
<add> if (this._outputNode) return this._outputNode;
<add> const outputNode = document.createElement('div');
<add>
<add> outputNode.innerHTML = 'TESTS GO HERE';
<add>
<add> outputNode.style.background = 'lightblue';
<add>
<add> // The z-index needs increasing as ViewZones default to below the lines.
<add> outputNode.style.zIndex = '10';
<add>
<add> this._outputNode = outputNode;
<add>
<add> return outputNode;
<add> }
<add>
<ide> focusOnHotkeys() {
<ide> if (this.props.containerRef.current) {
<ide> this.props.containerRef.current.focus();
<ide> class Editor extends Component {
<ide>
<ide> onChange = editorValue => {
<ide> const { updateFile } = this.props;
<add> // TODO: widgets can go
<add> const widget = this.data[this.state.fileKey].widget;
<add> if (widget) {
<add> this._editor.layoutContentWidget(widget);
<add> }
<ide> updateFile({ key: this.state.fileKey, editorValue });
<ide> };
<ide>
<ide> class Editor extends Component {
<ide> };
<ide>
<ide> showEditableRegion(editableBoundaries) {
<add> if (editableBoundaries.length !== 2) return;
<ide> // this is a heuristic: if the cursor is at the start of the page, chances
<ide> // are the user has not edited yet. If so, move to the start of the editable
<ide> // region.
<ide> class Editor extends Component {
<ide> return target.deltaDecorations([], lineDecoration.concat(inlineDecoration));
<ide> }
<ide>
<del> decorateForbiddenRanges(model, editableRegion) {
<add> // NOTE: this is where the view zone *should* be, not necessarily were it
<add> // currently is. (see getLineAfterViewZone)
<add> // TODO: DRY this and getOutputZoneTop out.
<add> getViewZoneTop() {
<add> const heightDelta = this.data[this.state.fileKey].viewZoneHeight || 0;
<add>
<add> const top =
<add> this._editor.getTopForLineNumber(this.getLineAfterViewZone()) -
<add> heightDelta -
<add> this._editor.getScrollTop() +
<add> 'px';
<add>
<add> return top;
<add> }
<add>
<add> getOutputZoneTop() {
<add> const heightDelta = this.data[this.state.fileKey].outputZoneHeight || 0;
<add>
<add> const top =
<add> this._editor.getTopForLineNumber(this.getLineAfterEditableRegion()) -
<add> heightDelta -
<add> this._editor.getScrollTop() +
<add> 'px';
<add>
<add> return top;
<add> }
<add>
<add> // It's not possible to directly access the current view zone so we track
<add> // the region it should cover instead.
<add> // TODO: DRY
<add> getLineAfterViewZone() {
<add> const { fileKey } = this.state;
<add> return (
<add> this.data[fileKey].model.getDecorationRange(this.data[fileKey].decId)
<add> .endLineNumber + 1
<add> );
<add> }
<add>
<add> getLineAfterEditableRegion() {
<add> const { fileKey } = this.state;
<add> return this.data[fileKey].model.getDecorationRange(
<add> this.data[fileKey].endEditDecId
<add> ).startLineNumber;
<add> }
<add>
<add> decorateForbiddenRanges(key, editableRegion) {
<add> const model = this.data[key].model;
<ide> const forbiddenRanges = [
<ide> [1, editableRegion[0]],
<ide> [editableRegion[1], model.getLineCount()]
<ide> class Editor extends Component {
<ide> ranges
<ide> );
<ide>
<add> // TODO: avoid getting from array
<add> this.data[key].decId = decIds[0];
<add> this.data[key].endEditDecId = decIds[1];
<add>
<ide> // TODO refactor this mess
<ide> // TODO this listener needs to be replaced on reset.
<ide> model.onDidChangeContent(e => {
<ide> class Editor extends Component {
<ide> }
<ide>
<ide> componentDidUpdate(prevProps) {
<add> // TODO: re-organise into something less nested
<add> const { fileKey } = this.state;
<ide> // If a challenge is reset, it needs to communicate that change to the
<ide> // editor. This looks for changes any challenge files and updates if needed.
<ide> if (this.props.challengeFiles !== prevProps.challengeFiles) {
<ide> this.updateEditorValues();
<ide> }
<ide>
<del> if (this.props.dimensions !== prevProps.dimensions && this._editor) {
<del> this._editor.layout();
<add> if (this._editor) {
<add> if (this.props.output !== prevProps.output && this._outputNode) {
<add> // TODO: output gets wiped when the preview gets updated, keeping the
<add> // display is an anti-pattern (the render should not ignore props!).
<add> // The correct solution is probably to create a new redux variable
<add> // (shownHint,maybe) and have that persist through previews. But, for
<add> // now:
<add> if (this.props.output) {
<add> this._outputNode.innerHTML = this.props.output;
<add> if (this.data[fileKey].decId) {
<add> this.updateOutputZone();
<add> }
<add> }
<add> }
<add>
<add> if (this.props.dimensions !== prevProps.dimensions) {
<add> // Order matters here. The view zones need to know the new editor
<add> // dimensions in order to render correctly.
<add> this._editor.layout();
<add> if (this.data[fileKey].decId) {
<add> console.log('data', this.data[fileKey]);
<add> this.updateViewZone();
<add> this.updateOutputZone();
<add> }
<add> }
<ide> }
<ide> }
<ide>
<add> // TODO: DRY (there's going to be a lot of that)
<add> updateOutputZone() {
<add> this._editor.changeViewZones(changeAccessor => {
<add> changeAccessor.removeZone(this.data[this.state.fileKey].outputZoneId);
<add> this.outputZoneCallback(changeAccessor);
<add> });
<add> }
<add>
<add> updateViewZone() {
<add> this._editor.changeViewZones(changeAccessor => {
<add> changeAccessor.removeZone(this.data[this.state.fileKey].viewZoneId);
<add> this.viewZoneCallback(changeAccessor);
<add> });
<add> }
<add>
<ide> componentWillUnmount() {
<ide> this.setState({ fileKey: null });
<ide> this.data = null;
<ide> class Editor extends Component {
<ide>
<ide> // TODO: tabs should be dynamically created from the challengeFiles
<ide> // TODO: is the key necessary? Try switching themes without it.
<add> // TODO: the tabs mess up the rendering (scroll doesn't work properly and
<add> // the in-editor description)
<ide> return (
<ide> <Suspense fallback={<Loader timeout={600} />}>
<ide> <span className='notranslate'>
<ide><path>client/src/templates/Challenges/classic/Show.js
<ide> class ShowClassic extends Component {
<ide>
<ide> renderEditor() {
<ide> const { files } = this.props;
<del>
<add> const { description } = this.getChallenge();
<ide> return (
<ide> files && (
<ide> <Editor
<ide> challengeFiles={files}
<ide> containerRef={this.containerRef}
<add> description={description}
<ide> ref={this.editorRef}
<ide> />
<ide> ) | 2 |
Javascript | Javascript | return boolean from child.send() | cf0130dc0df788bece8f905f7d295e15c0f523cc | <ide><path>lib/internal/child_process.js
<ide> function setupChannel(target, channel) {
<ide> handle: handle,
<ide> message: message.msg,
<ide> });
<del> return;
<add> return this._handleQueue.length === 1;
<ide> }
<ide>
<ide> var obj = handleConversion[message.type];
<ide><path>test/parallel/test-child-process-send-returns-boolean.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> const assert = require('assert');
<add>const path = require('path');
<add>const net = require('net');
<ide> const fork = require('child_process').fork;
<add>const spawn = require('child_process').spawn;
<ide>
<del>const n = fork(common.fixturesDir + '/empty.js');
<add>const emptyFile = path.join(common.fixturesDir, 'empty.js');
<add>
<add>const n = fork(emptyFile);
<ide>
<ide> const rv = n.send({ hello: 'world' });
<ide> assert.strictEqual(rv, true);
<add>
<add>const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] };
<add>const s = spawn(process.execPath, [emptyFile], spawnOptions);
<add>var handle = null;
<add>s.on('exit', function() {
<add> handle.close();
<add>});
<add>
<add>net.createServer(common.fail).listen(common.PORT, function() {
<add> handle = this._handle;
<add> assert.strictEqual(s.send('one', handle), true);
<add> assert.strictEqual(s.send('two', handle), true);
<add> assert.strictEqual(s.send('three'), false);
<add> assert.strictEqual(s.send('four'), false);
<add>}); | 2 |
Ruby | Ruby | move changed_attributes into dirty.rb | 8cbd500035aa64a5440d5ccc44209cfd902118fc | <ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> def reload(*)
<ide> end
<ide> end
<ide>
<add> def initialize_dup(other) # :nodoc:
<add> super
<add> init_changed_attributes
<add> end
<add>
<ide> private
<add> def initialize_internals_callback
<add> super
<add> init_changed_attributes
<add> end
<add>
<add> def init_changed_attributes
<add> @changed_attributes = nil
<add> # Intentionally avoid using #column_defaults since overridden defaults (as is done in
<add> # optimistic locking) won't get written unless they get marked as changed
<add> self.class.columns.each do |c|
<add> attr, orig_value = c.name, c.default
<add> changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
<add> end
<add> end
<add>
<ide> # Wrap write_attribute to remember original attribute value.
<ide> def write_attribute(attr, value)
<ide> attr = attr.to_s
<ide> def create_record(*)
<ide> # Serialized attributes should always be written in case they've been
<ide> # changed in place.
<ide> def keys_for_partial_write
<del> changed | (attributes.keys & self.class.serialized_attributes.keys)
<add> changed
<ide> end
<ide>
<ide> def _field_changed?(attr, old, value)
<ide><path>activerecord/lib/active_record/attribute_methods/serialization.rb
<ide> def initialize_attributes(attributes, options = {})
<ide> end
<ide> end
<ide>
<add> def should_record_timestamps?
<add> super || (self.record_timestamps && (attributes.keys & self.class.serialized_attributes.keys).present?)
<add> end
<add>
<add> def keys_for_partial_write
<add> super | (attributes.keys & self.class.serialized_attributes.keys)
<add> end
<add>
<ide> def type_cast_attribute_for_write(column, value)
<ide> if column && coder = self.class.serialized_attributes[column.name]
<ide> Attribute.new(coder, value, :unserialized)
<ide><path>activerecord/lib/active_record/core.rb
<ide> def initialize(attributes = nil, options = {})
<ide> @column_types = self.class.column_types
<ide>
<ide> init_internals
<del> init_changed_attributes
<del> ensure_proper_type
<del> populate_with_current_scope_attributes
<add> initialize_internals_callback
<ide>
<ide> # +options+ argument is only needed to make protected_attributes gem easier to hook.
<ide> # Remove it when we drop support to this gem.
<ide> def initialize_dup(other) # :nodoc:
<ide>
<ide> run_callbacks(:initialize) unless _initialize_callbacks.empty?
<ide>
<del> @changed_attributes = {}
<del> init_changed_attributes
<del>
<ide> @aggregation_cache = {}
<ide> @association_cache = {}
<ide> @attributes_cache = {}
<ide>
<ide> @new_record = true
<ide>
<del> ensure_proper_type
<ide> super
<ide> end
<ide>
<ide> def init_internals
<ide> @reflects_state = [false]
<ide> end
<ide>
<del> def init_changed_attributes
<del> # Intentionally avoid using #column_defaults since overridden defaults (as is done in
<del> # optimistic locking) won't get written unless they get marked as changed
<del> self.class.columns.each do |c|
<del> attr, orig_value = c.name, c.default
<del> changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
<del> end
<add> def initialize_internals_callback
<ide> end
<ide>
<ide> # This method is needed to make protected_attributes gem easier to hook.
<ide><path>activerecord/lib/active_record/inheritance.rb
<ide> def subclass_from_attributes(attrs)
<ide> end
<ide> end
<ide>
<add> def initialize_dup(other)
<add> super
<add> ensure_proper_type
<add> end
<add>
<ide> private
<ide>
<add> def initialize_internals_callback
<add> super
<add> ensure_proper_type
<add> end
<add>
<ide> # Sets the attribute used for single table inheritance to this class name if this is not the
<ide> # ActiveRecord::Base descendant.
<ide> # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
<ide><path>activerecord/lib/active_record/scoping.rb
<ide> def populate_with_current_scope_attributes
<ide> end
<ide> end
<ide>
<add> def initialize_internals_callback
<add> super
<add> populate_with_current_scope_attributes
<add> end
<add>
<ide> # This class stores the +:current_scope+ and +:ignore_default_scope+ values
<ide> # for different classes. The registry is stored as a thread local, which is
<ide> # accessed through +ScopeRegistry.current+.
<ide><path>activerecord/lib/active_record/timestamp.rb
<ide> def update_record(*args)
<ide> end
<ide>
<ide> def should_record_timestamps?
<del> self.record_timestamps && (!partial_writes? || changed? || (attributes.keys & self.class.serialized_attributes.keys).present?)
<add> self.record_timestamps && (!partial_writes? || changed?)
<ide> end
<ide>
<ide> def timestamp_attributes_for_create_in_model | 6 |
Ruby | Ruby | fix existing rule for github.io homepages | 64448834a68ee1e183e5c2bf9504dadfa9431dc1 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_homepage
<ide> # exemptions as they are discovered. Treat mixed content on homepages as a bug.
<ide> # Justify each exemptions with a code comment so we can keep track here.
<ide> case homepage
<del> when %r{^http://[^/]*github\.io/},
<add> when %r{^http://[^/]*\.github\.io/},
<ide> %r{^http://[^/]*\.sourceforge\.io/}
<ide> problem "Please use https:// for #{homepage}"
<ide> end | 1 |
Javascript | Javascript | add items in the correct order | e387680c43945e3c755a3d728f659a678d9d99b1 | <ide><path>examples/todomvc/src/reducers/todos.js
<ide> export default function todos(state = initialState, action) {
<ide> switch (action.type) {
<ide> case ADD_TODO:
<ide> return [
<add> ...state,
<ide> {
<ide> id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
<ide> completed: false,
<ide> text: action.text
<del> },
<del> ...state
<add> }
<ide> ]
<ide>
<ide> case DELETE_TODO:
<ide><path>examples/todomvc/src/reducers/todos.spec.js
<ide> describe('todos reducer', () => {
<ide> })
<ide> ).toEqual([
<ide> {
<del> text: 'Run the tests',
<del> completed: false,
<del> id: 1
<del> }, {
<ide> text: 'Use Redux',
<ide> completed: false,
<ide> id: 0
<add> },
<add> {
<add> text: 'Run the tests',
<add> completed: false,
<add> id: 1
<ide> }
<ide> ])
<ide>
<ide> expect(
<ide> todos([
<ide> {
<del> text: 'Run the tests',
<del> completed: false,
<del> id: 1
<del> }, {
<ide> text: 'Use Redux',
<ide> completed: false,
<ide> id: 0
<add> }, {
<add> text: 'Run the tests',
<add> completed: false,
<add> id: 1
<ide> }
<ide> ], {
<ide> type: types.ADD_TODO,
<ide> text: 'Fix the tests'
<ide> })
<ide> ).toEqual([
<ide> {
<del> text: 'Fix the tests',
<add> text: 'Use Redux',
<ide> completed: false,
<del> id: 2
<del> }, {
<add> id: 0
<add> },
<add> {
<ide> text: 'Run the tests',
<ide> completed: false,
<ide> id: 1
<del> }, {
<del> text: 'Use Redux',
<add> },
<add> {
<add> text: 'Fix the tests',
<ide> completed: false,
<del> id: 0
<add> id: 2
<ide> }
<ide> ])
<ide> })
<ide> describe('todos reducer', () => {
<ide> expect(
<ide> todos([
<ide> {
<del> text: 'Run the tests',
<del> completed: false,
<del> id: 1
<del> }, {
<ide> text: 'Use Redux',
<ide> completed: false,
<ide> id: 0
<add> },
<add> {
<add> text: 'Run the tests',
<add> completed: false,
<add> id: 1
<ide> }
<ide> ], {
<ide> type: types.DELETE_TODO,
<ide> describe('todos reducer', () => {
<ide> ])
<ide> ).toEqual([
<ide> {
<del> text: 'Write more tests',
<del> completed: false,
<del> id: 2
<del> }, {
<ide> text: 'Write tests',
<ide> completed: false,
<ide> id: 1
<add> }, {
<add> text: 'Write more tests',
<add> completed: false,
<add> id: 2
<ide> }
<ide> ])
<ide> }) | 2 |
Mixed | Javascript | move wpt to its own testing module | ff001c12b032c33dd54c6bcbb0bdba4fe549ec27 | <ide><path>benchmark/http/http_server_for_chunky_client.js
<ide> var http = require('http');
<ide> var fs = require('fs');
<ide> var fork = require('child_process').fork;
<ide> var common = require('../common.js');
<del>var test = require('../../test/common.js');
<add>var test = require('../../test/common');
<ide> var pep = `${path.dirname(process.argv[1])}/_chunky_http_client.js`;
<ide> var PIPE = test.PIPE;
<ide>
<ide><path>test/README.md
<ide> # Node.js Core Tests
<ide>
<del>This folder contains code and data used to test the Node.js implementation.
<add>This directory contains code and data used to test the Node.js implementation.
<ide>
<ide> For a detailed guide on how to write tests in this
<ide> directory, see [the guide on writing tests](../doc/guides/writing-tests.md).
<ide>
<ide> On how to run tests in this direcotry, see
<ide> [the contributing guide](../CONTRIBUTING.md#step-5-test).
<ide>
<del>## Table of Contents
<del>
<del>* [Test directories](#test-directories)
<del>* [Common module API](#common-module-api)
<del>
<ide> ## Test Directories
<ide>
<ide> <table>
<ide> On how to run tests in this direcotry, see
<ide> C++ test that is run as part of the build process.
<ide> </td>
<ide> </tr>
<add> <tr>
<add> <td>common</td>
<add> <td></td>
<add> <td>
<add> Common modules shared among many tests.
<add> <a href="./common/README.md">[Documentation]</a>
<add> </td>
<add> </tr>
<ide> <tr>
<ide> <td>debugger</td>
<ide> <td>No</td>
<ide> On how to run tests in this direcotry, see
<ide> </tr>
<ide> </tbody>
<ide> </table>
<del>
<del>## Common module API
<del>
<del>The common.js module is used by tests for consistency across repeated
<del>tasks. It has a number of helpful functions and properties to help with
<del>writing tests.
<del>
<del>### allowGlobals(...whitelist)
<del>* `whitelist` [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Array of Globals
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<del>
<del>Takes `whitelist` and concats that with predefined `knownGlobals`.
<del>
<del>### arrayStream
<del>A stream to push an array into a REPL
<del>
<del>### busyLoop(time)
<del>* `time` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>
<del>Blocks for `time` amount of time.
<del>
<del>### canCreateSymLink
<del>API to indicate whether the current running process can create
<del>symlinks. On Windows, this returns false if the process running
<del>doesn't have privileges to create symlinks (specifically
<del>[SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx)).
<del>On non-Windows platforms, this currently returns true.
<del>
<del>### crashOnUnhandledRejection()
<del>
<del>Installs a `process.on('unhandledRejection')` handler that crashes the process
<del>after a tick. This is useful for tests that use Promises and need to make sure
<del>no unexpected rejections occur, because currently they result in silent
<del>failures.
<del>
<del>### ddCommand(filename, kilobytes)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>
<del>Platform normalizes the `dd` command
<del>
<del>### enoughTestMem
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Check if there is more than 1gb of total memory.
<del>
<del>### expectsError(settings)
<del>* `settings` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del> with the following optional properties:
<del> * `code` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del> expected error must have this value for its `code` property
<del> * `type` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<del> expected error must be an instance of `type`
<del> * `message` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del> or [<RegExp>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
<del> if a string is provided for `message`, expected error must have it for its
<del> `message` property; if a regular expression is provided for `message`, the
<del> regular expression must match the `message` property of the expected error
<del>
<del>* return function suitable for use as a validation function passed as the second
<del> argument to `assert.throws()`
<del>
<del>The expected error should be [subclassed by the `internal/errors` module](https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md#api).
<del>
<del>### expectWarning(name, expected)
<del>* `name` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* `expected` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<del>
<del>Tests whether `name` and `expected` are part of a raised warning.
<del>
<del>## getArrayBufferViews(buf)
<del>* `buf` [<Buffer>](https://nodejs.org/api/buffer.html#buffer_class_buffer)
<del>* return [<ArrayBufferView[]>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)
<del>
<del>Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
<del>
<del>### hasCrypto
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks for 'openssl'.
<del>
<del>### hasFipsCrypto
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks `hasCrypto` and `crypto` with fips.
<del>
<del>### hasIPv6
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks whether `IPv6` is supported on this platform.
<del>
<del>### hasMultiLocalhost
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks if there are multiple localhosts available.
<del>
<del>### fileExists(pathname)
<del>* pathname [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks if `pathname` exists
<del>
<del>### fixturesDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Path to the 'fixtures' directory.
<del>
<del>### globalCheck
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Turn this off if the test should not check for global leaks.
<del>
<del>### inFreeBSDJail
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks whether free BSD Jail is true or false.
<del>
<del>### isAix
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Advanced Interactive eXecutive (AIX).
<del>
<del>### isAlive(pid)
<del>* `pid` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Attempts to 'kill' `pid`
<del>
<del>### isFreeBSD
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Free BSD.
<del>
<del>### isLinux
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Linux.
<del>
<del>### isLinuxPPCBE
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Linux on PowerPC.
<del>
<del>### isOSX
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for macOS.
<del>
<del>### isSunOS
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for SunOS.
<del>
<del>### isWindows
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Windows.
<del>
<del>### isWOW64
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Platform check for Windows 32-bit on Windows 64-bit.
<del>
<del>### leakedGlobals
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<del>
<del>Checks whether any globals are not on the `knownGlobals` list.
<del>
<del>### localhostIPv4
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Gets IP of localhost
<del>
<del>### localIPv6Hosts
<del>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<del>
<del>Array of IPV6 hosts.
<del>
<del>### mustCall([fn][, expected])
<del>* fn [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<del>* expected [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1
<del>* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<del>
<del>Returns a function that calls `fn`. If the returned function has not been called
<del>exactly `expected` number of times when the test is complete, then the test will
<del>fail.
<del>
<del>If `fn` is not provided, `common.noop` will be used.
<del>
<del>### nodeProcessAborted(exitCode, signal)
<del>* `exitCode` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* `signal` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Returns `true` if the exit code `exitCode` and/or signal name `signal` represent the exit code and/or signal name of a node process that aborted, `false` otherwise.
<del>
<del>### noop
<del>
<del>A non-op `Function` that can be used for a variety of scenarios.
<del>
<del>For instance,
<del>
<del><!-- eslint-disable strict, no-undef -->
<del>```js
<del>const common = require('../common');
<del>
<del>someAsyncAPI('foo', common.mustCall(common.noop));
<del>```
<del>
<del>### opensslCli
<del>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<del>
<del>Checks whether 'opensslCli' is supported.
<del>
<del>### platformTimeout(ms)
<del>* `ms` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<del>
<del>Platform normalizes timeout.
<del>
<del>### PIPE
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Path to the test sock.
<del>
<del>### PORT
<del>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = `12346`
<del>
<del>Port tests are running on.
<del>
<del>### refreshTmpDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Deletes the 'tmp' dir and recreates it
<del>
<del>### rootDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Path to the 'root' directory. either `/` or `c:\\` (windows)
<del>
<del>### skip(msg)
<del>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Logs '1..0 # Skipped: ' + `msg`
<del>
<del>### spawnPwd(options)
<del>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>
<del>Platform normalizes the `pwd` command.
<del>
<del>### spawnSyncPwd(options)
<del>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<del>
<del>Synchronous version of `spawnPwd`.
<del>
<del>### tmpDir
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>The realpath of the 'tmp' directory.
<del>
<del>### tmpDirName
<del>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<del>
<del>Name of the temp directory used by tests.
<del>
<del>### WPT
<del>
<del>A port of parts of
<del>[W3C testharness.js](https://github.com/w3c/testharness.js) for testing the
<del>Node.js
<del>[WHATWG URL API](https://nodejs.org/api/url.html#url_the_whatwg_url_api)
<del>implementation with tests from
<del>[W3C Web Platform Tests](https://github.com/w3c/web-platform-tests).
<ide><path>test/common/README.md
<add># Node.js Core Test Common Modules
<add>
<add>This directory contains modules used to test the Node.js implementation.
<add>
<add>## Table of Contents
<add>
<add>* [Common module API](#common-module-api)
<add>* [WPT module](#wpt-module)
<add>
<add>## Common Module API
<add>
<add>The `common` module is used by tests for consistency across repeated
<add>tasks.
<add>
<add>### allowGlobals(...whitelist)
<add>* `whitelist` [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Array of Globals
<add>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>
<add>Takes `whitelist` and concats that with predefined `knownGlobals`.
<add>
<add>### arrayStream
<add>A stream to push an array into a REPL
<add>
<add>### busyLoop(time)
<add>* `time` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>
<add>Blocks for `time` amount of time.
<add>
<add>### canCreateSymLink
<add>API to indicate whether the current running process can create
<add>symlinks. On Windows, this returns false if the process running
<add>doesn't have privileges to create symlinks (specifically
<add>[SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx)).
<add>On non-Windows platforms, this currently returns true.
<add>
<add>### crashOnUnhandledRejection()
<add>
<add>Installs a `process.on('unhandledRejection')` handler that crashes the process
<add>after a tick. This is useful for tests that use Promises and need to make sure
<add>no unexpected rejections occur, because currently they result in silent
<add>failures.
<add>
<add>### ddCommand(filename, kilobytes)
<add>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>
<add>Platform normalizes the `dd` command
<add>
<add>### enoughTestMem
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Check if there is more than 1gb of total memory.
<add>
<add>### expectsError(settings)
<add>* `settings` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add> with the following optional properties:
<add> * `code` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add> expected error must have this value for its `code` property
<add> * `type` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add> expected error must be an instance of `type`
<add> * `message` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add> or [<RegExp>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
<add> if a string is provided for `message`, expected error must have it for its
<add> `message` property; if a regular expression is provided for `message`, the
<add> regular expression must match the `message` property of the expected error
<add>
<add>* return function suitable for use as a validation function passed as the second
<add> argument to `assert.throws()`
<add>
<add>The expected error should be [subclassed by the `internal/errors` module](https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md#api).
<add>
<add>### expectWarning(name, expected)
<add>* `name` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* `expected` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>
<add>Tests whether `name` and `expected` are part of a raised warning.
<add>
<add>### fileExists(pathname)
<add>* pathname [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks if `pathname` exists
<add>
<add>### fixturesDir
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Path to the 'fixtures' directory.
<add>
<add>### getArrayBufferViews(buf)
<add>* `buf` [<Buffer>](https://nodejs.org/api/buffer.html#buffer_class_buffer)
<add>* return [<ArrayBufferView[]>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)
<add>
<add>Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
<add>
<add>### globalCheck
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Turn this off if the test should not check for global leaks.
<add>
<add>### hasCrypto
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks for 'openssl'.
<add>
<add>### hasFipsCrypto
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks `hasCrypto` and `crypto` with fips.
<add>
<add>### hasIPv6
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks whether `IPv6` is supported on this platform.
<add>
<add>### hasMultiLocalhost
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks if there are multiple localhosts available.
<add>
<add>### inFreeBSDJail
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks whether free BSD Jail is true or false.
<add>
<add>### isAix
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Advanced Interactive eXecutive (AIX).
<add>
<add>### isAlive(pid)
<add>* `pid` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Attempts to 'kill' `pid`
<add>
<add>### isFreeBSD
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Free BSD.
<add>
<add>### isLinux
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Linux.
<add>
<add>### isLinuxPPCBE
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Linux on PowerPC.
<add>
<add>### isOSX
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for macOS.
<add>
<add>### isSunOS
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for SunOS.
<add>
<add>### isWindows
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Windows.
<add>
<add>### isWOW64
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Platform check for Windows 32-bit on Windows 64-bit.
<add>
<add>### leakedGlobals
<add>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>
<add>Checks whether any globals are not on the `knownGlobals` list.
<add>
<add>### localhostIPv4
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Gets IP of localhost
<add>
<add>### localIPv6Hosts
<add>* return [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>
<add>Array of IPV6 hosts.
<add>
<add>### mustCall([fn][, expected])
<add>* fn [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add>* expected [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1
<add>* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
<add>
<add>Returns a function that calls `fn`. If the returned function has not been called
<add>exactly `expected` number of times when the test is complete, then the test will
<add>fail.
<add>
<add>If `fn` is not provided, `common.noop` will be used.
<add>
<add>### nodeProcessAborted(exitCode, signal)
<add>* `exitCode` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>* `signal` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Returns `true` if the exit code `exitCode` and/or signal name `signal` represent the exit code and/or signal name of a node process that aborted, `false` otherwise.
<add>
<add>### noop
<add>
<add>A non-op `Function` that can be used for a variety of scenarios.
<add>
<add>For instance,
<add>
<add><!-- eslint-disable strict, no-undef -->
<add>```js
<add>const common = require('../common');
<add>
<add>someAsyncAPI('foo', common.mustCall(common.noop));
<add>```
<add>
<add>### opensslCli
<add>* return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<add>
<add>Checks whether 'opensslCli' is supported.
<add>
<add>### platformTimeout(ms)
<add>* `ms` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
<add>
<add>Platform normalizes timeout.
<add>
<add>### PIPE
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Path to the test sock.
<add>
<add>### PORT
<add>* return [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = `12346`
<add>
<add>Port tests are running on.
<add>
<add>### refreshTmpDir
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Deletes the 'tmp' dir and recreates it
<add>
<add>### rootDir
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Path to the 'root' directory. either `/` or `c:\\` (windows)
<add>
<add>### skip(msg)
<add>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Logs '1..0 # Skipped: ' + `msg`
<add>
<add>### spawnPwd(options)
<add>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>
<add>Platform normalizes the `pwd` command.
<add>
<add>### spawnSyncPwd(options)
<add>* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>* return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<add>
<add>Synchronous version of `spawnPwd`.
<add>
<add>### tmpDir
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>The realpath of the 'tmp' directory.
<add>
<add>### tmpDirName
<add>* return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Name of the temp directory used by tests.
<add>
<add>## WPT Module
<add>
<add>The wpt.js module is a port of parts of
<add>[W3C testharness.js](https://github.com/w3c/testharness.js) for testing the
<add>Node.js
<add>[WHATWG URL API](https://nodejs.org/api/url.html#url_the_whatwg_url_api)
<add>implementation with tests from
<add>[W3C Web Platform Tests](https://github.com/w3c/web-platform-tests).
<add><path>test/common/index.js
<del><path>test/common.js
<ide> const Timer = process.binding('timer_wrap').Timer;
<ide> const execSync = require('child_process').execSync;
<ide>
<ide> const testRoot = process.env.NODE_TEST_DIR ?
<del> fs.realpathSync(process.env.NODE_TEST_DIR) : __dirname;
<add> fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..');
<ide>
<ide> const noop = () => {};
<ide>
<ide> exports.noop = noop;
<del>exports.fixturesDir = path.join(__dirname, 'fixtures');
<add>exports.fixturesDir = path.join(__dirname, '..', 'fixtures');
<ide> exports.tmpDirName = 'tmp';
<ide> // PORT should match the definition in test/testpy/__init__.py.
<ide> exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
<ide> Object.defineProperty(exports, 'hasIntl', {
<ide> }
<ide> });
<ide>
<del>// https://github.com/w3c/testharness.js/blob/master/testharness.js
<del>exports.WPT = {
<del> test: (fn, desc) => {
<del> try {
<del> fn();
<del> } catch (err) {
<del> console.error(`In ${desc}:`);
<del> throw err;
<del> }
<del> },
<del> assert_equals: assert.strictEqual,
<del> assert_true: (value, message) => assert.strictEqual(value, true, message),
<del> assert_false: (value, message) => assert.strictEqual(value, false, message),
<del> assert_throws: (code, func, desc) => {
<del> assert.throws(func, (err) => {
<del> return typeof err === 'object' &&
<del> 'name' in err &&
<del> err.name.startsWith(code.name);
<del> }, desc);
<del> },
<del> assert_array_equals: assert.deepStrictEqual,
<del> assert_unreached(desc) {
<del> assert.fail(`Reached unreachable code: ${desc}`);
<del> }
<del>};
<del>
<ide> // Useful for testing expected internal/error objects
<ide> exports.expectsError = function expectsError({code, type, message}) {
<ide> return function(error) {
<ide><path>test/common/wpt.js
<add>/* eslint-disable required-modules */
<add>'use strict';
<add>
<add>const assert = require('assert');
<add>
<add>// https://github.com/w3c/testharness.js/blob/master/testharness.js
<add>module.exports = {
<add> test: (fn, desc) => {
<add> try {
<add> fn();
<add> } catch (err) {
<add> console.error(`In ${desc}:`);
<add> throw err;
<add> }
<add> },
<add> assert_equals: assert.strictEqual,
<add> assert_true: (value, message) => assert.strictEqual(value, true, message),
<add> assert_false: (value, message) => assert.strictEqual(value, false, message),
<add> assert_throws: (code, func, desc) => {
<add> assert.throws(func, function(err) {
<add> return typeof err === 'object' &&
<add> 'name' in err &&
<add> err.name.startsWith(code.name);
<add> }, desc);
<add> },
<add> assert_array_equals: assert.deepStrictEqual,
<add> assert_unreached(desc) {
<add> assert.fail(`Reached unreachable code: ${desc}`);
<add> }
<add>};
<ide><path>test/parallel/test-whatwg-url-constructor.js
<ide> const common = require('../common');
<ide> const path = require('path');
<ide> const { URL, URLSearchParams } = require('url');
<del>const { test, assert_equals, assert_true, assert_throws } = common.WPT;
<add>const { test, assert_equals, assert_true, assert_throws } =
<add> require('../common/wpt');
<ide>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide><path>test/parallel/test-whatwg-url-historical.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> const URL = require('url').URL;
<del>const { test, assert_equals, assert_throws } = common.WPT;
<add>const { test, assert_equals, assert_throws } = require('../common/wpt');
<ide>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide><path>test/parallel/test-whatwg-url-origin.js
<ide> const common = require('../common');
<ide> const path = require('path');
<ide> const URL = require('url').URL;
<del>const { test, assert_equals } = common.WPT;
<add>const { test, assert_equals } = require('../common/wpt');
<ide>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide><path>test/parallel/test-whatwg-url-searchparams-append.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_equals, assert_true } = common.WPT;
<add>const { test, assert_equals, assert_true } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-constructor.js
<ide> const URLSearchParams = require('url').URLSearchParams;
<ide> const {
<ide> test, assert_equals, assert_true,
<ide> assert_false, assert_throws, assert_array_equals
<del>} = common.WPT;
<add>} = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> var params; // Strict mode fix for WPT.
<ide><path>test/parallel/test-whatwg-url-searchparams-delete.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const { URL, URLSearchParams } = require('url');
<del>const { test, assert_equals, assert_true, assert_false } = common.WPT;
<add>const { test, assert_equals, assert_true, assert_false } =
<add> require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-foreach.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const { URL, URLSearchParams } = require('url');
<del>const { test, assert_array_equals, assert_unreached } = common.WPT;
<add>const { test, assert_array_equals, assert_unreached } =
<add> require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> var i; // Strict mode fix for WPT.
<ide><path>test/parallel/test-whatwg-url-searchparams-get.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_equals, assert_true } = common.WPT;
<add>const { test, assert_equals, assert_true } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-getall.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_equals, assert_true, assert_array_equals } = common.WPT;
<add>const { test, assert_equals, assert_true, assert_array_equals } =
<add> require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-has.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_false, assert_true } = common.WPT;
<add>const { test, assert_false, assert_true } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-set.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_equals, assert_true } = common.WPT;
<add>const { test, assert_equals, assert_true } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-sort.js
<ide> 'use strict';
<ide>
<del>const common = require('../common');
<add>require('../common');
<ide> const { URL, URLSearchParams } = require('url');
<del>const { test, assert_array_equals } = common.WPT;
<add>const { test, assert_array_equals } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-searchparams-stringifier.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const URLSearchParams = require('url').URLSearchParams;
<del>const { test, assert_equals } = common.WPT;
<add>const { test, assert_equals } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/parallel/test-whatwg-url-setters.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide> const URL = require('url').URL;
<del>const { test, assert_equals } = common.WPT;
<add>const { test, assert_equals } = require('../common/wpt');
<ide> const additionalTestCases = require(
<ide> path.join(common.fixturesDir, 'url-setter-tests-additional.js'));
<ide>
<ide><path>test/parallel/test-whatwg-url-tojson.js
<ide> 'use strict';
<ide>
<del>const common = require('../common');
<add>require('../common');
<ide> const URL = require('url').URL;
<del>const { test, assert_equals } = common.WPT;
<add>const { test, assert_equals } = require('../common/wpt');
<ide>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide><path>test/sequential/test-module-loading.js
<ide> try {
<ide> }, {});
<ide>
<ide> assert.deepStrictEqual(children, {
<del> 'common.js': {},
<add> 'common/index.js': {},
<ide> 'fixtures/not-main-module.js': {},
<ide> 'fixtures/a.js': {
<ide> 'fixtures/b/c.js': {
<ide><path>test/testpy/__init__.py
<ide> def GetCommand(self):
<ide> source = open(self.file).read()
<ide> flags_match = FLAGS_PATTERN.search(source)
<ide> if flags_match:
<del> # PORT should match the definition in test/common.js.
<add> # PORT should match the definition in test/common/index.js.
<ide> env = { 'PORT': int(os.getenv('NODE_COMMON_PORT', '12346')) }
<ide> env['PORT'] += self.thread_id * 100
<ide> flag = flags_match.group(1).strip().format(**env).split() | 22 |
Text | Text | add clover health to airflow users | 92f3ea794b18e11525d2d0540d91474329373cc5 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * Agari [@r39132](https://github.com/r39132)
<ide> * [Bellhops](https://github.com/bellhops)
<ide> * BlueApron [[@jasonjho](https://github.com/jasonjho) & [@matthewdavidhauser](https://github.com/matthewdavidhauser)]
<add>* [Clover Health] (https://www.cloverhealth.com) [[@gwax](https://github.com/gwax) & [@vansivallab](https://github.com/vansivallab)]
<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)]
<ide> * Easy Taxi [[@caique-lima](https://github.com/caique-lima)] | 1 |
Ruby | Ruby | use real_mod_name on check for removed module | 15874514fa5a9b380a23e05ee5d7d84165757e56 | <ide><path>activesupport/lib/active_support/dependencies.rb
<ide> def qualified_name_for(mod, name)
<ide> # it is not possible to load the constant into from_mod, try its parent
<ide> # module using +const_missing+.
<ide> def load_missing_constant(from_mod, const_name)
<del> unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
<add> from_mod_name = real_mod_name(from_mod)
<add> unless qualified_const_defined?(from_mod_name) && Inflector.constantize(from_mod_name).equal?(from_mod)
<ide> raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
<ide> end
<ide> | 1 |
Javascript | Javascript | fix istanbul crash | 61a3bff8350db475ebcf258c2c4da7545dfa6b40 | <ide><path>test/configCases/plugins/define-plugin/webpack.config.js
<ide> module.exports = {
<ide> TRUE: true,
<ide> FALSE: false,
<ide> UNDEFINED: undefined,
<del> FUNCTION: function(a) {
<add> FUNCTION: /* istanbul ignore next */ function(a) {
<ide> return a + 1;
<ide> },
<ide> CODE: "(1+2)",
<ide> REGEXP: /abc/i,
<ide> OBJECT: {
<ide> SUB: {
<ide> UNDEFINED: undefined,
<del> FUNCTION: function(a) {
<add> FUNCTION: /* istanbul ignore next */ function(a) {
<ide> return a + 1;
<ide> },
<ide> CODE: "(1+2)", | 1 |
Javascript | Javascript | enforce access to prototype from primordials | 5c3944fa204f161335ace6e65834c57e7a4b27e9 | <ide><path>lib/internal/freeze_intrinsics.js
<ide> const {
<ide> Array,
<ide> ArrayBuffer,
<add> ArrayBufferPrototype,
<add> ArrayPrototype,
<ide> ArrayPrototypeForEach,
<add> ArrayPrototypePush,
<ide> BigInt,
<ide> BigInt64Array,
<add> BigInt64ArrayPrototype,
<add> BigIntPrototype,
<ide> BigUint64Array,
<add> BigUint64ArrayPrototype,
<ide> Boolean,
<add> BooleanPrototype,
<ide> DataView,
<add> DataViewPrototype,
<ide> Date,
<add> DatePrototype,
<ide> Error,
<add> ErrorPrototype,
<ide> EvalError,
<add> EvalErrorPrototype,
<ide> Float32Array,
<add> Float32ArrayPrototype,
<ide> Float64Array,
<add> Float64ArrayPrototype,
<ide> Function,
<add> FunctionPrototype,
<ide> Int16Array,
<add> Int16ArrayPrototype,
<ide> Int32Array,
<add> Int32ArrayPrototype,
<ide> Int8Array,
<del> JSON,
<add> Int8ArrayPrototype,
<ide> Map,
<del> Math,
<add> MapPrototype,
<ide> Number,
<add> NumberPrototype,
<ide> Object,
<ide> ObjectDefineProperty,
<ide> ObjectFreeze,
<ide> const {
<ide> ObjectGetOwnPropertyNames,
<ide> ObjectGetOwnPropertySymbols,
<ide> ObjectGetPrototypeOf,
<add> ObjectPrototype,
<ide> ObjectPrototypeHasOwnProperty,
<ide> Promise,
<add> PromisePrototype,
<ide> RangeError,
<add> RangeErrorPrototype,
<ide> ReferenceError,
<del> Reflect,
<add> ReferenceErrorPrototype,
<ide> ReflectOwnKeys,
<ide> RegExp,
<add> RegExpPrototype,
<add> SafeSet,
<ide> Set,
<add> SetPrototype,
<ide> String,
<add> StringPrototype,
<ide> Symbol,
<ide> SymbolIterator,
<ide> SyntaxError,
<add> SyntaxErrorPrototype,
<ide> TypeError,
<add> TypeErrorPrototype,
<ide> TypedArray,
<ide> TypedArrayPrototype,
<ide> Uint16Array,
<add> Uint16ArrayPrototype,
<ide> Uint32Array,
<add> Uint32ArrayPrototype,
<ide> Uint8Array,
<add> Uint8ArrayPrototype,
<ide> Uint8ClampedArray,
<add> Uint8ClampedArrayPrototype,
<ide> URIError,
<add> URIErrorPrototype,
<ide> WeakMap,
<add> WeakMapPrototype,
<ide> WeakSet,
<add> WeakSetPrototype,
<ide> } = primordials;
<ide>
<ide> module.exports = function() {
<ide> module.exports = function() {
<ide> TypedArrayPrototype,
<ide>
<ide> // 19 Fundamental Objects
<del> Object.prototype, // 19.1
<del> Function.prototype, // 19.2
<del> Boolean.prototype, // 19.3
<del>
<del> Error.prototype, // 19.5
<del> EvalError.prototype,
<del> RangeError.prototype,
<del> ReferenceError.prototype,
<del> SyntaxError.prototype,
<del> TypeError.prototype,
<del> URIError.prototype,
<add> ObjectPrototype, // 19.1
<add> FunctionPrototype, // 19.2
<add> BooleanPrototype, // 19.3
<add>
<add> ErrorPrototype, // 19.5
<add> EvalErrorPrototype,
<add> RangeErrorPrototype,
<add> ReferenceErrorPrototype,
<add> SyntaxErrorPrototype,
<add> TypeErrorPrototype,
<add> URIErrorPrototype,
<ide>
<ide> // 20 Numbers and Dates
<del> Number.prototype, // 20.1
<del> Date.prototype, // 20.3
<add> NumberPrototype, // 20.1
<add> DatePrototype, // 20.3
<ide>
<ide> // 21 Text Processing
<del> String.prototype, // 21.1
<del> RegExp.prototype, // 21.2
<add> StringPrototype, // 21.1
<add> RegExpPrototype, // 21.2
<ide>
<ide> // 22 Indexed Collections
<del> Array.prototype, // 22.1
<del>
<del> Int8Array.prototype,
<del> Uint8Array.prototype,
<del> Uint8ClampedArray.prototype,
<del> Int16Array.prototype,
<del> Uint16Array.prototype,
<del> Int32Array.prototype,
<del> Uint32Array.prototype,
<del> Float32Array.prototype,
<del> Float64Array.prototype,
<del> BigInt64Array.prototype,
<del> BigUint64Array.prototype,
<add> ArrayPrototype, // 22.1
<add>
<add> Int8ArrayPrototype,
<add> Uint8ArrayPrototype,
<add> Uint8ClampedArrayPrototype,
<add> Int16ArrayPrototype,
<add> Uint16ArrayPrototype,
<add> Int32ArrayPrototype,
<add> Uint32ArrayPrototype,
<add> Float32ArrayPrototype,
<add> Float64ArrayPrototype,
<add> BigInt64ArrayPrototype,
<add> BigUint64ArrayPrototype,
<ide>
<ide> // 23 Keyed Collections
<del> Map.prototype, // 23.1
<del> Set.prototype, // 23.2
<del> WeakMap.prototype, // 23.3
<del> WeakSet.prototype, // 23.4
<add> MapPrototype, // 23.1
<add> SetPrototype, // 23.2
<add> WeakMapPrototype, // 23.3
<add> WeakSetPrototype, // 23.4
<ide>
<ide> // 24 Structured Data
<del> ArrayBuffer.prototype, // 24.1
<del> DataView.prototype, // 24.3
<del> Promise.prototype, // 25.4
<add> ArrayBufferPrototype, // 24.1
<add> DataViewPrototype, // 24.3
<add> PromisePrototype, // 25.4
<ide>
<ide> // Other APIs / Web Compatibility
<ide> console.Console.prototype,
<del> BigInt.prototype,
<add> BigIntPrototype,
<ide> WebAssembly.Module.prototype,
<ide> WebAssembly.Instance.prototype,
<ide> WebAssembly.Table.prototype,
<ide> module.exports = function() {
<ide> const intrinsics = [
<ide> // Anonymous Intrinsics
<ide> // ThrowTypeError
<del> ObjectGetOwnPropertyDescriptor(Function.prototype, 'caller').get,
<add> ObjectGetOwnPropertyDescriptor(FunctionPrototype, 'caller').get,
<ide> // IteratorPrototype
<ide> ObjectGetPrototypeOf(
<ide> ObjectGetPrototypeOf(new Array()[SymbolIterator]())
<ide> module.exports = function() {
<ide>
<ide> // 20 Numbers and Dates
<ide> Number, // 20.1
<add> // eslint-disable-next-line node-core/prefer-primordials
<ide> Math, // 20.2
<ide> Date, // 20.3
<ide>
<ide> module.exports = function() {
<ide> // 24 Structured Data
<ide> ArrayBuffer, // 24.1
<ide> DataView, // 24.3
<add> // eslint-disable-next-line node-core/prefer-primordials
<ide> JSON, // 24.5
<ide> Promise, // 25.4
<ide>
<ide> // 26 Reflection
<add> // eslint-disable-next-line node-core/prefer-primordials
<ide> Reflect, // 26.1
<ide> Proxy, // 26.2
<ide>
<ide> module.exports = function() {
<ide> ];
<ide>
<ide> if (typeof Intl !== 'undefined') {
<del> intrinsicPrototypes.push(Intl.Collator.prototype);
<del> intrinsicPrototypes.push(Intl.DateTimeFormat.prototype);
<del> intrinsicPrototypes.push(Intl.ListFormat.prototype);
<del> intrinsicPrototypes.push(Intl.NumberFormat.prototype);
<del> intrinsicPrototypes.push(Intl.PluralRules.prototype);
<del> intrinsicPrototypes.push(Intl.RelativeTimeFormat.prototype);
<del> intrinsics.push(Intl);
<add> ArrayPrototypePush(intrinsicPrototypes,
<add> Intl.Collator.prototype,
<add> Intl.DateTimeFormat.prototype,
<add> Intl.ListFormat.prototype,
<add> Intl.NumberFormat.prototype,
<add> Intl.PluralRules.prototype,
<add> Intl.RelativeTimeFormat.prototype,
<add> );
<add> ArrayPrototypePush(intrinsics, Intl);
<ide> }
<ide>
<del> intrinsicPrototypes.forEach(enableDerivedOverrides);
<add> ArrayPrototypeForEach(intrinsicPrototypes, enableDerivedOverrides);
<ide>
<ide> const frozenSet = new WeakSet();
<del> intrinsics.forEach(deepFreeze);
<add> ArrayPrototypeForEach(intrinsics, deepFreeze);
<ide>
<ide> // Objects that are deeply frozen.
<ide> function deepFreeze(root) {
<ide> module.exports = function() {
<ide> */
<ide> function innerDeepFreeze(node) {
<ide> // Objects that we have frozen in this round.
<del> const freezingSet = new Set();
<add> const freezingSet = new SafeSet();
<ide>
<ide> // If val is something we should be freezing but aren't yet,
<ide> // add it to freezingSet.
<ide><path>lib/internal/process/warning.js
<ide> const {
<ide> ArrayIsArray,
<ide> Error,
<add> ErrorPrototypeToString,
<ide> ErrorCaptureStackTrace,
<ide> String,
<ide> } = primordials;
<ide> function onWarning(warning) {
<ide> if (trace && warning.stack) {
<ide> msg += `${warning.stack}`;
<ide> } else {
<del> const toString =
<add> msg +=
<ide> typeof warning.toString === 'function' ?
<del> warning.toString : Error.prototype.toString;
<del> msg += `${toString.apply(warning)}`;
<add> `${warning.toString()}` :
<add> ErrorPrototypeToString(warning);
<ide> }
<ide> if (typeof warning.detail === 'string') {
<ide> msg += `\n${warning.detail}`;
<ide><path>test/parallel/test-eslint-prefer-primordials.js
<ide> new RuleTester({
<ide> options: [{ name: 'Map', into: 'Safe' }],
<ide> errors: [{ message: /const { SafeMap } = primordials/ }]
<ide> },
<add> {
<add> code: `
<add> const { Function } = primordials;
<add> const noop = Function.prototype;
<add> `,
<add> options: [{ name: 'Function' }],
<add> errors: [{ message: /const { FunctionPrototype } = primordials/ }]
<add> },
<ide> ]
<ide> });
<ide><path>tools/eslint-rules/prefer-primordials.js
<ide> module.exports = {
<ide> acc.set(
<ide> option.name,
<ide> (option.ignore || [])
<del> .concat(['prototype'])
<ide> .reduce((acc, name) => acc.set(name, {
<ide> ignored: true
<ide> }), new Map()) | 4 |
Javascript | Javascript | add hascrypto to tls-wrap-event-emmiter | 5debcceafcdd73035d840f53deb931925691a3ab | <ide><path>test/parallel/test-tls-wrap-event-emmiter.js
<ide> * Test checks if we get exception instead of runtime error
<ide> */
<ide>
<del>require('../common');
<add>const common = require('../common');
<add>if (!common.hasCrypto) {
<add> common.skip('missing crypto');
<add> return;
<add>}
<ide> const assert = require('assert');
<ide>
<ide> const TlsSocket = require('tls').TLSSocket; | 1 |
Python | Python | raise exceptions instead of asserts | 64743d0abe7a37e67be7c27618cbb030c070c07e | <ide><path>src/transformers/data/processors/utils.py
<ide> def add_examples_from_csv(
<ide> def add_examples(
<ide> self, texts_or_text_and_labels, labels=None, ids=None, overwrite_labels=False, overwrite_examples=False
<ide> ):
<del> assert labels is None or len(texts_or_text_and_labels) == len(
<del> labels
<del> ), f"Text and labels have mismatched lengths {len(texts_or_text_and_labels)} and {len(labels)}"
<del> assert ids is None or len(texts_or_text_and_labels) == len(
<del> ids
<del> ), f"Text and ids have mismatched lengths {len(texts_or_text_and_labels)} and {len(ids)}"
<add> if labels is not None and len(texts_or_text_and_labels) != len(labels):
<add> raise ValueError(
<add> f"Text and labels have mismatched lengths {len(texts_or_text_and_labels)} and {len(labels)}"
<add> )
<add> if ids is not None and len(texts_or_text_and_labels) != len(ids):
<add> raise ValueError(f"Text and ids have mismatched lengths {len(texts_or_text_and_labels)} and {len(ids)}")
<ide> if ids is None:
<ide> ids = [None] * len(texts_or_text_and_labels)
<ide> if labels is None:
<ide> def get_features(
<ide> input_ids = input_ids + ([pad_token] * padding_length)
<ide> attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
<ide>
<del> assert len(input_ids) == batch_length, f"Error with input length {len(input_ids)} vs {batch_length}"
<del> assert (
<del> len(attention_mask) == batch_length
<del> ), f"Error with input length {len(attention_mask)} vs {batch_length}"
<add> if len(input_ids) != batch_length:
<add> raise ValueError(f"Error with input length {len(input_ids)} vs {batch_length}")
<add> if len(attention_mask) != batch_length:
<add> raise ValueError(f"Error with input length {len(attention_mask)} vs {batch_length}")
<ide>
<ide> if self.mode == "classification":
<ide> label = label_map[example.label] | 1 |
Text | Text | add comparison table with older brother in family | 85b324bee56c32142cc131149d7a92281964641f | <ide><path>model_cards/mrm8488/bert-tiny-finetuned-squadv2/README.md
<ide> The script for fine tuning can be found [here](https://github.com/huggingface/tr
<ide> | **EM** | **48.60** |
<ide> | **F1** | **49.73** |
<ide>
<add>
<add>| Model | EM | F1 score | SIZE (MB) |
<add>| ----------------------------------------------------------------------------------------- | --------- | --------- | --------- |
<add>| [bert-tiny-finetuned-squadv2](https://huggingface.co/mrm8488/bert-tiny-finetuned-squadv2) | 48.60 | 49.73 | **16.74** |
<add>| [bert-tiny-5-finetuned-squadv2](https://huggingface.co/mrm8488/bert-tiny-5-finetuned-squadv2) | **57.12** | **60.86** | 24.34
<add>
<ide> ## Model in action
<ide>
<ide> Fast usage with **pipelines**: | 1 |
Javascript | Javascript | add coverage for systemerror set name | 0f8d7a684f1a4885f14b5b5e1c5f675e2738712c | <ide><path>test/parallel/test-errors-systemerror.js
<ide> const { ERR_TEST } = codes;
<ide> assert.strictEqual(err.path, 'path');
<ide> assert.strictEqual(err.dest, 'path');
<ide> }
<add>
<add>{
<add> const ctx = {
<add> code: 'ERR_TEST',
<add> message: 'Error occurred',
<add> syscall: 'syscall_test'
<add> };
<add> assert.throws(
<add> () => {
<add> const err = new ERR_TEST(ctx);
<add> err.name = 'SystemError [CUSTOM_ERR_TEST]';
<add> throw err;
<add> },
<add> {
<add> code: 'ERR_TEST',
<add> name: 'SystemError [CUSTOM_ERR_TEST]',
<add> message: 'custom message: syscall_test returned ERR_TEST ' +
<add> '(Error occurred)',
<add> info: ctx
<add> }
<add> );
<add>} | 1 |
Python | Python | add support for eu-north-1 in ec2 | 457d340d6e86d6a5c07661e3941fe6497335f56f | <ide><path>libcloud/compute/constants.py
<ide> ],
<ide> "signature_version": "4"
<ide> },
<add> "eu-north-1": {
<add> "api_name": "ec2_eu_north",
<add> "country": "Stockholm",
<add> "endpoint": "ec2.eu-north-1.amazonaws.com",
<add> "id": "eu-north-1",
<add> "instance_types": [
<add> "c5.large",
<add> "c5.xlarge",
<add> "c5.metal",
<add> "c5.2xlarge",
<add> "c5.4xlarge",
<add> "c5.9xlarge",
<add> "c5.12xlarge",
<add> "c5.18xlarge",
<add> "c5.24xlarge",
<add> "c5a.large",
<add> "c5a.xlarge",
<add> "c5a.2xlarge",
<add> "c5a.4xlarge",
<add> "c5a.8xlarge",
<add> "c5a.12xlarge",
<add> "c5a.16xlarge",
<add> "c5a.24xlarge",
<add> "c5d.large",
<add> "c5d.xlarge",
<add> "c5d.metal",
<add> "c5d.2xlarge",
<add> "c5d.4xlarge",
<add> "c5d.9xlarge",
<add> "c5d.12xlarge",
<add> "c5d.18xlarge",
<add> "c5d.24xlarge",
<add> "c5n.large",
<add> "c5n.xlarge",
<add> "c5n.metal",
<add> "c5n.2xlarge",
<add> "c5n.4xlarge",
<add> "c5n.9xlarge",
<add> "c5n.18xlarge",
<add> "d2.xlarge",
<add> "d2.2xlarge",
<add> "d2.4xlarge",
<add> "d2.8xlarge",
<add> "g4dn.xlarge",
<add> "g4dn.2xlarge",
<add> "g4dn.4xlarge",
<add> "g4dn.8xlarge",
<add> "g4dn.12xlarge",
<add> "g4dn.16xlarge",
<add> "i3.large",
<add> "i3.xlarge",
<add> "i3.2xlarge",
<add> "i3.4xlarge",
<add> "i3.8xlarge",
<add> "i3.16xlarge",
<add> "i3en.large",
<add> "i3en.xlarge",
<add> "i3en.metal",
<add> "i3en.2xlarge",
<add> "i3en.3xlarge",
<add> "i3en.6xlarge",
<add> "i3en.12xlarge",
<add> "i3en.24xlarge",
<add> "m5.large",
<add> "m5.xlarge",
<add> "m5.metal",
<add> "m5.2xlarge",
<add> "m5.4xlarge",
<add> "m5.8xlarge",
<add> "m5.12xlarge",
<add> "m5.16xlarge",
<add> "m5.24xlarge",
<add> "m5d.large",
<add> "m5d.xlarge",
<add> "m5d.metal",
<add> "m5d.2xlarge",
<add> "m5d.4xlarge",
<add> "m5d.8xlarge",
<add> "m5d.12xlarge",
<add> "m5d.16xlarge",
<add> "m5d.24xlarge",
<add> "r5.large",
<add> "r5.xlarge",
<add> "r5.metal",
<add> "r5.2xlarge",
<add> "r5.4xlarge",
<add> "r5.8xlarge",
<add> "r5.12xlarge",
<add> "r5.16xlarge",
<add> "r5.24xlarge",
<add> "r5d.large",
<add> "r5d.xlarge",
<add> "r5d.metal",
<add> "r5d.2xlarge",
<add> "r5d.4xlarge",
<add> "r5d.8xlarge",
<add> "r5d.12xlarge",
<add> "r5d.16xlarge",
<add> "r5d.24xlarge",
<add> "t3.micro",
<add> "t3.small",
<add> "t3.medium",
<add> "t3.large",
<add> "t3.xlarge",
<add> "t3.nano",
<add> "t3.2xlarge",
<add> "c5.large",
<add> "c5.xlarge",
<add> "c5.metal",
<add> "c5.2xlarge",
<add> "c5.4xlarge",
<add> "c5.9xlarge",
<add> "c5.12xlarge",
<add> "c5.18xlarge",
<add> "c5.24xlarge",
<add> "c5a.large",
<add> "c5a.xlarge",
<add> "c5a.2xlarge",
<add> "c5a.4xlarge",
<add> "c5a.8xlarge",
<add> "c5a.12xlarge",
<add> "c5a.16xlarge",
<add> "c5a.24xlarge",
<add> "c5d.large",
<add> "c5d.xlarge",
<add> "c5d.metal",
<add> "c5d.2xlarge",
<add> "c5d.4xlarge",
<add> "c5d.9xlarge",
<add> "c5d.12xlarge",
<add> "c5d.18xlarge",
<add> "c5d.24xlarge",
<add> "c5n.large",
<add> "c5n.xlarge",
<add> "c5n.metal",
<add> "c5n.2xlarge",
<add> "c5n.4xlarge",
<add> "c5n.9xlarge",
<add> "c5n.18xlarge",
<add> "g4dn.xlarge",
<add> "g4dn.2xlarge",
<add> "g4dn.4xlarge",
<add> "g4dn.8xlarge",
<add> "g4dn.12xlarge",
<add> "g4dn.16xlarge",
<add> "i3.large",
<add> "i3.xlarge",
<add> "i3.2xlarge",
<add> "i3.4xlarge",
<add> "i3.8xlarge",
<add> "i3.16xlarge",
<add> "i3en.large",
<add> "i3en.xlarge",
<add> "i3en.metal",
<add> "i3en.2xlarge",
<add> "i3en.3xlarge",
<add> "i3en.6xlarge",
<add> "i3en.12xlarge",
<add> "i3en.24xlarge",
<add> "m5.large",
<add> "m5.xlarge",
<add> "m5.metal",
<add> "m5.2xlarge",
<add> "m5.4xlarge",
<add> "m5.8xlarge",
<add> "m5.12xlarge",
<add> "m5.16xlarge",
<add> "m5.24xlarge",
<add> "m5d.large",
<add> "m5d.xlarge",
<add> "m5d.metal",
<add> "m5d.2xlarge",
<add> "m5d.4xlarge",
<add> "m5d.8xlarge",
<add> "m5d.12xlarge",
<add> "m5d.16xlarge",
<add> "m5d.24xlarge",
<add> "r5.large",
<add> "r5.xlarge",
<add> "r5.metal",
<add> "r5.2xlarge",
<add> "r5.4xlarge",
<add> "r5.8xlarge",
<add> "r5.12xlarge",
<add> "r5.16xlarge",
<add> "r5.24xlarge",
<add> "r5d.large",
<add> "r5d.xlarge",
<add> "r5d.metal",
<add> "r5d.2xlarge",
<add> "r5d.4xlarge",
<add> "r5d.8xlarge",
<add> "r5d.12xlarge",
<add> "r5d.16xlarge",
<add> "r5d.24xlarge",
<add> "t3.xlarge",
<add> "t3.2xlarge"
<add> ],
<add> "signature_version": "4"
<add> },
<ide> "eu-west-1": {
<ide> "api_name": "ec2_eu_west",
<ide> "country": "Ireland", | 1 |
Javascript | Javascript | add support for the contenteditable attribute | cccf9ad91d8b6626e1e20bd267c9cd0b6223f15c | <ide><path>src/attributes.js
<ide> jQuery.extend({
<ide> rowspan: "rowSpan",
<ide> colspan: "colSpan",
<ide> usemap: "useMap",
<del> frameborder: "frameBorder"
<add> frameborder: "frameBorder",
<add> contenteditable: "contentEditable"
<ide> },
<ide>
<ide> prop: function( elem, name, value ) {
<ide><path>test/unit/attributes.js
<ide> test("jQuery.attrFix/jQuery.propFix integrity test", function() {
<ide> rowspan: "rowSpan",
<ide> colspan: "colSpan",
<ide> usemap: "useMap",
<del> frameborder: "frameBorder"
<add> frameborder: "frameBorder",
<add> contenteditable: "contentEditable"
<ide> },
<ide> propsShouldBe;
<ide>
<ide> test("attr(Hash)", function() {
<ide> });
<ide>
<ide> test("attr(String, Object)", function() {
<del> expect(56);
<add> expect(57);
<ide>
<ide> var div = jQuery("div").attr("foo", "bar"),
<ide> fail = false;
<ide> test("attr(String, Object)", function() {
<ide> equals( $text.attr("aria-disabled", false).attr("aria-disabled"), "false", "Setting aria attributes are not affected by boolean settings");
<ide> $text.removeData("something").removeData("another").removeAttr("aria-disabled");
<ide>
<add> jQuery("#foo").attr("contenteditable", true);
<add> equals( jQuery("#foo").attr("contenteditable"), "true", "Enumerated attributes are set properly" );
<add>
<ide> var attributeNode = document.createAttribute("irrelevant"),
<ide> commentNode = document.createComment("some comment"),
<ide> textNode = document.createTextNode("some text"); | 2 |
PHP | PHP | fix lying docblocks | 1950b298f68def0d47e66c1a258e25f14bbea716 | <ide><path>src/Http/Session.php
<ide> public function check(?string $name = null): bool
<ide> *
<ide> * @param string|null $name The name of the session variable (or a path as sent to Hash.extract)
<ide> * @param mixed $default The return value when the path does not exist
<del> * @return string|array|null The value of the session variable, null if session not available,
<add> * @return mixed|null The value of the session variable, null if session not available,
<ide> * session not started, or provided name not found in the session.
<ide> */
<ide> public function read(?string $name = null, $default = null)
<ide> public function read(?string $name = null, $default = null)
<ide> *
<ide> * @param string $name The name of the session variable (or a path as sent to Hash.extract)
<ide> * @throws \RuntimeException
<del> * @return array|string|null
<add> * @return mixed|null
<ide> */
<ide> public function readOrFail(string $name)
<ide> {
<ide> public function readOrFail(string $name)
<ide> * Reads and deletes a variable from session.
<ide> *
<ide> * @param string $name The key to read and remove (or a path as sent to Hash.extract).
<del> * @return mixed The value of the session variable, null if session not available,
<add> * @return mixed|null The value of the session variable, null if session not available,
<ide> * session not started, or provided name not found in the session.
<ide> */
<ide> public function consume(string $name) | 1 |
Java | Java | add consumewith to fluxexchangeresult | d742fc198abc8fee8477cea2d5761649b8ac40e3 | <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide> import org.springframework.core.io.ByteArrayResource;
<add>import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.reactive.function.BodyExtractor;
<add>import org.springframework.web.reactive.function.BodyExtractors;
<ide> import org.springframework.web.reactive.function.BodyInserter;
<ide> import org.springframework.web.reactive.function.client.ClientResponse;
<ide> import org.springframework.web.reactive.function.client.WebClient;
<ide> public BodyContentSpec expectBody() {
<ide> return new DefaultBodyContentSpec(this.result.decodeToByteArray());
<ide> }
<ide>
<add> @Override
<add> public FluxExchangeResult<DataBuffer> returnResult() {
<add> return this.result.decodeToFlux(BodyExtractors.toDataBuffers());
<add> }
<add>
<ide> @Override
<ide> public <T> FluxExchangeResult<T> returnResult(Class<T> elementType) {
<ide> return this.result.decodeToFlux(toFlux(elementType));
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/FluxExchangeResult.java
<ide> package org.springframework.test.web.reactive.server;
<ide>
<ide> import java.time.Duration;
<add>import java.util.function.Consumer;
<ide>
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> public byte[] getResponseBodyContent() {
<ide> .block();
<ide> }
<ide>
<add> /**
<add> * Invoke the given consumer within {@link #assertWithDiagnostics(Runnable)}
<add> * passing {@code "this"} instance to it. This method allows the following,
<add> * without leaving the {@code WebTestClient} chain of calls:
<add> * <pre class="code">
<add> * client.get()
<add> * .uri("/persons")
<add> * .accept(TEXT_EVENT_STREAM)
<add> * .exchange()
<add> * .expectStatus().isOk()
<add> * .returnResult()
<add> * .consumeWith(result -> assertThat(...);
<add> * </pre>
<add> * @param consumer consumer for {@code "this"} instance
<add> */
<add> public void consumeWith(Consumer<FluxExchangeResult<T>> consumer) {
<add> assertWithDiagnostics(() -> consumer.accept(this));
<add> }
<add>
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.format.FormatterRegistry;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> interface ResponseSpec {
<ide> * Variant of {@link #returnResult(Class)} for element types with generics.
<ide> */
<ide> <T> FluxExchangeResult<T> returnResult(ParameterizedTypeReference<T> elementType);
<add>
<add> /**
<add> * Return the exchange result with the body decoded to
<add> * {@code Flux<DataBuffer>}. Use this option for infinite streams and
<add> * consume the stream with the {@code StepVerifier} from the Reactor Add-Ons.
<add> *
<add> * @return
<add> */
<add> FluxExchangeResult<DataBuffer> returnResult();
<ide> }
<ide>
<ide> /** | 3 |
Javascript | Javascript | remove stack trace from production | 3bac2476279ca188f94b31c7f062b8019320163a | <ide><path>server/server.js
<ide> R.keys(passportProviders).map(function(strategy) {
<ide> * 500 Error Handler.
<ide> */
<ide>
<del>// if (process.env.NODE_ENV === 'development') {
<del>if (true) { // eslint-disable-line
<del> // NOTE(berks): adding pmx here for Beta test. Remove for production
<del> app.use(pmx.expressErrorHandler());
<add>if (process.env.NODE_ENV === 'development') {
<ide> app.use(errorHandler({
<ide> log: true
<ide> })); | 1 |
PHP | PHP | fix coding standards | 6a8913361f6fc43cd3b06778bd81433b5a8af3f4 | <ide><path>lib/Cake/Cache/Engine/MemcachedEngine.php
<ide> public function init($settings = array()) {
<ide> * Settings the memcached instance
<ide> *
<ide> */
<del> protected function _setOptions()
<del> {
<add> protected function _setOptions() {
<ide> $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
<ide> //$this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
<ide>
<ide> public function clear($check) {
<ide>
<ide> $keys = $this->_Memcached->getAllKeys();
<ide>
<del> foreach($keys as $key) {
<add> foreach ($keys as $key) {
<ide> if (strpos($key, $this->settings['prefix']) === 0) {
<ide> $this->_Memcached->delete($key);
<ide> } | 1 |
Text | Text | add autofocus to supported html attributes | a4c96d6e9c12e2b7438ba373f48b695f46cbbd6d | <ide><path>docs/docs/ref-04-tags-and-attributes.md
<ide> These standard attributes are supported:
<ide>
<ide> ```
<ide> accept acceptCharset accessKey action allowFullScreen allowTransparency alt
<del>async autoComplete autoPlay cellPadding cellSpacing charSet checked classID
<add>async autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked classID
<ide> className cols colSpan content contentEditable contextMenu controls coords
<ide> crossOrigin data dateTime defer dir disabled download draggable encType form
<ide> formAction formEncType formMethod formNoValidate formTarget frameBorder height | 1 |
Go | Go | clarify the need for named error | a40e337882dfe3f34af44a9f2aec2ed96dcce455 | <ide><path>graph/graph.go
<ide> func (graph *Graph) Create(layerData archive.ArchiveReader, containerID, contain
<ide>
<ide> // Register imports a pre-existing image into the graph.
<ide> func (graph *Graph) Register(img *Image, layerData archive.ArchiveReader) (err error) {
<add>
<ide> if err := image.ValidateID(img.ID); err != nil {
<ide> return err
<ide> }
<ide> func (graph *Graph) Register(img *Image, layerData archive.ArchiveReader) (err e
<ide> graph.imageMutex.Lock(img.ID)
<ide> defer graph.imageMutex.Unlock(img.ID)
<ide>
<add> // The returned `error` must be named in this function's signature so that
<add> // `err` is not shadowed in this deferred cleanup.
<ide> defer func() {
<ide> // If any error occurs, remove the new dir from the driver.
<ide> // Don't check for errors since the dir might not have been created.
<del> // FIXME: this leaves a possible race condition.
<ide> if err != nil {
<ide> graph.driver.Remove(img.ID)
<ide> } | 1 |
Text | Text | fix example package error | 7a5224afe469104fd35283a5fef7556563054214 | <ide><path>libnetwork/README.md
<ide> There are many networking solutions available to suit a broad range of use-cases
<ide> epInfo, err := ep.DriverInfo()
<ide> mapData, ok := epInfo[netlabel.PortMap]
<ide> if ok {
<del> portMapping, ok := mapData.([]netutils.PortBinding)
<add> portMapping, ok := mapData.([]types.PortBinding)
<ide> if ok {
<ide> fmt.Printf("Current port mapping for endpoint %s: %v", ep.Name(), portMapping)
<ide> } | 1 |
Ruby | Ruby | add method to env for setting up a debug build | 85d7d4e16c0988edcceb127dbbe3b12af3655bdd | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def Os
<ide> remove_from_cflags(/-O./)
<ide> append_to_cflags '-Os'
<ide> end
<add> def Og
<add> # Sometimes you want a debug build
<add> remove_from_cflags(/-O./)
<add> append_to_cflags '-g -O0'
<add> end
<ide>
<ide> def gcc_4_0_1
<ide> self['CC'] = self['LD'] = '/usr/bin/gcc-4.0' | 1 |
Python | Python | use class decorators to register types | c64850d729b5630582f85a7bd7baed21916aa992 | <ide><path>celery/canvas.py
<ide>
<ide> Composing task workflows.
<ide>
<del> Documentation for these functions are in :mod:`celery`.
<del> You should not import from this module directly.
<add> Documentation for some of these types are in :mod:`celery`.
<add> You should not import these from :mod:`celery` and not this module.
<add>
<ide>
<ide> """
<ide> from __future__ import absolute_import
<ide> class Signature(dict):
<ide> """Class that wraps the arguments and execution options
<ide> for a single task invocation.
<ide>
<del> Used as the parts in a :class:`group` or to safely
<del> pass tasks around as callbacks.
<add> Used as the parts in a :class:`group` and other constructs,
<add> or to pass tasks around as callbacks while being compatible
<add> with serializers with a strict type subset.
<ide>
<ide> :param task: Either a task class/instance, or the name of a task.
<ide> :keyword args: Positional arguments to apply.
<ide> def _apply_async(self):
<ide> immutable = _getitem_property('immutable')
<ide>
<ide>
<add>@Signature.register_type
<ide> class chain(Signature):
<ide>
<ide> def __init__(self, *tasks, **options):
<ide> def type(self):
<ide>
<ide> def __repr__(self):
<ide> return ' | '.join(repr(t) for t in self.tasks)
<del>Signature.register_type(chain)
<ide>
<ide>
<ide> class _basemap(Signature):
<ide> def from_dict(cls, d):
<ide> return cls(*cls._unpack_args(d['kwargs']), **d['options'])
<ide>
<ide>
<add>@Signature.register_type
<ide> class xmap(_basemap):
<ide> _task_name = 'celery.map'
<ide>
<ide> def __repr__(self):
<ide> task, it = self._unpack_args(self.kwargs)
<ide> return '[{0}(x) for x in {1}]'.format(task.task,
<ide> truncate(repr(it), 100))
<del>Signature.register_type(xmap)
<ide>
<ide>
<add>@Signature.register_type
<ide> class xstarmap(_basemap):
<ide> _task_name = 'celery.starmap'
<ide>
<ide> def __repr__(self):
<ide> task, it = self._unpack_args(self.kwargs)
<ide> return '[{0}(*x) for x in {1}]'.format(task.task,
<ide> truncate(repr(it), 100))
<del>Signature.register_type(xstarmap)
<ide>
<ide>
<add>@Signature.register_type
<ide> class chunks(Signature):
<ide> _unpack_args = itemgetter('task', 'it', 'n')
<ide>
<ide> def group(self):
<ide> @classmethod
<ide> def apply_chunks(cls, task, it, n):
<ide> return cls(task, it, n)()
<del>Signature.register_type(chunks)
<ide>
<ide>
<ide> def _maybe_group(tasks):
<ide> def _maybe_group(tasks):
<ide> return tasks
<ide>
<ide>
<add>@Signature.register_type
<ide> class group(Signature):
<ide>
<ide> def __init__(self, *tasks, **options):
<ide> def __iter__(self):
<ide>
<ide> def __repr__(self):
<ide> return repr(self.tasks)
<del>Signature.register_type(group)
<ide>
<ide>
<add>Signature.register_type
<ide> class chord(Signature):
<ide>
<ide> def __init__(self, header, body=None, task='celery.chord',
<ide> def __repr__(self):
<ide>
<ide> tasks = _getitem_property('kwargs.header')
<ide> body = _getitem_property('kwargs.body')
<del>Signature.register_type(chord)
<ide>
<ide>
<ide> def subtask(varies, *args, **kwargs): | 1 |
Python | Python | update support properties | fc1a3b24cb5c96ef4847b84aa2fe441bd2c28769 | <ide><path>utils/exporters/maya/plug-ins/threeJsFileTranslator.py
<ide> def _exportMaterial(self, mat):
<ide> "DbgName": mat.name(),
<ide> "blending": "NormalBlending",
<ide> "colorDiffuse": map(lambda i: i * mat.getDiffuseCoeff(), mat.getColor().rgb),
<del> "colorAmbient": mat.getAmbientColor().rgb,
<ide> "depthTest": True,
<ide> "depthWrite": True,
<ide> "shading": mat.__class__.__name__,
<del> "transparency": mat.getTransparency().a,
<add> "opacity": mat.getTransparency().a,
<ide> "transparent": mat.getTransparency().a != 1.0,
<ide> "vertexColors": False
<ide> } | 1 |
PHP | PHP | fix route naming issue | 68cde6fbab28a369f7f090af1aeb1837f053f088 | <ide><path>src/Illuminate/Routing/AbstractRouteCollection.php
<ide> protected function addToSymfonyRoutesCollection(SymfonyRouteCollection $symfonyR
<ide> throw new LogicException("Unable to prepare route [{$route->uri}] for serialization. Another route has already been assigned name [{$name}].");
<ide> }
<ide>
<del> $symfonyRoutes->add($name, $route->toSymfonyRoute());
<add> $symfonyRoutes->add($route->getName(), $route->toSymfonyRoute());
<ide>
<ide> return $symfonyRoutes;
<ide> }
<ide><path>tests/Integration/Routing/CompiledRouteCollectionTest.php
<ide> public function testGroupPrefixAndRoutePrefixAreProperlyHandled()
<ide> $this->assertSame('pre/{locale}', $route->getPrefix());
<ide> }
<ide>
<add> public function testGroupGenerateNameForDuplicateRouteNamesThatEndWithDot()
<add> {
<add> $this->routeCollection->add($this->newRoute('GET', 'foo', ['uses' => 'FooController@index'])->name('foo.'));
<add> $this->routeCollection->add($route = $this->newRoute('GET', 'bar', ['uses' => 'BarController@index'])->name('foo.'));
<add>
<add> $routes = $this->collection();
<add>
<add> $this->assertSame('BarController@index', $routes->match(Request::create('/bar', 'GET'))->getAction()['uses']);
<add> }
<add>
<ide> public function testRouteBindingsAreProperlySaved()
<ide> {
<ide> $this->routeCollection->add($this->newRoute('GET', 'posts/{post:slug}/show', [ | 2 |
Text | Text | add changelog.md entry for [ci skip] | 723f29c0dd172ae41d710b239e2a000b16aad01a | <ide><path>actionpack/CHANGELOG.md
<add>* Add DSL for configuring Content-Security-Policy header
<add>
<add> The DSL allows you to configure a global Content-Security-Policy
<add> header and then override within a controller. For more information
<add> about the Content-Security-Policy header see MDN:
<add>
<add> https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
<add>
<add> Example global policy:
<add>
<add> # config/initializers/content_security_policy.rb
<add> Rails.application.config.content_security_policy do
<add> p.default_src :self, :https
<add> p.font_src :self, :https, :data
<add> p.img_src :self, :https, :data
<add> p.object_src :none
<add> p.script_src :self, :https
<add> p.style_src :self, :https, :unsafe_inline
<add> end
<add>
<add> Example controller overrides:
<add>
<add> # Override policy inline
<add> class PostsController < ApplicationController
<add> content_security_policy do |p|
<add> p.upgrade_insecure_requests true
<add> end
<add> end
<add>
<add> # Using literal values
<add> class PostsController < ApplicationController
<add> content_security_policy do |p|
<add> p.base_uri "https://www.example.com"
<add> end
<add> end
<add>
<add> # Using mixed static and dynamic values
<add> class PostsController < ApplicationController
<add> content_security_policy do |p|
<add> p.base_uri :self, -> { "https://#{current_user.domain}.example.com" }
<add> end
<add> end
<add>
<add> Allows you to also only report content violations for migrating
<add> legacy content using the `content_security_policy_report_only`
<add> configuration attribute, e.g;
<add>
<add> # config/initializers/content_security_policy.rb
<add> Rails.application.config.content_security_policy_report_only = true
<add>
<add> # controller override
<add> class PostsController < ApplicationController
<add> self.content_security_policy_report_only = true
<add> end
<add>
<add> Note that this feature does not validate the header for performance
<add> reasons since the header is calculated at runtime.
<add>
<add> *Andrew White*
<add>
<ide> * Make `assert_recognizes` to traverse mounted engines
<ide>
<ide> *Yuichiro Kaneko* | 1 |
Text | Text | standardize references to userland | f5a3f44f5c0381d4b0505b4b8ff3df8de6225444 | <ide><path>CHANGELOG.md
<ide> https://iojs.org/api/tls.html
<ide> - Added async session storage events.
<ide> - Added async SNI callback.
<ide> - Added multi-key server support (for example, ECDSA+RSA server).
<del>- Added optional callback to `checkServerIdentity` for manual certificate validation in user-land.
<add>- Added optional callback to `checkServerIdentity` for manual certificate validation in userland.
<ide> - Added support for ECDSA/ECDHE cipher.
<ide> - Implemented TLS streams in C++, boosting their performance.
<ide> - Moved `createCredentials` to `tls` and renamed it to `createSecureContext`.
<ide><path>doc/tsc-meetings/io.js/2015-03-04.md
<ide> Discussion of how we should probably just add more Buffer methods to core.
<ide>
<ide> Bert: there’s another aspect of this. At some point Node was really modern, but we’ve fallen behind. We can’t even get HTTP/2 or web sockets, we’re in trouble.
<ide>
<del>Domenic: we’ve learned a lot over the last few years that pushes us to user-land code instead of in core. But we need to have some things be “official.”
<add>Domenic: we’ve learned a lot over the last few years that pushes us to userland code instead of in core. But we need to have some things be “official.”
<ide>
<ide> Trevor: I would like the infrastructure for HTTP/2 to be similar to HTTP/1, with http-parser etc.
<ide>
<ide> Ben: is there any reason HTTP/2 couldn’t be done in pure JS?
<ide>
<ide> Discussion of http-parser and current HTTP/1 implementation strategy and speed.
<ide>
<del>Bert: I think as a TC what we should say is “we would like to support HTTP/2, but want to see some user-land ideas first.” We don’t need to actually start implementation progress right now.
<add>Bert: I think as a TC what we should say is “we would like to support HTTP/2, but want to see some userland ideas first.” We don’t need to actually start implementation progress right now.
<ide>
<del>Ben: does anyone on the TC want to write a user-land HTTP/2 module?
<add>Ben: does anyone on the TC want to write a userland HTTP/2 module?
<ide>
<ide> Discussion of how Fedor already has a SPDY implementation.
<ide> | 2 |
Javascript | Javascript | fix figtabs sst race | 6ae0b344e5c221657287d1fc1511be520a6f6e58 | <ide><path>Libraries/Types/CoreEventTypes.js
<ide>
<ide> 'use strict';
<ide>
<del>export type Layout = {
<del> x: number,
<del> y: number,
<del> width: number,
<del> height: number,
<del>};
<del>export type LayoutEvent = {
<del> nativeEvent: {
<del> layout: Layout,
<del> },
<del>};
<add>export type Layout = {|
<add> +x: number,
<add> +y: number,
<add> +width: number,
<add> +height: number,
<add>|};
<add>export type LayoutEvent = {|
<add> +nativeEvent: {|
<add> +layout: Layout,
<add> |},
<add> +persist: () => void,
<add>|}; | 1 |
Javascript | Javascript | add support for 404 handling via $route.otherwise | ce7ab3d1ee0e496c4b9838950b56fc1555b5bcf0 | <ide><path>src/services.js
<ide> angularServiceInject('$route', function(location) {
<ide> if (params) extend(route, params);
<ide> dirty++;
<ide> return route;
<add> },
<add>
<add> /**
<add> * @workInProgress
<add> * @ngdoc method
<add> * @name angular.service.$route#otherwise
<add> * @methodOf angular.service.$route
<add> *
<add> * @description
<add> * Sets route definition that will be used on route change when no other route definition
<add> * is matched.
<add> *
<add> * @param {Object} params Mapping information to be assigned to `$route.current`.
<add> */
<add> otherwise: function(params) {
<add> $route.when(null, params);
<ide> }
<ide> };
<ide> function updateRoute(){
<ide> angularServiceInject('$route', function(location) {
<ide> }
<ide> }
<ide> });
<add>
<add> //fallback
<add> if (!childScope && routes[_null]) {
<add> childScope = createScope(parentScope);
<add> $route.current = extend({}, routes[_null], {
<add> scope: childScope,
<add> params: extend({}, location.hashSearch)
<add> });
<add> }
<add>
<add> //fire onChange callbacks
<ide> forEach(onChange, parentScope.$tryEval);
<add>
<ide> if (childScope) {
<ide> childScope.$become($route.current.controller);
<ide> }
<ide> }
<add>
<ide> this.$watch(function(){return dirty + location.hash;}, updateRoute);
<add>
<ide> return $route;
<ide> }, ['$location']);
<ide>
<ide><path>test/servicesSpec.js
<ide> describe("service", function(){
<ide> expect($route.current.controller).toBeUndefined();
<ide> expect(onChangeSpy).toHaveBeenCalled();
<ide> });
<add>
<add> it('should handle unknown routes with "otherwise" route definition', function() {
<add> var scope = angular.scope(),
<add> $location = scope.$service('$location'),
<add> $route = scope.$service('$route'),
<add> onChangeSpy = jasmine.createSpy('onChange');
<add>
<add> function NotFoundCtrl() {this.notFoundProp = 'not found!'}
<add>
<add> $route.when('/foo', {template: 'foo.html'});
<add> $route.otherwise({template: '404.html', controller: NotFoundCtrl});
<add> $route.onChange(onChangeSpy);
<add> expect($route.current).toBeNull();
<add> expect(onChangeSpy).not.toHaveBeenCalled();
<add>
<add> $location.updateHash('/unknownRoute');
<add> scope.$eval();
<add>
<add> expect($route.current.template).toBe('404.html');
<add> expect($route.current.controller).toBe(NotFoundCtrl);
<add> expect($route.current.scope.notFoundProp).toBe('not found!');
<add> expect(onChangeSpy).toHaveBeenCalled();
<add>
<add> onChangeSpy.reset();
<add> $location.updateHash('/foo');
<add> scope.$eval();
<add>
<add> expect($route.current.template).toEqual('foo.html');
<add> expect($route.current.controller).toBeUndefined();
<add> expect($route.current.scope.notFoundProp).toBeUndefined();
<add> expect(onChangeSpy).toHaveBeenCalled();
<add> });
<ide> });
<ide>
<ide> | 2 |
Javascript | Javascript | shorten config name in http benchmark | d3841ec8727cbc69d520fccbd3b95c90a4a6661b | <ide><path>benchmark/http/check_invalid_header_char.js
<ide> const common = require('../common.js');
<ide> const _checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
<ide>
<add>// Put it here so the benchmark result lines will not be super long.
<add>const LONG_AND_INVALID = 'Here is a value that is really a folded header ' +
<add> 'value\r\n this should be supported, but it is not currently';
<add>
<ide> const bench = common.createBenchmark(main, {
<ide> key: [
<ide> // Valid
<ide> const bench = common.createBenchmark(main, {
<ide> 'en-US',
<ide>
<ide> // Invalid
<del> 'Here is a value that is really a folded header value\r\n this should be \
<del> supported, but it is not currently',
<add> 'LONG_AND_INVALID',
<ide> '中文呢', // unicode
<ide> 'foo\nbar',
<ide> '\x7F'
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, key }) {
<add> if (key === 'LONG_AND_INVALID') {
<add> key = LONG_AND_INVALID;
<add> }
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> _checkInvalidHeaderChar(key); | 1 |
Java | Java | extend conditional conversion support | f13e3ad72b813d35d3187394dc53f98a35003c9a | <ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/ConditionalConversion.java
<add>/*
<add> * Copyright 2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.convert.converter;
<add>
<add>import org.springframework.core.convert.TypeDescriptor;
<add>
<add>/**
<add> * Allows a {@link Converter}, {@link GenericConverter} or {@link ConverterFactory} to
<add> * conditionally execute based on attributes of the {@code source} and {@code target}
<add> * {@link TypeDescriptor}.
<add> *
<add> * <p>Often used to selectively match custom conversion logic based on the presence of a
<add> * field or class-level characteristic, such as an annotation or method. For example, when
<add> * converting from a String field to a Date field, an implementation might return
<add> *
<add> * {@code true} if the target field has also been annotated with {@code @DateTimeFormat}.
<add> *
<add> * <p>As another example, when converting from a String field to an {@code Account} field, an
<add> * implementation might return {@code true} if the target Account class defines a
<add> * {@code public static findAccount(String)} method.
<add> *
<add> * @author Keith Donald
<add> * @author Phillip Webb
<add> * @since 3.2
<add> * @see Converter
<add> * @see GenericConverter
<add> * @see ConverterFactory
<add> * @see ConditionalGenericConverter
<add> */
<add>public interface ConditionalConversion {
<add>
<add> /**
<add> * Should the converter from {@code sourceType} to {@code targetType} currently under
<add> * consideration be selected?
<add> *
<add> * @param sourceType the type descriptor of the field we are converting from
<add> * @param targetType the type descriptor of the field we are converting to
<add> * @return true if conversion should be performed, false otherwise
<add> */
<add> boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
<add>}
<ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/ConditionalGenericConverter.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 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 org.springframework.core.convert.TypeDescriptor;
<ide>
<add>
<ide> /**
<del> * A generic converter that conditionally executes.
<del> *
<del> * <p>Applies a rule that determines if a converter between a set of
<del> * {@link #getConvertibleTypes() convertible types} matches given a client request to
<del> * convert between a source field of convertible type S and a target field of convertible type T.
<del> *
<del> * <p>Often used to selectively match custom conversion logic based on the presence of
<del> * a field or class-level characteristic, such as an annotation or method. For example,
<del> * when converting from a String field to a Date field, an implementation might return
<del> * <code>true</code> if the target field has also been annotated with <code>@DateTimeFormat</code>.
<del> *
<del> * <p>As another example, when converting from a String field to an Account field,
<del> * an implementation might return true if the target Account class defines a
<del> * <code>public static findAccount(String)</code> method.
<add> * A {@link GenericConverter} that may conditionally execute based on attributes of the
<add> * {@code source} and {@code target} {@link TypeDescriptor}. See
<add> * {@link ConditionalConversion} for details.
<ide> *
<ide> * @author Keith Donald
<add> * @author Phillip Webb
<ide> * @since 3.0
<add> * @see GenericConverter
<add> * @see ConditionalConversion
<ide> */
<del>public interface ConditionalGenericConverter extends GenericConverter {
<del>
<del> /**
<del> * Should the converter from <code>sourceType</code> to <code>targetType</code>
<del> * currently under consideration be selected?
<del> * @param sourceType the type descriptor of the field we are converting from
<del> * @param targetType the type descriptor of the field we are converting to
<del> * @return true if conversion should be performed, false otherwise
<del> */
<del> boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
<add>public interface ConditionalGenericConverter extends GenericConverter,
<add> ConditionalConversion {
<ide>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/Converter.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 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> * A converter converts a source object of type S to a target of type T.
<ide> * Implementations of this interface are thread-safe and can be shared.
<ide> *
<add> * <p>Implementations may additionally implement {@link ConditionalConversion}.
<add> *
<ide> * @author Keith Donald
<add> * @since 3.0
<add> * @see ConditionalConversion
<ide> * @param <S> The source type
<ide> * @param <T> The target type
<del> * @since 3.0
<ide> */
<ide> public interface Converter<S, T> {
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/ConverterFactory.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 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> * A factory for "ranged" converters that can convert objects from S to subtypes of R.
<ide> *
<add> * <p>Implementations may additionally implement {@link ConditionalConversion}.
<add> *
<ide> * @author Keith Donald
<ide> * @since 3.0
<add> * @see ConditionalConversion
<ide> * @param <S> The source type converters created by this factory can convert from
<ide> * @param <R> The target range (or base) type converters created by this factory can convert to;
<ide> * for example {@link Number} for a set of number subtypes.
<ide><path>spring-core/src/main/java/org/springframework/core/convert/converter/GenericConverter.java
<ide> /*
<del> * Copyright 2002-2011 the original author or authors.
<add> * Copyright 2002-2012 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> * <p>This interface should generally not be used when the simpler {@link Converter} or
<ide> * {@link ConverterFactory} interfaces are sufficient.
<ide> *
<add> * <p>Implementations may additionally implement {@link ConditionalConversion}.
<add> *
<ide> * @author Keith Donald
<ide> * @author Juergen Hoeller
<ide> * @since 3.0
<ide> * @see TypeDescriptor
<ide> * @see Converter
<ide> * @see ConverterFactory
<add> * @see ConditionalConversion
<ide> */
<ide> public interface GenericConverter {
<ide>
<ide> /**
<del> * Return the source and target types which this converter can convert between.
<del> * <p>Each entry is a convertible source-to-target type pair.
<add> * Return the source and target types which this converter can convert between. Each
<add> * entry is a convertible source-to-target type pair.
<add> * <p>
<add> * For {@link ConditionalConversion conditional} converters this method may return
<add> * {@code null} to indicate all source-to-target pairs should be considered. *
<ide> */
<ide> Set<ConvertiblePair> getConvertibleTypes();
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java
<ide> import org.springframework.core.convert.ConversionService;
<ide> import org.springframework.core.convert.ConverterNotFoundException;
<ide> import org.springframework.core.convert.TypeDescriptor;
<add>import org.springframework.core.convert.converter.ConditionalConversion;
<ide> import org.springframework.core.convert.converter.ConditionalGenericConverter;
<ide> import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.convert.converter.ConverterFactory;
<ide> public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
<ide> if(!this.typeInfo.getTargetType().equals(targetType.getObjectType())) {
<ide> return false;
<ide> }
<add> if (this.converter instanceof ConditionalConversion) {
<add> return ((ConditionalConversion) this.converter).matches(sourceType,
<add> targetType);
<add> }
<ide> return true;
<ide> }
<ide>
<ide> public String toString() {
<ide> * Adapts a {@link ConverterFactory} to a {@link GenericConverter}.
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> private final class ConverterFactoryAdapter implements GenericConverter {
<add> private final class ConverterFactoryAdapter implements ConditionalGenericConverter {
<ide>
<ide> private final ConvertiblePair typeInfo;
<ide>
<ide> public Set<ConvertiblePair> getConvertibleTypes() {
<ide> return Collections.singleton(this.typeInfo);
<ide> }
<ide>
<add> public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
<add> boolean matches = true;
<add> if (this.converterFactory instanceof ConditionalConversion) {
<add> matches = ((ConditionalConversion) this.converterFactory).matches(
<add> sourceType, targetType);
<add> }
<add> if(matches) {
<add> Converter<?, ?> converter = converterFactory.getConverter(targetType.getType());
<add> if(converter instanceof ConditionalConversion) {
<add> matches = ((ConditionalConversion) converter).matches(sourceType, targetType);
<add> }
<add> }
<add> return matches;
<add> }
<add>
<ide> public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
<ide> if (source == null) {
<ide> return convertNullSource(sourceType, targetType);
<ide> private static class Converters {
<ide> IGNORED_CLASSES = Collections.unmodifiableSet(ignored);
<ide> }
<ide>
<add> private final Set<GenericConverter> globalConverters =
<add> new LinkedHashSet<GenericConverter>();
<add>
<ide> private final Map<ConvertiblePair, ConvertersForPair> converters =
<ide> new LinkedHashMap<ConvertiblePair, ConvertersForPair>(36);
<ide>
<ide> public void add(GenericConverter converter) {
<ide> Set<ConvertiblePair> convertibleTypes = converter.getConvertibleTypes();
<del> Assert.state(converter.getConvertibleTypes() != null, "Converter does not specifiy ConvertibleTypes");
<del> for (ConvertiblePair convertiblePair : convertibleTypes) {
<del> ConvertersForPair convertersForPair = getMatchableConverters(convertiblePair);
<del> convertersForPair.add(converter);
<add> if (convertibleTypes == null) {
<add> Assert.state(converter instanceof ConditionalConversion,
<add> "Only conditional converters may return null convertible types");
<add> globalConverters.add(converter);
<add> } else {
<add> for (ConvertiblePair convertiblePair : convertibleTypes) {
<add> ConvertersForPair convertersForPair = getMatchableConverters(convertiblePair);
<add> convertersForPair.add(converter);
<add> }
<ide> }
<ide> }
<ide>
<ide> private GenericConverter getRegisteredConverter(TypeDescriptor sourceType, TypeD
<ide> return converter;
<ide> }
<ide>
<add> // Check ConditionalGenericConverter that match all types
<add> for (GenericConverter globalConverter : this.globalConverters) {
<add> if (((ConditionalConversion)globalConverter).matches(
<add> sourceCandidate,
<add> targetCandidate)) {
<add> return globalConverter;
<add> }
<add> }
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java
<ide> import java.util.Collection;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<add>import java.util.Iterator;
<ide> import java.util.LinkedHashMap;
<add>import java.util.LinkedHashSet;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import org.springframework.core.convert.ConversionFailedException;
<ide> import org.springframework.core.convert.ConverterNotFoundException;
<ide> import org.springframework.core.convert.TypeDescriptor;
<add>import org.springframework.core.convert.converter.ConditionalConversion;
<ide> import org.springframework.core.convert.converter.Converter;
<add>import org.springframework.core.convert.converter.ConverterFactory;
<ide> import org.springframework.core.convert.converter.GenericConverter;
<ide> import org.springframework.core.io.DescriptiveResource;
<ide> import org.springframework.core.io.Resource;
<ide> public void removeConvertible() throws Exception {
<ide> conversionService.removeConvertible(String.class, Color.class);
<ide> assertFalse(conversionService.canConvert(String.class, Color.class));
<ide> }
<add>
<add> @Test
<add> public void conditionalConverter() throws Exception {
<add> GenericConversionService conversionService = new GenericConversionService();
<add> MyConditionalConverter converter = new MyConditionalConverter();
<add> conversionService.addConverter(new ColorConverter());
<add> conversionService.addConverter(converter);
<add> assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class));
<add> assertTrue(converter.getMatchAttempts() > 0);
<add> }
<add>
<add> @Test
<add> public void conditionalConverterFactory() throws Exception {
<add> GenericConversionService conversionService = new GenericConversionService();
<add> MyConditionalConverterFactory converter = new MyConditionalConverterFactory();
<add> conversionService.addConverter(new ColorConverter());
<add> conversionService.addConverterFactory(converter);
<add> assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class));
<add> assertTrue(converter.getMatchAttempts() > 0);
<add> assertTrue(converter.getNestedMatchAttempts() > 0);
<add> }
<add>
<add> @Test
<add> public void shouldNotSuportNullConvertibleTypesFromNonConditionalGenericConverter()
<add> throws Exception {
<add> GenericConversionService conversionService = new GenericConversionService();
<add> GenericConverter converter = new GenericConverter() {
<add>
<add> public Set<ConvertiblePair> getConvertibleTypes() {
<add> return null;
<add> }
<add>
<add> public Object convert(Object source, TypeDescriptor sourceType,
<add> TypeDescriptor targetType) {
<add> return null;
<add> }
<add> };
<add> try {
<add> conversionService.addConverter(converter);
<add> fail("Did not throw");
<add> } catch (IllegalStateException e) {
<add> assertEquals("Only conditional converters may return null convertible types", e.getMessage());
<add> }
<add> }
<add>
<add> @Test
<add> public void conditionalConversionForAllTypes() throws Exception {
<add> GenericConversionService conversionService = new GenericConversionService();
<add> MyConditionalGenericConverter converter = new MyConditionalGenericConverter();
<add> conversionService.addConverter(converter);
<add> assertEquals((Integer) 3, conversionService.convert(3, Integer.class));
<add> Iterator<TypeDescriptor> iterator = converter.getSourceTypes().iterator();
<add> assertEquals(Integer.class, iterator.next().getType());
<add> assertEquals(Number.class, iterator.next().getType());
<add> TypeDescriptor last = null;
<add> while (iterator.hasNext()) {
<add> last = iterator.next();
<add> }
<add> assertEquals(Object.class, last.getType());
<add> }
<add>
<add> private static class MyConditionalConverter implements Converter<String, Color>,
<add> ConditionalConversion {
<add>
<add> private int matchAttempts = 0;
<add>
<add> public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
<add> matchAttempts++;
<add> return false;
<add> }
<add>
<add> public Color convert(String source) {
<add> throw new IllegalStateException();
<add> }
<add>
<add> public int getMatchAttempts() {
<add> return matchAttempts;
<add> }
<add> }
<add>
<add> private static class MyConditionalGenericConverter implements GenericConverter,
<add> ConditionalConversion {
<add>
<add> private Set<TypeDescriptor> sourceTypes = new LinkedHashSet<TypeDescriptor>();
<add>
<add> public Set<ConvertiblePair> getConvertibleTypes() {
<add> return null;
<add> }
<add>
<add> public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
<add> sourceTypes.add(sourceType);
<add> return false;
<add> }
<add>
<add> public Object convert(Object source, TypeDescriptor sourceType,
<add> TypeDescriptor targetType) {
<add> return null;
<add> }
<add>
<add> public Set<TypeDescriptor> getSourceTypes() {
<add> return sourceTypes;
<add> }
<add> }
<add>
<add> private static class MyConditionalConverterFactory implements
<add> ConverterFactory<String, Color>, ConditionalConversion {
<add>
<add> private MyConditionalConverter converter = new MyConditionalConverter();
<add>
<add> private int matchAttempts = 0;
<add>
<add> public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
<add> matchAttempts++;
<add> return true;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> public <T extends Color> Converter<String, T> getConverter(Class<T> targetType) {
<add> return (Converter<String, T>) converter;
<add> }
<add>
<add> public int getMatchAttempts() {
<add> return matchAttempts;
<add> }
<add>
<add> public int getNestedMatchAttempts() {
<add> return converter.getMatchAttempts();
<add> }
<add> }
<add>
<ide> } | 7 |
Javascript | Javascript | remove unused variables from https tests | fd395ba5c9924168880d212bb7b9bd02ceee45f5 | <ide><path>test/parallel/test-https-agent-disable-session-reuse.js
<ide> if (!common.hasCrypto) {
<ide> const TOTAL_REQS = 2;
<ide>
<ide> const https = require('https');
<del>const crypto = require('crypto');
<ide>
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-agent-servername.js
<ide> 'use strict';
<ide> var common = require('../common');
<del>var assert = require('assert');
<ide>
<ide> if (!common.hasCrypto) {
<ide> console.log('1..0 # Skipped: missing crypto');
<ide><path>test/parallel/test-https-byteswritten.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var fs = require('fs');
<del>var http = require('http');
<ide>
<ide> if (!common.hasCrypto) {
<ide> console.log('1..0 # Skipped: missing crypto');
<ide><path>test/parallel/test-https-eof-for-eom.js
<ide> var bodyBuffer = '';
<ide>
<ide> server.listen(common.PORT, function() {
<ide> console.log('1) Making Request');
<del> var req = https.get({
<add> https.get({
<ide> port: common.PORT,
<ide> rejectUnauthorized: false
<ide> }, function(res) {
<ide><path>test/parallel/test-https-localaddress-bind-error.js
<ide> var server = https.createServer(options, function(req, res) {
<ide> });
<ide>
<ide> server.listen(common.PORT, '127.0.0.1', function() {
<del> var req = https.request({
<add> https.request({
<ide> host: 'localhost',
<ide> port: common.PORT,
<ide> path: '/',
<ide><path>test/parallel/test-https-socket-options.js
<ide> 'use strict';
<ide> var common = require('../common');
<del>var assert = require('assert');
<ide>
<ide> if (!common.hasCrypto) {
<ide> console.log('1..0 # Skipped: missing crypto');
<ide> if (!common.hasCrypto) {
<ide> var https = require('https');
<ide>
<ide> var fs = require('fs');
<del>var exec = require('child_process').exec;
<ide>
<ide> var http = require('http');
<ide>
<ide><path>test/parallel/test-https-strict.js
<ide> function makeReq(path, port, error, host, ca) {
<ide> path: path,
<ide> ca: ca
<ide> };
<del> var whichCa = 0;
<add>
<ide> if (!ca) {
<ide> options.agent = agent0;
<ide> } else {
<ide><path>test/parallel/test-https-timeout-server-2.js
<ide> if (!common.hasCrypto) {
<ide> }
<ide> var https = require('https');
<ide>
<del>var net = require('net');
<ide> var tls = require('tls');
<ide> var fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-timeout-server.js
<ide> if (!common.hasCrypto) {
<ide> var https = require('https');
<ide>
<ide> var net = require('net');
<del>var tls = require('tls');
<ide> var fs = require('fs');
<ide>
<ide> var clientErrors = 0;
<ide><path>test/parallel/test-https-timeout.js
<ide> 'use strict';
<ide> var common = require('../common');
<del>var assert = require('assert');
<ide>
<ide> if (!common.hasCrypto) {
<ide> console.log('1..0 # Skipped: missing crypto');
<ide> if (!common.hasCrypto) {
<ide> var https = require('https');
<ide>
<ide> var fs = require('fs');
<del>var exec = require('child_process').exec;
<ide>
<ide> var options = {
<ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<ide><path>test/parallel/test-https-truncate.js
<ide> if (!common.hasCrypto) {
<ide> var https = require('https');
<ide>
<ide> var fs = require('fs');
<del>var path = require('path');
<ide>
<ide> var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem');
<ide> var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); | 11 |
Javascript | Javascript | remove tests for jquery events | d0dc039a5d0bee7a1bbef0ab478fb13a0135cf15 | <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/input-angle-test.js
<del>import { RenderingTestCase, moduleFor, runDestroy, runTask } from 'internal-test-helpers';
<add>import { moduleFor, RenderingTestCase, runDestroy, runTask } from 'internal-test-helpers';
<ide> import { EMBER_MODERNIZED_BUILT_IN_COMPONENTS } from '@ember/canary-features';
<ide> import { action } from '@ember/object';
<ide> import { Checkbox, TextArea, TextField } from '@ember/-internals/glimmer';
<ide> import { set } from '@ember/-internals/metal';
<ide> import { TargetActionSupport } from '@ember/-internals/runtime';
<del>import { getElementView, jQueryDisabled, jQuery, TextSupport } from '@ember/-internals/views';
<add>import { getElementView, TextSupport } from '@ember/-internals/views';
<ide>
<ide> import { Component } from '../../utils/helpers';
<ide>
<ide> moduleFor(
<ide>
<ide> this.render(`<Input @enter={{action 'foo'}} />`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> value: 'initial',
<ide>
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> triggered++;
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide>
<ide> this.render(`<Input @insert-newline={{action 'foo'}} />`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide>
<ide> this.render(`<Input @escape-press={{action 'foo'}} />`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> () => {
<ide> this.render(`<Input @key-down={{action 'foo'}} />`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> triggered++;
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> () => {
<ide> this.render(`<Input @key-up={{action 'foo'}} />`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> triggered++;
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide><path>packages/@ember/-internals/glimmer/tests/integration/components/input-curly-test.js
<ide> import { RenderingTestCase, moduleFor, runDestroy, runTask } from 'internal-test
<ide> import { EMBER_MODERNIZED_BUILT_IN_COMPONENTS } from '@ember/canary-features';
<ide> import { action } from '@ember/object';
<ide> import { set } from '@ember/-internals/metal';
<del>import { jQueryDisabled, jQuery } from '@ember/-internals/views';
<ide>
<ide> import { Component } from '../../utils/helpers';
<ide>
<ide> moduleFor(
<ide>
<ide> this.render(`{{input enter=(action 'foo')}}`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> value: 'initial',
<ide>
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> triggered++;
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide>
<ide> this.render(`{{input insert-newline=(action 'foo')}}`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide>
<ide> this.render(`{{input escape-press=(action 'foo')}}`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> () => {
<ide> this.render(`{{input key-down=(action 'foo')}}`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> triggered++;
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> });
<ide> moduleFor(
<ide> () => {
<ide> this.render(`{{input key-up=(action 'foo')}}`, {
<ide> actions: {
<del> foo(value, event) {
<add> foo() {
<ide> assert.ok(true, 'action was triggered');
<del> if (jQueryDisabled) {
<del> assert.notOk(event.originalEvent, 'event is not a jQuery.Event');
<del> } else {
<del> assert.ok(event instanceof jQuery.Event, 'jQuery event was passed');
<del> }
<ide> },
<ide> },
<ide> }); | 2 |
Text | Text | move code not working? section back to readme.md | b4d4c19d055528329962e1903df4ae6be7c3f0c4 | <ide><path>README.md
<ide> Welcome to Free Code Camp's open source codebase and curriculum!
<ide>
<ide> Free Code Camp is an open-source community where you learn to code and help nonprofits.
<ide>
<del>You start by working through our self-paced, browser-based full stack JavaScript curriculum.
<add>You start by working through our self-paced, browser-based full stack JavaScript curriculum.
<ide>
<ide> After you complete the first 400 hours worth of challenges (which involves building 10 single-page apps), you'll earn your Front End Development Certification.
<ide>
<ide> Wiki
<ide>
<ide> We would love your help expanding our [wiki](https://github.com/freecodecamp/freecodecamp/wiki). Our goal is to become a great resource for people learning to code, building local coding communities, and applying for coding jobs.
<ide>
<add>Found a bug?
<add>------------
<add>
<add>Do not file an issue until you have followed these steps:
<add>
<add>1. Read [Help I've Found a Bug](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-I've-Found-a-Bug) wiki page and follow the instructions there.
<add>2. Asked for confirmation in the appropriate [Help Room](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-Rooms)
<add>3. Please *do not* open an issue without a 3rd party confirmation of your problem.
<add>
<ide> Contributing
<ide> ------------
<ide> | 1 |
Python | Python | add default name to emr serverless jobs | 2ef15c5da0261a8b519913db4a0d0c3773a91e96 | <ide><path>airflow/providers/amazon/aws/operators/emr.py
<ide> class EmrServerlessStartJobOperator(BaseOperator):
<ide> Its value must be unique for each request.
<ide> :param config: Optional dictionary for arbitrary parameters to the boto API start_job_run call.
<ide> :param wait_for_completion: If true, waits for the job to start before returning. Defaults to True.
<del> :param aws_conn_id: AWS connection to use
<add> :param aws_conn_id: AWS connection to use.
<add> :param name: Name for the EMR Serverless job. If not provided, a default name will be assigned.
<ide> """
<ide>
<ide> template_fields: Sequence[str] = (
<ide> def __init__(
<ide> config: dict | None = None,
<ide> wait_for_completion: bool = True,
<ide> aws_conn_id: str = "aws_default",
<add> name: str | None = None,
<ide> **kwargs,
<ide> ):
<ide> self.aws_conn_id = aws_conn_id
<ide> def __init__(
<ide> self.configuration_overrides = configuration_overrides
<ide> self.wait_for_completion = wait_for_completion
<ide> self.config = config or {}
<add> self.name = name or self.config.pop("name", f"emr_serverless_job_airflow_{uuid4()}")
<ide> super().__init__(**kwargs)
<ide>
<ide> self.client_request_token = client_request_token or str(uuid4())
<ide> def execute(self, context: Context) -> dict:
<ide> executionRoleArn=self.execution_role_arn,
<ide> jobDriver=self.job_driver,
<ide> configurationOverrides=self.configuration_overrides,
<add> name=self.name,
<ide> **self.config,
<ide> )
<ide>
<ide><path>tests/providers/amazon/aws/operators/test_emr_serverless.py
<ide> def test_job_run_app_started(self, mock_conn):
<ide> job_driver=job_driver,
<ide> configuration_overrides=configuration_overrides,
<ide> )
<del>
<add> default_name = operator.name
<ide> id = operator.execute(None)
<ide>
<ide> assert operator.wait_for_completion is True
<ide> def test_job_run_app_started(self, mock_conn):
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide> mock_conn.get_job_run.assert_called_once_with(applicationId=application_id, jobRunId=job_run_id)
<ide>
<ide> def test_job_run_job_failed(self, mock_conn):
<ide> job_driver=job_driver,
<ide> configuration_overrides=configuration_overrides,
<ide> )
<add> default_name = operator.name
<ide> with pytest.raises(AirflowException) as ex_message:
<ide> id = operator.execute(None)
<ide> assert id == job_run_id
<ide> def test_job_run_job_failed(self, mock_conn):
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide>
<ide> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.waiter")
<ide> def test_job_run_app_not_started(self, mock_conn, mock_waiter):
<ide> job_driver=job_driver,
<ide> configuration_overrides=configuration_overrides,
<ide> )
<add> default_name = operator.name
<ide>
<ide> id = operator.execute(None)
<ide>
<ide> def test_job_run_app_not_started(self, mock_conn, mock_waiter):
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide>
<ide> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.conn")
<ide> def test_job_run_app_not_started_no_wait_for_completion(self, mock_conn, mock_wa
<ide> configuration_overrides=configuration_overrides,
<ide> wait_for_completion=False,
<ide> )
<del>
<add> default_name = operator.name
<ide> id = operator.execute(None)
<ide>
<ide> mock_conn.get_application.assert_called_once_with(applicationId=application_id)
<ide> def test_job_run_app_not_started_no_wait_for_completion(self, mock_conn, mock_wa
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide>
<ide> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.waiter")
<ide> def test_job_run_app_started_no_wait_for_completion(self, mock_conn, mock_waiter
<ide> configuration_overrides=configuration_overrides,
<ide> wait_for_completion=False,
<ide> )
<del>
<add> default_name = operator.name
<ide> id = operator.execute(None)
<ide> assert id == job_run_id
<ide> mock_conn.start_job_run.assert_called_once_with(
<ide> def test_job_run_app_started_no_wait_for_completion(self, mock_conn, mock_waiter
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide> assert not mock_waiter.called
<ide>
<ide> def test_failed_start_job_run(self, mock_conn, mock_waiter):
<ide> job_driver=job_driver,
<ide> configuration_overrides=configuration_overrides,
<ide> )
<add> default_name = operator.name
<ide> with pytest.raises(AirflowException) as ex_message:
<ide> operator.execute(None)
<ide>
<ide> def test_failed_start_job_run(self, mock_conn, mock_waiter):
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<ide> )
<ide>
<ide> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.conn")
<ide> def test_start_job_run_fail_on_wait_for_completion(self, mock_conn):
<ide> job_driver=job_driver,
<ide> configuration_overrides=configuration_overrides,
<ide> )
<add> default_name = operator.name
<ide> with pytest.raises(AirflowException) as ex_message:
<ide> operator.execute(None)
<ide>
<ide> def test_start_job_run_fail_on_wait_for_completion(self, mock_conn):
<ide> executionRoleArn=execution_role_arn,
<ide> jobDriver=job_driver,
<ide> configurationOverrides=configuration_overrides,
<add> name=default_name,
<add> )
<add>
<add> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.conn")
<add> def test_start_job_default_name(self, mock_conn):
<add> mock_conn.get_application.return_value = {"application": {"state": "STARTED"}}
<add> mock_conn.start_job_run.return_value = {
<add> "jobRunId": job_run_id,
<add> "ResponseMetadata": {"HTTPStatusCode": 200},
<add> }
<add> mock_conn.get_job_run.return_value = {"jobRun": {"state": "SUCCESS"}}
<add>
<add> operator = EmrServerlessStartJobOperator(
<add> task_id=task_id,
<add> client_request_token=client_request_token,
<add> application_id=application_id,
<add> execution_role_arn=execution_role_arn,
<add> job_driver=job_driver,
<add> configuration_overrides=configuration_overrides,
<add> )
<add> operator.execute(None)
<add> default_name = operator.name
<add> generated_name_uuid = default_name.split("_")[-1]
<add> assert default_name.startswith("emr_serverless_job_airflow")
<add>
<add> mock_conn.start_job_run.assert_called_once_with(
<add> clientToken=client_request_token,
<add> applicationId=application_id,
<add> executionRoleArn=execution_role_arn,
<add> jobDriver=job_driver,
<add> configurationOverrides=configuration_overrides,
<add> name=f"emr_serverless_job_airflow_{str(UUID(generated_name_uuid, version=4))}",
<add> )
<add>
<add> @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrServerlessHook.conn")
<add> def test_start_job_custom_name(self, mock_conn):
<add> mock_conn.get_application.return_value = {"application": {"state": "STARTED"}}
<add> custom_name = "test_name"
<add> mock_conn.start_job_run.return_value = {
<add> "jobRunId": job_run_id,
<add> "ResponseMetadata": {"HTTPStatusCode": 200},
<add> }
<add> mock_conn.get_job_run.return_value = {"jobRun": {"state": "SUCCESS"}}
<add>
<add> operator = EmrServerlessStartJobOperator(
<add> task_id=task_id,
<add> client_request_token=client_request_token,
<add> application_id=application_id,
<add> execution_role_arn=execution_role_arn,
<add> job_driver=job_driver,
<add> configuration_overrides=configuration_overrides,
<add> name=custom_name,
<add> )
<add> operator.execute(None)
<add>
<add> mock_conn.start_job_run.assert_called_once_with(
<add> clientToken=client_request_token,
<add> applicationId=application_id,
<add> executionRoleArn=execution_role_arn,
<add> jobDriver=job_driver,
<add> configurationOverrides=configuration_overrides,
<add> name=custom_name,
<ide> )
<ide>
<ide> | 2 |
Ruby | Ruby | use double quotes | 289e3b90728cacdb96d61e721b30de566a0a8134 | <ide><path>ci/ci_build.rb
<ide>
<ide> # for now, use the no-passwd sudoers approach (documented in ci_setup_notes.txt)
<ide> # A security hole, but there is nothing valuable on rails CI box anyway.
<del>build_results[:geminstaller] = system 'sudo geminstaller --config=#{root_dir}/ci/geminstaller.yml --exceptions'
<add>build_results[:geminstaller] = system "sudo geminstaller --config=#{root_dir}/ci/geminstaller.yml --exceptions"
<ide>
<ide> cd "#{root_dir}/activesupport" do
<ide> puts | 1 |
PHP | PHP | remove unused code and correct doc for modelclass | db9c3e5bf39113710910787997549b6c6e81f852 | <ide><path>lib/Cake/Controller/Controller.php
<ide> class Controller extends Object implements CakeEventListener {
<ide> public $methods = array();
<ide>
<ide> /**
<del> * This controller's primary model class name, the Inflector::classify()'ed version of
<add> * This controller's primary model class name, the Inflector::singularize()'ed version of
<ide> * the controller's $name property.
<ide> *
<ide> * Example: For a controller named 'Comments', the modelClass would be 'Comment'
<ide> public function __isset($name) {
<ide> foreach ($this->uses as $modelClass) {
<ide> list($plugin, $class) = pluginSplit($modelClass, true);
<ide> if ($name === $class) {
<del> if (!$plugin) {
<del> $plugin = $this->plugin ? $this->plugin . '.' : null;
<del> }
<ide> return $this->loadModel($modelClass);
<ide> }
<ide> } | 1 |
Text | Text | add missing word in 'field.allow_null' docs | 5fc35eb7eb1ce8ca91fa6364978b5e423b80a332 | <ide><path>docs/api-guide/fields.md
<ide> Defaults to `True`.
<ide>
<ide> Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value.
<ide>
<del>Note that setting this argument to `True` will imply a default value of `null` for serialization output, but does imply a default for input deserialization.
<add>Note that setting this argument to `True` will imply a default value of `null` for serialization output, but does not imply a default for input deserialization.
<ide>
<ide> Defaults to `False`
<ide> | 1 |
Go | Go | handle external network when deploying | 6fff8454099092780655e8a2c7d71402ce547c5c | <ide><path>cli/command/stack/common.go
<ide> func getServices(
<ide> types.ServiceListOptions{Filters: getStackFilter(namespace)})
<ide> }
<ide>
<del>func getNetworks(
<add>func getStackNetworks(
<ide> ctx context.Context,
<ide> apiclient client.APIClient,
<ide> namespace string,
<ide><path>cli/command/stack/deploy.go
<ide> import (
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<ide> servicecmd "github.com/docker/docker/cli/command/service"
<add> dockerclient "github.com/docker/docker/client"
<ide> "github.com/docker/docker/opts"
<ide> runconfigopts "github.com/docker/docker/runconfig/opts"
<ide> "github.com/docker/go-connections/nat"
<ide> func deployCompose(ctx context.Context, dockerCli *command.DockerCli, opts deplo
<ide>
<ide> namespace := namespace{name: opts.namespace}
<ide>
<del> networks := convertNetworks(namespace, config.Networks)
<add> networks, externalNetworks := convertNetworks(namespace, config.Networks)
<add> if err := validateExternalNetworks(ctx, dockerCli, externalNetworks); err != nil {
<add> return err
<add> }
<ide> if err := createNetworks(ctx, dockerCli, namespace, networks); err != nil {
<ide> return err
<ide> }
<ide> func getConfigFile(filename string) (*composetypes.ConfigFile, error) {
<ide> func convertNetworks(
<ide> namespace namespace,
<ide> networks map[string]composetypes.NetworkConfig,
<del>) map[string]types.NetworkCreate {
<add>) (map[string]types.NetworkCreate, []string) {
<ide> if networks == nil {
<ide> networks = make(map[string]composetypes.NetworkConfig)
<ide> }
<ide>
<ide> // TODO: only add default network if it's used
<ide> networks["default"] = composetypes.NetworkConfig{}
<ide>
<add> externalNetworks := []string{}
<ide> result := make(map[string]types.NetworkCreate)
<ide>
<ide> for internalName, network := range networks {
<del> if network.External.Name != "" {
<add> if network.External.External {
<add> externalNetworks = append(externalNetworks, network.External.Name)
<ide> continue
<ide> }
<ide>
<ide> func convertNetworks(
<ide> result[internalName] = createOpts
<ide> }
<ide>
<del> return result
<add> return result, externalNetworks
<add>}
<add>
<add>func validateExternalNetworks(
<add> ctx context.Context,
<add> dockerCli *command.DockerCli,
<add> externalNetworks []string) error {
<add> client := dockerCli.Client()
<add>
<add> for _, networkName := range externalNetworks {
<add> network, err := client.NetworkInspect(ctx, networkName)
<add> if err != nil {
<add> if dockerclient.IsErrNetworkNotFound(err) {
<add> return fmt.Errorf("network %q is declared as external, but could not be found. You need to create the network before the stack is deployed (with overlay driver)", networkName)
<add> }
<add> return err
<add> }
<add> if network.Scope != "swarm" {
<add> return fmt.Errorf("network %q is declared as external, but it is not in the right scope: %q instead of %q", networkName, network.Scope, "swarm")
<add> }
<add> }
<add>
<add> return nil
<ide> }
<ide>
<ide> func createNetworks(
<ide> func createNetworks(
<ide> ) error {
<ide> client := dockerCli.Client()
<ide>
<del> existingNetworks, err := getNetworks(ctx, client, namespace.name)
<add> existingNetworks, err := getStackNetworks(ctx, client, namespace.name)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func createNetworks(
<ide>
<ide> func convertServiceNetworks(
<ide> networks map[string]*composetypes.ServiceNetworkConfig,
<add> networkConfigs map[string]composetypes.NetworkConfig,
<ide> namespace namespace,
<ide> name string,
<del>) []swarm.NetworkAttachmentConfig {
<add>) ([]swarm.NetworkAttachmentConfig, error) {
<ide> if len(networks) == 0 {
<ide> return []swarm.NetworkAttachmentConfig{
<ide> {
<ide> Target: namespace.scope("default"),
<ide> Aliases: []string{name},
<ide> },
<del> }
<add> }, nil
<ide> }
<ide>
<ide> nets := []swarm.NetworkAttachmentConfig{}
<ide> for networkName, network := range networks {
<add> networkConfig, ok := networkConfigs[networkName]
<add> if !ok {
<add> return []swarm.NetworkAttachmentConfig{}, fmt.Errorf("invalid network: %s", networkName)
<add> }
<ide> var aliases []string
<ide> if network != nil {
<ide> aliases = network.Aliases
<ide> }
<add> target := namespace.scope(networkName)
<add> if networkConfig.External.External {
<add> target = networkName
<add> }
<ide> nets = append(nets, swarm.NetworkAttachmentConfig{
<del> Target: namespace.scope(networkName),
<add> Target: target,
<ide> Aliases: append(aliases, name),
<ide> })
<ide> }
<del> return nets
<add> return nets, nil
<ide> }
<ide>
<ide> func convertVolumes(
<ide> func convertServices(
<ide>
<ide> services := config.Services
<ide> volumes := config.Volumes
<add> networks := config.Networks
<ide>
<ide> for _, service := range services {
<del> serviceSpec, err := convertService(namespace, service, volumes)
<add> serviceSpec, err := convertService(namespace, service, networks, volumes)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func convertServices(
<ide> func convertService(
<ide> namespace namespace,
<ide> service composetypes.ServiceConfig,
<add> networkConfigs map[string]composetypes.NetworkConfig,
<ide> volumes map[string]composetypes.VolumeConfig,
<ide> ) (swarm.ServiceSpec, error) {
<ide> name := namespace.scope(service.Name)
<ide> func convertService(
<ide> return swarm.ServiceSpec{}, err
<ide> }
<ide>
<add> networks, err := convertServiceNetworks(service.Networks, networkConfigs, namespace, service.Name)
<add> if err != nil {
<add> return swarm.ServiceSpec{}, err
<add> }
<add>
<ide> serviceSpec := swarm.ServiceSpec{
<ide> Annotations: swarm.Annotations{
<ide> Name: name,
<ide> func convertService(
<ide> },
<ide> EndpointSpec: endpoint,
<ide> Mode: mode,
<del> Networks: convertServiceNetworks(service.Networks, namespace, service.Name),
<add> Networks: networks,
<ide> UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
<ide> }
<ide>
<ide><path>cli/command/stack/remove.go
<ide> func runRemove(dockerCli *command.DockerCli, opts removeOptions) error {
<ide> }
<ide> }
<ide>
<del> networks, err := getNetworks(ctx, client, namespace)
<add> networks, err := getStackNetworks(ctx, client, namespace)
<ide> if err != nil {
<ide> return err
<ide> } | 3 |
Javascript | Javascript | replace fixturesdir with usage of fixtures module | fb31e074503145302acaaec49bbf779fdf067d83 | <ide><path>test/parallel/test-tls-ecdh-disable.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<add>// Test that the usage of eliptic curves are not permitted if disabled during
<add>// server initialization.
<add>
<ide> 'use strict';
<ide> const common = require('../common');
<add>const { readKey } = require('../common/fixtures');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> if (!common.opensslCli)
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> const exec = require('child_process').exec;
<del>const fs = require('fs');
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`),
<add> key: readKey('agent2-key.pem'),
<add> cert: readKey('agent2-cert.pem'),
<ide> ciphers: 'ECDHE-RSA-AES128-SHA',
<ide> ecdhCurve: false
<ide> }; | 1 |
PHP | PHP | clarify invalid connection message | 61c887fddd6706208be16da5e3e7f3a2ddf95953 | <ide><path>src/Illuminate/Database/DatabaseManager.php
<ide> protected function configuration($name)
<ide> $connections = $this->app['config']['database.connections'];
<ide>
<ide> if (is_null($config = Arr::get($connections, $name))) {
<del> throw new InvalidArgumentException("Database [{$name}] not configured.");
<add> throw new InvalidArgumentException("Database connection [{$name}] not configured.");
<ide> }
<ide>
<ide> return (new ConfigurationUrlParser) | 1 |
Text | Text | fix arch build instructions | 3a3e4c1eb9e05a4c4ad34f7e7a6d0712afddb252 | <ide><path>docs/build-instructions/linux.md
<ide> Ubuntu LTS 12.04 64-bit is the recommended platform.
<ide> ### Arch
<ide>
<ide> * `sudo pacman -S gconf base-devel git nodejs libgnome-keyring python2`
<del>* `export python=/usr/bin/python2` before building Atom.
<add>* `export PYTHON=/usr/bin/python2` before building Atom.
<ide>
<ide> ### Slackware
<ide> | 1 |
PHP | PHP | implement a warning for large cookies | 1f92036673ff4f66e4ff0b79a223d332f942e44f | <ide><path>src/Http/Cookie/CookieCollection.php
<ide> public function addToRequest(RequestInterface $request, array $extraCookies = []
<ide> $cookies = array_merge($cookies, $extraCookies);
<ide> $cookiePairs = [];
<ide> foreach ($cookies as $key => $value) {
<del> $cookiePairs[] = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
<add> $cookie = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
<add> $size = mb_strlen($cookie);
<add> if ($size > 4096) {
<add> triggerWarning(sprintf(
<add> 'The cookie `%s` exceeds the recommended maximum cookie length of 4096 bytes.',
<add> $key
<add> ));
<add> }
<add> $cookiePairs[] = $cookie;
<ide> }
<add>
<ide> if (empty($cookiePairs)) {
<ide> return $request;
<ide> }
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> public function testAddToRequestNoCookies()
<ide> $this->assertFalse($request->hasHeader('Cookie'), 'No header should be set.');
<ide> }
<ide>
<add> /**
<add> * Testing the cookie size limit warning
<add> *
<add> * @expectedException \PHPUnit\Framework\Error\Warning
<add> * @expectedExceptionMessage The cookie `default` exceeds the recommended maximum cookie length of 4096 bytes.
<add> * @return void
<add> */
<add> public function testCookieSizeWarning()
<add> {
<add> $collection = new CookieCollection();
<add> $collection = $collection
<add> ->add(new Cookie('default', random_bytes(9000), null, '/', 'example.com'));
<add> $request = new ClientRequest('http://example.com/api');
<add> $collection->addToRequest($request);
<add> }
<add>
<ide> /**
<ide> * Test adding cookies from the collection to request.
<ide> * | 2 |
Javascript | Javascript | fix bugs in humanize and asyears | bcda4cf0c040047acd85bfe4864e6aead598eb38 | <ide><path>moment.js
<ide> years === 1 && ['y'] || ['yy', years];
<ide>
<ide> args[2] = withoutSuffix;
<del> args[3] = +msOrDuration > 0;
<add> args[3] = +posNegDuration > 0;
<ide> args[4] = lang;
<ide> return substituteTimeAgo.apply({}, args);
<ide> }
<ide> moment.duration.fn.asDays = function () { return this.as('d'); };
<ide> moment.duration.fn.asWeeks = function () { return this.as('weeks'); };
<ide> moment.duration.fn.asMonths = function () { return this.as('M'); };
<del> moment.duration.fn.asYears = function () { return this.as('Y'); };
<add> moment.duration.fn.asYears = function () { return this.as('y'); };
<ide>
<ide> /************************************
<ide> Default Lang | 1 |
Text | Text | update korean translation to 5275244 | 6f434b35ade6a6ac776f9469aeadcd134f2bc4b1 | <ide><path>docs/docs/02-displaying-data.ko-KR.md
<ide> setInterval(function() {
<ide>
<ide> ## 컴포넌트들은 함수와 같습니다
<ide>
<del>React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props` 와 `state` (이것들은 나중에 언급할 것입니다) 를 받고 HTML을 렌더링하는 단순한 함수들로 생각해도 됩니다. 그것들은 너무 단순하기 때문에, 그것들의 작동을 이해하는 것 또한 쉽게 만듭니다.
<add>React 컴포넌트들은 매우 단순합니다. 당신은 그것들을 `props` 와 `state` (이것들은 나중에 언급할 것입니다) 를 받고 HTML을 렌더링하는 단순한 함수들로 생각해도 됩니다. 이걸 염두하면, 컴포넌트의 작동을 이해하는 것도 쉽습니다.
<ide>
<ide> > 주의:
<ide> >
<ide><path>docs/docs/02.2-jsx-spread.ko-KR.md
<ide> next: jsx-gotchas-ko-KR.html
<ide>
<ide> 이것은 안티 패턴입니다. 왜냐하면 한참 뒤까지 정확한 propTypes을 체크할 수 없다는 뜻이기 때문입니다. 이것은 propTypes 에러는 알기 힘든 스택 트레이스로 끝난다는 의미입니다.
<ide>
<del>이 시점에서 props는 불변성인 것을 고려해야 합니다. props 객체를 변경하는 것은 다른 곳에서 예기치 못한 결과가 생길 수 있기 때문에 이상적으로는 이 시점에서 frozen 객체가 되어야 합니다.
<add>props는 변하지 않는 것으로 간주해야 합니다. props 객체를 변경하는 것은 다른 곳에서 예기치 못한 결과가 생길 수 있기 때문에 이상적으로는 이 시점에서 frozen 객체가 되어야 합니다.
<ide>
<ide> ## 스프레드 어트리뷰트
<ide>
<ide><path>docs/docs/04-multiple-components.ko-KR.md
<ide> React에서 데이터는 위에서 말한 것처럼 `props`를 통해 소유자
<ide>
<ide> ## 성능의 주의점
<ide>
<del>소유자가 가지고 있는 노드의 수가 많아지면 데이터의 변화에 반응하는 비용이 증가할 것으로 생각할 수도 있습니다. 좋은 소식은 JavaScript의 속도는 빠르고 `render()` 메소드는 꽤 간단한 경향이 있어, 대부분 애플리케이션에서 매우 빠르다는 점입니다. 덧붙여, 대부분의 병목 현상은 JS 실행이 아닌 DOM 변경에서 일어나고, React는 배치와 탐지 변경을 이용해 최적화해 줍니다.
<add>소유자가 가지고 있는 노드의 수가 많아지면 데이터가 변화하는 비용이 증가할 것으로 생각할 수도 있습니다. 좋은 소식은 JavaScript의 속도는 빠르고 `render()` 메소드는 꽤 간단한 경향이 있어, 대부분 애플리케이션에서 매우 빠르다는 점입니다. 덧붙여, 대부분의 병목 현상은 JS 실행이 아닌 DOM 변경에서 일어나고, React는 배치와 탐지 변경을 이용해 최적화해 줍니다.
<ide>
<ide> 하지만, 가끔 성능을 위해 정교하게 제어해야 할 때도 있습니다. 이런 경우, React가 서브트리의 처리를 건너 뛰도록 간단히 `shouldComponentUpdate()`를 오버라이드해 false를 리턴하게 할 수 있습니다. 좀 더 자세한 정보는 [React 참조 문서](/react/docs/component-specs-ko-KR.html)를 보세요.
<ide>
<ide><path>docs/docs/05-reusable-components.ko-KR.md
<ide> prev: multiple-components-ko-KR.html
<ide> next: transferring-props-ko-KR.html
<ide> ---
<ide>
<del>인터페이스를 설계할 때, 공통적으로 사용되는 디자인 요소들(버튼, 폼 필드, 레이아웃 컴포넌트 등)을 잘 정의된 인터페이스의 재사용 가능한 컴포넌트로 분해합니다. 이런 방법으로 다음에 UI를 구축할 때에는 훨씬 적은 코드로 만들 수 있습니다. 이 말은 더 빠른 개발 시간, 더 적은 버그, 더 적은 용량으로 할 수 있다는 뜻이죠.
<add>인터페이스를 설계할 때, 공통적으로 사용되는 디자인 요소들(버튼, 폼 필드, 레이아웃 컴포넌트 등.)을 잘 정의된 인터페이스의 재사용 가능한 컴포넌트로 분해합니다. 이런 방법으로 다음에 UI를 구축할 때에는 훨씬 적은 코드로 만들 수 있습니다. 이 말은 더 빠른 개발 시간, 더 적은 버그, 더 적은 용량으로 할 수 있다는 뜻이죠.
<ide>
<ide>
<ide> ## Prop 검증
<ide> Counter.defaultProps = { initialCount: 0 };
<ide>
<ide> ### 자동 바인딩 안됨
<ide>
<del>메소드는 일반 ES6 클래스와 동일한 시멘틱을 따릅니다. `this`를 인스턴스에 자동으로 바인딩하지 않는다는 이야기입니다. 명시적으로 `.bind(this)`나 화살표 함수(arrow function)을 사용하세요.
<add>메소드는 일반 ES6 클래스와 동일한 시멘틱을 따릅니다. `this`를 인스턴스에 자동으로 바인딩하지 않는다는 이야기입니다. 명시적으로 `.bind(this)`나 [화살표 함수(arrow function)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`를 사용하세요.
<ide>
<ide> ### 믹스인 안됨
<ide>
<ide><path>docs/docs/06-transferring-props.ko-KR.md
<ide> React.render(
<ide> ```
<ide>
<ide> > 주의:
<del>>
<add>>
<ide> > 위의 예제에서는 `checked` prop 또한 마찬가지로 유효한 DOM 어트리뷰트입니다. 이런 식으로 구조의 해체(destructuring)를 하지 않으면 의도하지 않게 함께 전달될 수 있습니다.
<ide>
<ide> 미상의 `other` props을 전달할 때는 항상 구조 해체 패턴을 사용하세요.
<ide> var FancyCheckbox = React.createClass({
<ide>
<ide> ## 같은 Prop을 소비하고 전달하기
<ide>
<del>컴포넌트가 프로퍼티를 사용하지만 계속 넘겨야한다면, `checked={checked}`처럼 명시적으로 다시 넘길 수 있습니다. 리팩토링과 린트(lint)하기가 더 쉬우므로 이 방식이 `this.props` 객체 전부를 넘기는 것보다 낫습니다.
<add>컴포넌트가 프로퍼티를 사용하지만 계속 넘기길 원한다면, `checked={checked}`처럼 명시적으로 다시 넘길 수 있습니다. 리팩토링과 린트(lint)하기가 더 쉬우므로 이 방식이 `this.props` 객체 전부를 넘기는 것보다 낫습니다.
<ide>
<ide> ```javascript
<ide> var FancyCheckbox = React.createClass({
<ide> var FancyCheckbox = React.createClass({
<ide> ```
<ide>
<ide> > 주의:
<del>>
<add>>
<ide> > 순서는 중요합니다. `{...other}`를 JSX props 이전에 넣는 것으로 컴포넌트의 사용자가 확실히 그것들을 오버라이드 할 수 없게 합니다. 위의 예제에서는 input이 `"checkbox"` 타입인 것을 보장합니다.
<ide>
<ide> <a name="rest-and-spread-properties-..."></a>
<ide><path>docs/docs/08.1-more-about-refs.ko-KR.md
<ide> Refs는 반응적인 `props`와 `state` 스트리밍을 통해서는 불편했
<ide>
<ide> - 컴포넌트 클래스에 public 메소드(ex. Typeahead의 reset)를 선언할 수 있으며 refs를 통해 그를 호출할 수 있습니다. (ex. `this.refs.myTypeahead.reset()`)
<ide> - DOM을 측정하기 위해서는 거의 항상 `<input />` 같은 "기본" 컴포넌트를 다루고 `React.findDOMNode(this.refs.myInput)`를 통해 그 기저의 DOM 노드에 접근해야 합니다. Refs는 이 일을 확실하게 수행하는 몇 안 되는 실용적인 방법의 하나입니다.
<del>- Refs는 자동으로 기록을 관리합니다! 자식이 파괴되면, 그의 ref도 마찬가지로 파괴됩니다. 참조를 유지하기 위해 뭔가 미친 짓을 하지 않는 한, 메모리 걱정은 하지 않아도 됩니다.
<add>- Refs는 자동으로 관리합니다! 자식이 파괴되면, 그의 ref도 마찬가지로 파괴됩니다. 참조를 유지하기 위해 뭔가 미친 짓을 하지 않는 한, 메모리 걱정은 하지 않아도 됩니다.
<ide>
<ide> ### 주의:
<ide>
<ide><path>docs/docs/10.1-animation.ko-KR.md
<ide> var TodoList = React.createClass({
<ide> }
<ide> ```
<ide>
<add>### 처음 마운트에서 애니메이션 하기
<add>
<add>`ReactCSSTransitionGroup`은 컴포넌트를 처음 마운트할 때 추가 트렌지션 단계를 추가하기 위해, 선택적인 prop `transitionAppear`를 제공합니다. 일반적으로 처음 마운트할 때 트렌지션 단계를 넣지 않기 때문에 `transitionAppear`의 기본 값은 `false`입니다. 뒤의 예제는 `transitionAppear` prop에 `true` 값을 넘기고 있습니다.
<add>
<add>```javascript{3-5}
<add> render: function() {
<add> return (
<add> <ReactCSSTransitionGroup transitionName="example" transitionAppear="true">
<add> <h1>Fading at Initial Mount</h1>
<add> </ReactCSSTransitionGroup>
<add> );
<add> }
<add>```
<add>
<add>처음 마운트할 때 `ReactCSSTransitionGroup`은 `example-appear` CSS 클래스를 받고 그 다음에 `example-appear-active` CSS 클래스가 추가됩니다.
<add>
<add>```css
<add>.example-appear {
<add> opacity: 0.01;
<add> transition: opacity .5s ease-in;
<add>}
<add>
<add>.example-appear.example-appear-active {
<add> opacity: 1;
<add>}
<add>```
<add>
<add>처음 마운트할 때, `ReactCSSTransitionGroup`의 모든 자식은 `appear`하지만 `enter`하지 않습니다. 하지만, 존재하는 `ReactCSSTransitionGroup`에 추가되는 모든 자식은 `enter`하지만 `appear`하지 않습니다.
<add>
<add>> 주의:
<add>>
<add>> `transitionAppear` prop은 버전 `0.13`에서 `ReactCSSTransitionGroup`에 추가되었습니다. 하위 호환성을 생각해서, 기본 값은 `false`로 설정되어 있습니다.
<add>
<ide> ### 애니메이션 그룹이 작동하려면 마운트가 필요
<ide>
<del>자식들에게 트랜지션을 적용하려면 `ReactCSSTransitionGroup`은 이미 DOM에 마운트되어 있어야 합니다. 예를 들어, 밑의 코드는 동작하지 않을 것입니다. 왜냐하면 `ReactCSSTransitionGroup` 안에서 새 아이템을 마운트하는 대신 새 아이템과 같이 `ReactCSSTransitionGroup`를 마운트했기 때문입니다. 이 것을 위에 있는 [시작하기](#getting-stared) 항목과 비교해보세요.
<add>자식들에게 트랜지션을 적용하려면 `ReactCSSTransitionGroup`은 이미 DOM에 마운트되어 있거나 prop `transitionAppear`가 `true`로 설정되어야만 합니다. 예를 들어, 밑의 코드는 동작하지 않을 것입니다. 왜냐하면 `ReactCSSTransitionGroup` 안에서 새 아이템을 마운트하는 대신 새 아이템과 같이 `ReactCSSTransitionGroup`를 마운트했기 때문입니다. 이 것을 위에 있는 [시작하기](#getting-stared) 항목과 비교해보세요.
<ide>
<ide> ```javascript{12-15}
<ide> render: function() {
<ide> var TodoList = React.createClass({
<ide>
<ide> ### 아이템 하나이거나 없을 때의 애니메이션
<ide>
<del>위의 에제에서 `ReactCSSTransitionGroup`에 아이템 목록을 렌더했지만, `ReactCSSTransitionGroup`의 자식은 하나이거나 없을 수도 있습니다. 이는 한 엘리먼트가 들어오고 나가는 것의 애니메이션을 가능하게 합니다. 비슷하게, 현재 엘리먼트가 나가는 동안 새 앨리먼트의 애니메이션을 하면, 새 엘리먼트가 현재 엘리먼트를 교체하는 애니메이션을 만들 수 있습니다. 예를 들어 이렇게 간단한 이미지 회전 베너(carousel)를 구현할 수 있습니다.
<add>위의 예제에서 `ReactCSSTransitionGroup`에 아이템 목록을 렌더했지만, `ReactCSSTransitionGroup`의 자식은 하나이거나 없을 수도 있습니다. 이는 한 엘리먼트가 들어오고 나가는 것의 애니메이션을 가능하게 합니다. 비슷하게, 현재 엘리먼트가 나가는 동안 새 앨리먼트의 애니메이션을 하면, 새 엘리먼트가 현재 엘리먼트를 교체하는 애니메이션을 만들 수 있습니다. 예를 들어 이렇게 간단한 이미지 회전 베너(carousel)를 구현할 수 있습니다.
<ide>
<ide> ```javascript{10-12}
<ide> var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
<ide><path>docs/docs/10.7-update.ko-KR.md
<ide> next: pure-render-mixin-ko-KR.html
<ide>
<ide> React에서는 mutation을 포함해 어떤 데이터 관리 방식도 사용하실 수 있습니다. 하지만 애플리케이션의 성능이 중요한 부분에서 불변의(immutable) 데이터를 사용할 수 있다면, 쉽게 빠른 `shouldComponentUpdate()` 메소드를 구현해 애플리케이션의 속도를 크게 향상시킬 수 있습니다.
<ide>
<del>JavaScript에서 불변성의 데이터를 다루는 것은 [Clojure](http://clojure.org/)같이 그것을 위해 디자인된 언어로 다루는 것보다는 어렵습니다. 하지만, React는 간단한 불변성 헬퍼를 제공합니다. `update()`는 이런 종류의 데이터를 근본적인 변화 *없이* 쉽게 다루도록 해줍니다.
<add>JavaScript에서 불변성의 데이터를 다루는 것은 [Clojure](http://clojure.org/)같이 그것을 위해 디자인된 언어로 다루는 것보다는 어렵습니다. 하지만, React는 간단한 불변성 헬퍼를 제공합니다. `update()`는 이런 종류의 데이터를 근본적인 변화 *없이* 쉽게 다루도록 해줍니다. Immutable-js에 관한 좀 더 자세한 정보는 페이스북의 [Immutable-js](https://facebook.github.io/immutable-js/docs/)나 [성능 심화](react/docs/advanced-performance-ko-KR.html)을 참조하세요.
<ide>
<ide> ## 주요 아이디어
<ide>
<ide><path>docs/docs/11-advanced-performance.ko-KR.md
<ide> shouldComponentUpdate: function(nextProps, nextState) {
<ide>
<ide> C1과 C3의 `shouldComponentUpdate`가 `true`를 반환했기 때문에 React는 하위 노드로 내려가 그들을 확인합니다. C6는 `true`를 반환했네요; 이는 가상의 DOM과 같지 않기 때문에 DOM의 조정이 일어났습니다. 마지막으로 흥미로운 사례는 C8입니다. React가 이 노드를 위해 가상의 DOM을 작동했지만, 노드가 이전의 것과 일치했기 때문에 DOM의 조정을 일어나지 않았습니다.
<ide>
<del>React가 C6에만 DOM 변경을 수행한 것을 확인하세요. 이는 필연적이었습니다. C8의 경우는 가상의 DOM과 비교를 해 제외되었고, C2의 하위 트리와 C7은 `shouldComponentUpdate` 단계에서 제외되어 가상의 DOM은 구동조차 되지 않았습니다.
<add>React가 C6에만 DOM 변경을 수행한 것을 확인하세요. 이는 필연적이었습니다. C8의 경우는, 가상의 DOM과 비교를 해 제외되었고, C2의 하위 트리와 C7은 `shouldComponentUpdate` 단계에서 제외되어 가상의 DOM은 구동조차 되지 않았습니다.
<ide>
<ide> 자 그럼, 어떻게 `shouldComponentUpdate`를 구현해야 할까요? 문자열 값을 렌더하는 컴포넌트를 생각해보죠.
<ide>
<ide> React.createClass({
<ide> this.props.value !== nextProps.value; // true
<ide> ```
<ide>
<del>문제는 prop이 실제로 변경되지 않았을 때도 `shouldComponentUpdate`가 `true`를 반환할 거라는 겁니다. 이를 해결하기 위한 대안으로 아래와 같이 구현해 볼 수 있습니다:
<add>문제는 prop이 실제로 변경되지 않았을 때도 `shouldComponentUpdate`가 `true`를 반환할 거라는 겁니다. 이를 해결하기 위한 대안으로, 아래와 같이 구현해 볼 수 있습니다:
<ide>
<ide> ```javascript
<ide> shouldComponentUpdate: function(nextProps, nextState) {
<ide> return this.props.value.foo !== nextProps.value.foo;
<ide> }
<ide> ```
<ide>
<del>기본적으로, 우리는 변경을 정확히 추적하기 위해서 깊은 비교를 해야 했습니다. 이 방법은 성능 면에서 제법 비싸고 각각의 모델마다 다른 깊은 등식 코드를 작성해야 하므로 확장이 힘들어 집니다. 심지어 객체 참조를 신중히 관리하지 않는다면 작동하지도 않을 수 있습니다. 컴포넌트가 부모에 의해 다뤄지는 경우를 살펴보죠:
<add>기본적으로, 우리는 변경을 정확히 추적하기 위해서 깊은 비교를 해야 했습니다. 이 방법은 성능 면에서 제법 비쌉니다. 각각의 모델마다 다른 깊은 등식 코드를 작성해야 하므로 확장이 힘들어 집니다. 심지어 객체 참조를 신중히 관리하지 않는다면 작동하지도 않을 수 있습니다. 컴포넌트가 부모에 의해 다뤄지는 경우를 살펴보죠:
<ide>
<ide> ```javascript
<ide> React.createClass({
<ide> this.messages = this.messages.push(new Message({
<ide> });
<ide> ```
<ide>
<del>자료구조가 불변이기 때문에 push 함수의 결과를 this.messages에 할당할 필요가 있으니 주의하세요.
<add>자료구조가 불변이기 때문에 push 함수의 결과를 `this.messages`에 할당할 필요가 있으니 주의하세요.
<ide>
<ide> React 측에서는, 컴포넌트의 state를 보존하기 위해 immutable-js 자료구조를 사용한다면, 모든 컴포넌트에 `PureRenderMixin`을 혼합해 다시 렌더링하는 프로세스를 중단할 수 있습니다.
<ide><path>docs/docs/ref-02-component-api.ko-KR.md
<ide> setState({mykey: '새로운 값'});
<ide> ```javascript
<ide> setState(function(previousState, currentProps) {
<ide> return {myInteger: previousState.myInteger + 1};
<del>});`
<add>});
<ide> ```
<ide>
<ide> 두번째 인자는 선택적이며, `setState`가 한번 완료되고 컴포넌트가 다시 렌더 되었을때 실행되는 콜백 함수입니다.
<ide><path>docs/docs/thinking-in-react.ko-KR.md
<ide> next: videos-ko-KR.html
<ide>
<ide> 제가 생각하기에, React는 JavaScript로 크고 빠른 웹 애플리케이션을 만드는데 최고입니다. 페이스북과 인스타그램에서 우리에게 잘 맞도록 조정되어 왔습니다.
<ide>
<del>React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케이션을 만들게 한다는 겁니다. 이 포스트에서 React를 이용해 검색이 가능한 상품자료 테이블을 만드는 생각 과정을 이해할 수 있게 차근차근 설명할 겁니다.
<add>React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케이션을 만들게 한다는 겁니다. 이 포스트에서, React를 이용해 검색이 가능한 상품자료 테이블을 만드는 생각 과정을 이해할 수 있게 차근차근 설명할 겁니다.
<ide>
<ide> ## 모형으로 시작해보기
<ide>
<ide> React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케
<ide>
<ide> 당신이 하고싶은 첫번째는 모형에 있는 모든 컴포넌트 (그리고 자식엘리먼트) 주위에 상자를 그리고, 이름을 부여하는 것입니다. 만약 당신이 디자이너와 같이 작업중이라면, 그들은 이미 이 작업을 해놨을지도 모릅니다. 당장 가서 이야기해보세요. 그들의 포토샵 레이어 이름이 결국 당신의 React 컴포넌트들의 이름이 될 것입니다.
<ide>
<del>그런데 무엇이 컴포넌트가 되어야 할까요? 당신이 새로운 함수나 객체를 만들어야만 한다면, 똑같이 적용하세요. 한가지 방법은 [단일 책임의 원칙](http://ko.wikipedia.org/wiki/%EB%8B%A8%EC%9D%BC_%EC%B1%85%EC%9E%84_%EC%9B%90%EC%B9%99) 입니다. 즉 하나의 컴포넌트는 이상적으로 한가지 작업만 수행해야 합니다. 컴포넌트가 결국 커진다면 작은 자식 컴포넌트로 쪼개져야 합니다.
<add>그런데 무엇이 컴포넌트가 되어야 할까요? 당신이 새로운 함수나 객체를 만들어야만 한다면, 똑같이 적용하세요. 한가지 방법은 [단일 책임의 원칙](http://ko.wikipedia.org/wiki/%EB%8B%A8%EC%9D%BC_%EC%B1%85%EC%9E%84_%EC%9B%90%EC%B9%99) 입니다. 즉 하나의 컴포넌트는 이상적으로 한가지 작업만 수행해야 합니다. 컴포넌트가 결국 커진다면, 작은 자식 컴포넌트로 쪼개져야 합니다.
<ide>
<del>주로 JSON 데이터 모델을 사용자에게 보여주기 때문에, 자료 모델이 잘 설계 되었다면 UI(혹은 컴포넌트 구조)가 잘 맞아 떨어진다는 것을 알게 될 겁니다. UI와 자료 모델은 같은 *정보 설계구조*로 따라가는 경향이 있기 때문입니다. 즉, UI를 컴포넌트들로 쪼개는 작업은 크게 어렵지 않습니다. 확실하게 각각 하나의 부분이 되도록 쪼개세요.
<add>주로 JSON 데이터 모델을 사용자에게 보여주기 때문에, 자료 모델이 잘 설계 되었다면, UI(혹은 컴포넌트 구조)가 잘 맞아 떨어진다는 것을 알게 될 겁니다. UI와 자료 모델은 같은 *정보 설계구조*로 따라가는 경향이 있기 때문입니다. 즉, UI를 컴포넌트들로 쪼개는 작업은 크게 어렵지 않습니다. 확실하게 각각 하나의 부분이 되도록 쪼개세요.
<ide>
<ide> 
<ide>
<ide> React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케
<ide> 4. **`ProductCategoryRow` (청록):** 각 *카테고리*의 제목을 보여줍니다.
<ide> 5. **`ProductRow` (빨강):** 각 *프로덕트*를 보여줍니다.
<ide>
<del>`ProductTable`을 보면 테이블 제목("Name", "Price" 라벨들을 포함한)은 컴포넌트가 아닌것을 알 수 있습니다. 이건 기호의 문제이고, 어느쪽으로 만들던 논쟁거리입니다. 예를 들어 저는 *자료 모음*을 그리는 `ProductTable`의 의무라고 생각했기 때문에 남겨 두었습니다. 하지만 이 제목이 복잡해진다면 (예를 들어 정렬을 추가할 여유가 있다거나 하는), 이건 확실히 `ProductTableHeader` 컴포넌트로 만드는 것이 맞을 겁니다.
<add>`ProductTable`을 보면, 테이블 제목("Name", "Price" 라벨들을 포함한)은 컴포넌트가 아닌것을 알 수 있습니다. 이건 기호의 문제이고, 어느쪽으로 만들던 논쟁거리입니다. 이 예제에서는, 저는 *자료 모음*을 그리는 `ProductTable`의 의무라고 생각했기 때문에 남겨 두었습니다. 하지만, 이 제목이 복잡해진다면 (예를 들어 정렬을 추가할 여유가 있다거나 하는), 이건 확실히 `ProductTableHeader` 컴포넌트로 만드는 것이 맞을 겁니다.
<ide>
<ide> 이제 모형에 들어있는 컴포넌트들에 대해 알아보았으니, 계층 구조로 만들어 봅시다. 이건 쉽습니다. 다른 컴포넌트 속에 들어있는 컴포넌트를 자식으로 나타내기만 하면 됩니다.
<ide>
<ide> React의 많은 뛰어난 점들 중 하나는 생각을 하면서 애플리케
<ide>
<ide> <iframe width="100%" height="300" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<ide>
<del>계층구조의 컴포넌트들을 가지고 있으니, 이젠 애플리케이션을 구현할 시간입니다. 가장 쉬운 방법은 상호작용을 하지 않는 채로 자료 모델을 이용해 UI를 그리는 것입니다. 정적 버전을 만드는 데에는 적은 생각과 많은 노동이 필요하고, 상호작용을 추가하는 데에는 많은 생각과 적은 노동이 필요하기 때문에 둘을 분리하는 것은 쉽습니다. 왜 그런지 봅시다.
<add>계층구조의 컴포넌트들을 가지고 있으니, 이젠 애플리케이션을 구현할 시간입니다. 가장 쉬운 방법은 상호작용을 하지 않는 채로 자료 모델을 이용해 UI를 그리는 것입니다. 정적 버전을 만드는 데에는 적은 생각과 많은 노동이 필요하고, 상호작용을 추가하는 데에는 많은 생각과 적은 노동이 필요하기 때문에 둘을 분리하는 것이 가장 좋습니다. 왜 그런지 봅시다.
<ide>
<ide> 자료 모델을 그리는 애플리케이션의 정적버전을 만들기 위해서, 다른 컴포넌트에 재사용할 컴포넌트를 만들고 자료 전달을 위해 *props*를 사용하고 싶을 것입니다. 만약 *상태*라는 개념에 익숙하다면, 정적 버전을 만들때 **절대 상태를 사용하지 마세요**. 상태는 오직 상호작용, 즉 가변적인 자료를 위해서만 준비되어 있습니다. 정적 버전을 만들 때는 필요가 없습니다.
<ide>
<del>껍데기부터 혹은 속알맹이부터 만들 수 있습니다. 즉 계층구조상 위에서부터 (`FilterableProductTable` 부터) 혹은 아래에서부터 (`ProductRow`), 어느 방향에서든 시작해도 됩니다. 통상 큰 프로젝트에서는 계층구조상 위에서부터 시작하는 것이 쉽고, 테스트를 작성할때는 아래에서부터 시작하는 것이 쉽습니다.
<add>껍데기부터 혹은 속알맹이부터 만들 수 있습니다. 즉 계층구조상 위에서부터 (`FilterableProductTable` 부터) 혹은 아래에서부터 (`ProductRow`), 어느 방향에서든 시작해도 됩니다. 통상 큰 프로젝트에서는 계층구조상 위에서부터 시작하는 것이 쉽고, 테스트를 작성할때는, 아래에서부터 시작하는 것이 쉽습니다.
<ide>
<del>이 단계의 결과, 자료 모델을 그리는 재활용 가능한 컴포넌트의 라이브러리를 갖게 되었습니다. 정적버전 이후로 컴포넌트들은 오직 `render()` 메소드만 갖고 있습니다. 계층구조상 가장 위의 컴포넌트 (`FilterableProductTable`)은 자료 모델을 prop으로 취할 것입니다. 자료 모델이 변했을 때, `React.render()`를 다시 부르면 업데이트 됩니다. 어떻게 UI가 업데이트 되는지 참 알기 쉽습니다. 자료가 바뀌어도 처리해야 할 복잡한 일이 아무것도 없습니다. React의 **단일 방향 자료 흐름** (혹은 *단일방향 바인딩*)이 모든것을 모듈식으로, 추론하기 쉽게, 그리고 빠르게 유지해줍니다.
<add>이 단계의 결과, 자료 모델을 그리는 재활용 가능한 컴포넌트의 라이브러리를 갖게 되었습니다. 정적버전 이후로 컴포넌트들은 오직 `render()` 메소드만 갖고 있습니다. 계층구조상 가장 위의 컴포넌트 (`FilterableProductTable`)은 자료 모델을 prop으로 취할 것입니다. 자료 모델이 변했을 때, `React.render()`를 다시 부르면 UI가 업데이트 됩니다. 어떻게 UI가 업데이트 되는지 참 알기 쉽습니다. 자료가 바뀌어도 처리해야 할 복잡한 일이 아무것도 없습니다. React의 **단일 방향 자료 흐름** (혹은 *단일방향 바인딩*)이 모든것을 모듈식으로, 추론하기 쉽게, 그리고 빠르게 유지해줍니다.
<ide>
<ide> 이 단계를 진행하는 데에 도움이 필요하시다면, [React 문서](/react/docs/getting-started-ko-KR.html)를 참조하세요.
<ide>
<ide> product 들의 원본 목록은 props를 통해서 전달되기 때문에, state
<ide>
<ide> <iframe width="100%" height="300" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<ide>
<del>이제 최소한의 state가 무엇인지 알아냈습니다. 다음은 어떤 컴포넌트가 이 state를 변형하거나 만들어낼지 알아내야 합니다.
<add>이제 최소한의 state가 무엇인지 알아냈습니다. 다음은, 어떤 컴포넌트가 이 state를 변형하거나 만들어낼지 알아내야 합니다.
<ide>
<ide> 기억하세요: React는 계층적 아래 컴포넌트로만 향하는 단일방향성 자료 흐름을 가집니다. 지금당장은 어떤 컴포넌트가 자기 자신의 state를 가져야 할지 명확하지 않을 것입니다. **이것이 초심자가 가장 이해하기 어려운 부분입니다**. 이제 개념을 명확히 하기 위해 다음으로 따라가 봅시다:
<ide>
<ide> product 들의 원본 목록은 props를 통해서 전달되기 때문에, state
<ide> * 대표 컴포넌트는 `FilterableProductTable` 입니다.
<ide> * 개념적으로 검색어와 체크박스 값은 `FilterableProductTable`에 있어야 한다는 것이 명확합니다.
<ide>
<del>좋습니다. state를 `FilterableProductTable`에서 관리하도록 결정했습니다. 먼저 `getInitialState()` 메소드를 `FilterableProductTable`에 추가하세요. 이 메소드는 애플리케이션의 초기 state를 갖도록 `{filterText: '', inStockOnly: false}`를 리턴하면 됩니다. 그리고 `filterText`와 `inStockOnly` 를 `ProductTable`과 `SearchBar`에 prop으로 전달하세요. 마지막으로 이 prop들을 `ProductTable`을 걸러내는 데, 그리고 `SearchBar` form fields의 값을 세팅하는데 사용하세요.
<add>좋습니다. state를 `FilterableProductTable`에서 관리하도록 결정했습니다. 먼저, `getInitialState()` 메소드를 `FilterableProductTable`에 추가하세요. 이 메소드는 애플리케이션의 초기 state를 갖도록 `{filterText: '', inStockOnly: false}`를 리턴하면 됩니다. 그리고, `filterText`와 `inStockOnly` 를 `ProductTable`과 `SearchBar`에 prop으로 전달하세요. 마지막으로, 이 prop들을 `ProductTable`을 걸러내는 데, 그리고 `SearchBar` form fields의 값을 세팅하는데 사용하세요.
<ide>
<ide> 이제 어떻게 애플리케이션이 동작하는지 볼 수 있습니다: `filterText`를 `"ball"`로 설정하고 업데이트합니다. 자료 테이블이 제대로 업데이트 되는 것을 볼 수 있을 겁니다.
<ide>
<ide> React는 어떻게 이 프로그램이 동작하는지 이해하기 쉽게 이
<ide>
<ide> 우리가 원하는 것이 무엇인지 생각해 봅시다. 사용자 입력을 반영하기 위해, 사용자가 form을 바꿀때마다 업데이트 하기를 원하죠. 컴포넌트들이 오직 자기 자신의 state만 업데이트 하더라도 `FilterableProductTable`은 state가 변할때마다 반영되어야할 `SearchBar`에 콜백을 전달할 것입니다. 이 알림을 위해서 `onChange`이벤트를 사용할 수 있습니다. 그리고 `FilterableProductTable`으로부터 전달된 콜백은 `setState()`를 호출할 것이고, 애플리케이션은 업데이트될 것입니다.
<ide>
<del>많은 코드가 필요한 것 같이 들릴 수 있지만 실제로는 몇 줄 되지 않습니다. 그리고 애플리케이션의 구석구석에서 데이터가 어떻게 흐르는지 매우 명확해집니다.
<add>복잡하게 들릴 수 있지만, 실제로는 몇 줄 되지 않습니다. 그리고 애플리케이션의 구석구석에서 데이터가 어떻게 흐르는지 매우 명확해집니다.
<ide>
<ide> ## 그리고
<ide>
<ide><path>docs/docs/tutorial.ko-KR.md
<ide> var Comment = React.createClass({
<ide>
<ide> 하지만 여기엔 문제가 있습니다! 우리는 HTML 태그들이 정상적으로 렌더되길 원하지만 브라우저에 출력된 결과물은 "`<p>``<em>`또 다른`</em>` 댓글입니다`</p>`"처럼 태그가 그대로 보일것입니다.
<ide>
<del>React는 이런 식으로 XSS 공격을 예방합니다. 우회할 방법이 있긴 하지만 프레임워크는 사용하지 않도록 경고하고 있습니다:
<add>React는 이런 식으로 [XSS 공격](https://en.wikipedia.org/wiki/Cross-site_scripting)을 예방합니다. 우회할 방법이 있긴 하지만 프레임워크는 사용하지 않도록 경고하고 있습니다:
<ide>
<ide> ```javascript{4,10}
<ide> // tutorial7.js
<ide><path>docs/tips/01-introduction.ko-KR.md
<ide> React 팁 섹션에서는 여러 궁금증을 해결해주고 흔히 하는 실
<ide>
<ide> ## 기여하기
<ide>
<del>[현재 팁](https://github.com/facebook/react/tree/master/docs)의 형식을 따르는 풀 리퀘스트를 [React 저장소](https://github.com/facebook/react)에 보내주세요. PR을 보내기 전에 리뷰가 필요하다면 [freenode의 #reactjs 채널](irc://chat.freenode.net/reactjs)이나 [reactjs Google 그룹](https://groups.google.com/group/reactjs)에서 도움을 요청하실 수 있습니다.
<add>[현재 팁](https://github.com/facebook/react/tree/master/docs)의 형식을 따르는 풀 리퀘스트를 [React 저장소](https://github.com/facebook/react)에 보내주세요. PR을 보내기 전에 리뷰가 필요하다면 [freenode의 #reactjs 채널](irc://chat.freenode.net/reactjs)이나 [discuss.reactjs.org 포럼](https://discuss.reactjs.org/)에서 도움을 요청하실 수 있습니다. | 13 |
PHP | PHP | move empty check to a more general purpose place | 39e9863a2588462cf9a523a2da8e32f166182d41 | <ide><path>src/Database/Query.php
<ide> protected function _makeJoin($table, $conditions, $type)
<ide> */
<ide> public function where($conditions = null, $types = [], $overwrite = false)
<ide> {
<del> if (empty($conditions)) {
<del> return $this;
<del> }
<ide> if ($overwrite) {
<ide> $this->_parts['where'] = $this->newExpr();
<ide> }
<ide> protected function _decorateStatement($statement)
<ide> */
<ide> protected function _conjugate($part, $append, $conjunction, $types)
<ide> {
<add> if (empty($append)) {
<add> return;
<add> }
<ide> $expression = $this->_parts[$part] ?: $this->newExpr();
<ide>
<ide> if (!is_string($append) && is_callable($append)) { | 1 |
Text | Text | remove broken links | 29a64f2384f53760e9133d11a0c60e0d32ed9187 | <ide><path>guides/source/rails_on_rack.md
<ide> Resources
<ide>
<ide> * [Official Rack Website](http://rack.github.io)
<ide> * [Introducing Rack](http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html)
<del>* [Ruby on Rack #1 - Hello Rack!](http://m.onkey.org/ruby-on-rack-1-hello-rack)
<del>* [Ruby on Rack #2 - The Builder](http://m.onkey.org/ruby-on-rack-2-the-builder)
<ide>
<ide> ### Understanding Middlewares
<ide> | 1 |
Java | Java | fix potential npe in uiviewoperationqueue | cfb90284d654664c705a04fe451e7a16f0779b4f | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java
<ide> import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<add>import com.facebook.react.bridge.SoftAssertions;
<ide> import com.facebook.react.bridge.UiThreadUtil;
<ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
<ide> import com.facebook.systrace.Systrace;
<ide> public void run() {
<ide> * subclass to support UIOperations not provided by UIViewOperationQueue.
<ide> */
<ide> protected void enqueueUIOperation(UIOperation operation) {
<add> SoftAssertions.assertNotNull(operation);
<ide> mOperations.add(operation);
<ide> }
<ide> | 1 |
Text | Text | fix consistency of component api document | b7860b7da4f87bbe4b66dd5f5b1be8ff698a71b4 | <ide><path>docs/docs/ref-02-component-api.md
<ide> replaceState(object nextState[, function callback])
<ide> Like `setState()` but deletes any pre-existing state keys that are not in nextState.
<ide>
<ide>
<del>### forceUpdate()
<add>### forceUpdate
<ide>
<ide> ```javascript
<ide> forceUpdate([function callback])
<ide> DOMElement getDOMNode()
<ide> If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. When `render` returns `null` or `false`, `this.getDOMNode()` returns `null`.
<ide>
<ide>
<del>### isMounted()
<add>### isMounted
<ide>
<ide> ```javascript
<ide> bool isMounted() | 1 |
Python | Python | fix newlines in diagnostics output of numpy.f2py | cbc25d2cc9ed50e8f0d026d1e2e4766378d1640f | <ide><path>numpy/f2py/capi_maps.py
<ide> def getpydocsign(a, var):
<ide> sigout = sig
<ide> else:
<ide> errmess(
<del> 'getpydocsign: Could not resolve docsignature for "%s".\\n' % a)
<add> 'getpydocsign: Could not resolve docsignature for "%s".\n' % a)
<ide> return sig, sigout
<ide>
<ide>
<ide><path>numpy/f2py/crackfortran.py
<ide> def analyzeline(m, case, line):
<ide> groupcache[groupcounter]['args'].append(k)
<ide> else:
<ide> errmess(
<del> 'analyzeline: intent(callback) %s is ignored' % (k))
<add> 'analyzeline: intent(callback) %s is ignored\n' % (k))
<ide> else:
<ide> errmess('analyzeline: intent(callback) %s is already'
<del> ' in argument list' % (k))
<add> ' in argument list\n' % (k))
<ide> if case in ['optional', 'required', 'public', 'external', 'private', 'intrinsic']:
<ide> ap = case
<ide> if 'attrspec' in edecl[k]:
<ide> def get_useparameters(block, param_map=None):
<ide> continue
<ide> # XXX: apply mapping
<ide> if mapping:
<del> errmess('get_useparameters: mapping for %s not impl.' % (mapping))
<add> errmess('get_useparameters: mapping for %s not impl.\n' % (mapping))
<ide> for k, v in list(params.items()):
<ide> if k in param_map:
<ide> outmess('get_useparameters: overriding parameter %s with'
<del> ' value from module %s' % (repr(k), repr(usename)))
<add> ' value from module %s\n' % (repr(k), repr(usename)))
<ide> param_map[k] = v
<ide>
<ide> return param_map
<ide> def get_parameters(vars, global_params={}):
<ide>
<ide> elif iscomplex(vars[n]):
<ide> outmess(f'get_parameters[TODO]: '
<del> f'implement evaluation of complex expression {v}')
<add> f'implement evaluation of complex expression {v}\n')
<ide>
<ide> try:
<ide> params[n] = eval(v, g_params, params)
<ide> def analyzevars(block):
<ide> vars[n]['intent'].append('c')
<ide> else:
<ide> errmess(
<del> "analyzevars: charselector=%r unhandled." % (d))
<add> "analyzevars: charselector=%r unhandled.\n" % (d))
<ide>
<ide> if 'check' not in vars[n] and 'args' in block and n in block['args']:
<ide> # n is an argument that has no checks defined. Here we
<ide><path>numpy/f2py/f2py2e.py
<ide> def scaninputline(inputline):
<ide> sys.exit()
<ide> if not os.path.isdir(buildpath):
<ide> if not verbose:
<del> outmess('Creating build directory %s' % (buildpath))
<add> outmess('Creating build directory %s\n' % (buildpath))
<ide> os.mkdir(buildpath)
<ide> if signsfile:
<ide> signsfile = os.path.join(buildpath, signsfile) | 3 |
Javascript | Javascript | improve $location.hash() example | 228281eecc703d1535e2e9871249a4ec8e2d9843 | <ide><path>src/ng/location.js
<ide> var locationPrototype = {
<ide> *
<ide> *
<ide> * ```js
<del> * // given url http://example.com/some/path?foo=bar&baz=xoxo#hashValue
<add> * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
<ide> * var hash = $location.hash();
<ide> * // => "hashValue"
<ide> * ``` | 1 |
Text | Text | add 2.17.0-beta.5 to changelog | 131bf7ba6c18d4ea711297e58764a7b05f7ba51a | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.17.0-beta.5 (November 7, 2017)
<add>- [#15797](https://github.com/emberjs/ember.js/pull/15797) [BUGFIX] Fix issues with using partials nested within other partials.
<add>- [#15808](https://github.com/emberjs/ember.js/pull/15808) [BUGFIX] Fix a memory leak in certain testing scenarios.
<add>
<ide> ### 2.17.0-beta.4 (October 30, 2017)
<ide> - [#15746](https://github.com/emberjs/ember.js/pull/15746) [BUGFIX] Fix computed sort regression when array property is initally `null`.
<ide> - [#15777](https://github.com/emberjs/ember.js/pull/15777) [BUGFIX] Fix various issues around accessing dynamic data within a partial. | 1 |
Go | Go | implement docker pull with standalone client lib | e78f02c4dbc3cada909c114fef6b6643969ab912 | <ide><path>api/client/client.go
<ide> package client
<ide> import (
<ide> "io"
<ide>
<add> "github.com/docker/docker/api/client/lib"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> type apiClient interface {
<ide> ImageImport(options types.ImageImportOptions) (io.ReadCloser, error)
<ide> ImageList(options types.ImageListOptions) ([]types.Image, error)
<ide> ImageLoad(input io.Reader) (io.ReadCloser, error)
<add> ImagePull(options types.ImagePullOptions, privilegeFunc lib.RequestPrivilegeFunc) (io.ReadCloser, error)
<ide> ImageRemove(options types.ImageRemoveOptions) ([]types.ImageDelete, error)
<ide> ImageSave(imageIDs []string) (io.ReadCloser, error)
<ide> ImageTag(options types.ImageTagOptions) error
<ide><path>api/client/create.go
<ide> package client
<ide>
<ide> import (
<del> "encoding/base64"
<del> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> "os"
<ide> func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error {
<ide> }
<ide>
<ide> // Resolve the Auth config relevant for this server
<del> authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index)
<del> buf, err := json.Marshal(authConfig)
<add> encodedAuth, err := cli.encodeRegistryAuth(repoInfo.Index)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> options := types.ImageCreateOptions{
<ide> Parent: ref.Name(),
<ide> Tag: tag,
<del> RegistryAuth: base64.URLEncoding.EncodeToString(buf),
<add> RegistryAuth: encodedAuth,
<ide> }
<ide>
<ide> responseBody, err := cli.client.ImageCreate(options)
<ide><path>api/client/lib/image_create.go
<ide> func (cli *Client) ImageCreate(options types.ImageCreateOptions) (io.ReadCloser,
<ide> query := url.Values{}
<ide> query.Set("fromImage", options.Parent)
<ide> query.Set("tag", options.Tag)
<del>
<del> headers := map[string][]string{"X-Registry-Auth": {options.RegistryAuth}}
<del> resp, err := cli.post("/images/create", query, nil, headers)
<add> resp, err := cli.tryImageCreate(query, options.RegistryAuth)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> return resp.body, nil
<ide> }
<add>
<add>func (cli *Client) tryImageCreate(query url.Values, registryAuth string) (*serverResponse, error) {
<add> headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
<add> return cli.post("/images/create", query, nil, headers)
<add>}
<ide><path>api/client/lib/image_pull.go
<add>package lib
<add>
<add>import (
<add> "io"
<add> "net/http"
<add> "net/url"
<add>
<add> "github.com/docker/docker/api/types"
<add>)
<add>
<add>// ImagePull request the docker host to pull an image from a remote registry.
<add>// It executes the privileged function if the operation is unauthorized
<add>// and it tries one more time.
<add>// It's up to the caller to handle the io.ReadCloser and close it properly.
<add>func (cli *Client) ImagePull(options types.ImagePullOptions, privilegeFunc RequestPrivilegeFunc) (io.ReadCloser, error) {
<add> query := url.Values{}
<add> query.Set("fromImage", options.ImageID)
<add> if options.Tag != "" {
<add> query.Set("tag", options.Tag)
<add> }
<add>
<add> resp, err := cli.tryImageCreate(query, options.RegistryAuth)
<add> if resp.statusCode == http.StatusUnauthorized {
<add> newAuthHeader, privilegeErr := privilegeFunc()
<add> if privilegeErr != nil {
<add> return nil, privilegeErr
<add> }
<add> resp, err = cli.tryImageCreate(query, newAuthHeader)
<add> }
<add> if err != nil {
<add> return nil, err
<add> }
<add> return resp.body, nil
<add>}
<ide><path>api/client/lib/privileged.go
<add>package lib
<add>
<add>// RequestPrivilegeFunc is a function interface that
<add>// clients can supply to retry operations after
<add>// getting an authorization error.
<add>// This function returns the registry authentication
<add>// header value in base 64 format, or an error
<add>// if the privilege request fails.
<add>type RequestPrivilegeFunc func() (string, error)
<ide><path>api/client/pull.go
<ide> package client
<ide> import (
<ide> "errors"
<ide> "fmt"
<del> "net/url"
<ide>
<ide> "github.com/docker/distribution/reference"
<add> "github.com/docker/docker/api/client/lib"
<add> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<add> "github.com/docker/docker/cliconfig"
<add> "github.com/docker/docker/pkg/jsonmessage"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/registry"
<ide> tagpkg "github.com/docker/docker/tag"
<ide> func (cli *DockerCli) CmdPull(args ...string) error {
<ide> return err
<ide> }
<ide>
<add> authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index)
<add> requestPrivilege := cli.registryAuthenticationPrivilegedFunc(repoInfo.Index, "pull")
<add>
<ide> if isTrusted() && !ref.HasDigest() {
<ide> // Check if tag is digest
<del> authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index)
<del> return cli.trustedPull(repoInfo, ref, authConfig)
<add> return cli.trustedPull(repoInfo, ref, authConfig, requestPrivilege)
<add> }
<add>
<add> return cli.imagePullPrivileged(authConfig, distributionRef.String(), "", requestPrivilege)
<add>}
<add>
<add>func (cli *DockerCli) imagePullPrivileged(authConfig cliconfig.AuthConfig, imageID, tag string, requestPrivilege lib.RequestPrivilegeFunc) error {
<add>
<add> encodedAuth, err := authConfig.EncodeToBase64()
<add> if err != nil {
<add> return err
<add> }
<add> options := types.ImagePullOptions{
<add> ImageID: imageID,
<add> Tag: tag,
<add> RegistryAuth: encodedAuth,
<ide> }
<ide>
<del> v := url.Values{}
<del> v.Set("fromImage", distributionRef.String())
<add> responseBody, err := cli.client.ImagePull(options, requestPrivilege)
<add> if err != nil {
<add> return err
<add> }
<add> defer responseBody.Close()
<ide>
<del> _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull")
<del> return err
<add> return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut)
<ide> }
<ide><path>api/client/trust.go
<ide> import (
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/distribution/registry/client/transport"
<add> "github.com/docker/docker/api/client/lib"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/ansiescape"
<ide> func notaryError(err error) error {
<ide> return err
<ide> }
<ide>
<del>func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig cliconfig.AuthConfig) error {
<del> var (
<del> v = url.Values{}
<del> refs = []target{}
<del> )
<add>func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig cliconfig.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<add> var refs []target
<ide>
<ide> notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig)
<ide> if err != nil {
<ide> func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registr
<ide> refs = append(refs, r)
<ide> }
<ide>
<del> v.Set("fromImage", repoInfo.LocalName.Name())
<ide> for i, r := range refs {
<ide> displayTag := r.reference.String()
<ide> if displayTag != "" {
<ide> displayTag = ":" + displayTag
<ide> }
<ide> fmt.Fprintf(cli.out, "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), repoInfo.LocalName, displayTag, r.digest)
<del> v.Set("tag", r.digest.String())
<ide>
<del> _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull")
<del> if err != nil {
<add> if err := cli.imagePullPrivileged(authConfig, repoInfo.LocalName.Name(), r.digest.String(), requestPrivilege); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>api/client/utils.go
<ide> func (cli *DockerCli) cmdAttempt(authConfig cliconfig.AuthConfig, method, path s
<ide> return serverResp.body, serverResp.statusCode, err
<ide> }
<ide>
<add>func (cli *DockerCli) encodeRegistryAuth(index *registry.IndexInfo) (string, error) {
<add> authConfig := registry.ResolveAuthConfig(cli.configFile, index)
<add> return authConfig.EncodeToBase64()
<add>}
<add>
<add>func (cli *DockerCli) registryAuthenticationPrivilegedFunc(index *registry.IndexInfo, cmdName string) lib.RequestPrivilegeFunc {
<add> return func() (string, error) {
<add> fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
<add> if err := cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
<add> return "", err
<add> }
<add> return cli.encodeRegistryAuth(index)
<add> }
<add>}
<add>
<ide> func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
<ide>
<ide> // Resolve the Auth config relevant for this server
<ide><path>api/types/client.go
<ide> type ImageListOptions struct {
<ide> Filters filters.Args
<ide> }
<ide>
<add>// ImagePullOptions holds information to pull images.
<add>type ImagePullOptions struct {
<add> ImageID string
<add> Tag string
<add> // RegistryAuth is the base64 encoded credentials for this server
<add> RegistryAuth string
<add>}
<add>
<ide> // ImageRemoveOptions holds parameters to remove images.
<ide> type ImageRemoveOptions struct {
<ide> ImageID string
<ide><path>cliconfig/config.go
<ide> type AuthConfig struct {
<ide> RegistryToken string `json:"registrytoken,omitempty"`
<ide> }
<ide>
<add>// EncodeToBase64 serializes the auth configuration as JSON base64 payload
<add>func (a AuthConfig) EncodeToBase64() (string, error) {
<add> buf, err := json.Marshal(a)
<add> if err != nil {
<add> return "", err
<add> }
<add> return base64.URLEncoding.EncodeToString(buf), nil
<add>}
<add>
<ide> // ConfigFile ~/.docker/config.json file info
<ide> type ConfigFile struct {
<ide> AuthConfigs map[string]AuthConfig `json:"auths"` | 10 |
Mixed | Javascript | add arraybuffer support | 284871862ed0fc08ed2946be9ee005c16877d05d | <ide><path>doc/api/zlib.md
<ide> Compression strategy.
<ide> <!-- YAML
<ide> added: v0.11.1
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `dictionary` option can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12001
<ide> description: The `dictionary` option can be an Uint8Array now.
<ide> ignored by the decompression classes.
<ide> * `level` {integer} (compression only)
<ide> * `memLevel` {integer} (compression only)
<ide> * `strategy` {integer} (compression only)
<del>* `dictionary` {Buffer|TypedArray|DataView} (deflate/inflate only, empty dictionary by
<del> default)
<add>* `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only,
<add> empty dictionary by default)
<ide> * `info` {boolean} (If `true`, returns an object with `buffer` and `engine`)
<ide>
<ide> See the description of `deflateInit2` and `inflateInit2` at
<ide> Creates and returns a new [Unzip][] object with the given [options][].
<ide>
<ide> <!--type=misc-->
<ide>
<del>All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][], or string as
<del>the first argument, an optional second argument to supply options to the `zlib`
<del>classes and will call the supplied callback with `callback(error, result)`.
<add>All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][],
<add>[`ArrayBuffer`][] or string as the first argument, an optional second argument
<add>to supply options to the `zlib` classes and will call the supplied callback
<add>with `callback(error, result)`.
<ide>
<ide> Every method has a `*Sync` counterpart, which accept the same arguments, but
<ide> without a callback.
<ide> without a callback.
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Compress a chunk of data with [Deflate][].
<ide>
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Compress a chunk of data with [DeflateRaw][].
<ide>
<ide> ### zlib.gunzip(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Decompress a chunk of data with [Gunzip][].
<ide>
<ide> ### zlib.gzip(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Compress a chunk of data with [Gzip][].
<ide>
<ide> ### zlib.inflate(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Decompress a chunk of data with [Inflate][].
<ide>
<ide> ### zlib.inflateRaw(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Decompress a chunk of data with [InflateRaw][].
<ide>
<ide> ### zlib.unzip(buffer[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> <!-- YAML
<ide> added: v0.11.12
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/16042
<add> description: The `buffer` parameter can be an ArrayBuffer.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12223
<ide> description: The `buffer` parameter can be any TypedArray or DataView now.
<ide> changes:
<ide> description: The `buffer` parameter can be an Uint8Array now.
<ide> -->
<ide>
<del>- `buffer` {Buffer|TypedArray|DataView|string}
<add>- `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<ide>
<ide> Decompress a chunk of data with [Unzip][].
<ide>
<ide> [`.flush()`]: #zlib_zlib_flush_kind_callback
<ide> [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<add>[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
<ide> [`Buffer`]: buffer.html#buffer_class_buffer
<ide> [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
<ide> [`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
<ide><path>lib/zlib.js
<ide> const errors = require('internal/errors');
<ide> const Transform = require('_stream_transform');
<ide> const { _extend } = require('util');
<add>const { isAnyArrayBuffer } = process.binding('util');
<ide> const { isArrayBufferView } = require('internal/util/types');
<ide> const binding = process.binding('zlib');
<ide> const assert = require('assert').ok;
<ide> function zlibBuffer(engine, buffer, callback) {
<ide> if (isArrayBufferView(buffer) &&
<ide> Object.getPrototypeOf(buffer) !== Buffer.prototype) {
<ide> buffer = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
<add> } else if (isAnyArrayBuffer(buffer)) {
<add> buffer = Buffer.from(buffer);
<ide> }
<ide> engine.buffers = null;
<ide> engine.nread = 0;
<ide> function zlibBufferSync(engine, buffer) {
<ide> if (typeof buffer === 'string') {
<ide> buffer = Buffer.from(buffer);
<ide> } else if (!isArrayBufferView(buffer)) {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'buffer',
<del> ['string', 'Buffer', 'TypedArray', 'DataView']);
<add> if (isAnyArrayBuffer(buffer)) {
<add> buffer = Buffer.from(buffer);
<add> } else {
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<add> 'buffer',
<add> ['string', 'Buffer', 'TypedArray', 'DataView',
<add> 'ArrayBuffer']);
<add> }
<ide> }
<ide> buffer = processChunkSync(engine, buffer, engine._finishFlushFlag);
<ide> if (engine._info)
<ide> function Zlib(opts, mode) {
<ide>
<ide> dictionary = opts.dictionary;
<ide> if (dictionary !== undefined && !isArrayBufferView(dictionary)) {
<del> throw new errors.TypeError('ERR_INVALID_OPT_VALUE',
<del> 'dictionary',
<del> dictionary);
<add> if (isAnyArrayBuffer(dictionary)) {
<add> dictionary = Buffer.from(dictionary);
<add> } else {
<add> throw new errors.TypeError('ERR_INVALID_OPT_VALUE',
<add> 'dictionary',
<add> dictionary);
<add> }
<ide> }
<ide>
<ide> if (opts.encoding || opts.objectMode || opts.writableObjectMode) {
<ide><path>test/common/README.md
<ide> Checks if `pathname` exists
<ide>
<ide> Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
<ide>
<add>### getBufferSources(buf)
<add>* `buf` [<Buffer>]
<add>* return [<BufferSource[]>]
<add>
<add>Returns an instance of all possible `BufferSource`s of the provided Buffer,
<add>consisting of all `ArrayBufferView` and an `ArrayBuffer`.
<add>
<ide> ### getCallSite(func)
<ide> * `func` [<Function>]
<ide> * return [<String>]
<ide><path>test/common/index.js
<ide> exports.getArrayBufferViews = function getArrayBufferViews(buf) {
<ide> return out;
<ide> };
<ide>
<add>exports.getBufferSources = function getBufferSources(buf) {
<add> return [...exports.getArrayBufferViews(buf), new Uint8Array(buf).buffer];
<add>};
<add>
<ide> // Crash the process on unhandled rejections.
<ide> exports.crashOnUnhandledRejection = function() {
<ide> process.on('unhandledRejection',
<ide><path>test/parallel/test-zlib-convenience-methods.js
<ide> const optsInfo = {
<ide> for (const [type, expect] of [
<ide> ['string', expectStr],
<ide> ['Buffer', expectBuf],
<del> ...common.getArrayBufferViews(expectBuf).map((obj) =>
<add> ...common.getBufferSources(expectBuf).map((obj) =>
<ide> [obj[Symbol.toStringTag], obj]
<ide> )
<ide> ]) {
<ide><path>test/parallel/test-zlib-dictionary.js
<ide> function deflateRawResetDictionaryTest(spdyDict) {
<ide> });
<ide> }
<ide>
<del>for (const dict of [spdyDict, ...common.getArrayBufferViews(spdyDict)]) {
<add>for (const dict of [spdyDict, ...common.getBufferSources(spdyDict)]) {
<ide> basicDictionaryTest(dict);
<ide> deflateResetDictionaryTest(dict);
<ide> rawDictionaryTest(dict);
<ide><path>test/parallel/test-zlib-not-string-or-buffer.js
<ide> const zlib = require('zlib');
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "buffer" argument must be one of type string, Buffer, ' +
<del> 'TypedArray, or DataView'
<add> 'TypedArray, DataView, or ArrayBuffer'
<ide> }
<ide> );
<ide> }); | 7 |
Ruby | Ruby | fix logger format with ruby 3.1 | 5f5bd542b3ad0e9eba69559f539ad6d7113e8e07 | <ide><path>activesupport/test/clean_logger_test.rb
<ide> def test_datetime_format
<ide> @logger.formatter.datetime_format = "%Y-%m-%d"
<ide> @logger.debug "debug"
<ide> assert_equal "%Y-%m-%d", @logger.formatter.datetime_format
<del> assert_match(/D, \[\d\d\d\d-\d\d-\d\d#\d+\] DEBUG -- : debug/, @out.string)
<add> assert_match(/D, \[\d\d\d\d-\d\d-\d\d[ ]?#\d+\] DEBUG -- : debug/, @out.string)
<ide> end
<ide>
<ide> def test_nonstring_formatting | 1 |
Ruby | Ruby | remove sqlite version support caveats [ci skip] | c699cbc4feac8ad9b52c3c4802083328383e7481 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def truncate_tables(*table_names) # :nodoc:
<ide> # end
<ide> #
<ide> # only post with title "first" is created.
<del> # This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also
<del> # supports it.
<ide> #
<ide> # See ActiveRecord::Transactions to learn more.
<ide> # | 1 |
Javascript | Javascript | simulate support of the int8array for ie9 | cebf7836f47cc1be7cb6b0516f3327387f93613c | <ide><path>web/compatibility.js
<ide> if (typeof PDFJS === 'undefined') {
<ide> }
<ide>
<ide> window.Uint8Array = TypedArray;
<add> window.Int8Array = TypedArray;
<ide>
<ide> // we don't need support for set, byteLength for 32-bit array
<ide> // so we can use the TypedArray as well | 1 |
Text | Text | add missing changelog item | 6b99c6f9d376bacbb769264d743c405b495b03ad | <ide><path>CHANGELOG.md
<ide> * Fix containing elements getting focused on SSR markup mismatch. ([@koba04](https://github.com/koba04) in [#11737](https://github.com/facebook/react/pull/11737))
<ide> * Fix `value` and `defaultValue` to ignore Symbol values. ([@nhunzaker](https://github.com/nhunzaker) in [#11741](https://github.com/facebook/react/pull/11741))
<ide> * Fix refs to class components not getting cleaned up when the attribute is removed. ([@bvaughn](https://github.com/bvaughn) in [#12178](https://github.com/facebook/react/pull/12178))
<add>* Fix an IE/Edge issue when rendering inputs into a different window. ([@M-ZubairAhmed](https://github.com/M-ZubairAhmed) in [#11870](https://github.com/facebook/react/pull/11870))
<ide> * Throw with a meaningful message if the component runs after jsdom has been destroyed. ([@gaearon](https://github.com/gaearon) in [#11677](https://github.com/facebook/react/pull/11677))
<ide> * Don't crash if there is a global variable called `opera` with a `null` value. [@alisherdavronov](https://github.com/alisherdavronov) in [#11854](https://github.com/facebook/react/pull/11854))
<ide> * Don't check for old versions of Opera. ([@skiritsis](https://github.com/skiritsis) in [#11921](https://github.com/facebook/react/pull/11921)) | 1 |
Text | Text | improve grammar in api description | 230bce8e86c66751356b1469e0f918788dbff602 | <ide><path>doc/api/tls.md
<ide> Verifies the certificate `cert` is issued to `hostname`.
<ide> Returns {Error} object, populating it with `reason`, `host`, and `cert` on
<ide> failure. On success, returns {undefined}.
<ide>
<del>This function can be overwritten by providing alternative function as part of
<del>the `options.checkServerIdentity` option passed to `tls.connect()`. The
<add>This function can be overwritten by providing an alternative function as the
<add>`options.checkServerIdentity` option that is passed to `tls.connect()`. The
<ide> overwriting function can call `tls.checkServerIdentity()` of course, to augment
<ide> the checks done with additional verification.
<ide> | 1 |
Mixed | Javascript | add middleware guide | 673c23168492c3a2859ea6aa7184f0a80bdc1d8f | <ide><path>docs/guides/middleware.md
<add># Middleware
<add>
<add>Middleware is a Video.js feature that allows interaction with and modification of how the `Player` and `Tech` talk to each other. For more in-depth information, check out our [feature spotlight](http://blog.videojs.com/feature-spotlight-middleware/).
<add>
<add>## Table of Contents
<add>
<add>* [Understanding Middleware](#understanding-middleware)
<add>* [Using Middleware](#using-middleware)
<add>* [setSource](#setsource)
<add>
<add>## Understanding Middleware
<add>
<add>Middleware are functions that return an object with methods matching those on the `Tech`. There are currently a limited set of allowed methods that will be understood by middleware. These are: `buffered`, `currentTime`, `setCurrentTime`, `duration`, `seekable` and `played`.
<add>
<add>These allowed methods are split into two categories: `getters` and `setters`. Setters will be called on the `Player` first and run through middleware(from left to right) before calling the method, with its arguments, on the `Tech`. Getters are called on the `Tech` first and are run though middleware(from right to left) before returning the result to the `Player`.
<add>
<add>```
<add>+----------+ +----------+
<add>| | setter middleware | |
<add>| +----------------------> |
<add>| Player | | Tech |
<add>| <----------------------+ |
<add>| | getter middleware | |
<add>+----------+ +----------+
<add>```
<add>
<add>## Using Middleware
<add>
<add>Middleware are registered to a video MIME type, and will be run for any source with that type.
<add>
<add>```javascript
<add>videojs.use('video/mp4', myMiddleware);
<add>```
<add>
<add>You can also register a middleware on all sources by registering it on `*`.
<add>
<add>```javascript
<add>videojs.use('*', myMiddleware);
<add>```
<add>
<add>Your middleware should be a function that takes a player as an argument and returns an object with methods on it like below:
<add>
<add>```javascript
<add>var myMiddleware = function(player) {
<add> return {
<add> currentTime: function(ct) {
<add> return ct / 2;
<add> },
<add> setCurrentTime: function(time) {
<add> return time * 2;
<add> },
<add> ...
<add> };
<add>};
<add>
<add>videojs.use('*', myMiddleware);
<add>```
<add>
<add>
<add>## setSource
<add>
<add>`setSource` is a required method for all middleware and must be included in the returned object. If your middlware is not manipulating or rejecting the source, you can pass along the source by doing the following:
<add>
<add>```javascript
<add>videojs.use('*', function(player) {
<add> return {
<add> setSource: function(srcObj, next) {
<add> // pass null as the first argument to indicate that the source is not rejected
<add> next(null, srcObj);
<add> }
<add> };
<add>});
<add>```
<add>
<ide><path>src/js/tech/middleware.js
<ide> function setSourceHelper(src = {}, middleware = [], next, player, acc = [], last
<ide> // we've succeeded, now we need to go deeper
<ide> acc.push(mw);
<ide>
<del> // if it's the same time, continue does the current chain
<add> // if it's the same type, continue down the current chain
<ide> // otherwise, we want to go down the new chain
<ide> setSourceHelper(_src,
<ide> src.type === _src.type ? mwrest : middlewares[_src.type], | 2 |
Python | Python | remove redundant path | 6145b7c15334f43d093c6bcd7fb2dd145ec0df98 | <ide><path>spacy/cli/link.py
<ide> def link_package(package_name, link_name, force=False):
<ide>
<ide> def symlink(model_path, link_name, force):
<ide> model_path = Path(model_path)
<del> if not Path(model_path).exists():
<add> if not model_path.exists():
<ide> util.sys_exit(
<ide> "The data should be located in {p}".format(p=model_path),
<ide> title="Can't locate model data") | 1 |
Python | Python | fix one more shlex.split | 1176783310095c7c31ba9963a2aa1d1266c66707 | <ide><path>spacy/cli/project.py
<ide> def project_clone(
<ide> run_command(["git", "-C", str(tmp_dir), "fetch"])
<ide> run_command(["git", "-C", str(tmp_dir), "checkout"])
<ide> shutil.move(str(tmp_dir / Path(name).name), str(project_dir))
<del> msg.good(f"Cloned project '{name}' from {repo}")
<add> msg.good(f"Cloned project '{name}' from {repo} into {project_dir}")
<ide> for sub_dir in DIRS:
<ide> dir_path = project_dir / sub_dir
<ide> if not dir_path.exists():
<ide> def update_dvc_config(
<ide> path = path.resolve()
<ide> dvc_config_path = path / DVC_CONFIG
<ide> if dvc_config_path.exists():
<del> # Cneck if the file was generated using the current config, if not, redo
<add> # Check if the file was generated using the current config, if not, redo
<ide> with dvc_config_path.open("r", encoding="utf8") as f:
<ide> ref_hash = f.readline().strip().replace("# ", "")
<ide> if ref_hash == config_hash and not force:
<ide> def run_commands(
<ide> for command in commands:
<ide> # Substitute variables, e.g. "./{NAME}.json"
<ide> command = command.format(**variables)
<del> command = shlex.split(command)
<add> command = shlex.split(command, posix=not is_windows)
<ide> # TODO: is this needed / a good idea?
<ide> if len(command) and command[0] == "python":
<ide> command[0] = sys.executable | 1 |
Javascript | Javascript | make a method used externaly (in a test) public | 1d7c990424e1e6f72fd2732901d8e6c413823852 | <ide><path>Libraries/BatchedBridge/MessageQueue.js
<ide> class MessageQueue {
<ide> };
<ide> }
<ide>
<del> _getCallableModule(name: string) {
<add> getCallableModule(name: string) {
<ide> const getValue = this._lazyCallableModules[name];
<ide> return getValue ? getValue() : null;
<ide> }
<ide> class MessageQueue {
<ide> if (this.__spy) {
<ide> this.__spy({ type: TO_JS, module, method, args});
<ide> }
<del> const moduleMethods = this._getCallableModule(module);
<add> const moduleMethods = this.getCallableModule(module);
<ide> invariant(
<ide> !!moduleMethods,
<ide> 'Module %s is not a registered callable module (calling %s)',
<ide><path>Libraries/BatchedBridge/__tests__/MessageQueue-test.js
<ide> describe('MessageQueue', function() {
<ide> it('should return lazily registered module', () => {
<ide> const dummyModule = {}, name = 'modulesName';
<ide> queue.registerLazyCallableModule(name, () => dummyModule);
<del> expect(queue._getCallableModule(name)).toEqual(dummyModule);
<add>
<add> expect(queue.getCallableModule(name)).toEqual(dummyModule);
<ide> });
<ide>
<ide> it('should not initialize lazily registered module before it was used for the first time', () => {
<ide> describe('MessageQueue', function() {
<ide> const dummyModule = {}, name = 'modulesName';
<ide> const factory = jest.fn(() => dummyModule);
<ide> queue.registerLazyCallableModule(name, factory);
<del> queue._getCallableModule(name);
<del> queue._getCallableModule(name);
<add> queue.getCallableModule(name);
<add> queue.getCallableModule(name);
<ide> expect(factory).toHaveBeenCalledTimes(1);
<ide> });
<ide> }); | 2 |
Text | Text | update master documentation link in readme | b6321452738925983ba1306fb5396982d64f408a | <ide><path>README.md
<ide> Choose the right framework for every part of a model's lifetime
<ide> | [Quick tour: Fine-tuning/usage scripts](#quick-tour-of-the-fine-tuningusage-scripts) | Using provided scripts: GLUE, SQuAD and Text generation |
<ide> | [Migrating from pytorch-transformers to transformers](#Migrating-from-pytorch-transformers-to-transformers) | Migrating your code from pytorch-transformers to transformers |
<ide> | [Migrating from pytorch-pretrained-bert to pytorch-transformers](#Migrating-from-pytorch-pretrained-bert-to-transformers) | Migrating your code from pytorch-pretrained-bert to transformers |
<del>| [Documentation][(v2.2.0)](https://huggingface.co/transformers/v2.2.0) [(v2.1.1)](https://huggingface.co/transformers/v2.1.1) [(v2.0.0)](https://huggingface.co/transformers/v2.0.0) [(v1.2.0)](https://huggingface.co/transformers/v1.2.0) [(v1.1.0)](https://huggingface.co/transformers/v1.1.0) [(v1.0.0)](https://huggingface.co/transformers/v1.0.0) [(master](https://huggingface.co/transformers) | Full API documentation and more |
<add>| [Documentation][(v2.2.0)](https://huggingface.co/transformers/v2.2.0) [(v2.1.1)](https://huggingface.co/transformers/v2.1.1) [(v2.0.0)](https://huggingface.co/transformers/v2.0.0) [(v1.2.0)](https://huggingface.co/transformers/v1.2.0) [(v1.1.0)](https://huggingface.co/transformers/v1.1.0) [(v1.0.0)](https://huggingface.co/transformers/v1.0.0) [(master)](https://huggingface.co/transformers) | Full API documentation and more |
<ide>
<ide> ## Installation
<ide> | 1 |
Javascript | Javascript | use strict comparison when evaluating checked-ness | 5ac7daea72ec31cf337d1d21b13f0d17ff33994f | <ide><path>src/ng/directive/input.js
<ide> function radioInputType(scope, element, attr, ctrl) {
<ide> if (doTrim) {
<ide> value = trim(value);
<ide> }
<del> // Strict comparison would cause a BC
<del> // eslint-disable-next-line eqeqeq
<del> element[0].checked = (value == ctrl.$viewValue);
<add> element[0].checked = (value === ctrl.$viewValue);
<ide> };
<ide>
<ide> attr.$observe('value', ctrl.$render);
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> expect($rootScope.color).toBe('blue');
<ide> });
<ide>
<del>
<del> // We generally use strict comparison. This tests behavior we cannot change without a BC
<del> it('should use non-strict comparison the evaluate checked-ness', function() {
<add> it('should treat the value as a string when evaluating checked-ness', function() {
<ide> var inputElm = helper.compileInput(
<ide> '<input type="radio" ng-model="model" value="0" />');
<ide>
<ide> $rootScope.$apply('model = \'0\'');
<ide> expect(inputElm[0].checked).toBe(true);
<ide>
<ide> $rootScope.$apply('model = 0');
<del> expect(inputElm[0].checked).toBe(true);
<add> expect(inputElm[0].checked).toBe(false);
<ide> });
<ide>
<ide>
<ide> describe('input', function() {
<ide> });
<ide>
<ide>
<add> it('should use strict comparison between model and value', function() {
<add> $rootScope.selected = false;
<add> var inputElm = helper.compileInput('<input type="radio" ng-model="selected" ng-value="false">' +
<add> '<input type="radio" ng-model="selected" ng-value="\'\'">' +
<add> '<input type="radio" ng-model="selected" ng-value="0">');
<add>
<add> expect(inputElm[0].checked).toBe(true);
<add> expect(inputElm[1].checked).toBe(false);
<add> expect(inputElm[2].checked).toBe(false);
<add> });
<add>
<add>
<ide> it('should watch the expression', function() {
<ide> var inputElm = helper.compileInput('<input type="radio" ng-model="selected" ng-value="value">');
<ide> | 2 |
PHP | PHP | add test for new getassociation() being strict | 8a612f2e009b9b66ddbd84aaee59f0cf4681b9e9 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\Validator;
<add>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * Used to test correct class is instantiated when using TableRegistry::get();
<ide> public function testAssociationDotSyntax()
<ide> );
<ide> }
<ide>
<add> /**
<add> * Tests that the getAssociation() method throws an exception on non-existent ones.
<add> *
<add> * @return void
<add> */
<add> public function testGetAssociationNonExistent()
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add>
<add> TableRegistry::get('Groups')->getAssociation('FooBar');
<add> }
<add>
<ide> /**
<ide> * Tests that belongsTo() creates and configures correctly the association
<ide> * | 1 |
Ruby | Ruby | fix incorrect comment | 8aa537c9452d40aeaf25e6d7e0c5bb1205b05d1a | <ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> def to_yaml(*args)
<ide> UNSAFE_STRING_METHODS.each do |unsafe_method|
<ide> class_eval <<-EOT, __FILE__, __LINE__ + 1
<ide> def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
<del> to_str.#{unsafe_method}(*args, &block) # to_str.gsub(*args, &block)
<add> to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
<ide> end # end
<ide>
<ide> def #{unsafe_method}!(*args) # def capitalize!(*args) | 1 |
Text | Text | add reactnext 2017 to conference list | b22387d4fe471255f17e26e898bc8c704920b084 | <ide><path>docs/community/conferences.md
<ide> September 6-7 in Wroclaw, Poland
<ide>
<ide> [Website](http://react-native.eu/)
<ide>
<add>### ReactNext 2017
<add>September 8-10 in Tel Aviv, Israel
<add>
<add>[Website](http://react-next.com/) - [Twitter](https://twitter.com/ReactNext)
<add>
<ide> ### React Boston 2017
<ide> September 23-24 in Boston, Massachusetts USA
<ide> | 1 |
Python | Python | add test for 46d8a66 | 526be4082329d16ecf7b1fa40b81f2008396a325 | <ide><path>spacy/tests/serialize/test_serialize_language.py
<ide>
<ide> from ..util import make_tempdir
<ide> from ...language import Language
<add>from ...tokenizer import Tokenizer
<ide>
<ide> import pytest
<add>import re
<ide>
<ide>
<ide> @pytest.fixture
<ide> def test_serialize_language_meta_disk(meta_data):
<ide> language.to_disk(d)
<ide> new_language = Language().from_disk(d)
<ide> assert new_language.meta == language.meta
<add>
<add>
<add>def test_serialize_with_custom_tokenizer():
<add> """Test that serialization with custom tokenizer works without token_match.
<add> See: https://support.prodi.gy/t/how-to-save-a-custom-tokenizer/661/2
<add> """
<add> prefix_re = re.compile(r'''1/|2/|:[0-9][0-9][A-K]:|:[0-9][0-9]:''')
<add> suffix_re = re.compile(r'''''')
<add> infix_re = re.compile(r'''[~]''')
<add>
<add> def custom_tokenizer(nlp):
<add> return Tokenizer(nlp.vocab,
<add> {},
<add> prefix_search=prefix_re.search,
<add> suffix_search=suffix_re.search,
<add> infix_finditer=infix_re.finditer)
<add>
<add> nlp = Language()
<add> nlp.tokenizer = custom_tokenizer(nlp)
<add> with make_tempdir() as d:
<add> nlp.to_disk(d) | 1 |
PHP | PHP | fix bug in lockout | 407ee032a90e9e2a26774f4a346228f54a132eb7 | <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php
<ide> protected function hasTooManyLoginAttempts(Request $request)
<ide> {
<ide> $attempts = $this->getLoginAttempts($request);
<ide>
<del> if ($attempts > 5) {
<del> Cache::add($this->getLoginLockExpirationKey($request), time() + 60, 1);
<add> $lockedOut = Cache::has($this->getLoginLockExpirationKey($request));
<add>
<add> if ($attempts > 5 || $lockedOut) {
<add> if (! $lockedOut) {
<add> Cache::put($this->getLoginLockExpirationKey($request), time() + 60, 1);
<add> }
<ide>
<ide> return true;
<ide> } | 1 |
Ruby | Ruby | fix build failures on pg | a69842447739d2f22657e347bad3b23c64b0c6b8 | <ide><path>activerecord/lib/active_record/relation/predicate_builder.rb
<ide> def expand_from_hash(attributes)
<ide> expand_from_hash(query).reduce(&:and)
<ide> end
<ide> queries.reduce(&:or)
<add> # FIXME: Deprecate this and provide a public API to force equality
<add> elsif (value.is_a?(Range) || value.is_a?(Array)) &&
<add> table.type(key.to_s).respond_to?(:subtype)
<add> BasicObjectHandler.new(self).call(table.arel_attribute(key), value)
<ide> else
<ide> build(table.arel_attribute(key), value)
<ide> end | 1 |
Javascript | Javascript | change warnings to use expectdev | 4aa9cfb6ba33efb7bb823721df948f78444df673 | <ide><path>src/addons/__tests__/ReactFragment-test.js
<ide> describe('ReactFragment', () => {
<ide>
<ide> ReactFragment.create({1: <span />, 2: <span />});
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Child objects should have non-numeric keys so ordering is preserved.'
<ide> );
<ide> });
<ide>
<ide> it('should warn if passing null to createFragment', () => {
<ide> spyOn(console, 'error');
<ide> ReactFragment.create(null);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'React.addons.createFragment only accepts a single object.'
<ide> );
<ide> });
<ide>
<ide> it('should warn if passing an array to createFragment', () => {
<ide> spyOn(console, 'error');
<ide> ReactFragment.create([]);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'React.addons.createFragment only accepts a single object.'
<ide> );
<ide> });
<ide>
<ide> it('should warn if passing a ReactElement to createFragment', () => {
<ide> spyOn(console, 'error');
<ide> ReactFragment.create(<div />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'React.addons.createFragment does not accept a ReactElement without a ' +
<ide> 'wrapper object.'
<ide> );
<ide><path>src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js
<ide> describe('ReactCSSTransitionGroup', () => {
<ide> );
<ide>
<ide> // Warning about the missing transitionLeaveTimeout prop
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should not warn if timeouts is zero', () => {
<ide> describe('ReactCSSTransitionGroup', () => {
<ide> container
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should clean-up silently after the timeout elapses', () => {
<ide> describe('ReactCSSTransitionGroup', () => {
<ide> }
<ide>
<ide> // No warnings
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> // The leaving child has been removed
<ide> expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
<ide><path>src/addons/transitions/__tests__/ReactTransitionGroup-test.js
<ide> describe('ReactTransitionGroup', () => {
<ide> var container;
<ide>
<ide> function normalizeCodeLocInfo(str) {
<del> return str.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
<ide> }
<ide>
<ide> beforeEach(() => {
<ide> describe('ReactTransitionGroup', () => {
<ide>
<ide> ReactDOM.render(<Component />, container);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: flattenChildren(...): ' +
<ide> 'Encountered two children with the same key, `1`. ' +
<ide> 'Child keys must be unique; when two children share a key, ' +
<ide> 'only the first child will be used.'
<ide> );
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<ide> 'Warning: flattenChildren(...): ' +
<ide> 'Encountered two children with the same key, `1`. ' +
<ide> 'Child keys must be unique; when two children share a key, ' +
<ide><path>src/isomorphic/classic/__tests__/ReactContextValidator-test.js
<ide> var ReactTestUtils;
<ide>
<ide> describe('ReactContextValidator', () => {
<ide> function normalizeCodeLocInfo(str) {
<del> return str.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
<ide> }
<ide>
<ide> beforeEach(() => {
<ide> describe('ReactContextValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Failed context type: ' +
<ide> 'The context `foo` is marked as required in `Component`, but its value ' +
<ide> 'is `undefined`.\n' +
<ide> describe('ReactContextValidator', () => {
<ide> );
<ide>
<ide> // Previous call should not error
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> var ComponentInFooNumberContext = React.createClass({
<ide> childContextTypes: {
<ide> describe('ReactContextValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<ComponentInFooNumberContext fooValue={123} />);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<ide> 'Warning: Failed context type: ' +
<ide> 'Invalid context `foo` of type `number` supplied ' +
<ide> 'to `Component`, expected `string`.\n' +
<ide> describe('ReactContextValidator', () => {
<ide> });
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Failed childContext type: ' +
<ide> 'The child context `foo` is marked as required in `Component`, but its ' +
<ide> 'value is `undefined`.\n' +
<ide> describe('ReactContextValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
<ide> 'Warning: Failed childContext type: ' +
<ide> 'Invalid child context `foo` of type `number` ' +
<ide> 'supplied to `Component`, expected `string`.\n' +
<ide> describe('ReactContextValidator', () => {
<ide> );
<ide>
<ide> // Previous calls should not log errors
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> });
<ide><path>src/isomorphic/classic/class/__tests__/ReactBind-test.js
<ide> describe('autobinding', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<TestBindComponent />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: bind(): You are binding a component method to the component. ' +
<ide> 'React does this for you automatically in a high-performance ' +
<ide> 'way, so you can safely remove this call. See TestBindComponent'
<ide> describe('autobinding', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<TestBindComponent />);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> });
<ide><path>src/isomorphic/classic/class/__tests__/ReactBindOptout-test.js
<ide> describe('autobind optout', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<TestBindComponent />);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn if you pass an manually bound method to setState', () => {
<ide> describe('autobind optout', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<TestBindComponent />);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> });
<ide><path>src/isomorphic/classic/class/__tests__/ReactClass-test.js
<ide> describe('ReactClass-spec', () => {
<ide> return <span>{this.props.prop}</span>;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component: prop type `prop` is invalid; ' +
<ide> 'it must be a function, usually from React.PropTypes.'
<ide> );
<ide> describe('ReactClass-spec', () => {
<ide> return <span>{this.props.prop}</span>;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component: context type `prop` is invalid; ' +
<ide> 'it must be a function, usually from React.PropTypes.'
<ide> );
<ide> describe('ReactClass-spec', () => {
<ide> return <span>{this.props.prop}</span>;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component: child context type `prop` is invalid; ' +
<ide> 'it must be a function, usually from React.PropTypes.'
<ide> );
<ide> describe('ReactClass-spec', () => {
<ide> return <div />;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: A component has a method called componentShouldUpdate(). Did you ' +
<ide> 'mean shouldComponentUpdate()? The name is phrased as a question ' +
<ide> 'because the function is expected to return a value.'
<ide> describe('ReactClass-spec', () => {
<ide> return <div />;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'Warning: NamedComponent has a method called componentShouldUpdate(). Did you ' +
<ide> 'mean shouldComponentUpdate()? The name is phrased as a question ' +
<ide> 'because the function is expected to return a value.'
<ide> describe('ReactClass-spec', () => {
<ide> return <div />;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: A component has a method called componentWillRecieveProps(). Did you ' +
<ide> 'mean componentWillReceiveProps()?'
<ide> );
<ide> describe('ReactClass-spec', () => {
<ide> return <div />;
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(4);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'createClass(...): `mixins` is now a static property and should ' +
<ide> 'be defined inside "statics".'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'createClass(...): `propTypes` is now a static property and should ' +
<ide> 'be defined inside "statics".'
<ide> );
<del> expect(console.error.calls.argsFor(2)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(2)[0]).toBe(
<ide> 'createClass(...): `contextTypes` is now a static property and ' +
<ide> 'should be defined inside "statics".'
<ide> );
<del> expect(console.error.calls.argsFor(3)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(3)[0]).toBe(
<ide> 'createClass(...): `childContextTypes` is now a static property and ' +
<ide> 'should be defined inside "statics".'
<ide> );
<ide> describe('ReactClass-spec', () => {
<ide> });
<ide>
<ide> expect(() => Component()).toThrow();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Something is calling a React component directly. Use a ' +
<ide> 'factory or JSX instead. See: https://fb.me/react-legacyfactory'
<ide> );
<ide><path>src/isomorphic/classic/class/__tests__/ReactClassMixin-test.js
<ide> describe('ReactClass-mixin', () => {
<ide> },
<ide> });
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', () => {
<ide> },
<ide> });
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', () => {
<ide> },
<ide> });
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', () => {
<ide> },
<ide> });
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide><path>src/isomorphic/classic/element/__tests__/ReactElement-test.js
<ide> describe('ReactElement', () => {
<ide> );
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> ReactDOM.render(<Parent />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Child: `key` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide> describe('ReactElement', () => {
<ide> );
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> ReactDOM.render(<Parent />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Child: `key` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide> describe('ReactElement', () => {
<ide> it('should warn when `key` is being accessed on a host element', () => {
<ide> spyOn(console, 'error');
<ide> var element = <div key="3" />;
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> void element.props.key;
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'div: `key` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide> describe('ReactElement', () => {
<ide> );
<ide> },
<ide> });
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> ReactDOM.render(<Parent />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Child: `ref` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide> describe('ReactElement', () => {
<ide> children: 'text',
<ide> }, a);
<ide> expect(element.props.children).toBe(a);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not override children if no rest args are provided', () => {
<ide> describe('ReactElement', () => {
<ide> children: 'text',
<ide> });
<ide> expect(element.props.children).toBe('text');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('overrides children if null is provided as an argument', () => {
<ide> describe('ReactElement', () => {
<ide> children: 'text',
<ide> }, null);
<ide> expect(element.props.children).toBe(null);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('merges rest arguments onto the children prop in an array', () => {
<ide> describe('ReactElement', () => {
<ide> var c = 3;
<ide> var element = React.createFactory(ComponentClass)(null, a, b, c);
<ide> expect(element.props.children).toEqual([1, 2, 3]);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> // NOTE: We're explicitly not using JSX here. This is intended to test
<ide> describe('ReactElement', () => {
<ide>
<ide> var element = React.createElement(StaticMethodComponentClass);
<ide> expect(element.type.someStaticMethod()).toBe('someReturnValue');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> // NOTE: We're explicitly not using JSX here. This is intended to test
<ide> describe('ReactElement', () => {
<ide> });
<ide> var test = ReactTestUtils.renderIntoDocument(<Test value={+undefined} />);
<ide> expect(test.props.value).toBeNaN();
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> // NOTE: We're explicitly not using JSX here. This is intended to test
<ide><path>src/isomorphic/classic/element/__tests__/ReactElementClone-test.js
<ide> describe('ReactElementClone', () => {
<ide>
<ide> React.cloneElement(<div />, null, [<div />, <div />]);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactElementClone', () => {
<ide>
<ide> React.cloneElement(<div />, null, [<div key="#1" />, <div key="#2" />]);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the element is directly in rest args', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> React.cloneElement(<div />, null, <div />, <div />);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the array contains a non-element', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> React.cloneElement(<div />, null, [{}, {}]);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should check declared prop types after clone', () => {
<ide> describe('ReactElementClone', () => {
<ide> },
<ide> });
<ide> ReactTestUtils.renderIntoDocument(React.createElement(GrandParent));
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Failed prop type: ' +
<ide> 'Invalid prop `color` of type `number` supplied to `Component`, ' +
<ide> 'expected `string`.\n' +
<ide><path>src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js
<ide> var ReactTestUtils;
<ide>
<ide> describe('ReactElementValidator', () => {
<ide> function normalizeCodeLocInfo(str) {
<del> return str.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
<ide> }
<ide>
<ide> var ComponentClass;
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, [Component(), Component()]);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(ComponentWrapper)
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop. ' +
<ide> 'Check the render method of `InnerClass`. ' +
<ide> 'It was passed a child from ComponentWrapper. '
<ide> describe('ReactElementValidator', () => {
<ide> ];
<ide> ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Each child in an array or iterator should have a unique ' +
<ide> '"key" prop. See https://fb.me/react-warning-keys for more information.\n' +
<ide> ' in div (at **)'
<ide> describe('ReactElementValidator', () => {
<ide> ];
<ide> ReactTestUtils.renderIntoDocument(<div>{divs}</div>);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Each child in an array or iterator should have a unique ' +
<ide> '"key" prop. Check the top-level render call using <div>. See ' +
<ide> 'https://fb.me/react-warning-keys for more information.\n' +
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<GrandParent />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Each child in an array or iterator should have a unique ' +
<ide> '"key" prop. Check the render method of `Component`. See ' +
<ide> 'https://fb.me/react-warning-keys for more information.\n' +
<ide> describe('ReactElementValidator', () => {
<ide> </Wrapper>
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('warns for keys for iterables of elements in rest args', () => {
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, iterable);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, [Component({key: '#1'}), Component({key: '#2'})]);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warns for iterable elements with keys', () => {
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, iterable);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the element is directly in rest args', () => {
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, Component(), Component());
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the array contains a non-element', () => {
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> Component(null, [{}, {}]);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> // TODO: These warnings currently come from the composite component, but
<ide> describe('ReactElementValidator', () => {
<ide> },
<ide> });
<ide> ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Failed prop type: ' +
<ide> 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
<ide> 'expected `string`.\n' +
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(null);
<ide> React.createElement(true);
<ide> React.createElement(123);
<del> expect(console.error.calls.count()).toBe(4);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(2)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(2)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(3)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(3)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components).'
<ide> );
<ide> React.createElement('div');
<del> expect(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.count()).toBe(4);
<ide> });
<ide>
<ide> it('includes the owner name when passing null, undefined, boolean, or number', () => {
<ide> describe('ReactElementValidator', () => {
<ide> 'or a class/function (for composite components) but got: null. Check ' +
<ide> 'the render method of `ParentComp`.'
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components). Check the render method of ' +
<ide> describe('ReactElementValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(React.createElement(Component));
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Failed prop type: The prop `prop` is marked as required in ' +
<ide> '`Component`, but its value is `null`.\n' +
<ide> ' in Component'
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(Component, {prop:null})
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Failed prop type: The prop `prop` is marked as required in ' +
<ide> '`Component`, but its value is `null`.\n' +
<ide> ' in Component'
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(Component, {prop: 42})
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Failed prop type: ' +
<ide> 'The prop `prop` is marked as required in `Component`, but its value ' +
<ide> 'is `undefined`.\n' +
<ide> ' in Component'
<ide> );
<ide>
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'Warning: Failed prop type: ' +
<ide> 'Invalid prop `prop` of type `number` supplied to ' +
<ide> '`Component`, expected `string`.\n' +
<ide> describe('ReactElementValidator', () => {
<ide> );
<ide>
<ide> // Should not error for strings
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('should warn if a PropType creator is used as a PropType', () => {
<ide> describe('ReactElementValidator', () => {
<ide> React.createElement(Component, {myProp: {value: 'hi'}})
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component: type specification of prop `myProp` is invalid; ' +
<ide> 'the type checker function must return `null` or an `Error` but ' +
<ide> 'returned a function. You may have forgotten to pass an argument to ' +
<ide> describe('ReactElementValidator', () => {
<ide> });
<ide> var TestFactory = React.createFactory(TestComponent);
<ide> expect(TestFactory.type).toBe(TestComponent);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Factory.type is deprecated. Access the class directly before ' +
<ide> 'passing it to createFactory.'
<ide> );
<ide> // Warn once, not again
<ide> expect(TestFactory.type).toBe(TestComponent);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('does not warn when using DOM node as children', () => {
<ide> describe('ReactElementValidator', () => {
<ide> var node = document.createElement('div');
<ide> // This shouldn't cause a stack overflow or any other problems (#3883)
<ide> ReactTestUtils.renderIntoDocument(<DOMContainer>{node}</DOMContainer>);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should not enumerate enumerable numbers (#4776)', () => {
<ide> describe('ReactElementValidator', () => {
<ide> spyOn(console, 'error');
<ide> var Foo = undefined;
<ide> void <Foo>{[<div />]}</Foo>;
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: React.createElement: type should not be null, undefined, ' +
<ide> 'boolean, or number. It should be a string (for DOM elements) or a ' +
<ide> 'ReactClass (for composite components).'
<ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
<ide> describe('ReactPropTypes', () => {
<ide> var instance = <Component label={<div />} />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should warn when passing no label and isRequired is set', () => {
<ide> describe('ReactPropTypes', () => {
<ide> var instance = <Component />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should be implicitly optional and not warn without values', () => {
<ide> describe('ReactPropTypes', () => {
<ide> k4: null,
<ide> k5: undefined,
<ide> }));
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should not warn for iterables', () => {
<ide> describe('ReactPropTypes', () => {
<ide>
<ide> PropTypes.oneOf('red', 'blue');
<ide>
<del> expect(console.error).toHaveBeenCalled();
<del> expect(console.error.calls.argsFor(0)[0])
<add> expectDev(console.error).toHaveBeenCalled();
<add> expectDev(console.error.calls.argsFor(0)[0])
<ide> .toContain('Invalid argument supplied to oneOf, expected an instance of array.');
<ide>
<ide> typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red');
<ide> describe('ReactPropTypes', () => {
<ide>
<ide> PropTypes.oneOfType(PropTypes.string, PropTypes.number);
<ide>
<del> expect(console.error).toHaveBeenCalled();
<del> expect(console.error.calls.argsFor(0)[0])
<add> expectDev(console.error).toHaveBeenCalled();
<add> expectDev(console.error.calls.argsFor(0)[0])
<ide> .toContain('Invalid argument supplied to oneOfType, expected an instance of array.');
<ide>
<ide> typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []);
<ide> describe('ReactPropTypes', () => {
<ide>
<ide> var instance = <Component num={6} />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactPropTypes', () => {
<ide>
<ide> var instance = <Component num={5} />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> }
<ide> );
<ide> });
<ide><path>src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js
<ide> describe('ReactJSXElement', () => {
<ide> var a = 1;
<ide> var element = <Component children="text">{a}</Component>;
<ide> expect(element.props.children).toBe(a);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not override children if no JSX children are provided', () => {
<ide> spyOn(console, 'error');
<ide> var element = <Component children="text" />;
<ide> expect(element.props.children).toBe('text');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('overrides children if null is provided as a JSX child', () => {
<ide> spyOn(console, 'error');
<ide> var element = <Component children="text">{null}</Component>;
<ide> expect(element.props.children).toBe(null);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('overrides children if undefined is provided as an argument', () => {
<ide> describe('ReactJSXElement', () => {
<ide> var c = 3;
<ide> var element = <Component>{a}{b}{c}</Component>;
<ide> expect(element.props.children).toEqual([1, 2, 3]);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('allows static methods to be called using the type property', () => {
<ide> describe('ReactJSXElement', () => {
<ide>
<ide> var element = <StaticMethodComponent />;
<ide> expect(element.type.someStaticMethod()).toBe('someReturnValue');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('identifies valid elements', () => {
<ide><path>src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> void <Component>{[<Component />, <Component />]}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<ComponentWrapper />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop. ' +
<ide> 'Check the render method of `InnerComponent`. ' +
<ide> 'It was passed a child from ComponentWrapper. '
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> void <Component>{iterable}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> void <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warns for iterable elements with keys', () => {
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> void <Component>{iterable}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn for numeric keys in entry iterable as a child', () => {
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> void <Component>{iterable}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the element is directly as children', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> void <Component><Component /><Component /></Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('does not warn when the child array contains non-elements', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> void <Component>{[{}, {}]}</Component>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> // TODO: These warnings currently come from the composite component, but
<ide> describe('ReactJSXElementValidator', () => {
<ide> void <Null />;
<ide> void <True />;
<ide> void <Num />;
<del> expect(console.error.calls.count()).toBe(4);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'type should not be null, undefined, boolean, or number. It should be ' +
<ide> 'a string (for DOM elements) or a ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain(
<ide> 'type should not be null, undefined, boolean, or number. It should be ' +
<ide> 'a string (for DOM elements) or a ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(2)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(2)[0]).toContain(
<ide> 'type should not be null, undefined, boolean, or number. It should be ' +
<ide> 'a string (for DOM elements) or a ReactClass (for composite components).'
<ide> );
<del> expect(console.error.calls.argsFor(3)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(3)[0]).toContain(
<ide> 'type should not be null, undefined, boolean, or number. It should be ' +
<ide> 'a string (for DOM elements) or a ReactClass (for composite components).'
<ide> );
<ide> void <Div />;
<del> expect(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.count()).toBe(4);
<ide> });
<ide>
<ide> it('should check default prop values', () => {
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactJSXElementValidator', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactJSXElementValidator', () => {
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent />);
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={42} />);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactJSXElementValidator', () => {
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />);
<ide>
<ide> // Should not error for strings
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('should warn on invalid prop types', () => {
<ide> describe('ReactJSXElementValidator', () => {
<ide> prop: null,
<ide> };
<ide> ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' +
<ide> 'function, usually from React.PropTypes.'
<ide> );
<ide> describe('ReactJSXElementValidator', () => {
<ide> prop: null,
<ide> };
<ide> ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'NullContextTypeComponent: context type `prop` is invalid; it must ' +
<ide> 'be a function, usually from React.PropTypes.'
<ide> );
<ide> describe('ReactJSXElementValidator', () => {
<ide> prop: 'foo',
<ide> });
<ide> ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'getDefaultProps is only used on classic React.createClass definitions.' +
<ide> ' Use a static property named `defaultProps` instead.'
<ide> );
<ide><path>src/renderers/dom/__tests__/ReactDOMProduction-test.js
<ide> describe('ReactDOMProduction', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> warning(false, 'Do cows go moo?');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should use prod React', () => {
<ide> describe('ReactDOMProduction', () => {
<ide> // no key warning
<ide> void <div>{[<span />]}</div>;
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should handle a simple flow', () => {
<ide><path>src/renderers/dom/shared/__tests__/CSSPropertyOperations-test.js
<ide> describe('CSSPropertyOperations', () => {
<ide> spyOn(console, 'error');
<ide> var root = document.createElement('div');
<ide> ReactDOM.render(<Comp />, root);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Unsupported style property background-color. Did you mean backgroundColor? ' +
<ide> 'Check the render method of `Comp`.'
<ide> );
<ide> describe('CSSPropertyOperations', () => {
<ide> ReactDOM.render(<Comp />, root);
<ide> ReactDOM.render(<Comp style={styles} />, root);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Unsupported style property -ms-transform. Did you mean msTransform? ' +
<ide> 'Check the render method of `Comp`.'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toEqual(
<add> expectDev(console.error.calls.argsFor(1)[0]).toEqual(
<ide> 'Warning: Unsupported style property -webkit-transform. Did you mean WebkitTransform? ' +
<ide> 'Check the render method of `Comp`.'
<ide> );
<ide> describe('CSSPropertyOperations', () => {
<ide> var root = document.createElement('div');
<ide> ReactDOM.render(<Comp />, root);
<ide> // msTransform is correct already and shouldn't warn
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Unsupported vendor-prefixed style property oTransform. ' +
<ide> 'Did you mean OTransform? Check the render method of `Comp`.'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toEqual(
<add> expectDev(console.error.calls.argsFor(1)[0]).toEqual(
<ide> 'Warning: Unsupported vendor-prefixed style property webkitTransform. ' +
<ide> 'Did you mean WebkitTransform? Check the render method of `Comp`.'
<ide> );
<ide> describe('CSSPropertyOperations', () => {
<ide> spyOn(console, 'error');
<ide> var root = document.createElement('div');
<ide> ReactDOM.render(<Comp />, root);
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Style property values shouldn\'t contain a semicolon. ' +
<ide> 'Check the render method of `Comp`. Try "backgroundColor: blue" instead.',
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toEqual(
<add> expectDev(console.error.calls.argsFor(1)[0]).toEqual(
<ide> 'Warning: Style property values shouldn\'t contain a semicolon. ' +
<ide> 'Check the render method of `Comp`. Try "color: red" instead.',
<ide> );
<ide> describe('CSSPropertyOperations', () => {
<ide> var root = document.createElement('div');
<ide> ReactDOM.render(<Comp />, root);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: `NaN` is an invalid value for the `fontSize` css style property. ' +
<ide> 'Check the render method of `Comp`.'
<ide> );
<ide><path>src/renderers/dom/shared/__tests__/ReactBrowserEventEmitter-test.js
<ide> describe('ReactBrowserEventEmitter', () => {
<ide> expect(idCallOrder[0]).toBe(getInternal(CHILD));
<ide> expect(idCallOrder[1]).toBe(getInternal(PARENT));
<ide> expect(idCallOrder[2]).toBe(getInternal(GRANDPARENT));
<del> expect(console.error.calls.count()).toEqual(0);
<add> expectDev(console.error.calls.count()).toEqual(0);
<ide> });
<ide>
<ide> /**
<ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', () => {
<ide> var inputValueTracking;
<ide>
<ide> function normalizeCodeLocInfo(str) {
<del> return str.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
<ide> }
<ide>
<ide> beforeEach(() => {
<ide> describe('ReactDOMComponent', () => {
<ide> var stub = ReactTestUtils.renderIntoDocument(<App />);
<ide> style.position = 'absolute';
<ide> stub.setState({style: style});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: `div` was passed a style object that has previously been ' +
<ide> 'mutated. Mutating `style` is deprecated. Consider cloning it ' +
<ide> 'beforehand. Check the `render` of `App`. Previous style: ' +
<ide> describe('ReactDOMComponent', () => {
<ide> style.background = 'green';
<ide> stub.setState({style: {background: 'green'}});
<ide> // already warned once for the same component and owner
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> style = {background: 'red'};
<ide> var div = document.createElement('div');
<ide> ReactDOM.render(<span style={style}></span>, div);
<ide> style.background = 'blue';
<ide> ReactDOM.render(<span style={style}></span>, div);
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('should warn for unknown prop', () => {
<ide> spyOn(console, 'error');
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(<div foo="bar" />, container);
<del> expect(console.error.calls.count(0)).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count(0)).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Unknown prop `foo` on <div> tag. Remove this prop from the element. ' +
<ide> 'For details, see https://fb.me/react-unknown-prop\n in div (at **)'
<ide> );
<ide> describe('ReactDOMComponent', () => {
<ide> spyOn(console, 'error');
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(<div foo="bar" baz="qux" />, container);
<del> expect(console.error.calls.count(0)).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count(0)).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Unknown props `foo`, `baz` on <div> tag. Remove these props from the element. ' +
<ide> 'For details, see https://fb.me/react-unknown-prop\n in div (at **)'
<ide> );
<ide> describe('ReactDOMComponent', () => {
<ide> spyOn(console, 'error');
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(<div onDblClick={() => {}} />, container);
<del> expect(console.error.calls.count(0)).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count(0)).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: Unknown event handler property onDblClick. Did you mean `onDoubleClick`?\n in div (at **)'
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> }
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component />);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should warn nicely about NaN in style', () => {
<ide> describe('ReactDOMComponent', () => {
<ide> ReactDOM.render(<span style={style}></span>, div);
<ide> ReactDOM.render(<span style={style}></span>, div);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: `NaN` is an invalid value for the `fontSize` css style property.',
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> );
<ide> ReactDOM.render(element, container);
<ide> }
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`'
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> );
<ide> ReactDOM.render(afterUpdate, container);
<ide> }
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toEqual(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toEqual(
<ide> 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`'
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> errorEvent.initEvent('error', false, false);
<ide> container.getElementsByTagName('source')[0].dispatchEvent(errorEvent);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'onError called'
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> });
<ide> var node = document.createElement('div');
<ide> ReactDOM.render(<ShadyComponent />, node);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'ShadyComponent is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.'
<ide> );
<ide> mountComponent({is: 'custom-shady-div2'});
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> } finally {
<ide> document.createElement = defaultCreateElement;
<ide> describe('ReactDOMComponent', () => {
<ide> };
<ide>
<ide> mountComponent({is: 'custom-shady-div'});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.'
<ide> );
<ide>
<ide> mountComponent({is: 'custom-shady-div2'});
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> } finally {
<ide> document.createElement = defaultCreateElement;
<ide> describe('ReactDOMComponent', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> mountComponent({innerHTML: '<span>Hi Jim!</span>'});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Directly setting property `innerHTML` is not permitted. '
<ide> );
<ide> });
<ide> describe('ReactDOMComponent', () => {
<ide> it('should warn about contentEditable and children', () => {
<ide> spyOn(console, 'error');
<ide> mountComponent({contentEditable: true, children: ''});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
<ide> });
<ide>
<ide> it('should respect suppressContentEditableWarning', () => {
<ide> spyOn(console, 'error');
<ide> mountComponent({contentEditable: true, children: '', suppressContentEditableWarning: true});
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should validate against invalid styles', () => {
<ide> describe('ReactDOMComponent', () => {
<ide> <div contentEditable={true}><div /></div>,
<ide> container
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
<ide> });
<ide>
<ide> it('should validate against invalid styles', () => {
<ide> describe('ReactDOMComponent', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<div onScroll={function() {}} />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This browser doesn\'t support the `onScroll` event'
<ide> );
<ide> });
<ide>
<ide> it('should not warn when server-side rendering `onScroll`', () => {
<ide> spyOn(console, 'error');
<ide> ReactDOMServer.renderToString(<div onScroll={() => {}}/>);
<del> expect(console.error).not.toHaveBeenCalled();
<add> expectDev(console.error).not.toHaveBeenCalled();
<ide> });
<ide> });
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<div><tr /><tr /></div>);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
<ide> '<div>. See div > tr.'
<ide> );
<ide> describe('ReactDOMComponent', () => {
<ide> var p = document.createElement('p');
<ide> ReactDOM.render(<span><p /></span>, p);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <p> cannot appear as a descendant ' +
<ide> 'of <p>. See p > ... > p.'
<ide> );
<ide> describe('ReactDOMComponent', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Foo />);
<ide>
<del> expect(console.error.calls.count()).toBe(3);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(3);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
<ide> '<table>. See Foo > table > Row > tr. Add a <tbody> to your code to ' +
<ide> 'match the DOM tree generated by the browser.'
<ide> );
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' +
<ide> 'child of <tr>. See Row > tr > #text.'
<ide> );
<del> expect(console.error.calls.argsFor(2)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(2)[0]).toBe(
<ide> 'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' +
<ide> 'appear as a child of <table>. Make sure you don\'t have any extra ' +
<ide> 'whitespace between tags on each line of your source code. See Foo > ' +
<ide> describe('ReactDOMComponent', () => {
<ide> render: () => <Viz1 />,
<ide> });
<ide> ReactTestUtils.renderIntoDocument(<App1 />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'See Viz1 > table > FancyRow > Row > tr.'
<ide> );
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> render: () => <Viz2 />,
<ide> });
<ide> ReactTestUtils.renderIntoDocument(<App2 />);
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(1)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain(
<ide> 'See Viz2 > FancyTable > Table > table > FancyRow > Row > tr.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<FancyTable><FancyRow /></FancyTable>);
<del> expect(console.error.calls.count()).toBe(3);
<del> expect(console.error.calls.argsFor(2)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(3);
<add> expectDev(console.error.calls.argsFor(2)[0]).toContain(
<ide> 'See FancyTable > Table > table > FancyRow > Row > tr.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<table><FancyRow /></table>);
<del> expect(console.error.calls.count()).toBe(4);
<del> expect(console.error.calls.argsFor(3)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(4);
<add> expectDev(console.error.calls.argsFor(3)[0]).toContain(
<ide> 'See table > FancyRow > Row > tr.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<FancyTable><tr /></FancyTable>);
<del> expect(console.error.calls.count()).toBe(5);
<del> expect(console.error.calls.argsFor(4)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(5);
<add> expectDev(console.error.calls.argsFor(4)[0]).toContain(
<ide> 'See FancyTable > Table > table > tr.'
<ide> );
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> }
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Link><div><Link /></div></Link>);
<del> expect(console.error.calls.count()).toBe(6);
<del> expect(console.error.calls.argsFor(5)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(6);
<add> expectDev(console.error.calls.argsFor(5)[0]).toContain(
<ide> 'See Link > a > ... > Link > a.'
<ide> );
<ide> });
<ide>
<ide> it('should warn about incorrect casing on properties (ssr)', () => {
<ide> spyOn(console, 'error');
<ide> ReactDOMServer.renderToString(React.createElement('input', {type: 'text', tabindex: '1'}));
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
<ide> });
<ide>
<ide> it('should warn about incorrect casing on event handlers (ssr)', () => {
<ide> spyOn(console, 'error');
<ide> ReactDOMServer.renderToString(React.createElement('input', {type: 'text', onclick: '1'}));
<ide> ReactDOMServer.renderToString(React.createElement('input', {type: 'text', onKeydown: '1'}));
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('onClick');
<del> expect(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('onClick');
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
<ide> });
<ide>
<ide> it('should warn about incorrect casing on properties', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', tabindex: '1'}));
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
<ide> });
<ide>
<ide> it('should warn about incorrect casing on event handlers', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', onclick: '1'}));
<ide> ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', onKeydown: '1'}));
<del> expect(console.error.calls.count()).toBe(2);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('onClick');
<del> expect(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
<add> expectDev(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('onClick');
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
<ide> });
<ide>
<ide> it('should warn about class', () => {
<ide> spyOn(console, 'error');
<ide> ReactDOMServer.renderToString(React.createElement('div', {class: 'muffins'}));
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('className');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('className');
<ide> });
<ide>
<ide> it('should warn about props that are no longer supported', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<div />);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactTestUtils.renderIntoDocument(<div onFocusIn={() => {}} />);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> ReactTestUtils.renderIntoDocument(<div onFocusOut={() => {}} />);
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('gives source code refs for unknown prop warning', () => {
<ide> spyOn(console, 'error');
<ide> ReactDOMServer.renderToString(<div class="paladin"/>);
<ide> ReactDOMServer.renderToString(<input type="text" onclick="1"/>);
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> expect(
<ide> normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])
<ide> ).toBe(
<ide> describe('ReactDOMComponent', () => {
<ide> var container = document.createElement('div');
<ide>
<ide> ReactDOMServer.renderToString(<div className="paladin" />, container);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactDOMServer.renderToString(<div class="paladin" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])
<ide> ).toBe(
<ide> describe('ReactDOMComponent', () => {
<ide> </div>
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide>
<del> expect(console.error.calls.argsFor(0)[0]).toContain('className');
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('className');
<ide> var matches = console.error.calls.argsFor(0)[0].match(/.*\(.*:(\d+)\).*/);
<ide> var previousLine = matches[1];
<ide>
<del> expect(console.error.calls.argsFor(1)[0]).toContain('onClick');
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain('onClick');
<ide> matches = console.error.calls.argsFor(1)[0].match(/.*\(.*:(\d+)\).*/);
<ide> var currentLine = matches[1];
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide>
<ide> ReactDOMServer.renderToString(<Parent />, container);
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide>
<del> expect(console.error.calls.argsFor(0)[0]).toContain('className');
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('className');
<ide> var matches = console.error.calls.argsFor(0)[0].match(/.*\(.*:(\d+)\).*/);
<ide> var previousLine = matches[1];
<ide>
<del> expect(console.error.calls.argsFor(1)[0]).toContain('onClick');
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain('onClick');
<ide> matches = console.error.calls.argsFor(1)[0].match(/.*\(.*:(\d+)\).*/);
<ide> var currentLine = matches[1];
<ide>
<ide> describe('ReactDOMComponent', () => {
<ide> ReactTestUtils.renderIntoDocument(React.createElement('label', {for: 'test'}));
<ide> ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', autofocus: true}));
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide>
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Unknown DOM property for. Did you mean htmlFor?\n in label'
<ide> );
<ide>
<del> expect(console.error.calls.argsFor(1)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(1)[0]).toBe(
<ide> 'Warning: Unknown DOM property autofocus. Did you mean autoFocus?\n in input'
<ide> );
<ide> });
<ide><path>src/renderers/dom/shared/__tests__/ReactDOMInvalidARIAHook-test.js
<ide> describe('ReactDOMInvalidARIAHook', () => {
<ide> it('should allow valid aria-* props', () => {
<ide> spyOn(console, 'error');
<ide> mountComponent({'aria-label': 'Bumble bees'});
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide> it('should warn for one invalid aria-* prop', () => {
<ide> spyOn(console, 'error');
<ide> mountComponent({'aria-badprop': 'maybe'});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Invalid aria prop `aria-badprop` on <div> tag. ' +
<ide> 'For details, see https://fb.me/invalid-aria-prop'
<ide> );
<ide> describe('ReactDOMInvalidARIAHook', () => {
<ide> 'aria-malprop': 'Turbulent seas',
<ide> }
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Invalid aria props `aria-badprop`, `aria-malprop` on <div> ' +
<ide> 'tag. For details, see https://fb.me/invalid-aria-prop'
<ide> );
<ide> describe('ReactDOMInvalidARIAHook', () => {
<ide> spyOn(console, 'error');
<ide> // The valid attribute name is aria-haspopup.
<ide> mountComponent({'aria-hasPopup': 'true'});
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Unknown ARIA attribute aria-hasPopup. ' +
<ide> 'Did you mean aria-haspopup?'
<ide> );
<ide><path>src/renderers/dom/shared/syntheticEvents/__tests__/SyntheticEvent-test.js
<ide> describe('SyntheticEvent', () => {
<ide> expect(syntheticEvent.nativeEvent).toBe(null);
<ide> expect(syntheticEvent.target).toBe(null);
<ide> // once for each property accessed
<del> expect(console.error.calls.count()).toBe(3);
<add> expectDev(console.error.calls.count()).toBe(3);
<ide> // assert the first warning for accessing `type`
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re accessing the property `type` on a ' +
<ide> 'released/nullified synthetic event. This is set to null. If you must ' +
<ide> describe('SyntheticEvent', () => {
<ide> var syntheticEvent = createEvent({srcElement: target});
<ide> syntheticEvent.destructor();
<ide> expect(syntheticEvent.type = 'MouseEvent').toBe('MouseEvent');
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re setting the property `type` on a ' +
<ide> 'released/nullified synthetic event. This is effectively a no-op. If you must ' +
<ide> describe('SyntheticEvent', () => {
<ide> var syntheticEvent = createEvent({});
<ide> SyntheticEvent.release(syntheticEvent);
<ide> syntheticEvent.preventDefault();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re accessing the method `preventDefault` on a ' +
<ide> 'released/nullified synthetic event. This is a no-op function. If you must ' +
<ide> describe('SyntheticEvent', () => {
<ide> var syntheticEvent = createEvent({});
<ide> SyntheticEvent.release(syntheticEvent);
<ide> syntheticEvent.stopPropagation();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re accessing the method `stopPropagation` on a ' +
<ide> 'released/nullified synthetic event. This is a no-op function. If you must ' +
<ide> describe('SyntheticEvent', () => {
<ide> }
<ide> var instance = ReactDOM.render(<div onClick={assignEvent} />, element);
<ide> ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> // access a property to cause the warning
<ide> event.nativeEvent; // eslint-disable-line no-unused-expressions
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re accessing the property `nativeEvent` on a ' +
<ide> 'released/nullified synthetic event. This is set to null. If you must ' +
<ide> describe('SyntheticEvent', () => {
<ide> SyntheticEvent.release(syntheticEvent);
<ide> expect(syntheticEvent.foo).toBe('bar');
<ide> if (typeof Proxy === 'function') {
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: This synthetic event is reused for performance reasons. If ' +
<ide> 'you\'re seeing this, you\'re adding a new property in the synthetic ' +
<ide> 'event object. The property is never released. ' +
<ide> 'See https://fb.me/react-event-pooling for more information.'
<ide> );
<ide> } else {
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> }
<ide> });
<ide> });
<ide><path>src/renderers/dom/shared/wrappers/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', () => {
<ide> document.body.appendChild(container);
<ide>
<ide> var node = ReactDOM.findDOMNode(stub);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> // Simulate a native change event
<ide> setUntrackedValue(node, 'giraffe');
<ide> describe('ReactDOMInput', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="text" value="zoink" readOnly={true} />
<ide> );
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="text" value="zoink" readOnly={false} />
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide>
<ide> describe('ReactDOMInput', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="checkbox" checked="false" readOnly={true} />
<ide> );
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="checkbox" checked="false" readOnly={false} />
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should update defaultValue to empty string', () => {
<ide> describe('ReactDOMInput', () => {
<ide>
<ide> it('should warn if value is null', () => {
<ide> ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> '`value` prop on `input` should not be null. ' +
<ide> 'Consider using the empty string to clear the component or `undefined` ' +
<ide> 'for uncontrolled components.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should warn if checked and defaultChecked props are specified', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="radio" checked={true} defaultChecked={true} readOnly={true} />
<ide> );
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component contains an input of type radio with both checked and defaultChecked props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the checked prop, or the defaultChecked prop, but not ' +
<ide> describe('ReactDOMInput', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="radio" checked={true} defaultChecked={true} readOnly={true} />
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should warn if value and defaultValue props are specified', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="text" value="foo" defaultValue="bar" readOnly={true} />
<ide> );
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component contains an input of type text with both value and defaultValue props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> describe('ReactDOMInput', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <input type="text" value="foo" defaultValue="bar" readOnly={true} />
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should warn if controlled input switches to uncontrolled (value is undefined)', () => {
<ide> var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="text" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type text to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="text" value={null} />, container);
<del> expect(console.error.calls.count()).toBeGreaterThan(0);
<del> expect(console.error.calls.argsFor(1)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBeGreaterThan(0);
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain(
<ide> 'A component is changing a controlled input of type text to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="text" defaultValue="uncontrolled" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type text to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="text" value="controlled" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type text to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="text" value="controlled" />, container);
<del> expect(console.error.calls.count()).toBeGreaterThan(0);
<del> expect(console.error.calls.argsFor(1)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBeGreaterThan(0);
<add> expectDev(console.error.calls.argsFor(1)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type text to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="checkbox" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="checkbox" checked={null} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="checkbox" defaultChecked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="checkbox" checked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="checkbox" checked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="radio" />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type radio to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="radio" checked={null} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type radio to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="radio" defaultChecked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type radio to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="radio" checked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type radio to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(stub, container);
<ide> ReactDOM.render(<input type="radio" checked={true} />, container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing an uncontrolled input of type radio to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> describe('ReactDOMInput', () => {
<ide> ReactDOM.render(<input type="radio" value="value" defaultChecked={true} />, container);
<ide> ReactDOM.render(<input type="radio" value="value" onChange={() => null} />, container);
<ide> ReactDOM.render(<input type="radio" />, container);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should not warn if radio value changes but never becomes uncontrolled', () => {
<ide> describe('ReactDOMInput', () => {
<ide> checked={false}
<ide> onChange={() => null}
<ide> />, container);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should warn if radio checked false changes to become uncontrolled', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(<input type="radio" value="value" checked={false} onChange={() => null} />, container);
<ide> ReactDOM.render(<input type="radio" value="value" />, container);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'A component is changing a controlled input of type radio to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide><path>src/renderers/dom/shared/wrappers/__tests__/ReactDOMOption-test.js
<ide> describe('ReactDOMOption', () => {
<ide> expect(node.innerHTML).toBe('1 2');
<ide> ReactTestUtils.renderIntoDocument(<option>{1} <div /> {2}</option>);
<ide> // only warn once
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('Only strings and numbers are supported as <option> children.');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('Only strings and numbers are supported as <option> children.');
<ide> });
<ide>
<ide> it('should ignore null/undefined/false children without warning', () => {
<ide> describe('ReactDOMOption', () => {
<ide>
<ide> var node = ReactDOM.findDOMNode(stub);
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> expect(node.innerHTML).toBe('1 2');
<ide> });
<ide>
<ide><path>src/renderers/dom/shared/wrappers/__tests__/ReactDOMSelect-test.js
<ide> describe('ReactDOMSelect', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> ReactTestUtils.renderIntoDocument(<select value={null}><option value="test"/></select>);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> '`value` prop on `select` should not be null. ' +
<ide> 'Consider using the empty string to clear the component or `undefined` ' +
<ide> 'for uncontrolled components.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<select value={null}><option value="test"/></select>);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should refresh state on change', () => {
<ide> describe('ReactDOMSelect', () => {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>
<ide> );
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Select elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> 'both). Decide between using a controlled or uncontrolled select ' +
<ide> describe('ReactDOMSelect', () => {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should be able to safely remove select onChange', () => {
<ide><path>src/renderers/dom/shared/wrappers/__tests__/ReactDOMTextarea-test.js
<ide> describe('ReactDOMTextarea', () => {
<ide> var stub = <textarea>giraffe</textarea>;
<ide> var node = renderTextarea(stub, container);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(node.value).toBe('giraffe');
<ide>
<ide> // Changing children should do nothing, it functions like `defaultValue`.
<ide> describe('ReactDOMTextarea', () => {
<ide> it('should allow numbers as children', () => {
<ide> spyOn(console, 'error');
<ide> var node = renderTextarea(<textarea>{17}</textarea>);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(node.value).toBe('17');
<ide> });
<ide>
<ide> it('should allow booleans as children', () => {
<ide> spyOn(console, 'error');
<ide> var node = renderTextarea(<textarea>{false}</textarea>);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(node.value).toBe('false');
<ide> });
<ide>
<ide> describe('ReactDOMTextarea', () => {
<ide> },
<ide> };
<ide> var node = renderTextarea(<textarea>{obj}</textarea>);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(node.value).toBe('sharkswithlasers');
<ide> });
<ide>
<ide> describe('ReactDOMTextarea', () => {
<ide> );
<ide> }).toThrow();
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> var node;
<ide> expect(function() {
<ide> describe('ReactDOMTextarea', () => {
<ide>
<ide> expect(node.value).toBe('[object Object]');
<ide>
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('should unmount', () => {
<ide> describe('ReactDOMTextarea', () => {
<ide> spyOn(console, 'error');
<ide>
<ide> ReactTestUtils.renderIntoDocument(<textarea value={null} />);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> '`value` prop on `textarea` should not be null. ' +
<ide> 'Consider using the empty string to clear the component or `undefined` ' +
<ide> 'for uncontrolled components.'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<textarea value={null} />);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('should warn if value and defaultValue are specified', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(
<ide> <textarea value="foo" defaultValue="bar" readOnly={true} />
<ide> );
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Textarea elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> 'both). Decide between using a controlled or uncontrolled textarea ' +
<ide> describe('ReactDOMTextarea', () => {
<ide> ReactTestUtils.renderIntoDocument(
<ide> <textarea value="foo" defaultValue="bar" readOnly={true} />
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> });
<ide><path>src/renderers/dom/stack/client/__tests__/ReactDOM-test.js
<ide> describe('ReactDOM', () => {
<ide> spyOn(console, 'error');
<ide> var element = React.DOM.div();
<ide> expect(element.type).toBe('div');
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('throws in render() if the mount callback is not a function', () => {
<ide><path>src/renderers/dom/stack/client/__tests__/ReactMount-test.js
<ide> describe('ReactMount', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactMount.render(<div />, container);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> container.innerHTML = ' ' + ReactDOMServer.renderToString(<div />);
<ide>
<ide> ReactMount.render(<div />, container);
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> it('should not warn if mounting into non-empty node', () => {
<ide> describe('ReactMount', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactMount.render(<div />, container);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should warn when mounting into document.body', () => {
<ide> describe('ReactMount', () => {
<ide>
<ide> ReactMount.render(<div />, iFrame.contentDocument.body);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Rendering components directly into document.body is discouraged'
<ide> );
<ide> });
<ide> describe('ReactMount', () => {
<ide> <div>This markup contains an nbsp entity: client text</div>,
<ide> div
<ide> );
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> ' (client) nbsp entity: client text</div>\n' +
<ide> ' (server) nbsp entity: server text</div>'
<ide> );
<ide> describe('ReactMount', () => {
<ide> spyOn(console, 'error');
<ide> var rootNode = container.firstChild;
<ide> ReactDOM.render(<span />, rootNode);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: render(...): Replacing React-rendered children with a new ' +
<ide> 'root component. If you intended to update the children of this node, ' +
<ide> 'you should instead have the existing children update their state and ' +
<ide> describe('ReactMount', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactDOMOther.unmountComponentAtNode(container);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: unmountComponentAtNode(): The node you\'re attempting to unmount ' +
<ide> 'was rendered by another copy of React.'
<ide> );
<ide>
<ide> // Don't throw a warning if the correct React copy unmounts the node
<ide> ReactDOM.unmountComponentAtNode(container);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('passes the correct callback context', () => {
<ide><path>src/renderers/dom/stack/client/__tests__/ReactMountDestruction-test.js
<ide> describe('ReactMount', () => {
<ide> var rootDiv = mainContainerDiv.firstChild;
<ide> spyOn(console, 'error');
<ide> ReactDOM.unmountComponentAtNode(rootDiv);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
<ide> 'unmount was rendered by React and is not a top-level container. You ' +
<ide> 'may have accidentally passed in a React root node instead of its ' +
<ide> describe('ReactMount', () => {
<ide> var nonRootDiv = mainContainerDiv.firstChild.firstChild;
<ide> spyOn(console, 'error');
<ide> ReactDOM.unmountComponentAtNode(nonRootDiv);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
<ide> 'unmount was rendered by React and is not a top-level container. ' +
<ide> 'Instead, have the parent component update its state and rerender in ' +
<ide><path>src/renderers/dom/stack/server/__tests__/ReactServerRendering-test.js
<ide> describe('ReactServerRendering', () => {
<ide> spyOn(console, 'error');
<ide> instance = ReactDOM.render(<TestComponent name="y" />, element);
<ide> expect(mountCount).toEqual(4);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(element.innerHTML.length > 0).toBe(true);
<ide> expect(element.innerHTML).not.toEqual(lastMarkup);
<ide>
<ide> describe('ReactServerRendering', () => {
<ide> spyOn(console, 'error');
<ide> ReactServerRendering.renderToString(<Foo />);
<ide> jest.runOnlyPendingTimers();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.mostRecent().args[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.mostRecent().args[0]).toBe(
<ide> 'Warning: setState(...): Can only update a mounting component.' +
<ide> ' This usually means you called setState() outside componentWillMount() on the server.' +
<ide> ' This is a no-op. Please check the code for the Foo component.'
<ide> describe('ReactServerRendering', () => {
<ide> spyOn(console, 'error');
<ide> ReactServerRendering.renderToString(<Bar />);
<ide> jest.runOnlyPendingTimers();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.mostRecent().args[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.mostRecent().args[0]).toBe(
<ide> 'Warning: replaceState(...): Can only update a mounting component. ' +
<ide> 'This usually means you called replaceState() outside componentWillMount() on the server. ' +
<ide> 'This is a no-op. Please check the code for the Bar component.'
<ide> describe('ReactServerRendering', () => {
<ide> spyOn(console, 'error');
<ide> ReactServerRendering.renderToString(<Baz />);
<ide> jest.runOnlyPendingTimers();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.mostRecent().args[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.mostRecent().args[0]).toBe(
<ide> 'Warning: forceUpdate(...): Can only update a mounting component. ' +
<ide> 'This usually means you called forceUpdate() outside componentWillMount() on the server. ' +
<ide> 'This is a no-op. Please check the code for the Baz component.'
<ide><path>src/renderers/shared/__tests__/ReactDebugTool-test.js
<ide> describe('ReactDebugTool', () => {
<ide> });
<ide>
<ide> ReactDebugTool.onTestEvent();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Exception thrown by hook while handling ' +
<ide> 'onTestEvent: Error: Hi.'
<ide> );
<ide>
<ide> ReactDebugTool.onTestEvent();
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('returns isProfiling state', () => {
<ide><path>src/renderers/shared/__tests__/ReactPerf-test.js
<ide> describe('ReactPerf', () => {
<ide> var measurements = measure(() => {});
<ide> spyOn(console, 'error');
<ide> ReactPerf.getMeasurementsSummaryMap(measurements);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' +
<ide> '`ReactPerf.getWasted(...)` instead.'
<ide> );
<ide>
<ide> ReactPerf.getMeasurementsSummaryMap(measurements);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('warns once when using printDOM', () => {
<ide> var measurements = measure(() => {});
<ide> spyOn(console, 'error');
<ide> ReactPerf.printDOM(measurements);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> '`ReactPerf.printDOM(...)` is deprecated. Use ' +
<ide> '`ReactPerf.printOperations(...)` instead.'
<ide> );
<ide>
<ide> ReactPerf.printDOM(measurements);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide>
<ide> it('returns isRunning state', () => {
<ide> describe('ReactPerf', () => {
<ide> expect(ReactPerf.stop()).toBe(undefined);
<ide> expect(ReactPerf.isRunning()).toBe(false);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide>
<ide> __DEV__ = true;
<ide> });
<ide><path>src/renderers/shared/hooks/__tests__/ReactComponentTreeHook-test.js
<ide> describe('ReactComponentTreeHook', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> getAddendum(-17);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactComponentTreeHook: Missing React element for ' +
<ide> 'debugID -17 when building stack'
<ide> );
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactComponent-test.js
<ide> describe('ReactComponent', () => {
<ide> );
<ide>
<ide> // One warning for each element creation
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> });
<ide>
<ide> });
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactComponentLifeCycle-test.js
<ide> describe('ReactComponentLifeCycle', () => {
<ide> }
<ide>
<ide> ReactTestUtils.renderIntoDocument(<StatefulComponent />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: setState(...): Can only update a mounted or ' +
<ide> 'mounting component. This usually means you called setState() on an ' +
<ide> 'unmounted component. This is a no-op. Please check the code for the ' +
<ide> describe('ReactComponentLifeCycle', () => {
<ide> var instance = ReactTestUtils.renderIntoDocument(element);
<ide> expect(instance.isMounted()).toBeTruthy();
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Component is accessing isMounted inside its render()'
<ide> );
<ide> });
<ide> describe('ReactComponentLifeCycle', () => {
<ide> var instance = ReactTestUtils.renderIntoDocument(element);
<ide> expect(instance.isMounted()).toBeTruthy();
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Component is accessing isMounted inside its render()'
<ide> );
<ide> });
<ide> describe('ReactComponentLifeCycle', () => {
<ide> });
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Component is accessing findDOMNode inside its render()'
<ide> );
<ide> });
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', () => {
<ide> mountedInstance.methodAutoBound();
<ide> }).not.toThrow();
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> var explicitlyBound = mountedInstance.methodToBeExplicitlyBound.bind(
<ide> mountedInstance
<ide> );
<del> expect(console.error.calls.count()).toBe(2);
<add> expectDev(console.error.calls.count()).toBe(2);
<ide> var autoBound = mountedInstance.methodAutoBound;
<ide>
<ide> var context = {};
<ide> describe('ReactCompositeComponent', () => {
<ide> instance = ReactDOM.render(instance, container);
<ide> instance.forceUpdate();
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> instance.forceUpdate();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: forceUpdate(...): Can only update a mounted or ' +
<ide> 'mounting component. This usually means you called forceUpdate() on an ' +
<ide> 'unmounted component. This is a no-op. Please check the code for the ' +
<ide> describe('ReactCompositeComponent', () => {
<ide>
<ide> instance.setState({value: 1});
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> expect(renders).toBe(2);
<ide>
<ide> describe('ReactCompositeComponent', () => {
<ide>
<ide> expect(renders).toBe(2);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: setState(...): Can only update a mounted or ' +
<ide> 'mounting component. This usually means you called setState() on an ' +
<ide> 'unmounted component. This is a no-op. Please check the code for the ' +
<ide> describe('ReactCompositeComponent', () => {
<ide> }
<ide> }
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> var instance = ReactDOM.render(<Component />, container);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: setState(...): Cannot update during an existing state ' +
<ide> 'transition (such as within `render` or another component\'s ' +
<ide> 'constructor). Render methods should be a pure function of props and ' +
<ide> describe('ReactCompositeComponent', () => {
<ide> }
<ide> }
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> var instance = ReactDOM.render(<Component />, container);
<ide> expect(renderPasses).toBe(2);
<ide> expect(instance.state.value).toBe(1);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: setState(...): Cannot call setState() inside getChildContext()'
<ide> );
<ide> });
<ide> describe('ReactCompositeComponent', () => {
<ide> var instance = ReactTestUtils.renderIntoDocument(<Component />);
<ide> instance.setState({bogus: true});
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component.shouldComponentUpdate(): Returned undefined instead of a ' +
<ide> 'boolean value. Make sure to return true or false.'
<ide> );
<ide> describe('ReactCompositeComponent', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Component />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Component has a method called ' +
<ide> 'componentDidUnmount(). But there is no such lifecycle method. ' +
<ide> 'Did you mean componentWillUnmount()?'
<ide> describe('ReactCompositeComponent', () => {
<ide> }
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Outer />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: _renderNewRootComponent(): Render methods should ' +
<ide> 'be a pure function of props and state; triggering nested component ' +
<ide> 'updates from render is not allowed. If necessary, trigger nested ' +
<ide> describe('ReactCompositeComponent', () => {
<ide> }
<ide> }
<ide>
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide>
<ide> ReactDOM.render(<Foo idx="qwe" />, container);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Foo(...): When calling super() in `Foo`, make sure to pass ' +
<ide> 'up the same props that your component\'s constructor was passed.'
<ide> );
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactMockedComponent-test.js
<ide> describe('ReactMockedComponent', () => {
<ide> it('should allow an implicitly mocked component to be rendered without warnings', () => {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<AutoMockedComponent />);
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('should allow an implicitly mocked component to be updated', () => {
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactMultiChild-test.js
<ide>
<ide> describe('ReactMultiChild', () => {
<ide> function normalizeCodeLocInfo(str) {
<del> return str.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
<ide> }
<ide>
<ide> var React;
<ide> describe('ReactMultiChild', () => {
<ide> container
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
<ide> 'Warning: flattenChildren(...): ' +
<ide> 'Encountered two children with the same key, `1`. ' +
<ide> 'Child keys must be unique; when two children share a key, ' +
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactMultiChildText-test.js
<ide> describe('ReactMultiChildText', () => {
<ide> [true, <div>{1.2}{''}{<div />}{'foo'}</div>, true, 1.2], [<div />, '1.2'],
<ide> ['', 'foo', <div>{true}{<div />}{1.2}{''}</div>, 'foo'], ['', 'foo', <div />, 'foo'],
<ide> ]);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('ReactMultiChildText', () => {
<ide> expect(childNodes[5]).toBe(alpha3);
<ide>
<ide> // Using Maps as children gives a single warning
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> });
<ide> });
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js
<ide> describe('ReactStatelessComponent', () => {
<ide>
<ide> ReactDOM.render(<StatelessComponentWithChildContext name="A" />, container);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'StatelessComponentWithChildContext(...): childContextTypes cannot ' +
<ide> 'be defined on a functional component.'
<ide> );
<ide> describe('ReactStatelessComponent', () => {
<ide> expect(function() {
<ide> ReactTestUtils.renderIntoDocument(<div><NotAComponent /></div>);
<ide> }).toThrow();
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'NotAComponent(...): A valid React element (or null) must be returned. ' +
<ide> 'You may have returned undefined, an array or some other invalid object.'
<ide> );
<ide> describe('ReactStatelessComponent', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Parent/>);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Stateless function components cannot be given refs ' +
<ide> '(See ref "stateless" in StatelessComponent created by Parent). ' +
<ide> 'Attempts to access this ref will fail.'
<ide> describe('ReactStatelessComponent', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<Child />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain('a unique "key" prop');
<del> expect(console.error.calls.argsFor(0)[0]).toContain('Child');
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('a unique "key" prop');
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain('Child');
<ide> });
<ide>
<ide> it('should support default props and prop types', () => {
<ide> describe('ReactStatelessComponent', () => {
<ide>
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<Child />);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactStatelessComponent', () => {
<ide> expect(function() {
<ide> ReactTestUtils.renderIntoDocument(<div><NotAComponent /></div>);
<ide> }).toThrow(); // has no method 'render'
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'NotAComponent(...): A valid React element (or null) must be returned. You may ' +
<ide> 'have returned undefined, an array or some other invalid object.'
<ide> );
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactUpdates-test.js
<ide> describe('ReactUpdates', () => {
<ide>
<ide> var component = ReactTestUtils.renderIntoDocument(<A />);
<ide>
<add> console.log('xxx', expect().toThrowError);
<ide> expect(() => component.setState({}, 'no')).toThrowError(
<ide> 'setState(...): Expected the last optional `callback` argument ' +
<ide> 'to be a function. Instead received: string.'
<ide><path>src/renderers/testing/__tests__/ReactTestRenderer-test.js
<ide> describe('ReactTestRenderer', () => {
<ide> }
<ide> ReactTestRenderer.create(<Baz />);
<ide> ReactTestRenderer.create(<Foo />);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Stateless function components cannot be given refs ' +
<ide> '(See ref "foo" in Bar created by Foo). ' +
<ide> 'Attempts to access this ref will fail.'
<ide><path>src/shared/utils/__tests__/traverseAllChildren-test.js
<ide> describe('traverseAllChildren', () => {
<ide> '.0'
<ide> );
<ide> expect(traverseContext.length).toEqual(1);
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('traverseAllChildren', () => {
<ide> '.2'
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Each child in an array or iterator should have a unique "key" prop.'
<ide> );
<ide> });
<ide> describe('traverseAllChildren', () => {
<ide> '.$#3:0'
<ide> );
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toContain(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toContain(
<ide> 'Warning: Using Maps as children is not yet fully supported. It is an ' +
<ide> 'experimental feature that might be removed. Convert it to a sequence ' +
<ide> '/ iterable of keyed ReactElements instead.'
<ide> describe('traverseAllChildren', () => {
<ide>
<ide> ReactTestUtils.renderIntoDocument(<Parent />);
<ide>
<del> expect(console.error.calls.count()).toBe(1);
<del> expect(console.error.calls.argsFor(0)[0]).toBe(
<add> expectDev(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: Using Maps as children is not yet fully supported. It is an ' +
<ide> 'experimental feature that might be removed. Convert it to a sequence ' +
<ide> '/ iterable of keyed ReactElements instead. Check the render method of `Parent`.'
<ide><path>src/test/__tests__/ReactTestUtils-test.js
<ide> describe('ReactTestUtils', () => {
<ide>
<ide> var shallowRenderer = ReactTestUtils.createRenderer();
<ide> shallowRenderer.render(<SimpleComponent />);
<del> expect(console.error.calls.count()).toBe(1);
<add> expectDev(console.error.calls.count()).toBe(1);
<ide> expect(
<ide> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
<ide> ).toBe(
<ide> describe('ReactTestUtils', () => {
<ide> ReactDOM.findDOMNode(instance),
<ide> {clientX: CLIENT_X}
<ide> );
<del> expect(console.error.calls.count()).toBe(0);
<add> expectDev(console.error.calls.count()).toBe(0);
<ide> });
<ide>
<ide> it('can scry with stateless components involved', () => { | 42 |
Java | Java | make "single" support backpressure | c1ec1f4a4ee2dad56ecd0fee959e54d72c5c9734 | <ide><path>rxjava-core/src/main/java/rx/internal/operators/OperatorSingle.java
<ide> public void onNext(T value) {
<ide> } else {
<ide> this.value = value;
<ide> isNonEmpty = true;
<add> // Issue: https://github.com/Netflix/RxJava/pull/1527
<add> // Because we cache a value and don't emit now, we need to request another one.
<add> request(1);
<ide> }
<ide> }
<ide>
<ide><path>rxjava-core/src/test/java/rx/internal/operators/OperatorSingleTest.java
<ide> */
<ide> package rx.internal.operators;
<ide>
<add>import static org.junit.Assert.assertEquals;
<ide> import static org.mockito.Matchers.isA;
<del>import static org.mockito.Mockito.inOrder;
<del>import static org.mockito.Mockito.mock;
<del>import static org.mockito.Mockito.times;
<add>import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.NoSuchElementException;
<ide>
<ide>
<ide> import rx.Observable;
<ide> import rx.Observer;
<add>import rx.Subscriber;
<ide> import rx.functions.Func1;
<add>import rx.functions.Func2;
<ide>
<ide> public class OperatorSingleTest {
<ide>
<ide> public Boolean call(Integer t1) {
<ide> inOrder.verify(observer, times(1)).onCompleted();
<ide> inOrder.verifyNoMoreInteractions();
<ide> }
<add>
<add> @Test
<add> public void testSingleWithBackpressure() {
<add> Observable<Integer> observable = Observable.from(1, 2).single();
<add>
<add> Subscriber<Integer> subscriber = spy(new Subscriber<Integer>() {
<add>
<add> @Override
<add> public void onStart() {
<add> request(1);
<add> }
<add>
<add> @Override
<add> public void onCompleted() {
<add>
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add>
<add> }
<add>
<add> @Override
<add> public void onNext(Integer integer) {
<add> request(1);
<add> }
<add> });
<add> observable.subscribe(subscriber);
<add>
<add> InOrder inOrder = inOrder(subscriber);
<add> inOrder.verify(subscriber, times(1)).onError(isA(IllegalArgumentException.class));
<add> inOrder.verifyNoMoreInteractions();
<add> }
<add>
<add> @Test(timeout = 30000)
<add> public void testIssue1527() throws InterruptedException {
<add> //https://github.com/Netflix/RxJava/pull/1527
<add> Observable<Integer> source = Observable.from(1, 2, 3, 4, 5, 6);
<add> Observable<Integer> reduced = source.reduce(new Func2<Integer, Integer, Integer>() {
<add> @Override
<add> public Integer call(Integer i1, Integer i2) {
<add> return i1 + i2;
<add> }
<add> });
<add>
<add> Integer r = reduced.toBlocking().first();
<add> assertEquals(21, r.intValue());
<add> }
<ide> } | 2 |
Text | Text | add a section on introduction to lists | 8df84d58e072cb1c89f1caf028304851700a56f6 | <ide><path>guide/english/python/lists/index.md
<ide> ---
<ide> title: Lists
<ide> ---
<add>
<ide> ## Lists
<ide> Lists is one of the most common Python data structures you will encounter while programming in Python along with dictionary, tuple or set.
<ide>
<del>It is an ordered mutable collection, this means that you store data in different postions in a list.
<add>A `list` is an ordered mutable collection, where each value is identified with an *index*. Lists are zero-indexed, i.e., the index of the **1st** element in a `list` is **0**, the index of the **2nd** element is **1**, and so on. This means that a list of **N** elements will have indices from **0** to **N - 1**(not N).
<ide>
<ide> Besides that due to list being *mutable*, you are allowed to make changes to the value of a list without affecting the order of positions within the list.
<ide> | 1 |
PHP | PHP | use 403 status code | b6fc316b1ff1bb8df4288726e9784de03925a21c | <ide><path>src/Illuminate/Routing/Exceptions/InvalidSignatureException.php
<ide> class InvalidSignatureException extends HttpException
<ide> */
<ide> public function __construct()
<ide> {
<del> parent::__construct(401, 'Invalid signature.');
<add> parent::__construct(403, 'Invalid signature.');
<ide> }
<ide> } | 1 |
PHP | PHP | allow identifierexpression as argument in function | 8df607657e3006b22761db1644e3e61cce00f9f2 | <ide><path>src/Database/FunctionsBuilder.php
<ide> public function dateDiff(array $args, array $types = []): FunctionExpression
<ide> * Returns the specified date part from the SQL expression.
<ide> *
<ide> * @param string $part Part of the date to return.
<del> * @param string $expression Expression to obtain the date part from.
<add> * @param mixed $expression Expression to obtain the date part from.
<ide> * @param array $types list of types to bind to the arguments
<ide> * @return \Cake\Database\Expression\FunctionExpression
<ide> */
<del> public function datePart(string $part, string $expression, array $types = []): FunctionExpression
<add> public function datePart(string $part, $expression, array $types = []): FunctionExpression
<ide> {
<ide> return $this->extract($part, $expression, $types);
<ide> }
<ide> public function datePart(string $part, string $expression, array $types = []): F
<ide> * Returns the specified date part from the SQL expression.
<ide> *
<ide> * @param string $part Part of the date to return.
<del> * @param string $expression Expression to obtain the date part from.
<add> * @param mixed $expression Expression to obtain the date part from.
<ide> * @param array $types list of types to bind to the arguments
<ide> * @return \Cake\Database\Expression\FunctionExpression
<ide> */
<del> public function extract(string $part, string $expression, array $types = []): FunctionExpression
<add> public function extract(string $part, $expression, array $types = []): FunctionExpression
<ide> {
<ide> $expression = $this->_literalArgumentFunction('EXTRACT', $expression, $types, 'integer');
<ide> $expression->setConjunction(' FROM')->add([$part => 'literal'], [], true);
<ide> public function extract(string $part, string $expression, array $types = []): Fu
<ide> /**
<ide> * Add the time unit to the date expression
<ide> *
<del> * @param string $expression Expression to obtain the date part from.
<add> * @param mixed $expression Expression to obtain the date part from.
<ide> * @param string|int $value Value to be added. Use negative to subtract.
<ide> * @param string $unit Unit of the value e.g. hour or day.
<ide> * @param array $types list of types to bind to the arguments
<ide> * @return \Cake\Database\Expression\FunctionExpression
<ide> */
<del> public function dateAdd(string $expression, $value, string $unit, array $types = []): FunctionExpression
<add> public function dateAdd($expression, $value, string $unit, array $types = []): FunctionExpression
<ide> {
<ide> if (!is_numeric($value)) {
<ide> $value = 0; | 1 |
Javascript | Javascript | fix challenge naming scheme | a7ba4bacf87e7b32166ab8c43ed4bc274a99e0b8 | <ide><path>index.js
<ide> Challenge.destroyAll(function(err, info) {
<ide> challenges.forEach(function(file) {
<ide> var challengeSpec = require('./challenges/' + file);
<ide> var order = challengeSpec.order;
<add> var block = challengeSpec.name;
<add>
<ide> var challenges = challengeSpec.challenges
<ide> .map(function(challenge, index) {
<ide> // NOTE(berks): add title for displaying in views
<ide> challenge.name =
<ide> _.capitalize(challenge.type) +
<ide> ': ' +
<ide> challenge.title.replace(/[^a-zA-Z0-9\s]/g, '');
<add>
<ide> challenge.dashedName = challenge.name
<ide> .toLowerCase()
<ide> .replace(/\:/g, '')
<ide> .replace(/\s/g, '-');
<ide> challenge.order = +('' + order + (index + 1));
<add> challenge.block = block;
<add>
<ide> return challenge;
<ide> });
<ide> | 1 |
Ruby | Ruby | replace inline lambdas with named methods | b09bbdb8bf342b3f6d19a2cc2c8860019e39cac9 | <ide><path>activerecord/lib/active_record/associations/collection_association.rb
<ide> def create!(attributes = {}, options = {}, &block)
<ide> # Add +records+ to this association. Returns +self+ so method calls may be chained.
<ide> # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
<ide> def concat(*records)
<del> result = true
<ide> load_target if owner.new_record?
<ide>
<del> block = lambda do
<del> records.flatten.each do |record|
<del> raise_on_type_mismatch(record)
<del> add_to_target(record) do |r|
<del> result &&= insert_record(record) unless owner.new_record?
<del> end
<del> end
<add> if owner.new_record?
<add> concat_records(records)
<add> else
<add> transaction { concat_records(records) }
<ide> end
<del>
<del> owner.new_record? ? block.call : transaction(&block)
<del>
<del> result && records
<ide> end
<ide>
<ide> # Starts a transaction in the association class's database connection.
<ide> def replace(other_array)
<ide> other_array.each { |val| raise_on_type_mismatch(val) }
<ide> original_target = load_target.dup
<ide>
<del> block = lambda do
<del> delete(target - other_array)
<del>
<del> unless concat(other_array - target)
<del> @target = original_target
<del> raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
<del> "new records could not be saved."
<del> end
<add> if owner.new_record?
<add> replace_records(other_array, original_target)
<add> else
<add> transaction { replace_records(other_array, original_target) }
<ide> end
<del>
<del> owner.new_record? ? block.call : transaction(&block)
<ide> end
<ide>
<ide> def include?(record)
<ide> def delete_or_destroy(records, method)
<ide> records.each { |record| raise_on_type_mismatch(record) }
<ide> existing_records = records.reject { |r| r.new_record? }
<ide>
<del> block = lambda do
<del> records.each { |record| callback(:before_remove, record) }
<add> if existing_records.empty?
<add> remove_records(existing_records, records, method)
<add> else
<add> transaction { remove_records(existing_records, records, method) }
<add> end
<add> end
<ide>
<del> delete_records(existing_records, method) if existing_records.any?
<del> records.each { |record| target.delete(record) }
<add> def remove_records(existing_records, records, method)
<add> records.each { |record| callback(:before_remove, record) }
<ide>
<del> records.each { |record| callback(:after_remove, record) }
<del> end
<add> delete_records(existing_records, method) if existing_records.any?
<add> records.each { |record| target.delete(record) }
<ide>
<del> existing_records.any? ? transaction(&block) : block.call
<add> records.each { |record| callback(:after_remove, record) }
<ide> end
<ide>
<ide> # Delete the given records from the association, using one of the methods :destroy,
<ide> def delete_records(records, method)
<ide> raise NotImplementedError
<ide> end
<ide>
<add> def replace_records(new_target, original_target)
<add> delete(target - new_target)
<add>
<add> unless concat(new_target - target)
<add> @target = original_target
<add> raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
<add> "new records could not be saved."
<add> end
<add> end
<add>
<add> def concat_records(records)
<add> result = true
<add>
<add> records.flatten.each do |record|
<add> raise_on_type_mismatch(record)
<add> add_to_target(record) do |r|
<add> result &&= insert_record(record) unless owner.new_record?
<add> end
<add> end
<add>
<add> result && records
<add> end
<add>
<ide> def callback(method, record)
<ide> callbacks_for(method).each do |callback|
<ide> case callback | 1 |
Python | Python | fix training_args.py barrier for torch_xla | 6c5b20aa09af5a5e1d09aee266fd737ac4527f27 | <ide><path>src/transformers/training_args.py
<ide> def main_process_first(self, local=True, desc="work"):
<ide> if not is_main_process:
<ide> # tell all replicas to wait
<ide> logger.debug(f"{self.process_index}: waiting for the {main_process_desc} to perform {desc}")
<del> torch.distributed.barrier()
<add> if is_torch_tpu_available():
<add> xm.rendezvous(desc)
<add> else:
<add> torch.distributed.barrier()
<ide> yield
<ide> finally:
<ide> if is_main_process:
<ide> # the wait is over
<ide> logger.debug(f"{self.process_index}: {main_process_desc} completed {desc}, releasing all replicas")
<del> torch.distributed.barrier()
<add> if is_torch_tpu_available():
<add> xm.rendezvous(desc)
<add> else:
<add> torch.distributed.barrier()
<ide> else:
<ide> yield
<ide> | 1 |
Mixed | Javascript | pass timestamp to ticks callback | b19fc0169facffc2a9a6715d98ccfc3dfba00e09 | <ide><path>docs/axes/labelling.md
<ide> To do this, you need to override the `ticks.callback` method in the axis configu
<ide>
<ide> The method receives 3 arguments:
<ide>
<del>* `value` - the tick value in the **internal data format** of the associated scale.
<add>* `value` - the tick value in the **internal data format** of the associated scale. For time scale, it is a timestamp.
<ide> * `index` - the tick index in the ticks array.
<ide> * `ticks` - the array containing all of the [tick objects](../api/interfaces/Tick).
<ide>
<ide><path>docs/migration/v4-migration.md
<ide> A number of changes were made to the configuration options passed to the `Chart`
<ide> #### Specific changes
<ide>
<ide> * The radialLinear grid indexable and scriptable options don't decrease the index of the specified grid line anymore.
<add>* Ticks callback on time scale now receives timestamp instead of a formatted label.
<ide>
<ide> #### Type changes
<ide> * The order of the `ChartMeta` parameters have been changed from `<Element, DatasetElement, Type>` to `<Type, Element, DatasetElement>`
<ide><path>src/scales/scale.time.js
<ide> export default class TimeScale extends Scale {
<ide> */
<ide> source: 'auto',
<ide>
<add> callback: false,
<add>
<ide> major: {
<ide> enabled: false
<ide> }
<ide> export default class TimeScale extends Scale {
<ide> */
<ide> _tickFormatFunction(time, index, ticks, format) {
<ide> const options = this.options;
<add> const formatter = options.ticks.callback;
<add>
<add> if (formatter) {
<add> return call(formatter, [time, index, ticks], this);
<add> }
<add>
<ide> const formats = options.time.displayFormats;
<ide> const unit = this._unit;
<ide> const majorUnit = this._majorUnit;
<ide> const minorFormat = unit && formats[unit];
<ide> const majorFormat = majorUnit && formats[majorUnit];
<ide> const tick = ticks[index];
<ide> const major = majorUnit && majorFormat && tick && tick.major;
<del> const label = this._adapter.format(time, format || (major ? majorFormat : minorFormat));
<del> const formatter = options.ticks.callback;
<del> return formatter ? call(formatter, [label, index, ticks], this) : label;
<add>
<add> return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
<ide> }
<ide>
<ide> /**
<ide><path>test/specs/scale.time.tests.js
<ide> describe('Time scale tests', function() {
<ide> },
<ide> ticks: {
<ide> source: 'auto',
<add> callback: false,
<ide> major: {
<ide> enabled: false
<ide> }
<ide> describe('Time scale tests', function() {
<ide> }
<ide> },
<ide> ticks: {
<del> callback: function(value) {
<del> return '<' + value + '>';
<add> callback: function(_, i) {
<add> return '<' + i + '>';
<ide> }
<ide> }
<ide> }
<ide> describe('Time scale tests', function() {
<ide> var labels = getLabels(this.scale);
<ide>
<ide> expect(labels.length).toEqual(21);
<del> expect(labels[0]).toEqual('<8:00:00>');
<del> expect(labels[labels.length - 1]).toEqual('<8:01:00>');
<add> expect(labels[0]).toEqual('<0>');
<add> expect(labels[labels.length - 1]).toEqual('<60>');
<ide> });
<ide>
<ide> it('should update ticks.callback correctly', function() {
<ide> var chart = this.chart;
<del> chart.options.scales.x.ticks.callback = function(value) {
<del> return '{' + value + '}';
<add> chart.options.scales.x.ticks.callback = function(_, i) {
<add> return '{' + i + '}';
<ide> };
<ide> chart.update();
<ide>
<ide> var labels = getLabels(this.scale);
<ide> expect(labels.length).toEqual(21);
<del> expect(labels[0]).toEqual('{8:00:00}');
<del> expect(labels[labels.length - 1]).toEqual('{8:01:00}');
<add> expect(labels[0]).toEqual('{0}');
<add> expect(labels[labels.length - 1]).toEqual('{60}');
<ide> });
<ide> });
<ide>
<ide> describe('Time scale tests', function() {
<ide>
<ide> expect(chartOptions).toEqual(chart.options);
<ide> });
<add>
<add> it('should pass timestamp to ticks callback', () => {
<add> let callbackValue;
<add> window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> xAxisID: 'x',
<add> data: [0, 0]
<add> }],
<add> labels: ['2015-01-01T20:00:00', '2015-01-01T20:01:00']
<add> },
<add> options: {
<add> scales: {
<add> x: {
<add> type: 'time',
<add> ticks: {
<add> callback(value) {
<add> callbackValue = value;
<add> return value;
<add> }
<add> }
<add> }
<add> }
<add> }
<add> });
<add>
<add> expect(typeof callbackValue).toBe('number');
<add> });
<ide> }); | 4 |
Python | Python | set default backend to tf on windows | 2b336756b661fe6d96856723f3d804c4db954c97 | <ide><path>keras/backend/__init__.py
<ide> if not os.path.exists(_keras_dir):
<ide> os.makedirs(_keras_dir)
<ide>
<del># Set theano as default backend for Windows users since tensorflow is not available for Windows yet.
<del>if os.name == 'nt':
<del> _BACKEND = 'theano'
<del>else:
<del> _BACKEND = 'tensorflow'
<add># Default backend: TensorFlow.
<add>_BACKEND = 'tensorflow'
<ide>
<ide> _config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json'))
<ide> if os.path.exists(_config_path):
<ide> _config = json.load(open(_config_path))
<ide> _floatx = _config.get('floatx', floatx())
<ide> assert _floatx in {'float16', 'float32', 'float64'}
<ide> _epsilon = _config.get('epsilon', epsilon())
<del> assert type(_epsilon) == float
<add> assert isinstance(_epsilon, float)
<ide> _backend = _config.get('backend', _BACKEND)
<ide> assert _backend in {'theano', 'tensorflow'}
<del> _image_dim_ordering = _config.get('image_dim_ordering', image_dim_ordering())
<add> _image_dim_ordering = _config.get('image_dim_ordering',
<add> image_dim_ordering())
<ide> assert _image_dim_ordering in {'tf', 'th'}
<ide>
<ide> set_floatx(_floatx)
<ide> sys.stderr.write('Using TensorFlow backend.\n')
<ide> from .tensorflow_backend import *
<ide> else:
<del> raise Exception('Unknown backend: ' + str(_BACKEND))
<add> raise ValueError('Unknown backend: ' + str(_BACKEND))
<ide>
<ide>
<ide> def backend(): | 1 |
PHP | PHP | add tests for self relationships | 116c1ebbdd8d3f2ca7d27ce3afd1402337cd5390 | <ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testOrHasNested()
<ide> $this->assertEquals($builder->toSql(), $result);
<ide> }
<ide>
<add> public function testSelfHasNested()
<add> {
<add> $model = new EloquentBuilderTestModelSelfRelatedStub();
<add>
<add> $nestedSql = $model->whereHas('parentFoo', function ($q) {
<add> $q->has('childFoo');
<add> })->toSql();
<add>
<add> $dotSql = $model->has('parentFoo.childFoo')->toSql();
<add>
<add> // alias has a dynamic hash, so replace with a static string for comparison
<add> $alias = 'self_alias_hash';
<add> $aliasRegex = '/\b(self_[a-f0-9]{32})(\b|$)/i';
<add>
<add> $nestedSql = preg_replace($aliasRegex, $alias, $nestedSql);
<add> $dotSql = preg_replace($aliasRegex, $alias, $dotSql);
<add>
<add> $this->assertEquals($nestedSql, $dotSql);
<add> }
<add>
<add> public function testSelfHasNestedUsesAlias()
<add> {
<add> $model = new EloquentBuilderTestModelSelfRelatedStub();
<add>
<add> $sql = $model->has('parentFoo.childFoo')->toSql();
<add>
<add> // alias has a dynamic hash, so replace with a static string for comparison
<add> $alias = 'self_alias_hash';
<add> $aliasRegex = '/\b(self_[a-f0-9]{32})(\b|$)/i';
<add>
<add> $sql = preg_replace($aliasRegex, $alias, $sql);
<add> $this->assertContains('"self_related_stubs"."parent_id" = "self_alias_hash"."id"', $sql);
<add> }
<add>
<ide> protected function mockConnectionForModel($model, $database)
<ide> {
<ide> $grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar';
<ide> public function baz()
<ide> class EloquentBuilderTestModelFarRelatedStub extends Illuminate\Database\Eloquent\Model
<ide> {
<ide> }
<add>
<add>class EloquentBuilderTestModelSelfRelatedStub extends Illuminate\Database\Eloquent\Model
<add>{
<add> protected $table = 'self_related_stubs';
<add>
<add> public function parentFoo()
<add> {
<add> return $this->belongsTo('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'parent');
<add> }
<add>
<add> public function childFoo()
<add> {
<add> return $this->hasOne('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'child');
<add> }
<add>
<add> public function childFoos()
<add> {
<add> return $this->hasMany('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'children');
<add> }
<add>
<add> public function parentBars()
<add> {
<add> return $this->belongsToMany('EloquentBuilderTestModelSelfRelatedStub', 'self_pivot', 'child_id', 'parent_id', 'parent_bars');
<add> }
<add>
<add> public function childBars()
<add> {
<add> return $this->belongsToMany('EloquentBuilderTestModelSelfRelatedStub', 'self_pivot', 'parent_id', 'child_id', 'child_bars');
<add> }
<add>
<add> public function bazes()
<add> {
<add> return $this->hasMany('EloquentBuilderTestModelFarRelatedStub', 'foreign_key', 'id', 'bar');
<add> }
<add>}
<ide>\ No newline at end of file
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testHasOnSelfReferencingBelongsToManyRelationship()
<ide> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<ide> }
<ide>
<add> public function testWhereHasOnSelfReferencingBelongsToManyRelationship()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<add>
<add> $results = EloquentTestUser::whereHas('friends', function ($query) {
<add> $query->where('email', 'abigailotwell@gmail.com');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<add> }
<add>
<add> public function testHasOnNestedSelfReferencingBelongsToManyRelationship()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<add> $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);
<add>
<add> $results = EloquentTestUser::has('friends.friends')->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<add> }
<add>
<add> public function testWhereHasOnNestedSelfReferencingBelongsToManyRelationship()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<add> $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);
<add>
<add> $results = EloquentTestUser::whereHas('friends.friends', function ($query) {
<add> $query->where('email', 'foo@gmail.com');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<add> }
<add>
<add> public function testHasOnSelfReferencingBelongsToManyRelationshipWithWherePivot()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<add>
<add> $results = EloquentTestUser::has('friendsOne')->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<add> }
<add>
<add> public function testHasOnNestedSelfReferencingBelongsToManyRelationshipWithWherePivot()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
<add> $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);
<add>
<add> $results = EloquentTestUser::has('friendsOne.friendsTwo')->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);
<add> }
<add>
<ide> public function testHasOnSelfReferencingBelongsToRelationship()
<ide> {
<ide> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
<ide> public function testHasOnSelfReferencingBelongsToRelationship()
<ide> $this->assertEquals('Child Post', $results->first()->name);
<ide> }
<ide>
<add> public function testWhereHasOnSelfReferencingBelongsToRelationship()
<add> {
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
<add>
<add> $results = EloquentTestPost::whereHas('parentPost', function ($query) {
<add> $query->where('name', 'Parent Post');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Child Post', $results->first()->name);
<add> }
<add>
<add> public function testHasOnNestedSelfReferencingBelongsToRelationship()
<add> {
<add> $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
<add>
<add> $results = EloquentTestPost::has('parentPost.parentPost')->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Child Post', $results->first()->name);
<add> }
<add>
<add> public function testWhereHasOnNestedSelfReferencingBelongsToRelationship()
<add> {
<add> $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
<add>
<add> $results = EloquentTestPost::whereHas('parentPost.parentPost', function ($query) {
<add> $query->where('name', 'Grandparent Post');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Child Post', $results->first()->name);
<add> }
<add>
<ide> public function testHasOnSelfReferencingHasManyRelationship()
<ide> {
<ide> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
<ide> public function testHasOnSelfReferencingHasManyRelationship()
<ide> $this->assertEquals('Parent Post', $results->first()->name);
<ide> }
<ide>
<add> public function testWhereHasOnSelfReferencingHasManyRelationship()
<add> {
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
<add>
<add> $results = EloquentTestPost::whereHas('childPosts', function ($query) {
<add> $query->where('name', 'Child Post');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Parent Post', $results->first()->name);
<add> }
<add>
<add> public function testHasOnNestedSelfReferencingHasManyRelationship()
<add> {
<add> $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
<add>
<add> $results = EloquentTestPost::has('childPosts.childPosts')->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Grandparent Post', $results->first()->name);
<add> }
<add>
<add> public function testWhereHasOnNestedSelfReferencingHasManyRelationship()
<add> {
<add> $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
<add> $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
<add> $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
<add>
<add> $results = EloquentTestPost::whereHas('childPosts.childPosts', function ($query) {
<add> $query->where('name', 'Child Post');
<add> })->get();
<add>
<add> $this->assertEquals(1, count($results));
<add> $this->assertEquals('Grandparent Post', $results->first()->name);
<add> }
<add>
<ide> public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()
<ide> {
<ide> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<ide> public function testBasicHasManyEagerLoading()
<ide> $this->assertEquals('taylorotwell@gmail.com', $post->first()->user->email);
<ide> }
<ide>
<add> public function testBasicNestedSelfReferencingHasManyEagerLoading()
<add> {
<add> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> $post = $user->posts()->create(['name' => 'First Post']);
<add> $post->childPosts()->create(['name' => 'Child Post', 'user_id' => $user->id]);
<add>
<add> $user = EloquentTestUser::with('posts.childPosts')->where('email', 'taylorotwell@gmail.com')->first();
<add>
<add> $this->assertNotNull($user->posts->first());
<add> $this->assertEquals('First Post', $user->posts->first()->name);
<add>
<add> $this->assertNotNull($user->posts->first()->childPosts->first());
<add> $this->assertEquals('Child Post', $user->posts->first()->childPosts->first()->name);
<add>
<add> $post = EloquentTestPost::with('parentPost.user')->where('name', 'Child Post')->get();
<add> $this->assertNotNull($post->first()->parentPost);
<add> $this->assertNotNull($post->first()->parentPost->user);
<add> $this->assertEquals('taylorotwell@gmail.com', $post->first()->parentPost->user->email);
<add> }
<add>
<ide> public function testBasicMorphManyRelationship()
<ide> {
<ide> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<ide> public function friends()
<ide> return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id');
<ide> }
<ide>
<add> public function friendsOne()
<add> {
<add> return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id')->wherePivot('user_id', 1);
<add> }
<add>
<add> public function friendsTwo()
<add> {
<add> return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id')->wherePivot('user_id', 2);
<add> }
<add>
<ide> public function posts()
<ide> {
<ide> return $this->hasMany('EloquentTestPost', 'user_id'); | 2 |
Javascript | Javascript | add more info, fix formatting | d59aeb4e0b5900a484de9c2fea12ce599810aac8 | <ide><path>src/jqLite.js
<ide> *
<ide> * If jQuery is available, `angular.element` is an alias for the
<ide> * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
<del> * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
<add> * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
<ide> *
<del> * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
<del> * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
<del> * commonly needed functionality with the goal of having a very small footprint.</div>
<add> * jqLite is a tiny, API-compatible subset of jQuery that allows
<add> * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
<add> * commonly needed functionality with the goal of having a very small footprint.
<ide> *
<del> * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
<add> * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
<add> * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
<add> * specific version of jQuery if multiple versions exist on the page.
<ide> *
<del> * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
<del> * jqLite; they are never raw DOM references.</div>
<add> * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
<add> * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
<ide> *
<ide> * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
<ide> * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
<ide> * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
<ide> * - [`clone()`](http://api.jquery.com/clone/)
<ide> * - [`contents()`](http://api.jquery.com/contents/)
<del> * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
<add> * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
<add> * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
<ide> * - [`data()`](http://api.jquery.com/data/)
<ide> * - [`detach()`](http://api.jquery.com/detach/)
<ide> * - [`empty()`](http://api.jquery.com/empty/) | 1 |
Javascript | Javascript | add hascrypto check to tls-legacy-deprecated | b98004b79cc5c55922ecd03a4128ba0dfdd07f48 | <ide><path>test/parallel/test-tls-legacy-deprecated.js
<ide> // Flags: --no-warnings
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto) {
<add> common.skip('missing crypto');
<add> return;
<add>}
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> | 1 |
Text | Text | add v3.6.0-beta.2 to changelog | e529ae76a1582b2213f8dc723db17e1dad8628b7 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.6.0-beta.2 (October 27, 2018)
<add>
<add>- [#17130](https://github.com/emberjs/ember.js/pull/17130) [BUGFIX] Ensure that timers scheduled after a system sleep are fired properly.
<add>- [#17137](https://github.com/emberjs/ember.js/pull/17137) [BUGFIX] Assert when local variables shadow modifier invocations
<add>- [#16923](https://github.com/emberjs/ember.js/pull/16923) [BUGFIX] ES6 classes on/removeListener and observes/removeObserver interop v2
<add>- [#17128](https://github.com/emberjs/ember.js/pull/17128) [BUGFIX] Fix sourcemaping issues due to multiple sourcemap directives.
<add>- [#17115](https://github.com/emberjs/ember.js/pull/17115) [BUGFIX] Pass the event parameter to sendAction
<add>- [#17153](https://github.com/emberjs/ember.js/pull/17153) [BUGFIX] Blueprints can generate components with a single word name
<add>
<ide> ### v3.6.0-beta.1 (October 8, 2018)
<ide>
<ide> - [#16956](https://github.com/emberjs/ember.js/pull/16956) [DEPRECATION] Deprecate Ember.merge | 1 |
Ruby | Ruby | add options to example usage | 1fbc32d8423f0518f295f1fa4e7485b7db4600ff | <ide><path>Library/Homebrew/cmd/help.rb
<ide> HOMEBREW_HELP = <<-EOS
<ide> Example usage:
<add> brew [info | home | options ] [FORMULA...]
<ide> brew install FORMULA...
<ide> brew uninstall FORMULA...
<ide> brew search [foo]
<ide> brew list [FORMULA...]
<ide> brew update
<ide> brew upgrade [FORMULA...]
<del> brew [info | home] [FORMULA...]
<ide>
<ide> Troubleshooting:
<ide> brew doctor | 1 |
Python | Python | use setuptools for bdist_egg distributions | 18b01010077b034556cdb73b751544a06f48dcdc | <ide><path>setup.py
<ide> def setup_package():
<ide> FULLVERSION, GIT_REVISION = get_version_info()
<ide> metadata['version'] = FULLVERSION
<ide> else:
<del> if (len(sys.argv) >= 2 and sys.argv[1] == 'bdist_wheel' or
<add> if (len(sys.argv) >= 2 and sys.argv[1] in ('bdist_wheel', 'bdist_egg') or
<ide> sys.version_info[0] < 3 and sys.platform == "win32"):
<del> # bdist_wheel and the MS python2.7 VS sdk needs setuptools
<add> # bdist_wheel, bdist_egg and the MS python2.7 VS sdk needs setuptools
<ide> # the latter can also be triggered by (see python issue23246)
<ide> # SET DISTUTILS_USE_SDK=1
<ide> # SET MSSdk=1 | 1 |
Javascript | Javascript | add missing flag for signtool.exe | 57a0de5b992adc890cec3db51e71d7fa078cd299 | <ide><path>script/lib/code-sign.js
<ide> module.exports = function (packagedAppPath) {
<ide> childProcess.spawnSync(signtoolPath, [
<ide> 'sign', '/v',
<ide> '/f', process.env.WIN_P12KEY_PATH,
<del> '/p', process.env.WIN_P12KEY_PASSWORD
<add> '/p', process.env.WIN_P12KEY_PASSWORD,
<add> binToSignPath
<ide> ], {stdio: 'inherit'})
<ide>
<ide> // TODO: when we will be able to generate an installer, sign that too!
<ide> // const installerToSignPath = computeInstallerPath()
<ide> // console.log(`Signing Windows Installer at ${installerToSignPath}`)
<ide> // childProcess.spawnSync(signtoolPath, [
<del> // 'sign', '/v',
<add> // 'sign', binToSignPath, '/v',
<ide> // '/f', process.env.WIN_P12KEY_PATH,
<ide> // '/p', process.env.WIN_P12KEY_PASSWORD
<ide> // ], {stdio: 'inherit'}) | 1 |
Text | Text | fix translation error. | dfcd44eb092bb57048ce2cb6090a813d368f6434 | <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.chinese.md
<ide> localeTitle: 使用导出默认值创建导出回退
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在<code>export</code>课程中,您了解了称为<dfn>命名导出</dfn>的语法。这使您可以使多个函数和变量可用于其他文件。您需要知道另一种<code>export</code>语法,称为<dfn>导出默认值</dfn> 。通常,如果只从文件导出一个值,您将使用此语法。它还用于为文件或模块创建回退值。以下是<code>export default</code>的快速示例: <blockquote> export default function add(x,y){ <br>返回x + y; <br> } </blockquote>注意:由于<code>export default</code>用于声明模块或文件的回退值,因此每个模块或文件中只能有一个值作为默认导出。此外,您不能将<code>export default</code>用于<code>var</code> , <code>let</code>或<code>const</code> </section>
<add><section id="description">在<code>export</code>课程中,您了解了称为<dfn>命名导出</dfn>的语法。这使您可以使多个函数和变量可用于其他文件。您需要知道另一种<code>export</code>语法,称为<dfn>导出默认值</dfn> 。通常,如果只从文件导出一个值,您将使用此语法。它还用于为文件或模块创建回退值。以下是<code>export default</code>的快速示例: <blockquote> export default function add(x,y){ <br> return x + y; <br> } </blockquote>注意:由于<code>export default</code>用于声明模块或文件的回退值,因此每个模块或文件中只能有一个值作为默认导出。此外,您不能将<code>export default</code>用于<code>var</code> , <code>let</code>或<code>const</code> </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">以下函数应该是模块的回退值。请添加必要的代码。 </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.chinese.md
<ide> localeTitle: 使用模板文字创建字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> ES6的一个新功能是<dfn>模板文字</dfn> 。这是一种特殊类型的字符串,可以更轻松地创建复杂字符串。模板文字允许您创建多行字符串并使用字符串插值功能来创建字符串。考虑以下代码: <blockquote> const person = { <br>名称:“Zodiac Hasbro”, <br>年龄:56岁<br> }; <br><br> //具有多行和字符串插值的模板文字<br> const greeting =`您好,我的名字是$ {person.name}! <br>我是$ {person.age}岁。 <br><br>的console.log(问候); //打印<br> //你好,我的名字是Zodiac Hasbro! <br> //我今年56岁<br></blockquote>那里发生了很多事情。首先,例如使用反引号( <code>`</code> ),而不是引号( <code>'</code>或<code>"</code> ),换行字符串。其次,请注意,该字符串是多线,无论是在代码和输出。这节省了插入<code>\n</code>串内。上面使用的<code>${variable}</code>语法是占位符。基本上,您不必再使用<code>+</code>运算符连接。要将变量添加到字符串,只需将变量放在模板字符串中并用<code>${</code>包装它<code>}</code>同样,您可以在您的字符串表达式的其他文字,例如<code>${a + b}</code>这个新创建的字符串的方式为您提供了更大的灵活性,以创建强大的字符串。 </section>
<add><section id="description"> ES6的一个新功能是<dfn>模板文字</dfn> 。这是一种特殊类型的字符串,可以更轻松地创建复杂字符串。模板文字允许您创建多行字符串并使用字符串插值功能来创建字符串。考虑以下代码: <blockquote> const person = { <br>name: "Zodiac Hasbro", <br>age: 56<br> }; <br><br> //具有多行和字符串插值的模板文字<br> const greeting =`您好,我的名字是${person.name}! <br>我是${person.age}岁。` <br><br>的console.log(greeting); //打印<br> //你好,我的名字是Zodiac Hasbro! <br> //我今年56岁<br></blockquote>那里发生了很多事情。首先,例如使用反引号( <code>`</code> ),而不是引号( <code>'</code>或<code>"</code> ),换行字符串。其次,请注意,该字符串是多线,无论是在代码和输出。这节省了插入<code>\n</code>串内。上面使用的<code>${variable}</code>语法是占位符。基本上,您不必再使用<code>+</code>运算符连接。要将变量添加到字符串,只需将变量放在模板字符串中并用<code>${</code>包装它<code>}</code>同样,您可以在您的字符串表达式的其他文字,例如<code>${a + b}</code>这个新创建的字符串的方式为您提供了更大的灵活性,以创建强大的字符串。 </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">使用带有反引号的模板文字语法来显示<code>result</code>对象的<code>failure</code>数组的每个条目。每个条目都应该包含在一个带有class属性<code>text-warning</code>的<code>li</code>元素中,并列在<code>resultDisplayArray</code> 。 </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.chinese.md
<ide> localeTitle: 使用const关键字声明只读变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>let</code>不是声明变量的唯一新方法。在ES6中,您还可以使用<code>const</code>关键字声明变量。 <code>const</code>拥有所有的真棒功能, <code>let</code>具有,与额外的奖励,使用声明的变量<code>const</code>是只读的。它们是一个常量值,这意味着一旦变量被赋值为<code>const</code> ,就无法重新赋值。 <blockquote> “严格使用” <br> const FAV_PET =“Cats”; <br> FAV_PET =“狗”; //返回错误</blockquote>如您所见,尝试重新分配使用<code>const</code>声明的变量将引发错误。您应该始终使用<code>const</code>关键字命名您不想重新分配的变量。当您意外尝试重新分配一个旨在保持不变的变量时,这会有所帮助。命名常量时的常见做法是使用全部大写字母,单词用下划线分隔。 </section>
<add><section id="description"> <code>let</code>不是声明变量的唯一新方法。在ES6中,您还可以使用<code>const</code>关键字声明变量。 <code>const</code>拥有所有的真棒功能, <code>let</code>具有,与额外的奖励,使用声明的变量<code>const</code>是只读的。它们是一个常量值,这意味着一旦变量被赋值为<code>const</code> ,就无法重新赋值。 <blockquote> "use strict" <br> const FAV_PET ="Cats"; <br> FAV_PET = "Dogs"; //返回错误</blockquote>如您所见,尝试重新分配使用<code>const</code>声明的变量将引发错误。您应该始终使用<code>const</code>关键字命名您不想重新分配的变量。当您意外尝试重新分配一个旨在保持不变的变量时,这会有所帮助。命名常量时的常见做法是使用全部大写字母,单词用下划线分隔。 </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">更改代码,以便使用<code>let</code>或<code>const</code>声明所有变量。如果希望变量更改,请使用<code>let</code> ;如果希望变量保持不变,请使用<code>const</code> 。此外,重命名用<code>const</code>声明的变量以符合常规做法,这意味着常量应该全部大写。 </section> | 3 |
PHP | PHP | fix whitespace for coding standards | 69ab443ed601fd9c4f57d5907dda538473816f2f | <ide><path>lib/Cake/I18n/Multibyte.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide>
<add>if (!function_exists('mb_stripos')) {
<add>
<ide> /**
<ide> * Find position of first occurrence of a case-insensitive string.
<ide> *
<ide> * @return integer|boolean The numeric position of the first occurrence of $needle in the $haystack string, or false
<ide> * if $needle is not found.
<ide> */
<del>if (!function_exists('mb_stripos')) {
<ide> function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> return Multibyte::stripos($haystack, $needle, $offset);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_stristr')) {
<add>
<ide> /**
<ide> * Finds first occurrence of a string within another, case insensitive.
<ide> *
<ide> function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string|boolean The portion of $haystack, or false if $needle is not found.
<ide> */
<del>if (!function_exists('mb_stristr')) {
<ide> function mb_stristr($haystack, $needle, $part = false, $encoding = null) {
<ide> return Multibyte::stristr($haystack, $needle, $part);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strlen')) {
<add>
<ide> /**
<ide> * Get string length.
<ide> *
<ide> function mb_stristr($haystack, $needle, $part = false, $encoding = null) {
<ide> * @return integer The number of characters in string $string having character encoding encoding.
<ide> * A multi-byte character is counted as 1.
<ide> */
<del>if (!function_exists('mb_strlen')) {
<ide> function mb_strlen($string, $encoding = null) {
<ide> return Multibyte::strlen($string);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strpos')) {
<add>
<ide> /**
<ide> * Find position of first occurrence of a string.
<ide> *
<ide> function mb_strlen($string, $encoding = null) {
<ide> * @return integer|boolean The numeric position of the first occurrence of $needle in the $haystack string.
<ide> * If $needle is not found, it returns false.
<ide> */
<del>if (!function_exists('mb_strpos')) {
<ide> function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> return Multibyte::strpos($haystack, $needle, $offset);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strrchr')) {
<add>
<ide> /**
<ide> * Finds the last occurrence of a character in a string within another.
<ide> *
<ide> function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string|boolean The portion of $haystack. or false if $needle is not found.
<ide> */
<del>if (!function_exists('mb_strrchr')) {
<ide> function mb_strrchr($haystack, $needle, $part = false, $encoding = null) {
<ide> return Multibyte::strrchr($haystack, $needle, $part);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strrichr')) {
<add>
<ide> /**
<ide> * Finds the last occurrence of a character in a string within another, case insensitive.
<ide> *
<ide> function mb_strrchr($haystack, $needle, $part = false, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string|boolean The portion of $haystack. or false if $needle is not found.
<ide> */
<del>if (!function_exists('mb_strrichr')) {
<ide> function mb_strrichr($haystack, $needle, $part = false, $encoding = null) {
<ide> return Multibyte::strrichr($haystack, $needle, $part);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strripos')) {
<add>
<ide> /**
<ide> * Finds position of last occurrence of a string within another, case insensitive
<ide> *
<ide> function mb_strrichr($haystack, $needle, $part = false, $encoding = null) {
<ide> * @return integer|boolean The numeric position of the last occurrence of $needle in the $haystack string,
<ide> * or false if $needle is not found.
<ide> */
<del>if (!function_exists('mb_strripos')) {
<ide> function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> return Multibyte::strripos($haystack, $needle, $offset);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strrpos')) {
<add>
<ide> /**
<ide> * Find position of last occurrence of a string in a string.
<ide> *
<ide> function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> * @return integer|boolean The numeric position of the last occurrence of $needle in the $haystack string.
<ide> * If $needle is not found, it returns false.
<ide> */
<del>if (!function_exists('mb_strrpos')) {
<ide> function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> return Multibyte::strrpos($haystack, $needle, $offset);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strstr')) {
<add>
<ide> /**
<ide> * Finds first occurrence of a string within another
<ide> *
<ide> function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string|boolean The portion of $haystack, or true if $needle is not found.
<ide> */
<del>if (!function_exists('mb_strstr')) {
<ide> function mb_strstr($haystack, $needle, $part = false, $encoding = null) {
<ide> return Multibyte::strstr($haystack, $needle, $part);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strtolower')) {
<add>
<ide> /**
<ide> * Make a string lowercase
<ide> *
<ide> * @param string $string The string being lowercased.
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string with all alphabetic characters converted to lowercase.
<ide> */
<del>if (!function_exists('mb_strtolower')) {
<ide> function mb_strtolower($string, $encoding = null) {
<ide> return Multibyte::strtolower($string);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_strtoupper')) {
<add>
<ide> /**
<ide> * Make a string uppercase
<ide> *
<ide> * @param string $string The string being uppercased.
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string with all alphabetic characters converted to uppercase.
<ide> */
<del>if (!function_exists('mb_strtoupper')) {
<ide> function mb_strtoupper($string, $encoding = null) {
<ide> return Multibyte::strtoupper($string);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_substr_count')) {
<add>
<ide> /**
<ide> * Count the number of substring occurrences
<ide> *
<ide> function mb_strtoupper($string, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return integer The number of times the $needle substring occurs in the $haystack string.
<ide> */
<del>if (!function_exists('mb_substr_count')) {
<ide> function mb_substr_count($haystack, $needle, $encoding = null) {
<ide> return Multibyte::substrCount($haystack, $needle);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_substr')) {
<add>
<ide> /**
<ide> * Get part of string
<ide> *
<ide> function mb_substr_count($haystack, $needle, $encoding = null) {
<ide> * @param string $encoding Character encoding name to use. If it is omitted, internal character encoding is used.
<ide> * @return string The portion of $string specified by the $string and $length parameters.
<ide> */
<del>if (!function_exists('mb_substr')) {
<ide> function mb_substr($string, $start, $length = null, $encoding = null) {
<ide> return Multibyte::substr($string, $start, $length);
<ide> }
<add>
<ide> }
<ide>
<add>if (!function_exists('mb_encode_mimeheader')) {
<add>
<ide> /**
<ide> * Encode string for MIME header
<ide> *
<ide> function mb_substr($string, $start, $length = null, $encoding = null) {
<ide> * @param integer $indent [definition unknown and appears to have no affect]
<ide> * @return string A converted version of the string represented in ASCII.
<ide> */
<del>if (!function_exists('mb_encode_mimeheader')) {
<ide> function mb_encode_mimeheader($str, $charset = 'UTF-8', $transferEncoding = 'B', $linefeed = "\r\n", $indent = 1) {
<ide> return Multibyte::mimeEncode($str, $charset, $linefeed);
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> * Multibyte handling methods.
<ide> *
<del> *
<ide> * @package Cake.I18n
<ide> */
<ide> class Multibyte { | 1 |
Ruby | Ruby | remove unused av helper fixtures from e10a2531 | d6efc1edc1ac8f0bd2cef76f0eb8e512c36f9932 | <ide><path>actionview/test/fixtures/helpers/fun/games_helper.rb
<del>module Fun
<del> module GamesHelper
<del> def stratego() "Iz guuut!" end
<del> end
<del>end
<ide>\ No newline at end of file
<ide><path>actionview/test/fixtures/helpers/fun/pdf_helper.rb
<del>module Fun
<del> module PdfHelper
<del> def foobar() 'baz' end
<del> end
<del>end
<ide><path>actionview/test/fixtures/helpers/just_me_helper.rb
<del>module JustMeHelper
<del> def me() "mine!" end
<del>end
<ide>\ No newline at end of file
<ide><path>actionview/test/fixtures/helpers/me_too_helper.rb
<del>module MeTooHelper
<del> def me() "me too!" end
<del>end
<ide>\ No newline at end of file | 4 |
Go | Go | fix login and search tls configuration | e863a07b89599fd4a03d34491d67c09c6bc84444 | <ide><path>registry/endpoint.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/registry/api/v2"
<ide> "github.com/docker/distribution/registry/client/transport"
<del> "github.com/docker/docker/pkg/tlsconfig"
<ide> )
<ide>
<ide> // for mocking in unit tests
<ide> func scanForAPIVersion(address string) (string, APIVersion) {
<ide>
<ide> // NewEndpoint parses the given address to return a registry endpoint.
<ide> func NewEndpoint(index *IndexInfo, metaHeaders http.Header) (*Endpoint, error) {
<del> // *TODO: Allow per-registry configuration of endpoints.
<del> tlsConfig := tlsconfig.ServerDefault
<del> tlsConfig.InsecureSkipVerify = !index.Secure
<del> endpoint, err := newEndpoint(index.GetAuthConfigKey(), &tlsConfig, metaHeaders)
<add> tlsConfig, err := newTLSConfig(index.Name, index.Secure)
<add> if err != nil {
<add> return nil, err
<add> }
<add> endpoint, err := newEndpoint(index.GetAuthConfigKey(), tlsConfig, metaHeaders)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>registry/registry.go
<ide> func init() {
<ide> dockerUserAgent = useragent.AppendVersions("", httpVersion...)
<ide> }
<ide>
<add>func newTLSConfig(hostname string, isSecure bool) (*tls.Config, error) {
<add> // PreferredServerCipherSuites should have no effect
<add> tlsConfig := tlsconfig.ServerDefault
<add>
<add> tlsConfig.InsecureSkipVerify = !isSecure
<add>
<add> if isSecure {
<add> hostDir := filepath.Join(CertsDir, hostname)
<add> logrus.Debugf("hostDir: %s", hostDir)
<add> if err := ReadCertsDirectory(&tlsConfig, hostDir); err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> return &tlsConfig, nil
<add>}
<add>
<ide> func hasFile(files []os.FileInfo, name string) bool {
<ide> for _, f := range files {
<ide> if f.Name() == name {
<ide><path>registry/service.go
<ide> import (
<ide> "fmt"
<ide> "net/http"
<ide> "net/url"
<del> "path/filepath"
<ide> "strings"
<ide>
<del> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/tlsconfig"
<ide> func (e APIEndpoint) ToV1Endpoint(metaHeaders http.Header) (*Endpoint, error) {
<ide>
<ide> // TLSConfig constructs a client TLS configuration based on server defaults
<ide> func (s *Service) TLSConfig(hostname string) (*tls.Config, error) {
<del> // PreferredServerCipherSuites should have no effect
<del> tlsConfig := tlsconfig.ServerDefault
<del>
<del> isSecure := s.Config.isSecureIndex(hostname)
<del>
<del> tlsConfig.InsecureSkipVerify = !isSecure
<del>
<del> if isSecure {
<del> hostDir := filepath.Join(CertsDir, hostname)
<del> logrus.Debugf("hostDir: %s", hostDir)
<del> if err := ReadCertsDirectory(&tlsConfig, hostDir); err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> return &tlsConfig, nil
<add> return newTLSConfig(hostname, s.Config.isSecureIndex(hostname))
<ide> }
<ide>
<ide> func (s *Service) tlsConfigForMirror(mirror string) (*tls.Config, error) { | 3 |
PHP | PHP | fix cursor pagination with hasmanythrough | 66c5afc3cb14f914990d8b8cbf79fa077887cb26 | <ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
<ide> public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'p
<ide> return $this->query->simplePaginate($perPage, $columns, $pageName, $page);
<ide> }
<ide>
<add> /**
<add> * Paginate the given query into a cursor paginator.
<add> *
<add> * @param int|null $perPage
<add> * @param array $columns
<add> * @param string $cursorName
<add> * @param string|null $cursor
<add> * @return \Illuminate\Contracts\Pagination\CursorPaginator
<add> */
<add> public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null)
<add> {
<add> $this->query->addSelect($this->shouldSelect($columns));
<add>
<add> return $this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor);
<add> }
<add>
<ide> /**
<ide> * Set the select clause for the relation query.
<ide> * | 1 |
Ruby | Ruby | check error number instead of a message | ac41b73d97a80f2552196516e29d7e3335e2d556 | <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
<ide>
<ide> module ActiveRecord
<ide> module ConnectionHandling # :nodoc:
<add> ER_BAD_DB_ERROR = 1049
<add>
<ide> # Establishes a connection to the database that's used by all Active Record objects.
<ide> def mysql2_connection(config)
<ide> config = config.symbolize_keys
<ide> def mysql2_connection(config)
<ide> client = Mysql2::Client.new(config)
<ide> ConnectionAdapters::Mysql2Adapter.new(client, logger, nil, config)
<ide> rescue Mysql2::Error => error
<del> if error.message.include?("Unknown database")
<add> if error.error_number == ER_BAD_DB_ERROR
<ide> raise ActiveRecord::NoDatabaseError
<ide> else
<ide> raise
<ide><path>activerecord/lib/active_record/tasks/mysql_database_tasks.rb
<ide> module ActiveRecord
<ide> module Tasks # :nodoc:
<ide> class MySQLDatabaseTasks # :nodoc:
<add> ER_DB_CREATE_EXISTS = 1007
<add>
<ide> delegate :connection, :establish_connection, to: ActiveRecord::Base
<ide>
<ide> def initialize(configuration)
<ide> def create
<ide> connection.create_database configuration["database"], creation_options
<ide> establish_connection configuration
<ide> rescue ActiveRecord::StatementInvalid => error
<del> if error.message.include?("database exists")
<add> if error.cause.error_number == ER_DB_CREATE_EXISTS
<ide> raise DatabaseAlreadyExists
<ide> else
<ide> raise | 2 |
Javascript | Javascript | remove unnecessary comma in shadowmapviewer | a4ac61806c4cfd96665443ba98fc336f0e836165 | <ide><path>examples/js/utils/ShadowMapViewer.js
<ide> THREE.ShadowMapViewer = function ( light ) {
<ide> x: 10,
<ide> y: 10,
<ide> width: 256,
<del> height: 256,
<add> height: 256
<ide> };
<ide>
<ide> var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 10 ); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.