问:
Save multiple objects in a sessionStorage
I am trying to save objects in a sessionStorage anytime I click on a bookmark icon. But instead of saving several objects. Anytime I click on my icon bookmark to save a book; it is being overridden by the new value.

How could I add several objects (books) in my sessionStorage?
Thanks

here is the code snippet

```<code>try {
        const responseData = await sendHttpRequest(
            'GET',
            "https://www.googleapis.com/books/v1/volumes?q=" + search );

        const listOfBooks = responseData;
            console.log(listOfBooks);

        for (i=0; i < listOfBooks.items.length; i++) {
             console.log(listOfBooks.items[i]);

            const postEl = document.importNode(template.content, true);
            console.log("postEl", postEl);

            //BookMark Icon event
            const target = postEl.querySelector('.icon-bookmark');
            target.addEventListener('click', () => {

                sessionStorage.setItem('bookStorage', bookStorage);
                sessionStorage.setItem('bookStorage' , JSON.stringify(bookStorage));

                const extractedBook = sessionStorage.getItem('bookStorage');

                const extractedBookInfo = JSON.parse(sessionStorage.getItem('bookStorage'));
                console.log(extractedBookInfo);
            });

            postEl.querySelector('.id').textContent = 'id: '+ listOfBooks.items[i].id;
            postEl.querySelector('.titre').textContent = 'Titre: '+ listOfBooks.items[i].volumeInfo.title;
            postEl.querySelector('.author').textContent = 'Auteur: '+ listOfBooks.items[i].volumeInfo.authors;
            postEl.querySelector('.desc').textContent ='Description: '+ listOfBooks.items[i].volumeInfo.description;
            postEl.querySelector('img').src = listOfBooks.items[i].volumeInfo.imageLinks.thumbnail;

            if (postEl.querySelector('.desc').textContent.length > 200) {
                postEl.querySelector('.desc').textContent = postEl.querySelector('.desc').textContent.substring(0,200);
            }

            if (!postEl.querySelector('img').src) {
                postEl.querySelector('img').src ="resources/css/img/unavailable.png";
            }

            listElement.append(postEl);

            const bookStorage = {
                id: listOfBooks.items[i].id,
                title: listOfBooks.items[i].volumeInfo.title,
                author: listOfBooks.items[i].volumeInfo.authors,
                desc: listOfBooks.items[i].volumeInfo.description,
                img: listOfBooks.items[i].volumeInfo.imageLinks.thumbnail
                };

        }
    } catch (error) {
      alert(error.message);
    }

}

btnRechercher.addEventListener('click', fetchBooks, false);
</code>```

答: You can only have unique keys inside session storage, that’s why everytime you insert a new entity with the same key the storage overwrites the old one. You can do a for and save every book, for example ‘book_1’, ‘book_2’. Or you can store an array, but you have to use json.stringify(name_of_your_array) and then when you want your array back you can use json.parse(storage.getItem(key))</p>

Body:
I am trying to save objects in a sessionStorage anytime I click on a bookmark icon. But instead of saving several objects. Anytime I click on my icon bookmark to save a book; it is being overridden by the new value.

How could I add several objects (books) in my sessionStorage?
Thanks

here is the code snippet

try {
        const responseData = await sendHttpRequest(
            'GET',
            "https://www.googleapis.com/books/v1/volumes?q=" + search );

        const listOfBooks = responseData;
            console.log(listOfBooks);

        for (i=0; i < listOfBooks.items.length; i++) {
             console.log(listOfBooks.items[i]);

            const postEl = document.importNode(template.content, true);
            console.log("postEl", postEl);

            //BookMark Icon event
            const target = postEl.querySelector('.icon-bookmark');
            target.addEventListener('click', () => {

                sessionStorage.setItem('bookStorage', bookStorage);
                sessionStorage.setItem('bookStorage' , JSON.stringify(bookStorage));

                const extractedBook = sessionStorage.getItem('bookStorage');

                const extractedBookInfo = JSON.parse(sessionStorage.getItem('bookStorage'));
                console.log(extractedBookInfo);
            });

            postEl.querySelector('.id').textContent = 'id: '+ listOfBooks.items[i].id;
            postEl.querySelector('.titre').textContent = 'Titre: '+ listOfBooks.items[i].volumeInfo.title;
            postEl.querySelector('.author').textContent = 'Auteur: '+ listOfBooks.items[i].volumeInfo.authors;
            postEl.querySelector('.desc').textContent ='Description: '+ listOfBooks.items[i].volumeInfo.description;
            postEl.querySelector('img').src = listOfBooks.items[i].volumeInfo.imageLinks.thumbnail;

            if (postEl.querySelector('.desc').textContent.length > 200) {
                postEl.querySelector('.desc').textContent = postEl.querySelector('.desc').textContent.substring(0,200);
            }

            if (!postEl.querySelector('img').src) {
                postEl.querySelector('img').src ="resources/css/img/unavailable.png";
            }

            listElement.append(postEl);

            const bookStorage = {
                id: listOfBooks.items[i].id,
                title: listOfBooks.items[i].volumeInfo.title,
                author: listOfBooks.items[i].volumeInfo.authors,
                desc: listOfBooks.items[i].volumeInfo.description,
                img: listOfBooks.items[i].volumeInfo.imageLinks.thumbnail
                };

        }
    } catch (error) {
      alert(error.message);
    }

}

btnRechercher.addEventListener('click', fetchBooks, false);


来源: stackexchange

问:
How to open a root window, close it and then open another window in tkinter after a few seconds?
I have made a GUI using Tkinter for my Python script for a Voice Assistant. It is working pretty well. But I want to add an animation window to display an animation that I have created using After Effects as an intro to the app. I want it to open without the default close(x), maximize and minimize buttons. The window should stay till the animation is completed, and then it would disappear. The main window would then open normally to launch the GUI. To disable the close, maximize and minimize buttons I have used the root.overrideredirect(True) method. But I am not being able to simultaneously open the two windows one after the other as mentioned. I would be highly obliged if somebody would help me out with this! I have tested it with a code on a simple GUI. I am providing the code below for help with the problem!

```<code>from tkinter import *
import time

root = Tk()
root.geometry('500x300')
root.overrideredirect(True) # To disable the default Window decoration
time.sleep(5) # Assuming that the animation runs for 5 seconds
root.destroy() # This window destroys after being on screen for 5 seconds
root.mainloop()

root2 = Tk() # After the previous window is destroyed, this window opens up. Assume that this is the main window
root2.geometry('500x300')
root.mainloop()
</code>```

Please help me out!

答:
The thing you call "animation window" is actually called "splash". There is a way to do what you want. You need to create a root window for the app (a Tk instance), and then you should hide (root.withdraw()) it. Now create a Toplevel for the splash, wait for 5 seconds, destroy it, and show (root.deiconify()) the Tk window again.

Note: time.sleep(5) should never be used with Tkinter, use root.after(ms, func) instead.

```<code>from tkinter import *

def show_splash():
    splash = Toplevel()
    splash.geometry('500x300')
    splash.overrideredirect(True) # To disable the default Window decoration
    splash.after(5000, splash.destroy) # This window destroys after being on screen for 5 seconds
    splash.wait_window()

root = Tk()
root.withdraw()
show_splash()
root.deiconify()
root.mainloop()
</code>```

PS: Procedural programming is not a good idea for pretty complex Tkinter-based apps. You should consider using OOP instead.

PPS: Take a look at this and this answers.

ContentLicense: CC BY-SA 4.0

Body:
I have made a GUI using Tkinter for my Python script for a Voice Assistant. It is working pretty well. But I want to add an animation window to display an animation that I have created using After Effects as an intro to the app. I want it to open without the default close(x), maximize and minimize buttons. The window should stay till the animation is completed, and then it would disappear. The main window would then open normally to launch the GUI. To disable the close, maximize and minimize buttons I have used the root.overrideredirect(True) method. But I am not being able to simultaneously open the two windows one after the other as mentioned. I would be highly obliged if somebody would help me out with this! I have tested it with a code on a simple GUI. I am providing the code below for help with the problem!

from tkinter import *
import time

root = Tk()
root.geometry('500x300')
root.overrideredirect(True) # To disable the default Window decoration
time.sleep(5) # Assuming that the animation runs for 5 seconds
root.destroy() # This window destroys after being on screen for 5 seconds
root.mainloop()

root2 = Tk() # After the previous window is destroyed, this window opens up. Assume that this is the main window
root2.geometry('500x300')
root.mainloop()

Please help me out!

Body:
The thing you call "animation window" is actually called "splash". There is a way to do what you want. You need to create a root window for the app (a Tk instance), and then you should hide (root.withdraw()) it. Now create a Toplevel for the splash, wait for 5 seconds, destroy it, and show (root.deiconify()) the Tk window again.

Note: time.sleep(5) should never be used with Tkinter, use root.after(ms, func) instead.

from tkinter import *

def show_splash():
    splash = Toplevel()
    splash.geometry('500x300')
    splash.overrideredirect(True) # To disable the default Window decoration
    splash.after(5000, splash.destroy) # This window destroys after being on screen for 5 seconds
    splash.wait_window()

root = Tk()
root.withdraw()
show_splash()
root.deiconify()
root.mainloop()

PS: Procedural programming is not a good idea for pretty complex Tkinter-based apps. You should consider using OOP instead.

PPS: Take a look at this and this answers.


问:
CLLocation, getting new locations
In More iPhone Programming book, the author does:

```<code>    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        if ([newLocation.timestamp timeIntervalSince1970] < [NSDate timeIntervalSinceReferenceDate] - 60)
        locationCoordinate = newLocation.coordinate;
return;
    ...
</code>```

