问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答:
The ternary operator RETURNS one of two values. Or, it can execute one of two statements based on its condition, but that's generally not a good idea, as it can lead to unintended side-effects.

```<code>bar ? () : baz();
</code>```

In this case, the () does nothing, while baz does something. But you've only made the code less clear. I'd go for more verbose code that's clearer and easier to maintain.

Further, this makes little sense at all:

```<code>var foo = bar ? () : baz();
</code>```

since () has no return type (it's void) and baz has a return type that's unknown at the point of call in this sample. If they don't agree, the compiler will complain, and loudly.

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

Body:
The ternary operator RETURNS one of two values. Or, it can execute one of two statements based on its condition, but that's generally not a good idea, as it can lead to unintended side-effects.

bar ? () : baz();

In this case, the () does nothing, while baz does something. But you've only made the code less clear. I'd go for more verbose code that's clearer and easier to maintain.

Further, this makes little sense at all:

var foo = bar ? () : baz();

since () has no return type (it's void) and baz has a return type that's unknown at the point of call in this sample. If they don't agree, the compiler will complain, and loudly.


来源: stackexchange

问:
How to add a function in const Target = props => {
How do I add a function to connect to one of my components onChange? Creating a function like this returns an error code of 'cardActionResponse' is not defined.

What the benefit of using a const class like this?

```<code>const Target = props => {

    const { markAsDone } = useContext(ItemContext);

    const [{ isOver }, drop] = useDrop({
        accept: 'Item',
        drop: (item, monitor) => console.log(item),
        collect: monitor => ({
            isOver: !!monitor.isOver()
        })
    })

    //Cannot do this. How else can I make a function to connect to CreateVideoCard?
    cardActionResponse = (event) => {
        console.log(event);
    }

    return (
        <div className="target top80 right30" ref={drop} style={{ backgroundColor: isOver ? 'black' : '' }} >
            <TitleDescription class="z1"/>
            <div class="right10 left10">
                <CreateVideoCard onChange={this.cardActionResponse} />
                <CreateDescriptionCard></CreateDescriptionCard>
                <CreateAudioCard></CreateAudioCard>
                <CreateTermsCard></CreateTermsCard>
            </div>
        </div>
    );
};

export default Target;
</code>```

答:
Functional components don't have it's own context (this), so you should simply use const variable.
Please use

```<code>const cardActionResponse = (event) => {
        console.log(event);
    }
</code>```

and then

```<code><CreateVideoCard onChange={cardActionResponse} />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I add a function to connect to one of my components onChange? Creating a function like this returns an error code of 'cardActionResponse' is not defined.

What the benefit of using a const class like this?

const Target = props => {

    const { markAsDone } = useContext(ItemContext);

    const [{ isOver }, drop] = useDrop({
        accept: 'Item',
        drop: (item, monitor) => console.log(item),
        collect: monitor => ({
            isOver: !!monitor.isOver()
        })
    })

    //Cannot do this. How else can I make a function to connect to CreateVideoCard?
    cardActionResponse = (event) => {
        console.log(event);
    }

    return (

            <TitleDescription class="z1"/>

                <CreateVideoCard onChange={this.cardActionResponse} />
                <CreateDescriptionCard></CreateDescriptionCard>
                <CreateAudioCard></CreateAudioCard>
                <CreateTermsCard></CreateTermsCard>

    );
};

export default Target;

Body:
Functional components don't have it's own context (this), so you should simply use const variable.
Please use

const cardActionResponse = (event) => {
        console.log(event);
    }

and then

<CreateVideoCard onChange={cardActionResponse} />


问:
Preventing SetInterval overlaps
I am using jqFancyTransitions.1.8 (http://workshop.rs/projects/jqfancytransitions/) and have the navigation enabled.

The problem I have is that if I spam click through the images (or simply click to early or too late), the effect goes crazy (especially on the curtain effect) - this is because the javascript intervals overlap and the offsets just go out of sync.

I have tried to edit the script to hide and reshow the navigation when a transition is not running, but I couldnt get this working properly, and the navigation would reshow at different intervals, maybe I was putting the code in the wrong place.

Can anyone help me insert $('#ft-buttons-slideshowHolder').show() &&  $('#ft-buttons-slideshowHolder').hide() in the right place to get this to work?

I was also wondering if anyone using this has had the same problem and constructed any hacks or fixes already, or if anyone is able to provide me with the assistance I require to make a quick fix happen!

Thank you SO community!!

(not my code, just beautified for easy assistance)...

```<code>/**
 * jqFancyTransitions - jQuery plugin
 * @version: 1.8 (2010/06/13)
 * @requires jQuery v1.2.2 or later
 * @author Ivan Lazarevic
 * Examples and documentation at: http://www.workshop.rs/projects/jqfancytransitions

 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 **/
(function ($) {
    var opts = new Array;
    var level = new Array;
    var img = new Array;
    var links = new Array;
    var titles = new Array;
    var order = new Array;
    var imgInc = new Array;
    var inc = new Array;
    var stripInt = new Array;
    var imgInt = new Array;
    $.fn.jqFancyTransitions = $.fn.jqfancytransitions = function (options) {
        init = function (el) {
            opts[el.id] = $.extend({}, $.fn.jqFancyTransitions.defaults, options);
            img[el.id] = new Array();
            links[el.id] = new Array();
            titles[el.id] = new Array();
            order[el.id] = new Array();
            imgInc[el.id] = 0;
            inc[el.id] = 0;
            params = opts[el.id];
            if (params.effect == 'zipper') {
                params.direction = 'alternate';
                params.position = 'alternate';
            }
            if (params.effect == 'wave') {
                params.direction = 'alternate';
                params.position = 'top';
            }
            if (params.effect == 'curtain') {
                params.direction = 'alternate';
                params.position = 'curtain';
            }
            stripWidth = parseInt(params.width / params.strips);
            gap = params.width - stripWidth * params.strips;
            stripLeft = 0;
            $.each($('#' + el.id + ' img'), function (i, item) {
                img[el.id][i] = $(item).attr('src');
                links[el.id][i] = $(item).next().attr('href');
                titles[el.id][i] = $(item).attr('alt') ? $(item).attr('alt') : '';
                $(item).hide();
            });
            $('#' + el.id).css({
                'background-image': 'url(' + img[el.id][0] + ')',
                'width': params.width,
                'height': params.height,
                'position': 'relative',
                'background-position': 'top left'
            });
            $('#' + el.id).append("<div class='ft-title' id='ft-title-" + el.id + "' style='position: absolute; bottom:0; left: 0; z-index: 1; color: #fff; background-color: #000; '>" + titles[el.id][0] + "</div>");
            if (titles[el.id][imgInc[el.id]]) $('#ft-title-' + el.id).css('opacity', opts[el.id].titleOpacity);
            else $('#ft-title-' + el.id).css('opacity', 0);
            if (params.navigation) {
                $.navigation(el);
                $('#ft-buttons-' + el.id).children().first().addClass('ft-button-' + el.id + '-active');
            }
            odd = 1;
            for (j = 1; j < params.strips + 1; j++) {
                if (gap > 0) {
                    tstripWidth = stripWidth + 1;
                    gap--;
                } else {
                    tstripWidth = stripWidth;
                }
                if (params.links) $('#' + el.id).append("<a href='" + links[el.id][0] + "' class='ft-" + el.id + "' id='ft-" + el.id + j + "' style='width:" + tstripWidth + "px; height:" + params.height + "px; float: left; position: absolute;outline:none;'></a>");
                else $('#' + el.id).append("<div class='ft-" + el.id + "' id='ft-" + el.id + j + "' style='width:" + tstripWidth + "px; height:" + params.height + "px; float: left; position: absolute;'></div>");
                $("#ft-" + el.id + j).css({
                    'background-position': -stripLeft + 'px top',
                    'left': stripLeft
                });
                stripLeft += tstripWidth;
                if (params.position == 'bottom') $("#ft-" + el.id + j).css('bottom', 0);
                if (j % 2 == 0 && params.position == 'alternate') $("#ft-" + el.id + j).css('bottom', 0);
                if (params.direction == 'fountain' || params.direction == 'fountainAlternate') {
                    order[el.id][j - 1] = parseInt(params.strips / 2) - (parseInt(j / 2) * odd);
                    order[el.id][params.strips - 1] = params.strips;
                    odd *= -1;
                } else {
                    order[el.id][j - 1] = j;
                }
            }
            $('.ft-' + el.id).mouseover(function () {
                opts[el.id].pause = true;
            });
            $('.ft-' + el.id).mouseout(function () {
                opts[el.id].pause = false;
            });
            $('#ft-title-' + el.id).mouseover(function () {
                opts[el.id].pause = true;
            });
            $('#ft-title-' + el.id).mouseout(function () {
                opts[el.id].pause = false;
            });
            clearInterval(imgInt[el.id]);
            imgInt[el.id] = setInterval(function () {
                $.transition(el)
            }, params.delay + params.stripDelay * params.strips);
        };
        $.transition = function (el, direction) {
            if (opts[el.id].pause == true) return;
            stripInt[el.id] = setInterval(function () {
                $.strips(order[el.id][inc[el.id]], el)
            }, opts[el.id].stripDelay);
            $('#' + el.id).css({
                'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
            });
            if (typeof (direction) == "undefined") imgInc[el.id]++;
            else if (direction == 'prev') imgInc[el.id]--;
            else imgInc[el.id] = direction;
            if (imgInc[el.id] == img[el.id].length) {
                imgInc[el.id] = 0;
            }
            if (imgInc[el.id] == -1) {
                imgInc[el.id] = img[el.id].length - 1;
            }
            if (titles[el.id][imgInc[el.id]] != '') {
                $('#ft-title-' + el.id).animate({
                    opacity: 0
                }, opts[el.id].titleSpeed, function () {
                    $(this).html(titles[el.id][imgInc[el.id]]).animate({
                        opacity: opts[el.id].titleOpacity
                    }, opts[el.id].titleSpeed);
                });
            } else {
                $('#ft-title-' + el.id).animate({
                    opacity: 0
                }, opts[el.id].titleSpeed);
            }
            inc[el.id] = 0;
            buttons = $('#ft-buttons-' + el.id).children();
            buttons.each(function (index) {
                if (index == imgInc[el.id]) {
                    $(this).addClass('ft-button-' + el.id + '-active');
                } else {
                    $(this).removeClass('ft-button-' + el.id + '-active');
                }
            });
            if (opts[el.id].direction == 'random') $.fisherYates(order[el.id]);
            if ((opts[el.id].direction == 'right' && order[el.id][0] == 1) || opts[el.id].direction == 'alternate' || opts[el.id].direction == 'fountainAlternate') order[el.id].reverse();
        };
        $.strips = function (itemId, el) {
            temp = opts[el.id].strips;
            if (inc[el.id] == temp) {
                clearInterval(stripInt[el.id]);
                return;
            }
            $('.ft-' + el.id).attr('href', links[el.id][imgInc[el.id]]);
            if (opts[el.id].position == 'curtain') {
                currWidth = $('#ft-' + el.id + itemId).width();
                $('#ft-' + el.id + itemId).css({
                    width: 0,
                    opacity: 0,
                    'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
                });
                $('#ft-' + el.id + itemId).animate({
                    width: currWidth,
                    opacity: 1
                }, 1000);
            } else {
                $('#ft-' + el.id + itemId).css({
                    height: 0,
                    opacity: 0,
                    'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
                });
                $('#ft-' + el.id + itemId).animate({
                    height: opts[el.id].height,
                    opacity: 1
                }, 1000);
            }
            inc[el.id]++;
        };
        $.navigation = function (el) {
            $('#' + el.id).append("<a href='#' id='ft-prev-" + el.id + "' class='ft-prev'>Prev</a>");
            $('#' + el.id).append("<a href='#' id='ft-next-" + el.id + "' class='ft-next'>Next</a>");
            $('#ft-prev-' + el.id).css({
                'position': 'absolute',
                'top': params.height / 2 - 15,
                'left': 0,
                'z-index': 1001,
                'line-height': '30px',
                'opacity': 0.7
            }).click(function (e) {
                e.preventDefault();
                $.transition(el, 'prev');
                clearInterval(imgInt[el.id]);
                imgInt[el.id] = setInterval(function () {
                    $.transition(el)
                }, params.delay + params.stripDelay * params.strips);
            });
            $('#ft-next-' + el.id).css({
                'position': 'absolute',
                'top': params.height / 2 - 15,
                'right': 0,
                'z-index': 1001,
                'line-height': '30px',
                'opacity': 0.7
            }).click(function (e) {
                e.preventDefault();
                $.transition(el);
                clearInterval(imgInt[el.id]);
                imgInt[el.id] = setInterval(function () {
                    $.transition(el)
                }, params.delay + params.stripDelay * params.strips);
            });
            $("<div id='ft-buttons-" + el.id + "'></div>").insertAfter($('#' + el.id));
            $('#ft-buttons-' + el.id).css({
                'text-align': 'right',
                'padding-top': 5,
                'width': opts[el.id].width
            });
            for (k = 1; k < img[el.id].length + 1; k++) {
                $('#ft-buttons-' + el.id).append("<a href='#' class='ft-button-" + el.id + "'>" + k + "</a>");
            }
            $('.ft-button-' + el.id).css({
                'padding': 5
            });
            $.each($('.ft-button-' + el.id), function (i, item) {
                $(item).click(function (e) {
                    e.preventDefault();
                    $.transition(el, i);
                    clearInterval(imgInt[el.id]);
                    imgInt[el.id] = setInterval(function () {
                        $.transition(el)
                    }, params.delay + params.stripDelay * params.strips);
                })
            });
        }
        $.fisherYates = function (arr) {
            var i = arr.length;
            if (i == 0) return false;
            while (--i) {
                var j = Math.floor(Math.random() * (i + 1));
                var tempi = arr[i];
                var tempj = arr[j];
                arr[i] = tempj;
                arr[j] = tempi;
            }
        }
        this.each(function () {
            init(this);
        });
    };
    $.fn.jqFancyTransitions.defaults = {
        width: 500,
        height: 332,
        strips: 10,
        delay: 5000,
        stripDelay: 50,
        titleOpacity: 0.7,
        titleSpeed: 1000,
        position: 'alternate',
        direction: 'fountainAlternate',
        effect: '',
        navigation: false,
        links: false
    };
})(jQuery);
</code>```

答: I agree with Marcus - the code is in dire need of an overhaul and I will be looking for an alternative. I advise the same to anyone that comes across the same problem with the same library as this version is not exactly "stable"</p>

ContentLicense: CC BY-SA 3.0

Title: Preventing SetInterval overlaps

Body:
I am using jqFancyTransitions.1.8 (http://workshop.rs/projects/jqfancytransitions/) and have the navigation enabled.

The problem I have is that if I spam click through the images (or simply click to early or too late), the effect goes crazy (especially on the curtain effect) - this is because the javascript intervals overlap and the offsets just go out of sync.

I have tried to edit the script to hide and reshow the navigation when a transition is not running, but I couldnt get this working properly, and the navigation would reshow at different intervals, maybe I was putting the code in the wrong place.

Can anyone help me insert $('#ft-buttons-slideshowHolder').show() &&  $('#ft-buttons-slideshowHolder').hide() in the right place to get this to work?

I was also wondering if anyone using this has had the same problem and constructed any hacks or fixes already, or if anyone is able to provide me with the assistance I require to make a quick fix happen!

Thank you SO community!!

(not my code, just beautified for easy assistance)...

/**
 * jqFancyTransitions - jQuery plugin
 * @version: 1.8 (2010/06/13)
 * @requires jQuery v1.2.2 or later
 * @author Ivan Lazarevic
 * Examples and documentation at: http://www.workshop.rs/projects/jqfancytransitions

 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 **/
(function ($) {
    var opts = new Array;
    var level = new Array;
    var img = new Array;
    var links = new Array;
    var titles = new Array;
    var order = new Array;
    var imgInc = new Array;
    var inc = new Array;
    var stripInt = new Array;
    var imgInt = new Array;
    $.fn.jqFancyTransitions = $.fn.jqfancytransitions = function (options) {
        init = function (el) {
            opts[el.id] = $.extend({}, $.fn.jqFancyTransitions.defaults, options);
            img[el.id] = new Array();
            links[el.id] = new Array();
            titles[el.id] = new Array();
            order[el.id] = new Array();
            imgInc[el.id] = 0;
            inc[el.id] = 0;
            params = opts[el.id];
            if (params.effect == 'zipper') {
                params.direction = 'alternate';
                params.position = 'alternate';
            }
            if (params.effect == 'wave') {
                params.direction = 'alternate';
                params.position = 'top';
            }
            if (params.effect == 'curtain') {
                params.direction = 'alternate';
                params.position = 'curtain';
            }
            stripWidth = parseInt(params.width / params.strips);
            gap = params.width - stripWidth * params.strips;
            stripLeft = 0;
            $.each($('#' + el.id + ' img'), function (i, item) {
                img[el.id][i] = $(item).attr('src');
                links[el.id][i] = $(item).next().attr('href');
                titles[el.id][i] = $(item).attr('alt') ? $(item).attr('alt') : '';
                $(item).hide();
            });
            $('#' + el.id).css({
                'background-image': 'url(' + img[el.id][0] + ')',
                'width': params.width,
                'height': params.height,
                'position': 'relative',
                'background-position': 'top left'
            });
            $('#' + el.id).append("
" + titles[el.id][0] + "
");
            if (titles[el.id][imgInc[el.id]]) $('#ft-title-' + el.id).css('opacity', opts[el.id].titleOpacity);
            else $('#ft-title-' + el.id).css('opacity', 0);
            if (params.navigation) {
                $.navigation(el);
                $('#ft-buttons-' + el.id).children().first().addClass('ft-button-' + el.id + '-active');
            }
            odd = 1;
            for (j = 1; j < params.strips + 1; j++) {
                if (gap > 0) {
                    tstripWidth = stripWidth + 1;
                    gap--;
                } else {
                    tstripWidth = stripWidth;
                }
                if (params.links) $('#' + el.id).append("");
                else $('#' + el.id).append("

");
                $("#ft-" + el.id + j).css({
                    'background-position': -stripLeft + 'px top',
                    'left': stripLeft
                });
                stripLeft += tstripWidth;
                if (params.position == 'bottom') $("#ft-" + el.id + j).css('bottom', 0);
                if (j % 2 == 0 && params.position == 'alternate') $("#ft-" + el.id + j).css('bottom', 0);
                if (params.direction == 'fountain' || params.direction == 'fountainAlternate') {
                    order[el.id][j - 1] = parseInt(params.strips / 2) - (parseInt(j / 2) * odd);
                    order[el.id][params.strips - 1] = params.strips;
                    odd *= -1;
                } else {
                    order[el.id][j - 1] = j;
                }
            }
            $('.ft-' + el.id).mouseover(function () {
                opts[el.id].pause = true;
            });
            $('.ft-' + el.id).mouseout(function () {
                opts[el.id].pause = false;
            });
            $('#ft-title-' + el.id).mouseover(function () {
                opts[el.id].pause = true;
            });
            $('#ft-title-' + el.id).mouseout(function () {
                opts[el.id].pause = false;
            });
            clearInterval(imgInt[el.id]);
            imgInt[el.id] = setInterval(function () {
                $.transition(el)
            }, params.delay + params.stripDelay * params.strips);
        };
        $.transition = function (el, direction) {
            if (opts[el.id].pause == true) return;
            stripInt[el.id] = setInterval(function () {
                $.strips(order[el.id][inc[el.id]], el)
            }, opts[el.id].stripDelay);
            $('#' + el.id).css({
                'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
            });
            if (typeof (direction) == "undefined") imgInc[el.id]++;
            else if (direction == 'prev') imgInc[el.id]--;
            else imgInc[el.id] = direction;
            if (imgInc[el.id] == img[el.id].length) {
                imgInc[el.id] = 0;
            }
            if (imgInc[el.id] == -1) {
                imgInc[el.id] = img[el.id].length - 1;
            }
            if (titles[el.id][imgInc[el.id]] != '') {
                $('#ft-title-' + el.id).animate({
                    opacity: 0
                }, opts[el.id].titleSpeed, function () {
                    $(this).html(titles[el.id][imgInc[el.id]]).animate({
                        opacity: opts[el.id].titleOpacity
                    }, opts[el.id].titleSpeed);
                });
            } else {
                $('#ft-title-' + el.id).animate({
                    opacity: 0
                }, opts[el.id].titleSpeed);
            }
            inc[el.id] = 0;
            buttons = $('#ft-buttons-' + el.id).children();
            buttons.each(function (index) {
                if (index == imgInc[el.id]) {
                    $(this).addClass('ft-button-' + el.id + '-active');
                } else {
                    $(this).removeClass('ft-button-' + el.id + '-active');
                }
            });
            if (opts[el.id].direction == 'random') $.fisherYates(order[el.id]);
            if ((opts[el.id].direction == 'right' && order[el.id][0] == 1) || opts[el.id].direction == 'alternate' || opts[el.id].direction == 'fountainAlternate') order[el.id].reverse();
        };
        $.strips = function (itemId, el) {
            temp = opts[el.id].strips;
            if (inc[el.id] == temp) {
                clearInterval(stripInt[el.id]);
                return;
            }
            $('.ft-' + el.id).attr('href', links[el.id][imgInc[el.id]]);
            if (opts[el.id].position == 'curtain') {
                currWidth = $('#ft-' + el.id + itemId).width();
                $('#ft-' + el.id + itemId).css({
                    width: 0,
                    opacity: 0,
                    'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
                });
                $('#ft-' + el.id + itemId).animate({
                    width: currWidth,
                    opacity: 1
                }, 1000);
            } else {
                $('#ft-' + el.id + itemId).css({
                    height: 0,
                    opacity: 0,
                    'background-image': 'url(' + img[el.id][imgInc[el.id]] + ')'
                });
                $('#ft-' + el.id + itemId).animate({
                    height: opts[el.id].height,
                    opacity: 1
                }, 1000);
            }
            inc[el.id]++;
        };
        $.navigation = function (el) {
            $('#' + el.id).append("Prev");
            $('#' + el.id).append("Next");
            $('#ft-prev-' + el.id).css({
                'position': 'absolute',
                'top': params.height / 2 - 15,
                'left': 0,
                'z-index': 1001,
                'line-height': '30px',
                'opacity': 0.7
            }).click(function (e) {
                e.preventDefault();
                $.transition(el, 'prev');
                clearInterval(imgInt[el.id]);
                imgInt[el.id] = setInterval(function () {
                    $.transition(el)
                }, params.delay + params.stripDelay * params.strips);
            });
            $('#ft-next-' + el.id).css({
                'position': 'absolute',
                'top': params.height / 2 - 15,
                'right': 0,
                'z-index': 1001,
                'line-height': '30px',
                'opacity': 0.7
            }).click(function (e) {
                e.preventDefault();
                $.transition(el);
                clearInterval(imgInt[el.id]);
                imgInt[el.id] = setInterval(function () {
                    $.transition(el)
                }, params.delay + params.stripDelay * params.strips);
            });
            $("

").insertAfter($('#' + el.id));
            $('#ft-buttons-' + el.id).css({
                'text-align': 'right',
                'padding-top': 5,
                'width': opts[el.id].width
            });
            for (k = 1; k < img[el.id].length + 1; k++) {
                $('#ft-buttons-' + el.id).append("" + k + "");
            }
            $('.ft-button-' + el.id).css({
                'padding': 5
            });
            $.each($('.ft-button-' + el.id), function (i, item) {
                $(item).click(function (e) {
                    e.preventDefault();
                    $.transition(el, i);
                    clearInterval(imgInt[el.id]);
                    imgInt[el.id] = setInterval(function () {
                        $.transition(el)
                    }, params.delay + params.stripDelay * params.strips);
                })
            });
        }
        $.fisherYates = function (arr) {
            var i = arr.length;
            if (i == 0) return false;
            while (--i) {
                var j = Math.floor(Math.random() * (i + 1));
                var tempi = arr[i];
                var tempj = arr[j];
                arr[i] = tempj;
                arr[j] = tempi;
            }
        }
        this.each(function () {
            init(this);
        });
    };
    $.fn.jqFancyTransitions.defaults = {
        width: 500,
        height: 332,
        strips: 10,
        delay: 5000,
        stripDelay: 50,
        titleOpacity: 0.7,
        titleSpeed: 1000,
        position: 'alternate',
        direction: 'fountainAlternate',
        effect: '',
        navigation: false,
        links: false
    };
})(jQuery);


问:
Generate Buttons inside Wrap from List<String> flutter
I have a List<String> and I want to generate, inside a Wrap widget, N Buttons (N string lenght).

I read about a List.generate, I'm trying to implement it, do you know how I can do that?

答:
First, create your buttons:

```<code>final strings = ['A', 'B'];
final buttons = List<Widget>.generate(
  strings.length,
  (i) => RaisedButton(
    onPressed: null,
    child: Text(strings[i]),
  ),
).toList();
</code>```

And then use them directly as Wrap's children:

```<code>Wrap(children: buttons)
</code>```

Body:
First, create your buttons:

final strings = ['A', 'B'];
final buttons = List<Widget>.generate(
  strings.length,
  (i) => RaisedButton(
    onPressed: null,
    child: Text(strings[i]),
  ),
).toList();

And then use them directly as Wrap's children:

Wrap(children: buttons)


问:
Can't seem to break while loop properly. Comes up with an error message
The code takes data from csv and reads up to row with no data- works well but code ends in error - break not working properly? Carries out necessary function of reading all data but it seems to continue through the while true statement past len(row) > 0 when it should be an empty row where len(row) == 0 - any ideas how to stop error message? Functionality is good but error message is obviously a tad annoying.</p>

```<code>while True:
    len(row) > 0
    row = csvFileArray[rowValue]  # row
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1

    if len(row) == 0:
        break
</code>```

答:
The second line len(row)>0 is a redundant statement not doing anything.

I think when your program runs into a row with no entry on the third line of your code i.e. row = csvFileArray[rowValue], it continues to assign this empty row to row and try to access indices of row beyond 0 in the following line, which gives error.

Try moving the last

```<code>    if len(row) == 0:
        break
</code>```

to the line after row = csvFileArray[rowValue]  # row so its length gets checked immediately before you attempt to access indices.

Body:
The code takes data from csv and reads up to row with no data- works well but code ends in error - break not working properly? Carries out necessary function of reading all data but it seems to continue through the while true statement past len(row) > 0 when it should be an empty row where len(row) == 0 - any ideas how to stop error message? Functionality is good but error message is obviously a tad annoying.

while True:
    len(row) > 0
    row = csvFileArray[rowValue]  # row
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1

    if len(row) == 0:
        break

Body:
The second line len(row)>0 is a redundant statement not doing anything.

I think when your program runs into a row with no entry on the third line of your code i.e. row = csvFileArray[rowValue], it continues to assign this empty row to row and try to access indices of row beyond 0 in the following line, which gives error.

Try moving the last

    if len(row) == 0:
        break

to the line after row = csvFileArray[rowValue]  # row so its length gets checked immediately before you attempt to access indices.


问:
Sending Sensor Data from Nodemcu ESP32 and Firebase
I'm trying to send sensor data from nodemcu ESP32 to firebase.
When using the basic example shown below it worked fine, and also when viewing the sensor data without sending it to firebase.
https://github.com/mobizt/Firebase-ESP32/tree/master/examples/Basic

However when I tried to edit the code a bit and send my sensor's data, I get an error, I would appreciate any help, code, and error attached.

```<code>#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

//Define FirebaseESP32 data object
FirebaseData firebaseData;

FirebaseJson json;
DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 15;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void printResult(FirebaseData &data);

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
    float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

      if (Firebase.setFloat(firebaseData, path + "/Air Temp" + t))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

  if (Firebase.setFloat(firebaseData, path + "/Air Humidity" + h))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Temperature" + temperatureC))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Moisture" + Soil_Moisture))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }
  delay(5000);
}
</code>```

Error:

firebasecode:74:65: error: no matching function for call to 'FirebaseESP32::setFloat(FirebaseData&, StringSumHelper&)'

答:
This is the new code which for some reason does not send the air humidity data, only air temp, the soil temp and moisture works fine.</p>

```<code>#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

