问:
How can I create a list of cards with input values using React?
I'm working on a project in which a doctor has to create a schedule. It consists of checkboxes of days in a week. The doctor can check (in a checkbox) those days on which he will be available in the hospital.

(screen shots are posted at the bottom)

```<code>state= {
      days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
      availableDays: []
}

daysChecked= (e,i) => {
  let checkbox= document.querySelectorAll('.checkbox')

  let arr= this.state.availableDays

  if(e.target.checked) {
    arr.push(e.target.value)

  }
  else{
    filterValue = arr.indexOf(e.target.value)
    arr.splice(filterValue, 1)
    filterIndex= index.indexOf(i)
    index.splice(filterIndex,1)
 }
 this.setState({
   availableDays: arr
 })
}
render() {
return(
  <div className='available'>
    <h3 className='availableDays'>Available Days</h3>
    <div className= 'available-days'>
      {this.state.days.map((day,i) => (
        <label key={i} className= 'days'>
          <input type='checkbox' className= 'checkbox' onClick={ (e) => this.props.daysChecked(e,i) } value= {day} />{day}</label>
        ))}
    </div>
  </div>
)
 }
}
</code>```

The daysChecked() method pushes the checked days into the state availableDays array.

Then, by using the map function, I created cards. On each card, a user can set time  (from - to):

```<code>  state= {
hour: ['H',1,2,3,4,5,6,7,8,9,10,11,12],
min: ['M','00',30],
period: ['','AM','PM']

}

render() {
    return(

  <div className='timeslots'>
    <h3>Time Slots</h3>
    {
      this.props.availableDays.map((day,i) => (
        <div key={day} className='timeslots-array'>
          <p className='timeSlots-day'>{day}</p>
          <div className= 'set-time from'>
            <select className= 'time from-hour'  >
              {this.state.hour.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'time from-min' >
              {this.state.min.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'from-period'  >
              {this.state.period.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
          </div>
          <p>TO</p>
          <div className= 'set-time to'>
            <select className= 'time to-hour'  >
              {this.state.hour.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'time to-min' >
              {this.state.min.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'to-period'  >
              {this.state.period.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
          </div>
          <a id={i} className='timeslots-button' ><i className="fas fa-plus-circle"></i></a>
          <div className= 'timslots-display'>

          </div>
        </div>
      ))
    }
  </div>
)
  }
}
</code>```

Now, if a user set time on a card and press '+' button then that time should be displayed below the '+' button on that card.
So how make that happen.

答:
```<code>
import React, { Component } from "react";

export default class App extends Component {
  state = {
    hour: ["H", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    min: ["M", "00", 30],
    period: ["", "AM", "PM"],
    days: [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ],
    availableDays: [],
    selectedData: []
  };
  daysChecked = (e, i) => {
    const { availableDays, selectedData } = this.state;
    let arr = availableDays;
    let selArr = selectedData;
    if (e.target.checked) {
      arr.push(e.target.value);
    } else {
      let filterValue = arr.indexOf(e.target.value);
      arr.splice(filterValue, 1);
      //when we unselect a day, to make the data disappear we set false to it's show property
      selArr[e.target.value].show = false;
    }
    this.setState({
      availableDays: arr,
      selectedData: selArr
    });
  };
  saveTime = (e, id, type) => {
    const { availableDays, selectedData } = this.state;
    var newArr = selectedData;
    availableDays &&
      availableDays.map((item, index) => {
        if (index === id) {
          newArr[item] = {
            ...newArr[item],
            show: false,
            [type]: e.target.value
          };
        }
      });
    this.setState({ selectedData: newArr });
  };
  showTime = (e, i) => {
    const { availableDays, selectedData } = this.state;
    var newShowValue = selectedData;
    newShowValue[availableDays[i]].show = true;
    this.setState({ selectedData: newShowValue });
  };
  render() {
    const { availableDays, selectedData } = this.state;
    return (
      <div>
        <div className="available">
          <h3 className="availableDays">Available Days</h3>
          <div className="available-days">
            {this.state.days.map((day, i) => (
              <label key={i} className="days">
                <input
                  type="checkbox"
                  className="checkbox"
                  onClick={e => this.daysChecked(e, i)}
                  value={day}
                />
                {day}
              </label>
            ))}
          </div>
        </div>
        <div className="timeslots">
          <h3>Time Slots</h3>
          {availableDays &&
            availableDays.map((day, i) => (
              <div
                key={day}
              >
                <p className="timeSlots-day">{day}</p>
                <div className="set-time from">
                  <select onChange={e => this.saveTime(e, i, "fromHour")}>
                    {this.state.hour.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "fromMin")}>
                    {this.state.min.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "fromPeriod")}>
                    {this.state.period.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                </div>
                <p>TO</p>
                <div className="set-time to">
                  <select onChange={e => this.saveTime(e, i, "toHour")}>
                    {this.state.hour.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "toMin")}>
                    {this.state.min.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "toPeriod")}>
                    {this.state.period.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                </div>
                <button onClick={e => this.showTime(e, i)}>+</button>
                {selectedData[availableDays[i]] &&
                selectedData[availableDays[i]].show === true ? (
                  <div>
                    From-
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromHour}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromMin}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromPeriod}
                    <br />
                    To-
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toHour}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toMin}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toPeriod}
                  </div>
                ) : (
                  <></>
                )}
              </div>
            ))}
        </div>
      </div>
    );
  }
}
</code>```

I have removed the css classes, reapply them.
Please try this and let me know if you face any issues.

Body:
I'm working on a project in which a doctor has to create a schedule. It consists of checkboxes of days in a week. The doctor can check (in a checkbox) those days on which he will be available in the hospital.

(screen shots are posted at the bottom)

state= {
      days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
      availableDays: []
}

daysChecked= (e,i) => {
  let checkbox= document.querySelectorAll('.checkbox')

  let arr= this.state.availableDays

  if(e.target.checked) {
    arr.push(e.target.value)

  }
  else{
    filterValue = arr.indexOf(e.target.value)
    arr.splice(filterValue, 1)
    filterIndex= index.indexOf(i)
    index.splice(filterIndex,1)
 }
 this.setState({
   availableDays: arr
 })
}
render() {
return(

Available Days

      {this.state.days.map((day,i) => (

          <input type='checkbox' className= 'checkbox' onClick={ (e) => this.props.daysChecked(e,i) } value= {day} />{day}
        ))}

)
 }
}

The daysChecked() method pushes the checked days into the state availableDays array.

Then, by using the map function, I created cards. On each card, a user can set time  (from - to):

  state= {
hour: ['H',1,2,3,4,5,6,7,8,9,10,11,12],
min: ['M','00',30],
period: ['','AM','PM']

}