To make sure the data was taken in the last minute.  Two questions:

1) What is the if statement doing.  It seems like on the left hand side, you are getting the time difference in seconds between when this method fires and the 1970 date.  Then on the right hand side, you get the difference in seconds between the 2001 date and now minus 60 seconds.  So to me, the if statement would never be valid since the data on the left is always going to be a greater amount of seconds.  Or am I understanding it wrong?

2) What does return in a void function do?  Is that considered good coding here?  Thx.

答:
for the if block :

the value return by  timeIntervalSinceReferenceDate could be negative. see the description .

If the receiver is earlier than the
  reference date, the value is negative.

So if condition could be false.

For the return statement.

if you want your function to return the control to the calling function before reaching the function closed bracket on some condition. See the eg.

```<code>-(void) SomeFunction
{

   if(Condition1)
   {
      return;
   }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: CLLocation, getting new locations

Body:
In More iPhone Programming book, the author does:

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        if ([newLocation.timestamp timeIntervalSince1970] < [NSDate timeIntervalSinceReferenceDate] - 60)
        locationCoordinate = newLocation.coordinate;
return;
    ...

To make sure the data was taken in the last minute.  Two questions:

1) What is the if statement doing.  It seems like on the left hand side, you are getting the time difference in seconds between when this method fires and the 1970 date.  Then on the right hand side, you get the difference in seconds between the 2001 date and now minus 60 seconds.  So to me, the if statement would never be valid since the data on the left is always going to be a greater amount of seconds.  Or am I understanding it wrong?

2) What does return in a void function do?  Is that considered good coding here?  Thx.

Body:
for the if block :

the value return by  timeIntervalSinceReferenceDate could be negative. see the description .

If the receiver is earlier than the
  reference date, the value is negative.

So if condition could be false.

For the return statement.

if you want your function to return the control to the calling function before reaching the function closed bracket on some condition. See the eg.

-(void) SomeFunction
{

   if(Condition1)
   {
      return;
   }

}


问:
APIs using fetch - cannot read property 'forEach' of undefined
I'm trying to pull a select of all of the names of characters from Game of Thrones (show) using the API https://api.got.show/api/general/characters/ . I've tried multiple methods and all of them fail. Right now it says "TypeError: Cannot read property 'forEach' of undefined", when I've tried with other APIs and it works. I don't know what to do. Here's my code so far:</p>

```<code><body>
    <h1>Game of thrones</h1>
    <select>
        <option id="characters"></option>
</select>
    <script>
        fetch('https://api.got.show/api/general/characters/')
            .then(data => data.json())
            .then(data_json => {
                console.log(data_json)
                show(data_json)
            })
            .catch(err => alert(`Ha habido un error. ${err}`))

        let show = data_json => {
            data_json.results.forEach((element, index) => {
                document.getElementById('characters').innerHTML += `<option class""character">${element.name}</option>`;
            });
        }
    </script>
</body>
</code>```

答:
I tried calling the API myself. Looks like the data_json has two properties book and show but not results.

Try this snippet instead for the show function:

```<code>let show = data_json => {
  data_json.show.forEach((element, index) => {
    document.getElementById('characters').innerHTML += `<option class="character">${element.name}</option>`;
  });
}

</code>```

Body:
I'm trying to pull a select of all of the names of characters from Game of Thrones (show) using the API https://api.got.show/api/general/characters/ . I've tried multiple methods and all of them fail. Right now it says "TypeError: Cannot read property 'forEach' of undefined", when I've tried with other APIs and it works. I don't know what to do. Here's my code so far:

Game of thrones

    <select>
        <option id="characters"></option>
</select>

Body:
I tried calling the API myself. Looks like the data_json has two properties book and show but not results.

Try this snippet instead for the show function:

let show = data_json => {
  data_json.show.forEach((element, index) => {
    document.getElementById('characters').innerHTML += `<option class="character">${element.name}</option>`;
  });
}


问:
How to insert arrays into objects that are inside an array? For ng2-charts / Charts.js
Let's say I have 2 arrays:

```<code>var array1 = [1,1,1];
var array2 = [2,2,2];
</code>```

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

```<code>// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]
</code>```

答:
By using the list of below statements you can achieve the above array of objects.

```<code>var array1 = [1,1,1];
var array2 = [2,2,2];
var arrObj = [];
var tempObj = {};
tempObj.data = array1;
tempObj.lable = "test1";
arrObj.push(tempObj);
tempObj.data = array2;
tempObj.lable = "test1";
arrObj.push(tempObj);
</code>```

"arrObj" has the sample output that you wanted

Body:
Let's say I have 2 arrays:

var array1 = [1,1,1];
var array2 = [2,2,2];

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]

Body:
By using the list of below statements you can achieve the above array of objects.

var array1 = [1,1,1];
var array2 = [2,2,2];
var arrObj = [];
var tempObj = {};
tempObj.data = array1;
tempObj.lable = "test1";
arrObj.push(tempObj);
tempObj.data = array2;
tempObj.lable = "test1";
arrObj.push(tempObj);

"arrObj" has the sample output that you wanted


问:
Import only tagged blocks from Ansible role
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

```<code>---
- hosts: some_host
  roles:
    - role: roles/some_role
</code>```

And then execute it from command line specifying single tag:

```<code>$ ansible-playbook -i hosts.yml playbook.yml --tags tag1
</code>```

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

答:
I couldn’t find any easy way to execute part of a role with specific tag from the playbook.

An way could be to break the tasks in multiple files and use a file from playbook using import_role or include_role. Say, if you create two files in role’s task directory named main.yml and other.yml then you can use other tasks like below.

```<code>- import_role:
     name: myrole
     tasks_from: other
