问:
jQuery Virtual keyboard are saving value from previous input
I work with Virtual keyboar, and i have issues.

Issues is, in one UI i have few input fields for each of this field i have class "input" which call key board.

When i tap for first input and enter data, this data which was for previous input field are copie to new.

$(document).ready(function () {
    $(".numpad").hide();
    $('.input').click(function () {
        $('.numpad').fadeToggle('fast');
    });

    $('.del').click(function () {
        $('.input').val($('.input').val().substring(0, $('.input').val().length - 1));
    });
    $('.faq').click(function () {
        alert("It's virtual keyboard");
    })
    $('.shuffle').click(function () {
        $('.input').val($('.input').val() + $(this).text());
    });

});

$(".input").on("click", function () {
    $('.modal, .cover').removeClass("hidden");
    $('.modal').addClass("zoom");
});

//hide modal
$(".cover, .close").on("click", function () {
    $('.modal').attr('class', 'modal');
    $('.modal, .cover').addClass("hidden");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.keyBoardButton {
    margin: 13px;
}

.keyBoardButton {
    display: inline-block;
    border: 1px solid #fff;
    color: #fff;
    border-radius: 30px;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    font-family: Verdana;
    width: auto;
    height: auto;
    font-size: 22px;
    padding: 20px 27px;
    background-color: #878787;
}

    .keyBoardButton:hover, .keyBoardButton:active {
        border: 1px solid #FFFFFF;
        color: #000;
        background-color: #fff;
    }

.cover {
    z-index: 1;
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: #333;
    top: 0;
    left: 0;
    opacity: .9;
}

.modal {
    z-index: 2;
    height: 390px;
    width: 350px;
    background-color: #262626;
    border-radius: 5px;
    text-align: center;
    border-top: solid 3px #262626;
    position: absolute;
    opacity: 0.9;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

    .modal .content p {
        font-size: 2em;
        color: #fff;
        height: 50px;
        width: 100%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }

.tiltup {
    display: block;
    transform: perspective(300px);
    animation: tiltup 0.7s;
    animation-fill-mode: forwards;
    padding-top: 0;
}

@keyframes tiltup {
    0% {
        bottom: -400px;
        opacity: 0;
        transform: rotateX(-80deg);
        border-top: solid 40px;
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.zoom {
    display: block;
    animation: zoom 0.7s;
    animation-fill-mode: forwards;
}

@keyframes zoom {
    0% {
        opacity: 0;
        transform: scale(0, 0);
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.hidden {
    display: none;
}

.reverse {
    animation-direction: reverse;
}</code>```

<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">

                    <button class="shuffle keyBoardButton">1</button>
                    <button class="shuffle keyBoardButton">2</button>
                    <button class="shuffle keyBoardButton">3</button>

                    <button class="shuffle keyBoardButton">4</button>
                    <button class="shuffle keyBoardButton">5</button>
                    <button class="shuffle keyBoardButton">6</button>

                    <button class="shuffle keyBoardButton">7</button>
                    <button class="shuffle keyBoardButton">8</button>
                    <button class="shuffle keyBoardButton">9</button>

                    <button class="del keyBoardButton">X</button>
                    <button class="shuffle keyBoardButton">0</button>
                    <button class="faq keyBoardButton">?</button>

```

So as you can see, when click in to input field, Virtual keyboard are opening in modal window, after addind data, at other input fileds this data will copie.

So for each input i need separate data.

答:
See this snippest, you will get some idea.

$(document).ready(function () {

 var selected_inp;
    $(".numpad").hide();
    $('.input').click(function () {
       selected_inp = $(this);
        $('.numpad').fadeToggle('fast');
    });

    $('.del').click(function () {
        $('.input').val($('.input').val().substring(0, $('.input').val().length - 1));
    });
    $('.faq').click(function () {
        alert("It's virtual keyboard");
    })
    $('.shuffle').click(function () {
        //$('.input').val($('.input').val() + $(this).text());
        selected_inp.val($(this).text());
    });
    (function ($) {

        $.fn.shuffle = function () {

            var allElems = this.get(),
                getRandom = function (max) {
                    return Math.floor(Math.random() * max);
                },
                shuffled = $.map(allElems, function () {
                    var random = getRandom(allElems.length),
                        randEl = $(allElems[random]).clone(true)[0];
                    allElems.splice(random, 1);
                    return randEl;
                });

            this.each(function (i) {
                $(this).replaceWith($(shuffled[i]));
            });

            return $(shuffled);

        };

    })(jQuery);

});

$(".input").on("click", function () {
    $('.modal, .cover').removeClass("hidden");
    $('.modal').addClass("zoom");
});

//hide modal
$(".cover, .close").on("click", function () {
    $('.modal').attr('class', 'modal');
    $('.modal, .cover').addClass("hidden");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.keyBoardButton {
    margin: 13px;
}

.keyBoardButton {
    display: inline-block;
    border: 1px solid #fff;
    color: #fff;
    border-radius: 30px;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    font-family: Verdana;
    width: auto;
    height: auto;
    font-size: 22px;
    padding: 20px 27px;
    background-color: #878787;
}

    .keyBoardButton:hover, .keyBoardButton:active {
        border: 1px solid #FFFFFF;
        color: #000;
        background-color: #fff;
    }

.cover {
    z-index: 1;
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: #333;
    top: 0;
    left: 0;
    opacity: .9;
}

.modal {
    z-index: 2;
    height: 390px;
    width: 350px;
    background-color: #262626;
    border-radius: 5px;
    text-align: center;
    border-top: solid 3px #262626;
    position: absolute;
    opacity: 0.9;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

    .modal .content p {
        font-size: 2em;
        color: #fff;
        height: 50px;
        width: 100%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }

.tiltup {
    display: block;
    transform: perspective(300px);
    animation: tiltup 0.7s;
    animation-fill-mode: forwards;
    padding-top: 0;
}

@keyframes tiltup {
    0% {
        bottom: -400px;
        opacity: 0;
        transform: rotateX(-80deg);
        border-top: solid 40px;
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.zoom {
    display: block;
    animation: zoom 0.7s;
    animation-fill-mode: forwards;
}

@keyframes zoom {
    0% {
        opacity: 0;
        transform: scale(0, 0);
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.hidden {
    display: none;
}

.reverse {
    animation-direction: reverse;
}</code>```

<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">

                    <button class="shuffle keyBoardButton">1</button>
                    <button class="shuffle keyBoardButton">2</button>
                    <button class="shuffle keyBoardButton">3</button>

                    <button class="shuffle keyBoardButton">4</button>
                    <button class="shuffle keyBoardButton">5</button>
                    <button class="shuffle keyBoardButton">6</button>

                    <button class="shuffle keyBoardButton">7</button>
                    <button class="shuffle keyBoardButton">8</button>
                    <button class="shuffle keyBoardButton">9</button>

                    <button class="del keyBoardButton">X</button>
                    <button class="shuffle keyBoardButton">0</button>
                    <button class="faq keyBoardButton">?</button>

```

Body:
I work with Virtual keyboar, and i have issues.

Issues is, in one UI i have few input fields for each of this field i have class "input" which call key board.

When i tap for first input and enter data, this data which was for previous input field are copie to new.

$(document).ready(function () {
    $(".numpad").hide();
    $('.input').click(function () {
        $('.numpad').fadeToggle('fast');
    });

    $('.del').click(function () {
        $('.input').val($('.input').val().substring(0, $('.input').val().length - 1));
    });
    $('.faq').click(function () {
        alert("It's virtual keyboard");
    })
    $('.shuffle').click(function () {
        $('.input').val($('.input').val() + $(this).text());
    });

});

$(".input").on("click", function () {
    $('.modal, .cover').removeClass("hidden");
    $('.modal').addClass("zoom");
});

//hide modal
$(".cover, .close").on("click", function () {
    $('.modal').attr('class', 'modal');
    $('.modal, .cover').addClass("hidden");
});

.keyBoardButton {
    margin: 13px;
}

.keyBoardButton {
    display: inline-block;
    border: 1px solid #fff;
    color: #fff;
    border-radius: 30px;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    font-family: Verdana;
    width: auto;
    height: auto;
    font-size: 22px;
    padding: 20px 27px;
    background-color: #878787;
}

    .keyBoardButton:hover, .keyBoardButton:active {
        border: 1px solid #FFFFFF;
        color: #000;
        background-color: #fff;
    }

.cover {
    z-index: 1;
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: #333;
    top: 0;
    left: 0;
    opacity: .9;
}

.modal {
    z-index: 2;
    height: 390px;
    width: 350px;
    background-color: #262626;
    border-radius: 5px;
    text-align: center;
    border-top: solid 3px #262626;
    position: absolute;
    opacity: 0.9;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

    .modal .content p {
        font-size: 2em;
        color: #fff;
        height: 50px;
        width: 100%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }

.tiltup {
    display: block;
    transform: perspective(300px);
    animation: tiltup 0.7s;
    animation-fill-mode: forwards;
    padding-top: 0;
}

@keyframes tiltup {
    0% {
        bottom: -400px;
        opacity: 0;
        transform: rotateX(-80deg);
        border-top: solid 40px;
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.zoom {
    display: block;
    animation: zoom 0.7s;
    animation-fill-mode: forwards;
}

@keyframes zoom {
    0% {
        opacity: 0;
        transform: scale(0, 0);
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.hidden {
    display: none;
}

.reverse {
    animation-direction: reverse;
}

<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">

                    <button class="shuffle keyBoardButton">1</button>
                    <button class="shuffle keyBoardButton">2</button>
                    <button class="shuffle keyBoardButton">3</button>

                    <button class="shuffle keyBoardButton">4</button>
                    <button class="shuffle keyBoardButton">5</button>
                    <button class="shuffle keyBoardButton">6</button>

                    <button class="shuffle keyBoardButton">7</button>
                    <button class="shuffle keyBoardButton">8</button>
                    <button class="shuffle keyBoardButton">9</button>

                    <button class="del keyBoardButton">X</button>
                    <button class="shuffle keyBoardButton">0</button>
                    <button class="faq keyBoardButton">?</button>

So as you can see, when click in to input field, Virtual keyboard are opening in modal window, after addind data, at other input fileds this data will copie.

So for each input i need separate data.

Body:
See this snippest, you will get some idea.

$(document).ready(function () {

 var selected_inp;
    $(".numpad").hide();
    $('.input').click(function () {
       selected_inp = $(this);
        $('.numpad').fadeToggle('fast');
    });

    $('.del').click(function () {
        $('.input').val($('.input').val().substring(0, $('.input').val().length - 1));
    });
    $('.faq').click(function () {
        alert("It's virtual keyboard");
    })
    $('.shuffle').click(function () {
        //$('.input').val($('.input').val() + $(this).text());
        selected_inp.val($(this).text());
    });
    (function ($) {

        $.fn.shuffle = function () {

            var allElems = this.get(),
                getRandom = function (max) {
                    return Math.floor(Math.random() * max);
                },
                shuffled = $.map(allElems, function () {
                    var random = getRandom(allElems.length),
                        randEl = $(allElems[random]).clone(true)[0];
                    allElems.splice(random, 1);
                    return randEl;
                });

            this.each(function (i) {
                $(this).replaceWith($(shuffled[i]));
            });

            return $(shuffled);

        };

    })(jQuery);

});

$(".input").on("click", function () {
    $('.modal, .cover').removeClass("hidden");
    $('.modal').addClass("zoom");
});

//hide modal
$(".cover, .close").on("click", function () {
    $('.modal').attr('class', 'modal');
    $('.modal, .cover').addClass("hidden");
});

.keyBoardButton {
    margin: 13px;
}

.keyBoardButton {
    display: inline-block;
    border: 1px solid #fff;
    color: #fff;
    border-radius: 30px;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    font-family: Verdana;
    width: auto;
    height: auto;
    font-size: 22px;
    padding: 20px 27px;
    background-color: #878787;
}

    .keyBoardButton:hover, .keyBoardButton:active {
        border: 1px solid #FFFFFF;
        color: #000;
        background-color: #fff;
    }

.cover {
    z-index: 1;
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: #333;
    top: 0;
    left: 0;
    opacity: .9;
}

.modal {
    z-index: 2;
    height: 390px;
    width: 350px;
    background-color: #262626;
    border-radius: 5px;
    text-align: center;
    border-top: solid 3px #262626;
    position: absolute;
    opacity: 0.9;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

    .modal .content p {
        font-size: 2em;
        color: #fff;
        height: 50px;
        width: 100%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }

.tiltup {
    display: block;
    transform: perspective(300px);
    animation: tiltup 0.7s;
    animation-fill-mode: forwards;
    padding-top: 0;
}

@keyframes tiltup {
    0% {
        bottom: -400px;
        opacity: 0;
        transform: rotateX(-80deg);
        border-top: solid 40px;
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.zoom {
    display: block;
    animation: zoom 0.7s;
    animation-fill-mode: forwards;
}

@keyframes zoom {
    0% {
        opacity: 0;
        transform: scale(0, 0);
    }

    30% {
        opacity: 0;
    }

    100% {
        bottom: 0;
    }
}

.hidden {
    display: none;
}

.reverse {
    animation-direction: reverse;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">
<input type="text" class="input">

<div class='cover hidden'></div>
<div class='modal hidden'>
    <div class='content'>
        <div class="numpad">
            <div id="container">
                <div>
                    <button class="shuffle keyBoardButton">1</button>
                    <button class="shuffle keyBoardButton">2</button>
                    <button class="shuffle keyBoardButton">3</button>
                </div>
                <div>
                    <button class="shuffle keyBoardButton">4</button>
                    <button class="shuffle keyBoardButton">5</button>
                    <button class="shuffle keyBoardButton">6</button>
                </div>
                <div>
                    <button class="shuffle keyBoardButton">7</button>
                    <button class="shuffle keyBoardButton">8</button>
                    <button class="shuffle keyBoardButton">9</button>
                </div>
                <div>
                    <button class="del keyBoardButton">X</button>
                    <button class="shuffle keyBoardButton">0</button>
                    <button class="faq keyBoardButton">?</button>
                </div>
            </div>
        </div>
    </div>

</div>


来源: stackexchange

问:
Does @RequestMapping(produces = "application/json;charset=utf-8") block jsonp requests?
I'm trying to debug a problem on production server where there's a method inside a controller that is annotated by:

```<code>@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
</code>```

And in javascript an ajax call is made to this endpoint:

```<code>$.ajax({
            type: "GET",
            async: true,
            url: "<%=endpointUrl%>",
            dataType: "jsonp",
            success: function(data){
                console.log("success!");
            },
            error: function(xhr, options, error){
                console.log("fail!");
            }
});
</code>```

But in chrome I get warning for Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json.

I thought jsonp is used to 'bypass' same-origin-policy for get requests? Why is it getting blocked?

EDIT: additional info, these headers are set in the endpoint:

```<code>httpResponse.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval'");
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-XSS-Protection", "1");
</code>```

答:
I figured it out..

```<code>@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
</code>```

change to

```<code>@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "text/javascript;charset=utf-8")
</code>```

The problem is caused by

```<code>httpResponse.setHeader("X-Content-Type-Options", "nosniff");
</code>```

enforcing content-type

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to debug a problem on production server where there's a method inside a controller that is annotated by:

@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")

And in javascript an ajax call is made to this endpoint:

$.ajax({
            type: "GET",
            async: true,
            url: "<%=endpointUrl%>",
            dataType: "jsonp",
            success: function(data){
                console.log("success!");
            },
            error: function(xhr, options, error){
                console.log("fail!");
            }
});

But in chrome I get warning for Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json.

I thought jsonp is used to 'bypass' same-origin-policy for get requests? Why is it getting blocked?

EDIT: additional info, these headers are set in the endpoint:

httpResponse.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval'");
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-XSS-Protection", "1");

Body:
I figured it out..

@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")

change to

@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "text/javascript;charset=utf-8")

The problem is caused by

httpResponse.setHeader("X-Content-Type-Options", "nosniff");

enforcing content-type


问:
Dismissing dialog and showing new one shortly shows underlying fragment before opening new dialog
I currently have one fragment that shows dialogfragment, and when I press the button on dialogfragment, I want to show another dialogfragment. In my first dialog fragment I have following method:

```<code> fun showSecondDialog() {
    dismiss()
    SecondDialog().showDialog(targetFragment!!)
}
</code>```

showDialog() looks like this:

```<code>    fun showDialog(fragment: Fragment) {
    val fragmentManager = fragment.fragmentManager
    val ft = fragmentManager!!.beginTransaction()
    val prev = fragmentManager.findFragmentByTag(getName())
    if (prev != null) {
        ft.remove(prev)
    }
    ft.addToBackStack(null)

    setTargetFragment(fragment, 0)
    show(ft, getName())
}
</code>```

The problem is, that dismissing dialog works immediately, but before the new dialog is shown there is a gap, where my underlying fragment is fully visible and this causes an undesirable flicker.

How to show second dialog immediately, or how to know when it's opened, so I could close the first one?

答:
I am also having this same problem, but you can try a workaround like this if it works according to your requirement : </p>

```<code>fun showSecondDialog() {

    SecondDialog().showDialog(targetFragment!!)

    Handler().postDelayed({ dismiss() }, 1000)

}
</code>```

Body:
I currently have one fragment that shows dialogfragment, and when I press the button on dialogfragment, I want to show another dialogfragment. In my first dialog fragment I have following method:

 fun showSecondDialog() {
    dismiss()
    SecondDialog().showDialog(targetFragment!!)
}

showDialog() looks like this:

    fun showDialog(fragment: Fragment) {
    val fragmentManager = fragment.fragmentManager
    val ft = fragmentManager!!.beginTransaction()
    val prev = fragmentManager.findFragmentByTag(getName())
    if (prev != null) {
        ft.remove(prev)
    }
    ft.addToBackStack(null)

    setTargetFragment(fragment, 0)
    show(ft, getName())
}

The problem is, that dismissing dialog works immediately, but before the new dialog is shown there is a gap, where my underlying fragment is fully visible and this causes an undesirable flicker.

How to show second dialog immediately, or how to know when it's opened, so I could close the first one?

Body:
I am also having this same problem, but you can try a workaround like this if it works according to your requirement :

fun showSecondDialog() {

    SecondDialog().showDialog(targetFragment!!)

    Handler().postDelayed({ dismiss() }, 1000)

}


问:
How to pass variable to url from the database, every-time a registration form is submitted
I'm working on an online exam site.
So when a user submits the registration form on my site, the user must be directed to 'url/accesscode'. Here, the accesscode variable must be sent to the URL from the database when the form is submitted. A new access code is to be sent for every new registration.

How can I accomplish this using javascript/PHP?

I tried to concatenate url using javascript, also tried hidden inputs on forms, but these will work for only single access code.

Method1 - Javascript

```<code>var aCode=“accesscode”
function onClick()
{
window.open("url"+aCode);
};
</code>```

Method2 - HTML

```<code><form action="URL" method="GET">
<input type="hidden" name="access_code" value="accesscode">
<?form>
</code>```

答:
You can use a couple of functions, like onclickor onsubmit(form function), but there's too a way to do that trough the input using onchangeor onblur, but you have to be beware about the behavior of each one.

Like:

onclick it'll be triggered when you click in the element.
onblur it'll be triggered every time the focus is out of the element (usually it used in input of text type).
onchange it'll be triggered every time the input is changing (when you filling it).

So following your sample of code the possibilities could be:

```<code>const element = document.getElementById('element');
const url = "something";
// using on change
element.onchange = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}

// using onblur
element.onchange = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}

// using on click
element.onclick = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}
</code>```

Now if you want to use in 'onsubmit' function you need referer the form element, like:

```<code>const form = document.getElementById("form");
const formUrl = "something";
form.onsubmit = function(event) {
   // if you want to prevent the default form behavior event.preventDefault();
   event.target.url = formUrl;
}
</code>```

After that, you can follow your logic normal.

Body:
I'm working on an online exam site.
So when a user submits the registration form on my site, the user must be directed to 'url/accesscode'. Here, the accesscode variable must be sent to the URL from the database when the form is submitted. A new access code is to be sent for every new registration.

How can I accomplish this using javascript/PHP?

I tried to concatenate url using javascript, also tried hidden inputs on forms, but these will work for only single access code.

Method1 - Javascript

var aCode=“accesscode”
function onClick()
{
window.open("url"+aCode);
};

Method2 - HTML

<form action="URL" method="GET">
<input type="hidden" name="access_code" value="accesscode">
<?form>

Body:
You can use a couple of functions, like onclickor onsubmit(form function), but there's too a way to do that trough the input using onchangeor onblur, but you have to be beware about the behavior of each one.

Like:

onclick it'll be triggered when you click in the element.
onblur it'll be triggered every time the focus is out of the element (usually it used in input of text type).
onchange it'll be triggered every time the input is changing (when you filling it).

So following your sample of code the possibilities could be:

const element = document.getElementById('element');
const url = "something";
// using on change
element.onchange = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}

// using onblur
element.onchange = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}

// using on click
element.onclick = function() {
    const form = document.getElementById("form");
    form.target.url = url;
}

Now if you want to use in 'onsubmit' function you need referer the form element, like:

const form = document.getElementById("form");
const formUrl = "something";
form.onsubmit = function(event) {
   // if you want to prevent the default form behavior event.preventDefault();
   event.target.url = formUrl;
}

After that, you can follow your logic normal.


问:
Testing ListPreference
I'm trying to test android preferences, and I'm a bit confused as to how to achieve that result.

Here is my preference

```<code><PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
    android:id="@+id/numberListPreference"
    android:defaultValue="3"
    android:entries="@array/number_text"
    android:entryValues="@array/number_value"
    android:key="@string/pref_key"
    android:summary="@string/pref_summary"
    android:title="@string/pref_title" />
</PreferenceScreen>
</code>```

I want to test that when I change the number in the displayed ListPreference, the SharedPreference is actually changed.

Right now, the code works, I'm just blocking on the testing part.

Here is part of my activity :

```<code>public class SettingActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager()
            .beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
    }

    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}
</code>```

The problem is I have the classic "If the target view is not part of the view hierarchy" error.

Any help is welcomed.
Thx !

答:
```<code>@Test
    public void clickListPreference() throws Exception{

        // Check if it is displayed
        Context appContext = InstrumentationRegistry.getTargetContext();

        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_key))))
          .check(matches(isDisplayed()));

        // Check if click is working
        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_key))))
          .onChildView(withText(appContext.getResources()
              .getString(R.string.pref_title))).perform(click());
 }
</code>```

Hope this will help you... Put your shared preference under click action

Title: Testing ListPreference

Body:
I'm trying to test android preferences, and I'm a bit confused as to how to achieve that result.

Here is my preference

<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
    android:id="@+id/numberListPreference"
    android:defaultValue="3"
    android:entries="@array/number_text"
    android:entryValues="@array/number_value"
    android:key="@string/pref_key"
    android:summary="@string/pref_summary"
    android:title="@string/pref_title" />
</PreferenceScreen>

I want to test that when I change the number in the displayed ListPreference, the SharedPreference is actually changed.

Right now, the code works, I'm just blocking on the testing part.

Here is part of my activity :

public class SettingActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager()
            .beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
    }

    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}

The problem is I have the classic "If the target view is not part of the view hierarchy" error.

Any help is welcomed.
Thx !

Body:
@Test
    public void clickListPreference() throws Exception{

        // Check if it is displayed
        Context appContext = InstrumentationRegistry.getTargetContext();

        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_key))))
          .check(matches(isDisplayed()));

        // Check if click is working
        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_key))))
          .onChildView(withText(appContext.getResources()
              .getString(R.string.pref_title))).perform(click());
 }

Hope this will help you... Put your shared preference under click action


问:
Trying to use javascript function to run mysql query for specific time when user click in php
When user click claim button, i want to run javascript function every 5 sec.
After i build up this code, and clicked the button but the script doesn't work. I'm not good at javascript at all. All i know is some php and mysql.

When user clicked claim button, the function send() should call payout() function and run this crul() function which is inside payout() function.
I don't know where i make mistake as i don't know much javascript.

this is the button function i build up. don't know if it wrong or not.

```<code><button onclick="send()" class="btn-success"><i class="fas fa-exclamation-circle"></i> Claim <i class="fas fa-exclamation-circle"></i></button>
<script>
function send() {
   setInterval(function(){ payout(); }, 5000);
}
</script>
</code>```

This is the function payout()

```<code>function payout(){
    $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://faucethub.io/api/v1/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "api_key=$apikey&to=$wallet&currency=$shortcurrency&amount=$doge ");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
}
</code>```

The result should be payout() function should send to that $wallet every 5 sec

答:
First, you need to create one PHP file and move your PHP payout() in php file. second, you need to ajax call in the javascript interval.

payout.php

```<code>//add the following code after your connection object
function payout(){
    $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://faucethub.io/api/v1/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "api_key=$apikey&to=$wallet&currency=$shortcurrency&amount=$doge ");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
}
</code>```

index.html

<button onclick="send()" class="btn-success"> Claim </button>
```

Body:
When user click claim button, i want to run javascript function every 5 sec.
After i build up this code, and clicked the button but the script doesn't work. I'm not good at javascript at all. All i know is some php and mysql.

When user clicked claim button, the function send() should call payout() function and run this crul() function which is inside payout() function.
I don't know where i make mistake as i don't know much javascript.

this is the button function i build up. don't know if it wrong or not.

<button onclick="send()" class="btn-success"> Claim </button>

This is the function payout()

function payout(){
    $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://faucethub.io/api/v1/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "api_key=$apikey&to=$wallet&currency=$shortcurrency&amount=$doge ");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
}

The result should be payout() function should send to that $wallet every 5 sec

Body:
First, you need to create one PHP file and move your PHP payout() in php file. second, you need to ajax call in the javascript interval.

payout.php

//add the following code after your connection object
function payout(){
    $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://faucethub.io/api/v1/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "api_key=$apikey&to=$wallet&currency=$shortcurrency&amount=$doge ");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
}

index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="send()" class="btn-success"><i class="fas fa-exclamation-circle"></i> Claim <i class="fas fa-exclamation-circle"></i></button>
<script>
function send() {
 setInterval(function () {
  $.ajax({
   type: 'POST',
   url: 'payout.php',
   success: function (data) {
    console.log("payout attempt");
   },
  });
 }, 3000);
}
</script>


问:
Replacing a portion of a string with an exact matching
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

```<code>    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */
</code>```

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q

答:
The easiest way to achieve your result as per your .net fiddle is use the replace as below.

string result = text.Replace("wd:response>", "response>");

But proper way to achieve this is parsing using XML

Body:
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q


问:
How can I sort sentences based on dates contained in them using python
I have a few paragraphs of customer data. Each paragraph starts with dd.mm.yyyy hh:mm:ss. I need to sort these paragraphs based on the date time stamp contained in them

I need to use python for this. I have tried regex on python but didn't get the output

Code:

```<code>*sep2 = '([0-3]?\d)[- \/.](0\d|1[0-2])[- \/.]((19|20)\d\d) ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)'
text2 = text1.split(sep2)
print(text2)*
</code>```

Input contains paragraphs which are unseparated by date. example of one paragraph:

```<code>21.01.2017 09:05:56 abcsdfasklfvd 02.01.2017 09:05:56 afgdsfggv
</code>```

Expected output:

```<code>text2[0] = 21.01.2017 09:05:56 abcsdfasklfvd
text2[1] = 02.01.2017 09:05:56 afgdsfggv
</code>```

then I want to apply some sorting function based on ascending date which would give

expected output:

```<code>sorted[0] = 02.01.2017 09:05:56 afgdsfggv
sorted[1] = 21.01.2017 09:05:56 abcsdfasklfvd
</code>```

答:
```<code>from datetime import datetime

text = ["21.01.2017 09:05:56 abcsdfasklfvd", "02.01.2017 09:05:56 afgdsfggv"]
sorted(text, key=lambda s: datetime.strptime(s[0:19], '%d.%m.%Y %H:%M:%S'))
</code>```

If the pattern dd.mm.yyyy hh:mm:ss does not appear inside paragraphs then you can use

```<code>text1 = "21.01.2017 09:05:56 abcsdfasklfvd 02.01.2017 09:05:56 afgdsfggv"

text = list()
for d, t in zip(*[iter(re.split(r'(\d+.\d+.\d+ \d+:\d+:\d+)', text1)[1:])]*2):
    text.append(d + t)

sorted(text, key=lambda s: datetime.strptime(s[0:19], '%d.%m.%Y %H:%M:%S'))
</code>```

```<code>def extract(s):
    try:
        return datetime.strptime(s, '%d.%m.%Y %H:%M:%S')
    except (ValueError):
        return datetime.strptime(s, '%d/%m/%Y %H:%M:%S')
sorted(text, key=lambda s: extract(s[0:19]))
</code>```

Body:
I have a few paragraphs of customer data. Each paragraph starts with dd.mm.yyyy hh:mm:ss. I need to sort these paragraphs based on the date time stamp contained in them

I need to use python for this. I have tried regex on python but didn't get the output

Code:

*sep2 = '([0-3]?\d)[- \/.](0\d|1[0-2])[- \/.]((19|20)\d\d) ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)'
text2 = text1.split(sep2)
print(text2)*

Input contains paragraphs which are unseparated by date. example of one paragraph:

21.01.2017 09:05:56 abcsdfasklfvd 02.01.2017 09:05:56 afgdsfggv

Expected output:

text2[0] = 21.01.2017 09:05:56 abcsdfasklfvd
text2[1] = 02.01.2017 09:05:56 afgdsfggv

then I want to apply some sorting function based on ascending date which would give

expected output:

sorted[0] = 02.01.2017 09:05:56 afgdsfggv
sorted[1] = 21.01.2017 09:05:56 abcsdfasklfvd

Body:
from datetime import datetime

text = ["21.01.2017 09:05:56 abcsdfasklfvd", "02.01.2017 09:05:56 afgdsfggv"]
sorted(text, key=lambda s: datetime.strptime(s[0:19], '%d.%m.%Y %H:%M:%S'))

If the pattern dd.mm.yyyy hh:mm:ss does not appear inside paragraphs then you can use

text1 = "21.01.2017 09:05:56 abcsdfasklfvd 02.01.2017 09:05:56 afgdsfggv"

text = list()
for d, t in zip(*[iter(re.split(r'(\d+.\d+.\d+ \d+:\d+:\d+)', text1)[1:])]*2):
    text.append(d + t)

sorted(text, key=lambda s: datetime.strptime(s[0:19], '%d.%m.%Y %H:%M:%S'))

def extract(s):
    try:
        return datetime.strptime(s, '%d.%m.%Y %H:%M:%S')
    except (ValueError):
        return datetime.strptime(s, '%d/%m/%Y %H:%M:%S')
sorted(text, key=lambda s: extract(s[0:19]))


问:
Return multiple elements using Lodash _.get?
I have this JavaScript object:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
}
```

<p>I was able to select only one item using Lodash's <code>_.get</code> method.</p>

<pre class="lang-js prettyprint-override"><code>_.get(object, 'categories[0].items[0].image')
// => "path/to/file-1.png"
</code>```

But I need an array with all occurrences, not just from position 0. Something like this:

_.get(object, 'categories[].items[].image')
// => ["path/to/file-1.png", "path/to/file-2.png", "path/to/file-3.png", "path/to/file-4.png", "path/to/file-5.png", "path/to/file-6.png"]
```

Is it possible to do it using Lodash?

If it's not possible, do you have any idea how to implement it?

EDIT: I'm looking for something like _.get from Lodash, where I can supply the "search schema" (path) as string. Obviously I know how to solve this with map, reduce, etc.

答:
Here is my implementation which can handle [] path:

const object = { categories: [ { title: "Category 1", items: [ { title: "Item 1", image: "path/to/file-1.png" }, { title: "Item 2", image: "path/to/file-2.png" }, { title: "Item 3", image: "path/to/file-3.png" } ] }, { title: "Category 2", items: [ { title: "Item 4", image: "path/to/file-4.png" }, { title: "Item 5", image: "path/to/file-5.png" }, { title: "Item 6", image: "path/to/file-6.png" } ] } ] };
const object2 = { categories: { title: "Category 1" } };

function flatGet(object, path) {
  const pathArray = path.split(".");
  while (pathArray.length > 0) {
    let pos = pathArray.shift();
    if (pos.includes("[]")) {
      pos = pos.slice(0, -2);
    }
    if (Array.isArray(object)) {
      object = object.reduce((acc, cur) => acc.concat(cur[pos]), []);
    } else {
      object = object[pos];
    }
  }
  return object;
}

var res = flatGet(object, "categories[].items[].image"); // ["path/to/file-1.png", ...]
var res2 = flatGet(object2, "categories.title"); // "Category 1"
```

<hr>

<p>edited before:</p>

<p>Cause you need to get the <code>images</code> Array, <code>map</code> could help with it. Here is a simple one:</p>

<pre class="lang-js prettyprint-override"><code>_.map(object.categories[0].items, o => _.get(o, 'image'))

// if categories[0].items is not always there, just use another get:

_.map(_.get(object, 'categories[0].items'), o => _.get(o, 'image'))
</code>```

Body:
I have this JavaScript object:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
}

I was able to select only one item using Lodash's _.get method.

_.get(object, 'categories[0].items[0].image')
// => "path/to/file-1.png"

But I need an array with all occurrences, not just from position 0. Something like this:

_.get(object, 'categories[].items[].image')
// => ["path/to/file-1.png", "path/to/file-2.png", "path/to/file-3.png", "path/to/file-4.png", "path/to/file-5.png", "path/to/file-6.png"]

Is it possible to do it using Lodash?

If it's not possible, do you have any idea how to implement it?

EDIT: I'm looking for something like _.get from Lodash, where I can supply the "search schema" (path) as string. Obviously I know how to solve this with map, reduce, etc.

Body:
Here is my implementation which can handle [] path:

const object = { categories: [ { title: "Category 1", items: [ { title: "Item 1", image: "path/to/file-1.png" }, { title: "Item 2", image: "path/to/file-2.png" }, { title: "Item 3", image: "path/to/file-3.png" } ] }, { title: "Category 2", items: [ { title: "Item 4", image: "path/to/file-4.png" }, { title: "Item 5", image: "path/to/file-5.png" }, { title: "Item 6", image: "path/to/file-6.png" } ] } ] };
const object2 = { categories: { title: "Category 1" } };

function flatGet(object, path) {
  const pathArray = path.split(".");
  while (pathArray.length > 0) {
    let pos = pathArray.shift();
    if (pos.includes("[]")) {
      pos = pos.slice(0, -2);
    }
    if (Array.isArray(object)) {
      object = object.reduce((acc, cur) => acc.concat(cur[pos]), []);
    } else {
      object = object[pos];
    }
  }
  return object;
}

var res = flatGet(object, "categories[].items[].image"); // ["path/to/file-1.png", ...]
var res2 = flatGet(object2, "categories.title"); // "Category 1"

edited before:

Cause you need to get the images Array, map could help with it. Here is a simple one:

_.map(object.categories[0].items, o => _.get(o, 'image'))

// if categories[0].items is not always there, just use another get:

_.map(_.get(object, 'categories[0].items'), o => _.get(o, 'image'))


问:
How to get value from form builder as label of trigger?
I'm working on custom control in Orbeon. In form builder, in settings there is a field called buttonName. Its value is supposed to show as a label of button visible in form runner.

I'm moving an old file that supposedly worked on old version of orbeon. I tried changing the way I refer to the value from form builder. Below I show old code, without my changes.

In form builder metadata I have declared input with ref:

```<code><xbl:binding element="fr|custom-input" id="fr-custom-input-binding" xxbl:mode="lhha binding value">
        <!-- Orbeon Form Builder Component Metadata -->
        <metadata xmlns="http://orbeon.org/oxf/xml/form-builder" xmlns:xf="http://www.w3.org/2002/xforms">
...
<control-details>
<xf:input ref="@buttonName">
                    ...
</code>```

Further on, there is a var to that binding

```<code><xf:var name="binding" value="xxf:binding('fr-custom-input-binding')"/>
</code>```

Finally, the reference in form runner:

```<code>                <xf:trigger class="xbl-fr-custom-input-trigger">
...
                    <xf:label value="$binding/@buttonName"></xf:label>
                </xf:trigger>
</code>```

答:
You want to access an attribute on the control itself:

```<code><fr:custom-input buttonName="Your value">
</code>```

This in contract to an attribute that you could have on the element the control is bound to, which is what $binding points to. So $binding/@buttonName is not the right expression to use here. Instead, inside your , you want to have:

```<code><xf:var name="buttonName" xbl:attr="xbl:text=buttonName"/>
</code>```

Then you can refer in XPath to the value of the attribute as $buttonName.

Body:
I'm working on custom control in Orbeon. In form builder, in settings there is a field called buttonName. Its value is supposed to show as a label of button visible in form runner.

I'm moving an old file that supposedly worked on old version of orbeon. I tried changing the way I refer to the value from form builder. Below I show old code, without my changes.

In form builder metadata I have declared input with ref:

<xbl:binding element="fr|custom-input" id="fr-custom-input-binding" xxbl:mode="lhha binding value">

        <metadata xmlns="http://orbeon.org/oxf/xml/form-builder" xmlns:xf="http://www.w3.org/2002/xforms">
...
<control-details>
<xf:input ref="@buttonName">
                    ...

Further on, there is a var to that binding

<xf:var name="binding" value="xxf:binding('fr-custom-input-binding')"/>

Finally, the reference in form runner:

                <xf:trigger class="xbl-fr-custom-input-trigger">
...
                    <xf:label value="$binding/@buttonName"></xf:label>
                </xf:trigger>

Body:
You want to access an attribute on the control itself:

<fr:custom-input buttonName="Your value">

This in contract to an attribute that you could have on the element the control is bound to, which is what $binding points to. So $binding/@buttonName is not the right expression to use here. Instead, inside your , you want to have:

<xf:var name="buttonName" xbl:attr="xbl:text=buttonName"/>

Then you can refer in XPath to the value of the attribute as $buttonName.


问:
JQuery to swap input and select-box data between two or more forms
I'm basically trying to create a 'directions' form with each 'stop' having an address input and a couple of select-box options. I want to be able to 'swap' the forms so that the data from the first 'stop' is swapped with the data from the second 'stop'. The tricky part is that there could be more than two 'stops', so the swap would need to be able to handle swapping stops 3-4, 4-5, 5-6, etc.

Here is the basic form template:

```<code><div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>
<div class="loc">
    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>
</div>
</div>
<div class="swap"><a>swap</a></div>
<div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>
<div class="loc">
    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>
</div>
</code>```

I would like to use JQuery if possible, but am really stumped on how to get started.

Thanks,
Brian

答:
This may not be the best way, but it answers your question:
http://jsfiddle.net/PBfvX/

Note: 0-based indexing means if you want the first and second form, form1=0 and form2=1

ContentLicense: CC BY-SA 3.0

Body:
I'm basically trying to create a 'directions' form with each 'stop' having an address input and a couple of select-box options. I want to be able to 'swap' the forms so that the data from the first 'stop' is swapped with the data from the second 'stop'. The tricky part is that there could be more than two 'stops', so the swap would need to be able to handle swapping stops 3-4, 4-5, 5-6, etc.

Here is the basic form template:

<input type="text" />

    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>

swap

<input type="text" />

    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>

I would like to use JQuery if possible, but am really stumped on how to get started.

Thanks,
Brian


问:
How to modify height of scroll view while ReadMore option at textview in Android?
I'm implemented add “...Read More” and "...Less" at the end of Text View after 2 lines. When I click on read more Scroll-View height will be increased but when I click on less at the end of Text-View I want to less/decrease the height of scroll view. How to manage Scroll View height click on Read More options?

Here is my ExpandableTextView code.

```<code>public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 100;
    private static final String ELLIPSIS = " .....Read More";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();

               // if click on read more trim is false
                if (trim == false)
                {
                    Log.e("", " trim=" + trim);
                }
                // if click on less trim is false
                else if (trim == true) {
                    Log.e("", " trim=" + trim);
                }
            }
        });
    }

    private void setText() {
        super.setText(getDisplayableText(), bufferType);

    }

    private CharSequence getDisplayableText() {

        return trim ? trimmedText : originalText;

    }

    @Override
    public void setText(CharSequence text, BufferType type)
    {

        originalText = text;
        trimmedText = getTrimmedText(text);
        Log.e(""," trimmedText ="+ trimmedText );
        bufferType = type;
        setText();
    }

    private CharSequence getTrimmedText(CharSequence text)
    {
        if (originalText != null && originalText.length() > trimLength)
        {

            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        }
        else
        {

            return originalText;
        }
    }

    public CharSequence getOriginalText()
    {
        return originalText;
    }

    public void setTrimLength(int trimLength)
    {

        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);
        setText();
    }

    public int getTrimLength()
    {

        return trimLength;
    }
}
</code>```

Here is my activity code.

```<code> ExpandableTextView txtRemark = (ExpandableTextView)findViewById(R.id.expandable_text);
        int strRemarkLength = strRemark.length();
        if(strRemarkLength > 100)
        {
            txtRemark.setText(strRemark.concat(" ...Less"));
            Log.e("", " Lesss !!!");

            RelativeLayout.LayoutParams scrollViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 350);
            scrollViewParams.addRule(RelativeLayout.BELOW, txtInspectorname.getId());
            scrollViewParams.addRule(RelativeLayout.RIGHT_OF, relativeLayout.getId());

            scrollView.setFillViewport(true);
            scrollView.setBackgroundColor(Color.parseColor("#00000000"));
            scrollView.setScrollContainer(false);
            scrollView.setLayoutParams(scrollViewParams);

        }
        else
        {
            txtRemark.setText(strRemark);
            Log.e("", "Not Lesss !!!");

            RelativeLayout.LayoutParams scrollViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 100);
            scrollViewParams.addRule(RelativeLayout.BELOW, txtInspectorname.getId());
            scrollViewParams.addRule(RelativeLayout.RIGHT_OF, relativeLayout.getId());

            scrollView.setFillViewport(true);
            scrollView.setBackgroundColor(Color.parseColor("#00000000"));
            scrollView.setScrollContainer(false);
            scrollView.setLayoutParams(scrollViewParams);

        }
</code>```

答:
I don't see the reason to write your own Textview in order to implement readmore future of textview while you can implement it easily by setting the maximum line of the textview programmatically. Use the android Textview and add another textview for readmore below your textview. For example, assume you have a tvReadMore textview below your txtRemark textview. First check if the text for your txtRemark textview is more enough to display the tvReadMore. if so, set the maxLine of your txtRemark to Integer.MAX_VALUE. Take a look at the following sample code

```<code>if(strRemark.length() > 100) { //assuming you want to show the [Read more] for more than 100 characters
   if(tvReadMore.getText().toString().equalsIgnoreCase("Read more")) { //you should set the text of tvReadMore textview to [Read more] in the beginning
       txtRemark.setMaxLines(Integer.MAX_VALUE); //set the maximum line to Maximum integer
       tvReadMore.setText("Show Less")
   } else {
        txtRemark.setMaxLines(3); //set the maximum line to 3
        tvReadMore.setText("Read more")
   }
} else { //if there are no enough characters to show the read more text
   tvReadMore.setVisibility(View.GONE); //hide the read more textview
}
</code>```

I have seen a lot of work arounds to implement the read more feature for textview but, in my opinion, this is the easiest and simplest way so far. The nice thing about this is, it works for both simple textview and a textview in a recyclerview.
if you want to add three dots at the end of your text, when there are more lines hidden, you can add

```<code> android::ellipsize(end)
</code>```

to your tvTitle textview.

Body:
I'm implemented add “...Read More” and "...Less" at the end of Text View after 2 lines. When I click on read more Scroll-View height will be increased but when I click on less at the end of Text-View I want to less/decrease the height of scroll view. How to manage Scroll View height click on Read More options?

Here is my ExpandableTextView code.

public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 100;
    private static final String ELLIPSIS = " .....Read More";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();

               // if click on read more trim is false
                if (trim == false)
                {
                    Log.e("", " trim=" + trim);
                }
                // if click on less trim is false
                else if (trim == true) {
                    Log.e("", " trim=" + trim);
                }
            }
        });
    }

    private void setText() {
        super.setText(getDisplayableText(), bufferType);

    }

    private CharSequence getDisplayableText() {

        return trim ? trimmedText : originalText;

    }

    @Override
    public void setText(CharSequence text, BufferType type)
    {

        originalText = text;
        trimmedText = getTrimmedText(text);
        Log.e(""," trimmedText ="+ trimmedText );
        bufferType = type;
        setText();
    }

    private CharSequence getTrimmedText(CharSequence text)
    {
        if (originalText != null && originalText.length() > trimLength)
        {

            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        }
        else
        {

            return originalText;
        }
    }

    public CharSequence getOriginalText()
    {
        return originalText;
    }

    public void setTrimLength(int trimLength)
    {

        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);
        setText();
    }

    public int getTrimLength()
    {

        return trimLength;
    }
}

Here is my activity code.

 ExpandableTextView txtRemark = (ExpandableTextView)findViewById(R.id.expandable_text);
        int strRemarkLength = strRemark.length();
        if(strRemarkLength > 100)
        {
            txtRemark.setText(strRemark.concat(" ...Less"));
            Log.e("", " Lesss !!!");

            RelativeLayout.LayoutParams scrollViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 350);
            scrollViewParams.addRule(RelativeLayout.BELOW, txtInspectorname.getId());
            scrollViewParams.addRule(RelativeLayout.RIGHT_OF, relativeLayout.getId());

            scrollView.setFillViewport(true);
            scrollView.setBackgroundColor(Color.parseColor("#00000000"));
            scrollView.setScrollContainer(false);
            scrollView.setLayoutParams(scrollViewParams);

        }
        else
        {
            txtRemark.setText(strRemark);
            Log.e("", "Not Lesss !!!");

            RelativeLayout.LayoutParams scrollViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 100);
            scrollViewParams.addRule(RelativeLayout.BELOW, txtInspectorname.getId());
            scrollViewParams.addRule(RelativeLayout.RIGHT_OF, relativeLayout.getId());

            scrollView.setFillViewport(true);
            scrollView.setBackgroundColor(Color.parseColor("#00000000"));
            scrollView.setScrollContainer(false);
            scrollView.setLayoutParams(scrollViewParams);

        }

Body:
I don't see the reason to write your own Textview in order to implement readmore future of textview while you can implement it easily by setting the maximum line of the textview programmatically. Use the android Textview and add another textview for readmore below your textview. For example, assume you have a tvReadMore textview below your txtRemark textview. First check if the text for your txtRemark textview is more enough to display the tvReadMore. if so, set the maxLine of your txtRemark to Integer.MAX_VALUE. Take a look at the following sample code

if(strRemark.length() > 100) { //assuming you want to show the [Read more] for more than 100 characters
   if(tvReadMore.getText().toString().equalsIgnoreCase("Read more")) { //you should set the text of tvReadMore textview to [Read more] in the beginning
       txtRemark.setMaxLines(Integer.MAX_VALUE); //set the maximum line to Maximum integer
       tvReadMore.setText("Show Less")
   } else {
        txtRemark.setMaxLines(3); //set the maximum line to 3
        tvReadMore.setText("Read more")
   }
} else { //if there are no enough characters to show the read more text
   tvReadMore.setVisibility(View.GONE); //hide the read more textview
}

I have seen a lot of work arounds to implement the read more feature for textview but, in my opinion, this is the easiest and simplest way so far. The nice thing about this is, it works for both simple textview and a textview in a recyclerview.
if you want to add three dots at the end of your text, when there are more lines hidden, you can add

 android::ellipsize(end)

to your tvTitle textview.


问:
Formula field based on Picklist value
I need to create a formula field based on another picklist Field.Based on the value available in picklist need to populate same value in formula field.Here in picklist field contains 30values.Please suggest how to implement this</p>

答:
Try this

```<code>TEXT(Picklist field API Name)
</code>```

Or Check this
https://help.salesforce.com/articleView?err=1&id=tips_for_using_picklist_formula_fields.htm&type=5

Title: Formula field based on Picklist value

Body:
Try this

TEXT(Picklist field API Name)

Or Check this
https://help.salesforce.com/articleView?err=1&id=tips_for_using_picklist_formula_fields.htm&type=5


问:
executing python scripts from a server
I have some python scripts on a server machine and i want to run those programs from a different machine on the same network. is there any way to run those programs remotely using a path somewhat like "http(or ftp):/10.10.5.18/path/script.py"

i am at an internship and i have made some basic python programs working with csv files, txt files, apis, gmplot, databases, mysql, pymysql, sqlite etc.. We have installed IDLE on the server machine and also have put all the pythhon scripts on it. now, to prevent the company's employees from coming to me again and again to get their work done, i want to give them links to the programs so that they can do their tasks themselves. is that possible in a simple way?

答:
You can run python scripts remotely with ssh, just like any other command on a server. For example, I put a couple of simple scripts to do addition and multipication on an account of mine on a server:

Remote file ~/steve/scripts/add.py:

```<code>#!/usr/bin/env python

import sys

name, p1, p2 = sys.argv[1:4]
sum = int(p1) + int(p2)
print("Hi {}, {} + {} = {}".format(name, p1, p2, sum))
</code>```

Remote file ~/steve/scripts/mult.py

```<code>#!/usr/bin/env python

import sys

name, p1, p2 = sys.argv[1:4]
product = int(p1) * int(p2)
print("Hi {}, {} * {} = {}".format(name, p1, p2, product))
</code>```

And then you just run these via ssh, supplying the proper arguments just like if you were calling the scripts locally:

Command executed locally:

```<code>ssh app1.unstable "~/steve/scripts/add.py" Joe 24 100
</code>```

Result:

```<code>Hi Joe, 24 + 100 = 124
</code>```

Command executed locally:

```<code>ssh app1.unstable "~/steve/scripts/mult.py" Kathy 12 24
</code>```

Result:

```<code>Hi Kathy, 12 * 24 = 288
</code>```

The results show up in your terminal just like if you were running the scripts locally.  You could redirect the output to a file, or whatever.

Title: executing python scripts from a server

Body:
You can run python scripts remotely with ssh, just like any other command on a server. For example, I put a couple of simple scripts to do addition and multipication on an account of mine on a server:

Remote file ~/steve/scripts/add.py:

#!/usr/bin/env python

import sys

name, p1, p2 = sys.argv[1:4]
sum = int(p1) + int(p2)
print("Hi {}, {} + {} = {}".format(name, p1, p2, sum))

Remote file ~/steve/scripts/mult.py

#!/usr/bin/env python

import sys

name, p1, p2 = sys.argv[1:4]
product = int(p1) * int(p2)
print("Hi {}, {} * {} = {}".format(name, p1, p2, product))

And then you just run these via ssh, supplying the proper arguments just like if you were calling the scripts locally:

Command executed locally:

ssh app1.unstable "~/steve/scripts/add.py" Joe 24 100

Result:

Hi Joe, 24 + 100 = 124

Command executed locally:

ssh app1.unstable "~/steve/scripts/mult.py" Kathy 12 24

Result:

Hi Kathy, 12 * 24 = 288

The results show up in your terminal just like if you were running the scripts locally.  You could redirect the output to a file, or whatever.


问:
Why I'm getting java.lang.IndexOutOfBoundsException when I try to get an item of jsonArray?
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

```<code>val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}
</code>```

I have problem at this line:

```<code>val obj = array.get(i).asJsonObject
</code>```

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

答:
You are using remove method inside the for loop iteration which is dynamically change array size.

If you need to remove only one item then refer @Jeeva's answer.

If you want to remove multiple positions from list at a time, you have to refer below method to remove item from array, .

```<code>val removePositions = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
   //array.remove(obj)
   //mNames.removeAt(position)
   removePositions.add(position)
   //Singleton.array = array
   //updateNames(mNames)
  }

  for (i in 0 until removePositions.size()) {
    array.remove(removePositions[i])
    mNames.remove(removePositions[i])
  }
  Singleton.array = array
  updateNames(mNames)
}
</code>```

Body:
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}

