问:
html/java Input with Slider
I do have slider that outputs a value as text. Now I need also to build an input Textfield that does change the slider value and the slider value change the input Textfield value. I did find couple solutions, but that does not work for me, because I have comparison boxes that work hand in hand, when I try those solutions everything crashes.

Here my code:

```<code>// Term Slider
function comparisons_term_slider($settings) {

    $term = str_replace('[term]',$settings['terminitial'],$settings['termoutput']);
    $term = str_replace('[period]',$settings['plural'],$term);

    $output = '<div class="comparisons-range comparisons-slider-term">
    <div class="comparisons_slider_output">';
    $output .= '<div class="output-pad"><span class="circle-down circle-control"></span><span class="output-number"><label for="loan-term">'.$settings['termlabel'].'</label> <output>'.$term.'</output><span class="circle-up circle-control"></span></div>';
    $output .= '</div>
    <input type="range" class="loan_term" name="loan-term" id="loan-term" min="'.$settings['termmin'].'" max="'.$settings['termmax'].'" value="'.$settings['terminitial'].'" step="'.$settings['termstep'].'" data-comparisons>
    </div>';

    return $output;
}
</code>```

and in javascript

```<code>// Select all relevant loan slider forms
    $(comparisons_loan_selector).each(function() {

        // Initialize sliders
        var sliders = $(this).find('[data-comparisons]'), x = $(this);

        sliders.change(comparisonsCalculate);
        sliders.comparisons({polyfill:false});
        $('#lc_show_more').click(function() {
            comparisonsShowMore.apply(this);
            //comparisonsCalculate;
        });
        $('#sortby').change(comparisonsCalculate);

        // Up and down buttons
        x.find('.circle-control').click(function() {
            var holder  = $(this).closest('.comparisons-range'),
                range   = holder.find('input'),
                newVal  = parseFloat(range.val()),
                step    = parseFloat(range.attr('step')),
                min     = parseFloat(range.attr('min')),
                max     = parseFloat(range.attr('max'));

            if ($(this).hasClass('circle-down')) { // reduce the slider value
                newVal = newVal - step;
                if (newVal > min) range.val(newVal);
                else range.val(min);
            } else { // raise the slider value
                newVal = newVal + step;
                if (newVal < max) range.val(newVal);
                else range.val(max);
            }

            range.change();
        });
</code>```
```<code>// Sliders
jQuery(document).ready(function($) {
    (function(factory) {
        'use strict';

        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof exports === 'object') {
            factory(require('jquery'));
        } else {
            factory(jQuery);
        }
    } (function($) {
        'use strict';

    function supportsRange() {
        var input = document.createElement('input');
        input.setAttribute('type', 'range');
        return input.type !== 'text';
    }

    var pluginName = 'comparisons',
        pluginInstances = [],
        inputrange = supportsRange(),
        defaults = {
            polyfill: true,
            rangeClass: 'comparisons',
            disabledClass: 'comparisons--disabled',
            fillClass: 'comparisons__fill',
            handleClass: 'comparisons__handle',
            startEvent: ['mousedown', 'touchstart', 'pointerdown'],
            moveEvent: ['mousemove', 'touchmove', 'pointermove'],
            endEvent: ['mouseup', 'touchend', 'pointerup']
        };

    function delay(fn, wait) {
        var args = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function(){ return fn.apply(null, args); }, wait);
    }

    function debounce(fn, debounceDuration) {
        debounceDuration = debounceDuration || 100;
        return function() {
            if (!fn.debouncing) {
                var args = Array.prototype.slice.apply(arguments);
                fn.lastReturnVal = fn.apply(window, args);
                fn.debouncing = true;
            }
            clearTimeout(fn.debounceTimeout);
            fn.debounceTimeout = setTimeout(function(){
                fn.debouncing = false;
            }, debounceDuration);
            return fn.lastReturnVal;
        };
    }

    function Plugin(element, options) {
        this.$window    = $(window);
        this.$document  = $(document);
        this.$element   = $(element);
        this.options    = $.extend( {}, defaults, options );
        this._defaults  = defaults;
        this._name    = pluginName;
        this.startEvent = this.options.startEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.moveEvent  = this.options.moveEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.endEvent   = this.options.endEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.polyfill   = this.options.polyfill;
        this.onInit  = this.options.onInit;
        this.onSlide    = this.options.onSlide;
        this.onSlideEnd = this.options.onSlideEnd;

        if (this.polyfill) {
            if (inputrange) { return false; }
        }

        this.identifier = 'js-' + pluginName + '-' +(+new Date())+'-'+(pluginInstances.length + 1);
        this.min        = parseFloat(this.$element[0].getAttribute('min') || 0);
        this.max        = parseFloat(this.$element[0].getAttribute('max') || 100);
        this.value    = parseFloat(this.$element[0].value || this.min + (this.max-this.min)/2);
        this.step      = parseFloat(this.$element[0].getAttribute('step') || 1);
        this.$fill    = $('<div class="' + this.options.fillClass + '" />');
        this.$handle    = $('<div class="' + this.options.handleClass + '" />');
        this.$range  = $('<div class="' + this.options.rangeClass + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);

        this.$element.css({
            'position': 'absolute',
            'width': '1px',
            'height': '1px',
            'overflow': 'hidden',
            'opacity': '0'
        });

        this.handleDown = $.proxy(this.handleDown, this);
        this.handleMove = $.proxy(this.handleMove, this);
        this.handleEnd  = $.proxy(this.handleEnd, this);

        this.init();

        var _this = this;

        this.$window.on('resize' + '.' + pluginName, debounce(function() {
            delay(function() { _this.update(); }, 300);
        }, 20));

        this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);

        this.$element.on('change' + '.' + pluginName, function(e, data) {
            if (data && data.origin === pluginName) {
                return;
            }

            var value = e.target.value,
                pos = _this.getPositionFromValue(value);
            _this.setPosition(pos);
        });
    }

    Plugin.prototype.init = function() {
        if (this.onInit && typeof this.onInit === 'function') {
            this.onInit();
        }
        this.update();
    };

    Plugin.prototype.attributes = function() {
        var e = this.$element;

        this.min = parseFloat(e.attr('min'));
        this.max = parseFloat(e.attr('max'));
        this.value = parseFloat(e.attr('value'));
        if (this.value > this.max) this.setValue(this.max);
        if (this.value < this.min) this.setValue(this.min);
        if (this.value > this.min && this.value > this.min) this.setValue(this.value);

        this.update();
    };

    Plugin.prototype.update = function() {
        this.handleWidth    = this.$handle[0].offsetWidth;
        this.rangeWidth  = this.$range[0].offsetWidth;
        this.maxHandleX  = this.rangeWidth - this.handleWidth;
        this.grabX        = this.handleWidth / 2;
        this.position      = this.getPositionFromValue(this.value);

        if (this.$element[0].disabled) {
            this.$range.addClass(this.options.disabledClass);
        } else {
            this.$range.removeClass(this.options.disabledClass);
        }

        this.setPosition(this.position);
    };

    Plugin.prototype.handleDown = function(e) {
        e.preventDefault();
        this.$document.on(this.moveEvent, this.handleMove);
        this.$document.on(this.endEvent, this.handleEnd);

        if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
            return;
        }

        var posX = this.getRelativePosition(this.$range[0], e),
            handleX = this.getPositionFromNode(this.$handle[0]) - this.getPositionFromNode(this.$range[0]);

        this.setPosition(posX - this.grabX);

        if (posX >= handleX && posX < handleX + this.handleWidth) {
            this.grabX = posX - handleX;
        }
    };

    Plugin.prototype.handleMove = function(e) {
        e.preventDefault();
        var posX = this.getRelativePosition(this.$range[0], e);

        this.setPosition(posX - this.grabX);
    };

    Plugin.prototype.handleEnd = function(e) {
        e.preventDefault();
        this.$document.off(this.moveEvent, this.handleMove);
        this.$document.off(this.endEvent, this.handleEnd);

        if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
            this.onSlideEnd(this.position, this.value);
        }
    };

    Plugin.prototype.cap = function(pos, min, max) {
        if (pos < min) { return min; }
        if (pos > max) { return max; }
        return pos;
    };

    Plugin.prototype.setPosition = function(pos) {
        var value, left;

        value = (this.getValueFromPosition(this.cap(pos, 0, this.maxHandleX)) / this.step) * this.step;
        left = this.getPositionFromValue(value);

        this.$fill[0].style.width = (left + this.grabX)  + 'px';
        this.$handle[0].style.left = left + 'px';

        this.setValue(value);

        this.position = left;
        this.value = value;

    };

    Plugin.prototype.getPositionFromNode = function(node) {
        var i = 0;
        while (node !== null) {
            i += node.offsetLeft;
            node = node.offsetParent;
        }
        return i;
    };

    Plugin.prototype.getRelativePosition = function(node, e) {
        return (e.pageX || e.originalEvent.clientX || e.originalEvent.touches[0].clientX || e.currentPoint.x) - this.getPositionFromNode(node);
    };

    Plugin.prototype.getPositionFromValue = function(value) {
        var percentage, pos;
        percentage = (value - this.min)/(this.max - this.min);
        pos = percentage * this.maxHandleX;

        return pos;
    };

    Plugin.prototype.getValueFromPosition = function(pos) {
        var percentage, value;
        percentage = ((pos) / (this.maxHandleX || 1));
        value = this.step * Math.round((((percentage) * (this.max - this.min)) + this.min) / this.step);
        return Number((value).toFixed(2));
    };

    Plugin.prototype.setValue = function(value) {
        if (value !== this.value) {
            this.$element.val(value).trigger('change', {origin: pluginName});
        }
    };

    Plugin.prototype.destroy = function() {
        this.$document.off(this.startEvent, '#' + this.identifier, this.handleDown);
        this.$element
            .off('.' + pluginName)
            .removeAttr('style')
            .removeData('plugin_' + pluginName);

        if (this.$range && this.$range.length) {
            this.$range[0].parentNode.removeChild(this.$range[0]);
        }

        pluginInstances.splice(pluginInstances.indexOf(this.$element[0]),1);
        if (!pluginInstances.length) {
            this.$window.off('.' + pluginName);
        }
    };

        $.fn[pluginName] = function(options) {
            return this.each(function() {
                var $this = $(this),
                data  = $this.data('plugin_' + pluginName);

                if (!data) {
                    $this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
                    pluginInstances.push(this);
                }

                if (typeof options === 'string') {
                    data[options]();
            }
            });
        };

    }));
});
</code>```

