问:
How to Implement scrollIntoView in a horizontal view table for testimony
I'm sorry maybe the title make you confused, but it exactly what the title said I want to make a testimony card using table as based but I almost finish it but i can't do the final touch for it, let say I have a pointer so when I click the pointer the card will swipe to the next card but it seems I'm confused as how to implement it using javascript. I get a hunch that I can use array of child for it and move in based on the index but the card testimony still won't move

I read some topic, but the near to what I want is answer in here: Scroll smoothly by 100px horizontally

but I confused as how to implement it.

this is my code:

            var slideIndex = 1;
            showSlides(slideIndex);

            // Thumbnail image controls
            function currentTestimony(n) {
                showSlides(slideIndex = n);
            }

            function showSlides(n) {
                var i;
                var slides = document.getElementsByClassName("slider-item");
                var pointers = document.getElementsByClassName("pointer");
                if (n > slides.length) {
                    slideIndex = 1
                }

                if (n < 1) {
                    slideIndex = slides.length
                }

//                for (i = 0; i < slides.length; i++) {
//                    slides[i].getElementsById('testimony-3').scrollIntoView()
//                }

                for (i = 0; i < pointers.length; i++) {
                    pointers[i].className = pointers[i].className.replace(" active", "");
                }

                pointers[slideIndex-1].className += " active";
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    scroll-behavior: smooth;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}</code>```

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

```

I feel I'm already near the answer but I can't quite know how to solved this, can someone help me to solve this problem?

答:
Here is a more Universal Answer that works on a fixed size. You can just change sizing into percentage to make it work for different screen sizes.

I've worked it out on VS Code. You can just copy and paste it and run.

```<code>   <!DOCTYPE html>
   <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            *{
                box-sizing: border-box;
            }

            .main-container {
                width: 100%;
                max-width: 1200px;
                overflow: hidden;
                margin: 0 auto;
                margin-bottom: 20px;
            }

            table.card-space{
                width: 100%;
                height: auto;
                min-height: 400px;
                position: relative;
                white-space: nowrap;
                margin: 0;
                padding: 0;
            }

            tr.card-space_container{
                width: 100%;
                left: 0; /* Initial Position */
                position: relative;

                /* Make a Smooth Left Transition */
                transition: left .5s ease;
                padding: 15px;
                margin: 0;
                padding: 0;
            }

            td.card{
                box-sizing: border-box;
                margin: 0;
                width: 400px;
                min-height: 390px;
                margin: 0;
                position: relative;
            }

            .card-space .card .content{
                width: 400px;
                min-height: 100%;
                background-color: #f5f5f5;
                min-height: 390px;
                padding: 15px;
            }

            .pointer-space{
                text-align: center;

                width: 100%;
                max-width: 1200px;
                margin: 0 auto;
            }

            .pointer-space .pointer {
                cursor: pointer;
                height: 15px;
                width: 15px;
                margin: 0 2px;
                background-color: #bbb;
                border-radius: 50%;
                display: inline-block;
                transition: background-color 0.6s ease;
            }

            .pointer-space .pointer:hover {
                background-color: #3b73c5;
            }

        </style>
    </head>
    <body>
        <div class="main-container">
            <table class="card-space">
                <tr class="card-space_container" id="card-space_container">
                    <td class="card">
                        <div class="content">
                            <h1>Card1</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card2</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card3</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card4</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card5</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card6</h1>
                        </div>
                    </td>
                </tr>
            </table>
        </div>

        <!-- The pointers/circles -->
        <div class="pointer-space">
        <span class="pointer" data-index="0"></span>
        <span class="pointer" data-index="1"></span>
        <span class="pointer" data-index="2"></span>
        <span class="pointer" data-index="3"></span>
        <span class="pointer" data-index="4"></span>
        <span class="pointer" data-index="5"></span>
        </div>

        <script>
        (function(){
            // Get all the Pointers
            var PointerList = document.querySelectorAll(".pointer");

            //  Get the Card container
            var container = document.getElementById("card-space_container");

            PointerList.forEach(function(pointer){
                pointer.addEventListener('click', function(){

                    //  First get the index represented by each pointer
                    var i = this.getAttribute('data-index');

                    //  Summary:
                    //      Then Calculate the position to which card-space_container must be set.
                    //  examples:
                    //      -If the index returned by a pointer is 0, then 0 x -40 = 0; so the position is set to 0px.
                    //      -If the pointer return index as 1, then 1  x -400 = -400%;
                    //      - etc...
                    container.style.left = (i * (-400)).toString().concat('px');
                });
            });
        })();
        </script>
    </body>
    </html>
</code>```

Body:
I'm sorry maybe the title make you confused, but it exactly what the title said I want to make a testimony card using table as based but I almost finish it but i can't do the final touch for it, let say I have a pointer so when I click the pointer the card will swipe to the next card but it seems I'm confused as how to implement it using javascript. I get a hunch that I can use array of child for it and move in based on the index but the card testimony still won't move

I read some topic, but the near to what I want is answer in here: Scroll smoothly by 100px horizontally

but I confused as how to implement it.

this is my code:

            var slideIndex = 1;
            showSlides(slideIndex);

            // Thumbnail image controls
            function currentTestimony(n) {
                showSlides(slideIndex = n);
            }

            function showSlides(n) {
                var i;
                var slides = document.getElementsByClassName("slider-item");
                var pointers = document.getElementsByClassName("pointer");
                if (n > slides.length) {
                    slideIndex = 1
                }

                if (n < 1) {
                    slideIndex = slides.length
                }

//                for (i = 0; i < slides.length; i++) {
//                    slides[i].getElementsById('testimony-3').scrollIntoView()
//                }

                for (i = 0; i < pointers.length; i++) {
                    pointers[i].className = pointers[i].className.replace(" active", "");
                }

                pointers[slideIndex-1].className += " active";
            }

@import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');

#dark-slider-testimonial .card{
    background-color: #f5f7fb;
    border-radius: 20px;
    width: 380px;
    height: 380px;
    margin: 0% 32px;
    padding: 20px;
    display: inline-table;
}

/*
    ===================================================================
    First Table
    ===================================================================
*/
#dark-slider-testimonial {
    border-radius: 20px;
    margin: 20px auto;
    padding: 5%;
    width: 100%;
    scroll-behavior: smooth;
}

#dark-slider-testimonial .container{
    width: 100%;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
}

#dark-slider-testimonial .container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

#dark-slider-testimonial table {
    font-family: 'Nunito', sans-serif;
    width: 100%;
    font-size: 0.8em;
    color: #1d3962;
    border: none;
    border-top: none;
}

#dark-slider-testimonial tr{
    text-align: left;
}

#dark-slider-testimonial td{
    text-align: left;
    scroll-snap-align: start;
}

#dark-slider-testimonial .testimony-name{
    font-size: 1.6em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-title{
    font-size: 1.4em;
    font-weight: bold;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-subtitle{
    font-size: 1.2em;
    font-weight: normal;
    color: #7E94B3;
    line-height: 1.7em;
}

#dark-slider-testimonial .testimony-desc{
    font-size: 1.2em;
    font-weight: normal;
    color: #1D3962;
    line-height: 1.7em;
}

#dark-slider-testimonial .pointer {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

#dark-slider-testimonial .active,
#dark-slider-testimonial .pointer:hover {
    background-color: #3b73c5;
}

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

                                        name

                                        title

                                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aspernatur eveniet harum aperiam autem ab modi, impedit culpa, obcaecati repellendus ipsa nulla repudiandae, illo consequatur. Eum fugiat explicabo voluptas numquam doloremque.

I feel I'm already near the answer but I can't quite know how to solved this, can someone help me to solve this problem?

Body:
Here is a more Universal Answer that works on a fixed size. You can just change sizing into percentage to make it work for different screen sizes.