FirebaseData firebaseData;

FirebaseJson json;

void printResult(FirebaseData &data);
//Define FirebaseESP32 data object

DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 32;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

    Firebase.setFloat(firebaseData, path + "/Air Humidity", h);
    Firebase.setFloat(firebaseData, path + "/Air Temp", t);
    Firebase.setFloat(firebaseData, path + "/Soil Temperature", temperatureC);
    Firebase.setFloat(firebaseData, path + "/Soil Moisture", Soil_Moisture);
 delay(5000);

}

</code>```

Body:
I'm trying to send sensor data from nodemcu ESP32 to firebase.
When using the basic example shown below it worked fine, and also when viewing the sensor data without sending it to firebase.
https://github.com/mobizt/Firebase-ESP32/tree/master/examples/Basic

However when I tried to edit the code a bit and send my sensor's data, I get an error, I would appreciate any help, code, and error attached.

#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

//Define FirebaseESP32 data object
FirebaseData firebaseData;

FirebaseJson json;
DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 15;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void printResult(FirebaseData &data);

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
    float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

      if (Firebase.setFloat(firebaseData, path + "/Air Temp" + t))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

  if (Firebase.setFloat(firebaseData, path + "/Air Humidity" + h))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Temperature" + temperatureC))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Moisture" + Soil_Moisture))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }
  delay(5000);
}

Error:

firebasecode:74:65: error: no matching function for call to 'FirebaseESP32::setFloat(FirebaseData&, StringSumHelper&)'

Body:
This is the new code which for some reason does not send the air humidity data, only air temp, the soil temp and moisture works fine.

#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

FirebaseData firebaseData;

FirebaseJson json;

void printResult(FirebaseData &data);
//Define FirebaseESP32 data object

DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 32;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

    Firebase.setFloat(firebaseData, path + "/Air Humidity", h);
    Firebase.setFloat(firebaseData, path + "/Air Temp", t);
    Firebase.setFloat(firebaseData, path + "/Soil Temperature", temperatureC);
    Firebase.setFloat(firebaseData, path + "/Soil Moisture", Soil_Moisture);
 delay(5000);

}


问:
Removing specific pattern from a string using regex in python
I am trying to remove the pattern  using following code

```<code>x = "mr<u+092d><u+093e><u+0935><u+0941><u+0915>"
pattern = '[<u+0-9de>]'
re.sub(pattern,'', x)
</code>```

Output

```<code>mr
</code>```

This output is actually correct for the given sample string but when I am running this code to the corpus, it removing all the occurrences of 'de' as well as digits etc. I want these things are replaced only when < > is used.

答:
You need to put the <> outside, as the structure will always be

start with <

following by u\+

4 chars in hexa [0-9a-f]{4} as from Unicode definition

end with >

```<code>pattern = '<u\+[0-9a-f]{4}>'
re.sub(pattern,'', x)
</code>```

                                   REGEX DEMO ★ CODE DEMO

Body:
I am trying to remove the pattern  using following code

x = "mr"
pattern = '[]'
re.sub(pattern,'', x)

Output

mr

This output is actually correct for the given sample string but when I am running this code to the corpus, it removing all the occurrences of 'de' as well as digits etc. I want these things are replaced only when < > is used.

Body:
You need to put the <> outside, as the structure will always be

start with <

following by u\+

4 chars in hexa [0-9a-f]{4} as from Unicode definition

end with >

pattern = '<u\+[0-9a-f]{4}>'
re.sub(pattern,'', x)

                                   REGEX DEMO ★ CODE DEMO


问:
Reshaping rectangular image to square
I want to convert a rectangular image to a square image.
But, I have problems.

My trial Python code is here:

```<code>from PIL import Image
import numpy as np