any solutions possible? Do you need more code?

Already did try this but it doesnt work aswell..

```<code><div>
    <input id="rangeInput" type="range" min="0" max="200" oninput="amount.value=rangeInput.value" />
    <input id="amount" type="number" value="100" min="0" max="200" oninput="rangeInput.value=amount.value" />
  </div>
</code>```

Title: html/java Input with Slider

Body:
I do have slider that outputs a value as text. Now I need also to build an input Textfield that does change the slider value and the slider value change the input Textfield value. I did find couple solutions, but that does not work for me, because I have comparison boxes that work hand in hand, when I try those solutions everything crashes.

Here my code:

// Term Slider
function comparisons_term_slider($settings) {

    $term = str_replace('[term]',$settings['terminitial'],$settings['termoutput']);
    $term = str_replace('[period]',$settings['plural'],$term);

    $output = '

';
    $output .= '
'.$settings['termlabel'].' <output>'.$term.'</output>
';
    $output .= '

    <input type="range" class="loan_term" name="loan-term" id="loan-term" min="'.$settings['termmin'].'" max="'.$settings['termmax'].'" value="'.$settings['terminitial'].'" step="'.$settings['termstep'].'" data-comparisons>

';

    return $output;
}

and in javascript

// Select all relevant loan slider forms
    $(comparisons_loan_selector).each(function() {

        // Initialize sliders
        var sliders = $(this).find('[data-comparisons]'), x = $(this);

        sliders.change(comparisonsCalculate);
        sliders.comparisons({polyfill:false});
        $('#lc_show_more').click(function() {
            comparisonsShowMore.apply(this);
            //comparisonsCalculate;
        });
        $('#sortby').change(comparisonsCalculate);

        // Up and down buttons
        x.find('.circle-control').click(function() {
            var holder  = $(this).closest('.comparisons-range'),
                range   = holder.find('input'),
                newVal  = parseFloat(range.val()),
                step    = parseFloat(range.attr('step')),
                min     = parseFloat(range.attr('min')),
                max     = parseFloat(range.attr('max'));

            if ($(this).hasClass('circle-down')) { // reduce the slider value
                newVal = newVal - step;
                if (newVal > min) range.val(newVal);
                else range.val(min);
            } else { // raise the slider value
                newVal = newVal + step;
                if (newVal < max) range.val(newVal);
                else range.val(max);
            }

            range.change();
        });

// Sliders
jQuery(document).ready(function($) {
    (function(factory) {
        'use strict';

        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof exports === 'object') {
            factory(require('jquery'));
        } else {
            factory(jQuery);
        }
    } (function($) {
        'use strict';

    function supportsRange() {
        var input = document.createElement('input');
        input.setAttribute('type', 'range');
        return input.type !== 'text';
    }

    var pluginName = 'comparisons',
        pluginInstances = [],
        inputrange = supportsRange(),
        defaults = {
            polyfill: true,
            rangeClass: 'comparisons',
            disabledClass: 'comparisons--disabled',
            fillClass: 'comparisons__fill',
            handleClass: 'comparisons__handle',
            startEvent: ['mousedown', 'touchstart', 'pointerdown'],
            moveEvent: ['mousemove', 'touchmove', 'pointermove'],
            endEvent: ['mouseup', 'touchend', 'pointerup']
        };

    function delay(fn, wait) {
        var args = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function(){ return fn.apply(null, args); }, wait);
    }

    function debounce(fn, debounceDuration) {
        debounceDuration = debounceDuration || 100;
        return function() {
            if (!fn.debouncing) {
                var args = Array.prototype.slice.apply(arguments);
                fn.lastReturnVal = fn.apply(window, args);
                fn.debouncing = true;
            }
            clearTimeout(fn.debounceTimeout);
            fn.debounceTimeout = setTimeout(function(){
                fn.debouncing = false;
            }, debounceDuration);
            return fn.lastReturnVal;
        };
    }

    function Plugin(element, options) {
        this.$window    = $(window);
        this.$document  = $(document);
        this.$element   = $(element);
        this.options    = $.extend( {}, defaults, options );
        this._defaults  = defaults;
        this._name    = pluginName;
        this.startEvent = this.options.startEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.moveEvent  = this.options.moveEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.endEvent   = this.options.endEvent.join('.' + pluginName + ' ') + '.' + pluginName;
        this.polyfill   = this.options.polyfill;
        this.onInit  = this.options.onInit;
        this.onSlide    = this.options.onSlide;
        this.onSlideEnd = this.options.onSlideEnd;

        if (this.polyfill) {
            if (inputrange) { return false; }
        }

        this.identifier = 'js-' + pluginName + '-' +(+new Date())+'-'+(pluginInstances.length + 1);
        this.min        = parseFloat(this.$element[0].getAttribute('min') || 0);
        this.max        = parseFloat(this.$element[0].getAttribute('max') || 100);
        this.value    = parseFloat(this.$element[0].value || this.min + (this.max-this.min)/2);
        this.step      = parseFloat(this.$element[0].getAttribute('step') || 1);
        this.$fill    = $('
');
        this.$handle    = $('
');
        this.$range  = $('
').insertAfter(this.$element).prepend(this.$fill, this.$handle);

        this.$element.css({
            'position': 'absolute',
            'width': '1px',
            'height': '1px',
            'overflow': 'hidden',
            'opacity': '0'
        });

        this.handleDown = $.proxy(this.handleDown, this);
        this.handleMove = $.proxy(this.handleMove, this);
        this.handleEnd  = $.proxy(this.handleEnd, this);

        this.init();

        var _this = this;

        this.$window.on('resize' + '.' + pluginName, debounce(function() {
            delay(function() { _this.update(); }, 300);
        }, 20));

        this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);

        this.$element.on('change' + '.' + pluginName, function(e, data) {
            if (data && data.origin === pluginName) {
                return;
            }

            var value = e.target.value,
                pos = _this.getPositionFromValue(value);
            _this.setPosition(pos);
        });
    }

    Plugin.prototype.init = function() {
        if (this.onInit && typeof this.onInit === 'function') {
            this.onInit();
        }
        this.update();
    };

    Plugin.prototype.attributes = function() {
        var e = this.$element;

        this.min = parseFloat(e.attr('min'));
        this.max = parseFloat(e.attr('max'));
        this.value = parseFloat(e.attr('value'));
        if (this.value > this.max) this.setValue(this.max);
        if (this.value < this.min) this.setValue(this.min);
        if (this.value > this.min && this.value > this.min) this.setValue(this.value);

        this.update();
    };

    Plugin.prototype.update = function() {
        this.handleWidth    = this.$handle[0].offsetWidth;
        this.rangeWidth  = this.$range[0].offsetWidth;
        this.maxHandleX  = this.rangeWidth - this.handleWidth;
        this.grabX        = this.handleWidth / 2;
        this.position      = this.getPositionFromValue(this.value);

        if (this.$element[0].disabled) {
            this.$range.addClass(this.options.disabledClass);
        } else {
            this.$range.removeClass(this.options.disabledClass);
        }

        this.setPosition(this.position);
    };

    Plugin.prototype.handleDown = function(e) {
        e.preventDefault();
        this.$document.on(this.moveEvent, this.handleMove);
        this.$document.on(this.endEvent, this.handleEnd);

        if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
            return;
        }

        var posX = this.getRelativePosition(this.$range[0], e),
            handleX = this.getPositionFromNode(this.$handle[0]) - this.getPositionFromNode(this.$range[0]);

        this.setPosition(posX - this.grabX);

        if (posX >= handleX && posX < handleX + this.handleWidth) {
            this.grabX = posX - handleX;
        }
    };

    Plugin.prototype.handleMove = function(e) {
        e.preventDefault();
        var posX = this.getRelativePosition(this.$range[0], e);

        this.setPosition(posX - this.grabX);
    };

    Plugin.prototype.handleEnd = function(e) {
        e.preventDefault();
        this.$document.off(this.moveEvent, this.handleMove);
        this.$document.off(this.endEvent, this.handleEnd);

        if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
            this.onSlideEnd(this.position, this.value);
        }
    };

    Plugin.prototype.cap = function(pos, min, max) {
        if (pos < min) { return min; }
        if (pos > max) { return max; }
        return pos;
    };

    Plugin.prototype.setPosition = function(pos) {
        var value, left;

        value = (this.getValueFromPosition(this.cap(pos, 0, this.maxHandleX)) / this.step) * this.step;
        left = this.getPositionFromValue(value);

        this.$fill[0].style.width = (left + this.grabX)  + 'px';
        this.$handle[0].style.left = left + 'px';

        this.setValue(value);

        this.position = left;
        this.value = value;

    };

    Plugin.prototype.getPositionFromNode = function(node) {
        var i = 0;
        while (node !== null) {
            i += node.offsetLeft;
            node = node.offsetParent;
        }
        return i;
    };

    Plugin.prototype.getRelativePosition = function(node, e) {
        return (e.pageX || e.originalEvent.clientX || e.originalEvent.touches[0].clientX || e.currentPoint.x) - this.getPositionFromNode(node);
    };

    Plugin.prototype.getPositionFromValue = function(value) {
        var percentage, pos;
        percentage = (value - this.min)/(this.max - this.min);
        pos = percentage * this.maxHandleX;

        return pos;
    };

    Plugin.prototype.getValueFromPosition = function(pos) {
        var percentage, value;
        percentage = ((pos) / (this.maxHandleX || 1));
        value = this.step * Math.round((((percentage) * (this.max - this.min)) + this.min) / this.step);
        return Number((value).toFixed(2));
    };

    Plugin.prototype.setValue = function(value) {
        if (value !== this.value) {
            this.$element.val(value).trigger('change', {origin: pluginName});
        }
    };

    Plugin.prototype.destroy = function() {
        this.$document.off(this.startEvent, '#' + this.identifier, this.handleDown);
        this.$element
            .off('.' + pluginName)
            .removeAttr('style')
            .removeData('plugin_' + pluginName);

        if (this.$range && this.$range.length) {
            this.$range[0].parentNode.removeChild(this.$range[0]);
        }

        pluginInstances.splice(pluginInstances.indexOf(this.$element[0]),1);
        if (!pluginInstances.length) {
            this.$window.off('.' + pluginName);
        }
    };

        $.fn[pluginName] = function(options) {
            return this.each(function() {
                var $this = $(this),
                data  = $this.data('plugin_' + pluginName);

                if (!data) {
                    $this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
                    pluginInstances.push(this);
                }

                if (typeof options === 'string') {
                    data[options]();
            }
            });
        };

    }));
});