render() {
    return(

Time Slots

    {
      this.props.availableDays.map((day,i) => (

{day}

            <select className= 'time from-hour'  >
              {this.state.hour.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'time from-min' >
              {this.state.min.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'from-period'  >
              {this.state.period.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>

TO

            <select className= 'time to-hour'  >
              {this.state.hour.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'time to-min' >
              {this.state.min.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>
            <select className= 'to-period'  >
              {this.state.period.map((e,i) => (
                <option key={e}>{e}</option>
              ))}
            </select>

      ))
    }

)
  }
}

Now, if a user set time on a card and press '+' button then that time should be displayed below the '+' button on that card.
So how make that happen.

Body:
import React, { Component } from "react";

export default class App extends Component {
  state = {
    hour: ["H", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    min: ["M", "00", 30],
    period: ["", "AM", "PM"],
    days: [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ],
    availableDays: [],
    selectedData: []
  };
  daysChecked = (e, i) => {
    const { availableDays, selectedData } = this.state;
    let arr = availableDays;
    let selArr = selectedData;
    if (e.target.checked) {
      arr.push(e.target.value);
    } else {
      let filterValue = arr.indexOf(e.target.value);
      arr.splice(filterValue, 1);
      //when we unselect a day, to make the data disappear we set false to it's show property
      selArr[e.target.value].show = false;
    }
    this.setState({
      availableDays: arr,
      selectedData: selArr
    });
  };
  saveTime = (e, id, type) => {
    const { availableDays, selectedData } = this.state;
    var newArr = selectedData;
    availableDays &&
      availableDays.map((item, index) => {
        if (index === id) {
          newArr[item] = {
            ...newArr[item],
            show: false,
            [type]: e.target.value
          };
        }
      });
    this.setState({ selectedData: newArr });
  };
  showTime = (e, i) => {
    const { availableDays, selectedData } = this.state;
    var newShowValue = selectedData;
    newShowValue[availableDays[i]].show = true;
    this.setState({ selectedData: newShowValue });
  };
  render() {
    const { availableDays, selectedData } = this.state;
    return (
      <div>
        <div className="available">
          <h3 className="availableDays">Available Days</h3>
          <div className="available-days">
            {this.state.days.map((day, i) => (
              <label key={i} className="days">
                <input
                  type="checkbox"
                  className="checkbox"
                  onClick={e => this.daysChecked(e, i)}
                  value={day}
                />
                {day}
              </label>
            ))}
          </div>
        </div>
        <div className="timeslots">
          <h3>Time Slots</h3>
          {availableDays &&
            availableDays.map((day, i) => (
              <div
                key={day}
              >
                <p className="timeSlots-day">{day}</p>
                <div className="set-time from">
                  <select onChange={e => this.saveTime(e, i, "fromHour")}>
                    {this.state.hour.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "fromMin")}>
                    {this.state.min.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "fromPeriod")}>
                    {this.state.period.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                </div>
                <p>TO</p>
                <div className="set-time to">
                  <select onChange={e => this.saveTime(e, i, "toHour")}>
                    {this.state.hour.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "toMin")}>
                    {this.state.min.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                  <select onChange={e => this.saveTime(e, i, "toPeriod")}>
                    {this.state.period.map((e, i) => (
                      <option key={e}>{e}</option>
                    ))}
                  </select>
                </div>
                <button onClick={e => this.showTime(e, i)}>+</button>
                {selectedData[availableDays[i]] &&
                selectedData[availableDays[i]].show === true ? (
                  <div>
                    From-
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromHour}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromMin}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].fromPeriod}
                    <br />
                    To-
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toHour}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toMin}
                    :
                    {selectedData[availableDays[i]] &&
                      selectedData[availableDays[i]].toPeriod}
                  </div>
                ) : (
                  <></>
                )}
              </div>
            ))}
        </div>
      </div>
    );
  }
}

I have removed the css classes, reapply them.
Please try this and let me know if you face any issues.


来源: stackexchange

问:
Firebase Function Error: The default Firebase app does not exist
Previously, the function worked. but I added some code, now this error is coming. How to fix this issue?

```<code>Error: Error occurred while parsing your function triggers.

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
    at FirebaseAppError.FirebaseError [as constructor] (/Users/demo/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)
</code>```

code

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