</code>```

Body:
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

---
- hosts: some_host
  roles:
    - role: roles/some_role

And then execute it from command line specifying single tag:

$ ansible-playbook -i hosts.yml playbook.yml --tags tag1

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

Body:
I couldn’t find any easy way to execute part of a role with specific tag from the playbook.

An way could be to break the tasks in multiple files and use a file from playbook using import_role or include_role. Say, if you create two files in role’s task directory named main.yml and other.yml then you can use other tasks like below.

- import_role:
     name: myrole
     tasks_from: other


问:
Java 5-compiled binaries on Java 1.3 runtime
May I know if there are any issues running a Java 5-compiled code (with Java 1.3 source/target compliance) on a Java 1.3 JVM?

I know this is quite odd, but most of our customers are on Java 5 but we are restricted by a few still on Java 1.3 due to conditions beyond our control.  Our CI tool uses Java 5 compiler but we set our source and target compliance to Java 1.3 for backward compatibility.  We are not using Java 1.3 for CI because there are unit tests that does not compile on 1.3.

Will this be an issue?

Thank you in advance!

Cheers,
- Paul

答: The only way to get the compiler to check that source in your app. only uses 1.3 methods is to specify a -bootclasspath pointing to a 1.3 rt.jar.  Note you can get that from a 1.3 JRE, it does not require a 1.3 SDK/compiler.  Of course, specify a -target of 1.3.


问:
Is there a way to overline text in android studio (java)
I am trying to display square roots in my java mobile aplication. I tried with HTML by typing the code below. It displays the square root symbol but there is no line over the variable (√100). Is there a way to overline the variable (x). Thanks for your help :)
TextView.settext(Html.fromHtml("&#x221A "+x));

答:
Inside:

```<code>TextView.settext(Html.fromHtml("&#x221A "+x));
</code>```

Add

```<code><SPAN STYLE="text-decoration:overline">here the text has overline.</SPAN>
</code>```

to your code for over-lined text. Instead of SPAN, you can use P or DIV.

Body:
Inside:

TextView.settext(Html.fromHtml("&#x221A "+x));

Add

<SPAN STYLE="text-decoration:overline">here the text has overline.</SPAN>

to your code for over-lined text. Instead of SPAN, you can use P or DIV.


问:
How do I append text to the line containing a substitution in Perl?
My goal is to replace all named constants in a *.bas file with their corresponding values, then append a comment to the line with the value-constant pair for future reference.

For example, I want to change this line:

```<code>Print #lngFile, rst.GetString(adClipString, -1, ",", vbNullString);
</code>```

To this:

```<code>Print #lngFile, rst.GetString(2, -1, ",", vbNullStrings); '2=adClipString
</code>```

Where the ADODB constant adClipString is replaced with its long value 2, and a comment is appended to the line.

The closest I've gotten is the following:

```<code>perl -pi -e 's/adClipString(.+\n)/2$1\x272=adClipString\n/' -- somefile.bas
</code>```

...but I can't figure out how to exclude the \n from the capturing group without also overwriting every line in the file. As written, the comment is placed on a new line (which is not what I want). I'm sure the answer is right in front of me.

I'm new to perl, having only run it on the command line. I'm sure there is a better [read: working] way to approach this.

答:
. doesn't match newlines, and perl -p processes one line at a time, so the string to replace never contains more than one line, and you don't need to match the newline character at all.

```<code>perl -pi -e 's/\badClipString\b(.*)/2$1\x272=adClipString/' -- somefile.bas
</code>```

I changed .+ to .* because you didn't give any indication that adClipString shouldn't be matched at the end of a line. I also surrounded the word to replace with \b so that things like thisIsABadClipStringOtherVariable won't get replaced.

The added complication is that you have a file with Windows line endings: CR+LF. . doesn't match LF (line feed, the Unix/POSIX/basically-everyone-but-Windows-nowadays newline character) but it does match CR (carriage return). So this replacement puts a CR in the middle of the line (just before the comment start), which may confuse Windows programs. One way to fix this is to exclude the CR from the “rest of line” group.

```<code>perl -pi -e 's/\badClipString\b([^\r\n]*)/2$1\x272=adClipString/' -- somefile.bas
</code>```

Another way to do this transformation would be to treat the string replacement and adding a comment as separate operations. An s command is considered true only if it makes a replacement.

```<code>perl -pi -e 's/\badClipString\b/2/ and s/\r?$/\x272=adClipString$&/' -- somefile.bas
</code>```

Or, in a less one-liner-y but more readable way:

```<code>perl -pi -e 'if (s/\badClipString\b/2/) { s/\r?$/\x272=adClipString$&/ }' -- somefile.bas
</code>```

The regex \r?$ matches at the end of a line, with an optional CR. The substitution puts additional text at the end of a line, with $& (which stands for the whole string matched by the regex) at the end to preserve the optional CR.

Body:
My goal is to replace all named constants in a *.bas file with their corresponding values, then append a comment to the line with the value-constant pair for future reference.

For example, I want to change this line:

Print #lngFile, rst.GetString(adClipString, -1, ",", vbNullString);

To this:

Print #lngFile, rst.GetString(2, -1, ",", vbNullStrings); '2=adClipString

Where the ADODB constant adClipString is replaced with its long value 2, and a comment is appended to the line.

The closest I've gotten is the following:

perl -pi -e 's/adClipString(.+\n)/2$1\x272=adClipString\n/' -- somefile.bas

...but I can't figure out how to exclude the \n from the capturing group without also overwriting every line in the file. As written, the comment is placed on a new line (which is not what I want). I'm sure the answer is right in front of me.

I'm new to perl, having only run it on the command line. I'm sure there is a better [read: working] way to approach this.

Body:
. doesn't match newlines, and perl -p processes one line at a time, so the string to replace never contains more than one line, and you don't need to match the newline character at all.

perl -pi -e 's/\badClipString\b(.*)/2$1\x272=adClipString/' -- somefile.bas

I changed .+ to .* because you didn't give any indication that adClipString shouldn't be matched at the end of a line. I also surrounded the word to replace with \b so that things like thisIsABadClipStringOtherVariable won't get replaced.

The added complication is that you have a file with Windows line endings: CR+LF. . doesn't match LF (line feed, the Unix/POSIX/basically-everyone-but-Windows-nowadays newline character) but it does match CR (carriage return). So this replacement puts a CR in the middle of the line (just before the comment start), which may confuse Windows programs. One way to fix this is to exclude the CR from the “rest of line” group.

perl -pi -e 's/\badClipString\b([^\r\n]*)/2$1\x272=adClipString/' -- somefile.bas

Another way to do this transformation would be to treat the string replacement and adding a comment as separate operations. An s command is considered true only if it makes a replacement.

perl -pi -e 's/\badClipString\b/2/ and s/\r?$/\x272=adClipString$&/' -- somefile.bas

Or, in a less one-liner-y but more readable way:

perl -pi -e 'if (s/\badClipString\b/2/) { s/\r?$/\x272=adClipString$&/ }' -- somefile.bas

The regex \r?$ matches at the end of a line, with an optional CR. The substitution puts additional text at the end of a line, with $& (which stands for the whole string matched by the regex) at the end to preserve the optional CR.


问:
How do I stop local kentico project from taking up port localhost:8080
I installed Kentico and have been going through the tutorial. But I needed to work on another project and when trying to do so I was unable to as the Kentico project seems to be running on the localhost:8080 port.

I would like to restore localhost:8080 back to the way it was.

This is the error that I get when opening localhost:8080
localhost error screenshot

I have tried to enable directory browsing and trying to stop the process running on localhost:8080 but they did not work.

Any help would be much appreciated if anyone has any suggestions or has had to deal with something like this before.

答: In IIS you need to stop the site you were working on and start the other site you want to work on. </p>


问:
JS - add selected or checked depending on input type
When iterating through form options I'm setting their option to default based on their value. </p>

<p>As I have both select and radio/checkboxes - there are two ways of setting default values - selected/checked. Is there any way to simplify with pure JS - that will get both select and check? </p>

```<code>if (param.type.select) {
          this.form.querySelector('[value="' + optionKey+'"]').selected = true;
        } else {
          this.form.querySelector('[value="' + optionKey+'"]').checked = true;
        }
</code>```

答:
You can use checked for all 3 input types. You can use checked for all 3 input types for reading the selected or checked value. For setting the selected option you need the selected-attribute.

// method to set selected or checked
const setSelected = (el, isSelect) => el[isSelect ? "selected" : "checked"] = true;

// initializing values for select, checkboxes and radio buttons
['3', 'cb3', 'r2'].forEach( v => {
  const elem = document.querySelector(`[value='${v}']`);
  elem &&
    (['checkbox', 'radio'].find(v => elem.type === v) ||
      elem.parentNode.options) &&
    setSelected(elem, elem.parentNode.options);
});

// add change handler
document.addEventListener("change", showValues);

function showValues() {
  console.clear();
  console.log(`selected option value: ${
    document.querySelector("select option:checked").value}`);
  document.querySelectorAll("input:checked")
    .forEach( v => console.log(`value of checked ${v.type}: ${v.value}`) );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option>opt 0</option>
  <option value="1">opt 1</option>
  <option value="2">opt 2</option>
  <option value="3">opt 3</option>
<select>
<p>
<input type="checkbox" value="cb1">cb 1
<input type="checkbox" value="cb2">cb 2
<input type="checkbox" value="cb3">cb 3
</p>
<input type="radio" name="x" value="r1"> r1
<input type="radio" name="x" value="r2"> r2
<input type="radio" name="x" value="r3"> r3</code>```

Body:
When iterating through form options I'm setting their option to default based on their value.

As I have both select and radio/checkboxes - there are two ways of setting default values - selected/checked. Is there any way to simplify with pure JS - that will get both select and check?

if (param.type.select) {
          this.form.querySelector('[value="' + optionKey+'"]').selected = true;
        } else {
          this.form.querySelector('[value="' + optionKey+'"]').checked = true;
        }

Body:
You can use checked for all 3 input types. You can use checked for all 3 input types for reading the selected or checked value. For setting the selected option you need the selected-attribute.

// method to set selected or checked
const setSelected = (el, isSelect) => el[isSelect ? "selected" : "checked"] = true;

// initializing values for select, checkboxes and radio buttons
['3', 'cb3', 'r2'].forEach( v => {
  const elem = document.querySelector(`[value='${v}']`);
  elem &&
    (['checkbox', 'radio'].find(v => elem.type === v) ||
      elem.parentNode.options) &&
    setSelected(elem, elem.parentNode.options);
});

// add change handler
document.addEventListener("change", showValues);

function showValues() {
  console.clear();
  console.log(`selected option value: ${
    document.querySelector("select option:checked").value}`);
  document.querySelectorAll("input:checked")
    .forEach( v => console.log(`value of checked ${v.type}: ${v.value}`) );
}

<select>
  <option>opt 0</option>
  <option value="1">opt 1</option>
  <option value="2">opt 2</option>
  <option value="3">opt 3</option>
<select>
<p>
<input type="checkbox" value="cb1">cb 1
<input type="checkbox" value="cb2">cb 2
<input type="checkbox" value="cb3">cb 3
</p>
<input type="radio" name="x" value="r1"> r1
<input type="radio" name="x" value="r2"> r2
<input type="radio" name="x" value="r3"> r3


问:
Binary search tree remove node function not removing
My removal method consists of 4 if statements that tackle the 4 different kinds of removal in a binary search tree. Not sure where wrong but it didn't remove any node when I check it. Any help if appreciated. Thanks in advance'

I suspect the problems lies in are where I try to replace the node removal to be null

