问:
BST insert(root, value) recursive method
EDIT: I've figured it out - scrapped this design and started over and it worked! Thank you for your suggestions.

I'm working on a BST algorithm homework assignment and I'm hopelessly stuck on the insert method. All of the resources I've found online have a version similar to what I've created, but I am failing the JUnit test given to us by our professor. I can pass the base cases (null root and binary tree where the root.payload == value). I can't seem to pass the next test though. Here is my code for the insert(root, value) method:

public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (root.payload.equals(value)) {
        return root;
    } else if (value < root.payload) {
        return root.left = insert(root.left, value);
    } else {
        return root.right = insert(root.right, value);
    }
    return root;
}
```

What ends up being returned is the original root node, but from my understanding, the returned value at the end should be my new node. I've looked at my textbook and some online resources and all of them have something very similar to this design, so I'm quite confused as to why it's not working. I've tried some other designs but all of them end up being a NullPointerException. The JUnit test that was given to us verifies that we inserted the node in the correct place, in addition to checking the Node's payload. I'm failing both of these tests. This is our first assignment using recursion, so I'm still fairly new at it. Any guidance would be greatly appreciated!

答:
If you want the returned value from your method to be the newly inserted node , you have to add return statement in the elseIf clause as well , so that when the recursive stack unwinds it returns the new created node. Check the code below </p>

```<code>public static Node<Integer> insert(Node<Integer> root, Integer value) {
if (root == null) {
    root = new Node<>(value);
} else if (value <= root.payload) {
    return root.left = insert(root.left, value);   // add a return here
} else {
   return  root.right = insert(root.right, value);  // add a return here
}
return root;
</code>```

<p>}</p>

Body:
EDIT: I've figured it out - scrapped this design and started over and it worked! Thank you for your suggestions.

I'm working on a BST algorithm homework assignment and I'm hopelessly stuck on the insert method. All of the resources I've found online have a version similar to what I've created, but I am failing the JUnit test given to us by our professor. I can pass the base cases (null root and binary tree where the root.payload == value). I can't seem to pass the next test though. Here is my code for the insert(root, value) method:

public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (root.payload.equals(value)) {
        return root;
    } else if (value < root.payload) {
        return root.left = insert(root.left, value);
    } else {
        return root.right = insert(root.right, value);
    }
    return root;
}

What ends up being returned is the original root node, but from my understanding, the returned value at the end should be my new node. I've looked at my textbook and some online resources and all of them have something very similar to this design, so I'm quite confused as to why it's not working. I've tried some other designs but all of them end up being a NullPointerException. The JUnit test that was given to us verifies that we inserted the node in the correct place, in addition to checking the Node's payload. I'm failing both of these tests. This is our first assignment using recursion, so I'm still fairly new at it. Any guidance would be greatly appreciated!

Body:
If you want the returned value from your method to be the newly inserted node , you have to add return statement in the elseIf clause as well , so that when the recursive stack unwinds it returns the new created node. Check the code below

public static Node<Integer> insert(Node<Integer> root, Integer value) {
if (root == null) {
    root = new Node<>(value);
} else if (value <= root.payload) {
    return root.left = insert(root.left, value);   // add a return here
} else {
   return  root.right = insert(root.right, value);  // add a return here
}
return root;

}


来源: stackexchange

问:
How do you create a button that works in javascript?
EDIT: So a few solutions work. Thing is, they work in codepen.io. But when I try to reload the actual HTML page from my computer to Chrome, the button clicks and shows nothing. Chrome is saying: 'dice.js:12 Uncaught TypeError: Cannot set property 'onclick' of null
    at dice.js:12.' How do I fix that?

I've looked at multiple similar questions that have different answers, and none of the answers I've tried has worked. I was able to make a random dice roll with the below code:

```<code>const min = 1;
const max = 7;

function diceRoll(random) {
    random = 0;
    while (random <= 0) {
        random = Math.floor(Math.random() * (max - min) + min);
        document.write('Dice # ' + random);
    }
}
</code>```

My html is:

```<code><button id="roll">Throw Dice</button>
</code>```

I haven't learned how to make buttons work, or how to start the javascript (other than writing it in the console. Can anyone help with how to create a button to make it work so I don't have to use the console? See below for what I've tried:

```<code>let button = document.getElementById('roll');

button.onclick = function() {
    let result = diceRoll();
    printNumber(result);
};
</code>```

Another try:

```<code> document.getElementById("roll").onclick = diceRoll();
</code>```

And another:

```<code>document.getElementById("roll").onclick = function() {
    diceRoll();
};
</code>```

答:
Codepen puts your script after the html, so the page is loaded by the time it gets to your script. This is important because if your script says document.getElementById('roll') but the page hasn't loaded, that element doesn't exist yet, and you won't have anything to be referencing- so you'll get null instead. That's no good. I bet that when you make a local file, you're not doing the same thing Codepen is doing. You're probably doing this:

```<code><html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }

            let button = document.getElementById('roll');

            button.onclick = function() {
                diceRoll();
            };
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
    </body>
</html>
</code>```

When you should be doing this:

```<code><html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
        <script>
            let button = document.getElementById('roll');

            button.onclick = function() {
                diceRoll();
            };
        </script>
    </body>
</html>
</code>```

Or this:

```<code><html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }

            window.addEventListener('load', (event) => {
                document.getElementById('roll').onclick = diceRoll;
            });
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
    </body>
</html>
</code>```

Or even this:

```<code><html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }
        </script>
    </head>
    <body>
        <button id="roll" onclick="diceRoll();">Throw Dice</button>
    </body>
</html>
</code>```

Believe it or not, there are still more ways to accomplish this that I haven't listed. The important thing is that they all let the element you're referencing load in the page before trying to grab it in JavaScript. Just choose the style of doing this that you like most and go with that.

Side note:

I saw that you also want a way to keep the button on the page. document.write clears the page, but you can just write your own output function that'll add your custom message to the innerHTML of a div on the page like this:

    <button id="roll" onclick="diceRoll();">Throw Dice</button>

```
</div>
</div>
</p>
<p>And as an extra bonus tip, using a tool called randojs, you can do this all as simply as this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <script src="https://randojs.com/1.0.0.js"></script>
  </head>
  <body>
    <button id="roll" onclick="document.getElementById('output').innerHTML += 'Dice # ' + rando(1, 6) + '<br/><br/>';">Throw Dice</button>
    <div id="output"></div>
  </body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
EDIT: So a few solutions work. Thing is, they work in codepen.io. But when I try to reload the actual HTML page from my computer to Chrome, the button clicks and shows nothing. Chrome is saying: 'dice.js:12 Uncaught TypeError: Cannot set property 'onclick' of null
    at dice.js:12.' How do I fix that?

I've looked at multiple similar questions that have different answers, and none of the answers I've tried has worked. I was able to make a random dice roll with the below code:

const min = 1;
const max = 7;

function diceRoll(random) {
    random = 0;
    while (random <= 0) {
        random = Math.floor(Math.random() * (max - min) + min);
        document.write('Dice # ' + random);
    }
}

My html is:

<button id="roll">Throw Dice</button>

I haven't learned how to make buttons work, or how to start the javascript (other than writing it in the console. Can anyone help with how to create a button to make it work so I don't have to use the console? See below for what I've tried:

let button = document.getElementById('roll');

button.onclick = function() {
    let result = diceRoll();
    printNumber(result);
};

Another try:

 document.getElementById("roll").onclick = diceRoll();

And another:

document.getElementById("roll").onclick = function() {
    diceRoll();
};

Body:
Codepen puts your script after the html, so the page is loaded by the time it gets to your script. This is important because if your script says document.getElementById('roll') but the page hasn't loaded, that element doesn't exist yet, and you won't have anything to be referencing- so you'll get null instead. That's no good. I bet that when you make a local file, you're not doing the same thing Codepen is doing. You're probably doing this:

<html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }

            let button = document.getElementById('roll');

            button.onclick = function() {
                diceRoll();
            };
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
    </body>
</html>

When you should be doing this:

<html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
        <script>
            let button = document.getElementById('roll');

            button.onclick = function() {
                diceRoll();
            };
        </script>
    </body>
</html>

Or this:

<html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }

            window.addEventListener('load', (event) => {
                document.getElementById('roll').onclick = diceRoll;
            });
        </script>
    </head>
    <body>
        <button id="roll">Throw Dice</button>
    </body>
</html>

Or even this:

<html>
    <head>
        <script>
            const min = 1;
            const max = 7;

            function diceRoll() {
                let random = 0;
                while (random <= 0) {
                    random = Math.floor(Math.random() * (max - min) + min);
                    document.write('Dice # ' + random);
                }
            }
        </script>
    </head>
    <body>
        <button id="roll" onclick="diceRoll();">Throw Dice</button>
    </body>
</html>

Believe it or not, there are still more ways to accomplish this that I haven't listed. The important thing is that they all let the element you're referencing load in the page before trying to grab it in JavaScript. Just choose the style of doing this that you like most and go with that.