//I tried both way, but same error came
// admin.initializeApp(functions.config().firebase);
admin.initializeApp();
exports.findUsers = functions.https.onCall(async (data: any, context: any) => {
</code>```

答:
It is difficult to say where exactly is your problem (and I am not 100% sure the following will solve it), but there is a mismatch between the way you import the required modules:

```<code>import * as functions from 'firebase-functions';
import ...
//.....
</code>```

and the way you export the Cloud Function:

```<code>exports.findUsers = functions.https.onCall(...)
</code>```

As you will read here, the import corresponds to a TypeScript Cloud Function, while the export corresponds to a JavaScript one.

You should align your code to the correct mode (JS or TS) depending on what  you use (probably TS, since data and context are typed):

JavaScript:

```<code>const functions = require('firebase-functions');

exports.findUsers = functions.https.onCall(async (data, context) => {...]);
</code>```

TypeScript:

```<code>import * as functions from 'firebase-functions';

export const findUsers = functions.https.onCall(async (data: any, context: any) => {...]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Previously, the function worked. but I added some code, now this error is coming. How to fix this issue?

Error: Error occurred while parsing your function triggers.

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
    at FirebaseAppError.FirebaseError [as constructor] (/Users/demo/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)

code

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

//I tried both way, but same error came
// admin.initializeApp(functions.config().firebase);
admin.initializeApp();
exports.findUsers = functions.https.onCall(async (data: any, context: any) => {

Body:
It is difficult to say where exactly is your problem (and I am not 100% sure the following will solve it), but there is a mismatch between the way you import the required modules:

import * as functions from 'firebase-functions';
import ...
//.....

and the way you export the Cloud Function:

exports.findUsers = functions.https.onCall(...)

As you will read here, the import corresponds to a TypeScript Cloud Function, while the export corresponds to a JavaScript one.

You should align your code to the correct mode (JS or TS) depending on what  you use (probably TS, since data and context are typed):

JavaScript:

const functions = require('firebase-functions');

exports.findUsers = functions.https.onCall(async (data, context) => {...]);

TypeScript:

import * as functions from 'firebase-functions';

export const findUsers = functions.https.onCall(async (data: any, context: any) => {...]);


问:
How can I implement basic question answering with hugging-face?
I have:

```<code>from transformers import XLNetTokenizer, XLNetForQuestionAnswering
import torch

tokenizer =  XLNetTokenizer.from_pretrained('xlnet-base-cased')
model = XLNetForQuestionAnswering.from_pretrained('xlnet-base-cased')

input_ids = torch.tensor(tokenizer.encode("What is my name?", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
start_positions = torch.tensor([1])
end_positions = torch.tensor([3])
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
loss = outputs[0]

print(outputs)
print(loss)
</code>```

As per the docs. This does something giving:

```<code>(tensor(2.3008, grad_fn=<DivBackward0>),)
tensor(2.3008, grad_fn=<DivBackward0>)
</code>```

However, I want an actual answer if possible?

答:
Thanks to Joe Davison for providing the answer on Twitter:

```<code>from transformers import pipeline

qa = pipeline('question-answering')
response = qa(context='I like to eat apples, but hate bananas.',
              question='What do I like?')

print(response)
</code>```

gives a response of:

```<code>{'score': 0.282511100858045, 'start': 31, 'end': 38, 'answer': 'bananas.'}
</code>```

Not quite right, but at least the score is low.

Body:
I have:

from transformers import XLNetTokenizer, XLNetForQuestionAnswering
import torch

tokenizer =  XLNetTokenizer.from_pretrained('xlnet-base-cased')
model = XLNetForQuestionAnswering.from_pretrained('xlnet-base-cased')

input_ids = torch.tensor(tokenizer.encode("What is my name?", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
start_positions = torch.tensor([1])
end_positions = torch.tensor([3])
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
loss = outputs[0]

print(outputs)
print(loss)

As per the docs. This does something giving:

(tensor(2.3008, grad_fn=<DivBackward0>),)
tensor(2.3008, grad_fn=<DivBackward0>)

However, I want an actual answer if possible?

Body:
Thanks to Joe Davison for providing the answer on Twitter:

from transformers import pipeline

qa = pipeline('question-answering')
response = qa(context='I like to eat apples, but hate bananas.',
              question='What do I like?')

print(response)

gives a response of:

{'score': 0.282511100858045, 'start': 31, 'end': 38, 'answer': 'bananas.'}

Not quite right, but at least the score is low.


问:
spring.io Authenticating with LDAP guide returns Bad Credentials
I am following the guide ( https://spring.io/guides/gs/authenticating-ldap/ ) and have the following classes:

Web Configuration class:

```<code>@Configuration
public class WebSecurityConfig {

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
        .formLogin();
}

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
                .url("ldap://localhost:8389/dc=springframework,dc=org")
                .and()
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");
    }
}
</code>```

Controller class

```<code>@RestController
public class SpringLdapController {

@GetMapping("/")
public String index() {
    return "Welcome to the home page";
}
}
</code>```

LDAP config file (.ldif)

```<code>dn: dc=springframework,dc=org
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: springframework

dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: subgroups

dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people

dn: ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: space cadets

dn: ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: "quoted people"

dn: ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: otherpeople

dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=

dn: uid=bob,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: bobspassword

dn: uid=joe,ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Joe Smeth
sn: Smeth
uid: joe
userPassword: joespassword

dn: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Mouse, Jerry
sn: Mouse
uid: jerry
userPassword: jerryspassword

dn: cn=slash/guy,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: slash/guy
sn: Slash
uid: slashguy
userPassword: slashguyspassword

dn: cn=quote\"guy,ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: quote\"guy
sn: Quote
uid: quoteguy
userPassword: quoteguyspassword

dn: uid=space cadet,ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Space Cadet
sn: Cadet
uid: space cadet
userPassword: spacecadetspassword

dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: uid=bob,ou=people,dc=springframework,dc=org

dn: cn=managers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: managers
ou: manager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: cn=mouse\, jerry,ou=people,dc=springframework,dc=org

dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: submanagers
ou: submanager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
</code>```

I have tried a combination of logins I thought would be correct such as:

"ben", "benspassword"||
"space cadet","spacecadetspassword"||
"jerry", "jerryspassword"

But I keep getting a "Bad Credentials" shown on my screen rejecting my login. Is there something I'm missing out?

答: Passwords in your ldif file are in plaintext, and at the same time you use passwordEncoder for password comparison. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am following the guide ( https://spring.io/guides/gs/authenticating-ldap/ ) and have the following classes:

Web Configuration class:

@Configuration
public class WebSecurityConfig {

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
        .formLogin();
}

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
                .url("ldap://localhost:8389/dc=springframework,dc=org")
                .and()
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");
    }
}

Controller class

@RestController
public class SpringLdapController {

@GetMapping("/")
public String index() {
    return "Welcome to the home page";
}
}

LDAP config file (.ldif)

dn: dc=springframework,dc=org
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: springframework

dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: subgroups

dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people

dn: ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: space cadets

dn: ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: "quoted people"

dn: ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: otherpeople

dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=

dn: uid=bob,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: bobspassword

dn: uid=joe,ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Joe Smeth
sn: Smeth
uid: joe
userPassword: joespassword

dn: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Mouse, Jerry
sn: Mouse
uid: jerry
userPassword: jerryspassword

dn: cn=slash/guy,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: slash/guy
sn: Slash
uid: slashguy
userPassword: slashguyspassword

dn: cn=quote\"guy,ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: quote\"guy
sn: Quote
uid: quoteguy
userPassword: quoteguyspassword

dn: uid=space cadet,ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Space Cadet
sn: Cadet
uid: space cadet
userPassword: spacecadetspassword

dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: uid=bob,ou=people,dc=springframework,dc=org

dn: cn=managers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: managers
ou: manager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: cn=mouse\, jerry,ou=people,dc=springframework,dc=org

dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: submanagers
ou: submanager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org

I have tried a combination of logins I thought would be correct such as:

"ben", "benspassword"||
"space cadet","spacecadetspassword"||
"jerry", "jerryspassword"

But I keep getting a "Bad Credentials" shown on my screen rejecting my login. Is there something I'm missing out?


问:
Initializing list property without "new List" causes NullReferenceException
```<code>using System;
using System.Collections.Generic;

class Parent
{
   public Child Child { get; set; }
}

class Child
{
   public List<string> Strings { get; set; }
}

static class Program
{
   static void Main() {
      // bad object initialization
      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
   }
}
</code>```

The above program compiles fine, but crashes at runtime with Object reference not set to an instance of the object.

If you notice in the above snippet, I have omitted new while initializing the child properties.

Obviously the correct way to initialize is:

```<code>      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { "hello", "world" }
         }
      };
</code>```

My question is why does the C# compiler not complain when it sees the first construct?

Why is the broken initialization valid syntax?

```<code>      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
</code>```

答:
Note that this syntax can cause some unexpected results and hard-to-spot errors:

```<code>class Test
{
    public List<int> Ids { get; set; } = new List<int> { 1, 2 };
}

var test = new Test { Ids = { 1, 3 } };

foreach (var n in test)
{
    Console.WriteLine(n);
}
</code>```

You might expect the output to be 1,3, but instead it is:

```<code>1
2
1
3
</code>```

Body:
using System;
using System.Collections.Generic;

class Parent
{
   public Child Child { get; set; }
}

class Child
{
   public List<string> Strings { get; set; }
}

static class Program
{
   static void Main() {
      // bad object initialization
      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
   }
}

The above program compiles fine, but crashes at runtime with Object reference not set to an instance of the object.

If you notice in the above snippet, I have omitted new while initializing the child properties.

Obviously the correct way to initialize is:

      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { "hello", "world" }
         }
      };

My question is why does the C# compiler not complain when it sees the first construct?

Why is the broken initialization valid syntax?

      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };

Body:
Note that this syntax can cause some unexpected results and hard-to-spot errors:

class Test
{
    public List<int> Ids { get; set; } = new List<int> { 1, 2 };
}

var test = new Test { Ids = { 1, 3 } };

foreach (var n in test)
{
    Console.WriteLine(n);
}

You might expect the output to be 1,3, but instead it is:

1
2
1
3


问:
How to get data from more than 2 tables in SQL Server with joins
I want to get data based on user login. If user1 is logged in, user1 data only should be populated instead of all others data.

I created a table like this, I have 3 tables pond, users, CustomerDevices. I want to show data with giving only one value in query like 'user1'. But I'm getting duplicate records. Based on username I want to pick the customerid and based on customerid need to get the imei and need all the imei data in the table.

```<code>SELECT temp, p.imei, timestatmp
FROM dbo.pond AS p
INNER JOIN customerdevices AS cd ON p.imei = cd.imei
INNER JOIN users AS u ON u.username = 'user1'
</code>```

Sample data:

```<code> id deviceid    timestatmp       ph       do    temp          imei
------------------------------------------------------------------------
 97 1001    2020-02-06 18:38:31.610 4.32    8.30    26.00   869668021731
181 1001    2020-02-07 18:19:07.967 8.10    6.93    24.00   869668021731
182 1001    2020-02-07 18:24:08.253 8.09    6.73    24.00   869668021731
183 1001    2020-02-07 18:29:10.520 8.10    6.72    24.00   869668021731
</code>```

id is the primary key of this table.

Table Users:

```<code>Id  Username    Password    CustomerId
---------------------------------------
4   user1        user1@123  Cust1001
</code>```

id is the primary key of this table.

Table CustomerDevices:

```<code>CustomerId  imei
-------------------------
Cust1001    869668021731
</code>```

Here, imei is the primary key.

答:
You are not joining your users table to anything. Try this...</p>

```<code>SELECT temp,p.imei,timestatmp
FROM dbo.pond as p
inner JOIN customerdevices as cd ON p.imei = cd.imei
inner Join users as u on cd.CustomerId = u.CustomerId
where u.username='user1'
</code>```

Body:
I want to get data based on user login. If user1 is logged in, user1 data only should be populated instead of all others data.

I created a table like this, I have 3 tables pond, users, CustomerDevices. I want to show data with giving only one value in query like 'user1'. But I'm getting duplicate records. Based on username I want to pick the customerid and based on customerid need to get the imei and need all the imei data in the table.

SELECT temp, p.imei, timestatmp
FROM dbo.pond AS p
INNER JOIN customerdevices AS cd ON p.imei = cd.imei
INNER JOIN users AS u ON u.username = 'user1'

Sample data:

 id deviceid    timestatmp       ph       do    temp          imei
------------------------------------------------------------------------
 97 1001    2020-02-06 18:38:31.610 4.32    8.30    26.00   869668021731
181 1001    2020-02-07 18:19:07.967 8.10    6.93    24.00   869668021731
182 1001    2020-02-07 18:24:08.253 8.09    6.73    24.00   869668021731
183 1001    2020-02-07 18:29:10.520 8.10    6.72    24.00   869668021731

id is the primary key of this table.

Table Users:

Id  Username    Password    CustomerId
---------------------------------------
4   user1        user1@123  Cust1001

id is the primary key of this table.

Table CustomerDevices:

CustomerId  imei
-------------------------
Cust1001    869668021731

Here, imei is the primary key.

Body:
You are not joining your users table to anything. Try this...

SELECT temp,p.imei,timestatmp
FROM dbo.pond as p
inner JOIN customerdevices as cd ON p.imei = cd.imei
inner Join users as u on cd.CustomerId = u.CustomerId
where u.username='user1'


问:
Laravel Grouping by Eloquent Relationship
How can I group by relation?

Example

```<code>Sales::with('product_detail.product')->groupBy('product_name')->get()
</code>```

How can I get a result with eloquent code?

答:
I think the top answer is not answering the question. As I understand, the aim is to group the results of the outer query, not the relationship.

This is not possible in an Eloquent-y DB call because the call for the With is separate. You can manually join the tables and group by the required column.

If you want to stay Eloquent-y, there are many convenient methods available to Collections, including GroupBy. So you can get the data first and group later.

Body:
How can I group by relation?

Example

Sales::with('product_detail.product')->groupBy('product_name')->get()

How can I get a result with eloquent code?


问:
Get current line number from bufferedReader
I have different text files I would like to read, and I am using BufferedReader for it like this:

```<code>int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

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

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8

答:
Very simple: you keep track yourself.</p>

```<code>    String line;
    int currentLine = 0;

    while ((line = bufferedReader.readLine()) != null) {
        String[] numbers = line.split(" ");

        System.out.println("Linenumber " + currentLine);
        System.out.println(numbers[0]);
        System.out.println(line);
        currentLine ++;
    }
    reader.close();
</code>```

Body:
I have different text files I would like to read, and I am using BufferedReader for it like this:

int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

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

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8

Body:
Very simple: you keep track yourself.

    String line;
    int currentLine = 0;

    while ((line = bufferedReader.readLine()) != null) {
        String[] numbers = line.split(" ");

        System.out.println("Linenumber " + currentLine);
        System.out.println(numbers[0]);
        System.out.println(line);
        currentLine ++;
    }
    reader.close();


问:
ionic4 sqlite No data available
I use ionic4 + angular8 + @ionic-native/sqlite/ngx

You can insert success. the number of data tables taken is correct, but no data

enter image description here
What's the problem  thank you

答:
You need to read data like this

```<code> this.sqlite.create({name: 'myapp.db',  location: 'default'}).then((db : SQLiteObject) => {
     db.executeSql('SELECT * FROM table_name where id=?', [id]).then((data) => {
            let results = []
            for (let i = 0; i < data.rows.length; i++) {
                let item = data.rows.item(i);
                results.push(item);
            }
            console.log(results)
        }).catch(e => console.log(e));
    }).catch(e => console.log('sqlite error',e))
</code>```

You will get all the data in results

Title: ionic4 sqlite No data available

Body:
You need to read data like this

 this.sqlite.create({name: 'myapp.db',  location: 'default'}).then((db : SQLiteObject) => {
     db.executeSql('SELECT * FROM table_name where id=?', [id]).then((data) => {
            let results = []
            for (let i = 0; i < data.rows.length; i++) {
                let item = data.rows.item(i);
                results.push(item);
            }
            console.log(results)
        }).catch(e => console.log(e));
    }).catch(e => console.log('sqlite error',e))

You will get all the data in results


问:
Populating table with textbox value from previous HTML page
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

```<code><div class="selecttier">
  <h1>5. Number of Clicks</h1>
  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
</code>```

JS on page 1:

```<code>$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });
</code>```

JS on page 2:

```<code>// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();
</code>```

Output HTML table (page 2):

```<code><table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
            <th>Number of Clicks</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>
</code>```

答:
As stated in the @Manu Varghese comment, the way to go would be using sessionStorage or localStorage.

First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.

For that, in the first page you must use:

sessionStorage.setItem("key", "value")
```
<p>You may set the item right when you perceives a change, like in the input 'blur' event.</p>
<p>and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:</p>
<pre class="lang-js prettyprint-override"><code>sessionStorage.getItem("key")
</code>```

Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).

Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.

Implementation in the given case

Your code can be modified in three steps:

Change the way you save the data to use the storage

Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.

Load the JSON object and its fields (the array and the number).

Step 1 - Changing to sessionStorage

Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.

If you want to use the storage rather than the URL for all the data, just change these lines of code from:

let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
```
<p>to the code that will save the data into a (local/session)Storage:</p>
<pre class="lang-js prettyprint-override"><code>let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page
</code>```

Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.

Step 2 -- Adding more data to save

Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.

Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:

let table_data = []; // the array you have
$('input[type=checkbox]').each(
    ... rest of code ...
); // the function that creates the array (I abbreviated it here)

// Creates an object with an array and a number
let jsonObj = {
    table_data: table_data,
    number_of_clicks: theNumberYouHave/* your variable with the number here */
};

// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";
```
<p>Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.</p>
<p>In other words, this simply will create an structure like that:</p>
```{
  number_of_clicks: 5216,
  table_data: [
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    ...
  ]
}
```
<p>See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.</p>
<p>Step 3 -- Loading data from page 1</p>
<p>For now, you have these two lines of code in page 2 to read data from page 1:</p>
<pre class="lang-js prettyprint-override"><code>let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
</code>```

What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:

let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number
```
<p>Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.</p>
<p>You have it with the unique ID "sum1", the you may just:</p>
<pre class="lang-js prettyprint-override"><code>$("#sum1").text(number_of_clicks);
</code>```

And you are done!

Body:
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

5. Number of Clicks

  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />

JS on page 1:

$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });

JS on page 2:

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("

");
            let recordName = $("	").text(data_from_page_1[i].name);
            let recordValue = $("	").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();

Output HTML table (page 2):

            Name
            Value
            Number of Clicks

                Total CPC:

Body:
As stated in the @Manu Varghese comment, the way to go would be using sessionStorage or localStorage.

First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.

For that, in the first page you must use:

sessionStorage.setItem("key", "value")

You may set the item right when you perceives a change, like in the input 'blur' event.

and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:

sessionStorage.getItem("key")

Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).

Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.

Implementation in the given case

Your code can be modified in three steps:

Change the way you save the data to use the storage

Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.

Load the JSON object and its fields (the array and the number).

Step 1 - Changing to sessionStorage

Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.

If you want to use the storage rather than the URL for all the data, just change these lines of code from:

let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;

to the code that will save the data into a (local/session)Storage:

let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page

Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.

Step 2 -- Adding more data to save

Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.

Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:

let table_data = []; // the array you have
$('input[type=checkbox]').each(
    ... rest of code ...
); // the function that creates the array (I abbreviated it here)

// Creates an object with an array and a number
let jsonObj = {
    table_data: table_data,
    number_of_clicks: theNumberYouHave/* your variable with the number here */
};

// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";

Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.

In other words, this simply will create an structure like that:

{
  number_of_clicks: 5216,
  table_data: [
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    { name: "...", value: "..."},
    ...
  ]
}

See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.

Step 3 -- Loading data from page 1

For now, you have these two lines of code in page 2 to read data from page 1:

let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));

What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:

let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number

Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.

You have it with the unique ID "sum1", the you may just:

$("#sum1").text(number_of_clicks);

And you are done!


问:
NativeScript refuses to detect my avdmanager emulator
Trying to create a NativeScript app, but having started up my emulator, tns device android --available-devices won't detect it:

My Android SDK is installed at /usr/local/android/sdk, and I've made sure to delete every other installation of it that exists. tns doctor returns no errors, so I assume that this isn't the issue.

It's probably worth mentioning that I'm using Kubuntu, which I'm pretty sure is the reason the emulator crashes if I click one of the side menu buttons, but I think that's unrelated. The emulator definitely exists too:

If anyone has any ideas or needs anymore information, please don't hesitate to ask. Thank you so much!

答:
Are you sure you do not have conflicting SDK installations? I've experienced conflicting SDKs when I install NativeScript - ensure that NativeScript is pointed to the same SDK that Android Studio is using.

Have you checked your bash profile?


问:
How to install koalas with conda?
According to the koalas docs, installing koalas with conda should be as easy as

```<code>conda install koalas
</code>```

But this raises the error:

Collecting package metadata (repodata.json): done Solving environment:
  failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from
  current channels:

koalas

Current channels:

https://conda.anaconda.org/anaconda-fusion/win-64

https://conda.anaconda.org/anaconda-fusion/noarch

https://repo.anaconda.com/pkgs/main/win-64

https://repo.anaconda.com/pkgs/main/noarch

https://repo.anaconda.com/pkgs/r/win-64

https://repo.anaconda.com/pkgs/r/noarch

https://repo.anaconda.com/pkgs/msys2/win-64

https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package
  you're looking for, navigate to

```<code>https://anaconda.org
</code>```

and use the search bar at the top of the page.

I tried running

```<code>conda install -c conda-forge pyspark
</code>```

first too, and that seemd to work out just fine. But koalas still raises the same error. Is there something more to

Koalas requires PySpark so please make sure your PySpark is available.

than conda install -c conda-forge pyspark that is too obvious to include in the docs?

I've also tried the whole thing in a virtual environment with

```<code>conda create --name koalas-dev-env
</code>```

if that should matter.

System info:

```<code>Python 3.7.0
Anaconda 2019.10
</code>```

答:
Running

conda create -c conda-forge -n koalas-dev-env koalas pyspark

will do. You run into issue since you have not provided the conda-forge channel. The latter you can also add to the .condarc config file.

[EDIT]

As pointed out by the OP, this should have been made clear in the docs. I made a pull request to fix that.

Title: How to install koalas with conda?

Body:
According to the koalas docs, installing koalas with conda should be as easy as

conda install koalas

But this raises the error:

Collecting package metadata (repodata.json): done Solving environment:
  failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from
  current channels:

koalas

Current channels:

https://conda.anaconda.org/anaconda-fusion/win-64

https://conda.anaconda.org/anaconda-fusion/noarch

https://repo.anaconda.com/pkgs/main/win-64

https://repo.anaconda.com/pkgs/main/noarch

https://repo.anaconda.com/pkgs/r/win-64

https://repo.anaconda.com/pkgs/r/noarch

https://repo.anaconda.com/pkgs/msys2/win-64

https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package
  you're looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.

I tried running

conda install -c conda-forge pyspark

first too, and that seemd to work out just fine. But koalas still raises the same error. Is there something more to

Koalas requires PySpark so please make sure your PySpark is available.

than conda install -c conda-forge pyspark that is too obvious to include in the docs?

I've also tried the whole thing in a virtual environment with

conda create --name koalas-dev-env

if that should matter.

System info:

Python 3.7.0
Anaconda 2019.10


问:
Need help editing script to move multiple rows to another tab to include one more field
https://docs.google.com/spreadsheets/d/1RaZXsOND3GptpD8W7CZPA6ntjChDp8Dmc6PMMhRBCJw/edit?usp=sharing

Ok, the script works BUT I can't pin point the fields that I want to move.
Its just the Date field actually. I don't want the text field A3 to move just the manually typed in field in B3..and then everything else below it.

Here is the current code I'm using that I found here and tailored to fit our needs just can't get that ONE field. Sure its something simple, just can't focus so hoping someone might help:

```<code>function reMove() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getActiveSheet();

  var destinationSheet = ss.getSheetByName("Archive");

  //max 7 to Archive
  for(var a=0;a<200;a++){

    var values = sourceSheet.getRange("A4:BY100").getValues();

      for(var v=0;v<values.length;v++){

        //row J, index 9
        if(values[v][3] !==  ""){

           destinationSheet.appendRow(values[v]);
           sourceSheet.deleteRow(v+1);
           break;

        }
      }
    }
    }
</code>```

答:
Here is the correct code that does exactly what I needed it to do ...</p>

```<code>function reMove() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var range = ss.getSheetByName('UPLOAD').getRange('A3:BY');
  var values = range.getValues().filter(function (r) {return r[0]})
  values[0][0] = null;
  range.offset(1, 0).clear()
 ss.getSheetByName("Process").clear().getRange(1, 1, values.length, values[1].length).setValues(values)
}
</code>```

Body:
https://docs.google.com/spreadsheets/d/1RaZXsOND3GptpD8W7CZPA6ntjChDp8Dmc6PMMhRBCJw/edit?usp=sharing

Ok, the script works BUT I can't pin point the fields that I want to move.
Its just the Date field actually. I don't want the text field A3 to move just the manually typed in field in B3..and then everything else below it.

Here is the current code I'm using that I found here and tailored to fit our needs just can't get that ONE field. Sure its something simple, just can't focus so hoping someone might help:

function reMove() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getActiveSheet();

  var destinationSheet = ss.getSheetByName("Archive");

  //max 7 to Archive
  for(var a=0;a<200;a++){

    var values = sourceSheet.getRange("A4:BY100").getValues();

      for(var v=0;v<values.length;v++){

        //row J, index 9
        if(values[v][3] !==  ""){

           destinationSheet.appendRow(values[v]);
           sourceSheet.deleteRow(v+1);
           break;

        }
      }
    }
    }

Body:
Here is the correct code that does exactly what I needed it to do ...

function reMove() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var range = ss.getSheetByName('UPLOAD').getRange('A3:BY');
  var values = range.getValues().filter(function (r) {return r[0]})
  values[0][0] = null;
  range.offset(1, 0).clear()
 ss.getSheetByName("Process").clear().getRange(1, 1, values.length, values[1].length).setValues(values)
}


问:
How to increment div id with php for loop?
I have the following div. I would like to have mydiv1, mydiv2 and mydiv3. Is this possible to do?

Code:

```<code><?php for($i =1; $i <3; $i++):?>
    <div id="mydiv<?php $i?>" style="float:left">