im = Image.open('aa.png')
pixMap = im.load()

img = Image.new( im.mode, im.size)
sqrWidth = np.ceil(np.sqrt(im.size[0]*im.size[1])

pixNew = Image.new(im.mode, (im.size[0]*im.size[1], 1))
pixSave = Image.new(im.mode, (sqrWidth, sqrWidth))

k=0
for i in range(img.size[0]):
    for j in range(img.size[1]):
        pixNew[k] = pixMap[i, j]
        k=k+1

k=0
for i in range(sqrWidth):
    for j in range(sqrWidth):
        pixSave[i, j] = pixNew[k]
        k=k+1

im.close()
img.show()
img.save("out.png")
img.close()
</code>```

My error is here:

```<code>Traceback (most recent call last):
  File "rect2square.py", line 13, in <module>
    pixNew[k] = pixMap[i, j]
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py",     line 528, in __getattr__
raise AttributeError(name)
AttributeError: __setitem__
</code>```

What's wrong?

答:
Here is a Python library that will help you resize your images while maintaining the aspect ratio. If the original aspect ratio is different from the aspect ratio you are converting it to, it will add a background with a color of your choice.

https://pypi.org/project/python-resize-image/

You might want to look at this function

resize_contain(image, size, validate=True, resample=Image.LANCZOS, bg_color=(255, 255, 255, 0))

Title: Reshaping rectangular image to square

Body:
I want to convert a rectangular image to a square image.
But, I have problems.

My trial Python code is here:

from PIL import Image
import numpy as np

im = Image.open('aa.png')
pixMap = im.load()

img = Image.new( im.mode, im.size)
sqrWidth = np.ceil(np.sqrt(im.size[0]*im.size[1])

pixNew = Image.new(im.mode, (im.size[0]*im.size[1], 1))
pixSave = Image.new(im.mode, (sqrWidth, sqrWidth))

k=0
for i in range(img.size[0]):
    for j in range(img.size[1]):
        pixNew[k] = pixMap[i, j]
        k=k+1

k=0
for i in range(sqrWidth):
    for j in range(sqrWidth):
        pixSave[i, j] = pixNew[k]
        k=k+1

im.close()
img.show()
img.save("out.png")
img.close()

My error is here:

Traceback (most recent call last):
  File "rect2square.py", line 13, in <module>
    pixNew[k] = pixMap[i, j]
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py",     line 528, in __getattr__
raise AttributeError(name)
AttributeError: __setitem__

What's wrong?


问:
NotesDocument opens twice
I have an application that uses 2 servers and has 2 databases.
Server 1 - Main application
Server 2 - Calendar

When launching a document in the main application, I have a link to the calendar entry.  This opens the calendar entry on the calendar server.  There is a link in the calendar entry that launches the document in the main application.

This action is performed using the notesuiworkspace.editDocument function.

The problem I have is that in my scenario above, I have the main document open in the application (1 document).  I then click on the button to launch the calendar entry (I now have 2 documents open, the document in the main application and the corresponding calendar entry).  If I then click on the open main document button, it opens another copy of the main document.  If the user is unaware they then cause save conflicts.

This has occurred for several versions of Notes, currently on 10.

Code from Main Application Server 1 docuemnt to open calendar entry:

```<code>Set uidoc = ws.CurrentDocument
Set doc = Srv1.GetDocumentByUNID(uidoc.FieldGetText("CalenderUNID")
If Not (doc Is Nothing) Then
  Set uidoc = ws.EditDocument(True, doc)
End If
</code>```

Code from Calendar Entry to Main document on Server1

```<code>sID = uidoc.FieldGetText("MainUNID")
Set doc = Srv1.GetDocumentByUNID(sID)
If Not (doc Is Nothing) Then
  Call uidoc.Close(True)
  Set uidoc = ws.EditDocument(True, doc)
End If
</code>```

答:
Please check the documentation for "EditDocument" in NotesUIWorkspace:

Set notesUIDocument = notesUIWorkspace .EditDocument( [editMode] , [notesDocument] , [notesDocumentReadOnly] , [documentAnchor$] , [returnNotesUIDocument] , [newInstance] )

You see, there is an optional parameter "newInstance". And if you read further it sais:

newInstance

Boolean. Optional. If True (default), opens a new instance of notesDocument (parameter 2) in the UI. If False, changes focus to an existing instance of notesDocument if one exists, or to a new instance if one does not exist. This parameter does not apply if notesDocument is not specified or the document has a target frame.

Just change your code accordingly:

```<code>Set uidoc = ws.EditDocument(True, doc,False,"",True,False)
</code>```

But beware: There is a (little) bug with the "newInstance" flag:
If you create a new main document and save it. Then open the calendar document and click the link back to the main document, then there will always be a second window with the main document unless you closed and reopened the main document in the meantime... A "new" document that has not been closed and reopened after saving is not recognized by the newinstance flag...

Title: NotesDocument opens twice

Body:
I have an application that uses 2 servers and has 2 databases.
Server 1 - Main application
Server 2 - Calendar

When launching a document in the main application, I have a link to the calendar entry.  This opens the calendar entry on the calendar server.  There is a link in the calendar entry that launches the document in the main application.

This action is performed using the notesuiworkspace.editDocument function.

The problem I have is that in my scenario above, I have the main document open in the application (1 document).  I then click on the button to launch the calendar entry (I now have 2 documents open, the document in the main application and the corresponding calendar entry).  If I then click on the open main document button, it opens another copy of the main document.  If the user is unaware they then cause save conflicts.

This has occurred for several versions of Notes, currently on 10.

Code from Main Application Server 1 docuemnt to open calendar entry:

Set uidoc = ws.CurrentDocument
Set doc = Srv1.GetDocumentByUNID(uidoc.FieldGetText("CalenderUNID")
If Not (doc Is Nothing) Then
  Set uidoc = ws.EditDocument(True, doc)
End If

Code from Calendar Entry to Main document on Server1

sID = uidoc.FieldGetText("MainUNID")
Set doc = Srv1.GetDocumentByUNID(sID)
If Not (doc Is Nothing) Then
  Call uidoc.Close(True)
  Set uidoc = ws.EditDocument(True, doc)
End If

Body:
Please check the documentation for "EditDocument" in NotesUIWorkspace:

Set notesUIDocument = notesUIWorkspace .EditDocument( [editMode] , [notesDocument] , [notesDocumentReadOnly] , [documentAnchor$] , [returnNotesUIDocument] , [newInstance] )

You see, there is an optional parameter "newInstance". And if you read further it sais:

newInstance

Boolean. Optional. If True (default), opens a new instance of notesDocument (parameter 2) in the UI. If False, changes focus to an existing instance of notesDocument if one exists, or to a new instance if one does not exist. This parameter does not apply if notesDocument is not specified or the document has a target frame.

Just change your code accordingly:

Set uidoc = ws.EditDocument(True, doc,False,"",True,False)

But beware: There is a (little) bug with the "newInstance" flag:
If you create a new main document and save it. Then open the calendar document and click the link back to the main document, then there will always be a second window with the main document unless you closed and reopened the main document in the meantime... A "new" document that has not been closed and reopened after saving is not recognized by the newinstance flag...


问:
3D rigid body transform decomposition reorder
I have this idea in my head and I am trying to figure out how to implement it. One of the parts that I am struggling with is how to take a 3D rigid-body transform and decompose it into dx, dy, dz, theta_X, theta_Y, and theta_Z.

This of course is a very well document algorithm. My problem is that matrix algebra is noncommutative. I would like to reorder the components such that it goes (dx*dy*theta_Z)*(dz*theta_X*theta_Y).

For any of you who wants to know why I want to do this is because I would like to do apply the transform (dx*dy*theta_Z) on a 3D image followed by then another operation followed by the completion of the rigid body transform. Does anyone know how to do this?

答:
If you first decompose your rotation into your desired ordering (theta_Z * theta_X * theta_Y), it is reasonably straightforward to reorder any translation the way you want:

```<code>let:   t' = theta_Z^-1 * t * theta_Z

then:  t * theta_Z = theta_Z * t'

and:   t * theta_Z * theta_X * theta_Y
     = theta_Z * t' * theta_X * theta_Y
</code>```

However, for the particular reordering you want, please note that rotation about the Z axis should not affect a pure translation about the Z axis at all!  Even though general rigid body transforms don't commute, your dz and theta_Z transforms do:

```<code>commutative:  dz * theta_Z = theta_Z * dz

and:  my_transform = dx * dy * dz * theta_Z * theta_X * theta_Y
                   = dx * dy * theta_Z * dz * theta_X * theta_Y
</code>```

Body:
If you first decompose your rotation into your desired ordering (theta_Z * theta_X * theta_Y), it is reasonably straightforward to reorder any translation the way you want:

let:   t' = theta_Z^-1 * t * theta_Z

then:  t * theta_Z = theta_Z * t'

and:   t * theta_Z * theta_X * theta_Y
     = theta_Z * t' * theta_X * theta_Y

However, for the particular reordering you want, please note that rotation about the Z axis should not affect a pure translation about the Z axis at all!  Even though general rigid body transforms don't commute, your dz and theta_Z transforms do:

commutative:  dz * theta_Z = theta_Z * dz

and:  my_transform = dx * dy * dz * theta_Z * theta_X * theta_Y
                   = dx * dy * theta_Z * dz * theta_X * theta_Y


问:
How would I resolve this 422 error during POST?
I'm trying to follow a code along on Udemy except making my version of the project. After using bcrypt and jwt, I'm unable to make any posts to my app. I'm able to login fine, but when trying to post something, I get a 422 error.

This is what's getting me stuck.

```<code>  const twottSubmitHandler = async (event) => {
    event.preventDefault();

    try {
      const formData = new FormData();
      formData.append("title", formState.inputs.title.value);
      formData.append("description", formState.inputs.description.value);
      formData.append("creator", auth.userId);
      await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
        Authorization: "Bearer " + auth.token,
      });
      history.push("/");
    } catch (err) {}
  };