any solutions possible? Do you need more code?

Already did try this but it doesnt work aswell..

    <input id="rangeInput" type="range" min="0" max="200" oninput="amount.value=rangeInput.value" />
    <input id="amount" type="number" value="100" min="0" max="200" oninput="rangeInput.value=amount.value" />


来源: stackexchange

问:
WebGL with offscreen canvas won't render my vertices
I'm trying to do some behind the scenes rendering work with WebGL and then copy the canvas data to an image.

I'm able to accomplish this successfully with a physical canvas element on the page, however, once I try to replace my

const canvas = document.getElementById("glcanvas") with either

const cavnas = document.createElement("canvas") or

const canvas = new OffscreenCanvas(640, 480)

My render doesn't seem to work anymore.

Interestingly I still see my WebGL clear color so I know it's rendering something.  If I go back to the getElemeentById method with a physical canvas in the DOM, everything works fine, any ideas?

code (I pretty much just followed the Mozilla tutorial for WebGL, some code is omitted because it is not important):

function main() {
    // Initialize the GL context
    const canvas = new OffscreenCanvas(640, 480)
    const gl = canvas.getContext("webgl2")

    // Only continue if WebGL is available and working
    if (gl === null) {
        alert("Unable to initialize WebGL. Your browser or machine may not support it.")
        return
    }

    // Set clear color to black, fully opaque
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    // Clear the color buffer with specified clear color
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Initialize a shader program; this is where all the lighting
    // for the vertices and so forth is established.
    const shaderProgram = initShaderProgram(gl, vsSource, fsSource);

    // Collect all the info needed to use the shader program.
    // Look up which attributes our shader program is using
    // for aVertexPosition, aVertexColor and also
    // look up uniform locations.
    const programInfo = {
        program: shaderProgram,
        attribLocations: {
            vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
            vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
        },
        uniformLocations: {
            projectionMatrix: gl.getUniformLocation(
                shaderProgram,
                "uProjectionMatrix"
            ),
            modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
        },
    };

    const objects = [
        initCuboid(
            gl,
            {x: 0, y: 0, z: 0},
            {x: 1, y: 1, z: 1},
            {pitch: 0, yaw: 0, roll: 0}
        ),
        initCuboid(
            gl,
            {x: 0, y: 2, z: 0},
            {x: .5, y: .5, z: .5},
            {pitch: 0, yaw: 0, roll: 0}
        ),

    ]

    function render() {
        drawScene(gl, programInfo, objects);
        canvas.convertToBlob().then((res) => {
            document.getElementById("glimg").src = URL.createObjectURL(res)
        })
        requestAnimationFrame(render)
    }

    requestAnimationFrame(render)
}
```

ContentLicense: CC BY-SA 4.0


问:
Why does the state return to the InitialState when the page is refreshed?
I have a checkbox for notifications and if we checked it, I want it to stay that way when the page is refreshed. In my userProfileSlice.js file, I send this request to the backend and update the comms_optin_email state with the response. I take this value from the state.userProfile.updateNotificationSettings state in the initialState of the Checkbox and put it. But when I check and refresh the page, the state returns to false. How can I solve this?

NotificationsSettingsPage

```<code>import { useTranslation } from 'react-i18next';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateNotificationSettingsStarted } from '../../../store/userProfileSlice';
import CommunicationPermisson from '../../AuthPages/CommunicationPermissionModal/CommunicationPermisson';
import NiceModal from '@ebay/nice-modal-react';

export default function NotificationSettingsPage() {
    const { t } = useTranslation();
    const dispatch = useDispatch();
    const { auth } = useSelector(state => state.auth);
    const { comms_optin_email } = useSelector(
        state => state.userProfile.updateNotificationSettings,
    );
    const [isOffersChecked, setIsOffersChecked] = useState(comms_optin_email);
    const nanoid = auth?.user?.nanoid;

    const handleOffersClick = e => {
        e.preventDefault();
        NiceModal.show(CommunicationPermisson);
    };

    const handleFormSubmit = e => {
        e.preventDefault();
        dispatch(
            updateNotificationSettingsStarted({
                nanoid: nanoid,
                isOffersChecked: isOffersChecked,
            }),
        );
    };

    return (
        <section aria-labelledby="payment-details-heading">
            <form onSubmit={handleFormSubmit}>
                <div className="shadow sm:rounded-md sm:overflow-hidden">
                    <div className="bg-white py-6 px-4 sm:p-6">
                        <div>
                            <h2
                                id="payment-details-heading"
                                className="text-lg leading-6 font-medium text-gray-900"
                            >
                                {t('notificationSettings.heading')}
                            </h2>
                            <p className="mt-1 text-sm text-gray-500">
                                {t('notificationSettings.description')}
                            </p>
                        </div>

                        <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-baseline">
                            <div className="mt-6 sm:col-span-2">
                                <div className="max-w-xl space-y-4">
                                    <div>
                                        <div className="relative flex items-start">
                                            <div className="flex items-center h-5">
                                                <input
                                                    id="offers"
                                                    name="offers"
                                                    type="checkbox"
                                                    className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                                                    checked={isOffersChecked}
                                                    onChange={() => setIsOffersChecked(!isOffersChecked)}
                                                />
                                            </div>
                                            <div className="ml-3 text-sm">
                                                <label
                                                    htmlFor="offers"
                                                    className="font-medium text-gray-700"
                                                >
                                                    {t('Offers')}
                                                </label>
                                                <p className="text-gray-500">
                                                    {t('notificationSettings.offerNotificationTextStart')}
                                                    <button
                                                        className="text-indigo-600 underline"
                                                        type="button"
                                                        onClick={handleOffersClick}
                                                    >
                                                        {t(
                                                            'notificationSettings.offerNotificationPopButton',
                                                        )}
                                                    </button>
                                                    {t('notificationSettings.offerNotificationTextEnd')}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="px-4 py-3 bg-gray-50 text-right sm:px-6">
                        <button
                            type="submit"
                            className="bg-gray-800 border border-transparent rounded-md shadow-sm py-2 px-4 inline-flex justify-center text-sm font-medium text-white hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
                        >
                            {t('Save')}
                        </button>
                    </div>
                </div>
            </form>
        </section>
    );
}
</code>```

userProfileSlice

```<code>import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    updateNotificationSettings: {
        error: false,
        success: false,
        fetch: false,
        message: '',
        comms_optin_email: false,
    },
};

// eslint-disable-next-line import/no-unused-modules
export const userProfileSlice = createSlice({
    name: 'userProfile',
    initialState,
    reducers: {
        updateNotificationSettingsStarted: state => {
            state.updateNotificationSettings = {
                error: false,
                success: false,
                fetch: true,
                message: '',
                comms_optin_email: false,
            };
        },
        updateNotificationSettingsFinished: (state, action) => {
            state.updateNotificationSettings = {
                error: false,
                success: true,
                fetch: false,
                message: '',
                comms_optin_email: action.payload,
            };
        },
        updateNotificationSettingsFailed: (state, action) => {
            state.updateNotificationSettings = {
                error: true,
                success: false,
                fetch: false,
                message: action.payload,
            };
        },
    },
});

// eslint-disable-next-line import/no-unused-modules
export const {
    updateNotificationSettingsStarted,
    updateNotificationSettingsFinished,
    updateNotificationSettingsFailed,
} = userProfileSlice.actions;