I have problem at this line:

val obj = array.get(i).asJsonObject

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

Body:
You are using remove method inside the for loop iteration which is dynamically change array size.

If you need to remove only one item then refer @Jeeva's answer.

If you want to remove multiple positions from list at a time, you have to refer below method to remove item from array, .

val removePositions = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
   //array.remove(obj)
   //mNames.removeAt(position)
   removePositions.add(position)
   //Singleton.array = array
   //updateNames(mNames)
  }

  for (i in 0 until removePositions.size()) {
    array.remove(removePositions[i])
    mNames.remove(removePositions[i])
  }
  Singleton.array = array
  updateNames(mNames)
}


问:
Is there a non trivial way to visit every red node in a red black tree?
The obvious solution to counting the number of red nodes in a red-black tree is to do a simple recursion that visits every node and counts the node if it is indeed red. But is there any property of red-black tress you can exploit to this faster than O(n) time? I cannot figure out what property could make this operation quicker.</p>

答:
There is no property of a generic red-black tree that would allow you to count red nodes in other than O(n) time. If the number of red nodes is of extreme importance for some reason you could make the count a property of the tree itself and keep track of manipulations during the insert/remove rebalance.

Even the theoretical possibility of skipping the node color check on children of red nodes (which could be done since those children have to be black in order for the tree to be valid) isn't reasonable since it is likely the checks in that case would be no simpler than directly checking node colors. And those black children still have to be visited in order for the examination to continue down the tree.