</code>```

In the twotts-controller, this is what's throwing the error,

```<code>  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(new HttpError("Invalid input passed", 422));
  }
  const { title, description, creator } = req.body;
  const createdTwott = new Twott({
    title,
    description,
    creator,
  });
</code>```

Is there a way to make it so it adds it using JSON.stringify instead of using FormData? Using

```<code>    try {
      await sendRequest(
        "http://localhost:3001/api/twotts",
        "POST",
        JSON.stringify({
          title: formState.inputs.title.value,
          description: formState.inputs.description.value,
          creator: auth.userId,
        }),
        { Authorization: "Bearer " + auth.token },
        { "Content-Type": "application/json" }
      );
      history.push("/");
    } catch (err) {}
</code>```

I still get invalid inputs. If I put the Authorization argument anywhere else, I'd get authentication issues.

the link to the repo is https://github.com/preintercede/Twotter (with commits) in case there's a part that I missed.

答:
You're constructing FormData and send it (implicitly) with Content-Type: multipart/form-data. express-validator doesn't validate such data out-of-the box (reasoning: https://github.com/express-validator/express-validator/issues/276)

One solution would be to use https://github.com/expressjs/multer, but my recommendation is just to submit JSON data with correct Content-Type, as already you're doing for other requests:

```<code>─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 modified: src/twotts/pages/NewTwott.js
 ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 @ src/twotts/pages/NewTwott.js:39 @ const NewTwott = () => {
      event.preventDefault();

      try {
 -      const formData = new FormData();
 -      formData.append("title", formState.inputs.title.value);
 -      formData.append("description", formState.inputs.description.value);
 -      formData.append("creator", auth.userId);
 -      await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
 +      await sendRequest("http://localhost:3001/api/twotts", "POST", JSON.stringify({
 +        title: formState.inputs.title.value,
 +        description: formState.inputs.description.value,
 +        creator: auth.userId
 +      }), {
          Authorization: "Bearer " + auth.token,
 +        "Content-Type": "application/json",
        });
        history.push("/");
      } catch (err) {}
</code>```

I recommend to wrap this into a helper function. This could also set the Bearer token to the request headers if present.

Body:
I'm trying to follow a code along on Udemy except making my version of the project. After using bcrypt and jwt, I'm unable to make any posts to my app. I'm able to login fine, but when trying to post something, I get a 422 error.

This is what's getting me stuck.

  const twottSubmitHandler = async (event) => {
    event.preventDefault();

    try {
      const formData = new FormData();
      formData.append("title", formState.inputs.title.value);
      formData.append("description", formState.inputs.description.value);
      formData.append("creator", auth.userId);
      await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
        Authorization: "Bearer " + auth.token,
      });
      history.push("/");
    } catch (err) {}
  };

In the twotts-controller, this is what's throwing the error,

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(new HttpError("Invalid input passed", 422));
  }
  const { title, description, creator } = req.body;
  const createdTwott = new Twott({
    title,
    description,
    creator,
  });

Is there a way to make it so it adds it using JSON.stringify instead of using FormData? Using

    try {
      await sendRequest(
        "http://localhost:3001/api/twotts",
        "POST",
        JSON.stringify({
          title: formState.inputs.title.value,
          description: formState.inputs.description.value,
          creator: auth.userId,
        }),
        { Authorization: "Bearer " + auth.token },
        { "Content-Type": "application/json" }
      );
      history.push("/");
    } catch (err) {}

I still get invalid inputs. If I put the Authorization argument anywhere else, I'd get authentication issues.

the link to the repo is https://github.com/preintercede/Twotter (with commits) in case there's a part that I missed.

Body:
You're constructing FormData and send it (implicitly) with Content-Type: multipart/form-data. express-validator doesn't validate such data out-of-the box (reasoning: https://github.com/express-validator/express-validator/issues/276)

One solution would be to use https://github.com/expressjs/multer, but my recommendation is just to submit JSON data with correct Content-Type, as already you're doing for other requests:

─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 modified: src/twotts/pages/NewTwott.js
 ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 @ src/twotts/pages/NewTwott.js:39 @ const NewTwott = () => {
      event.preventDefault();

      try {
 -      const formData = new FormData();
 -      formData.append("title", formState.inputs.title.value);
 -      formData.append("description", formState.inputs.description.value);
 -      formData.append("creator", auth.userId);
 -      await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
 +      await sendRequest("http://localhost:3001/api/twotts", "POST", JSON.stringify({
 +        title: formState.inputs.title.value,
 +        description: formState.inputs.description.value,
 +        creator: auth.userId
 +      }), {
          Authorization: "Bearer " + auth.token,
 +        "Content-Type": "application/json",
        });
        history.push("/");
      } catch (err) {}

I recommend to wrap this into a helper function. This could also set the Bearer token to the request headers if present.


问:
Why in NLTK "not" is considered as stopping word in English?
I am currently learning nltk in Python where I am writing a program for sentiment analysis. While working on it, I found out that "not, nor, never" are considered stopping words. So my question is why that is because these kinds of words can change the entire meaning of sentences and could lead to failure in sentiment analysis.</p>

答:
Stop words are usually created based on analysis of the most common words in the language (that is the main reason "not" is in there). The idea behind them is to allow analysis (normally a bag of words approach) to focus on the more interesting words of the document.

They are used for multiple purposes: they were not designed specifically for sentiment analysis. That is another reason "not" is in there.

A bag-of-words approach to sentiment analysis is always going to end up a bit crude, with or without stop words. E.g. It is not hard to create realistic-sounding positive movie reviews using negative words:

"This movie was not at all what I expected: I usually hate Tom Cruise but he made this movie work."

"I never watch chick-flicks, but as they say, never say never."

Anyway try customizing your stopword list, removing "not" and "never" to see if it improves results. Then try again using no stopwords at all.


问:
Wordpress Avada Theme remove border
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

```<code>#main .fusion-row {
    border-top: 0px !important;
}
</code>```

答:
You can tru and edit the border thickness as it is:</p>

```<code>#main .fusion-row {
    border-top: 0px solid #fff !important;
}
</code>```

Title: Wordpress Avada Theme remove border

Body:
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

#main .fusion-row {
    border-top: 0px !important;
}

Body:
You can tru and edit the border thickness as it is:

#main .fusion-row {
    border-top: 0px solid #fff !important;
}


问:
jq how to merge array objects into single object
in jq its possible to add objects using the + operator

if you have an array

```<code> [
      {
        "a": "value"
      },
      {
        "b": "value"
      },
      {
        "c": "value"
      }
 ]