<?php endfor;?>
</code>```

答:
Why do you have 9 elements? Because you're generating nine elements.

```<code>$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

foreach ($somearray as $k=>$v){
    for($i=1;$i<=3;$i++){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    }
}
</code>```

Let me elaborate:

The above code block is equal to this set of codeblocks.

where $somearray value = 'animal'=>'cat' do this:

```<code>for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}
</code>```

and

where $somearray value = 'place'=>'earth' do this:

```<code>for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}
</code>```

and

where $somearray value = 'food'=>'orange' do this:

```<code>for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}
</code>```

All because of this:

```<code>foreach ($somearray as $k=>$v){
  ...
}
</code>```

Body:
I have the following div. I would like to have mydiv1, mydiv2 and mydiv3. Is this possible to do?

Code:

<?php for($i =1; $i <3; $i++):?>
    <div id="mydiv<?php $i?>" style="float:left">
<?php endfor;?>

Body:
Why do you have 9 elements? Because you're generating nine elements.

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

foreach ($somearray as $k=>$v){
    for($i=1;$i<=3;$i++){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    }
}

Let me elaborate:

The above code block is equal to this set of codeblocks.

where $somearray value = 'animal'=>'cat' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

and

where $somearray value = 'place'=>'earth' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

and

where $somearray value = 'food'=>'orange' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

All because of this:

foreach ($somearray as $k=>$v){
  ...
}


答:
Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop </p>

<p>i.e. </p>

```<code>try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;
        long currentLineNr = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLineNr++;
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
            //Use the currentLineNr how you like
        }
        reader.close();

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