I've worked it out on VS Code. You can just copy and paste it and run.

   <!DOCTYPE html>
   <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            *{
                box-sizing: border-box;
            }

            .main-container {
                width: 100%;
                max-width: 1200px;
                overflow: hidden;
                margin: 0 auto;
                margin-bottom: 20px;
            }

            table.card-space{
                width: 100%;
                height: auto;
                min-height: 400px;
                position: relative;
                white-space: nowrap;
                margin: 0;
                padding: 0;
            }

            tr.card-space_container{
                width: 100%;
                left: 0; /* Initial Position */
                position: relative;

                /* Make a Smooth Left Transition */
                transition: left .5s ease;
                padding: 15px;
                margin: 0;
                padding: 0;
            }

            td.card{
                box-sizing: border-box;
                margin: 0;
                width: 400px;
                min-height: 390px;
                margin: 0;
                position: relative;
            }

            .card-space .card .content{
                width: 400px;
                min-height: 100%;
                background-color: #f5f5f5;
                min-height: 390px;
                padding: 15px;
            }

            .pointer-space{
                text-align: center;

                width: 100%;
                max-width: 1200px;
                margin: 0 auto;
            }

            .pointer-space .pointer {
                cursor: pointer;
                height: 15px;
                width: 15px;
                margin: 0 2px;
                background-color: #bbb;
                border-radius: 50%;
                display: inline-block;
                transition: background-color 0.6s ease;
            }

            .pointer-space .pointer:hover {
                background-color: #3b73c5;
            }

        </style>
    </head>
    <body>
        <div class="main-container">
            <table class="card-space">
                <tr class="card-space_container" id="card-space_container">
                    <td class="card">
                        <div class="content">
                            <h1>Card1</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card2</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card3</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card4</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card5</h1>
                        </div>
                    </td>
                    <td class="card">
                        <div class="content">
                            <h1>Card6</h1>
                        </div>
                    </td>
                </tr>
            </table>
        </div>

        <!-- The pointers/circles -->
        <div class="pointer-space">
        <span class="pointer" data-index="0"></span>
        <span class="pointer" data-index="1"></span>
        <span class="pointer" data-index="2"></span>
        <span class="pointer" data-index="3"></span>
        <span class="pointer" data-index="4"></span>
        <span class="pointer" data-index="5"></span>
        </div>

        <script>
        (function(){
            // Get all the Pointers
            var PointerList = document.querySelectorAll(".pointer");

            //  Get the Card container
            var container = document.getElementById("card-space_container");

            PointerList.forEach(function(pointer){
                pointer.addEventListener('click', function(){

                    //  First get the index represented by each pointer
                    var i = this.getAttribute('data-index');

                    //  Summary:
                    //      Then Calculate the position to which card-space_container must be set.
                    //  examples:
                    //      -If the index returned by a pointer is 0, then 0 x -40 = 0; so the position is set to 0px.
                    //      -If the pointer return index as 1, then 1  x -400 = -400%;
                    //      - etc...
                    container.style.left = (i * (-400)).toString().concat('px');
                });
            });
        })();
        </script>
    </body>
    </html>


来源: stackexchange

问:
setInterval on a for loop?
```<code>for (var i=list.length; i>=0; i--){
    //do something....
}
</code>```

I want to use a setInterval to make this process take 1 whole min no matter how many items are in the list. So if there are 10 items it would trigger every 6sec, 30items, every two seconds, etc.

Thanks for any help!

答:
```<code>var totalItem = list.length;
setInterval(function(){ alert('');}, 60000/totalItem);
</code>```

ContentLicense: CC BY-SA 3.0

Title: setInterval on a for loop?

Body:
for (var i=list.length; i>=0; i--){
    //do something....
}

I want to use a setInterval to make this process take 1 whole min no matter how many items are in the list. So if there are 10 items it would trigger every 6sec, 30items, every two seconds, etc.

Thanks for any help!


问:
Can openssh be installed on MSYS?
I'm using MSYS in windows 7 and now i need it to provide ssh server service. can openssh be installed in msys like it is in cygwin?

i can find ssh in /msys/bin, and it can be used as ssh client. but no server seems to be installed. how can i install one? i googled a lot but almost every theads leads to openssh in cygwin, that does not apply to my situation.

i compared cygwin and msys and decide to use msys. We need to run some applications both built and supposed to be ran in windows.

what i've tried:

```<code>mingw-get install mysys-openssh

test@WIN-L3L622JBT6G ~
$ mingw-get install msys-openssh
install: openssh-5.4p1-1-msys-1.0.13-bin.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-bin.tar.
install: openssh-5.4p1-1-msys-1.0.13-doc.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-doc.tar.
install: openssh-5.4p1-1-msys-1.0.13-lic.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-lic.tar.

test@WIN-L3L622JBT6G ~
$ openssh
sh: openssh: command not found
</code>```

the package seems to be installed but i don't know how to find the service. do i need to link it or modify the profile?

答: Msys is outdated. Use Msys2, which does support sshd: https://www.booleanworld.com/get-unix-linux-environment-windows-msys2/</p>

Title: Can openssh be installed on MSYS?

Body:
I'm using MSYS in windows 7 and now i need it to provide ssh server service. can openssh be installed in msys like it is in cygwin?

i can find ssh in /msys/bin, and it can be used as ssh client. but no server seems to be installed. how can i install one? i googled a lot but almost every theads leads to openssh in cygwin, that does not apply to my situation.

i compared cygwin and msys and decide to use msys. We need to run some applications both built and supposed to be ran in windows.

what i've tried:

mingw-get install mysys-openssh

test@WIN-L3L622JBT6G ~
$ mingw-get install msys-openssh
install: openssh-5.4p1-1-msys-1.0.13-bin.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-bin.tar.
install: openssh-5.4p1-1-msys-1.0.13-doc.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-doc.tar.
install: openssh-5.4p1-1-msys-1.0.13-lic.tar.lzm
 installing openssh-5.4p1-1-msys-1.0.13-lic.tar.

test@WIN-L3L622JBT6G ~
$ openssh
sh: openssh: command not found

the package seems to be installed but i don't know how to find the service. do i need to link it or modify the profile?

ContentLicense: CC BY-SA 4.0


问:
Why does golang use parentheses for byte slice and brackets for string slice?
I've always wondered why in golang you create a slice of bytes using parentheses:

[]byte("foo")
```

<p>While creating a slice of strings using bracket notation:</p>

<pre class="lang-golang prettyprint-override"><code>[]string{"foo", "bar"}
</code>```

Are parentheses used just because the expression expects a single value (e.g. the string "foo"), and so the parentheses are used as a 'grouping' syntax?

Note: the use of 'group' or 'grouping' to define this behaviour is very likely incorrect on my part, but I don't have a better word to use off the top of my head.

I presumed so because golang also use parentheses in a grouping sense for things like type asserting i.(T) and for pointer dereferencing (*p).z.

答:
You are getting this wrong.

[]byte("any_string") is actually type conversion from string type to []byte (slice type for byte) and its return type is []byte.

[]string{"string0", "string1", ...} is actually a slice of strings "string0", "string1", ...

Body:
I've always wondered why in golang you create a slice of bytes using parentheses:

[]byte("foo")

While creating a slice of strings using bracket notation:

[]string{"foo", "bar"}

Are parentheses used just because the expression expects a single value (e.g. the string "foo"), and so the parentheses are used as a 'grouping' syntax?

Note: the use of 'group' or 'grouping' to define this behaviour is very likely incorrect on my part, but I don't have a better word to use off the top of my head.

I presumed so because golang also use parentheses in a grouping sense for things like type asserting i.(T) and for pointer dereferencing (*p).z.


问:
remove the textfield on button click not working reactjs
I have multiple date textfield with close button, on clicking on close(x) should delete the textfield,
But not working,( remove the textfield on clicking on close button )
Here is my codelink https://codesandbox.io/s/strange-http-zhj4f</p>

答:
Try something like this. Make sure you pass the date into the method in you X button. like this

onClick={() => this.textareaHandler(datevalue)}

Here is a working code

```<code>import React from "react";
import DatePicker from "react-date-picker";

class AddDate extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      closedatearr: ["12-02-2020", "19-02-2020"]
    };
  }

  buttonHanlder = value => {
    var dateformat = [
      ("0" + value.getDate()).slice(-2) +
        "-" +
        ("0" + (value.getMonth() + 1)).slice(-2) +
        "-" +
        value.getFullYear()
    ];
    this.setState(prevState => ({
      closedatearr: [...prevState.closedatearr, ...dateformat]
    }));
  };

  textareaHandler = val => {
    const { closedatearr } = this.state;
    let removeval = closedatearr.filter(item => item !== val);
    this.setState({
      closedatearr: removeval
    });
  };

  render() {
    const { closedatearr } = this.state;
    return (
      <React.Fragment>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            <label htmlFor="sortorder" className="floatLeft label2">
              Select Date
            </label>
          </div>
        </div>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            <DatePicker
              locale="en-GB"
              onChange={value => {
                this.setState({ closedate: value }, () => {
                  this.buttonHanlder(value);
                });
              }}
              value={new Date()}
            />
          </div>
        </div>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            {closedatearr.map((datevalue, i) => {
              return (
                <div className="text-content" key={i}>
                  <input type="text" value={datevalue} className="inputfield" />
                  <button
                    type="button"
                    onClick={() => this.textareaHandler(datevalue)}
                  >
                    X
                  </button>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ height: "30px" }} />
      </React.Fragment>
    );
  }
}

export default AddDate;
</code>```

Body:
Try something like this. Make sure you pass the date into the method in you X button. like this

onClick={() => this.textareaHandler(datevalue)}

Here is a working code

import React from "react";
import DatePicker from "react-date-picker";