问:
I have a two node js servers. second server is for the socket connection. How do I establish a connection between these two servers?
I'm setting up another nodejs server for the socketio, which is index.js. so I have two servers one is app.js and other one is index.js. so how do i establish a connection between these two servers?</p>

答:
Can you please explain your problem in detail.And second thing, I don't understand why you want to establish two servers.Because you can always connect socket.io using your Node server.The code for it is below:

```<code>//Server side code
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
        console.log(data);
  });
});

//Client Side code
var socket = io.connect();
socket.emit('my other event', {
     data : 'Hello'
});
</code>```

This is very basic example for client-server communication using socket.io

I hope you will get your answer.

Body:
Can you please explain your problem in detail.And second thing, I don't understand why you want to establish two servers.Because you can always connect socket.io using your Node server.The code for it is below:

//Server side code
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
        console.log(data);
  });
});

//Client Side code
var socket = io.connect();
socket.emit('my other event', {
     data : 'Hello'
});

This is very basic example for client-server communication using socket.io

I hope you will get your answer.


问:
Only when all statuses the same than return result
I am selecting Q_GRADEBOOK_ID if all the status against Q_GRADEBOOK_ID is 488 than return Q_GRADEBOOK_ID otherwise return empty

```<code>TABLE Q_GB_CAT_SCORE
---------------------------------------------------------
 Q_GRADEBOOK_ID | PERSON_ID | STATUS | Q_GRADEBOOK_CAT_ID
      1         |     1     |  488   |       1
      1         |     1     |  488   |       2
      1         |     2     |  488   |       1
      2         |     2     |  486   |       1
      2         |     2     |  488   |       2
</code>```