export default userProfileSlice.reducer;
</code>```

Body:
I have a checkbox for notifications and if we checked it, I want it to stay that way when the page is refreshed. In my userProfileSlice.js file, I send this request to the backend and update the comms_optin_email state with the response. I take this value from the state.userProfile.updateNotificationSettings state in the initialState of the Checkbox and put it. But when I check and refresh the page, the state returns to false. How can I solve this?

NotificationsSettingsPage

import { useTranslation } from 'react-i18next';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateNotificationSettingsStarted } from '../../../store/userProfileSlice';
import CommunicationPermisson from '../../AuthPages/CommunicationPermissionModal/CommunicationPermisson';
import NiceModal from '@ebay/nice-modal-react';

export default function NotificationSettingsPage() {
    const { t } = useTranslation();
    const dispatch = useDispatch();
    const { auth } = useSelector(state => state.auth);
    const { comms_optin_email } = useSelector(
        state => state.userProfile.updateNotificationSettings,
    );
    const [isOffersChecked, setIsOffersChecked] = useState(comms_optin_email);
    const nanoid = auth?.user?.nanoid;

    const handleOffersClick = e => {
        e.preventDefault();
        NiceModal.show(CommunicationPermisson);
    };

    const handleFormSubmit = e => {
        e.preventDefault();
        dispatch(
            updateNotificationSettingsStarted({
                nanoid: nanoid,
                isOffersChecked: isOffersChecked,
            }),
        );
    };

    return (

            <form onSubmit={handleFormSubmit}>

                                {t('notificationSettings.heading')}

                                {t('notificationSettings.description')}

                                                <input
                                                    id="offers"
                                                    name="offers"
                                                    type="checkbox"
                                                    className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                                                    checked={isOffersChecked}
                                                    onChange={() => setIsOffersChecked(!isOffersChecked)}
                                                />

                                                    {t('Offers')}

                                                    {t('notificationSettings.offerNotificationTextStart')}
                                                    <button
                                                        className="text-indigo-600 underline"
                                                        type="button"
                                                        onClick={handleOffersClick}
                                                    >
                                                        {t(
                                                            'notificationSettings.offerNotificationPopButton',
                                                        )}
                                                    </button>
                                                    {t('notificationSettings.offerNotificationTextEnd')}

                        <button
                            type="submit"
                            className="bg-gray-800 border border-transparent rounded-md shadow-sm py-2 px-4 inline-flex justify-center text-sm font-medium text-white hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
                        >
                            {t('Save')}
                        </button>

            </form>

    );
}

userProfileSlice

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    updateNotificationSettings: {
        error: false,
        success: false,
        fetch: false,
        message: '',
        comms_optin_email: false,
    },
};

// eslint-disable-next-line import/no-unused-modules
export const userProfileSlice = createSlice({
    name: 'userProfile',
    initialState,
    reducers: {
        updateNotificationSettingsStarted: state => {
            state.updateNotificationSettings = {
                error: false,
                success: false,
                fetch: true,
                message: '',
                comms_optin_email: false,
            };
        },
        updateNotificationSettingsFinished: (state, action) => {
            state.updateNotificationSettings = {
                error: false,
                success: true,
                fetch: false,
                message: '',
                comms_optin_email: action.payload,
            };
        },
        updateNotificationSettingsFailed: (state, action) => {
            state.updateNotificationSettings = {
                error: true,
                success: false,
                fetch: false,
                message: action.payload,
            };
        },
    },
});

// eslint-disable-next-line import/no-unused-modules
export const {
    updateNotificationSettingsStarted,
    updateNotificationSettingsFinished,
    updateNotificationSettingsFailed,
} = userProfileSlice.actions;

export default userProfileSlice.reducer;


问:
Generating list of tuples using list comprehension
I have a function which takes as an argument list of tuples representing column name and it's type. Based on the list passed, I need to generate another list of tuples, this time containing data from spreadsheet. Each row should have information from all the columns covered in columns tuple.

How can I generate list of tuples with data using list comprehension?

I came up with this code:

```<code># Validate the index range if provided
if index_range is not None:
    if not isinstance(index_range, tuple):
        raise ValueError(f"index_range provided is of type {type(index_range)} not tuple")
    elif len(index_range) != 2:
        raise ValueError(f"index_range provided has length {len(index_range)} but should have length 2")
    elif type(index_range[0]) is not int:
        raise ValueError(f"Start index in index_range is type {type(index_range[0])} but should be int")
    elif type(index_range[1]) is not int:
        raise ValueError(f"End index in index_range is type {type(index_range[0])} but should be int")
    elif index_range[1] < index_range[0]:
        raise ValueError(f"End index in index_range is {index_range[1]} and start index is {index_range[0]}. "
                         f"End index cannot be lower than start index")

# Read the 'data' workbook from this file
excel_file = pd.ExcelFile(path)
df = pd.read_excel(excel_file, 'data')

# Tuples list instance
list_tuples = list()

# Determine the indexes
if index_range is not None:
    start_index = index_range[0]
    end_index = index_range[1] + 1
else:
    start_index = 0
    end_index = df[df.columns[0]].count()

# Iterate through the results and insert data tuples into the list
for i in range(start_index, end_index):
    try:
        list_tuples.append(tuple(
            [convert_to(df.loc[i, el[0]], el[1]) for el in clmns]
        ))
    except Exception as ex:
        log.log_error(f"[{df.loc[i, clmns[0]]}] {str(ex)}", True)
        if is_test:
            list_tuples.append((
                df.loc[i, clmns[0]], None, None, None, None, None, None, None, None, None, None, None, None, None
            ))

# Check if there were results and finish
if len(list_tuples) > 0:
    to_call(list_tuples, is_test)
else:
    log.log_info('There are no results from Excel')
</code>```

el[0] is column name and el[1] is the desired type. It works OK for the first row, but even when start index is 0 and end index is 10, the main for loop generates only one tuple and then breaks...

convert_to:

```<code>if pd.isna(obj):
        return None
    elif as_type is None or obj is None:
        return obj
    else:
        return as_type(obj)
</code>```

Body:
I have a function which takes as an argument list of tuples representing column name and it's type. Based on the list passed, I need to generate another list of tuples, this time containing data from spreadsheet. Each row should have information from all the columns covered in columns tuple.

How can I generate list of tuples with data using list comprehension?

I came up with this code:

# Validate the index range if provided
if index_range is not None:
    if not isinstance(index_range, tuple):
        raise ValueError(f"index_range provided is of type {type(index_range)} not tuple")
    elif len(index_range) != 2:
        raise ValueError(f"index_range provided has length {len(index_range)} but should have length 2")
    elif type(index_range[0]) is not int:
        raise ValueError(f"Start index in index_range is type {type(index_range[0])} but should be int")
    elif type(index_range[1]) is not int:
        raise ValueError(f"End index in index_range is type {type(index_range[0])} but should be int")
    elif index_range[1] < index_range[0]:
        raise ValueError(f"End index in index_range is {index_range[1]} and start index is {index_range[0]}. "
                         f"End index cannot be lower than start index")

# Read the 'data' workbook from this file
excel_file = pd.ExcelFile(path)
df = pd.read_excel(excel_file, 'data')

# Tuples list instance
list_tuples = list()

# Determine the indexes
if index_range is not None:
    start_index = index_range[0]
    end_index = index_range[1] + 1
else:
    start_index = 0
    end_index = df[df.columns[0]].count()

# Iterate through the results and insert data tuples into the list
for i in range(start_index, end_index):
    try:
        list_tuples.append(tuple(
            [convert_to(df.loc[i, el[0]], el[1]) for el in clmns]
        ))
    except Exception as ex:
        log.log_error(f"[{df.loc[i, clmns[0]]}] {str(ex)}", True)
        if is_test:
            list_tuples.append((
                df.loc[i, clmns[0]], None, None, None, None, None, None, None, None, None, None, None, None, None
            ))

# Check if there were results and finish
if len(list_tuples) > 0:
    to_call(list_tuples, is_test)
else:
    log.log_info('There are no results from Excel')

el[0] is column name and el[1] is the desired type. It works OK for the first row, but even when start index is 0 and end index is 10, the main for loop generates only one tuple and then breaks...

convert_to:

if pd.isna(obj):
        return None
    elif as_type is None or obj is None:
        return obj
    else:
        return as_type(obj)


问:
How to remove marginal points in Gaussian power curve?
I'm trying to generate a power a curve which is Gaussian but in the plot generated I need to remove the marginal values. Could someone please guide me how? Thanks

Following is the code I've written for the power curve:

```<code>function [xgrid,ygrid,Z] = biVariateContourPlotsGMMCopula(givenData,gmmObject,~,numMeshPoints,x_dim,y_dim)

d = 2;
if nargin < 5
    x_dim = 1;
    y_dim = 2;
end

if x_dim == y_dim
    hist(givenData(:,x_dim),10);
    return;
end

numMeshPoints = min(numMeshPoints,256);

givenData = givenData(:,[x_dim y_dim]);
alpha = gmmObject.alpha;
mu = gmmObject.mu(:,[x_dim y_dim]);
sigma = gmmObject.sigma([x_dim y_dim],[x_dim y_dim],:) + 0.005*repmat(eye(d),[1 1 numel(alpha)]);

gmmObject = gmdistribution(mu,sigma,alpha);