Side note:

I saw that you also want a way to keep the button on the page. document.write clears the page, but you can just write your own output function that'll add your custom message to the innerHTML of a div on the page like this:

<html>
  <head>
    <script>
      const min = 1;
      const max = 7;

      function diceRoll() {
        let random = 0;
        while (random <= 0) {
          random = Math.floor(Math.random() * (max - min) + min);
          output('Dice # ' + random);
        }
      }

      function output(message) {
        document.getElementById("output").innerHTML += message + "<br/><br/>";
      }
    </script>
  </head>
  <body>
    <button id="roll" onclick="diceRoll();">Throw Dice</button>
    <div id="output"></div>
  </body>
</html>

And as an extra bonus tip, using a tool called randojs, you can do this all as simply as this:

<html>
  <head>
    <script src="https://randojs.com/1.0.0.js"></script>
  </head>
  <body>
    <button id="roll" onclick="document.getElementById('output').innerHTML += 'Dice # ' + rando(1, 6) + '<br/><br/>';">Throw Dice</button>
    <div id="output"></div>
  </body>
</html>


问:
How to make a component (popup modal) appear only once using React hooks or otherwise (React/Next js)
I want to make a popup modal appear only once per visit (I don't want it to appear every time someone goes back to the index page). Is there a way to do this using hooks or is there a better method?</p>

```<code> export default function Popup() {
        const [visible, setVisible] = React.useState(true);

        if(!visible) return null;

        return (
            <div className={styles.popup} onClick={() => setVisible(false)}>
                {/* <div className={styles.popupInner}> */}
                <div className={styles.popupInner}>
                    <div className={styles.buttonContainer}><Button color="danger" className={styles.button}>Okay</Button></div>
                </div>
                {/* </div> */}
            </div>
        )
    }
</code>```

答:
You could do with localstorage  and useEffect hook

why localstorage ?

You could achieve same result using useContext hook. But at the time of refresh.Hooks not hold the previous value.so better use localstorage to store the pop status

```<code>export default function Popup() {
        const [visible, setVisible] = React.useState(false);
        useEffect(()=>{
          let pop_status = localStorage.getItem('pop_status');
          if(!pop_status){
            setVisible(true);
            localStorage.setItem('pop_status',1);
          }
        },[])
        if(!visible) return null;

        return (
            <div className={styles.popup} onClick={() => setVisible(false)}>
                {/* <div className={styles.popupInner}> */}
                <div className={styles.popupInner}>
                    <div className={styles.buttonContainer}><Button color="danger" className={styles.button}>Okay</Button></div>
                </div>
                {/* </div> */}
            </div>
        )
    }
</code>```

Body:
I want to make a popup modal appear only once per visit (I don't want it to appear every time someone goes back to the index page). Is there a way to do this using hooks or is there a better method?

 export default function Popup() {
        const [visible, setVisible] = React.useState(true);

        if(!visible) return null;

        return (

 setVisible(false)}>
                {/*
 */}

<Button color="danger" className={styles.button}>Okay</Button>

                {/*
 */}

        )
    }

Body:
You could do with localstorage  and useEffect hook

why localstorage ?

You could achieve same result using useContext hook. But at the time of refresh.Hooks not hold the previous value.so better use localstorage to store the pop status

export default function Popup() {
        const [visible, setVisible] = React.useState(false);
        useEffect(()=>{
          let pop_status = localStorage.getItem('pop_status');
          if(!pop_status){
            setVisible(true);
            localStorage.setItem('pop_status',1);
          }
        },[])
        if(!visible) return null;

        return (
            <div className={styles.popup} onClick={() => setVisible(false)}>
                {/* <div className={styles.popupInner}> */}
                <div className={styles.popupInner}>
                    <div className={styles.buttonContainer}><Button color="danger" className={styles.button}>Okay</Button></div>
                </div>
                {/* </div> */}
            </div>
        )
    }


问:
AWS S3 Glacier upload-archive taking a long time to finish execution - ways to check status or speed upload?
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz
```

<p>I checked today, and found it still has yet to finish execution.</p>

<hr>

<p>My question is two parts:</p>

<ul>
<li>Is there some way to see that the command is still running?

<ul>
<li>A progress bar would be awesome</li>
</ul></li>
<li>Are there any ways (or alternate methods) to speed up the <code>upload-archive</code>?</li>
</ul>

<p>FYI, I am using <code>aws-cli==2.0.17</code>.  Thank you in advance for any help!</p>

<hr>

<p><strong>**Edit**</strong></p>

<p>After running for two days, the <code>upload-archive</code> command errored out with the below message:</p>

```An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118
```

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.

答:
Like Adi Dembak suggested I would instead use a multipart upload. By taking this approach you will be able to use the ProgessListener API to track its progress. See the following link for more details.
     https://docs.amazonaws.cn/en_us/AmazonS3/latest/dev/HLTrackProgressMPUJava.html</p>

Body:
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz

I checked today, and found it still has yet to finish execution.

My question is two parts:

Is there some way to see that the command is still running?

A progress bar would be awesome

Are there any ways (or alternate methods) to speed up the upload-archive?

FYI, I am using aws-cli==2.0.17.  Thank you in advance for any help!

**Edit**

After running for two days, the upload-archive command errored out with the below message:

An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.


问:
Can not configure 5GHz WiFi band for Beaglebone AI
I am trying to configure 5GHz WiFi band for my new Beaglebone AI.

What I am doing is

```<code>cp /tmp/hostapd-bbai.conf to /etc/hostapd.conf
</code>```

opening /etc/default/bb-wl18xx and changing USE_GENERATED_HOSTAPD to 'no'

```<code>USE_GENERATED_HOSTAPD=no
</code>```

in order to use /etc/hostapd.conf file instead of generated conf file from /tmp

this method works perfect for 'b' and 'g' but I can not configure to 'a' in order to use 5GHz band

Can anyone help me regarding this?

this is my hostapd.conf

```<code>interface=SoftAp0
ssid=BeagleBone-59A4
hw_mode=a
channel=1
wmm_enabled=1
country_code=IN
ieee80211d=1
ieee80211n=1
ieee80211ac=1
wmm_enabled=1
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=BeagleBone
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
logger_syslog=-1
logger_syslog_level=2
</code>```

答:
New Beagle Bone AI WIFI stack is more powerful and its auto handle.
if still you facing issue regarding any other interfaces then please follow below link :

https://github.com/MalavPatel3501/BeagleBone-AI--mpBBAI-IO-Python-Library

In this project you got .dts file and all pin muxing steps. Moreover i puts some example code in this project.

Body:
I am trying to configure 5GHz WiFi band for my new Beaglebone AI.

What I am doing is

cp /tmp/hostapd-bbai.conf to /etc/hostapd.conf

opening /etc/default/bb-wl18xx and changing USE_GENERATED_HOSTAPD to 'no'

USE_GENERATED_HOSTAPD=no

in order to use /etc/hostapd.conf file instead of generated conf file from /tmp

this method works perfect for 'b' and 'g' but I can not configure to 'a' in order to use 5GHz band

Can anyone help me regarding this?

this is my hostapd.conf

interface=SoftAp0
ssid=BeagleBone-59A4
hw_mode=a
channel=1
wmm_enabled=1
country_code=IN
ieee80211d=1
ieee80211n=1
ieee80211ac=1
wmm_enabled=1
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=BeagleBone
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
logger_syslog=-1
logger_syslog_level=2


答:
```<code>     export default function Popup() {
            const [visible, setVisible] = React.useState(true);

            if(!visible) return null;

            return (
                <div className={styles.popup}>
                <button onClick={() => setVisible(false)}>Click</button>

                    { visible ? <div className={styles.popupInner}>
                    <div className={styles.popupInner}>
                        <div className={styles.buttonContainer}>
                           <Button color="danger" className={styles.button}>Okay</Button>
                        </div>
                    </div>
                    </div> : "" }
                </div>
            )
        }
</code>```

Title: How to make a component (popup modal) appear only once using React hooks or otherwise (React/Next js)


问:
Looping through API response Node JS
I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this? </p>

<p>I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API. </p>

```<code>[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]
</code>```

答:
Worked it out, should have known now that I look at it, but to help anyone in the future I'll leave the solution. </p>

```<code>const fetch = require('node-fetch');

let settings = {
    method: "Get"
};

fetch('http://127.0.0.1:3000/test', settings)
    .then(res => res.json())
    .then((json) => {
        for (var i = 0; i < json.length; i++) {
            json.id = json[i].id;
            console.log(json.id);
        }
    });
</code>```

Title: Looping through API response Node JS

Body:
I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this?

I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API.

[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]

Body:
Worked it out, should have known now that I look at it, but to help anyone in the future I'll leave the solution.

const fetch = require('node-fetch');

let settings = {
    method: "Get"
};

fetch('http://127.0.0.1:3000/test', settings)
    .then(res => res.json())
    .then((json) => {
        for (var i = 0; i < json.length; i++) {
            json.id = json[i].id;
            console.log(json.id);
        }
    });


问:
Why is there a curled bracket on the List?
Recently stumped upon this line in a program, and I have no idea what the bracket for (List<Level>) is for . Anybody got any idea ?

List<Level> levelList = (List<Level>)dao.getAllLevels();

答: This casts the result of dao.getAllLevels(); to a List

ContentLicense: CC BY-SA 3.0


问:
Onclick event on moving images does not work
I am trying to count the numbers of clicks that click on the fox image.
But it does not works.
I am sure that this onclick function is works.

```<code>$(document).ready(function () {
    var i = 0;
    $(".fox").click(function(){
        $(".animal-quantity").html(i++);
    });
});
</code>```

Can anyone help me with this issue.
Thank you very much.
Link below is my full code.
https://jsfiddle.net/rbtj3ywo/1/

答:
Your pointer-events: none; is not correct.

$(document).ready(function () {
  var i = 0;
  $(".fox").on('click',function(){
      console.log("hi");
      $("#quantity > span").text(i++);
  });
 });

 (function() {
        var NUMBER_OF_ANIMALS = 10;

        function init() {
            /* Get a reference to the element that will contain the animals */
            var container = document.getElementById('animals');

            /* Fill the empty container with new animals */
            try {
                for (var i = 0; i < NUMBER_OF_ANIMALS; i++) {
                    container.appendChild(createAnimal());
                }
            }
            catch(e) {
            }
        }

        function randomInteger(low, high) {
            return low + Math.floor(Math.random() * (high - low));
        }

        function randomFloat(low, high) {
            return low + Math.random() * (high - low);
        }

        function pixelValue(value) {
            return value + 'px';
        }

        function durationValue(value) {
            return value + 's';
        }

        /*
         Uses an img element to create each animal.
         */
        function createAnimal() {
            /* Start by creating a wrapper div, and an empty img element */
            var animalDiv = document.createElement('div');
            var image = document.createElement('img');

            /* Randomly choose a animal image and assign it to the newly created element */
            image.src ='https://pngimage.net/wp-content/uploads/2018/05/cute-animals-png-4.png';
         image.style.width = randomInteger(7, 20) + 'vw';
            image.className = 'fox';

            /* Position the animal at a random location along the screen */
            animalDiv.style.top = pixelValue(randomInteger(-100, -250));
            animalDiv.style.left = randomInteger(0, 60) + 'vw';

            /* Set the -webkit-animation-name property with these values */
            animalDiv.style.webkitAnimationName ='fade, drop';
            animalDiv.style.animationName ='fade, drop';

            var fadeAndDropDuration = durationValue(randomFloat(1.2, 8.2));
            animalDiv.style.webkitAnimationDuration = fadeAndDropDuration + ', ' + fadeAndDropDuration;
            animalDiv.style.animationDuration = fadeAndDropDuration + ', ' + fadeAndDropDuration;

            var animalDelay = durationValue(randomFloat(0, 1));
            animalDiv.style.webkitAnimationDelay = animalDelay + ', ' + animalDelay;
            animalDiv.style.animationDelay = animalDelay + ', ' + animalDelay;
            animalDiv.appendChild(image);
            return animalDiv;
        }
        init();
    }
)();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fox {
  z-index: 100;
}

#animals {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            width: 100%;
            z-index: 98;
        }
        #animals > div {
            position: relative;
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-direction: normal, normal;
            -webkit-animation-timing-function: linear, ease-in;
            -webkit-backface-visibility: hidden;
            animation-iteration-count: infinite;
            animation-direction: normal, normal;
            animation-timing-function: linear, ease-in;
            backface-visibility: hidden;
        }
        #animals > div > img {
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-direction: alternate;
            -webkit-animation-timing-function: linear;
            -webkit-backface-visibility: hidden;
            animation-iteration-count: infinite;
            animation-direction: alternate;
            animation-timing-function: linear;
        }
        @-webkit-keyframes fade {
            0%, 90% {
                opacity: 1;
            }
            100% {
                opacity: 0;
            }
        }
        @keyframes fade {
            0%, 90% {
                opacity: 1;
            }
            100% {
                opacity: 0;
            }
        }
        @-webkit-keyframes drop {
            0% {
                -webkit-transform: translate3d(0, 0, 0);
            }
            100% {
                -webkit-transform: translate3d(0, 1100px, 0);
            }
        }
        @keyframes drop {
            0% {
                transform: translate3d(0, 0, 0);
            }
            100% {
                transform: translate3d(0, 1100px, 0);
            }
        }
        .quantity{
            position: absolute;
            left: 0;
            right: 0;
            text-align: center;
            top: 100px;
        }</code>```

Total quantity: 0
```

Body:
I am trying to count the numbers of clicks that click on the fox image.
But it does not works.
I am sure that this onclick function is works.

$(document).ready(function () {
    var i = 0;
    $(".fox").click(function(){
        $(".animal-quantity").html(i++);
    });
});

Can anyone help me with this issue.
Thank you very much.
Link below is my full code.
https://jsfiddle.net/rbtj3ywo/1/

Body:
Your pointer-events: none; is not correct.

$(document).ready(function () {
  var i = 0;
  $(".fox").on('click',function(){
      console.log("hi");
      $("#quantity > span").text(i++);
  });
 });

 (function() {
        var NUMBER_OF_ANIMALS = 10;

        function init() {
            /* Get a reference to the element that will contain the animals */
            var container = document.getElementById('animals');

            /* Fill the empty container with new animals */
            try {
                for (var i = 0; i < NUMBER_OF_ANIMALS; i++) {
                    container.appendChild(createAnimal());
                }
            }
            catch(e) {
            }
        }

        function randomInteger(low, high) {
            return low + Math.floor(Math.random() * (high - low));
        }

        function randomFloat(low, high) {
            return low + Math.random() * (high - low);
        }

        function pixelValue(value) {
            return value + 'px';
        }

        function durationValue(value) {
            return value + 's';
        }

        /*
         Uses an img element to create each animal.
         */
        function createAnimal() {
            /* Start by creating a wrapper div, and an empty img element */
            var animalDiv = document.createElement('div');
            var image = document.createElement('img');

            /* Randomly choose a animal image and assign it to the newly created element */
            image.src ='https://pngimage.net/wp-content/uploads/2018/05/cute-animals-png-4.png';
         image.style.width = randomInteger(7, 20) + 'vw';
            image.className = 'fox';

            /* Position the animal at a random location along the screen */
            animalDiv.style.top = pixelValue(randomInteger(-100, -250));
            animalDiv.style.left = randomInteger(0, 60) + 'vw';

            /* Set the -webkit-animation-name property with these values */
            animalDiv.style.webkitAnimationName ='fade, drop';
            animalDiv.style.animationName ='fade, drop';

            var fadeAndDropDuration = durationValue(randomFloat(1.2, 8.2));
            animalDiv.style.webkitAnimationDuration = fadeAndDropDuration + ', ' + fadeAndDropDuration;
            animalDiv.style.animationDuration = fadeAndDropDuration + ', ' + fadeAndDropDuration;

            var animalDelay = durationValue(randomFloat(0, 1));
            animalDiv.style.webkitAnimationDelay = animalDelay + ', ' + animalDelay;
            animalDiv.style.animationDelay = animalDelay + ', ' + animalDelay;
            animalDiv.appendChild(image);
            return animalDiv;
        }
        init();
    }
)();

.fox {
  z-index: 100;
}

#animals {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            width: 100%;
            z-index: 98;
        }
        #animals > div {
            position: relative;
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-direction: normal, normal;
            -webkit-animation-timing-function: linear, ease-in;
            -webkit-backface-visibility: hidden;
            animation-iteration-count: infinite;
            animation-direction: normal, normal;
            animation-timing-function: linear, ease-in;
            backface-visibility: hidden;
        }
        #animals > div > img {
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-direction: alternate;
            -webkit-animation-timing-function: linear;
            -webkit-backface-visibility: hidden;
            animation-iteration-count: infinite;
            animation-direction: alternate;
            animation-timing-function: linear;
        }
        @-webkit-keyframes fade {
            0%, 90% {
                opacity: 1;
            }
            100% {
                opacity: 0;
            }
        }
        @keyframes fade {
            0%, 90% {
                opacity: 1;
            }
            100% {
                opacity: 0;
            }
        }
        @-webkit-keyframes drop {
            0% {
                -webkit-transform: translate3d(0, 0, 0);
            }
            100% {
                -webkit-transform: translate3d(0, 1100px, 0);
            }
        }
        @keyframes drop {
            0% {
                transform: translate3d(0, 0, 0);
            }
            100% {
                transform: translate3d(0, 1100px, 0);
            }
        }
        .quantity{
            position: absolute;
            left: 0;
            right: 0;
            text-align: center;
            top: 100px;
        }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="animals"></div>
        <img src="https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/pf-misctexture01-beer-000_5.jpg?w=800&dpr=1&fit=default&crop=default&q=65&vib=3&con=3&usm=15&bg=F4F4F3&ixlib=js-2.2.1&s=c1552a7bdc2ea7b6e17d8d0d893c15be" class="background" style="width: 100%; position: relative;">
  <div class="quantity" id="quantity">Total quantity: <span class="animal-quantity">0</span></div>


答:
If I understand what you mean, you can use foreach to access any of the features of the object, such as the example below.

```<code>   Object.keys(obj).forEach(function(k){
          console.log(k + ' - ' + obj[k].id);
     });
</code>```

Title: Looping through API response Node JS

Body:
If I understand what you mean, you can use foreach to access any of the features of the object, such as the example below.

   Object.keys(obj).forEach(function(k){
          console.log(k + ' - ' + obj[k].id);
     });


问:
Why is negative (MSE or MAS) Scoring parameter like- neg_mean_absolute_error in SKLEARN is considered for regression model evaluation
I an a novice in Machine Learning and while going through the course I came across the "Scoring Parameter". I understood for Regression model evaluation, we consider the negatives of Mean Squared error, mean absolute error etc.

When I wanted to know the reason, I went through SKLearn documentation which says "All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as neg_mean_squared_error which return the negated value of the metric."

This explanation does not answer my why's completely and I am confused. So, why is the negatives taken more because logically if the difference in prediction is higher whether -ve or +ve, it makes our models equally bad. Then why is it that scoring parameter is focused on negative differences?

答:
It's simple: minimizing MSE is equivalent to maximizing negative-MSE.

An objective function that the scorer can maximize is just by "convention" as the Sklearn documentation suggests.


问:
Zend two submit buttons same name
I built a form class extending zend_form.I have two submitting buttons :

```<code>$like=new Zend_Form_Element_Image('vote');
$like->setImage($config->path->images."up.png")
->setValue(2);

$dislike=new Zend_Form_Element_Image('vote');
$dislike->setImage($config->path->images."down.png")
->setValue(1);
</code>```

I'd want to have two submit buttons with same name and different value so that I can later access the value of the submitted one  by a switch statement in the controller:

```<code>$submit = $this->_request->getPost('vote');

 switch($submit) {
 case 'one':
 // button one was pressed
 break;
 case 'two':
}

}
</code>```

But If I do set those with the same name the last one is overriding the first so only one button is output.

With file elements theres a method setMultifile() that does the trick.

what should I do here?

thanks

Luca

答:
As you have stated second button with the same name will overide the first.  The only solution I can think of is to use a viewScript for the form and add the button HTML manually.

I hope this helps.

Regards,

Garry

Title: Zend two submit buttons same name

Body:
I built a form class extending zend_form.I have two submitting buttons :

$like=new Zend_Form_Element_Image('vote');
$like->setImage($config->path->images."up.png")
->setValue(2);

$dislike=new Zend_Form_Element_Image('vote');
$dislike->setImage($config->path->images."down.png")
->setValue(1);

I'd want to have two submit buttons with same name and different value so that I can later access the value of the submitted one  by a switch statement in the controller:

$submit = $this->_request->getPost('vote');

 switch($submit) {
 case 'one':
 // button one was pressed
 break;
 case 'two':
}

}

But If I do set those with the same name the last one is overriding the first so only one button is output.

With file elements theres a method setMultifile() that does the trick.

what should I do here?

thanks

Luca


问:
How to Export CSV file from ASP.NET core
I am trying to migrate code from ASP.net to ASP.net core.

Where as in ASP.net code was like below,

```<code>var progresses = db.Progresses.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";
var csv = new CsvWriter(Response.Output);