```<code>public class BinaryTree<T extends Comparable<T>> {

private class Node{

    private T data;
    private Node left;
    private Node right;

    // left and right child do not have to nessary exist
    public Node ( T data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }}

    private Node root;
    private int count = 0;

    public void add( T data) {
        if ( isEmpty()) {
            root = new Node(data);
            count++;
        }
        else {
            insert(data, root);
            count++;
        }
    }

    public boolean isEmpty() {
        return root == null;
    }

    public T getRoot()  {
        if ( root.data == null) {
            System.out.println("Root is empty");
            return null;
        }
        else {
        return  root.data;
    }}

    public Node getRootNode() {
        return root;
    }

    /*
     * Checking if the data is larger or lesser than the parent's data
     * If the data is smaller than the parent's data, node.left is created
     * If the data is bigger than the parent's data, node.right is created
     */
    private void insert( T data, Node node) {

        /*
         * If 1st obj is less than the 2nd obj return a neg
         * if 1st obj is more than the 2nd obj return a pos
         * if equal return 0
         */
        int compare = data.compareTo(node.data);
        if ( compare < 1 ){
            if (node.left == null ) {
                node.left = new Node(data);

            }

        // make node.left if it is filled
            else {
                insert(data, node.left);
            }
        }

        else {
            if ( node.right == null) {
                node.right = new Node(data);
            }
            else {
                insert( data, node.right);
            }
        }
    }

    public int getSize() {
        return count;
    }

    public boolean search ( T data) {

        Node temp = searchInner(data, root);
        if ( temp.data == data) {
            System.out.println(temp.data);
            return true;
        }
        else {
            return false;
        }

    }

    public Node searchInner( T data, Node node) {

        int compare = data.compareTo(node.data);

        if ( getRoot() == data ) {
            return root;
        }

        if ( compare > 0) {
            return searchInner( data, node.right);
        }

        if ( compare < 0 ) {
            return searchInner(data , node.left);
        }

        if ( compare == 0 ) {
            return node;
        }

        else {
            System.out.println("Not found");
            return node;
        }

    }

    public void remove( T data) {
        remove1( root, data);
    }

    private Node remove1( Node node1, T data) {

        Node parent = root;
        Node node = root;
        Node temp;
        boolean isLeft = true;

        while ( node.data != data) {

            parent = node;

            if ( isEmpty()) {
                System.out.println("Unable to remove, root is empty");
                break;
            }

            if ( compare(data, node.data) < 0) {
                node = node.left;
                isLeft = true;
            }

            if ( compare(data, node.data) > 0) {
                node = node.right;
                isLeft = false;
            }

            else {
                // remove node if left child available
                if ( node.left == null && node.right != null) {

                    if ( isLeft) {
                        parent.left = node.right;
                    }

                    else {
                        parent.right = node.right;
                    }
                    count --;
                    break;
                }

                //remove node if right child available
                if ( node.right == null && node.left != null) {

                    if ( isLeft) {
                        parent.left = node.left;
                    }

                    else {
                        parent.right = node.left;
                    }
                    count --;
                    break;
                }

                // Remove node if 2 child available
                if ( node.left != null && node.right != null ) {

                    node = min(node.right);
                    node.right = remove1(node.right, node.data);

                }

                // remove node if no child available
                 if ( node.left == null && node.right == null) {
                    if (  isLeft ) {
                        parent.left = null;
                    }
                    else {
                        parent.right = null;
                    }
                    count --;
                    break;
                }

            }

        }
            return node;
        }

    // fine the smallest node in the right subtree
    private Node min ( Node node1 ) {
        while ( node1.left != null) {
            node1 = node1.left;
        }
        return node1;
    }

    private int compare( T data, T data1) {
        return data.compareTo(data1);
    }

    public void printBST(T data) {
        printTree( root, data);
    }

    private void printTree( Node node, T data)
     {
        if(node == null) return;

        System.out.println(data + " + " + node.data);
        printTree(node.left , data);
        printTree(node.right , data);
     }

    public int getHeight() {
        return height(root);
    }

    private int height( Node node) {

        if  (node == null) return 0;
        else
            return 1 + Math.max(height(node.left), height(node.right));
        }

    public void print() {
        println(root);
    }

    private void println ( Node node) {

        LinkedList<T> q = new LinkedList<T>();
        q.add(node.data);

        if ( node == null) {
            return;
        }

        int size = getSize();
        while ( size > 0) {

                System.out.print(q);

            q.clear();
            if ( node.left != null) {
                q.add(node.left.data);
                size --;
            }
            if ( node.right != null) {
                q.add(node.right.data);
                size --;
            }
            if ( node.right != null&& node.left != null) {
                System.out.println();
            }
            if ( size > 1) {
                System.out.println(",");
            }
        }

    }

    public boolean sameTree( Node root1, Node root2) {

        if ( root1 == null && root2 == null) {
            return true;
        }

        if ( root1 != null && root2 != null) {
            return  root1.data == root2.data && sameTree(root1.left,root2.left) && sameTree(root1.right, root2.right);
        }
        else {
            return false;
        }
    }
</code>```

}

答:
I have rewritten your BinaryTree class. I have added a new remove method, which uses your min(Node node) method and other one I have created, that only removes the minimum element of the tree. In addition, I have modified your Node class too by adding a new constructor and  added your size variable that was in BinaryTree class
I have modified all of this in order to make the method remove() working properly

```<code>
import java.util.LinkedList;

public class BinaryTree<T extends Comparable<T>> {

    private class Node<T> { //Here we specify what the node contains

        private T data;
        private Node<T> left;
        private Node<T> right;
        private int size;

        public Node(T value) {
            this(value, null, null);
        }

        // left and right child do not have to nessary exist
        public Node(T data, Node<T> left, Node<T> right) {
            this.data = data;
            this.left = null;
            this.right = null;
            size = 1;
            if (left != null) {
                size += left.size;
            }
            if (right != null) {
                size += right.size;
            }
        }
    }
    private Node root;

    public BinaryTree() { //Added a constructor to set the root node to null
        root = null;
    }

    public boolean isEmpty() {
        return root == null;
    }

    public T getRootData() { //Changed the name to other more clear
        if (root.data == null) {
            System.out.println("Root is empty");
            return null;
        } else {
            return (T) root.data;
        }
    }

    public Node getRootNode() {
        return root;
    }

    public void insert(T x) { //The new insert method
        root = insert(x, root);
    }

    protected Node<T> insert(T x, Node<T> actual) {
        //We check if the node exists, in case not we just create a new node
        if (actual == null) {
            return new Node<T>(x);
        }
        int cmp = compare(x, actual.data);
        if (cmp < 0) {
            actual.left = insert(x, actual.left);
        } else if (cmp > 0) {
            actual.right = insert(x, actual.right);
        } else {
            // If the node exists we just update his content
            actual.data = x;
        }
        actual.size = 1 + getSize(actual.left) + getSize(actual.right);
        return actual;
    }

     public int getSize() { //New method
        return getSize(root);
    }

    private int getSize(Node<T> actual) {
        if (actual == null) {
            return 0;
        } else {
            return actual.size;
        }
    }

    public boolean search(T data) {

        Node temp = searchInner(data, root);
        if (temp.data == data) {
            System.out.println(temp.data);
            return true;
        } else {
            return false;
        }

    }

    public Node searchInner(T data, Node node) {

        int compare = data.compareTo((T) node.data);

        if (getRootData() == data) {
            return root;
        }

        if (compare > 0) {
            return searchInner(data, node.right);
        }

        if (compare < 0) {
            return searchInner(data, node.left);
        }

        if (compare == 0) {
            return node;
        } else {
            System.out.println("Not found");
            return node;
        }

    }

    public void remove(T data) {

        remove1(root, data);
    }

    private Node remove1(Node actual, T data) {
        if (actual == null) {
            return actual;
        }
        int cmp = compare(data, (T) actual.data);
        //Check whether the value is lesser greater or equal than the one we are just visiting
        if (cmp < 0) {
            actual.left = remove1(actual.left, data);
        } else if (cmp > 0) {
            actual.right = remove1(actual.right, data);
        } else {
            if (actual.right == null) {
                return actual.left;
            }
            if (actual.left == null) {
                return actual.right;
            }
            actual.data = min(actual.right).data;
            actual.right = removeMin(actual.right);
        }
        return actual;
    }

    public Node removeMin() {
        //A new method to remove the minimum element
        Node min = min(root);
        root = removeMin(root);
        return min;
    }

    private Node removeMin(Node actual) {
        if (actual.left == null) {
            return actual.right;
        }
        actual.left = removeMin(actual.left);
        actual.size--;
        return actual;
    }

    // fine the smallest node in the right subtree
    private Node min(Node node1) {
        while (node1.left != null) {
            node1 = node1.left;
        }
        return node1;
    }

    private int compare(T data, T data1) {
        return data.compareTo(data1);
    }

    public void printBST(T data) {
        printTree(root, data);
    }

    private void printTree(Node node, T data) {
        if (node == null) {
            return;
        }

        System.out.println(data + " + " + node.data);
        printTree(node.left, data);
        printTree(node.right, data);
    }

    public int getHeight() {
        return height(root);
    }

    private int height(Node node) {

        if (node == null) {
            return 0;
        } else {
            return 1 + Math.max(height(node.left), height(node.right));
        }
    }

    public void print() {
        println(root);
    }

    private void println(Node node) {

        LinkedList<T> q = new LinkedList<T>();
        q.add((T) node.data);

        if (node == null) {
            return;
        }

        int size = getSize();
        while (size > 0) {

            System.out.print(q);

            q.clear();
            if (node.left != null) {
                q.add((T) node.left.data);
                size--;
            }
            if (node.right != null) {
                q.add((T) node.right.data);
                size--;
            }
            if (node.right != null && node.left != null) {
                System.out.println();
            }
            if (size > 1) {
                System.out.println(",");
            }
        }

    }

    public boolean sameTree(Node root1, Node root2) {

        if (root1 == null && root2 == null) {
            return true;
        }

        if (root1 != null && root2 != null) {
            return root1.data == root2.data && sameTree(root1.left, root2.left) && sameTree(root1.right, root2.right);
        } else {
            return false;
        }

    }
}

</code>```

I hope this helps to you

Body:
My removal method consists of 4 if statements that tackle the 4 different kinds of removal in a binary search tree. Not sure where wrong but it didn't remove any node when I check it. Any help if appreciated. Thanks in advance'

I suspect the problems lies in are where I try to replace the node removal to be null

public class BinaryTree<T extends Comparable<T>> {

private class Node{

    private T data;
    private Node left;
    private Node right;

    // left and right child do not have to nessary exist
    public Node ( T data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }}

    private Node root;
    private int count = 0;

    public void add( T data) {
        if ( isEmpty()) {
            root = new Node(data);
            count++;
        }
        else {
            insert(data, root);
            count++;
        }
    }

    public boolean isEmpty() {
        return root == null;
    }

    public T getRoot()  {
        if ( root.data == null) {
            System.out.println("Root is empty");
            return null;
        }
        else {
        return  root.data;
    }}

    public Node getRootNode() {
        return root;
    }

    /*
     * Checking if the data is larger or lesser than the parent's data
     * If the data is smaller than the parent's data, node.left is created
     * If the data is bigger than the parent's data, node.right is created
     */
    private void insert( T data, Node node) {

        /*
         * If 1st obj is less than the 2nd obj return a neg
         * if 1st obj is more than the 2nd obj return a pos
         * if equal return 0
         */
        int compare = data.compareTo(node.data);
        if ( compare < 1 ){
            if (node.left == null ) {
                node.left = new Node(data);

            }

        // make node.left if it is filled
            else {
                insert(data, node.left);
            }
        }

        else {
            if ( node.right == null) {
                node.right = new Node(data);
            }
            else {
                insert( data, node.right);
            }
        }
    }