class AddDate extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      closedatearr: ["12-02-2020", "19-02-2020"]
    };
  }

  buttonHanlder = value => {
    var dateformat = [
      ("0" + value.getDate()).slice(-2) +
        "-" +
        ("0" + (value.getMonth() + 1)).slice(-2) +
        "-" +
        value.getFullYear()
    ];
    this.setState(prevState => ({
      closedatearr: [...prevState.closedatearr, ...dateformat]
    }));
  };

  textareaHandler = val => {
    const { closedatearr } = this.state;
    let removeval = closedatearr.filter(item => item !== val);
    this.setState({
      closedatearr: removeval
    });
  };

  render() {
    const { closedatearr } = this.state;
    return (
      <React.Fragment>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            <label htmlFor="sortorder" className="floatLeft label2">
              Select Date
            </label>
          </div>
        </div>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            <DatePicker
              locale="en-GB"
              onChange={value => {
                this.setState({ closedate: value }, () => {
                  this.buttonHanlder(value);
                });
              }}
              value={new Date()}
            />
          </div>
        </div>
        <div className="row">
          <div className="form-group col-lg-12 col-sm-12">
            {closedatearr.map((datevalue, i) => {
              return (
                <div className="text-content" key={i}>
                  <input type="text" value={datevalue} className="inputfield" />
                  <button
                    type="button"
                    onClick={() => this.textareaHandler(datevalue)}
                  >
                    X
                  </button>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ height: "30px" }} />
      </React.Fragment>
    );
  }
}

export default AddDate;


问:
HC 05 Bluetooth module with arduino uno
i want to know for executing "Bluetooth.available();"
how much time is required, if connection is available, also in case of non availability of connection how much time is spent.

also for

Bluetooth.read() ;
Bluetooth.println("LED On!");

How much time is required .

my project is time sensitive so asking . kindly help

part of my code :::::::

```<code>     #include <SoftwareSerial.h>
   SoftwareSerial Bluetooth(10, 9); // RX, TX
  int LED = 13; // the on-board LED
  int Data; // the data received

     void setup() {
      Bluetooth.begin(9600);
     Serial.begin(9600);
     Serial.println("Waiting for command...");
      Bluetooth.println("Send 1 to turn on the LED. Send 0 to turn Off");
       pinMode(LED,OUTPUT);

     }

       void loop() {
        if (Bluetooth.available()){ //wait for data received
        Data=Bluetooth.read();
         if(Data=='1'){
        digitalWrite(LED,1);
        Serial.println("LED On!");
    Bluetooth.println("LED On!");
</code>```

答:
how much time is required, if connection is available, also in case of non availability of connection how much time is spent.

None! available() and read() return immediately. SoftwareSerial itself burdens the controller a little bit, while data is being read or written. While sending at 9600 (which takes 1 ms per character), other things can happen in parallel, if the send buffer is not yet full.
However SoftwareSerial cannot work full duplex, so while writing, nothing can be read.

Title: HC 05 Bluetooth module with arduino uno

Body:
i want to know for executing "Bluetooth.available();"
how much time is required, if connection is available, also in case of non availability of connection how much time is spent.

also for

Bluetooth.read() ;
Bluetooth.println("LED On!");

How much time is required .

my project is time sensitive so asking . kindly help

part of my code :::::::

     #include <SoftwareSerial.h>
   SoftwareSerial Bluetooth(10, 9); // RX, TX
  int LED = 13; // the on-board LED
  int Data; // the data received

     void setup() {
      Bluetooth.begin(9600);
     Serial.begin(9600);
     Serial.println("Waiting for command...");
      Bluetooth.println("Send 1 to turn on the LED. Send 0 to turn Off");
       pinMode(LED,OUTPUT);

     }

       void loop() {
        if (Bluetooth.available()){ //wait for data received
        Data=Bluetooth.read();
         if(Data=='1'){
        digitalWrite(LED,1);
        Serial.println("LED On!");
    Bluetooth.println("LED On!");


问:
Python copy to clipboard the content of a variable
I have a variable that stores text that the user types in a dialogue box.
I need to copy this text and then paste it in another field (to make a search)

I tried pyperclip but it works only with plain text, not with variables. Here is the code just for the dialogue box and e is my variable.

```<code>from tkinter import *
master = Tk()
e = Entry(master)
e.pack()

e.focus_set()

def callback():
    print(e.get())  # This is the text I want to use later

b = Button(master, text="insert", width=10, command=callback)
b.pack()

mainloop()
</code>```

答:
This doesn't work in your context?</p>

```<code>import pyperclip

test = "Hugo"
pyperclip.copy(test)
print(pyperclip.paste())
</code>```

Body:
I have a variable that stores text that the user types in a dialogue box.
I need to copy this text and then paste it in another field (to make a search)

I tried pyperclip but it works only with plain text, not with variables. Here is the code just for the dialogue box and e is my variable.

from tkinter import *
master = Tk()
e = Entry(master)
e.pack()

e.focus_set()

def callback():
    print(e.get())  # This is the text I want to use later

b = Button(master, text="insert", width=10, command=callback)
b.pack()

mainloop()

Body:
This doesn't work in your context?

import pyperclip

test = "Hugo"
pyperclip.copy(test)
print(pyperclip.paste())


问:
How to process each output line in a loop?
I have a number of lines retrieved from a file after running the grep command as follows:

```<code>var=`grep xyz abc.txt`
</code>```

Let’s say I got 10 lines which consists of xyz as a result.

Now I need to process each line I got as a result of the grep command. How do I proceed for this?

答:
For those looking for a one-liner:</p>

```<code>grep xyz abc.txt | while read -r line; do echo "Processing $line"; done
</code>```

Body:
I have a number of lines retrieved from a file after running the grep command as follows:

var=`grep xyz abc.txt`

Let’s say I got 10 lines which consists of xyz as a result.

Now I need to process each line I got as a result of the grep command. How do I proceed for this?

Body:
For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done


问:
Lambda authorizer response using async/await in Node.js
I'm trying to create a lambda authorizer on aws using node.js async/await instead of callbacks but there is no information on how to create the HTTP response returned to API Gateway. For example, if i return this :

```<code>{
  statusCode: 401
}
</code>```

the API gateway doesn't seem to understand and return an error 403 to the client :

```<code>{
    "statusCode": 403,
    "error": "Forbidden",
    "message": "No principalId set on the Response"
}
</code>```

Does anyone knows how to do what is described here : https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
but using async / await ?

Thanks in advance !

EDIT :

The way to return an error 401 is simply to throw an error like this :
throw new Error("Unauthorized")
And if the user is explicitly deny / allow, simply return the JSON policy.

答:
To return a 401 error you simply need to throw an error with "Unauthorized" as message, like this :

throw new Error("Unauthorized")
```

And if the user is explicitly deny / allow, simply return the JSON policy like you would do with callbacks.

Body:
I'm trying to create a lambda authorizer on aws using node.js async/await instead of callbacks but there is no information on how to create the HTTP response returned to API Gateway. For example, if i return this :

{
  statusCode: 401
}

the API gateway doesn't seem to understand and return an error 403 to the client :

{
    "statusCode": 403,
    "error": "Forbidden",
    "message": "No principalId set on the Response"
}

Does anyone knows how to do what is described here : https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
but using async / await ?

Thanks in advance !

EDIT :

The way to return an error 401 is simply to throw an error like this :
throw new Error("Unauthorized")
And if the user is explicitly deny / allow, simply return the JSON policy.

Body:
To return a 401 error you simply need to throw an error with "Unauthorized" as message, like this :

throw new Error("Unauthorized")

And if the user is explicitly deny / allow, simply return the JSON policy like you would do with callbacks.


问:
Send Object as string, not JSON, via Node Express
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}
```

<p>Should be returned as </p>

```"{foo: 'bar', baz: 1}"
```

<p>Instead of</p>

```{"foo": "bar", "baz": 1}
```

<p>Why? I need to use the string as a link in quickchart</p>

<pre class="lang-html prettyprint-override"><code><img src="https://quickchart.io/chart?c={type:'line',data:{labels:['January','February', 'March','April', 'May'], datasets:[{label:'Dogs', data: [50,60,70,180,190], fill:false,borderColor:'blue'},{label:'Cats', data:[100,200,300,400,500], fill:false,borderColor:'green'}]}}">
</code>```

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

答:
The double quotes in JSON break the image link.

You have an XY problem.

The problem is that using " characters in an attribute value delimited by " characters will break the attribute value.

While avoiding using " characters in the data is a solution, it isn't a good one (largely because avoiding them without breaking other stuff is hard). A better solution is to correctly escape them.

```<code>const json = JSON.stringify(obj);
const url_escaped_json = encodeURIComponent(json);
const img = `<img src="https://quickchart.io/chart?c=${url_escaped_json}" alt="...">`;
</code>```

Note that this doesn't use HTML escaping (which would replace " with "), because you are putting the data into a URL so it needs URL escaping first (and that will replace " with %20 rendering the HTML escaping unneeded).

Body:
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}

Should be returned as

"{foo: 'bar', baz: 1}"

Instead of

{"foo": "bar", "baz": 1}

Why? I need to use the string as a link in quickchart

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

Body:
The double quotes in JSON break the image link.

You have an XY problem.

The problem is that using " characters in an attribute value delimited by " characters will break the attribute value.

While avoiding using " characters in the data is a solution, it isn't a good one (largely because avoiding them without breaking other stuff is hard). A better solution is to correctly escape them.

const json = JSON.stringify(obj);
const url_escaped_json = encodeURIComponent(json);
const img = `<img src="https://quickchart.io/chart?c=${url_escaped_json}" alt="...">`;

Note that this doesn't use HTML escaping (which would replace " with &quot;), because you are putting the data into a URL so it needs URL escaping first (and that will replace " with %20 rendering the HTML escaping unneeded).


问:
typescript - cloning object
I have a super class that is the parent (Entity) for many subclass (Customer, Product, ProductCategory...)

I'm looking to clone dynamically an object that contains different sub objects in Typescript.

In example : a Customer that has different Product who has a ProductCategory

```<code>var cust:Customer  = new Customer ();

cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));
</code>```

In order to clone the whole tree of object I created a function in Entity

```<code>public clone():any {
    var cloneObj = new this.constructor();
    for (var attribut in this) {
        if(typeof this[attribut] === "object"){
           cloneObj[attribut] = this.clone();
        } else {
           cloneObj[attribut] = this[attribut];
        }
    }
    return cloneObj;
}
</code>```

The new rises the following error when it is transpiled to javascript: error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Although the script works, I would like to get rid of the transpiled error

答:
You could use destructuring assignment with spread syntax :</p>

```<code>var obj = {id = 1, name = 'product1'};
var clonedObject = {...obj};
</code>```

Title: typescript - cloning object

Body:
I have a super class that is the parent (Entity) for many subclass (Customer, Product, ProductCategory...)

I'm looking to clone dynamically an object that contains different sub objects in Typescript.

In example : a Customer that has different Product who has a ProductCategory

var cust:Customer  = new Customer ();

cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));

In order to clone the whole tree of object I created a function in Entity

public clone():any {
    var cloneObj = new this.constructor();
    for (var attribut in this) {
        if(typeof this[attribut] === "object"){
           cloneObj[attribut] = this.clone();
        } else {
           cloneObj[attribut] = this[attribut];
        }
    }
    return cloneObj;
}

The new rises the following error when it is transpiled to javascript: error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Although the script works, I would like to get rid of the transpiled error

Body:
You could use destructuring assignment with spread syntax :

var obj = {id = 1, name = 'product1'};
var clonedObject = {...obj};


问:
Whenever I open integrated terminal in VS code 1.18, it crashes PowerShell
Even though I have set below code in setting.json:

```<code>"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
</code>```

Whenever I open the "integrated terminal" it starts and right away shows:

```<code>"The terminal process terminated with exit code: 259"
</code>```

There is also a dialog outside code saying:

```<code>"powershell has stopped working
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is available."
</code>```

this happens in 32bit and 64bit too

Any idea how to overcome this?

答:
The code 259 usually means STILL_ACTIVE and this is rather strange.
You may try to use ProcessMonitor to determine which processes are started during your call and perhaps that gives you a clue.

Open Task Manager
I Clicked on End Task on all process of VS Code

Error vanished

Body:
Even though I have set below code in setting.json:

"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"

Whenever I open the "integrated terminal" it starts and right away shows:

"The terminal process terminated with exit code: 259"

There is also a dialog outside code saying:

"powershell has stopped working
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is available."

this happens in 32bit and 64bit too

Any idea how to overcome this?


问:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.

I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others can benefit from that, but I'm curious if there's any preferred way in the Open Source community to deal with this problem.

I have been reading here and there in the python.org site and in some other websites, but I haven't found anything conclusive.  The only thing that I found is that this is a chicken-and-egg problem.

It's out of the question (unless there's no other option) that I ship a dump of a library with my own modifications just to make it 3.x compliant.

Should I...

prepare all the code with __future imports and change here and there appropriately and leave it ready to work with both 2.x and 3.x?  Am I going to find any problem with this, other than the natural resistance of upstream to integrate such amount of changes?

create another branch of the code?  That, to me, should be quite useless, as nobody will maintain that branch except me, probably, and it's a huge duplication effort.

use some type of wrapper that I am not aware of to use those libraries as-is (like using some intermediate bindings in another language) and just create the glue in my code?

Many thanks!

答:
There are various strategies you can use, and which is best depends on several things, like what you are porting, how complex it is and how much of Pythons internals it uses.Basically, if you want to support both Python 2 and Python 3 at one time, run 2to3 on your code, and see how much it changes. If the changes are mostly such things that you can solve with __future__ imports, then porting to Python 3 and the reintroducing Python 2 compatibility may be a feasible way forward.
(For an in-depth look at this, see my Migration strategies page.)

If the changes are major, you are probably better off using 2to3 to support Python 3. This is made easier if you can use Distribute for packaging your project.

In both cases you may have use of six.

See also my talk on the subject.


问:
How to send props in class component to functional component?
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

```<code>import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}
</code>```

Another page is wall-factory-3d.js

```<code>import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}
</code>```

I tried this but not get output.

答:
You could either use React Hooks or any other state management library like Redux, MobX etc.

In React, if there is no immediate relationship(parent-children) between two components you can connect these two with a global state.

A global state in simple words is an object that can be accessed by many components using connectors or Flux technics.

Body:
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}

Another page is wall-factory-3d.js

import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}

I tried this but not get output.


问:
Infinite recursion ! how to convert?
I have following classes

```<code>class SomeClass{

    private String id;
    private String name;
    private List<SomeClass> history;

}
</code>```

```<code>class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;
}
</code>```

Now i want a method to convert this SomeClass Object to SomeClassDto.

答:
You should use cache for objects:</p>

```<code>import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by aprisadkov on 18.02.2020.
 */