csv.Configuration.RegisterClassMap<ReportCSVMap>();

Response.ClearContent();

Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition",
   "attachment; filename=" + downloadName);

csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}
Response.Flush();
Response.End();
return null;
</code>```

But while using it in ASP.NET core, I Converted it like,

```<code>var progresses = _elearnContext.Progress.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

// List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";

System.IO.TextWriter writeFile = new StreamWriter(Response.Body.ToString());
CsvWriter csv = new CsvWriter(writeFile);
csv.Configuration.RegisterClassMap<GroupReportCSVMap>();
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=" + downloadName);

csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}

Response.Clear();
return null;
</code>```

In ASP.net where Response.Output is available but its not available in core. So I tried to use it like Response.Body

Can Anybody tell me, where I did wrong?

答:
```<code>using CsvHelper;
using CsvHelper.Configuration;

namespace projectX.Controllers {
  [Route("MyController")]
  public class MyController : Controller {
    [Route("export")]
    [HttpGet]
    public ActionResult export() {
      var cc = new CsvConfiguration(new System.Globalization.CultureInfo("en-US"));
      using (var ms = new MemoryStream()) {
        using (var sw = new StreamWriter(stream: ms, encoding: new UTF8Encoding(true))) {
          using (var cw = new CsvWriter(sw, cc)) {
            cw.WriteRecords(YourGenericList);
          }// The stream gets flushed here.
          return File(ms.ToArray(), "text/csv", $"export_{DateTime.UtcNow.Ticks}.csv");
        }
      }
    }
  }
}
</code>```

Thanks to Exporting data to CSV from Controller

Body:
I am trying to migrate code from ASP.net to ASP.net core.

Where as in ASP.net code was like below,

var progresses = db.Progresses.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";
var csv = new CsvWriter(Response.Output);

csv.Configuration.RegisterClassMap<ReportCSVMap>();

Response.ClearContent();

Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition",
   "attachment; filename=" + downloadName);

csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}
Response.Flush();
Response.End();
return null;

But while using it in ASP.NET core, I Converted it like,

var progresses = _elearnContext.Progress.Where(p => p.UserId == id).Include(p => p.User.UserMetaData).Include(p => p.Quiz).Include(p => p.User.Groups).OrderByDescending(p => p.UpdatedAt).ToList();

// List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
List<ReportCSVModel> reportCSVModels = new List<ReportCSVModel>();
const string downloadName = "Reports.csv";

System.IO.TextWriter writeFile = new StreamWriter(Response.Body.ToString());
CsvWriter csv = new CsvWriter(writeFile);
csv.Configuration.RegisterClassMap<GroupReportCSVMap>();
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=" + downloadName);

csv.WriteHeader<ReportCSVModel>();
foreach (var progress in progresses)
{
    var reportCSVModel = new ReportCSVModel();
    reportCSVModel.Quiz = progress.Quiz.Title;
    reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString();
    reportCSVModel.Status = progress.Status;
    reportCSVModel.CompletedDate = progress.UpdatedAt.ToString();
    reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "";
    reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "";

    csv.WriteRecord<ReportCSVModel>(reportCSVModel);
}

Response.Clear();
return null;

In ASP.net where Response.Output is available but its not available in core. So I tried to use it like Response.Body

Can Anybody tell me, where I did wrong?

Body:
using CsvHelper;
using CsvHelper.Configuration;

namespace projectX.Controllers {
  [Route("MyController")]
  public class MyController : Controller {
    [Route("export")]
    [HttpGet]
    public ActionResult export() {
      var cc = new CsvConfiguration(new System.Globalization.CultureInfo("en-US"));
      using (var ms = new MemoryStream()) {
        using (var sw = new StreamWriter(stream: ms, encoding: new UTF8Encoding(true))) {
          using (var cw = new CsvWriter(sw, cc)) {
            cw.WriteRecords(YourGenericList);
          }// The stream gets flushed here.
          return File(ms.ToArray(), "text/csv", $"export_{DateTime.UtcNow.Ticks}.csv");
        }
      }
    }
  }
}

Thanks to Exporting data to CSV from Controller


问:
Rails and JQuery-Load DB data into Textfields for save and delete
I have below data in database.My requirement-I have two options in dropdwon Get and Set. If i select Set option from dropdown , textfields along with checkbox needs to be created inside table dynamically with values of database ParaName,Datatype,Values as below.User can edit and delete records by selecting checkbox.I am new to ruby on rails.Can someone help,how to implement this?

UI Design look like below format

```<code> ParaName DataType  Value