bin_num = 256;
for j = 1:2
   l_limit = min(gmmObject.mu(:,j))-3*(max(gmmObject.Sigma(j,j,:))^0.5);
   u_limit = max(gmmObject.mu(:,j))+3*(max(gmmObject.Sigma(j,j,:))^0.5);
   xmesh_inverse_space{j} = (l_limit:(u_limit-l_limit)/(bin_num-1):u_limit);
end

</code>```

%if isempty(xmesh)||isempty(pdensity)||isempty(cdensity)
% Following for loop does the non-parameteric estimation of marginal
% densities if not provided

```<code>
    for i = 1:d
        currentVar = givenData(:,i);
        [bandwidth,pdensity{i},xmesh{i}]=kde(currentVar,numMeshPoints);
        pdensity{i}(find(pdensity{i}<0)) = 0;

        cdensity{i} = cumsum(pdensity{i});
        cdensity{i} = (cdensity{i}-min(cdensity{i}))/(max(cdensity{i})-min(cdensity{i}));
    end

[xgrid,ygrid] = meshgrid(xmesh{1}(2:end-1),xmesh{2}(2:end-1));

for k = 1:d
    marginalLogLikelihood_grid{k} = log(pdensity{k}(2:end-1)+eps);
    marginalCDFValues_grid{k} = cdensity{k}(2:end-1);
end
[marg1,marg2] = meshgrid(marginalLogLikelihood_grid{1},marginalLogLikelihood_grid{2});

[xg,yg] = meshgrid(marginalCDFValues_grid{1},marginalCDFValues_grid{2});
inputMatrix = [reshape(xg,numel(xg),1) reshape(yg,numel(yg),1)];
clear xg yg;

copulaLogLikelihoodVals = gmmCopulaPDF(inputMatrix,gmmObject,xmesh_inverse_space);
Z = reshape(copulaLogLikelihoodVals,size(marg1,1),size(marg1,2));
Z = Z+marg1+marg2;

Z = exp(Z);

plot(givenData(:,1),givenData(:,2),'k.','MarkerSize',3);hold
contour(xgrid,ygrid,Z,40);

%title_string = ['GMCM fit (Log-Likelihood = ',num2str(logLikelihoodVal), ')'];
%title(title_string,'FontSize',12,'FontWeight','demi');

axis tight;

</code>```

Body:
I'm trying to generate a power a curve which is Gaussian but in the plot generated I need to remove the marginal values. Could someone please guide me how? Thanks

Following is the code I've written for the power curve:

function [xgrid,ygrid,Z] = biVariateContourPlotsGMMCopula(givenData,gmmObject,~,numMeshPoints,x_dim,y_dim)

d = 2;
if nargin < 5
    x_dim = 1;
    y_dim = 2;
end

if x_dim == y_dim
    hist(givenData(:,x_dim),10);
    return;
end

numMeshPoints = min(numMeshPoints,256);

givenData = givenData(:,[x_dim y_dim]);
alpha = gmmObject.alpha;
mu = gmmObject.mu(:,[x_dim y_dim]);
sigma = gmmObject.sigma([x_dim y_dim],[x_dim y_dim],:) + 0.005*repmat(eye(d),[1 1 numel(alpha)]);

gmmObject = gmdistribution(mu,sigma,alpha);

bin_num = 256;
for j = 1:2
   l_limit = min(gmmObject.mu(:,j))-3*(max(gmmObject.Sigma(j,j,:))^0.5);
   u_limit = max(gmmObject.mu(:,j))+3*(max(gmmObject.Sigma(j,j,:))^0.5);
   xmesh_inverse_space{j} = (l_limit:(u_limit-l_limit)/(bin_num-1):u_limit);
end

%if isempty(xmesh)||isempty(pdensity)||isempty(cdensity)
% Following for loop does the non-parameteric estimation of marginal
% densities if not provided

    for i = 1:d
        currentVar = givenData(:,i);
        [bandwidth,pdensity{i},xmesh{i}]=kde(currentVar,numMeshPoints);
        pdensity{i}(find(pdensity{i}<0)) = 0;

        cdensity{i} = cumsum(pdensity{i});
        cdensity{i} = (cdensity{i}-min(cdensity{i}))/(max(cdensity{i})-min(cdensity{i}));
    end

[xgrid,ygrid] = meshgrid(xmesh{1}(2:end-1),xmesh{2}(2:end-1));

for k = 1:d
    marginalLogLikelihood_grid{k} = log(pdensity{k}(2:end-1)+eps);
    marginalCDFValues_grid{k} = cdensity{k}(2:end-1);
end
[marg1,marg2] = meshgrid(marginalLogLikelihood_grid{1},marginalLogLikelihood_grid{2});

[xg,yg] = meshgrid(marginalCDFValues_grid{1},marginalCDFValues_grid{2});
inputMatrix = [reshape(xg,numel(xg),1) reshape(yg,numel(yg),1)];
clear xg yg;

copulaLogLikelihoodVals = gmmCopulaPDF(inputMatrix,gmmObject,xmesh_inverse_space);
Z = reshape(copulaLogLikelihoodVals,size(marg1,1),size(marg1,2));
Z = Z+marg1+marg2;

Z = exp(Z);

plot(givenData(:,1),givenData(:,2),'k.','MarkerSize',3);hold
contour(xgrid,ygrid,Z,40);

%title_string = ['GMCM fit (Log-Likelihood = ',num2str(logLikelihoodVal), ')'];
%title(title_string,'FontSize',12,'FontWeight','demi');

axis tight;


问:
set "message of absence" in strato webmail via curl
I would like to set my "message of absence" in strato webmail programmatically.
For that I open the developer tools (firefox) and I login via strato webmail and set the "message of absence". I get the curl request from the developer console and I rebuild this as a php code:

```<code>$myJson = '
{
    "actioncmds": [
        {
            "addresses": [
                "mail@domain.de"
            ],
            "days": "7",
            "id": "vacation",
            "subject": "My Subject",
            "text": "My Message"
        }
    ],
    "active": true,
    "flags": [
        "vacation"
    ],
    "id": 5,
    "position": 0,
    "rulename": "Abwesenheitsbenachrichtigung",
    "test": {
        "id": "allof",
        "tests": [
            {
                "comparison": "ge",
                "datepart": "date",
                "datevalue": [
                    1672272000000
                ],
                "id": "currentdate",
                "zone": "+0100"
            },
            {
                "comparison": "le",
                "datepart": "date",
                "datevalue": [
                    1672876800000
                ],
                "id": "currentdate",
                "zone": "+0100"
            }
        ]
    }
}';

function stratoCurl( $url, $type, $parameter ) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $parameter);
    curl_setopt($ch, CURLOPT_HTTPHEADER,
        array (
            'Content-Type: application/x-www-form-urlencoded'
        ),
    );

    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $response;
}

$stratoLogin = stratoCurl("https://webmail.strato.de/appsuite/api/login", "POST", http_build_query(array (
    "action"                        =>  "login",
    "name"                          =>  "myUserName",
    "password"                      =>  "myPassword"
)));

$setMessage = stratoCurl("https://webmail.strato.de/appsuite/api/mailfilter/v2?action=update&session=".$stratoLogin['session'], "PUT", $myJson);

echo '```';
print_r($stratoLogin);
print_r($setMessage);
echo '```';
</code>```

Result:

```<code>Array
(
    [session] => MY_SESSION_ID
    [user] => myUsername
    [user_id] => 9
    [context_id] => 52515441
    [locale] => de_DE
)
Array
(
    [error] => Your session expired. Please login again.
    [error_params] => Array
        (
            [0] => MY_SESSION_ID
        )

    [categories] => TRY_AGAIN
    [category] => 4
    [code] => SES-0203
    [error_id] => -673980302-22682517
    [error_desc] => Your session MY_SESSION_ID expired. Please start a new browser session.
)
</code>```

Login seems to be successfull, but if I would like to set the message, the session expired?? Any idea?

Body:
I would like to set my "message of absence" in strato webmail programmatically.
For that I open the developer tools (firefox) and I login via strato webmail and set the "message of absence". I get the curl request from the developer console and I rebuild this as a php code:

$myJson = '
{
    "actioncmds": [
        {
            "addresses": [
                "mail@domain.de"
            ],
            "days": "7",
            "id": "vacation",
            "subject": "My Subject",
            "text": "My Message"
        }
    ],
    "active": true,
    "flags": [
        "vacation"
    ],
    "id": 5,
    "position": 0,
    "rulename": "Abwesenheitsbenachrichtigung",
    "test": {
        "id": "allof",
        "tests": [
            {
                "comparison": "ge",
                "datepart": "date",
                "datevalue": [
                    1672272000000
                ],
                "id": "currentdate",
                "zone": "+0100"
            },
            {
                "comparison": "le",
                "datepart": "date",
                "datevalue": [
                    1672876800000
                ],
                "id": "currentdate",
                "zone": "+0100"
            }
        ]
    }
}';

function stratoCurl( $url, $type, $parameter ) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $parameter);
    curl_setopt($ch, CURLOPT_HTTPHEADER,
        array (
            'Content-Type: application/x-www-form-urlencoded'
        ),
    );

    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $response;
}

$stratoLogin = stratoCurl("https://webmail.strato.de/appsuite/api/login", "POST", http_build_query(array (
    "action"                        =>  "login",
    "name"                          =>  "myUserName",
    "password"                      =>  "myPassword"
)));

$setMessage = stratoCurl("https://webmail.strato.de/appsuite/api/mailfilter/v2?action=update&session=".$stratoLogin['session'], "PUT", $myJson);

echo '
';
print_r($stratoLogin);
print_r($setMessage);
echo '
';

Result:

Array
(
    [session] => MY_SESSION_ID
    [user] => myUsername
    [user_id] => 9
    [context_id] => 52515441
    [locale] => de_DE
)
Array
(
    [error] => Your session expired. Please login again.
    [error_params] => Array
        (
            [0] => MY_SESSION_ID
        )

    [categories] => TRY_AGAIN
    [category] => 4
    [code] => SES-0203
    [error_id] => -673980302-22682517
    [error_desc] => Your session MY_SESSION_ID expired. Please start a new browser session.
)

Login seems to be successfull, but if I would like to set the message, the session expired?? Any idea?


问:
Storybook arg detection and selection
I'm trying to create a button in Storybook, that consists of a primary and secondary button, sizes and the option of a color scheme. I can't figure out how to handle the color classes/args, as they are different, depending on whether you've chosen a primary or secondary button.

Primary button with "grey" color scheme should add the classes

bg-grey-900 text-white

Secondary button with "grey" color scheme should add the classes:

bg-grey-100 text-grey-100

Working example of a color theme for the primary button

```<code>const buttonstyle = cva("rounded", {
  defaultVariants: {
    variants: "primary",
    size: "md",
    color: "indigo",
  },
  variants: {
    variants: {
      primary: "",
      secondary: "",
    },
    size: {
      xs: "text-xs px-2.5 py-1.5",
      sm: "text-sm px-3 py-2",
      md: "text-sm px-4 py-2",
      lg: "text-base px-4 py-2",
      xl: "text-base px-6 py-3"
    },
    color: {
      grey: "bg-grey-700 text-white"
      slate: "bg-slate-700 text-white"
    },
  },
});