public class InfiniteConvert {
    class SomeClass{

        private String id;
        private String name;
        private List<SomeClass> history;

    }
    class someClassDto{

        private String name;
        private List<someClassDto> historyDto;
    }
    HashMap<String, someClassDto> objById = new HashMap();

    public someClassDto convertDto(SomeClass someObj)
    {
        someClassDto ret = objById.get(someObj.id);

        if(ret == null) {
            ret = new someClassDto();
            objById.put(someObj.id, ret);

            ret.name = someObj.name;
            ret.historyDto = someObj.history.stream().map(t -> convertDto(t)).collect(Collectors.toList());
        }
        return ret;
    }

    public static void main(String[] args) throws Exception {
        InfiniteConvert m = new InfiniteConvert();
        m.test();
    }

    public void test()
    {
        SomeClass s1 = new SomeClass();
        s1.id = "1";
        s1.name = "s1";
        SomeClass s2 = new SomeClass();
        s2.id = "2";
        s2.name = "s2";
        SomeClass s3 = new SomeClass();
        s3.id = "3";
        s3.name = "s3";
        SomeClass s4 = new SomeClass();
        s4.id = "4";
        s4.name = "s4";

        s1.history = Arrays.asList(s2,s3,s4);
        s2.history = Arrays.asList(s3,s4);
        s3.history = Arrays.asList(s4);
        s4.history = Arrays.asList(s2,s3,s1);
        someClassDto sn =  convertDto(s1);
    }
}
</code>```

Title: Infinite recursion ! how to convert?

Body:
I have following classes

class SomeClass{

    private String id;
    private String name;
    private List<SomeClass> history;

}

class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;
}

Now i want a method to convert this SomeClass Object to SomeClassDto.

Body:
You should use cache for objects:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by aprisadkov on 18.02.2020.
 */
public class InfiniteConvert {
    class SomeClass{

        private String id;
        private String name;
        private List<SomeClass> history;

    }
    class someClassDto{

        private String name;
        private List<someClassDto> historyDto;
    }
    HashMap<String, someClassDto> objById = new HashMap();

    public someClassDto convertDto(SomeClass someObj)
    {
        someClassDto ret = objById.get(someObj.id);

        if(ret == null) {
            ret = new someClassDto();
            objById.put(someObj.id, ret);

            ret.name = someObj.name;
            ret.historyDto = someObj.history.stream().map(t -> convertDto(t)).collect(Collectors.toList());
        }
        return ret;
    }

    public static void main(String[] args) throws Exception {
        InfiniteConvert m = new InfiniteConvert();
        m.test();
    }

    public void test()
    {
        SomeClass s1 = new SomeClass();
        s1.id = "1";
        s1.name = "s1";
        SomeClass s2 = new SomeClass();
        s2.id = "2";
        s2.name = "s2";
        SomeClass s3 = new SomeClass();
        s3.id = "3";
        s3.name = "s3";
        SomeClass s4 = new SomeClass();
        s4.id = "4";
        s4.name = "s4";

        s1.history = Arrays.asList(s2,s3,s4);
        s2.history = Arrays.asList(s3,s4);
        s3.history = Arrays.asList(s4);
        s4.history = Arrays.asList(s2,s3,s1);
        someClassDto sn =  convertDto(s1);
    }
}


问:
Sencha ExtJS: why do menus get attached to the Viewport instead of the instancing View?
Hey I'm new to ExtJS development and development in general. I'm still in college and I'm currently trying to build the UI for a Webapp made in ExtJS and I'm having a bit of a problem with menus and how they work. I am pretty sure I'm overlooking something and there has to be a simple way to do what I'm intending to do with menus.

To be specific I have 2 menus in my App and they both give me the same kind of problem...
The first one uses code from this example: https://examples.sencha.com/extjs/6.7.0/examples/kitchensink/?modern#menus

it has a few fields that when changed then should update the main view...
the problem here is that the menu gets attached to the Viewport

```<code>this.topMenu = Ext.Viewport.setMenu(this.getMenuCfg('top'), {
            side: 'top'
        });