Textfield1 Textfield2 Textfield3
TestData1   String     test      Checkbox
TestData2   boolean    true      Checkbox
TestData3   int        3         Checkbox

Button   Button
Save     Delete
</code>```

DATABASE

```<code>ParaName|DataType|Value
TestData1|String  |test
TestData2|boolean |true
TestData3|int     |3

</code>```

Thanks,
Suba

答:
The get/set dropdown can use the data-remote attribute to fire javascript through the controller, like this in [name of controller method].html.erb

```<code><%= select_tag :type, options_for_select([ "Get", "Set" ]), include_blank: true, data: { remote: true, url: '/same_path' } %>
<div id="fields"></div>
</code>```

In the controller

```<code>respond_to :html, :js
</code>```

[name of controller method].js.erb file

```<code>$('#fields').html("<%= j render partial: 'fields' %>");
</code>```

In _fields.html.erb render the fields as necessary. You can get the type that was selected in the get/set dropdown with params[:type]. If you need to load database objects in the controller to work with in any of the partials, you can do so like this

```<code>respond_to do |format|
  @types = Model.all
  format.html {
    # perform logic here for the html view
  }
  format.js {
    # perform logic here for the javascript view
  }
end
</code>```

Body:
I have below data in database.My requirement-I have two options in dropdwon Get and Set. If i select Set option from dropdown , textfields along with checkbox needs to be created inside table dynamically with values of database ParaName,Datatype,Values as below.User can edit and delete records by selecting checkbox.I am new to ruby on rails.Can someone help,how to implement this?

UI Design look like below format

 ParaName DataType  Value

Textfield1 Textfield2 Textfield3
TestData1   String     test      Checkbox
TestData2   boolean    true      Checkbox
TestData3   int        3         Checkbox

Button   Button
Save     Delete

DATABASE

ParaName|DataType|Value
TestData1|String  |test
TestData2|boolean |true
TestData3|int     |3

Thanks,
Suba

Body:
The get/set dropdown can use the data-remote attribute to fire javascript through the controller, like this in [name of controller method].html.erb

<%= select_tag :type, options_for_select([ "Get", "Set" ]), include_blank: true, data: { remote: true, url: '/same_path' } %>
<div id="fields"></div>

In the controller

respond_to :html, :js

[name of controller method].js.erb file

$('#fields').html("<%= j render partial: 'fields' %>");

In _fields.html.erb render the fields as necessary. You can get the type that was selected in the get/set dropdown with params[:type]. If you need to load database objects in the controller to work with in any of the partials, you can do so like this

respond_to do |format|
  @types = Model.all
  format.html {
    # perform logic here for the html view
  }
  format.js {
    # perform logic here for the javascript view
  }
end


问:
why is this regex in C++ throwing an invalid range in bracket expression exception?
I am playing around with C++ regular expression:

```<code>#include <iostream>
#include <regex>
using namespace std;