export const Button = ({
  variants,
  size,
  className,
  placeholder,
  color,
  ...rest
}: Props) => {
  const style = buttonstyle({ variants, size, className, color });
  return (
    <button className={style} {...rest}>
      {placeholder}
    </button>
  );
};
</code>```

So what I want, is to automatically detect, whether a button is primary or secondary, and then select between two different options of a single color arg. How can I do something like that?

Something like this – not working

```<code>color: {
  grey {
    primary: "bg-grey-700 text-white",
    secondary: "bg-grey-100 text-grey-700 "
  }
},
</code>```

Title: Storybook arg detection and selection

Body:
I'm trying to create a button in Storybook, that consists of a primary and secondary button, sizes and the option of a color scheme. I can't figure out how to handle the color classes/args, as they are different, depending on whether you've chosen a primary or secondary button.

Primary button with "grey" color scheme should add the classes

bg-grey-900 text-white

Secondary button with "grey" color scheme should add the classes:

bg-grey-100 text-grey-100

Working example of a color theme for the primary button

const buttonstyle = cva("rounded", {
  defaultVariants: {
    variants: "primary",
    size: "md",
    color: "indigo",
  },
  variants: {
    variants: {
      primary: "",
      secondary: "",
    },
    size: {
      xs: "text-xs px-2.5 py-1.5",
      sm: "text-sm px-3 py-2",
      md: "text-sm px-4 py-2",
      lg: "text-base px-4 py-2",
      xl: "text-base px-6 py-3"
    },
    color: {
      grey: "bg-grey-700 text-white"
      slate: "bg-slate-700 text-white"
    },
  },
});

export const Button = ({
  variants,
  size,
  className,
  placeholder,
  color,
  ...rest
}: Props) => {
  const style = buttonstyle({ variants, size, className, color });
  return (
    <button className={style} {...rest}>
      {placeholder}
    </button>
  );
};

So what I want, is to automatically detect, whether a button is primary or secondary, and then select between two different options of a single color arg. How can I do something like that?

Something like this – not working

color: {
  grey {
    primary: "bg-grey-700 text-white",
    secondary: "bg-grey-100 text-grey-700 "
  }
},


问:
How to use find command to search two directories at different maxdepth?
I have two directories dir1 and dir2. I want to run find on them at different maxdepths, how do I do this?

Effectively I want the results of the following 2 concatenated:

find dir1 -maxdepth 2

find dir2 -maxdepth 3


问:
Argument Exception when using PostgresSQL extension for Entity Framework with Docker-Compose
I have a ASP.NET Core API using .NET 6, Entity Framework Core with a code first approach and a PostgresSQL 15 database running with docker-compose start-up project from Visual Studio:

This is the docker-compose.yml file:

```<code>version: '3.9'

services:
    webapi:
        image: ${DOCKER_REGISTRY-}webapi
        build:
            context: .
            dockerfile: WebApi/Dockerfile
        ports:
            - "5000:80"
        depends_on:
            - main_database
        environment:
            - MAIN_DB_CONNECTION_STRING="host=main_database;port=5432;database=pocdb;username=poc_user;password=poc_user"
        networks:
            - internal-dev-network
    main_database:
        image: postgres:15.1-alpine3.17
        restart: always
        environment:
            - POSTGRES_DB=pocdb
            - POSTGRES_USER=poc_user
            - POSTGRES_PASSWORD=poc_user
        ports:
            - "5432:5432"
        networks:
            - internal-dev-network
networks:
    internal-dev-network:
        driver: bridge
</code>```

And this is the Dockerfile for the WebApi:

```<code>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["WebApi/WebApi.csproj", "WebApi/"]
RUN dotnet restore "WebApi/WebApi.csproj"
COPY . .
WORKDIR "/src/WebApi"
RUN dotnet build "WebApi.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApi.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApi.dll"]
</code>```

The thing is that when I try to access the database context I get the fallowing error:

```<code>System.ArgumentException: Format of the initialization string does not conform to specification starting at index 63.
   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms, Boolean useOdbcRules)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at Npgsql.NpgsqlConnection.SetupDataSource()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateDbCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at EntityFrameworkDataManager.Repositories.UserRepository.GetAllUsers() in C:\POC\Back\EntityFrameworkRepositoryManager\Repositories\UserRepository.cs:line 28
   at Domain.Services.UserService.GetAllUsers() in C:\POC\Back\Domain\Services\UserService.cs:line 23
   at WebApi.Controllers.UserController.GetAllUsersAsync() in C:\POC\Back\WebApi\Controllers\UserController.cs:line 30
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Host: localhost:62104
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54
:method: GET
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Referer: https://localhost:62104/swagger/index.html
sec-ch-ua: "Not?A_Bra
</code>```

Researched a lot but found no solution to this specific error. It seems to be an error in the connection string but it seems correct to me considering the examples I'm following:

https://www.npgsql.org/efcore/index.html

https://github.com/rajvirtual/docker-aspnetcore-postgresql/blob/master/docker-compose.yml

That's how I'm adding the Context with the Connection String:

Already tried to run without the port in the connection string (just like it is in the documentation) but it also doesn't work. Also tried this format postgres://{username}:{password}@{host}:{port}/{db_name} but didn't work as well.

Checked and the PostgresSQL container is being created correctly:

Body:
I have a ASP.NET Core API using .NET 6, Entity Framework Core with a code first approach and a PostgresSQL 15 database running with docker-compose start-up project from Visual Studio:

This is the docker-compose.yml file:

version: '3.9'

services:
    webapi:
        image: ${DOCKER_REGISTRY-}webapi
        build:
            context: .
            dockerfile: WebApi/Dockerfile
        ports:
            - "5000:80"
        depends_on:
            - main_database
        environment:
            - MAIN_DB_CONNECTION_STRING="host=main_database;port=5432;database=pocdb;username=poc_user;password=poc_user"
        networks:
            - internal-dev-network
    main_database:
        image: postgres:15.1-alpine3.17
        restart: always
        environment:
            - POSTGRES_DB=pocdb
            - POSTGRES_USER=poc_user
            - POSTGRES_PASSWORD=poc_user
        ports:
            - "5432:5432"
        networks:
            - internal-dev-network
networks:
    internal-dev-network:
        driver: bridge

And this is the Dockerfile for the WebApi:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["WebApi/WebApi.csproj", "WebApi/"]
RUN dotnet restore "WebApi/WebApi.csproj"
COPY . .
WORKDIR "/src/WebApi"
RUN dotnet build "WebApi.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApi.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApi.dll"]

The thing is that when I try to access the database context I get the fallowing error:

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 63.
   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms, Boolean useOdbcRules)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at Npgsql.NpgsqlConnection.SetupDataSource()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateDbCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at EntityFrameworkDataManager.Repositories.UserRepository.GetAllUsers() in C:\POC\Back\EntityFrameworkRepositoryManager\Repositories\UserRepository.cs:line 28
   at Domain.Services.UserService.GetAllUsers() in C:\POC\Back\Domain\Services\UserService.cs:line 23
   at WebApi.Controllers.UserController.GetAllUsersAsync() in C:\POC\Back\WebApi\Controllers\UserController.cs:line 30
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Host: localhost:62104
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54
:method: GET
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Referer: https://localhost:62104/swagger/index.html
sec-ch-ua: "Not?A_Bra

Researched a lot but found no solution to this specific error. It seems to be an error in the connection string but it seems correct to me considering the examples I'm following:

https://www.npgsql.org/efcore/index.html

https://github.com/rajvirtual/docker-aspnetcore-postgresql/blob/master/docker-compose.yml

That's how I'm adding the Context with the Connection String:

Already tried to run without the port in the connection string (just like it is in the documentation) but it also doesn't work. Also tried this format postgres://{username}:{password}@{host}:{port}/{db_name} but didn't work as well.

Checked and the PostgresSQL container is being created correctly:


问:
Laravel Auth::attempt return Undefined array key 1
i have an error in my laravel project but i dont know where the error, when i,m trying to login its return Undefined array key 1.
Here is the Error

here is my code.

This is my Login controller

```<code>
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie as FacadesCookie;