</code>```

I want to convert it into a single object { a:"value", b:"value", c:"value" }
I can use the following filter .[0] + .[1] + .[2], but i want to do it for the whole array without specifying all the indexes.

答:
The simplest way is just to call add filter.

"The filter add takes as input an array, and produces as output the elements of the array added together. This might mean summed, concatenated or merged depending on the types of the elements of the input array - the rules are the same as those for the + operator (described above)."

Source: https://stedolan.github.io/jq/manual/#add

```<code>$ cat test.json
[
    {
        "a": "value"
    },
    {
        "b": "value"
    },
    {
        "c": "value"
    }
 ]

$ jq 'add' test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}
</code>```

As mentioned by peak in the comment, you can even skip wrapping add filter with the quotes:

```<code>$ jq add test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}
</code>```

Body:
in jq its possible to add objects using the + operator

if you have an array

 [
      {
        "a": "value"
      },
      {
        "b": "value"
      },
      {
        "c": "value"
      }
 ]

I want to convert it into a single object { a:"value", b:"value", c:"value" }
I can use the following filter .[0] + .[1] + .[2], but i want to do it for the whole array without specifying all the indexes.

Body:
The simplest way is just to call add filter.

"The filter add takes as input an array, and produces as output the elements of the array added together. This might mean summed, concatenated or merged depending on the types of the elements of the input array - the rules are the same as those for the + operator (described above)."

Source: https://stedolan.github.io/jq/manual/#add

$ cat test.json
[
    {
        "a": "value"
    },
    {
        "b": "value"
    },
    {
        "c": "value"
    }
 ]

$ jq 'add' test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}

As mentioned by peak in the comment, you can even skip wrapping add filter with the quotes:

$ jq add test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}


问:
Unity error immediately after creating a new Project
When creating a new 3D project in Unity (version 2019.3.3f1), I got an error in the Unity console without making any change or doing anything within Unity.

The Error:

IndexOutOfRangeException: Index was outside the bounds of the array.
  VSCodeEditor.ProjectGeneration.b__25_0 (System.String asset) (at Library/PackageCache/com.unity.ide.vscode@1.1.4/Editor/ProjectGeneration/ProjectGeneration.cs:175)

And the line of code supposedly wrong is from the file created w/ the Project called projectGeneration.cs.

```<code>var affectedNames = affectedFiles.Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset)?.Split(new [] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);
</code>```

答:
Downgrade visual studio code version to 1.1.3 to fix this error

Open Unity, then go to: Window->Package Manager->Visual Studio Code 1.1.3

After that, just restart Unity and it will fix the error.

Body:
When creating a new 3D project in Unity (version 2019.3.3f1), I got an error in the Unity console without making any change or doing anything within Unity.

The Error:

IndexOutOfRangeException: Index was outside the bounds of the array.
  VSCodeEditor.ProjectGeneration.b__25_0 (System.String asset) (at Library/PackageCache/com.unity.ide.vscode@1.1.4/Editor/ProjectGeneration/ProjectGeneration.cs:175)

And the line of code supposedly wrong is from the file created w/ the Project called projectGeneration.cs.

var affectedNames = affectedFiles.Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset)?.Split(new [] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);


问:
Increasing the count field of model whenever a search is applied
I have a search api

```<code>   class SearchViewSet(RetrieveModelViewSet):
        serializer_class = ArticleSerializer
        queryset = Article.objects.all()
        query = self.request.query_params.get("query")

        final_queryset = search(query,queryset,#some logic)

        #logic to generate serialiser and return serialiser.data
        serialiser = self.get_serializer(final_ueryset, many=True)
</code>```

search function returns a list of articles i.e

```<code>   type(final_queryset) is List
</code>```

And. I wan't to return the articles order_by('count) as well.
Now I wan't to increase the count of top 3 articles from the final_queryset is there a way of doing this.

答:
Figured out a way for doing this
Just simply iterate on the list and increment the count of the objects in the list

```<code>   class SearchViewSet(RetrieveModelViewSet):
        serializer_class = ArticleSerializer
        queryset = Article.objects.all()
        query = self.request.query_params.get("query")

        final_queryset = search(query,queryset,#some logic)

        # to increment the count of top 3 entity_aliases
        for instance in final_queryset[:3]:
            instance.count += 1
            instance.save()

        #logic to generate serialiser and return serialiser.data
        serialiser = self.get_serializer(final_ueryset, many=True)
</code>```

Body:
I have a search api

   class SearchViewSet(RetrieveModelViewSet):
        serializer_class = ArticleSerializer
        queryset = Article.objects.all()
        query = self.request.query_params.get("query")

        final_queryset = search(query,queryset,#some logic)

        #logic to generate serialiser and return serialiser.data
        serialiser = self.get_serializer(final_ueryset, many=True)

search function returns a list of articles i.e

   type(final_queryset) is List

And. I wan't to return the articles order_by('count) as well.
Now I wan't to increase the count of top 3 articles from the final_queryset is there a way of doing this.

Body:
Figured out a way for doing this
Just simply iterate on the list and increment the count of the objects in the list

   class SearchViewSet(RetrieveModelViewSet):
        serializer_class = ArticleSerializer
        queryset = Article.objects.all()
        query = self.request.query_params.get("query")

        final_queryset = search(query,queryset,#some logic)

        # to increment the count of top 3 entity_aliases
        for instance in final_queryset[:3]:
            instance.count += 1
            instance.save()

        #logic to generate serialiser and return serialiser.data
        serialiser = self.get_serializer(final_ueryset, many=True)


问:
Are there any ready-to-use map controls for wp7?
I know microsoft provides a bing map control.
And ESRI has a map control for wp7.

Are there any other map controls?

答:
What other sort of Map control do you want? The Bing Maps control is highly extensible allowing you to create tile sources for all sorts of other mapping data. For example you can use it to render Google Sky tiles:

http://www.scottlogic.co.uk/blog/colin/2011/02/google-sky-on-windows-phone-7/


问:
Cannot create native container on Windows
I want to create a native container for the getting-started quarkus application.
I get successful when I tried on Ubuntu, but for some reasons I am facing issues on Windows 10. Here is what I've tried so far.

I have no problem for creating a native executable with this command:

```<code>cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative'
</code>```

But when I try to create a native container with the command given in the quarkus guide:

```<code>cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative -Dquarkus.native.container-build=true'
</code>```

I get the following errors:

```<code>Error: Invalid Path entry getting-started-1.0-SNAPSHOT-runner.jar
Caused by: java.nio.file.NoSuchFileException: /project/getting-started-1.0-SNAPSHOT-runner.jar
</code>```

I've already checked my shared resources on Docker Desktop and I have C:\ and D:\ (which are my hard disks). So I don't know how to go further in the solution... Here is my entire stack if needed:

```<code>> cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative -Dquarkus.native.container-build=true'

**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.0
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\git\quarkus-quickstarts\getting-started\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ getting-started ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.acme.getting.started.GreetingResourceTest
2020-05-17 16:25:01,839 INFO  [io.quarkus] (main) Quarkus 1.4.2.Final started in 1.350s. Listening on: http://0.0.0.0:8081
2020-05-17 16:25:01,847 INFO  [io.quarkus] (main) Profile test activated.
2020-05-17 16:25:01,848 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.874 s - in org.acme.getting.started.GreetingResourceTest
2020-05-17 16:25:03,019 INFO  [io.quarkus] (main) Quarkus stopped in 0.030s
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ getting-started ---
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:build (default) @ getting-started ---
[INFO] [org.jboss.threads] JBoss Threads version 3.1.1.Final
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building thin jar: D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.QuarkusAugmentor] Quarkus augmentation completed in 850ms
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:native-image (default) @ getting-started ---
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building native image source jar: D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-native-image-source-jar\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Building native image from D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-native-image-source-jar\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Pulling image quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
19.3.1-java11: Pulling from quarkus/ubi-quarkus-native-image
Digest: sha256:9e2dd59c82db091bb90fd0ee60530291a5ecc201ebc718ffcc59ab0f406e47ea
Status: Image is up to date for quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Running Quarkus native-image plugin on GraalVM Version 19.3.1 CE
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] docker run -v //d/git/quarkus-quickstarts/getting-started/target/getting-started-1.0-SNAPSHOT-native-image-source-jar:/project:z --env LANG=C --rm quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11 -J-Djava.util.logging.manager=org.jboss.logmanager.LogManager -J-Dsun.nio.ch.maxUpdateArraySize=100 -J-Dvertx.logger-delegate-factory-class-name=io.quarkus.vertx.core.runtime.VertxLogDelegateFactory -J-Dvertx.disableDnsResolver=true -J-Dio.netty.leakDetection.level=DISABLED -J-Dio.netty.allocator.maxOrder=1 -J-Duser.language=fr -J-Dfile.encoding=Cp1252 --initialize-at-build-time= -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime -H:+JNI -jar getting-started-1.0-SNAPSHOT-runner.jar -H:FallbackThreshold=0 -H:+ReportExceptionStackTraces -H:-AddAllCharsets -H:-IncludeAllTimeZones -H:EnableURLProtocols=http -H:-UseServiceLoaderFeature -H:+StackTrace getting-started-1.0-SNAPSHOT-runner
Error: Invalid Path entry getting-started-1.0-SNAPSHOT-runner.jar
Caused by: java.nio.file.NoSuchFileException: /project/getting-started-1.0-SNAPSHOT-runner.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.752 s
[INFO] Finished at: 2020-05-17T16:25:09+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.4.2.Final:native-image (default) on project getting-started: Failed to generate native image: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[ERROR]         [error]: Build step io.quarkus.deployment.pkg.steps.NativeImageBuildStep#build threw an exception: java.lang.RuntimeException: Failed to build native image
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:353)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]         at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]         at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR]         at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:931)
[ERROR]         at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
[ERROR]         at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
[ERROR]         at java.base/java.lang.Thread.run(Thread.java:834)
[ERROR]         at org.jboss.threads.JBossThread.run(JBossThread.java:479)
[ERROR] Caused by: java.lang.RuntimeException: Image generation failed. Exit code: 1
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.imageGenerationFailed(NativeImageBuildStep.java:369)
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:339)
[ERROR]         ... 12 more
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答: Updating Docker Desktop for Windows to the latest version (2.3.0.3) fixed my issue.