My Query

```<code> SELECT
 DISTINCT
 Q_GRADEBOOK_ID
 FROM
 Q_GB_CAT_SCORE WHERE
 STATUS IN ('488')
</code>```

This query return this result

```<code>Q_GRADEBOOK_ID
      1
      2
</code>```

Expected Result

```<code>Q_GRADEBOOK_ID
      1
</code>```

I expect it because Q_GRADEBOOK_ID 1 return because against Q_GRADEBOOK_ID 1 all the status is 488.

答:
You can exclude ID with different status:</p>

```<code>SELECT distinct
 Q_GRADEBOOK_ID
  FROM Q_GB_CAT_SCORE
 WHERE Q_GRADEBOOK_ID not in
        (select distinct Q_GRADEBOOK_ID FROM Q_GB_CAT_SCORE WHERE status <> '488')
</code>```

Body:
I am selecting Q_GRADEBOOK_ID if all the status against Q_GRADEBOOK_ID is 488 than return Q_GRADEBOOK_ID otherwise return empty

TABLE Q_GB_CAT_SCORE
---------------------------------------------------------
 Q_GRADEBOOK_ID | PERSON_ID | STATUS | Q_GRADEBOOK_CAT_ID
      1         |     1     |  488   |       1
      1         |     1     |  488   |       2
      1         |     2     |  488   |       1
      2         |     2     |  486   |       1
      2         |     2     |  488   |       2