</code>```

which sets the scope of the fields' listeners that are inside the menu to the viewport instead of to the instancing views' controller which then makes it hard to get to the actual components I was looking for inside my main view or even loading stores from the viewmodel attached to my main view.

in fact I had to reverse engineer it with a debugger to then find this cryptic way to my store:

```<code>var me = this,
    vm = me.getViewModel().children["generated-cryptic-name-of-my-model-1"],
    myStore = vm.getStore('MyStore');
</code>```

and of course the problem also works the other way around...
inside methods fired from my main views' controller I won't be able to find the references of the components inside the menu with

```<code>this.lookupReference('reference')
</code>```

instead I had to again find a rather unintuitive a way to my components by giving them an ID. Again I only found this by using a debugger... it looks like this:

```<code>var me = this,
    menuItems = me.topMenu.getActiveItem().getItems(),
    fieldset = menuItems.getByKey('fldSet'),
    myField = fieldset.getItems().getByKey('myField');
</code>```

because I was only using 1 menu in my entire App at first I saw it as sort of technical debt and I didnt really look into it any further because I found a workaround.

But now I added another Menu, this time to the split section of a SplitButton, as shown in the Docs(https://docs.sencha.com/extjs/6.7.0/modern/Ext.SplitButton.html)

and again the menu gets attached to the viewport instead of the instancing view, which makes the handler functions fire at the viewportcontroller and takes the ability to find the references of my components inside the instancing views with this.lookupReference('reference').

I can make the handlers fire at the right controller by setting a controller config for the menu when instancing, but I haven't found an easy way of getting my components references and it is really bugging me at this point...

I would love to hear your suggestions, cheers ;)

答: It would probably help to know which views, viewcontrollers and viewmodels there are. The code vm = me.getViewModel().children["generated-cryptic-name-of-my-model-1"] makes me suspect there are more viewmodels and viewcontrollers involved, and it would help to know their relations. I wouldn't be surprised if the menus are not the problem at all...

Body:
Hey I'm new to ExtJS development and development in general. I'm still in college and I'm currently trying to build the UI for a Webapp made in ExtJS and I'm having a bit of a problem with menus and how they work. I am pretty sure I'm overlooking something and there has to be a simple way to do what I'm intending to do with menus.

To be specific I have 2 menus in my App and they both give me the same kind of problem...
The first one uses code from this example: https://examples.sencha.com/extjs/6.7.0/examples/kitchensink/?modern#menus

it has a few fields that when changed then should update the main view...
the problem here is that the menu gets attached to the Viewport

this.topMenu = Ext.Viewport.setMenu(this.getMenuCfg('top'), {
            side: 'top'
        });

which sets the scope of the fields' listeners that are inside the menu to the viewport instead of to the instancing views' controller which then makes it hard to get to the actual components I was looking for inside my main view or even loading stores from the viewmodel attached to my main view.

in fact I had to reverse engineer it with a debugger to then find this cryptic way to my store:

var me = this,
    vm = me.getViewModel().children["generated-cryptic-name-of-my-model-1"],
    myStore = vm.getStore('MyStore');

and of course the problem also works the other way around...
inside methods fired from my main views' controller I won't be able to find the references of the components inside the menu with

this.lookupReference('reference')

instead I had to again find a rather unintuitive a way to my components by giving them an ID. Again I only found this by using a debugger... it looks like this:

var me = this,
    menuItems = me.topMenu.getActiveItem().getItems(),
    fieldset = menuItems.getByKey('fldSet'),
    myField = fieldset.getItems().getByKey('myField');

because I was only using 1 menu in my entire App at first I saw it as sort of technical debt and I didnt really look into it any further because I found a workaround.

But now I added another Menu, this time to the split section of a SplitButton, as shown in the Docs(https://docs.sencha.com/extjs/6.7.0/modern/Ext.SplitButton.html)

and again the menu gets attached to the viewport instead of the instancing view, which makes the handler functions fire at the viewportcontroller and takes the ability to find the references of my components inside the instancing views with this.lookupReference('reference').

I can make the handlers fire at the right controller by setting a controller config for the menu when instancing, but I haven't found an easy way of getting my components references and it is really bugging me at this point...

I would love to hear your suggestions, cheers ;)


问:
How to add choices from a view?
I am trying to dynamically populate two form choice fields, and namely person and work.

The view called assign_work_to_person should allow the user to select a person, a work that has not yet been assigned to a person, and once the form is submitted the selected work should be linked to the selected person (e.g. 'Leonardo da Vinci' should be linked to 'Mona Lisa').

What I am doing is creating the form class with empty choices for the two fields

```<code>class AssignWorkToPerson(forms.Form):
    person = forms.ChoiceField()
    work = forms.ChoiceField()
</code>```

and then retrieving the available persons and authorless works to populate the form fields when the user accesses the assign_work_to_person view.

I am trying to dynamically set these choices in this way:

```<code>form.fields['the_field_name'].choices = a_list_of_tuples
</code>```

When I access the view, the template renders ok, with all the available choices being correctly displayed.

The problem is that when I submit the form, it raises validation errors for both fields, telling me to select a valid choice.

By running some (very basic print) tests, I have realized that trying to populate the fields this way, doesn't actually add the choices, even though they are there in the template. In fact, as you can see from the second picture, once I have submitted the form, the template renders the form with no choices available.

How can I make this work?

I know from other answers to similar questions that this can be done by specifying an __init__ method in the model (in my case the form, I suppose), and then by setting the choices through the queryset keyword argument, but I'd rather do this in the view, if possible.

Edit

```<code>def assign_work_to_person(request):
    form = AssignWorkToPerson()
    persons = Person.objects.all()
    person_choices = []
    for person in persons:
        person_choices.append((person.first_name + ' ' + person.last_name, person.first_name + ' ' + person.last_name))
    form.fields['person'].choices = person_choices
    works = Work.objects.all()
    work_choices = []
    for work in works.filter(author=None):
        work_choices.append((work.name, work.name))
    form.fields['work'].choices = work_choices

    if request.method == 'POST':
        persons = Person.objects.all()
        person_choices = []
        for person in persons:
            person_choices.append(
                (person.first_name + ' ' + person.last_name, person.first_name + ' ' + person.last_name))
        form.fields['person'].choices = person_choices
        works = Work.objects.all()
        work_choices = []
        for work in works.filter(author=None):
            work_choices.append((work.name, work.name))
        form.fields['work'].choices = work_choices
        print(form.fields['person'].choices)
        form = AssignWorkToPerson(request.POST)

        if form.is_valid():

            print('THIS FORM CONTAINS VALID DATA')
    template_name = 'assign_work_to_person.html'
    context = {'form': form}
    return render(request, template_name, context)
</code>```

答:
You are reinitializing form

```
<code>
print(form.fields['person'].choices)
<b>form = AssignWorkToPerson(request.POST)</b>

if form.is_valid():
</code>
```

It should be like this

```
<code>
   if request.method == 'POST':
        <b>form = AssignWorkToPerson(request.POST)</b>
        # skipped
        form.fields['person'].choices = person_choices
        if form.is_valid():
            pass