int main()
{
   std::regex e("[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]");
   std::string str = "¡";//u00A1, trying to match this character
   bool match = std::regex_match(str, e);
   cout << match << endl;

   return 0;
}
</code>```

The compilation failed with exception thrown:

```<code>terminate called after throwing an instance of 'std::regex_error'
what():  Invalid range in bracket expression.
</code>```

I tested on regex101.com with:

```<code>[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]
</code>```

and it gives me a match.

Also, is regex in C++ using the ECMAScript flavor?  Thanks.

答:
The problem is that you are using a char based regex but a 16 bit regular expression. Try switching to wchar_t as your character type.

```<code>#include <iostream>
#include <regex>
using namespace std;

int main()
{
   std::wregex e(L"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]");
   std::wstring str = L"¡";//u00A1, trying to match this character
   bool match = std::regex_match(str, e);
   cout << match << endl;

   return 0;
}
</code>```

Body:
I am playing around with C++ regular expression:

#include <iostream>
#include <regex>
using namespace std;

int main()
{
   std::regex e("[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]");
   std::string str = "¡";//u00A1, trying to match this character
   bool match = std::regex_match(str, e);
   cout << match << endl;

   return 0;
}

The compilation failed with exception thrown:

terminate called after throwing an instance of 'std::regex_error'
what():  Invalid range in bracket expression.

I tested on regex101.com with:

[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]

and it gives me a match.

Also, is regex in C++ using the ECMAScript flavor?  Thanks.

Body:
The problem is that you are using a char based regex but a 16 bit regular expression. Try switching to wchar_t as your character type.

#include <iostream>
#include <regex>
using namespace std;

int main()
{
   std::wregex e(L"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]");
   std::wstring str = L"¡";//u00A1, trying to match this character
   bool match = std::regex_match(str, e);
   cout << match << endl;

   return 0;
}


问:
Which model should use VAR or VECM in the following problem?
I have three variables, all are nonstationary at levels but stationary at first difference I(1) and there exist cointegration among the variable. The problem is, should I go for VAR or VECM model?  </p>

答:
since there is statistical evidence of cointegration between the series, you can take advantage of the related series by using a VECM model. Here is an example of an R code, where Xt, Yt and Zt are the series you are analyzing:  </p>

```<code>#VECM model estimation

library(tsDyn)
data<-cbind(Xt,Yt,Zt)
vecm<-VECM(data,lag=1,estim="2OLS")
summary(vecm)
</code>```

Body:
since there is statistical evidence of cointegration between the series, you can take advantage of the related series by using a VECM model. Here is an example of an R code, where Xt, Yt and Zt are the series you are analyzing:

#VECM model estimation

library(tsDyn)
data<-cbind(Xt,Yt,Zt)
vecm<-VECM(data,lag=1,estim="2OLS")
summary(vecm)


问:
How can i remove special character from a variable using perl
This is my sample code

```<code>#!/usr/bin/perl
$file = SUN;
$file1 = abc.$file.cde
print "Value is : $file1\n"
</code>```

I want Output like this abcSUNcde
What regular expression need for this.

答:
As well ikegami said in his comment you are missing the semicolons at the end of the line (terminating the line or line should be ended).

```<code>#!/usr/bin/perl
$file = SUN;
$file1 = "abc${file}cde";
print "Value is : $file1\n";
</code>```

This is will print abcSUNcde as an output of your code.

In case if you want to remove the special characters (what I understand except keyboarding characters)

```<code>$file2=~s/[^A-Za-z]//g;
</code>```

Let try this and modify as well you can.

Body:
This is my sample code

#!/usr/bin/perl
$file = SUN;
$file1 = abc.$file.cde
print "Value is : $file1\n"

I want Output like this abcSUNcde
What regular expression need for this.

Body:
As well ikegami said in his comment you are missing the semicolons at the end of the line (terminating the line or line should be ended).

#!/usr/bin/perl
$file = SUN;
$file1 = "abc${file}cde";
print "Value is : $file1\n";

This is will print abcSUNcde as an output of your code.

In case if you want to remove the special characters (what I understand except keyboarding characters)

$file2=~s/[^A-Za-z]//g;

Let try this and modify as well you can.


问:
HTML2canvas generates Blurry images
I am using jsPDF and it uses html2canvas to generate an image from some html element and insert on the .pdf file. But there is a problem on html2canvas, it generates blurry images from the html. See example below:

HTML content:

http://puu.sh/7SZz4.png

html2canvas generated image:

http://puu.sh/7SZAT.png

Is there any way to fix it or is there any better option to get the image form html?

thanks!

答:
I was facing this problem and i solved it by using domtoimage instead of html2canvas.

This HTML2CANVAS solution was not working good for me i know the scale option does increase the target div's size before capturing it but it won't work if you have something inside that div which won't resize e.g in my case it was canvas for my editing tool.

Anyway for this i opted for domtoimage and trust me i think that this is the best solution of them all.

I didn't had to face any problem of html2canvas for example:

need to be at the top of webpage so html2canvas can capture the shot completely and low dpi problem

```<code>function print()
{
    var node = document.getElementById('shirtDiv');
    var options = {
        quality: 0.95
    };

    domtoimage.toJpeg(node, options).then(function (dataUrl)
    {
        var doc = new jsPDF();
        doc.addImage(dataUrl, 'JPEG', -18, 20, 240, 134.12);
        doc.save('Test.pdf');
    });
}
</code>```

Cdn for dom to image:

https://cdnjs.com/libraries/dom-to-image

Cdn for jspdf:

https://cdnjs.com/libraries/jspdf

Title: HTML2canvas generates Blurry images

Body:
I was facing this problem and i solved it by using domtoimage instead of html2canvas.

This HTML2CANVAS solution was not working good for me i know the scale option does increase the target div's size before capturing it but it won't work if you have something inside that div which won't resize e.g in my case it was canvas for my editing tool.

Anyway for this i opted for domtoimage and trust me i think that this is the best solution of them all.

I didn't had to face any problem of html2canvas for example:

need to be at the top of webpage so html2canvas can capture the shot completely and low dpi problem

function print()
{
    var node = document.getElementById('shirtDiv');
    var options = {
        quality: 0.95
    };

    domtoimage.toJpeg(node, options).then(function (dataUrl)
    {
        var doc = new jsPDF();
        doc.addImage(dataUrl, 'JPEG', -18, 20, 240, 134.12);
        doc.save('Test.pdf');
    });
}

Cdn for dom to image:

https://cdnjs.com/libraries/dom-to-image

Cdn for jspdf:

https://cdnjs.com/libraries/jspdf


问:
Stuck in the middle
When should I use margin-left:auto; margin-right:auto to center and when should I use margin-left:50%; margin-right:50%?

Maybe "auto" when I am centering something contained in another element & 50% when I am centering on the page?

Or I am I just hopelessly confused?

答:
To Center a div container you need to give it a width and a hight than you use </p>

<pre class="lang-css prettyprint-override"><code>#div {
   height: 700px;
   width: 1000px;
   margin: 0 auto;
}
</code>```

Title: Stuck in the middle

Body:
To Center a div container you need to give it a width and a hight than you use