My Query

 SELECT
 DISTINCT
 Q_GRADEBOOK_ID
 FROM
 Q_GB_CAT_SCORE WHERE
 STATUS IN ('488')

This query return this result

Q_GRADEBOOK_ID
      1
      2

Expected Result

Q_GRADEBOOK_ID
      1

I expect it because Q_GRADEBOOK_ID 1 return because against Q_GRADEBOOK_ID 1 all the status is 488.

Body:
You can exclude ID with different status:

SELECT distinct
 Q_GRADEBOOK_ID
  FROM Q_GB_CAT_SCORE
 WHERE Q_GRADEBOOK_ID not in
        (select distinct Q_GRADEBOOK_ID FROM Q_GB_CAT_SCORE WHERE status <> '488')


问:
How to trim only white space but not \n in Java
I have a string like

String str = " hello world\n "

when I call str.trim(),
it returns

"hello world"

However, I need the string looks like

"hello world\n"

How could I do it for only remove leading and trailing white space in a string?

答:
You have to escape the backslash so it gets treated like a literal:

```<code>String str = " hello world\\n ";
System.out.println(str.trim());
</code>```

Output

hello world\n

Body:
You have to escape the backslash so it gets treated like a literal:

String str = " hello world\\n ";
System.out.println(str.trim());