Title: Get current line number from bufferedReader

Body:
Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop

i.e.

try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;
        long currentLineNr = 0;
        while ((line = bufferedReader.readLine()) != null) {
            currentLineNr++;
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
            //Use the currentLineNr how you like
        }
        reader.close();

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


问:
Difference B/W, WHERE and ON in SQL join Operation
Here is my test code for explaination

```<code>create table Test3(id integer, name varchar(100));
insert into Test3(id, name) values(1, "Vijay");
insert into Test3(id, name) values(2, "Sandy");
insert into Test3(id, name) values(3, "Rohit");
create table Test4(id integer, surname varchar(100));
insert into Test4(id, surname) values(1, "karma");
insert into Test4(id, surname) values(2, "sharma");
</code>```

Here is my Queries:

```<code>select Test3.id , Test3.name , Test4.surname from Test3,Test4 where Test3.id = Test4.id;
select Test3.id , Test3.name , Test4.surname from Test3 join Test4 on Test3.id = Test4.id;
</code>```

Both the above query statements resulted same as below:

1   Vijay   karma

2   Sandy   sharma

What is the difference in both queries internally and which one on more efficient?

答:
The two queries are functionaly equivalent.

One uses old-school, implicit joins (with a comma in the from clause), the other uses explicit joins (with the on keyword).