</code>
```

form = AssignWorkToPerson(request.POST) should be on top just after method check not at the end.

Title: How to add choices from a view?

Body:
I am trying to dynamically populate two form choice fields, and namely person and work.

The view called assign_work_to_person should allow the user to select a person, a work that has not yet been assigned to a person, and once the form is submitted the selected work should be linked to the selected person (e.g. 'Leonardo da Vinci' should be linked to 'Mona Lisa').

What I am doing is creating the form class with empty choices for the two fields

class AssignWorkToPerson(forms.Form):
    person = forms.ChoiceField()
    work = forms.ChoiceField()

and then retrieving the available persons and authorless works to populate the form fields when the user accesses the assign_work_to_person view.

I am trying to dynamically set these choices in this way:

form.fields['the_field_name'].choices = a_list_of_tuples

When I access the view, the template renders ok, with all the available choices being correctly displayed.

The problem is that when I submit the form, it raises validation errors for both fields, telling me to select a valid choice.

By running some (very basic print) tests, I have realized that trying to populate the fields this way, doesn't actually add the choices, even though they are there in the template. In fact, as you can see from the second picture, once I have submitted the form, the template renders the form with no choices available.

How can I make this work?

I know from other answers to similar questions that this can be done by specifying an __init__ method in the model (in my case the form, I suppose), and then by setting the choices through the queryset keyword argument, but I'd rather do this in the view, if possible.

Edit

def assign_work_to_person(request):
    form = AssignWorkToPerson()
    persons = Person.objects.all()
    person_choices = []
    for person in persons:
        person_choices.append((person.first_name + ' ' + person.last_name, person.first_name + ' ' + person.last_name))
    form.fields['person'].choices = person_choices
    works = Work.objects.all()
    work_choices = []
    for work in works.filter(author=None):
        work_choices.append((work.name, work.name))
    form.fields['work'].choices = work_choices

    if request.method == 'POST':
        persons = Person.objects.all()
        person_choices = []
        for person in persons:
            person_choices.append(
                (person.first_name + ' ' + person.last_name, person.first_name + ' ' + person.last_name))
        form.fields['person'].choices = person_choices
        works = Work.objects.all()
        work_choices = []
        for work in works.filter(author=None):
            work_choices.append((work.name, work.name))
        form.fields['work'].choices = work_choices
        print(form.fields['person'].choices)
        form = AssignWorkToPerson(request.POST)

        if form.is_valid():

            print('THIS FORM CONTAINS VALID DATA')
    template_name = 'assign_work_to_person.html'
    context = {'form': form}
    return render(request, template_name, context)

Body:
You are reinitializing form

print(form.fields['person'].choices)
form = AssignWorkToPerson(request.POST)

if form.is_valid():

It should be like this

   if request.method == 'POST':
        form = AssignWorkToPerson(request.POST)
        # skipped
        form.fields['person'].choices = person_choices
        if form.is_valid():
            pass

form = AssignWorkToPerson(request.POST) should be on top just after method check not at the end.


问:
MassTransit RabbitMq Sending Messages
I am not able to figure out on how to specify the Exchange and Queue in my GetSendEndpoint()) task when sending / publishing messages?

As per MassTransit documentation https://masstransit-project.com/usage/producers.html#send you can specify the exchange and queue like

```<code>GetSendEndpoint(new Uri("queue:input-queue"))
</code>```

However, I can only do one or the other?

Is there an alternative way of sending with exchange and queue specified?

I am doing this in Asp.Net Core so here are my configuration:

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
   services.AddMassTransit();

   services.AddSingleton(p => Bus.Factory.CreateUsingRabbitMq(cfg =>
   {
         cfg.Host("rabbitmq://localhost", h =>
         {
             h.Username("admin");
             h.Password("admin");
         });
   }));

   services.AddSingleton<IBus>(p => p.GetRequiredService<IBusControl>());
   services.AddSingleton<IHostedService, BusService>();
}
</code>```

And this is how send the message

```<code>var endpoint = await _bus.GetSendEndpoint(new Uri(queue:Test.Queue));
await endpoint.Send(new Message()
{
     Text = "This is a test message"
});
</code>```

As you can see I can only specify the queue name.

答:
Reading Chris's response in here Mass Transit : No consumer

It seems like Exchanges are created by MassTransit when publishing messages, based on the message types. Publishing does not create any queues. Queues are where messages are stored for delivery to consumers.

and Queues are created when receive endpoints are added to a bus. For the consumers, handlers, and sagas added to a receive endpoint, the exchanges are created and bound so that messages published to the exchanges are received by the receive endpoint (via the queue).

So if my publisher doesn't have a receive endpoint defined then any messages I send will be lost as there will be no queues or binding?

Further reading on here https://groups.google.com/forum/#!topic/masstransit-discuss/oVzZkg1os9o seems to further confirm this.

So based on the above link in order to achieve what I want i.e. to create the exchange and bind it to a queue I will need to specify it in the Uri as such

```<code>var sendEndpoint = bus.GetSendEndpoint(new Uri("rabbitmq://localhost/vhost1/exchange1?bind=true&queue=queue1"));
</code>```

where exchange1 is the Exchange, queue1 is the Queue and bind=true would bind the queue to the exchange.

If sticking to the original MT design a Consumers needs to be running before to setup the exchanges and queues before a Producer can start publishing? This seems to give less flexibility to the Publisher?

Title: MassTransit RabbitMq Sending Messages

Body:
I am not able to figure out on how to specify the Exchange and Queue in my GetSendEndpoint()) task when sending / publishing messages?

As per MassTransit documentation https://masstransit-project.com/usage/producers.html#send you can specify the exchange and queue like

GetSendEndpoint(new Uri("queue:input-queue"))

However, I can only do one or the other?

Is there an alternative way of sending with exchange and queue specified?

I am doing this in Asp.Net Core so here are my configuration:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   services.AddMassTransit();

   services.AddSingleton(p => Bus.Factory.CreateUsingRabbitMq(cfg =>
   {
         cfg.Host("rabbitmq://localhost", h =>
         {
             h.Username("admin");
             h.Password("admin");
         });
   }));

   services.AddSingleton<IBus>(p => p.GetRequiredService<IBusControl>());
   services.AddSingleton<IHostedService, BusService>();
}

And this is how send the message

var endpoint = await _bus.GetSendEndpoint(new Uri(queue:Test.Queue));
await endpoint.Send(new Message()
{
     Text = "This is a test message"
});

As you can see I can only specify the queue name.

Body:
Reading Chris's response in here Mass Transit : No consumer

It seems like Exchanges are created by MassTransit when publishing messages, based on the message types. Publishing does not create any queues. Queues are where messages are stored for delivery to consumers.

and Queues are created when receive endpoints are added to a bus. For the consumers, handlers, and sagas added to a receive endpoint, the exchanges are created and bound so that messages published to the exchanges are received by the receive endpoint (via the queue).

So if my publisher doesn't have a receive endpoint defined then any messages I send will be lost as there will be no queues or binding?

Further reading on here https://groups.google.com/forum/#!topic/masstransit-discuss/oVzZkg1os9o seems to further confirm this.

So based on the above link in order to achieve what I want i.e. to create the exchange and bind it to a queue I will need to specify it in the Uri as such

var sendEndpoint = bus.GetSendEndpoint(new Uri("rabbitmq://localhost/vhost1/exchange1?bind=true&queue=queue1"));

where exchange1 is the Exchange, queue1 is the Queue and bind=true would bind the queue to the exchange.

If sticking to the original MT design a Consumers needs to be running before to setup the exchanges and queues before a Producer can start publishing? This seems to give less flexibility to the Publisher?


问:
why does iostream header file not get included?
```<code>#include <sstream>
using namespace std;

int main()
{
    cout << "hi"; // error: undeclared cout
}
</code>```

From what I have read, sstream class is derived from iostream class but why does it not get included automatically?

答: std::sstream is derived from both std::istream and std::ostream. That means you don't need to include <istream> or <ostream>. However, std::cout is defined in neither of those two headers. That's why you need yet another header, <iostream>.

Body:
#include <sstream>
using namespace std;

int main()
{
    cout << "hi"; // error: undeclared cout
}

From what I have read, sstream class is derived from iostream class but why does it not get included automatically?


问:
How to reach the needed atribute through condition in groupby Pandas&
Have the following task in jupyter notebook:

How many women are there in the most crowded class?

Have the following columns in table:

PassengerId   Survived    Pclass  Name    Sex Age SibSp   Parch   Ticket  Fare    Cabin   Embarked

The 'class' from the task is the 'Pclass' from the table.

Cannot understand how do i solve this.

Have counted number of people for each class:

```<code>data_by_class = data.groupby(['Pclass'])
data_by_class['Pclass'].value_counts()
</code>```

Output:

```<code>Pclass  Pclass
1       1         216
2       2         184
3       3         491
Name: Pclass, dtype: int64
</code>```

I can get the maximum:

data_by_class['Pclass'].value_counts().max()

Output:

491

How do I connect count to class? It is easy with SQL but do not understand how to do it with Pandas.
Would be grateful if anybody could help with solving the task at the beginning.

答:
Sample:

```<code>data = pd.DataFrame({
         'Pclass':[1,2,1,2,2,1],
         'Sex':['male'] + ['female'] * 5
})
</code>```

First is necessary grouping by Sex column and add Series.reset_index for convert Series with MultiIndex to 3 columns DataFrame:

```<code>data_by_class = data.groupby('Sex')['Pclass'].value_counts().reset_index(name='count')
print (data_by_class)
      Sex  Pclass  count
0  female       2      3
1  female       1      2
2    male       1      1
</code>```

Then for maximal values per groups use DataFrameGroupBy.idxmax with DataFrame.loc:

```<code>df = data_by_class.loc[data_by_class.groupby('Sex')['count'].idxmax()]
print (df)
      Sex  Pclass  count
0  female       2      3
2    male       1      1
</code>```

And last if want scalars output convert column to index:

```<code>df = df.set_index('Sex')
print (df)
        Pclass  count
Sex
female       2      3
male         1      1
</code>```

So is possible select by labels by DataFrame.loc:

```<code>print (df.loc['female', 'count'])
3
print (df.loc['female', 'Pclass'])
2
</code>```

Body:
Have the following task in jupyter notebook:

How many women are there in the most crowded class?

Have the following columns in table:

PassengerId   Survived    Pclass  Name    Sex Age SibSp   Parch   Ticket  Fare    Cabin   Embarked

The 'class' from the task is the 'Pclass' from the table.