Body:
I want to create a native container for the getting-started quarkus application.
I get successful when I tried on Ubuntu, but for some reasons I am facing issues on Windows 10. Here is what I've tried so far.

I have no problem for creating a native executable with this command:

cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative'

But when I try to create a native container with the command given in the quarkus guide:

cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative -Dquarkus.native.container-build=true'

I get the following errors:

Error: Invalid Path entry getting-started-1.0-SNAPSHOT-runner.jar
Caused by: java.nio.file.NoSuchFileException: /project/getting-started-1.0-SNAPSHOT-runner.jar

I've already checked my shared resources on Docker Desktop and I have C:\ and D:\ (which are my hard disks). So I don't know how to go further in the solution... Here is my entire stack if needed:

> cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative -Dquarkus.native.container-build=true'

**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.0
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\git\quarkus-quickstarts\getting-started\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ getting-started ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.acme.getting.started.GreetingResourceTest
2020-05-17 16:25:01,839 INFO  [io.quarkus] (main) Quarkus 1.4.2.Final started in 1.350s. Listening on: http://0.0.0.0:8081
2020-05-17 16:25:01,847 INFO  [io.quarkus] (main) Profile test activated.
2020-05-17 16:25:01,848 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.874 s - in org.acme.getting.started.GreetingResourceTest
2020-05-17 16:25:03,019 INFO  [io.quarkus] (main) Quarkus stopped in 0.030s
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ getting-started ---
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:build (default) @ getting-started ---
[INFO] [org.jboss.threads] JBoss Threads version 3.1.1.Final
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building thin jar: D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.QuarkusAugmentor] Quarkus augmentation completed in 850ms
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:native-image (default) @ getting-started ---
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building native image source jar: D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-native-image-source-jar\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Building native image from D:\git\quarkus-quickstarts\getting-started\target\getting-started-1.0-SNAPSHOT-native-image-source-jar\getting-started-1.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Pulling image quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
19.3.1-java11: Pulling from quarkus/ubi-quarkus-native-image
Digest: sha256:9e2dd59c82db091bb90fd0ee60530291a5ecc201ebc718ffcc59ab0f406e47ea
Status: Image is up to date for quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Running Quarkus native-image plugin on GraalVM Version 19.3.1 CE
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] docker run -v //d/git/quarkus-quickstarts/getting-started/target/getting-started-1.0-SNAPSHOT-native-image-source-jar:/project:z --env LANG=C --rm quay.io/quarkus/ubi-quarkus-native-image:19.3.1-java11 -J-Djava.util.logging.manager=org.jboss.logmanager.LogManager -J-Dsun.nio.ch.maxUpdateArraySize=100 -J-Dvertx.logger-delegate-factory-class-name=io.quarkus.vertx.core.runtime.VertxLogDelegateFactory -J-Dvertx.disableDnsResolver=true -J-Dio.netty.leakDetection.level=DISABLED -J-Dio.netty.allocator.maxOrder=1 -J-Duser.language=fr -J-Dfile.encoding=Cp1252 --initialize-at-build-time= -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime -H:+JNI -jar getting-started-1.0-SNAPSHOT-runner.jar -H:FallbackThreshold=0 -H:+ReportExceptionStackTraces -H:-AddAllCharsets -H:-IncludeAllTimeZones -H:EnableURLProtocols=http -H:-UseServiceLoaderFeature -H:+StackTrace getting-started-1.0-SNAPSHOT-runner
Error: Invalid Path entry getting-started-1.0-SNAPSHOT-runner.jar
Caused by: java.nio.file.NoSuchFileException: /project/getting-started-1.0-SNAPSHOT-runner.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.752 s
[INFO] Finished at: 2020-05-17T16:25:09+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.4.2.Final:native-image (default) on project getting-started: Failed to generate native image: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[ERROR]         [error]: Build step io.quarkus.deployment.pkg.steps.NativeImageBuildStep#build threw an exception: java.lang.RuntimeException: Failed to build native image
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:353)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]         at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]         at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]         at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR]         at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:931)
[ERROR]         at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
[ERROR]         at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
[ERROR]         at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
[ERROR]         at java.base/java.lang.Thread.run(Thread.java:834)
[ERROR]         at org.jboss.threads.JBossThread.run(JBossThread.java:479)
[ERROR] Caused by: java.lang.RuntimeException: Image generation failed. Exit code: 1
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.imageGenerationFailed(NativeImageBuildStep.java:369)
[ERROR]         at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:339)
[ERROR]         ... 12 more
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException


问:
Confused by a very simple if / else statement in perl
```<code>print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}
</code>```

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?

答:
OK, nevermind my first response. This is from the perldoc for unlink:

Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets $! (errno)

Proof that there is no such thing as a standard. Also proof that whomever wrote that code, unfortunately has a bug. Personally I would have expected 0 to mean success. If you look at the C syscall unlink, zero means success. Utter madness, I tell you.

Body:
print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?