    public int getSize() {
        return count;
    }

    public boolean search ( T data) {

        Node temp = searchInner(data, root);
        if ( temp.data == data) {
            System.out.println(temp.data);
            return true;
        }
        else {
            return false;
        }

    }

    public Node searchInner( T data, Node node) {

        int compare = data.compareTo(node.data);

        if ( getRoot() == data ) {
            return root;
        }

        if ( compare > 0) {
            return searchInner( data, node.right);
        }

        if ( compare < 0 ) {
            return searchInner(data , node.left);
        }

        if ( compare == 0 ) {
            return node;
        }

        else {
            System.out.println("Not found");
            return node;
        }

    }

    public void remove( T data) {
        remove1( root, data);
    }

    private Node remove1( Node node1, T data) {

        Node parent = root;
        Node node = root;
        Node temp;
        boolean isLeft = true;

        while ( node.data != data) {

            parent = node;

            if ( isEmpty()) {
                System.out.println("Unable to remove, root is empty");
                break;
            }

            if ( compare(data, node.data) < 0) {
                node = node.left;
                isLeft = true;
            }

            if ( compare(data, node.data) > 0) {
                node = node.right;
                isLeft = false;
            }

            else {
                // remove node if left child available
                if ( node.left == null && node.right != null) {

                    if ( isLeft) {
                        parent.left = node.right;
                    }

                    else {
                        parent.right = node.right;
                    }
                    count --;
                    break;
                }

                //remove node if right child available
                if ( node.right == null && node.left != null) {

                    if ( isLeft) {
                        parent.left = node.left;
                    }

                    else {
                        parent.right = node.left;
                    }
                    count --;
                    break;
                }

                // Remove node if 2 child available
                if ( node.left != null && node.right != null ) {

                    node = min(node.right);
                    node.right = remove1(node.right, node.data);

                }

                // remove node if no child available
                 if ( node.left == null && node.right == null) {
                    if (  isLeft ) {
                        parent.left = null;
                    }
                    else {
                        parent.right = null;
                    }
                    count --;
                    break;
                }

            }

        }
            return node;
        }

    // fine the smallest node in the right subtree
    private Node min ( Node node1 ) {
        while ( node1.left != null) {
            node1 = node1.left;
        }
        return node1;
    }

    private int compare( T data, T data1) {
        return data.compareTo(data1);
    }

    public void printBST(T data) {
        printTree( root, data);
    }

    private void printTree( Node node, T data)
     {
        if(node == null) return;

        System.out.println(data + " + " + node.data);
        printTree(node.left , data);
        printTree(node.right , data);
     }

    public int getHeight() {
        return height(root);
    }

    private int height( Node node) {

        if  (node == null) return 0;
        else
            return 1 + Math.max(height(node.left), height(node.right));
        }

    public void print() {
        println(root);
    }

    private void println ( Node node) {

        LinkedList<T> q = new LinkedList<T>();
        q.add(node.data);

        if ( node == null) {
            return;
        }

        int size = getSize();
        while ( size > 0) {

                System.out.print(q);

            q.clear();
            if ( node.left != null) {
                q.add(node.left.data);
                size --;
            }
            if ( node.right != null) {
                q.add(node.right.data);
                size --;
            }
            if ( node.right != null&& node.left != null) {
                System.out.println();
            }
            if ( size > 1) {
                System.out.println(",");
            }
        }

    }

    public boolean sameTree( Node root1, Node root2) {

        if ( root1 == null && root2 == null) {
            return true;
        }

        if ( root1 != null && root2 != null) {
            return  root1.data == root2.data && sameTree(root1.left,root2.left) && sameTree(root1.right, root2.right);
        }
        else {
            return false;
        }
    }

}

Body:
I have rewritten your BinaryTree class. I have added a new remove method, which uses your min(Node node) method and other one I have created, that only removes the minimum element of the tree. In addition, I have modified your Node class too by adding a new constructor and  added your size variable that was in BinaryTree class
I have modified all of this in order to make the method remove() working properly

import java.util.LinkedList;

public class BinaryTree<T extends Comparable<T>> {

    private class Node<T> { //Here we specify what the node contains

        private T data;
        private Node<T> left;
        private Node<T> right;
        private int size;

        public Node(T value) {
            this(value, null, null);
        }

        // left and right child do not have to nessary exist
        public Node(T data, Node<T> left, Node<T> right) {
            this.data = data;
            this.left = null;
            this.right = null;
            size = 1;
            if (left != null) {
                size += left.size;
            }
            if (right != null) {
                size += right.size;
            }
        }
    }
    private Node root;

    public BinaryTree() { //Added a constructor to set the root node to null
        root = null;
    }

    public boolean isEmpty() {
        return root == null;
    }

    public T getRootData() { //Changed the name to other more clear
        if (root.data == null) {
            System.out.println("Root is empty");
            return null;
        } else {
            return (T) root.data;
        }
    }

    public Node getRootNode() {
        return root;
    }

    public void insert(T x) { //The new insert method
        root = insert(x, root);
    }

    protected Node<T> insert(T x, Node<T> actual) {
        //We check if the node exists, in case not we just create a new node
        if (actual == null) {
            return new Node<T>(x);
        }
        int cmp = compare(x, actual.data);
        if (cmp < 0) {
            actual.left = insert(x, actual.left);
        } else if (cmp > 0) {
            actual.right = insert(x, actual.right);
        } else {
            // If the node exists we just update his content
            actual.data = x;
        }
        actual.size = 1 + getSize(actual.left) + getSize(actual.right);
        return actual;
    }

     public int getSize() { //New method
        return getSize(root);
    }

    private int getSize(Node<T> actual) {
        if (actual == null) {
            return 0;
        } else {
            return actual.size;
        }
    }

    public boolean search(T data) {

        Node temp = searchInner(data, root);
        if (temp.data == data) {
            System.out.println(temp.data);
            return true;
        } else {
            return false;
        }

    }

    public Node searchInner(T data, Node node) {

        int compare = data.compareTo((T) node.data);

        if (getRootData() == data) {
            return root;
        }

        if (compare > 0) {
            return searchInner(data, node.right);
        }

        if (compare < 0) {
            return searchInner(data, node.left);
        }

        if (compare == 0) {
            return node;
        } else {
            System.out.println("Not found");
            return node;
        }

    }

    public void remove(T data) {

        remove1(root, data);
    }

    private Node remove1(Node actual, T data) {
        if (actual == null) {
            return actual;
        }
        int cmp = compare(data, (T) actual.data);
        //Check whether the value is lesser greater or equal than the one we are just visiting
        if (cmp < 0) {
            actual.left = remove1(actual.left, data);
        } else if (cmp > 0) {
            actual.right = remove1(actual.right, data);
        } else {
            if (actual.right == null) {
                return actual.left;
            }
            if (actual.left == null) {
                return actual.right;
            }
            actual.data = min(actual.right).data;
            actual.right = removeMin(actual.right);
        }
        return actual;
    }

    public Node removeMin() {
        //A new method to remove the minimum element
        Node min = min(root);
        root = removeMin(root);
        return min;
    }

    private Node removeMin(Node actual) {
        if (actual.left == null) {
            return actual.right;
        }
        actual.left = removeMin(actual.left);
        actual.size--;
        return actual;
    }

    // fine the smallest node in the right subtree
    private Node min(Node node1) {
        while (node1.left != null) {
            node1 = node1.left;
        }
        return node1;
    }

    private int compare(T data, T data1) {
        return data.compareTo(data1);
    }

    public void printBST(T data) {
        printTree(root, data);
    }

    private void printTree(Node node, T data) {
        if (node == null) {
            return;
        }

        System.out.println(data + " + " + node.data);
        printTree(node.left, data);
        printTree(node.right, data);
    }

    public int getHeight() {
        return height(root);
    }

    private int height(Node node) {

        if (node == null) {
            return 0;
        } else {
            return 1 + Math.max(height(node.left), height(node.right));
        }
    }

    public void print() {
        println(root);
    }

    private void println(Node node) {

        LinkedList<T> q = new LinkedList<T>();
        q.add((T) node.data);

        if (node == null) {
            return;
        }

        int size = getSize();
        while (size > 0) {

            System.out.print(q);

            q.clear();
            if (node.left != null) {
                q.add((T) node.left.data);
                size--;
            }
            if (node.right != null) {
                q.add((T) node.right.data);
                size--;
            }
            if (node.right != null && node.left != null) {
                System.out.println();
            }
            if (size > 1) {
                System.out.println(",");
            }
        }

    }

    public boolean sameTree(Node root1, Node root2) {

        if (root1 == null && root2 == null) {
            return true;
        }

        if (root1 != null && root2 != null) {
            return root1.data == root2.data && sameTree(root1.left, root2.left) && sameTree(root1.right, root2.right);
        } else {
            return false;
        }

    }
}

I hope this helps to you


问:
How to avoid autogenerated values check on id with Hibernate
I have the following table declaration:

```<code>CREATE TABLE `chat_session` (
 `session_id` BINARY(36) NOT NULL COMMENT 'Chat session identifier',
 ...
 PRIMARY KEY (`session_id`)
</code>```

and the following class:

```<code>@ToString()
@EqualsAndHashCode(doNotUseGetters = true)
@Entity
@Table(name = "chat_session")
public class ChatSession {

    @Id
    @Column(name = "session_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String sessionId;
</code>```