#div {
   height: 700px;
   width: 1000px;
   margin: 0 auto;
}


问:
How to append multiple child elements in the DOM and display them, using vanilla javascript?
I am trying to insert some SVG icons in the dom but the SVG(parent node) is always being replaced by the use(child node). Anyone help me figure it out?

Source code Image here

Codepen here

```<code>const icons = [
    "html5" ,
    "css3" ,
    "javascript" ,
    "bootstrap" ,
    "sass" ,
    "node" ,
    "mongodb" ,
    "d3" ,
    "react" ,
    "webpack" ,
    "wordpress"
];

const tech_icons = document.querySelector( "#techs__icons" );

icons.forEach( icon=> {

    const svg = document.createElement( "svg" );
    const use = document.createElement( "use" );

        svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );

    tech_icons.appendChild( use ).appendChild( use );

} );
</code>```

I can successfully log them in the console but they don't seem to appear on the document.

I appended it already to the parent node (techs_icons) but can't figure it out at this point!

UPDATED CODE

```<code>icons.forEach( icon=> {

    const tech_icons = document.querySelector( "#techs__icons" );

    const svg = document.createElement( "svg" );
    svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    const use = document.createElement( "use" );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );

    svg.appendChild( use );

    tech_icons.appendChild( svg );

} );
</code>```

This snapshot seems to work here

Still won't be displayed in the DOM. Actually, they are being appended because when I hover them over in the inspector they are there but not visible.

SECOND UPDATE TO THE CODE

It looks like you need to create some kind of "fake" element inside my svg>use>"fake element", like a shadowRoot which i actually do not understand why the browser creates such an element when importing SVG files!

I figured it out when inspecting the element and saw that the browser actually creates automatically that shadow.

SVG

```<code><symbol id="icon-html5">
   <path d="M2 0h28l-2.547 28.751-11.484 3.249-11.419-3.251-2.551-28.749zM11.375 13l-0.309-3.624 13.412 0.004 0.307-3.496-17.568-0.004 0.931 10.68h12.168l-0.435 4.568-3.88 1.072-3.94-1.080-0.251-2.813h-3.479l0.44 5.561 7.229 1.933 7.172-1.924 0.992-10.876h-12.789z"/>
 </symbol>
</code>```

Inspected code showing the auto created shadow element

```<code>const tech_icons = document.querySelector( "#techs__icons" );
const fragment = document.createDocumentFragment();

icons.forEach( icon => {

    const svg = document.createElement( "svg" );
    const use = document.createElement( "use" );
    let shadow = use.attachShadow( { mode : open } );

    svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );
    shadow.appendChild( "I am a: child element inside shadowroot (svg>use>shadowroot>ME)" );

   svg.appendChild( use );

   fragment.appendChild( svg );

});

tech_icons.appendChild( fragment );
</code>```

So at this point to recap:

Added the result for the forEach() loop to a document fragment and after that loop ended i appended that fragment as a child to the real DOM element (.techs_info)

Created a shadow and also append it as a child to the use element

Problem still exists, while when appending the shadow to the use element neither the DOM or the console does not actually display anything!

答:
```<code>componentDidMount (){

    const script = document.createElement("script");
    const script1 = document.createElement("script");
    const script2 = document.createElement("script");

    script.src = 'assets/js/jquery.showmore.js';
    script1.src = 'assets/js/showmore.js';
    script2.src = 'assets/js/owl-carousel.js';
    script.async = true;
    script1.async = true;
    script2.async = true;

    document.body.appendChild(script);
    document.body.appendChild(script1);
    document.body.appendChild(script2);
}
</code>```

Body:
I am trying to insert some SVG icons in the dom but the SVG(parent node) is always being replaced by the use(child node). Anyone help me figure it out?

Source code Image here

Codepen here

const icons = [
    "html5" ,
    "css3" ,
    "javascript" ,
    "bootstrap" ,
    "sass" ,
    "node" ,
    "mongodb" ,
    "d3" ,
    "react" ,
    "webpack" ,
    "wordpress"
];

const tech_icons = document.querySelector( "#techs__icons" );

icons.forEach( icon=> {

    const svg = document.createElement( "svg" );
    const use = document.createElement( "use" );

        svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );

    tech_icons.appendChild( use ).appendChild( use );

} );

I can successfully log them in the console but they don't seem to appear on the document.

I appended it already to the parent node (techs_icons) but can't figure it out at this point!

UPDATED CODE

icons.forEach( icon=> {

    const tech_icons = document.querySelector( "#techs__icons" );

    const svg = document.createElement( "svg" );
    svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    const use = document.createElement( "use" );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );

    svg.appendChild( use );

    tech_icons.appendChild( svg );

} );

This snapshot seems to work here

Still won't be displayed in the DOM. Actually, they are being appended because when I hover them over in the inspector they are there but not visible.

SECOND UPDATE TO THE CODE

It looks like you need to create some kind of "fake" element inside my svg>use>"fake element", like a shadowRoot which i actually do not understand why the browser creates such an element when importing SVG files!

I figured it out when inspecting the element and saw that the browser actually creates automatically that shadow.

SVG

<symbol id="icon-html5">
   <path d="M2 0h28l-2.547 28.751-11.484 3.249-11.419-3.251-2.551-28.749zM11.375 13l-0.309-3.624 13.412 0.004 0.307-3.496-17.568-0.004 0.931 10.68h12.168l-0.435 4.568-3.88 1.072-3.94-1.080-0.251-2.813h-3.479l0.44 5.561 7.229 1.933 7.172-1.924 0.992-10.876h-12.789z"/>
 </symbol>

Inspected code showing the auto created shadow element

const tech_icons = document.querySelector( "#techs__icons" );
const fragment = document.createDocumentFragment();

icons.forEach( icon => {

    const svg = document.createElement( "svg" );
    const use = document.createElement( "use" );
    let shadow = use.attachShadow( { mode : open } );

    svg.setAttribute( "class" , `techs__icon icon icon-${icon}` );
    use.setAttribute( "href" , `./src/images/sprites.svg#icon-${icon}` );
    shadow.appendChild( "I am a: child element inside shadowroot (svg>use>shadowroot>ME)" );

   svg.appendChild( use );

   fragment.appendChild( svg );

});

tech_icons.appendChild( fragment );

So at this point to recap:

Added the result for the forEach() loop to a document fragment and after that loop ended i appended that fragment as a child to the real DOM element (.techs_info)

Created a shadow and also append it as a child to the use element

Problem still exists, while when appending the shadow to the use element neither the DOM or the console does not actually display anything!


问:
converting error with using Convert.ToDateTime in asp.net C#
Before that, the code was working fine, while the program didn't recognize the date format may be because of different cultureInfo.
I am using the Convert.ToDateTime method to convert the DateTime format.

```<code>Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value).ToString("yyyy-MM-dd HH:mm:ss");
</code>```

As a result, it converted but with incorrect MM and dd.

From "1/6/2020" To "2020-01-06 00:00:00"

```<code>string test1 = gvwTest.Rows[i].Cells["TxnDate"].Value.ToString();
string test2 = gvwTest.Rows[i].Cells["TxnDate"].Value.GetType().ToString();

test1 = "1/6/2020";
test2 = "System.String";
</code>```

答:
You can use DateTime.ParseExact

```<code>CultureInfo provider = CultureInfo.InvariantCulture;
var date = DateTime.ParseExact("1/6/2020", "M/d/yyyy", provider);
var dateString = date.ToString("yyyy-MM-dd HH:mm:ss");
</code>```

Outputs - 2020-01-06 00:00:00

In my example I have used as input 1/6/2020.

Body:
Before that, the code was working fine, while the program didn't recognize the date format may be because of different cultureInfo.
I am using the Convert.ToDateTime method to convert the DateTime format.

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value).ToString("yyyy-MM-dd HH:mm:ss");

As a result, it converted but with incorrect MM and dd.

From "1/6/2020" To "2020-01-06 00:00:00"

string test1 = gvwTest.Rows[i].Cells["TxnDate"].Value.ToString();
string test2 = gvwTest.Rows[i].Cells["TxnDate"].Value.GetType().ToString();

test1 = "1/6/2020";
test2 = "System.String";

Body:
You can use DateTime.ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
var date = DateTime.ParseExact("1/6/2020", "M/d/yyyy", provider);
var dateString = date.ToString("yyyy-MM-dd HH:mm:ss");

Outputs - 2020-01-06 00:00:00

In my example I have used as input 1/6/2020.


问:
How to make blog layout with Html Css
I am a beginner in web designing. I know some basics about layout in CSS.
I am tried to create a blog post layout, given in the picture below.
see image layout
Please help me to do that.</p>

答:
Welcome to StackOverflow! As heads up, usually you will want to come here for more specific questions to solve problems with your code, or to explain weird behavior you didn't quite understand. Your question is a little bit too open ended to be answered here but I can help you get started:

For starters, start thinking about translating every box in your picture into an HTML div. If you break each part of that picture into divs it can be a good foundation to add your css styling on top of. In your case, you might want something like this:

```

Of course you would be generating each row inside a for loop or .map() type function. You would also add in your .css in a 'class' attribute for every div.

Please let me know if you find this helpful by selecting my post as the answer, and don't be shy if you have any more questions :)

Title: How to make blog layout with Html Css

Body:
Welcome to StackOverflow! As heads up, usually you will want to come here for more specific questions to solve problems with your code, or to explain weird behavior you didn't quite understand. Your question is a little bit too open ended to be answered here but I can help you get started:

For starters, start thinking about translating every box in your picture into an HTML div. If you break each part of that picture into divs it can be a good foundation to add your css styling on top of. In your case, you might want something like this:

<div id="articleList">
  <div id="article_1">
    <div id="articleImage_1">
      <img src="articleImage_1.jpg" alt="Picture #1">
    </div>
    <div id="articleContent_1">
      <div id="articleTags_1"></div>
      <div id="articleTitle_1"></div>
      <div id="articleAuthorNameAndCommentsSubheader_1"></div>
      <div id="articleBody_1"></div>
    </div>
  </div>
  <div id="article_2">
    <div id="articleImage_2">
      <img src="articleImage_2.jpg" alt="Picture #2">
    </div>
    <div id="articleContent_2">
      <div id="articleTags_2"></div>
      <div id="articleTitle_2"></div>
      <div id="articleAuthorNameAndCommentsSubheader_2"></div>
      <div id="articleBody_2"></div>
    </div>
  </div>
</div>

Of course you would be generating each row inside a for loop or .map() type function. You would also add in your .css in a 'class' attribute for every div.

Please let me know if you find this helpful by selecting my post as the answer, and don't be shy if you have any more questions :)


问:
Is there a way to add a column of type dictionary to a spark dataframe in pyspark?
This is how I create a dataframe with primitive data types in pyspark:

```<code>from pyspark.sql.types import StructType, StructField, DoubleType, StringType, IntegerType
fields = [StructField('column1', IntegerType(), True), StructField('column2', IntegerType(), True)]
schema = StructType(fields)
df = spark.createDataFrame([], schema)
values = [tuple([i]) +
          tuple([i])
          for i in range(3)]
df = spark.createDataFrame(values, schema)
</code>```

Now, if I want to have a third column with dictionary data, eg: {"1": 1.0, "2": 2.0, "3": 3.0}, what should I do?
I want to create this data frame:

```<code>+--------------------+-----------------+------------------------------+
|column1             |column2          |column3                       |
+--------------------+-----------------+------------------------------+
|1                   |1                |{"1": 1.0, "2": 1.0, "3": 1.0}|
+--------------------+-----------------+------------------------------+
|2                   |2                |{"1": 2.0, "2": 2.0, "3": 2.0}|
+--------------------+-----------------+------------------------------+
|3                   |3                |{"1": 3.0, "2": 3.0, "3": 3.0}|
+--------------------+-----------------+------------------------------+
</code>```

There is a MapType that seems to be helpful, but I can't figure out how to use it?

And assuming the data frame is created, how to filter it based on the third column, given a dict to select the rows of the data frame that have that dict value?

答:
You can do this without UDF using, create_map(spark2.0+), you can create a new column of MapType, using ur dictionary to be used, and then use filter as shown below to get all rows where my_dict is equal to column3.

```<code>from pyspark.sql import functions as F

df.show() #sample dataframe
my_dict = {'b':3.7, 'e':4.9} #dictionary to filter with

#+-------+-------+--------------------+
#|column1|column2|             column3|
#+-------+-------+--------------------+
#|      1|      2|[a -> 3.5, b -> 4.2]|
#|      4|      8|[e -> 4.9, b -> 3.7]|
#+-------+-------+--------------------+

from pyspark.sql import functions as F

df.withColumn("map", F.create_map(*[item for sublist in [[F.lit(x),F.lit(y)]\
                                for x,y in my_dict.items()] for item in sublist]))\
  .filter(' and '.join(["column3.{0}=map.{0}".format(x) for x in my_dict.keys()])+\
          ' and size(column3)=size(map)').drop("map").show()

#+-------+-------+--------------------+
#|column1|column2|             column3|
#+-------+-------+--------------------+
#|      4|      8|[e -> 4.9, b -> 3.7]|
#+-------+-------+--------------------+
</code>```

Body:
This is how I create a dataframe with primitive data types in pyspark:

from pyspark.sql.types import StructType, StructField, DoubleType, StringType, IntegerType
fields = [StructField('column1', IntegerType(), True), StructField('column2', IntegerType(), True)]
schema = StructType(fields)
df = spark.createDataFrame([], schema)
values = [tuple([i]) +
          tuple([i])
          for i in range(3)]
df = spark.createDataFrame(values, schema)

Now, if I want to have a third column with dictionary data, eg: {"1": 1.0, "2": 2.0, "3": 3.0}, what should I do?
I want to create this data frame:

+--------------------+-----------------+------------------------------+
|column1             |column2          |column3                       |
+--------------------+-----------------+------------------------------+
|1                   |1                |{"1": 1.0, "2": 1.0, "3": 1.0}|
+--------------------+-----------------+------------------------------+
|2                   |2                |{"1": 2.0, "2": 2.0, "3": 2.0}|
+--------------------+-----------------+------------------------------+
|3                   |3                |{"1": 3.0, "2": 3.0, "3": 3.0}|
+--------------------+-----------------+------------------------------+

There is a MapType that seems to be helpful, but I can't figure out how to use it?

And assuming the data frame is created, how to filter it based on the third column, given a dict to select the rows of the data frame that have that dict value?

Body:
You can do this without UDF using, create_map(spark2.0+), you can create a new column of MapType, using ur dictionary to be used, and then use filter as shown below to get all rows where my_dict is equal to column3.

from pyspark.sql import functions as F

df.show() #sample dataframe
my_dict = {'b':3.7, 'e':4.9} #dictionary to filter with

#+-------+-------+--------------------+
#|column1|column2|             column3|
#+-------+-------+--------------------+
#|      1|      2|[a -> 3.5, b -> 4.2]|
#|      4|      8|[e -> 4.9, b -> 3.7]|
#+-------+-------+--------------------+

from pyspark.sql import functions as F

df.withColumn("map", F.create_map(*[item for sublist in [[F.lit(x),F.lit(y)]\
                                for x,y in my_dict.items()] for item in sublist]))\
  .filter(' and '.join(["column3.{0}=map.{0}".format(x) for x in my_dict.keys()])+\
          ' and size(column3)=size(map)').drop("map").show()

#+-------+-------+--------------------+
#|column1|column2|             column3|
#+-------+-------+--------------------+
#|      4|      8|[e -> 4.9, b -> 3.7]|
#+-------+-------+--------------------+


问:
CreateProcess error=2, The system cannot find the file specified [Android studio]
I upgraded my windows and reinstalled Android studio 0.3.2. I am using windows8.1 Pro now and installed java x64, I also did set up JAVA_HOME EV to C:\Program Files\Java\jdk1.7.0_45 and Android studio is installed in D:\Android Stutio\

When I try to run my project I get the Following Error

Cannot run program "C:\Program Files (x86)\Java\jdk1.7.0_40\bin\java" (in directory "D:\Android Stutio\system\compile-server"): CreateProcess error=2, The system cannot find the file specified

Android studio is installed in D:\Android Stutio\

How to fix this one

答:
I am getting this because of ndk path .

Check the ndk path in local.properties file & also check the sdk path .
Delete the build file , sometimes it makes the error in case you are migrating the project from Linux to windows or vice versa .

Then click invalidate cache and restart .

Mine this solved this issue . Hope this will help you .


问:
I am trying to create a action card using CDS but facing below issue on request
Body Content:

```<code>{
 "@odata.context": "https://aaaaaaaaaaaaaaaaa.crm.dynamics.com/api/data/v9.0/$metadata#actioncards/$entity",

"_cardtypeid_value@OData.Community.Display.V1.FormattedValue": "CloseDateComingSoon",
"_cardtypeid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": "cardtypeid",
"_cardtypeid_value@Microsoft.Dynamics.CRM.lookuplogicalname": "cardtype",
"_cardtypeid_value": "c16b8555-d33a-4e98-8188-1b123efbd4e9",

"_ownerid_value@OData.Community.Display.V1.FormattedValue": "Sudhakar Marreddy",
"_ownerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": "ownerid",
"_ownerid_value@Microsoft.Dynamics.CRM.lookuplogicalname": "systemuser",
 "_ownerid_value": "f6fa6fa7-0bac-e711-8114-c4346bdca111",

"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",

"expirydate": "2020-06-27T21:36:05Z",
"priority": 400,
"source": 1,
"startdate": "2020-05-19T01:36:05Z",
"state": 0,
"visibility": true,
"title": "TestingRACards_5/19_via_postman",
"description": "This Works! RA Cards created successfullt from Postman"

}
</code>```

Result :

```<code>{
"error": {
    "code": "0x0",
    "message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
    "innererror": {
        "message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
        "type": "Microsoft.Crm.CrmHttpException",
        "stacktrace": "   at Microsoft.Crm.Extensibility.OData.TypeConverters.EntityReferenceAttributeTypeConverter.ConvertToCrmTypeInternal(Guid edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.SetStructuralPropertyToXrmEntity(Entity entity, EntityMetadata entityMetadata, String crmAttributeName, IEdmProperty edmProperty, Object propertyValue)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.ConvertToCrmTypeInternal(EdmEntityObject edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.EdmTypeConverter.ConvertToCrmEntity(EdmEntityObject edmEntity, EntityReference entityReference, IEdmModel edmModel)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)\r\n   at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
    }
}
}
</code>```

答:
```<code>"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",
</code>```

Instead of this line, you should get something similar to _ownerid_value for _regardingobjectid_value. So some simple assignment issue.

Use this below snippet for assignment of regardingobjectid lookup: (make sure you are using correct entity in place of accounts)

```<code>"regardingobjectid@odata.bind": "/accounts(77af6f8e-f55d-e811-a83d-000d3a1bbafa)",
</code>```

Body:
Body Content:

{
 "@odata.context": "https://aaaaaaaaaaaaaaaaa.crm.dynamics.com/api/data/v9.0/$metadata#actioncards/$entity",

"_cardtypeid_value@OData.Community.Display.V1.FormattedValue": "CloseDateComingSoon",
"_cardtypeid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": "cardtypeid",
"_cardtypeid_value@Microsoft.Dynamics.CRM.lookuplogicalname": "cardtype",
"_cardtypeid_value": "c16b8555-d33a-4e98-8188-1b123efbd4e9",

"_ownerid_value@OData.Community.Display.V1.FormattedValue": "Sudhakar Marreddy",
"_ownerid_value@Microsoft.Dynamics.CRM.associatednavigationproperty": "ownerid",
"_ownerid_value@Microsoft.Dynamics.CRM.lookuplogicalname": "systemuser",
 "_ownerid_value": "f6fa6fa7-0bac-e711-8114-c4346bdca111",

"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",

"expirydate": "2020-06-27T21:36:05Z",
"priority": 400,
"source": 1,
"startdate": "2020-05-19T01:36:05Z",
"state": 0,
"visibility": true,
"title": "TestingRACards_5/19_via_postman",
"description": "This Works! RA Cards created successfullt from Postman"

}

Result :

{
"error": {
    "code": "0x0",
    "message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
    "innererror": {
        "message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
        "type": "Microsoft.Crm.CrmHttpException",
        "stacktrace": "   at Microsoft.Crm.Extensibility.OData.TypeConverters.EntityReferenceAttributeTypeConverter.ConvertToCrmTypeInternal(Guid edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.SetStructuralPropertyToXrmEntity(Entity entity, EntityMetadata entityMetadata, String crmAttributeName, IEdmProperty edmProperty, Object propertyValue)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.ConvertToCrmTypeInternal(EdmEntityObject edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n   at Microsoft.Crm.Extensibility.OData.EdmTypeConverter.ConvertToCrmEntity(EdmEntityObject edmEntity, EntityReference entityReference, IEdmModel edmModel)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)\r\n   at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
    }
}
}

Body:
"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",

Instead of this line, you should get something similar to _ownerid_value for _regardingobjectid_value. So some simple assignment issue.

Use this below snippet for assignment of regardingobjectid lookup: (make sure you are using correct entity in place of accounts)

"regardingobjectid@odata.bind": "/accounts(77af6f8e-f55d-e811-a83d-000d3a1bbafa)",


问:
fetch record form single coulmn
I am trying to get record form product which have multiple website_id in one one column.
I am sharing a screenshot here.

I am trying to fetech record by  websiteid .if website id equal or match with inside of column then query need to fetch data.

```<code>$websiteid=1;
    $productAll=Product::where(['category_id'=>$categoryDetials->id,'status'=>1])->whereIn('website_id',$websiteid)->get();