Output

hello world\n


问:
Multiple java processes in Tomcat
I am working on a web-based application which is deployed in the Tomcat server. In our local dev enviroemt, when we start the Tomcat server it spawns only one java process which keeps running. However, an issue has been reported in production where the CPU usage for java process has gone up and there are multiple java processes which have  been spawned.

There is no other java application running, so this must have been spawned from Tomcat itself. What is the reason that in our development enviroment there is only one java process while in production multiple java processes have been spawned by Tomcat and how to correct it.

Regards,
    Dev

答:
Unlike Apache HTTPD, Tomcat doesn't spawn processes on its own (it uses multiple threads to serve multiple clients) so you should look elsewhere. For example, how do you deploy your application to the Tomcat. Could it be something like a buggy deployment script?

Also, what other applications run on this Tomcat container?

Title: Multiple java processes in Tomcat


问:
is it possible to get another view's width in flutter?
I want to make this design , can we get another widget's width ?

As per shown in image I want to make underline below the Text widget and width of Text is wrap so underline width is also change according to Text name.

答:
Thanks for your contribution guys, as I am beginner in flutter UI design.And have find the easiest solution for the above question.yes its looks so easy when I have found solutions.
Thanks

the solutions is :

```<code>Container(
          decoration: BoxDecoration(
            border: BorderDirectional(
              bottom: BorderSide(
                color: Colors.white,
                width: 2,
                style: BorderStyle.solid
              )
            )
          ),
          child: Text('Any text',
              softWrap: true,
              style: YourClassName.of(context)
                  .commonTextStyle(FontWeight.w600, 0xffffffff, 0.4, 16)),
        )
</code>```