which, when saving, turns into an error like the following:

```<code>javax.persistence.PersistenceException: org.hibernate.HibernateException: The database returned no natively generated identity value
</code>```

actually, I don't want to change the schema, and I need to feed my entities with proper values, not autogenerated. Can I do it?

答:
If you cannot change the database schema , you have to manually generate an unique ID and assign it for the new entities.

You can do it by simply removing @GeneratedValue :

@Entity
@Table(name = "chat_session")
public class ChatSession {

    @Id
    @Column(name = "session_id")
    private String sessionId;
}
```

<p>Consult with the business requirement to see if there are any rules about the ID format. If yes , implement it and manually generate a new ID and set it for the new entity by yourself. If you do not have such business rule , you can simply use the UUID generator from Java to ensure the generated ID is unique:</p>

<pre class="lang-java prettyprint-override"><code>UUID.randomUUID().toString()
</code>```

Body:
I have the following table declaration:

CREATE TABLE `chat_session` (
 `session_id` BINARY(36) NOT NULL COMMENT 'Chat session identifier',
 ...
 PRIMARY KEY (`session_id`)

and the following class:

@ToString()
@EqualsAndHashCode(doNotUseGetters = true)
@Entity
@Table(name = "chat_session")
public class ChatSession {

    @Id
    @Column(name = "session_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String sessionId;

which, when saving, turns into an error like the following:

javax.persistence.PersistenceException: org.hibernate.HibernateException: The database returned no natively generated identity value

actually, I don't want to change the schema, and I need to feed my entities with proper values, not autogenerated. Can I do it?

Body:
If you cannot change the database schema , you have to manually generate an unique ID and assign it for the new entities.

You can do it by simply removing @GeneratedValue :

@Entity
@Table(name = "chat_session")
public class ChatSession {

    @Id
    @Column(name = "session_id")
    private String sessionId;
}

Consult with the business requirement to see if there are any rules about the ID format. If yes , implement it and manually generate a new ID and set it for the new entity by yourself. If you do not have such business rule , you can simply use the UUID generator from Java to ensure the generated ID is unique:

UUID.randomUUID().toString()


答:
I don't know what is going on here, its confusing statement, I have use something like this

```<code>    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
        NSDate* eventDate = newLocation.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        if( abs(howRecent) > 1.0 )
               return;
        ////process your event here
}
</code>```

It is right to put return in void method, as I don't want to execute the statement next for some conditions..the same code can be written as

```<code>    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
        NSDate* eventDate = newLocation.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        if( abs(howRecent) < 1.0 ){
                 ///process your event
               }
}
</code>```

it just depends upon your need.

Title: CLLocation, getting new locations

Body:
In More iPhone Programming book, the author does:

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        if ([newLocation.timestamp timeIntervalSince1970] < [NSDate timeIntervalSinceReferenceDate] - 60)
        locationCoordinate = newLocation.coordinate;
return;
    ...

To make sure the data was taken in the last minute.  Two questions:

1) What is the if statement doing.  It seems like on the left hand side, you are getting the time difference in seconds between when this method fires and the 1970 date.  Then on the right hand side, you get the difference in seconds between the 2001 date and now minus 60 seconds.  So to me, the if statement would never be valid since the data on the left is always going to be a greater amount of seconds.  Or am I understanding it wrong?

2) What does return in a void function do?  Is that considered good coding here?  Thx.

Body:
I don't know what is going on here, its confusing statement, I have use something like this

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
        NSDate* eventDate = newLocation.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        if( abs(howRecent) > 1.0 )
               return;
        ////process your event here
}

It is right to put return in void method, as I don't want to execute the statement next for some conditions..the same code can be written as

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
        NSDate* eventDate = newLocation.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        if( abs(howRecent) < 1.0 ){
                 ///process your event
               }
}

it just depends upon your need.


问:
How to add custom Css in nextjs
I was trying to add these Template into one of my Components, this component also gets other values dynamically.
But I'm getting this error instead

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

I also tried next-images in next.config.js but still gives me the same error.

This is my package.json

```<code>{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "isomorphic-fetch": "^2.2.1",
    "js-cookie": "^2.2.1",
    "moment": "^2.25.3",
    "next": "^9.3.6",
    "nprogress": "^0.2.0",
    "prop-types": "^15.7.2",
    "query-string": "^6.12.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-modal": "^3.11.2",
    "react-quill": "^1.3.5",
    "react-render-html": "^0.6.0",
    "reactstrap": "^8.4.1"
  }
}

</code>```

Update:

My next.config.js

```<code>const withCSS = require('@zeit/next-css')

module.exports = withCSS({

    publicRuntimeConfig : {
        APP_NAME : '  ',
        API_DEVELOPMENT : '',
        API_PRODUCTION : '',
        PRODUCTION:false

    }
})

</code>```

答:
Try this in your next.config.js:

// next.config.js

```<code>const withCSS = require('@zeit/next-css')

module.exports = withCSS({

  cssLoaderOptions: {
    url: false

  }
})

</code>```

Title: How to add custom Css in nextjs

Body:
I was trying to add these Template into one of my Components, this component also gets other values dynamically.
But I'm getting this error instead

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

I also tried next-images in next.config.js but still gives me the same error.

This is my package.json

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "isomorphic-fetch": "^2.2.1",
    "js-cookie": "^2.2.1",
    "moment": "^2.25.3",
    "next": "^9.3.6",
    "nprogress": "^0.2.0",
    "prop-types": "^15.7.2",
    "query-string": "^6.12.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-modal": "^3.11.2",
    "react-quill": "^1.3.5",
    "react-render-html": "^0.6.0",
    "reactstrap": "^8.4.1"
  }
}

Update:

My next.config.js

const withCSS = require('@zeit/next-css')

module.exports = withCSS({

    publicRuntimeConfig : {
        APP_NAME : '  ',
        API_DEVELOPMENT : '',
        API_PRODUCTION : '',
        PRODUCTION:false

    }
})

Body:
Try this in your next.config.js:

// next.config.js

const withCSS = require('@zeit/next-css')

module.exports = withCSS({

  cssLoaderOptions: {
    url: false

  }
})


问:
Link XML and XSD using java
i'm trying to write the header for an xml file so it would be something like this:

```<code><file xmlns="http://my_namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://my_namespace file.xsd">
</code>```

however, I can't seem to find how to do it using the Document class in java. This is what I have:

```<code>public void exportToXML() {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        try {

            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            doc.setXmlStandalone(true);
            doc.createTextNode("<file xmlns=\"http://my_namespace"\n" +
                    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                    "xsi:schemaLocation=\"http://my_namespace file.xsd\">");
            Element mainRootElement = doc.createElement("MainRootElement");
            doc.appendChild(mainRootElement);

            for(int i = 0; i < tipoDadosParaExportar.length; i++) {
                mainRootElement.appendChild(criarFilhos(doc, tipoDadosParaExportar[i]));
            }
            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.transform(new DOMSource(doc),
                    new StreamResult(new FileOutputStream(filename)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

I tried writing it on the file using the createTextNode but it didn't work either, it only writes the version before showing the elements.

PrintStartXMLFile

Would appreciate if you could help me. Have a nice day

答:
Your createTextNode() method is only suitable for creating text nodes, it's not suitable for creating elements. You need to use createElement() for this. If you're doing this by building a tree, then you need to build nodes, you can't write lexical markup.

I'm not sure what MainRootElement is supposed to be; you've only given a fragment of your desired output so it's hard to tell.

Creating a DOM tree and then serializing it is a pretty laborious way of constructing an XML file. Using something like an XMLEventWriter is easier. But to be honest, I got frustrated by all the existing approaches and wrote a new library for the purpose as part of Saxon 10. It's called simply "Push", and looks something like this:

```<code>Processor proc = new Processor();
Serializer serializer = proc.newSerializer(new File(fileName));
Push push = proc.newPush(serializer);
Document doc = push.document(true);
doc.setDefaultNamespace("http://my_namespace");
Element root = doc.element("root")
  .attribute(new QName("xsi", "http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"),
             "http://my_namespace file.xsd");