class LoginController extends Controller
{

    public function authenticate(Request $request){
        $credentials = $request->validate([
            'username' => 'required',
            'password' => 'required | min:5 | max:50'
        ]);

        if(Auth::attempt($credentials)){
            $request->session()->regenerate();

            if($request->has('remember')){
                FacadesCookie::queue('adminuser', $request->username,1440);
                FacadesCookie::queue('adminpw', $request->password,1440);
            }

            return redirect()->intended('/beranda_admin');
        }

        return back()->with('loginError', 'Login Gagal!');

    }
}

</code>```

this is the Login Blade

```<code><div class="container">
        @if(session()->has('success'))
            <div class="alert alert-success alert-dismissable fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif

        @if(session()->has('loginError'))
            <div class="alert alert-danger alert-dismissable fade show" role="alert">
                {{ session('loginError') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        <div class="forms-container">
            <img src="img/login.png" alt="icon back" class="img">

            <div class="login">
                <!-- form login -->
                <form action="{{ url('/login') }}" method="POST" class="login">
                    @csrf
                    <h2 class="title">LPPM SINGLE SIGN ON</h2>
                    <!-- username login -->
                    <h3>Username</h3>
                    <div class="input-field">
                        <input type="text" name="username" @if(Cookie::has('adminuser')) value="{{ Cookie::get('adminuser') }}" @endif
                        id="username" autofocus required value="{{ old('username') }}">
                    </div>
                    <!-- password login -->
                    <h3>Password</h3>
                    <div class="input-field">
                        <input type="password" name="password"  @if(Cookie::has('adminpw')) value="{{ Cookie::get('adminpw') }}" @endif id="password" required>
                    </div>
                    <!-- remember me-->
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" @if(Cookie::has('adminuser')) checked @endif name="remember" value="" id="flexCheckDefault">
                        <label>
                            Remember Me
                        </label>
                    </div>
                    <input type="submit" value="login" class="btn solid">
                </form>

            </div>
        </div>
    </div>
</code>```

Model

```<code><?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'id',
        'username',
        'password',
        'remember_token',
        'created_at',
        'updated_at',
    ];
    protected $guarded = ['id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

</code>```

Route

```<code>Route::get('/', [PagesController::class, 'beranda']);
Route::get('/beranda_admin', [PagesController::class, 'beranda_admin'])->middleware('auth');
Route::get('/hlmnlogin', [PagesController::class, 'login']);
Route::get('/form_izinpenelitian', [PagesController::class, 'form_izin_penelitian']);
Route::get('/form_izinpengabdian', [PagesController::class, 'form_izin_pengabdian']);
Route::get('/form_tugaspenelitian', [PagesController::class, 'form_tugas_penelitian']);
Route::get('/form_tugaspengabdian', [PagesController::class, 'form_tugas_pengabdian']);
Route::post('/izinpenelitian', [PagesController::class, 'store_permohonan']);
Route::post('/izinpengabdian', [PagesController::class, 'store_permohonan']);
Route::post('/tugaspenelitian', [PagesController::class, 'store_tugas']);
Route::post('/tugaspengabdian', [PagesController::class, 'store_tugas']);
Route::post('/login', [LoginController::class, 'authenticate']);
Route::post('/logout', [LoginController::class, 'logout']);
Route::get('/ganti_password', [LoginController::class, 'gantiPassword']);
Route::post('/ganti_password', [LoginController::class, 'updatePassword']);
</code>```

i dont know where the error, but it happen after i try to add captcha feature and fail. Thanks for your help guys

Body:
i have an error in my laravel project but i dont know where the error, when i,m trying to login its return Undefined array key 1.
Here is the Error

here is my code.

This is my Login controller

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cookie as FacadesCookie;

class LoginController extends Controller
{

    public function authenticate(Request $request){
        $credentials = $request->validate([
            'username' => 'required',
            'password' => 'required | min:5 | max:50'
        ]);

        if(Auth::attempt($credentials)){
            $request->session()->regenerate();

            if($request->has('remember')){
                FacadesCookie::queue('adminuser', $request->username,1440);
                FacadesCookie::queue('adminpw', $request->password,1440);
            }

            return redirect()->intended('/beranda_admin');
        }

        return back()->with('loginError', 'Login Gagal!');

    }
}

this is the Login Blade

        @if(session()->has('success'))

                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

        @endif

        @if(session()->has('loginError'))

                {{ session('loginError') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

        @endif

                <form action="{{ url('/login') }}" method="POST" class="login">
                    @csrf

LPPM SINGLE SIGN ON

Username

                        <input type="text" name="username" @if(Cookie::has('adminuser')) value="{{ Cookie::get('adminuser') }}" @endif
                        id="username" autofocus required value="{{ old('username') }}">

Password

                        <input type="password" name="password"  @if(Cookie::has('adminpw')) value="{{ Cookie::get('adminpw') }}" @endif id="password" required>

                        <input class="form-check-input" type="checkbox" @if(Cookie::has('adminuser')) checked @endif name="remember" value="" id="flexCheckDefault">

                            Remember Me

                    <input type="submit" value="login" class="btn solid">
                </form>

Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'id',
        'username',
        'password',
        'remember_token',
        'created_at',
        'updated_at',
    ];
    protected $guarded = ['id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Route

Route::get('/', [PagesController::class, 'beranda']);
Route::get('/beranda_admin', [PagesController::class, 'beranda_admin'])->middleware('auth');
Route::get('/hlmnlogin', [PagesController::class, 'login']);
Route::get('/form_izinpenelitian', [PagesController::class, 'form_izin_penelitian']);
Route::get('/form_izinpengabdian', [PagesController::class, 'form_izin_pengabdian']);
Route::get('/form_tugaspenelitian', [PagesController::class, 'form_tugas_penelitian']);
Route::get('/form_tugaspengabdian', [PagesController::class, 'form_tugas_pengabdian']);
Route::post('/izinpenelitian', [PagesController::class, 'store_permohonan']);
Route::post('/izinpengabdian', [PagesController::class, 'store_permohonan']);
Route::post('/tugaspenelitian', [PagesController::class, 'store_tugas']);
Route::post('/tugaspengabdian', [PagesController::class, 'store_tugas']);
Route::post('/login', [LoginController::class, 'authenticate']);
Route::post('/logout', [LoginController::class, 'logout']);
Route::get('/ganti_password', [LoginController::class, 'gantiPassword']);
Route::post('/ganti_password', [LoginController::class, 'updatePassword']);

i dont know where the error, but it happen after i try to add captcha feature and fail. Thanks for your help guys


问:
fluent-ffmpeg Output stream closed, when using aws s3
Can someone help, when I run this code I am getting Output stream closed Erorr from fluent-ffmpeg. How you can see I am passing stream directly to aws s3 and that what is causing a problem I think. If I just usefs.createWriteStream('output.webm') in the pipe, then it work flawlessly, but I want to directly pass stream to aws s3

```<code>   const passthroughs = new PassThrough();
        const data = videoOptions[3];
        ffmpeg(fs.createReadStream(pathToFile))
          .format('webm')
          .outputOptions([
            `-vf scale=${data.scale}`,
            `-b:v ${data.avgBitRate}`,
            `-minrate ${data.minBitRate}`,
            `-maxrate ${data.maxBitRate}`,
            `-tile-columns ${data.tileColumns}`,
            `-g ${data.g}`,
            `-threads ${data.threads}`,
            `-quality ${data.quality}`,
            `-crf ${data.crf}`,
            `-c:v ${data.videoCodec}`,
            `-c:a ${data.audioCodec}`,
            `-speed ${data.speed}`,
            `-y`,
          ])
          .pipe(passthroughs)
          .on('error', (err) => {
            console.log(err);
          })
          .on('data', (data) => {
            console.log({ data });
          })
          .on('progress', (progress) => {
            console.log(progress);
          })
          .on('end', async () => {
            console.log('Video conversion complete');
          });

        const upload = new Upload({
          client: this.s3BucketService.client,
          params: {
            Bucket: 'youtube-nest',
            Key: 'test.webm',
            Body: passthroughs,
          },
        });

        await upload.done();
</code>```

Body:
Can someone help, when I run this code I am getting Output stream closed Erorr from fluent-ffmpeg. How you can see I am passing stream directly to aws s3 and that what is causing a problem I think. If I just usefs.createWriteStream('output.webm') in the pipe, then it work flawlessly, but I want to directly pass stream to aws s3

   const passthroughs = new PassThrough();
        const data = videoOptions[3];
        ffmpeg(fs.createReadStream(pathToFile))
          .format('webm')
          .outputOptions([
            `-vf scale=${data.scale}`,
            `-b:v ${data.avgBitRate}`,
            `-minrate ${data.minBitRate}`,
            `-maxrate ${data.maxBitRate}`,
            `-tile-columns ${data.tileColumns}`,
            `-g ${data.g}`,
            `-threads ${data.threads}`,
            `-quality ${data.quality}`,
            `-crf ${data.crf}`,
            `-c:v ${data.videoCodec}`,
            `-c:a ${data.audioCodec}`,
            `-speed ${data.speed}`,
            `-y`,
          ])
          .pipe(passthroughs)
          .on('error', (err) => {
            console.log(err);
          })
          .on('data', (data) => {
            console.log({ data });
          })
          .on('progress', (progress) => {
            console.log(progress);
          })
          .on('end', async () => {
            console.log('Video conversion complete');
          });

        const upload = new Upload({
          client: this.s3BucketService.client,
          params: {
            Bucket: 'youtube-nest',
            Key: 'test.webm',
            Body: passthroughs,
          },
        });

        await upload.done();


问:
Why is the display image in Pictureedit/PictureBox not appropriate during the Focusrow event in GridView DevExpress in vb.net
there is a problem if I use FocusedRow changes because the image that appears from the previous row still appears. Below I attach a screenshot. How can I solve the problem?

Thanks

```<code>Private Sub GridView1_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim view As GridView = TryCast(sender, GridView)

        If view.FocusedRowHandle = GridControl.AutoFilterRowHandle Then
            Return
        End If

        Dim SUBFOLDERP As String = view.GetFocusedRowCellValue("SUBFOLDERP")?.ToString
        Dim Filename1 As String = view.GetFocusedRowCellValue("FILENAME1")?.ToString
        Dim Filename2 As String = view.GetFocusedRowCellValue("FILENAME2")?.ToString
        parentpathimage = Directory.GetCurrentDirectory()
        Dim filePath1 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename1, False)
        Dim filePath2 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename2, False)
        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
            End If
        End If
    End Sub