Body:
Thanks for your contribution guys, as I am beginner in flutter UI design.And have find the easiest solution for the above question.yes its looks so easy when I have found solutions.
Thanks

the solutions is :

Container(
          decoration: BoxDecoration(
            border: BorderDirectional(
              bottom: BorderSide(
                color: Colors.white,
                width: 2,
                style: BorderStyle.solid
              )
            )
          ),
          child: Text('Any text',
              softWrap: true,
              style: YourClassName.of(context)
                  .commonTextStyle(FontWeight.w600, 0xffffffff, 0.4, 16)),
        )


问:
regex pattern not fit well for code like assignment
i am trying to use a regular expression to match expression like code assignment
for example:

```<code>"k=++g677"
"k=--j77"
"k=++gfrf677frfr"
</code>```

i've tried:

```<code>([a-zA-Z])([a-zA-Z]|\d)*[=][+][+]|[-][-]|[*][*]|[\/][\/]([\d]*|([a-zA-Z]([a-zA-Z]\d)*))
</code>```

but it's seemds to match also things like

```<code>"k++"
"k=++@ff"
</code>```

can u help?

答:
You may use

```<code>^[a-zA-Z_][\da-zA-Z_]*=([+*\/-])\1[a-zA-Z_][\da-zA-Z_]*$
</code>```