doc.close();
</code>```

Title: Link XML and XSD using java

Body:
i'm trying to write the header for an xml file so it would be something like this:

<file xmlns="http://my_namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://my_namespace file.xsd">

however, I can't seem to find how to do it using the Document class in java. This is what I have:

public void exportToXML() {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        try {

            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            doc.setXmlStandalone(true);
            doc.createTextNode("<file xmlns=\"http://my_namespace"\n" +
                    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                    "xsi:schemaLocation=\"http://my_namespace file.xsd\">");
            Element mainRootElement = doc.createElement("MainRootElement");
            doc.appendChild(mainRootElement);

            for(int i = 0; i < tipoDadosParaExportar.length; i++) {
                mainRootElement.appendChild(criarFilhos(doc, tipoDadosParaExportar[i]));
            }
            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.transform(new DOMSource(doc),
                    new StreamResult(new FileOutputStream(filename)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I tried writing it on the file using the createTextNode but it didn't work either, it only writes the version before showing the elements.

PrintStartXMLFile

Would appreciate if you could help me. Have a nice day

Body:
Your createTextNode() method is only suitable for creating text nodes, it's not suitable for creating elements. You need to use createElement() for this. If you're doing this by building a tree, then you need to build nodes, you can't write lexical markup.

I'm not sure what MainRootElement is supposed to be; you've only given a fragment of your desired output so it's hard to tell.

Creating a DOM tree and then serializing it is a pretty laborious way of constructing an XML file. Using something like an XMLEventWriter is easier. But to be honest, I got frustrated by all the existing approaches and wrote a new library for the purpose as part of Saxon 10. It's called simply "Push", and looks something like this:

Processor proc = new Processor();
Serializer serializer = proc.newSerializer(new File(fileName));
Push push = proc.newPush(serializer);
Document doc = push.document(true);
doc.setDefaultNamespace("http://my_namespace");
Element root = doc.element("root")
  .attribute(new QName("xsi", "http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"),
             "http://my_namespace file.xsd");
doc.close();


问:
How to save & retrive image to/from mysql?
Two part quersion.

Part 1:

Im uploading an image to my server and want to save it to my database.

So far:

table:

resolver:

```<code>registerPhoto: inSequence([
  async (obj, { file }) => {
    const { filename, mimetype, createReadStream } = await file;
    const stream = createReadStream();

    const t = await db.images.create({
      Name: 'test',
      imageData: stream ,
    });
  },
])
</code>```

executing query:

```<code>Executing (default): INSERT INTO `images` (`Id`,`imageData`,`Name`) VALUES (DEFAULT,?,?);
</code>```

But nothing is saved.

Im new to this and im probably missing something but dont know what.

Part2:

This is followed by part 1, lets say I manage to save the image, how do I read it and send it back to my FE?

An edit: Ive read alot of guides saving the an image name to the db and then tha actuall image in a folder. This is NOT what im after, want to save the image to the DB and then be able to fetch it from the DB abd present it.

答: you should save the image in a directory and save the link of this image in the database</p>

Body:
Two part quersion.

Part 1:

Im uploading an image to my server and want to save it to my database.

So far:

table:

resolver:

registerPhoto: inSequence([
  async (obj, { file }) => {
    const { filename, mimetype, createReadStream } = await file;
    const stream = createReadStream();

    const t = await db.images.create({
      Name: 'test',
      imageData: stream ,
    });
  },
])

executing query:

Executing (default): INSERT INTO `images` (`Id`,`imageData`,`Name`) VALUES (DEFAULT,?,?);

But nothing is saved.

Im new to this and im probably missing something but dont know what.

Part2:

This is followed by part 1, lets say I manage to save the image, how do I read it and send it back to my FE?

An edit: Ive read alot of guides saving the an image name to the db and then tha actuall image in a folder. This is NOT what im after, want to save the image to the DB and then be able to fetch it from the DB abd present it.


问:
how to use getparam from navigation properly in react native?
Im using react navigation v4
I used the navigation.navigate to send params in other page i built,
when I try to do the same in other page I get undefined value.

I want to pass that

```<code>let VolunteerDest = documentSnapshot.data().delegation;
console.log('testing user delegation: ', VolunteerDest)  // <~~~~~~~~~ its working ~~~~~~~~~~
this.props.navigation.navigate('Volunteer', {userDelegation: VolunteerDest});
</code>```

and on the other page I tried it in compDidMount / Constructor.. none of them working:

```<code> const id = this.props.navigation.getParam('userDelegation');
 console.log('testing user delegation:' , id);  // <~~~~~~~~~~~~~~  undefined
</code>```

can someone please tell me whats wrong with it?
I read the navigation doc and searched here and google but cant find my mistake.(like I said it worked on different page navigation but here I face that issue)

答:
```<code>    First Scrren :

     <Button
              title="Go Next"
              //Button Title
              onPress={() =>
                navigate('SecondPage', {
                  JSON_ListView_Clicked_Item: this.state.username,
                })
              }/>

Second:

First Use this line

 const { navigate } = this.props.navigation;

then after  {this.props.navigation.state.params.JSON_ListView_Clicked_Item
            ? this.props.navigation.state.params.JSON_ListView_Clicked_Item
            : 'No Value Passed'}
</code>```

Body:
Im using react navigation v4
I used the navigation.navigate to send params in other page i built,
when I try to do the same in other page I get undefined value.

I want to pass that

let VolunteerDest = documentSnapshot.data().delegation;
console.log('testing user delegation: ', VolunteerDest)  // <~~~~~~~~~ its working ~~~~~~~~~~
this.props.navigation.navigate('Volunteer', {userDelegation: VolunteerDest});

and on the other page I tried it in compDidMount / Constructor.. none of them working:

 const id = this.props.navigation.getParam('userDelegation');
 console.log('testing user delegation:' , id);  // <~~~~~~~~~~~~~~  undefined

can someone please tell me whats wrong with it?
I read the navigation doc and searched here and google but cant find my mistake.(like I said it worked on different page navigation but here I face that issue)


问:
Why doesn't Python release file handles after calling file.close()?
I am on windows with Python 2.5. I have an open file for writing. I write some data. Call file close. When I try to delete the file from the folder using Windows Explorer, it errors, saying that a process still holds a handle to the file.

If I shutdown python, and try again, it succeeds.

答:
I did it using intermediate file:

import os

f = open("report.tmp","w")
f.write("{}".format("Hello"))
f.close()
os.system("move report.tmp report.html") #this line is for Windows users
```

OwnerDisplayName: ApplePieIsGood

ContentLicense: CC BY-SA 2.5


问:
trying to create a div below a div css
I realize this is a a pretty basic question, and perhaps I'm taking advantage of you all while I should be sifting through some dense css books/materials. But I can't figure out why my code doesn't work.

I'm trying to create two divs on a page, one below the other and it seems like I should be able to give the lower and absolute position which is below the top div.

I've got to div box whose css layouts are all the same but they don't look anything like eachother. Why is it that the second one looks completely unlike the first, why can't I make a "copy" of the first and place it below the first?

Heres the code. the top is the desired scroller is the desired effect. http://jsfiddle.net/7YueC/

答:
Like mentioned prior if you are duplicating the same effect on two divs, change the styling to a class and use it on both. Secondly an ID cannot start with a number, otherwise the styling will not take affect. Change it to secondEventImage or similar. If you are programming websites, I would suggest using Firefox and plugin Firebug. It allows you to check if the styling is being applied and make quick edits to view how things will be prior to making changes in the code.

CODE - Example

```<code> div#two {margin-left: 10%;margin-right: 10%;overflow-x: scroll;overflow-y: hidden;}
 div#two ul {list-style: none;height: 100%;width: 8000px;}
 div#two ul li{float:left;}
 div#two img {width: 200px;float: left;}

 OR

 div.sameDivs {..........}
 div.sameDivs ul {..........}
 div.sameDivs ul li {..........}
 div.sameDivs img {..........}
 <div id="lasteventimg" class="sameDivs"> ....... </div>
</code>```

Title: trying to create a div below a div css

Body:
Like mentioned prior if you are duplicating the same effect on two divs, change the styling to a class and use it on both. Secondly an ID cannot start with a number, otherwise the styling will not take affect. Change it to secondEventImage or similar. If you are programming websites, I would suggest using Firefox and plugin Firebug. It allows you to check if the styling is being applied and make quick edits to view how things will be prior to making changes in the code.

CODE - Example

 div#two {margin-left: 10%;margin-right: 10%;overflow-x: scroll;overflow-y: hidden;}
 div#two ul {list-style: none;height: 100%;width: 8000px;}
 div#two ul li{float:left;}
 div#two img {width: 200px;float: left;}

 OR

 div.sameDivs {..........}
 div.sameDivs ul {..........}
 div.sameDivs ul li {..........}
 div.sameDivs img {..........}
 <div id="lasteventimg" class="sameDivs"> ....... </div>


问:
how to make field required in mongodb while inserting?
I am using nestjs + mongodb with typeorm .I want to add validation that on name field.name field should be  required .so it will give error if I am trying to add blank string in mongodb. but it is not giving me error .it added blank string in mongodb why ?

I make entity

```<code>export class BootcampEntity extends BaseEntity {
  @ObjectIdColumn() id: ObjectID;

  @IsNotEmpty()
  @Column('text',{nullable: false})
  name:string;
</code>```

like this

in controller or repository I am saving like this

```<code>async createBootcamp(
    createBootcampDto: CreateBootcampDto,
  ): Promise<BootcampEntity> {
    const { name, description } = createBootcampDto;

    const camp = new BootcampEntity();
    camp.name = "";
  //  camp.description = description;

    try {
      await camp.save();
    } catch (error) {
      throw new InternalServerErrorException();
    }
</code>```

camp.name = ""; It add hard coded blank string.it should give database error .but not giving any error.

i already used {nullable: false}

答:
I think you are missing validateOrReject method

import {validateOrReject} from "class-validator";

async createBootcamp(createBootcampDto: CreateBootcampDto): Promise<BootcampEntity> {
    const { name, description } = createBootcampDto;

    const camp = new BootcampEntity();
    camp.name = "";

    const errors = await validateOrReject(camp);

    try {
      await camp.save();
    } catch (error) {
      throw new InternalServerErrorException();
    }
}
```

<p>If you don't want to place it before <code>save</code> method you can use BeforeInsert hook</p>

<pre class="lang-js prettyprint-override"><code>class BootcampEntity {

  ...

  @BeforeInsert()
  async validate() {
    await validateOrReject(this);
  }
}
</code>```

Body:
I am using nestjs + mongodb with typeorm .I want to add validation that on name field.name field should be  required .so it will give error if I am trying to add blank string in mongodb. but it is not giving me error .it added blank string in mongodb why ?

I make entity

export class BootcampEntity extends BaseEntity {
  @ObjectIdColumn() id: ObjectID;