</code>```

Body:
there is a problem if I use FocusedRow changes because the image that appears from the previous row still appears. Below I attach a screenshot. How can I solve the problem?

Thanks

Private Sub GridView1_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim view As GridView = TryCast(sender, GridView)

        If view.FocusedRowHandle = GridControl.AutoFilterRowHandle Then
            Return
        End If

        Dim SUBFOLDERP As String = view.GetFocusedRowCellValue("SUBFOLDERP")?.ToString
        Dim Filename1 As String = view.GetFocusedRowCellValue("FILENAME1")?.ToString
        Dim Filename2 As String = view.GetFocusedRowCellValue("FILENAME2")?.ToString
        parentpathimage = Directory.GetCurrentDirectory()
        Dim filePath1 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename1, False)
        Dim filePath2 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename2, False)
        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
            End If
        End If
    End Sub


问:
Why does k8s need GVR?

In kuberentes, RESTMapper converts GVR to GVK and Scheme converts GVK to a go struct.

Why GVR is needed? Is it okay to remove GVR?

Title: Why does k8s need GVR?


问:
Errors in loading sdk in my express js project
I am trying to develop an expressjs app and inside my project I would like to use the following sdk:
https://loopring-1.gitbook.io/loopring-dev-docs/sdk/sdk-guides

Following the instructions, I have installed the package via npm and I created a file inside my project named loop.js where I have pasted the starting code provided in the website:

```<code>import * as sdk from "@loopring-web/loopring-sdk";
export class LoopringAPIClass {
  public static userAPI: UserAPI;
  public static exchangeAPI: ExchangeAPI;
  public static ammpoolAPI: AmmpoolAPI;
  public static walletAPI: WalletAPI;
  public static wsAPI: WsAPI;
  public static nftAPI: NFTAPI;
  public static delegate: DelegateAPI;
  public static globalAPI: GlobalAPI;
  public static contractAPI: typeof ContractAPI;
  public static __chainId__: sdk.ChainId;
  public static InitApi = (chainId: sdk.ChainId) => {
    LoopringAPI.userAPI = new UserAPI({ chainId });
    LoopringAPI.exchangeAPI = new ExchangeAPI({ chainId });
    LoopringAPI.globalAPI = new GlobalAPI({ chainId });
    LoopringAPI.ammpoolAPI = new AmmpoolAPI({ chainId });
    LoopringAPI.walletAPI = new WalletAPI({ chainId });
    LoopringAPI.wsAPI = new WsAPI({ chainId });
    LoopringAPI.nftAPI = new NFTAPI({ chainId });
    LoopringAPI.delegate = new DelegateAPI({ chainId });
    LoopringAPI.__chainId__ = chainId;
    LoopringAPI.contractAPI = ContractAPI;
  };
}
/* env:
 * test:  sdk.ChainId.GOERLI
 * eth:  sdk.ChainId.MAINNET
 */
LoopringAPIClass.InitApi({sdk.ChainId.MAINNET});
</code>```

When I try to run the code in nodejs I get the following error:
error1

I have tried to add the "type": "module" line in package.json but then I got this different kind of error by running the import line:

error2

Could you please help me to integrate the sdk in my project?

Body:
I am trying to develop an expressjs app and inside my project I would like to use the following sdk:
https://loopring-1.gitbook.io/loopring-dev-docs/sdk/sdk-guides

Following the instructions, I have installed the package via npm and I created a file inside my project named loop.js where I have pasted the starting code provided in the website:

import * as sdk from "@loopring-web/loopring-sdk";
export class LoopringAPIClass {
  public static userAPI: UserAPI;
  public static exchangeAPI: ExchangeAPI;
  public static ammpoolAPI: AmmpoolAPI;
  public static walletAPI: WalletAPI;
  public static wsAPI: WsAPI;
  public static nftAPI: NFTAPI;
  public static delegate: DelegateAPI;
  public static globalAPI: GlobalAPI;
  public static contractAPI: typeof ContractAPI;
  public static __chainId__: sdk.ChainId;
  public static InitApi = (chainId: sdk.ChainId) => {
    LoopringAPI.userAPI = new UserAPI({ chainId });
    LoopringAPI.exchangeAPI = new ExchangeAPI({ chainId });
    LoopringAPI.globalAPI = new GlobalAPI({ chainId });
    LoopringAPI.ammpoolAPI = new AmmpoolAPI({ chainId });
    LoopringAPI.walletAPI = new WalletAPI({ chainId });
    LoopringAPI.wsAPI = new WsAPI({ chainId });
    LoopringAPI.nftAPI = new NFTAPI({ chainId });
    LoopringAPI.delegate = new DelegateAPI({ chainId });
    LoopringAPI.__chainId__ = chainId;
    LoopringAPI.contractAPI = ContractAPI;
  };
}
/* env:
 * test:  sdk.ChainId.GOERLI
 * eth:  sdk.ChainId.MAINNET
 */
LoopringAPIClass.InitApi({sdk.ChainId.MAINNET});

When I try to run the code in nodejs I get the following error:
error1

I have tried to add the "type": "module" line in package.json but then I got this different kind of error by running the import line:

error2

Could you please help me to integrate the sdk in my project?


问:
Memory leak with recursive Parse model (parent/children)
I have defined a Parse model class Task which contains a bunch of simple data (text, images), and can optionally represent a composite structure via a parent/child relation, implemented by means of a parent pointer and a children array:

class Task: PFObject, PFSubclassing {
  class func parseClassName() -> String { "Task" }

  @NSManaged var note: String?
  @NSManaged var images: [PFFileObject]?

  @NSManaged var parent: Task?
  @NSManaged var children: [Task]?
}
```
<p>Using Xcode's "Debug Memory Graph" view, I observed that this data structure causes a memory leak: when parent/child Task objects are released by my code, they still are kept in memory. This does not happen for "standalone" Task objects (i.e. the ones having neither a parent or children), they get released correctly.</p>
<p>I already tried to manually unset the parent/child relation properties, without success:</p>
<pre class="lang-swift prettyprint-override"><code>for task in tasks {
  for childTask in task.children ?? [] {
    childTask.parent = nil
    // or: childTask.remove(forKey: "parent")
  }

  task.children = []
  // or: task.remove(forKey: "children")
}

</code>```

I still assume that the problem comes from the strong reference in the children property; for some reason, I cannot break it by manually unsetting that reference though. Any help resolving the memory leak in this data model is appreciated :)

(P.S.: I know about relations; please don't suggest to change the data model in this direction.)

Using Parse-SDK-iOS-OSX version 1.19.4 via CocoaPods, Swift, Xcode 14.2, iOS 16.2.

Body:
I have defined a Parse model class Task which contains a bunch of simple data (text, images), and can optionally represent a composite structure via a parent/child relation, implemented by means of a parent pointer and a children array:

class Task: PFObject, PFSubclassing {
  class func parseClassName() -> String { "Task" }

  @NSManaged var note: String?
  @NSManaged var images: [PFFileObject]?

  @NSManaged var parent: Task?
  @NSManaged var children: [Task]?
}

Using Xcode's "Debug Memory Graph" view, I observed that this data structure causes a memory leak: when parent/child Task objects are released by my code, they still are kept in memory. This does not happen for "standalone" Task objects (i.e. the ones having neither a parent or children), they get released correctly.

I already tried to manually unset the parent/child relation properties, without success:

for task in tasks {
  for childTask in task.children ?? [] {
    childTask.parent = nil
    // or: childTask.remove(forKey: "parent")
  }

  task.children = []
  // or: task.remove(forKey: "children")
}

I still assume that the problem comes from the strong reference in the children property; for some reason, I cannot break it by manually unsetting that reference though. Any help resolving the memory leak in this data model is appreciated :)

(P.S.: I know about relations; please don't suggest to change the data model in this direction.)

Using Parse-SDK-iOS-OSX version 1.19.4 via CocoaPods, Swift, Xcode 14.2, iOS 16.2.