Or, if you need to capture each detail into a separate group:

```<code>^([a-zA-Z_][\da-zA-Z_]*)(=)(([+*\/-])\4)([a-zA-Z_][\da-zA-Z_]*)$
</code>```

See this regex demo and its graph:

Details

^ - start of string

[a-zA-Z_] - an uppercase ASCII letter or underscore

[a-zA-Z\d_]*  - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)

= - an equal sign

([+*\/-])\1 - +, *, / or - and then exactly 1 the same char

[a-zA-Z_] - an ASCII letter or _

[a-zA-Z\d_]* - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)

$ - end of string.

Body:
i am trying to use a regular expression to match expression like code assignment
for example:

"k=++g677"
"k=--j77"
"k=++gfrf677frfr"

i've tried:

([a-zA-Z])([a-zA-Z]|\d)*[=][+][+]|[-][-]|[*][*]|[\/][\/]([\d]*|([a-zA-Z]([a-zA-Z]\d)*))

but it's seemds to match also things like

"k++"
"k=++@ff"

can u help?

Body:
You may use

^[a-zA-Z_][\da-zA-Z_]*=([+*\/-])\1[a-zA-Z_][\da-zA-Z_]*$

Or, if you need to capture each detail into a separate group:

^([a-zA-Z_][\da-zA-Z_]*)(=)(([+*\/-])\4)([a-zA-Z_][\da-zA-Z_]*)$

See this regex demo and its graph:

Details

^ - start of string

[a-zA-Z_] - an uppercase ASCII letter or underscore

[a-zA-Z\d_]*  - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)

= - an equal sign

([+*\/-])\1 - +, *, / or - and then exactly 1 the same char

[a-zA-Z_] - an ASCII letter or _

[a-zA-Z\d_]* - 0 or more alphanumerics / _ (replace with \w if it is not Unicode aware by default)

$ - end of string.


问:
WPF Noob Seeking Guidance
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

```<code><ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>
</code>```

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

```<code>public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}
</code>```

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

答:
I've figured out the problem, but could use some guidance on why it was occuring. When I removed the following nodes from the XAML, it works correctly:

```<code><ItemsPanelTemplate>
    <StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</code>```

Why was it counting that template among the items collection? My understanding was that this was simply the container item it chose to add each data template to.

Title: WPF Noob Seeking Guidance

Body:
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

<ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

Body:
I've figured out the problem, but could use some guidance on why it was occuring. When I removed the following nodes from the XAML, it works correctly:

<ItemsPanelTemplate>
    <StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>

Why was it counting that template among the items collection? My understanding was that this was simply the container item it chose to add each data template to.