  @IsNotEmpty()
  @Column('text',{nullable: false})
  name:string;

like this

in controller or repository I am saving like this

async createBootcamp(
    createBootcampDto: CreateBootcampDto,
  ): Promise<BootcampEntity> {
    const { name, description } = createBootcampDto;

    const camp = new BootcampEntity();
    camp.name = "";
  //  camp.description = description;

    try {
      await camp.save();
    } catch (error) {
      throw new InternalServerErrorException();
    }

camp.name = ""; It add hard coded blank string.it should give database error .but not giving any error.

i already used {nullable: false}

Body:
I think you are missing validateOrReject method

import {validateOrReject} from "class-validator";

async createBootcamp(createBootcampDto: CreateBootcampDto): Promise<BootcampEntity> {
    const { name, description } = createBootcampDto;

    const camp = new BootcampEntity();
    camp.name = "";

    const errors = await validateOrReject(camp);

    try {
      await camp.save();
    } catch (error) {
      throw new InternalServerErrorException();
    }
}

If you don't want to place it before save method you can use BeforeInsert hook

class BootcampEntity {

  ...

  @BeforeInsert()
  async validate() {
    await validateOrReject(this);
  }
}


问:
converting Unicode letters with accents in ASCII/UTF8
I'm searching a technique to convert a string (a JSON) sent by a server containing something like this :
...."Test \u00e9\u00e9\u00e9"..... in something like : "Test ééé"
I found a solution : boost::replace_all(listFolder, "\\u00e9", "é");
and I'm using this boost function with the other letters àùèê etc.... that's painful !

I wonder if there is a function who did this kind of conversion automatically.

Otherwise, I want to tell you something else, the server will treat correctly strings I send to it and containing letters with accents if I use this function :

```<code>std::string fromLocale(std::string localeStr)
{
    boost::locale::generator g;
    g.locale_cache_enabled(true);
    std::locale loc = g(boost::locale::util::get_system_locale());
    return boost::locale::conv::to_utf<char>(localeStr,loc);
}
</code>```

unfortunately, the inverse of that code didn't work to treat the strings sent by the server.

```<code>std::string toLocale(std::string utf8Str)
{
    boost::locale::generator g;
    g.locale_cache_enabled(true);
    std::locale loc = g(boost::locale::util::get_system_locale());
    return boost::locale::conv::from_utf<char>(utf8Str,loc);
}
</code>```

答: The solution I found is to use RapidJson.</p>

Body:
I'm searching a technique to convert a string (a JSON) sent by a server containing something like this :
...."Test \u00e9\u00e9\u00e9"..... in something like : "Test ééé"
I found a solution : boost::replace_all(listFolder, "\\u00e9", "é");
and I'm using this boost function with the other letters àùèê etc.... that's painful !

I wonder if there is a function who did this kind of conversion automatically.

Otherwise, I want to tell you something else, the server will treat correctly strings I send to it and containing letters with accents if I use this function :

std::string fromLocale(std::string localeStr)
{
    boost::locale::generator g;
    g.locale_cache_enabled(true);
    std::locale loc = g(boost::locale::util::get_system_locale());
    return boost::locale::conv::to_utf<char>(localeStr,loc);
}

unfortunately, the inverse of that code didn't work to treat the strings sent by the server.

std::string toLocale(std::string utf8Str)
{
    boost::locale::generator g;
    g.locale_cache_enabled(true);
    std::locale loc = g(boost::locale::util::get_system_locale());
    return boost::locale::conv::from_utf<char>(utf8Str,loc);
}


问:
Search a ListBox and Select result in C#
I have searched the site but could not find a answer.

I have a listbox called "CompetitorDetailsOutput" I then have a textbox above called "searchbox" and a button called "searchbutton" The data in the list box constanly changes and get it data from a .txt file wich stores the  data in the following format

```<code>string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore);
</code>```

the listbox then displays as follows

```<code>string.Format("{0,-20}|{1,-10}|{2,-9}|{3,-7}|{4,2}|{5,2}|{6,2}|{7,2}|{8,2}|{9,2}|{10,2}|{11,2}|{12,3}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore)
</code>```

I want to be able to search the listbox as follows:
user only enters data into "searchbox" and presses "searchbutton", system then searches the listbox, If it finds it selects the item in the listbox, if not then a close match is selected, if there are no close matches then a error message is displayed.

Code is C# and software VS 2008 Pro

Thanks

答:
```<code>private void FindAllOfMyString(string searchString)
    {
        // Set the SelectionMode property of the ListBox to select multiple items.
        ListBox.SelectionMode = SelectionMode.MultiExtended;

        // Set our intial index variable to -1.
        int x = -1;
        // If the search string is empty exit.
        if (searchString.Length != 0)
        {
            // Loop through and find each item that matches the search string.
            do
            {
                // Retrieve the item based on the previous index found. Starts with -1 which searches start.
                x = ListBox.FindString(searchString, x);
                // If no item is found that matches exit.
                if (x != -1)
                {
                    // Since the FindString loops infinitely, determine if we found first item again and exit.
                    if (ListBox.SelectedIndices.Count > 0)
                    {
                        if (x == ListBox.SelectedIndices[0])
                            return;
                    }
                    // Select the item in the ListBox once it is found.
                    ListBox.SetSelected(x, true);
                }
            } while (x != -1);
        }
    }

private void Srchbtn_Click(object sender, EventArgs e)
    {
        FindAllOfMyString(SrchBox.Text);
    }
</code>```

http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.findstring(v=vs.71).aspx

Body:
I have searched the site but could not find a answer.

I have a listbox called "CompetitorDetailsOutput" I then have a textbox above called "searchbox" and a button called "searchbutton" The data in the list box constanly changes and get it data from a .txt file wich stores the  data in the following format

string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore);

the listbox then displays as follows

string.Format("{0,-20}|{1,-10}|{2,-9}|{3,-7}|{4,2}|{5,2}|{6,2}|{7,2}|{8,2}|{9,2}|{10,2}|{11,2}|{12,3}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore)

I want to be able to search the listbox as follows:
user only enters data into "searchbox" and presses "searchbutton", system then searches the listbox, If it finds it selects the item in the listbox, if not then a close match is selected, if there are no close matches then a error message is displayed.

Code is C# and software VS 2008 Pro

Thanks

Body:
private void FindAllOfMyString(string searchString)
    {
        // Set the SelectionMode property of the ListBox to select multiple items.
        ListBox.SelectionMode = SelectionMode.MultiExtended;

        // Set our intial index variable to -1.
        int x = -1;
        // If the search string is empty exit.
        if (searchString.Length != 0)
        {
            // Loop through and find each item that matches the search string.
            do
            {
                // Retrieve the item based on the previous index found. Starts with -1 which searches start.
                x = ListBox.FindString(searchString, x);
                // If no item is found that matches exit.
                if (x != -1)
                {
                    // Since the FindString loops infinitely, determine if we found first item again and exit.
                    if (ListBox.SelectedIndices.Count > 0)
                    {
                        if (x == ListBox.SelectedIndices[0])
                            return;
                    }
                    // Select the item in the ListBox once it is found.
                    ListBox.SetSelected(x, true);
                }
            } while (x != -1);
        }
    }

private void Srchbtn_Click(object sender, EventArgs e)
    {
        FindAllOfMyString(SrchBox.Text);
    }

http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.findstring(v=vs.71).aspx


问:
Keyboard hides TextField in a PageView
I have a quite complex screen with a page view and a FutureBuilder. In the Pagebuilder I also have a TextFormField, when I now click into the text field the keyboard opens like expected. But it then hides the textfield and a button below the text field.
I already searched for solutions, things i tried:

setting resizeToAvoidBottomInset to true

putting the outer column or the pageview into a SingleChildScrollView

adding some padding (in the size of the keyboard) to the bottom

Any other ideas?

I only have ONE Scaffold.

答:
What approach are you using to get the keyboard size? The best approach is to add a bottom padding that pushes the textfield upwards, you might also want to put the form fields inside the SingleChildScrollView that you've mentioned:

```<code>padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom + 10
</code>```

Title: Keyboard hides TextField in a PageView

Body:
What approach are you using to get the keyboard size? The best approach is to add a bottom padding that pushes the textfield upwards, you might also want to put the form fields inside the SingleChildScrollView that you've mentioned:

padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom + 10


问:
Spring path variable url
We have a request mapping as below

```<code> @RequestMapping(value = "/{city}/{category}", method = RequestMethod.GET)
</code>```

Now spring security OAuth URL also get directed to the above mapping

```<code>"/oath/token"
</code>```

How do I prevent this or Any suggestion to make "/{city}/{category}" more specific.

PS:- "/resources/manifest.json" is also getting directed to same.

答:
I think you should change you naming convention, because when you use two path parameters one by one in your path it's like two wildcards /*/* anything can match that URL.

When you create RESTful application you should follow the REST naming convention. In your case it should be:

```<code> @RequestMapping(value = "cities/{cityId}/categories/{categoryId}", method = RequestMethod.GET)
</code>```

REST naming convention explained:
https://restfulapi.net/resource-naming/

Title: Spring path variable url

Body:
We have a request mapping as below

 @RequestMapping(value = "/{city}/{category}", method = RequestMethod.GET)

Now spring security OAuth URL also get directed to the above mapping

"/oath/token"

How do I prevent this or Any suggestion to make "/{city}/{category}" more specific.

PS:- "/resources/manifest.json" is also getting directed to same.

Body:
I think you should change you naming convention, because when you use two path parameters one by one in your path it's like two wildcards /*/* anything can match that URL.

When you create RESTful application you should follow the REST naming convention. In your case it should be:

 @RequestMapping(value = "cities/{cityId}/categories/{categoryId}", method = RequestMethod.GET)

REST naming convention explained:
https://restfulapi.net/resource-naming/