While both queries are guaranteed to generate the same results (and would likely have the same performance), I would strongly recommend to use the explicit join syntax. Implicit joins have fallen out of favor decades ago (that was the ANSI 92 days) for many reasons, notably because they are harder to follow (the logic is spread between the from clause and the where clause), and cannot be easily converted to a left join.

Body:
Here is my test code for explaination

create table Test3(id integer, name varchar(100));
insert into Test3(id, name) values(1, "Vijay");
insert into Test3(id, name) values(2, "Sandy");
insert into Test3(id, name) values(3, "Rohit");
create table Test4(id integer, surname varchar(100));
insert into Test4(id, surname) values(1, "karma");
insert into Test4(id, surname) values(2, "sharma");

Here is my Queries:

select Test3.id , Test3.name , Test4.surname from Test3,Test4 where Test3.id = Test4.id;
select Test3.id , Test3.name , Test4.surname from Test3 join Test4 on Test3.id = Test4.id;

Both the above query statements resulted same as below:

1   Vijay   karma

2   Sandy   sharma

What is the difference in both queries internally and which one on more efficient?


问:
How to define a cell's content based on the contents of an object's attribute using setCellFactory?
I've created a class called "ChatMessage" with 3 attributes:

```<code>a) timeOfMessage
b) sentOrReceived
c) message
</code>```

and chat messages are stored inside an array of ChatMessages.
I've defined a tableView, and 3 tableColumns (for a, b and c), like so:

```<code>// ------------------------
// Step 1: Define tableView
// ------------------------
@FXML private TableView<ChatMessage> tableViewAllMessages;

// ---------------------------
// Step 2: Define table's data
// ---------------------------
private ObservableList<ChatMessage> allMessagesList;

// --------------------------------
// Step 3: Define table's 3 columns
// --------------------------------
@FXML private TableColumn<ChatMessage, LocalDateTime> timeColumn;
@FXML private TableColumn<ChatMessage, Boolean> sentOrReceivedColumn;
@FXML private TableColumn<ChatMessage, String> messageColumn;

// ---------------------------------
// Step 4: Using setCellValueFactory
// ---------------------------------
timeColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage,LocalDateTime>("dateTime"));
sentOrReceivedColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage, Boolean>("sentOrReceived"));
messageColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage,String>("message"));
tableViewAllMessages.setItems(allMessagesList);
</code>```

Everything works fine!
However, I would like to turn sentOrReceivedColumn (in Step 2), which currently of a boolean value, into a string value, based on the true/false it returns.
Is there a way to make a cell write 'someStringA' when false and 'someStringB' when true?
To be more specific, what do I need to change in here:

```<code>sentOrReceivedColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage, Boolean>("sentOrReceived"));
</code>```

or maybe add a line like this:

```<code>sentOrReceivedColumn.setCellFactory(/* But what Do I write here? */);
</code>```

?

```<code>
// Here is my ChatMessage Class:
public class ChatMessage {
    private Customer customer;
    private int messageNumber;
    private LocalDateTime dateTime;
    private String message;
    private boolean sentOrReceived;

    public ChatMessage(Customer customer, int messageNumber, LocalDateTime dateTime, String message, boolean sentOrReceived) {
        this.customer = customer;
        this.messageNumber = messageNumber;
        this.dateTime = dateTime;
        this.message = message;
        this.sentOrReceived = sentOrReceived;
    }
}
</code>```

答:
Thank you Slaw for your comment! It steered me in the right direction.
I implemented my own factory that maps the value with just a lambda expression as you suggested. This was the answer I was looking for:

```<code>col2_Nickname.setCellFactory(lambda -> new TableCell<ChatMessage, Boolean>() {
            @Override
            public void updateItem(Boolean sentOrReceived, boolean empty) {
                super.updateItem(sentOrReceived, empty);
                if (empty) {
                    setText(null);
                }else{
                    setText(sentOrReceived ? "MyNickname" : "His/Her nickname");
                }
            }
        });
</code>```

Body:
I've created a class called "ChatMessage" with 3 attributes:

a) timeOfMessage
b) sentOrReceived
c) message

and chat messages are stored inside an array of ChatMessages.
I've defined a tableView, and 3 tableColumns (for a, b and c), like so:

// ------------------------
// Step 1: Define tableView
// ------------------------
@FXML private TableView<ChatMessage> tableViewAllMessages;

// ---------------------------
// Step 2: Define table's data
// ---------------------------
private ObservableList<ChatMessage> allMessagesList;