Cannot understand how do i solve this.

Have counted number of people for each class:

data_by_class = data.groupby(['Pclass'])
data_by_class['Pclass'].value_counts()

Output:

Pclass  Pclass
1       1         216
2       2         184
3       3         491
Name: Pclass, dtype: int64

I can get the maximum:

data_by_class['Pclass'].value_counts().max()

Output:

491

How do I connect count to class? It is easy with SQL but do not understand how to do it with Pandas.
Would be grateful if anybody could help with solving the task at the beginning.

Body:
Sample:

data = pd.DataFrame({
         'Pclass':[1,2,1,2,2,1],
         'Sex':['male'] + ['female'] * 5
})

First is necessary grouping by Sex column and add Series.reset_index for convert Series with MultiIndex to 3 columns DataFrame:

data_by_class = data.groupby('Sex')['Pclass'].value_counts().reset_index(name='count')
print (data_by_class)
      Sex  Pclass  count
0  female       2      3
1  female       1      2
2    male       1      1

Then for maximal values per groups use DataFrameGroupBy.idxmax with DataFrame.loc:

df = data_by_class.loc[data_by_class.groupby('Sex')['count'].idxmax()]
print (df)
      Sex  Pclass  count
0  female       2      3
2    male       1      1

And last if want scalars output convert column to index:

df = df.set_index('Sex')
print (df)
        Pclass  count
Sex
female       2      3
male         1      1

So is possible select by labels by DataFrame.loc:

print (df.loc['female', 'count'])
3
print (df.loc['female', 'Pclass'])
2


问:
Multilevel login system in Python randomly rejecting attempts
I wrote this multilevel login system in Python. When I logged in with the data in the first row, it worked just fine, but when I tried the second data line, I couldn't log in.

This is how the login data looks like (stored in a .txt file):

1|Farhan|admin|admin|Administrator
2|Hilmi|user|user|user
3|jghgh|jhhj|hh|user
```

<p>This is my code:</p>

<pre class="lang-py prettyprint-override"><code>def login():
    users = open("E:\\SI\\alpro\\Tubes\\users.txt").read().split("\n")
    for i in range(len(users)):
        users[i] = users[i].split("|")

    while True:
        print(">>> LOGIN")
        print("-"*100)
        username = str(input("Username \t: "))
        password = str(input("Password \t: "))

        for user in users:
            uname = user[2]
            pword = user[3]
            kode = user[4]

            if uname == username and pword == password and kode == "Administrator":
                print("\nWelcome, " + user[1] + ".")
                print("You Log in as : " + user[4] + ".")
                admin()
                break
            elif uname == username and pword == password and kode == "user":
                print("Welcome, " + user[1] + ".")
                print("You Log in as : " + user[4] + ".")
                break
            else:
                print("-"*58)
                print("| \u274c  \u274c  Invalid  \u274c  |\n")
                login()
        break
</code>```

答:
If you add

```<code>print('checking', username , password, 'against', uname, pword, kode)
</code>```

before the if/elif/else, you'll see the issue.
When you check "user"/"user" against your txt file, on the first round it is against admin. So it doesn't match, ends in the else clause, which immediately calls login again.

So you need to completely rethink the while and if blocks.
A nice idea could be with a users dictionary, so instead of all the if user == username, you'd directly get to the correct line with user_dict[username].

Body:
I wrote this multilevel login system in Python. When I logged in with the data in the first row, it worked just fine, but when I tried the second data line, I couldn't log in.

This is how the login data looks like (stored in a .txt file):

1|Farhan|admin|admin|Administrator
2|Hilmi|user|user|user
3|jghgh|jhhj|hh|user

This is my code:

def login():
    users = open("E:\\SI\\alpro\\Tubes\\users.txt").read().split("\n")
    for i in range(len(users)):
        users[i] = users[i].split("|")

    while True:
        print(">>> LOGIN")
        print("-"*100)
        username = str(input("Username \t: "))
        password = str(input("Password \t: "))

        for user in users:
            uname = user[2]
            pword = user[3]
            kode = user[4]

            if uname == username and pword == password and kode == "Administrator":
                print("\nWelcome, " + user[1] + ".")
                print("You Log in as : " + user[4] + ".")
                admin()
                break
            elif uname == username and pword == password and kode == "user":
                print("Welcome, " + user[1] + ".")
                print("You Log in as : " + user[4] + ".")
                break
            else:
                print("-"*58)
                print("| \u274c  \u274c  Invalid  \u274c  |\n")
                login()
        break

Body:
If you add

print('checking', username , password, 'against', uname, pword, kode)

before the if/elif/else, you'll see the issue.
When you check "user"/"user" against your txt file, on the first round it is against admin. So it doesn't match, ends in the else clause, which immediately calls login again.

So you need to completely rethink the while and if blocks.
A nice idea could be with a users dictionary, so instead of all the if user == username, you'd directly get to the correct line with user_dict[username].


问:
How can I convert uppercase letters to lowercase letters in ARM Assembly?
I have the following program:

```<code> .data
 cc: .byte 0x42
     .byte 0x4f
     .byte 0x4e
     .byte 0x4a
     .byte 0x4f
     .byte 0x55
     .byte 0x52
     .byte 0x00
co: .asciz "au revoir..."

    .text
    .global main
main:

@ impression de la chaine de caractere d'adresse cc
     ldr r1, LD_cc
     bl EcrChaine

@ modification de la chaine d'adresse cc
    @To be completed

@ impression de la chaine modifiee
     ldr r1, LD_co
     bl EcrChaine

fin: B exit  @ terminaison immediate du processus (plus tard on saura faire mieux)

LD_cc: .word cc
LD_ca: .word ca
LD_co: .word co
</code>```

cc contains the string "BONJOUR" in uppercase letters. In the "to be completed" part I have to take this string and convert it in lowercase letters using a bitwise OR operation (the ORR command). My understanding is that since the string is using the ASCII table, all I have to do is add 32 to each character. The corresponding command is
ORR R1, R1, #32, however I'm trying to do this and when running the program the output is blank. I tried using an online emulator to see the changes in values, but I can see that only the first letter changes. Do I have to use a loop? Can anyone help me please?

答:
Thanks for the comments. I solved my issue. I didn't use a loop because "it's next week's lesson" but here's how I did it:

First, I loaded the first 4 characters into R2 (I'm not sure if I could load more but the emulator I used can store up to 8 bytes. A character is equal to 2 bytes, thus 4 characters):

```<code>LDR r2, [r1]
</code>```

and the number 32 inside R3:

```<code>MOV R3, 0x20
</code>```

Then for each character I repeated this sequence of instructions:

```<code>ORR r2, r3, r2
LSL r3, r3, #8
</code>```

I used LSL to multiply the value of R3 (in decimal 32, in hexadecimal 0x20) with 2 in the power of 8 (i.e. multiply with 256). As a result, with each LSL, 2 zeros were added after my number and I could use the ORR instruction on the next character.

After I finished with the first set of characters I stored them in memory and loaded the second one:

```<code>STR r2, [r1]
ADD r1, r1, #4
LDR r2, [r1]
</code>```

I initialised R3 into 32 again:

```<code>LSR r3, r3, #24
</code>```

and repeated ORR and LSL 3 more times. I stored that set of characters next to the first one and then went back to the start of my string and called my function that prints the string on the terminal:

```<code>STR r2, [r1]
SUB r1, r1, #4
bl EcrChaine
</code>```

which worked perfectly. The resulting file however is very big in terms of number of lines and can be substantially lowered using a loop, but I didn't use one for the moment because  "we haven't been taught that in class yet".

Body:
I have the following program:

 .data
 cc: .byte 0x42
     .byte 0x4f
     .byte 0x4e
     .byte 0x4a
     .byte 0x4f
     .byte 0x55
     .byte 0x52
     .byte 0x00
co: .asciz "au revoir..."

    .text
    .global main
main:

@ impression de la chaine de caractere d'adresse cc
     ldr r1, LD_cc
     bl EcrChaine

@ modification de la chaine d'adresse cc
    @To be completed

@ impression de la chaine modifiee
     ldr r1, LD_co
     bl EcrChaine

fin: B exit  @ terminaison immediate du processus (plus tard on saura faire mieux)

LD_cc: .word cc
LD_ca: .word ca
LD_co: .word co

cc contains the string "BONJOUR" in uppercase letters. In the "to be completed" part I have to take this string and convert it in lowercase letters using a bitwise OR operation (the ORR command). My understanding is that since the string is using the ASCII table, all I have to do is add 32 to each character. The corresponding command is
ORR R1, R1, #32, however I'm trying to do this and when running the program the output is blank. I tried using an online emulator to see the changes in values, but I can see that only the first letter changes. Do I have to use a loop? Can anyone help me please?

Body:
Thanks for the comments. I solved my issue. I didn't use a loop because "it's next week's lesson" but here's how I did it:

First, I loaded the first 4 characters into R2 (I'm not sure if I could load more but the emulator I used can store up to 8 bytes. A character is equal to 2 bytes, thus 4 characters):

LDR r2, [r1]

and the number 32 inside R3:

MOV R3, 0x20

Then for each character I repeated this sequence of instructions:

ORR r2, r3, r2
LSL r3, r3, #8

I used LSL to multiply the value of R3 (in decimal 32, in hexadecimal 0x20) with 2 in the power of 8 (i.e. multiply with 256). As a result, with each LSL, 2 zeros were added after my number and I could use the ORR instruction on the next character.

After I finished with the first set of characters I stored them in memory and loaded the second one:

STR r2, [r1]
ADD r1, r1, #4
LDR r2, [r1]

I initialised R3 into 32 again:

LSR r3, r3, #24

and repeated ORR and LSL 3 more times. I stored that set of characters next to the first one and then went back to the start of my string and called my function that prints the string on the terminal:

STR r2, [r1]
SUB r1, r1, #4
bl EcrChaine

which worked perfectly. The resulting file however is very big in terms of number of lines and can be substantially lowered using a loop, but I didn't use one for the moment because  "we haven't been taught that in class yet".


问:
Reduce the border/attach iframe border to another
Below is the sample iframe app in R shiny. Wanted to check if it is possible to reduce the border. I have attached below . Can anyone please help me

```<code>library(shiny)
members <- data.frame(name=c("Name 1", "Name 2"), nr=c('BCRA1','FITM2'))

ui <- fluidPage(titlePanel("Getting Iframe"),
                sidebarLayout(
                  sidebarPanel(
                    fluidRow(
                      column(6, selectInput("Member", label=h5("Choose a option"),choices=c('BCRA1','FITM2'))
                      ))),
                  mainPanel(fluidRow(
                    htmlOutput("frame")
                  )
                  )
                ))

server <- function(input, output) {
  observe({
    query <- members[which(members$nr==input$Member),2]
    test <<- paste0("http://news.scibite.com/scibites/news.html?q=GENE$",query)
  })
  output$frame <- renderUI({
    input$Member
    my_test <- tags$iframe(src=test, height=1000, width=1035, frameborder = "yes")
    print(my_test)
    my_test
  })
}

shinyApp(ui, server)
</code>```

Reduce this (Like can we make "b" attached to "a"

答:
Yes, it is possible and I think this is possibly the easiest answer (I may stand corrected here).

Your issue is/was down to your CSS for h2 (margin-top:20px). I have wrapped your titlePanel in a div and gave it an id (test) to only control the CSS for that particular element. Next I added some specific CSS directly to your code tags$style("#test h2 {margin-top: 10px;}"). This should control the margin-top specifically for your titlePanel and shouldn't affect any subsequent uses of titelPanel or h2().

You can control the space by setting margin-top: 10px; to the amount of px you like.

```<code>library(shiny)
members <- data.frame(name=c("Name 1", "Name 2"), nr=c('BCRA1','FITM2'))

ui <- fluidPage(tags$style("#test h2 {margin-top: 10px;}"), # add style here
                div(id = "test", titlePanel("Getting Iframe")), # add id here
                sidebarLayout(
                  sidebarPanel(
                    fluidRow(
                      column(6, selectInput("Member", label=h5("Choose a option"),choices=c('BCRA1','FITM2'))
                      ))),
                  mainPanel(fluidRow(
                    htmlOutput("frame")
                  )
                  )
                ))

server <- function(input, output) {
  observe({
    query <- members[which(members$nr==input$Member),2]
    test <<- paste0("http://news.scibite.com/scibites/news.html?q=GENE$",query)
  })
  output$frame <- renderUI({
    input$Member
    my_test <- tags$iframe(src=test, height=1000, width=1035, frameborder = "yes")
    print(my_test)
    my_test
  })
}

shinyApp(ui, server)
</code>```

Body:
Below is the sample iframe app in R shiny. Wanted to check if it is possible to reduce the border. I have attached below . Can anyone please help me

library(shiny)
members <- data.frame(name=c("Name 1", "Name 2"), nr=c('BCRA1','FITM2'))

ui <- fluidPage(titlePanel("Getting Iframe"),
                sidebarLayout(
                  sidebarPanel(
                    fluidRow(
                      column(6, selectInput("Member", label=h5("Choose a option"),choices=c('BCRA1','FITM2'))
                      ))),
                  mainPanel(fluidRow(
                    htmlOutput("frame")
                  )
                  )
                ))

server <- function(input, output) {
  observe({
    query <- members[which(members$nr==input$Member),2]
    test <<- paste0("http://news.scibite.com/scibites/news.html?q=GENE$",query)
  })
  output$frame <- renderUI({
    input$Member
    my_test <- tags$iframe(src=test, height=1000, width=1035, frameborder = "yes")
    print(my_test)
    my_test
  })
}

shinyApp(ui, server)

Reduce this (Like can we make "b" attached to "a"

Body:
Yes, it is possible and I think this is possibly the easiest answer (I may stand corrected here).

Your issue is/was down to your CSS for h2 (margin-top:20px). I have wrapped your titlePanel in a div and gave it an id (test) to only control the CSS for that particular element. Next I added some specific CSS directly to your code tags$style("#test h2 {margin-top: 10px;}"). This should control the margin-top specifically for your titlePanel and shouldn't affect any subsequent uses of titelPanel or h2().

You can control the space by setting margin-top: 10px; to the amount of px you like.

library(shiny)
members <- data.frame(name=c("Name 1", "Name 2"), nr=c('BCRA1','FITM2'))

ui <- fluidPage(tags$style("#test h2 {margin-top: 10px;}"), # add style here
                div(id = "test", titlePanel("Getting Iframe")), # add id here
                sidebarLayout(
                  sidebarPanel(
                    fluidRow(
                      column(6, selectInput("Member", label=h5("Choose a option"),choices=c('BCRA1','FITM2'))
                      ))),
                  mainPanel(fluidRow(
                    htmlOutput("frame")
                  )
                  )
                ))

server <- function(input, output) {
  observe({
    query <- members[which(members$nr==input$Member),2]
    test <<- paste0("http://news.scibite.com/scibites/news.html?q=GENE$",query)
  })
  output$frame <- renderUI({
    input$Member
    my_test <- tags$iframe(src=test, height=1000, width=1035, frameborder = "yes")
    print(my_test)
    my_test
  })
}

shinyApp(ui, server)


问:
how to convert this string to an array?
I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.

Here where I create the array in my JS file.

```<code>function get_array(){
  var datos = []; // Array
  $("#tbl_esctructura tbody > tr").each(function() {

    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(4)').text();

    datos.push({
       "item": item,
       "cantidad": cantidad
    });
  });

  datos =  JSON.stringify(datos);
  $.ajax({
        data: {
            'datos': datos
        },
        url: "<?php echo base_url() ?>Controller/data_from_array",
        type: 'POST',
        dataType : "json",
        success: function(response) {

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

the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

Now my controller PHP

```<code>public function data_from_array(){
   $data   =  $this->input->post('datos', TRUE);
   $items = explode(',', $data);
   var_dump($items);
   foreach ($items as $row) {
       echo  $row->item.'<br>';
   }
}
</code>```

and the var_dump($items) this is the result

array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
        }

And in this echo I get this error Message: Trying to get property 'item' of non-object

And I don't know what I'm doing wrong

答:
Looks like a standard JSON.
Be sure to add true to json_decode function (second parameter) to return array instead of object.

```<code>$result = json_decode($data, true);
</code>```

Have a look at JSON as this is a, nowadays, standard of data interchange for web and mobile apps and learn more about the function:

https://www.php.net/manual/en/function.json-decode.php

also look at its counterpart that will encode your arrays into JSON format:

https://www.php.net/manual/en/function.json-encode.php

Title: how to convert this string to an array?

Body:
I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.

Here where I create the array in my JS file.

function get_array(){
  var datos = []; // Array
  $("#tbl_esctructura tbody > tr").each(function() {

    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(4)').text();

    datos.push({
       "item": item,
       "cantidad": cantidad
    });
  });

  datos =  JSON.stringify(datos);
  $.ajax({
        data: {
            'datos': datos
        },
        url: "<?php echo base_url() ?>Controller/data_from_array",
        type: 'POST',
        dataType : "json",
        success: function(response) {

        }
    });
}

the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

Now my controller PHP

public function data_from_array(){
   $data   =  $this->input->post('datos', TRUE);
   $items = explode(',', $data);
   var_dump($items);
   foreach ($items as $row) {
       echo  $row->item.'
';
   }
}

and the var_dump($items) this is the result

array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
        }

And in this echo I get this error Message: Trying to get property 'item' of non-object

And I don't know what I'm doing wrong

Body:
Looks like a standard JSON.
Be sure to add true to json_decode function (second parameter) to return array instead of object.

$result = json_decode($data, true);

Have a look at JSON as this is a, nowadays, standard of data interchange for web and mobile apps and learn more about the function:

https://www.php.net/manual/en/function.json-decode.php

also look at its counterpart that will encode your arrays into JSON format:

https://www.php.net/manual/en/function.json-encode.php