</code>```

Please let me know it's possible becouse whereIn syntax is working for array and column value is comm seprated .
Please help me if you have any possible solution

答:
Since it is comma separated, you need to explode it to the array like:

```<code>$websiteIdArray = explode(',', $websiteid);
</code>```

After getting the website id in array, now you can use wherein like:

```<code>$productAll = Product::where(['category_id'=>$categoryDetials->id,'status'=>1])
                     ->whereIn('website_id',$websiteIdArray)
                     ->get();
</code>```

Title: fetch record form single coulmn

Body:
I am trying to get record form product which have multiple website_id in one one column.
I am sharing a screenshot here.

I am trying to fetech record by  websiteid .if website id equal or match with inside of column then query need to fetch data.

$websiteid=1;
    $productAll=Product::where(['category_id'=>$categoryDetials->id,'status'=>1])->whereIn('website_id',$websiteid)->get();

Please let me know it's possible becouse whereIn syntax is working for array and column value is comm seprated .
Please help me if you have any possible solution

Body:
Since it is comma separated, you need to explode it to the array like:

$websiteIdArray = explode(',', $websiteid);

After getting the website id in array, now you can use wherein like:

$productAll = Product::where(['category_id'=>$categoryDetials->id,'status'=>1])
                     ->whereIn('website_id',$websiteIdArray)
                     ->get();


问:
SpringBoot not loading controllers which are generated using OpenAPI 3.0
I am generating code using openapi-generator-maven-plugin. The code is getting generated succesfully. But the spring boot is not loading the generated code in the context. I am not sure why, because I have done following things.

Below is my configuration of plugin:

```<code><plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>4.3.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/spec/SchoolAPIs.v1.yaml</inputSpec>
                <output>${project.build.directory}/server</output>
                <language>spring</language>
                <apiPackage>com.school.rest.controllers</apiPackage>
                <modelPackage>com.school.rest.generated.dtos</modelPackage>
                <supportingFilesToGenerate>ApiUtil.java</supportingFilesToGenerate>
                <library>spring-boot</library>
                <configOptions>
                    <java8>false</java8>
                    <dateLibrary>java8</dateLibrary>
                    <delegatePattern>true</delegatePattern>
                    <useBeanValidation>true</useBeanValidation>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Below is my main class where I have specified the configuration:

```<code>@EnableSwagger2
@EnableAsync
@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.school.rest"})
@EnableJpaRepositories(basePackages = "com.school.rest.repository")
@Slf4j
public class SchoolAPIApplication implements CommandLineRunner {

    public static void main(String[] args) {
        ApplicationContext context = new SpringApplicationBuilder(SchoolAPIApplication.class)
                .registerShutdownHook(true).run(args);
        PlansApiController plansApiController = context.getBean(PlansApiController.class);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", plansApiController);
    }

}
</code>```

I am not sure what is going wrong here, been struggling with this for almost 2 days. Can't figure out what is missing.

Please let me know if you have any solutions available.

Update: This call results in following error>

```<code>log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", plansApiController);
</code>```

Error:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type...
</code>```

Regards

答:
Okay so for me the answer goes like this,

I am facing the issue because of the lower spring-boot version, which was not supporting reading from the interfaces that are generated. And because of that reason, the code generator was generating code with Interfaces annotated with all the documentation but was not being read by the spring and added to context.

Upgrade my spring version from 2.0.0 to 2.1.4 and things are fixed.
Posting here for others reference.

Body:
I am generating code using openapi-generator-maven-plugin. The code is getting generated succesfully. But the spring boot is not loading the generated code in the context. I am not sure why, because I have done following things.

Below is my configuration of plugin:

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>4.3.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/spec/SchoolAPIs.v1.yaml</inputSpec>
                <output>${project.build.directory}/server</output>
                <language>spring</language>
                <apiPackage>com.school.rest.controllers</apiPackage>
                <modelPackage>com.school.rest.generated.dtos</modelPackage>
                <supportingFilesToGenerate>ApiUtil.java</supportingFilesToGenerate>
                <library>spring-boot</library>
                <configOptions>
                    <java8>false</java8>
                    <dateLibrary>java8</dateLibrary>
                    <delegatePattern>true</delegatePattern>
                    <useBeanValidation>true</useBeanValidation>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

Below is my main class where I have specified the configuration:

@EnableSwagger2
@EnableAsync
@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.school.rest"})
@EnableJpaRepositories(basePackages = "com.school.rest.repository")
@Slf4j
public class SchoolAPIApplication implements CommandLineRunner {

    public static void main(String[] args) {
        ApplicationContext context = new SpringApplicationBuilder(SchoolAPIApplication.class)
                .registerShutdownHook(true).run(args);
        PlansApiController plansApiController = context.getBean(PlansApiController.class);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", plansApiController);
    }

}

I am not sure what is going wrong here, been struggling with this for almost 2 days. Can't figure out what is missing.

Please let me know if you have any solutions available.

Update: This call results in following error>

log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", plansApiController);

Error:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type...

Regards