// --------------------------------
// Step 3: Define table's 3 columns
// --------------------------------
@FXML private TableColumn<ChatMessage, LocalDateTime> timeColumn;
@FXML private TableColumn<ChatMessage, Boolean> sentOrReceivedColumn;
@FXML private TableColumn<ChatMessage, String> messageColumn;

// ---------------------------------
// Step 4: Using setCellValueFactory
// ---------------------------------
timeColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage,LocalDateTime>("dateTime"));
sentOrReceivedColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage, Boolean>("sentOrReceived"));
messageColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage,String>("message"));
tableViewAllMessages.setItems(allMessagesList);

Everything works fine!
However, I would like to turn sentOrReceivedColumn (in Step 2), which currently of a boolean value, into a string value, based on the true/false it returns.
Is there a way to make a cell write 'someStringA' when false and 'someStringB' when true?
To be more specific, what do I need to change in here:

sentOrReceivedColumn.setCellValueFactory(new PropertyValueFactory<ChatMessage, Boolean>("sentOrReceived"));

or maybe add a line like this:

sentOrReceivedColumn.setCellFactory(/* But what Do I write here? */);

?

// Here is my ChatMessage Class:
public class ChatMessage {
    private Customer customer;
    private int messageNumber;
    private LocalDateTime dateTime;
    private String message;
    private boolean sentOrReceived;

    public ChatMessage(Customer customer, int messageNumber, LocalDateTime dateTime, String message, boolean sentOrReceived) {
        this.customer = customer;
        this.messageNumber = messageNumber;
        this.dateTime = dateTime;
        this.message = message;
        this.sentOrReceived = sentOrReceived;
    }
}

Body:
Thank you Slaw for your comment! It steered me in the right direction.
I implemented my own factory that maps the value with just a lambda expression as you suggested. This was the answer I was looking for:

col2_Nickname.setCellFactory(lambda -> new TableCell<ChatMessage, Boolean>() {
            @Override
            public void updateItem(Boolean sentOrReceived, boolean empty) {
                super.updateItem(sentOrReceived, empty);
                if (empty) {
                    setText(null);
                }else{
                    setText(sentOrReceived ? "MyNickname" : "His/Her nickname");
                }
            }
        });


问:
How to select checked checkbox dynamically from a component with a call of the function?
I have a function inside the angular7 components. I want to call this function and get selected checkbox with id, class  whatever the possible solution.

```<code>get_selected_users(){
     checked_users = [01,333,43,54,656,234,234,324];
     checked_users.forEach(function(element) {
           console.log("element --->",element);
     });
</code>```

Html code

```<code><input type="checkbox" value="333" />
<input type="checkbox" value="54" />
<input type="checkbox" value="100" />
<input type="checkbox" value="999" />
</code>```

答:
Use below by including jquery:</p>

```<code>import * as $ from 'jquery';

$.each(checked_users, function(i, val){

if($("input[value='" + val + "']"))
   $("input[value='" + val + "']").prop('checked', true);

});
</code>```

Body:
I have a function inside the angular7 components. I want to call this function and get selected checkbox with id, class  whatever the possible solution.

get_selected_users(){
     checked_users = [01,333,43,54,656,234,234,324];
     checked_users.forEach(function(element) {
           console.log("element --->",element);
     });

Html code

<input type="checkbox" value="333" />
<input type="checkbox" value="54" />
<input type="checkbox" value="100" />
<input type="checkbox" value="999" />

Body:
Use below by including jquery:

import * as $ from 'jquery';

$.each(checked_users, function(i, val){

if($("input[value='" + val + "']"))
   $("input[value='" + val + "']").prop('checked', true);

});


问:
Timezone Abbreviations in Java
I have a collection of Java Date objects, loaded from an old database which did not store timezone info.

I know that all the dates (which include hours, minutes and seconds) are for the U.S. Eastern time zone.

I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.

Here is my attempt (using Java 11). It is unwieldy, to say the least.

I looked into the following classes:

```<code>java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules
</code>```

Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.

EDIT - based on @VGR's comment below, I have updated the example. Now it expects a timezone display name - for example "America/New_York":

```<code>public String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
    return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}
</code>```

It works (I have test cases), but is there a less verbose way?

(I did not find any code examples which use Date as their starting point).

答:
I have accepted Arvind's answer because he pointed out TimeZone.inDaylightTime() - but for the record, here is the updated version of the method in my question.

It is more concise now:

```<code>// tzName is a timezone display name, such as "America/New_York"

public static String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    return tz.getDisplayName(tz.inDaylightTime(date), TimeZone.SHORT);
}
</code>```

Warning

I also found answers in this question helpful - because if you type a non-existent timezone display name (or ID) when using TimeZone.getTimeZone(), Java will return "the specified TimeZone, or the GMT zone if the given ID cannot be understood" (emphasis mine). See here.

Typing...

America/New-York

...instead of...

America/New_York

...is enough to cause problems.

Therefore...

We should use java.time.ZoneId instead. This will throw an error for an invalid/unknown ID.

Title: Timezone Abbreviations in Java

Body:
I have a collection of Java Date objects, loaded from an old database which did not store timezone info.

I know that all the dates (which include hours, minutes and seconds) are for the U.S. Eastern time zone.

I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.

Here is my attempt (using Java 11). It is unwieldy, to say the least.

I looked into the following classes:

java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules

Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.

EDIT - based on @VGR's comment below, I have updated the example. Now it expects a timezone display name - for example "America/New_York":

public String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
    return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}

It works (I have test cases), but is there a less verbose way?

(I did not find any code examples which use Date as their starting point).

Body:
I have accepted Arvind's answer because he pointed out TimeZone.inDaylightTime() - but for the record, here is the updated version of the method in my question.

It is more concise now:

// tzName is a timezone display name, such as "America/New_York"

public static String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    return tz.getDisplayName(tz.inDaylightTime(date), TimeZone.SHORT);
}

Warning

I also found answers in this question helpful - because if you type a non-existent timezone display name (or ID) when using TimeZone.getTimeZone(), Java will return "the specified TimeZone, or the GMT zone if the given ID cannot be understood" (emphasis mine). See here.

Typing...

America/New-York

...instead of...

America/New_York

...is enough to cause problems.

Therefore...

We should use java.time.ZoneId instead. This will throw an error for an invalid/unknown ID.


问:
Finding all instances of a string within a string
What is a way that I can find (and loop through) all instances of a string within another string in lua? For example, if I have the string

```<code>"honewaidoneaeifjoneaowieone"
</code>```

And I want to loop through all instances (and by this, I mean indexes) of "one" within that string, well, I can see that it appears four times, but I have no clue how to actually find them. I know that string.find() can find the first instance, but that doesn't help me very much.

答:
You can tell string.find where to start the search:

```<code>s="honewaidoneaeifjoneaowieone"
p="one"
b=1
while true do
    local x,y=string.find(s,p,b,true)
    if x==nil then break end
    print(x)
    b=y+1
end
</code>```

This code starts each search after the end of the previous match, that is, it finds only non-overlapping occurrences of a string. If you want to find overlapping occurrences of a string, use b=x+1 instead.

Body:
What is a way that I can find (and loop through) all instances of a string within another string in lua? For example, if I have the string

"honewaidoneaeifjoneaowieone"

And I want to loop through all instances (and by this, I mean indexes) of "one" within that string, well, I can see that it appears four times, but I have no clue how to actually find them. I know that string.find() can find the first instance, but that doesn't help me very much.

Body:
You can tell string.find where to start the search:

s="honewaidoneaeifjoneaowieone"
p="one"
b=1
while true do
    local x,y=string.find(s,p,b,true)
    if x==nil then break end
    print(x)
    b=y+1
end

This code starts each search after the end of the previous match, that is, it finds only non-overlapping occurrences of a string. If you want to find overlapping occurrences of a string, use b=x+1 instead.


答:
Remove the inner for loop and you will get only 3 divs.

if you want to assign id's in div dynamically try this:

```<code>$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);
$i=1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    $i++;
}
</code>```

In your code you are getting 9 elements because what you are doing is first loop through $somearray elements which is 3 times and inside that loop you again loop for 3 times using variable $i so 3*3=9. and you are getting 9 divs.

Title: How to increment div id with php for loop?

Body:
Remove the inner for loop and you will get only 3 divs.

if you want to assign id's in div dynamically try this:

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);
$i=1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    $i++;
}

In your code you are getting 9 elements because what you are doing is first loop through $somearray elements which is 3 times and inside that loop you again loop for 3 times using variable $i so 3*3=9. and you are getting 9 divs.


问:
Is it possible to auto generate some code in HTML?
I'm a newbie with HTML and maybe the question is very stupid but Is it possible to create a loop in html?

What I have done so far is a survey that asks the user a number. Now with that number the idea is to create a determined text area with some inputs.

This is what I have:

```<code><p>-----DEFINITIONS-----

    <h1 id="demo"></h1>
    <script>
        var cant_def=prompt("How many definitions do you have?")
        var cant_par= prompt("How many pairs do you have?")

    </script>
    <p><b>Definition 1:</b></p>
    <p>Introduce the word:</p>
    <input type="text" name="campo1" style="width: 300px;"/>
    <p>Introduce the meaning:</p>
    <input type="text" name="camp1_res" style="width: 500px;" />

   <!--<textarea id="def1" rows="1" cols="20" name="def1"></textarea></p>  -->
</p>

</code>```

The area named "Definition 1:" only will works if the given number saved in "cant_def" is 1 and "cant_par" is 2. But if you want to have 3 definitions and 4 pairs the group "Definition 1" will appear 3 times with "campo1" and "camp1_res" repeated 4 times.

Let me show you what I mean with a graphic example.

The webpage asks you for the numbers and you write "2" and then, "2". So this would be the code generated:

```<code><p><b>Definition 1:</b></p>
    <p>Introduce the word:</p>
    <input type="text" name="campo1" style="width: 300px;"/>
    <p>Introduce the meaning:</p>
    <input type="text" name="camp1_res" style="width: 500px;" />
    <p>Introduce the word:</p>
    <input type="text" name="campo1" style="width: 300px;"/>
    <p>Introduce the meaning:</p>
    <input type="text" name="camp1_res" style="width: 500px;" />

    <p><b>Definition 2:</b></p>
    <p>Introduce the word:</p>
    <input type="text" name="campo1" style="width: 300px;"/>
    <p>Introduce the meaning:</p>
    <input type="text" name="camp1_res" style="width: 500px;" />
    <p>Introduce the word:</p>
    <input type="text" name="campo1" style="width: 300px;"/>
    <p>Introduce the meaning:</p>
    <input type="text" name="camp1_res" style="width: 500px;" />

</code>```

And this would be the result:

Another important thing, the variable "cant_par" must be an even number!
Thanks in advise~

答:
HTML is only a markup language, and cannot actually execute code. However, you can use JavaScript to loop using a for and/or while setup.

var number_of_definitions = 5;
for(i=0;i!=number_of_definitions;i++) {
    document.write("your html here");
}
```

Also, your definitions should be places in
 elements for easier handling. They help a lot when you get to CSS or when trying and format anything.

Body:
I'm a newbie with HTML and maybe the question is very stupid but Is it possible to create a loop in html?

What I have done so far is a survey that asks the user a number. Now with that number the idea is to create a determined text area with some inputs.

This is what I have:

-----DEFINITIONS-----

Definition 1:

Introduce the word:

    <input type="text" name="campo1" style="width: 300px;"/>

Introduce the meaning:

    <input type="text" name="camp1_res" style="width: 500px;" />

The area named "Definition 1:" only will works if the given number saved in "cant_def" is 1 and "cant_par" is 2. But if you want to have 3 definitions and 4 pairs the group "Definition 1" will appear 3 times with "campo1" and "camp1_res" repeated 4 times.

Let me show you what I mean with a graphic example.

The webpage asks you for the numbers and you write "2" and then, "2". So this would be the code generated:

Definition 1:

Introduce the word:

    <input type="text" name="campo1" style="width: 300px;"/>

Introduce the meaning:

    <input type="text" name="camp1_res" style="width: 500px;" />

Introduce the word:

    <input type="text" name="campo1" style="width: 300px;"/>

Introduce the meaning:

    <input type="text" name="camp1_res" style="width: 500px;" />

Definition 2:

Introduce the word:

    <input type="text" name="campo1" style="width: 300px;"/>

Introduce the meaning:

    <input type="text" name="camp1_res" style="width: 500px;" />

Introduce the word:

    <input type="text" name="campo1" style="width: 300px;"/>

Introduce the meaning:

    <input type="text" name="camp1_res" style="width: 500px;" />

And this would be the result:

Another important thing, the variable "cant_par" must be an even number!
Thanks in advise~

Body:
HTML is only a markup language, and cannot actually execute code. However, you can use JavaScript to loop using a for and/or while setup.

var number_of_definitions = 5;
for(i=0;i!=number_of_definitions;i++) {
    document.write("your html here");
}

Also, your definitions should be places in <div> elements for easier handling. They help a lot when you get to CSS or when trying and format anything.


问:
How do I throw an exception in my Java code?
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?</p>

```<code>class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}
</code>```

答:
Firstly you call your printAnimal() method without a parameter. That's no good.

Secondly, there are two kinda of exceptions in Java, checked and unchecked. You need to consider which kind you're working with.

Checked means your function must be declared by:

methodName() throws SomeException{
...}

And accordingly a caller MUST catch exceptions.

Unchecked means you can throw the exception without doing this, but other programmers aren't made aware of (and conversely, not forced to handle) any exceptions thrown.

Exceptions should be created, like classes, inheriting the base type of exception appropriate.

Checked exception

```<code>class someException extends exception{...}
</code>```

Unchecked exception

```<code>class someException extends RuntimeException{...}
</code>```

For non custom exceptions they are thrown like so:

The checked exception

```<code>throw new Exception ('message');
</code>```

The unchecked exception

```<code>throw new RuntimeException ('message');
</code>```

Please read the Java doc on exceptions.
Exceptions are an important part of OOP

(This was written on a phone, so there might be a few typos etc.)

Body:
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?

class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}

Body:
Firstly you call your printAnimal() method without a parameter. That's no good.

Secondly, there are two kinda of exceptions in Java, checked and unchecked. You need to consider which kind you're working with.

Checked means your function must be declared by:

methodName() throws SomeException{
...}

And accordingly a caller MUST catch exceptions.

Unchecked means you can throw the exception without doing this, but other programmers aren't made aware of (and conversely, not forced to handle) any exceptions thrown.

Exceptions should be created, like classes, inheriting the base type of exception appropriate.

Checked exception

class someException extends exception{...}

Unchecked exception

class someException extends RuntimeException{...}

For non custom exceptions they are thrown like so:

The checked exception

throw new Exception ('message');

The unchecked exception

throw new RuntimeException ('message');

Please read the Java doc on exceptions.
Exceptions are an important part of OOP

(This was written on a phone, so there might be a few typos etc.)