问:
H2 - Hibernate not inserting Default column values on SQL INSERT
I'm developing a service and currently working on 2 of its entities (Section and GradeLevel)
While I'm still developing, I decided to use H2 and I generate the tables from Java code.

Section.java

```<code>@Entity
@Setter
@Getter
public class Section{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;

    @OneToOne
    private GradeLevel gradeLevel;

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}
</code>```

GradeLevel.java

```<code>@Entity
@Getter
@Setter
public class GradeLevel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String code; //GL-01, GL-02...

    @Column(unique = true)
    private String description; //Kinder 1, Kinder 2, Grade 1....
    private String category; //Elementary School, Junior Highschool, Senior Highschool

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}
</code>```

SectionRESTController.java

```<code>@RestController
@RequestMapping(value = "/api/sections")
public class SectionRESTController {

    @Autowired
    private SectionService sectionService;

    @GetMapping(path = "/{sectionId}")
    public Section getSectionById(@PathVariable("sectionId") Long id) {
        return sectionService.getSectionById(id);
    }

    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<Section> createSection(@Valid @RequestBody SectionCreateDTO sectionCreateDTO) {
        Section createdSection = sectionService.createSection(sectionCreateDTO.toSection());
        if (createdSection == null) {
            return ResponseEntity.notFound().build();
        } else {
            URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{sectionId}")
                    .buildAndExpand(createdSection.getId())
                    .toUri();
            return ResponseEntity.created(uri)
                    .body(createdSection);
        }
    }
}
</code>```

SectionCreateDTO.java

```<code>@Data
public class SectionCreateDTO {
    @NotEmpty(message = "Section name is required.")
    private String name;

    @NotNull(message = "gradelevel id is required.")
    private Long gradeLevelId;

    public Section toSection() {
        Section section = new Section();
        section.setName(name);

        GradeLevel gradeLevel = new GradeLevel();
        gradeLevel.setId(gradeLevelId);

        section.setGradeLevel(gradeLevel);
        return section;
    }
}
</code>```

Problem :
The createSection() controller method is not inserting the DEFAULT column values for Section's  IS_ACTIVE and DATE_CREATED column. I have set both of these 2 columns to have TRUE and CURRENT_TIMESTAMP default values

Sample request in Postman :

POST localhost:8080/api/sections

```<code>{
        "name": "MERCURY",
        "gradeLevelId" : 1
}
</code>```

In H2 Console, Section table shows NULL and FALSE for those fields. Instead of the correct timestamp and TRUE value.

application.properties

```<code>#========================================================================
#H2 Properties
#========================================================================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
</code>```

I don't know if this problem is only specific to H2 or maybe I am missing something here.

I'd appreciate any comments.

====== EDIT. Below is the Solution =======

The solution that worked for me is this :

```<code>@Column(columnDefinition = "boolean default true")
private Boolean isActive = true;

@CreationTimestamp
@Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();

@UpdateTimestamp
@Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
</code>```

Thank you for the suggestion and answers.

答:
The issue with IS_ACTIVE column that you are using boolean(it is false by default, but you need a null) instead of Boolean.
For created timestamp you can try adding @CreationTimestamp</p>

Body:
I'm developing a service and currently working on 2 of its entities (Section and GradeLevel)
While I'm still developing, I decided to use H2 and I generate the tables from Java code.

Section.java

@Entity
@Setter
@Getter
public class Section{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;

    @OneToOne
    private GradeLevel gradeLevel;

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}

GradeLevel.java

@Entity
@Getter
@Setter
public class GradeLevel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String code; //GL-01, GL-02...

    @Column(unique = true)
    private String description; //Kinder 1, Kinder 2, Grade 1....
    private String category; //Elementary School, Junior Highschool, Senior Highschool

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}

SectionRESTController.java

@RestController
@RequestMapping(value = "/api/sections")
public class SectionRESTController {

    @Autowired
    private SectionService sectionService;

    @GetMapping(path = "/{sectionId}")
    public Section getSectionById(@PathVariable("sectionId") Long id) {
        return sectionService.getSectionById(id);
    }

    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity
 createSection(@Valid @RequestBody SectionCreateDTO sectionCreateDTO) {
        Section createdSection = sectionService.createSection(sectionCreateDTO.toSection());
        if (createdSection == null) {
            return ResponseEntity.notFound().build();
        } else {
            URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{sectionId}")
                    .buildAndExpand(createdSection.getId())
                    .toUri();
            return ResponseEntity.created(uri)
                    .body(createdSection);
        }
    }
}

SectionCreateDTO.java

@Data
public class SectionCreateDTO {
    @NotEmpty(message = "Section name is required.")
    private String name;

    @NotNull(message = "gradelevel id is required.")
    private Long gradeLevelId;

    public Section toSection() {
        Section section = new Section();
        section.setName(name);

        GradeLevel gradeLevel = new GradeLevel();
        gradeLevel.setId(gradeLevelId);

        section.setGradeLevel(gradeLevel);
        return section;
    }
}

Problem :
The createSection() controller method is not inserting the DEFAULT column values for Section's  IS_ACTIVE and DATE_CREATED column. I have set both of these 2 columns to have TRUE and CURRENT_TIMESTAMP default values

Sample request in Postman :

POST localhost:8080/api/sections

{
        "name": "MERCURY",
        "gradeLevelId" : 1
}

In H2 Console, Section table shows NULL and FALSE for those fields. Instead of the correct timestamp and TRUE value.

application.properties

#========================================================================
#H2 Properties
#========================================================================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

I don't know if this problem is only specific to H2 or maybe I am missing something here.

I'd appreciate any comments.

====== EDIT. Below is the Solution =======

The solution that worked for me is this :

@Column(columnDefinition = "boolean default true")
private Boolean isActive = true;

@CreationTimestamp
@Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();

@UpdateTimestamp
@Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();

Thank you for the suggestion and answers.


来源: stackexchange

问:
Angular programmatically add ngbTooltip on event target doesn't work
I'm trying to add a tooltip on the clicked elements in my component view, which are mostly svg polygons and paths,
I have tried this function to set the ngbtooltip attribute on the target clicked elements,
but nothing is happening when I click an element and hover on it again, although the clicked element in my inspector appear to have the ngbtooltip attribute added

my View

```<code><div class="col py-2" #ngbTooltipp>
    <!-- poc only -->
    <svg-icon (click)="selectSector($event)" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>
  </div>
</code>```

my ts file

```<code> public selectSector($event: MouseEvent) {
    // set the tooltip
    let clickedEl = $event.target;
    this.renderer.setAttribute(clickedEl, "ngbtooltip", "hello");
  }
</code>```

答:
Try this form https://ng-bootstrap.github.io/#/components/tooltip/examples#triggers

    <svg-icon ngbTooltip="You see, I show up on click!" triggers="click:blur" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>

```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add a tooltip on the clicked elements in my component view, which are mostly svg polygons and paths,
I have tried this function to set the ngbtooltip attribute on the target clicked elements,
but nothing is happening when I click an element and hover on it again, although the clicked element in my inspector appear to have the ngbtooltip attribute added

my View

    <svg-icon (click)="selectSector($event)" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>

my ts file

 public selectSector($event: MouseEvent) {
    // set the tooltip
    let clickedEl = $event.target;
    this.renderer.setAttribute(clickedEl, "ngbtooltip", "hello");
  }

Body:
Try this form https://ng-bootstrap.github.io/#/components/tooltip/examples#triggers

<div class="col py-2" #ngbTooltipp>
    <!-- poc only -->
    <svg-icon ngbTooltip="You see, I show up on click!" triggers="click:blur" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>
  </div>


问:
How to use CSS to create a 2nd card next to another one, side by side to display information?
I have created a weather "page" project using HTML, CSS and javascript.

I want to create a seperate card to display map informations and put it next to the other card that displays the weather information.

I want this (ignore the language, it's in greek, my native language):

code:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  font-family: 'Open Sans', sans-serif;
  background: #222;
  background-image: url('https://source.unsplash.com/1600x900/?landscape');
  font-size: 115%;
}

.card {
  background: #000000d0;
  color: white;
  padding: 2em;
  border-radius: 30px;
  width: 100%;
  max-width: 420px;
  margin: 1em;
  margin-top: 5%;
  margin-right: 40%;

}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
}
.city {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 200%;
}
button {
  margin: 0.5em;
  border-radius: 50%;
  border: none;
  height: 44px;
  width: 44px;
  outline: none;
  background: #7c7c7c2b;
  color: white;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}

input.search-bar {
  border: none;
  outline: none;
  padding: 0.4em 1em;
  border-radius: 24px;
  background: #7c7c7c2b;
  color: white;
  font-family: inherit;
  font-size: 105%;
  width: calc(100% - 100px);
}

button:hover {
  background: #7c7c7c6b;
}

h1.temp {
  margin: 0;
  margin-bottom: 0.4em;
  display: flex;
  justify-content: center;
  align-items: center;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.description {
  text-transform: capitalize;
  margin-left: 8px;
  margin-top: 20px;
}

.icon{
  margin-top: 3px;
}
.weather.loading {
  visibility: hidden;
  max-height: 20px;
  position: relative;
}

.weather.loading:after {
  visibility: visible;
  content: "Loading...";
  color: white;
  position: absolute;
  top: 0;
  left: 20px;
}
.coord {
  color:rgb(221, 218, 215);
  margin-left: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.coord-list{
   display: flex;
  justify-content: center;
  align-items: center;
  color:rgb(221, 218, 215);
  font-size: 85%;
  margin: 0;
  margin-top: -10px;
}

.icon-sunrise {
  margin-left: 4px;
}
.icon-sunset {
  margin-left: 4px;
}

.feels-like {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  align-items: center;
  margin-top: 5px;
  font-size: 85%

}

p {
  display: flex;
    flex-wrap: wrap;
    justify-content: center;
  align-items: center;
  margin-top: -10px;
  font-size: 85%
}

.local-time {
  margin-top: -20px;
  margin-bottom: 20px;
  font-size: 110%
}

#time-icon{
  margin-top: 20px;
  margin-bottom: -2px;

  margin-left: 4px;
}

.date {
  font-size: 80%;
  display: flex;
  justify-content: center;
  align-items: center;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather App</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">

  <link rel="stylesheet" href="./style.css">

</head>

<body>

  <script src="https://momentjs.com/downloads/moment.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script src="./script.js" defer></script>

  <div class="card">

    <div class="search">
      <input type="text" class="search-bar" placeholder="Search">
      <button><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1.5em"
          width="1.5em" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z">
          </path>
        </svg></button>
    </div>
    <div class="weather loading">
      <hr>
      <div class="date">Date: </div>
      <hr>
      <h2 class="city">Weather in Denver</h2>
      <div class="local-time" style="text-align: center;">
      <span class="time">Time: </span>
      <svg id="time-icon"stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path><path d="M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"></path></svg>
      </div>
      <hr>
      <h4 class="coord">Γεωγραφικές Συντεταγμένες:</h4>
      <ul class="coord-list">
        <li class="lon">Γεωγραφικό μήκος (longitude): </li>
        <li class="lat">Γεωγραφικό πλάτος (latitude):</li>
      </ul>

      <hr>
      <div class="flex">
        <img src="https://openweathermap.org/img/wn/04n.png" alt="" class="icon" />
        <h3 class="description">Cloudy</h3>
      </div>
      <h1 class="temp">51°C</h1>
      <p class="feels-like">Feels like:</p>
      <p class="temp_min">Temp min: </p>
      <p class="temp_max">Temp max: </p>
      <hr>
      <div class="humidity">Humidity: 60%</div>
      <div class="visibility">Visibility: </div>
      <div class="cloudiness">clouds:</div>
      <div class="pressure">Πιεση:</div>
      <div class="wind">Wind speed: 6.2 km/h</div>
      <div class="wind-deg">Wind deg: </div>
      <div class="wind-gust">Wind gust: </div>
      <hr>
      <span class="sunrise">Sunrise: </span>
      <svg class ="icon-sunrise" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M17 18a5 5 0 0 0-10 0"></path><line x1="12" y1="2" x2="12" y2="9"></line><line x1="4.22" y1="10.22" x2="5.64" y2="11.64"></line><line x1="1" y1="18" x2="3" y2="18"></line><line x1="21" y1="18" x2="23" y2="18"></line><line x1="18.36" y1="11.64" x2="19.78" y2="10.22"></line><line x1="23" y1="22" x2="1" y2="22"></line><polyline points="8 6 12 2 16 6"></polyline></svg>
      <br>
      <span class="sunset">Sunset: </span>
      <svg class="icon-sunset" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M17 18a5 5 0 0 0-10 0"></path><line x1="12" y1="9" x2="12" y2="2"></line><line x1="4.22" y1="10.22" x2="5.64" y2="11.64"></line><line x1="1" y1="18" x2="3" y2="18"></line><line x1="21" y1="18" x2="23" y2="18"></line><line x1="18.36" y1="11.64" x2="19.78" y2="10.22"></line><line x1="23" y1="22" x2="1" y2="22"></line><polyline points="16 5 12 9 8 5"></polyline></svg>
     </div>

</body>
</html></code>```

How can I achieve this? I want the 2nd card to be the same style as the 1st card.

Thank you and sorry for my lack of knowledge, I am a begginer.

答:
I'm not 100% sure this is the best way to do it since I usually use bootstrap to manage the styles. But something you can do is encase both cards in a flex div and make that div a flexbox, the code would look like so:

html:

```<code><div class="flexbox">
    <div class="card">
        [...]
    </div>
    <div class="card">
        [...]
    </div>
</div>
</code>```

css:

```<code>  .flexbox {
      display: flex;
  }
  .card {
      margin-right: 5%;
  }
</code>```

Body:
I have created a weather "page" project using HTML, CSS and javascript.

I want to create a seperate card to display map informations and put it next to the other card that displays the weather information.

I want this (ignore the language, it's in greek, my native language):

code:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  font-family: 'Open Sans', sans-serif;
  background: #222;
  background-image: url('https://source.unsplash.com/1600x900/?landscape');
  font-size: 115%;
}

.card {
  background: #000000d0;
  color: white;
  padding: 2em;
  border-radius: 30px;
  width: 100%;
  max-width: 420px;
  margin: 1em;
  margin-top: 5%;
  margin-right: 40%;

}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
}
.city {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 200%;
}
button {
  margin: 0.5em;
  border-radius: 50%;
  border: none;
  height: 44px;
  width: 44px;
  outline: none;
  background: #7c7c7c2b;
  color: white;
  cursor: pointer;
  transition: 0.2s ease-in-out;
}

input.search-bar {
  border: none;
  outline: none;
  padding: 0.4em 1em;
  border-radius: 24px;
  background: #7c7c7c2b;
  color: white;
  font-family: inherit;
  font-size: 105%;
  width: calc(100% - 100px);
}

button:hover {
  background: #7c7c7c6b;
}

h1.temp {
  margin: 0;
  margin-bottom: 0.4em;
  display: flex;
  justify-content: center;
  align-items: center;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.description {
  text-transform: capitalize;
  margin-left: 8px;
  margin-top: 20px;
}

.icon{
  margin-top: 3px;
}
.weather.loading {
  visibility: hidden;
  max-height: 20px;
  position: relative;
}

.weather.loading:after {
  visibility: visible;
  content: "Loading...";
  color: white;
  position: absolute;
  top: 0;
  left: 20px;
}
.coord {
  color:rgb(221, 218, 215);
  margin-left: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.coord-list{
   display: flex;
  justify-content: center;
  align-items: center;
  color:rgb(221, 218, 215);
  font-size: 85%;
  margin: 0;
  margin-top: -10px;
}

.icon-sunrise {
  margin-left: 4px;
}
.icon-sunset {
  margin-left: 4px;
}

.feels-like {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  align-items: center;
  margin-top: 5px;
  font-size: 85%

}

p {
  display: flex;
    flex-wrap: wrap;
    justify-content: center;
  align-items: center;
  margin-top: -10px;
  font-size: 85%
}

.local-time {
  margin-top: -20px;
  margin-bottom: 20px;
  font-size: 110%
}

#time-icon{
  margin-top: 20px;
  margin-bottom: -2px;

  margin-left: 4px;
}

.date {
  font-size: 80%;
  display: flex;
  justify-content: center;
  align-items: center;

}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather App</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">

  <link rel="stylesheet" href="./style.css">

      <input type="text" class="search-bar" placeholder="Search">
      <button><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1.5em"
          width="1.5em" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z">
          </path>
        </svg></button>

Date:

Weather in Denver

      Time:
      <svg id="time-icon"stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path><path d="M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"></path></svg>

Γεωγραφικές Συντεταγμένες:

Γεωγραφικό μήκος (longitude):

Γεωγραφικό πλάτος (latitude):

Cloudy

51°C

Feels like:

Temp min:

Temp max:

Humidity: 60%

Visibility:

clouds:

Πιεση:

Wind speed: 6.2 km/h

Wind deg:

Wind gust:

      Sunrise:
      <svg class ="icon-sunrise" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M17 18a5 5 0 0 0-10 0"></path><line x1="12" y1="2" x2="12" y2="9"></line><line x1="4.22" y1="10.22" x2="5.64" y2="11.64"></line><line x1="1" y1="18" x2="3" y2="18"></line><line x1="21" y1="18" x2="23" y2="18"></line><line x1="18.36" y1="11.64" x2="19.78" y2="10.22"></line><line x1="23" y1="22" x2="1" y2="22"></line><polyline points="8 6 12 2 16 6"></polyline></svg>

      Sunset:
      <svg class="icon-sunset" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M17 18a5 5 0 0 0-10 0"></path><line x1="12" y1="9" x2="12" y2="2"></line><line x1="4.22" y1="10.22" x2="5.64" y2="11.64"></line><line x1="1" y1="18" x2="3" y2="18"></line><line x1="21" y1="18" x2="23" y2="18"></line><line x1="18.36" y1="11.64" x2="19.78" y2="10.22"></line><line x1="23" y1="22" x2="1" y2="22"></line><polyline points="16 5 12 9 8 5"></polyline></svg>

How can I achieve this? I want the 2nd card to be the same style as the 1st card.

Thank you and sorry for my lack of knowledge, I am a begginer.

Body:
I'm not 100% sure this is the best way to do it since I usually use bootstrap to manage the styles. But something you can do is encase both cards in a flex div and make that div a flexbox, the code would look like so:

html:

<div class="flexbox">
    <div class="card">
        [...]
    </div>
    <div class="card">
        [...]
    </div>
</div>

css:

  .flexbox {
      display: flex;
  }
  .card {
      margin-right: 5%;
  }


问:
how to list a range of numbers in file
I have a file named example.txt and inside the file I have numbers from 1 -50 but I only want to view number within a particular range like 1-25

I tried this command:
less example.txt | grep [1-25]

but this didn't help, please help

答:
[1-25] means match group of characters consisting of characters between 1 and 2 and character 5. It's the same as [125] - match any of 1 2 or 5.

You can:

```<code>grep '[1-9]\|1[0-9]\|2[0-5]'
</code>```

Match digits 1 to 9, or match 1 followed by digit 0 to 8, or match 2 followed by digit 0 to 5. Maybe add -w, see man grep.

I recommend regex crosswords for learning regex.

Title: how to list a range of numbers in file

Body:
[1-25] means match group of characters consisting of characters between 1 and 2 and character 5. It's the same as [125] - match any of 1 2 or 5.

You can:

grep '[1-9]\|1[0-9]\|2[0-5]'

Match digits 1 to 9, or match 1 followed by digit 0 to 8, or match 2 followed by digit 0 to 5. Maybe add -w, see man grep.

I recommend regex crosswords for learning regex.


问:
Checking a Python module version at runtime
Many third-party Python modules have an attribute which holds the version information for the module (usually something like module.VERSION or module.__version__), however some do not.

Particular examples of such modules are libxslt and libxml2.

I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?

A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty.

Is there a better solutions?

答:
Some ideas:

Try checking for functions that exist or don't exist in your needed versions.

If there are no function differences, inspect function arguments and signatures.

If you can't figure it out from function signatures, set up some stub calls at import time and check their behavior.

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Richard Levasseur

ContentLicense: CC BY-SA 2.5


问:
Order a set, maintaining multiple defined groupings
Since its hard for me to describe what I want in general, I try it with an example:

Given a set {x,y,z,d} and subsets {x,z}, {d,y} and {x,y}, I would like to order the first set {x,y,z,d} so that the small sets dont get torn apart (the permutation in each set is not important, so {x,y} or {y,x} is the same}.

The length of the example sets can be larger than what is given here. The small sets are always real subsets of the largest set.

I think it would be nice to have a way to say ok this part of the set has to stay in this configuration (x has to be next to y), but this part is arbitrary. Any recommendation how to do it?
I tried to do it with a tree, but I am completely failing with this problem:(

答:
I don't think a brute force solution lacks elegance, but it will certainly try many options that aren't worth considering:

```<code>from itertools import permutations

def find_ordering(main, subsets):
    for p in permutations(main):
        if all(any(set(p[i:i+len(s)]) == s
                   for i in range(len(main) - len(s) + 1))
               for s in subsets):
            return p

print(find_ordering({1, 2, 3, 4}, [{1, 3}, {4, 2}, {1, 2}]))
</code>```

Result:

```<code>(3, 1, 2, 4)
</code>```

Edit: OK, that was a tough nut to crack, but here's a smarter solution:

```<code>from functools import reduce
from itertools import permutations

def shove(xs: set, yss: list[set]) -> list[set]:
    # move n up to the first part of yss that's not or only partially contained in xs
    # this works because there's no duplicates members among any members of yss
    n = 0
    while n < len(yss) and yss[n] <= xs:
        xs = xs - yss[n]
        n += 1
    # if xs could be shoved into yss entirely
    if not xs:
        return yss
    # if xs covers yss entirely, and some is left over
    elif n >= len(yss):
        return [xs] + yss
    else:
        # h, i, t = xs - yss[n], xs & yss[n], yss[n] - xs
        h, t = xs - (i := yss[n] & xs), yss[n] - i
        # avoid returning empty sets as part of the solution
        return ([h] if h else []) + yss[:n] + ([i] if i else []) + ([t] if t else []) + yss[n+1:]

def find_ordering(main: set, subsets: list[set]) -> list | None:
    # ensure there are no elements in subsets that are not in main
    if not set(reduce(set.union, subsets, set())) <= main:
        return None
    for p in permutations(subsets):
        solution = []
        solution_set = set()
        # try to shove subsets into each other, in order p
        for subset in p:
            solution = shove(subset, solution)
            # if new solution[0] contains elements in the prev solution, there's now duplicates
            if solution[0] & solution_set:
                break
            solution_set = solution_set.union(solution[0])
        else:
            # if all subsets could be shoved together, it's a solution, stop looking and return
            return [x for xs in solution for x in xs]

print(find_ordering({1, 2, 3, 4}, [{1, 3}, {4, 2}, {1, 2}]))
print(find_ordering({1, 2, 3, 4, 5, 6, 7}, [{1, 3}, {4, 2}, {1, 2}, {4, 5, 6}, {3, 7}]))
print(find_ordering({1, 2, 3, 4, 5, 6, 7}, [{1, 6}, {2, 1, 4}, {7, 3}, {3, 4}, {5, 6}]))
</code>```

Result:

```<code>[4, 2, 1, 3]
[7, 3, 1, 2, 4, 5, 6]
[5, 6, 1, 2, 4, 3, 7]
</code>```

The approach hinges on the idea of shoving subsets into each other. If you shove {1, 2} into [{2, 3, 4}], the outcome is [{1}, {2}, {3, 4}] - i.e. a fixed ordering of sets that still contains the groupings in the original sets. 3 and 4 can still change places and the ordering will hold, but none of the sets can change place or the ordering is broken. The shove() function performs this operation. When shoving, it never changes the order of the sets in the list, but it ignores the order of elements in the sets for matching (as expected).

The find_ordering() function uses shove to try and shove subsets into each other in every possible order (using permutations of the subsets).

If the first set in an expanded solution (after a shove) contains any elements that were already in the solution, it means there's now a duplicate in the solution and it won't work, so it moves on to the next permutation.

Before starting find_ordering(), it checks if the subsets actually solely consist of elements of main, because otherwise it would try them all while a solution is impossible. In that case, or if no permutation works, the function returns None.

That was a fun question, thanks. If you see any issue with this solution, do let me know.

Edit: you correctly identified a problem with the solution - turns out there were 3 problems, but I think this is better. Don't drink and code, kids.

Body:
I don't think a brute force solution lacks elegance, but it will certainly try many options that aren't worth considering:

from itertools import permutations

def find_ordering(main, subsets):
    for p in permutations(main):
        if all(any(set(p[i:i+len(s)]) == s
                   for i in range(len(main) - len(s) + 1))
               for s in subsets):
            return p

print(find_ordering({1, 2, 3, 4}, [{1, 3}, {4, 2}, {1, 2}]))

Result:

(3, 1, 2, 4)

Edit: OK, that was a tough nut to crack, but here's a smarter solution:

from functools import reduce
from itertools import permutations

def shove(xs: set, yss: list[set]) -> list[set]:
    # move n up to the first part of yss that's not or only partially contained in xs
    # this works because there's no duplicates members among any members of yss
    n = 0
    while n < len(yss) and yss[n] <= xs:
        xs = xs - yss[n]
        n += 1
    # if xs could be shoved into yss entirely
    if not xs:
        return yss
    # if xs covers yss entirely, and some is left over
    elif n >= len(yss):
        return [xs] + yss
    else:
        # h, i, t = xs - yss[n], xs & yss[n], yss[n] - xs
        h, t = xs - (i := yss[n] & xs), yss[n] - i
        # avoid returning empty sets as part of the solution
        return ([h] if h else []) + yss[:n] + ([i] if i else []) + ([t] if t else []) + yss[n+1:]

def find_ordering(main: set, subsets: list[set]) -> list | None:
    # ensure there are no elements in subsets that are not in main
    if not set(reduce(set.union, subsets, set())) <= main:
        return None
    for p in permutations(subsets):
        solution = []
        solution_set = set()
        # try to shove subsets into each other, in order p
        for subset in p:
            solution = shove(subset, solution)
            # if new solution[0] contains elements in the prev solution, there's now duplicates
            if solution[0] & solution_set:
                break
            solution_set = solution_set.union(solution[0])
        else:
            # if all subsets could be shoved together, it's a solution, stop looking and return
            return [x for xs in solution for x in xs]

print(find_ordering({1, 2, 3, 4}, [{1, 3}, {4, 2}, {1, 2}]))
print(find_ordering({1, 2, 3, 4, 5, 6, 7}, [{1, 3}, {4, 2}, {1, 2}, {4, 5, 6}, {3, 7}]))
print(find_ordering({1, 2, 3, 4, 5, 6, 7}, [{1, 6}, {2, 1, 4}, {7, 3}, {3, 4}, {5, 6}]))

Result:

[4, 2, 1, 3]
[7, 3, 1, 2, 4, 5, 6]
[5, 6, 1, 2, 4, 3, 7]

The approach hinges on the idea of shoving subsets into each other. If you shove {1, 2} into [{2, 3, 4}], the outcome is [{1}, {2}, {3, 4}] - i.e. a fixed ordering of sets that still contains the groupings in the original sets. 3 and 4 can still change places and the ordering will hold, but none of the sets can change place or the ordering is broken. The shove() function performs this operation. When shoving, it never changes the order of the sets in the list, but it ignores the order of elements in the sets for matching (as expected).

The find_ordering() function uses shove to try and shove subsets into each other in every possible order (using permutations of the subsets).

If the first set in an expanded solution (after a shove) contains any elements that were already in the solution, it means there's now a duplicate in the solution and it won't work, so it moves on to the next permutation.

Before starting find_ordering(), it checks if the subsets actually solely consist of elements of main, because otherwise it would try them all while a solution is impossible. In that case, or if no permutation works, the function returns None.

That was a fun question, thanks. If you see any issue with this solution, do let me know.

Edit: you correctly identified a problem with the solution - turns out there were 3 problems, but I think this is better. Don't drink and code, kids.


问:
How do I convert integer 'category' dtypes in a Pandas DataFrame to 'int64'/'float64'?
Take a look at the Pandas DataFrame here.

I have certain columns that are strings, and others that are integers/floats. However, all the columns in the dataset are currently formatted with a 'category' dtype.

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 29744 entries, 0 to 29743
Data columns (total 366 columns):
 #    Column      Non-Null Count  Dtype
---   ------      --------------  -----
 0    ASBG01      29360 non-null  category
 1    ASBG03      28726 non-null  category
 2    ASBG04      28577 non-null  category
 3    ASBG05A     29130 non-null  category
 4    ASBG05B     29055 non-null  category
 5    ASBG05C     29001 non-null  category
 6    ASBG05D     28938 non-null  category
 7    ASBG05E     28938 non-null  category
 8    ASBG05F     29030 non-null  category
 9    ASBG05G     28745 non-null  category
 10   ASBG05H     28978 non-null  category
 11   ASBG05I     28971 non-null  category
 12   ASBG06A     28956 non-null  category
 13   ASBG06B     28797 non-null  category
 14   ASBG07      28834 non-null  category
 15   ASBG08      28955 non-null  category
 16   ASBG09A     28503 non-null  category
 17   ASBG09B     27778 non-null  category
 18   ASBG10A     29025 non-null  category
 19   ASBG10B     28940 non-null  category
 ...
 363  ATDMDAT     13133 non-null  category
 364  ATDMMEM     25385 non-null  category
 365  Target      29744 non-null  float64
dtypes: category(365), float64(1)
memory usage: 60.5 MB
</code>```

How can I convert all the columns that have a integer/float value under them to actual integer/float dtypes?

Thanks.

答:
Suppose the following dataframe:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'cat_str': ['Hello', 'World'],
                   'cat_int': [0, 1],
                   'cat_float': [3.14, 2.71]}, dtype='category')
print(df.dtypes)

# Output
cat_str      category
cat_int      category
cat_float    category
dtype: object
</code>```

You can try:

```<code>dtypes = {col: df[col].cat.categories.dtype for col in df.columns
             if np.issubdtype(df[col].cat.categories.dtype, np.number)}

df = df.astype(dtypes)
print(df.dtypes)

# Output
cat_str      category
cat_int         int64
cat_float     float64
dtype: object
</code>```

Or if you want to remove all category dtypes, use:

```<code>dtypes = {col: df[col].cat.categories.dtype for col in df.columns}

df = df.astype(dtypes)
print(df.dtypes)

# Output
cat_str       object
cat_int        int64
cat_float    float64
dtype: object
</code>```

Body:
Take a look at the Pandas DataFrame here.

I have certain columns that are strings, and others that are integers/floats. However, all the columns in the dataset are currently formatted with a 'category' dtype.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29744 entries, 0 to 29743
Data columns (total 366 columns):
 #    Column      Non-Null Count  Dtype
---   ------      --------------  -----
 0    ASBG01      29360 non-null  category
 1    ASBG03      28726 non-null  category
 2    ASBG04      28577 non-null  category
 3    ASBG05A     29130 non-null  category
 4    ASBG05B     29055 non-null  category
 5    ASBG05C     29001 non-null  category
 6    ASBG05D     28938 non-null  category
 7    ASBG05E     28938 non-null  category
 8    ASBG05F     29030 non-null  category
 9    ASBG05G     28745 non-null  category
 10   ASBG05H     28978 non-null  category
 11   ASBG05I     28971 non-null  category
 12   ASBG06A     28956 non-null  category
 13   ASBG06B     28797 non-null  category
 14   ASBG07      28834 non-null  category
 15   ASBG08      28955 non-null  category
 16   ASBG09A     28503 non-null  category
 17   ASBG09B     27778 non-null  category
 18   ASBG10A     29025 non-null  category
 19   ASBG10B     28940 non-null  category
 ...
 363  ATDMDAT     13133 non-null  category
 364  ATDMMEM     25385 non-null  category
 365  Target      29744 non-null  float64
dtypes: category(365), float64(1)
memory usage: 60.5 MB

How can I convert all the columns that have a integer/float value under them to actual integer/float dtypes?

Thanks.

Body:
Suppose the following dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame({'cat_str': ['Hello', 'World'],
                   'cat_int': [0, 1],
                   'cat_float': [3.14, 2.71]}, dtype='category')
print(df.dtypes)

# Output
cat_str      category
cat_int      category
cat_float    category
dtype: object

You can try:

dtypes = {col: df[col].cat.categories.dtype for col in df.columns
             if np.issubdtype(df[col].cat.categories.dtype, np.number)}

df = df.astype(dtypes)
print(df.dtypes)

# Output
cat_str      category
cat_int         int64
cat_float     float64
dtype: object

Or if you want to remove all category dtypes, use:

dtypes = {col: df[col].cat.categories.dtype for col in df.columns}

df = df.astype(dtypes)
print(df.dtypes)

# Output
cat_str       object
cat_int        int64
cat_float    float64
dtype: object


问:
safety -- late initialization error // FLUTTER

I have an error in the code because of safety in Flutter and I have tried to solve it with the declaration of variables using LATE.<br /

But it appears antother one when I try to build it:

Error

This is my code:

```<code>class AnimacionesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CuadradoAnimado(),
      ),
    );
  }
}

class CuadradoAnimado extends StatefulWidget {
  @override
  _CuadradoAnimadoState createState() => _CuadradoAnimadoState();
}

class _CuadradoAnimadoState extends State<CuadradoAnimado>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

@override
  void initState() {
    controller = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 4000));

    rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));

 @override
  Widget build(BuildContext context) {
    // Play / Reproducción
    controller.forward();

    return AnimatedBuilder(
      animation: controller,
      child: _Rectangulo(),
</code>```

答:
try this</p>
```<code>     class _CuadradoAnimadoState extends State<CuadradoAnimado>
                with SingleTickerProviderStateMixin {
              AnimationController? controller;
              Animation<double>? rotacion;

            @override
              void initState() {
                controller = new AnimationController(
                    vsync: this, duration: Duration(milliseconds: 4000));

                rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
                    .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));
             controller.forward();
setState((){});
    }
             @override
              Widget build(BuildContext context) {
                // Play / Reproducción

                return controller==null && rotacion==null ? CircularProgressIndicator.adaptive():  AnimatedBuilder(
                  animation: controller!,
                  child: _Rectangulo());
</code>```

Body:
I have an error in the code because of safety in Flutter and I have tried to solve it with the declaration of variables using LATE.<br /

But it appears antother one when I try to build it:

Error

This is my code:

class AnimacionesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CuadradoAnimado(),
      ),
    );
  }
}

class CuadradoAnimado extends StatefulWidget {
  @override
  _CuadradoAnimadoState createState() => _CuadradoAnimadoState();
}

class _CuadradoAnimadoState extends State<CuadradoAnimado>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> rotacion;

@override
  void initState() {
    controller = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 4000));

    rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
        .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));

 @override
  Widget build(BuildContext context) {
    // Play / Reproducción
    controller.forward();

    return AnimatedBuilder(
      animation: controller,
      child: _Rectangulo(),

Body:
try this

     class _CuadradoAnimadoState extends State<CuadradoAnimado>
                with SingleTickerProviderStateMixin {
              AnimationController? controller;
              Animation<double>? rotacion;

            @override
              void initState() {
                controller = new AnimationController(
                    vsync: this, duration: Duration(milliseconds: 4000));

                rotacion = Tween(begin: 0.0, end: 2 * Math.pi)
                    .animate(CurvedAnimation(parent: controller, curve: Curves.easeOut));
             controller.forward();
setState((){});
    }
             @override
              Widget build(BuildContext context) {
                // Play / Reproducción

                return controller==null && rotacion==null ? CircularProgressIndicator.adaptive():  AnimatedBuilder(
                  animation: controller!,
                  child: _Rectangulo());


问:
Get random password in javascript
I'm making a course and one of the tasks is to generate four different passwords that should fill the four different paragraphs

,

,

,

I have created a script that creates a password but somehow it doesn't print the first password. When I do console.log(password) it shows that creates a password on the console. But when I try to put first.textContent = password it shows nothing.

let chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"]
let number = 10
let password = ""
let first = document.getElementById("first")
let second = document.getElementById("second")
let third = document.getElementById("third")
let fourth = document.getElementById("fourth")

function generate() {
  for (let i = 0; i < number; i++) {
    let passwordChar = Math.floor(Math.random() * chars.length)
    password += chars[passwordChar]
    return password
  }
}
first.textContent = password```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <link rel="stylesheet" href="index.css">
</head>

<body>
  <h1>Generate a random password</h1>
  <p id="description">Never use an insecure password again</p>
  <button onclick="generate()">Generate passwords</button>
  <p id="line"></p>
  <p id="first"></p>
  <p id="second"></p>
  <p id="third"></p>
  <p id="fourth"></p>
</body>

</html></code>```

I'm also stuck to generate each time the function is running a new password and put it on the next paragraph. Like so:

```<code>first.textContent = password
second.textContent = password
third.textContent = password
fourth.textContent = password
</code>```

Any help will be appreciated

答:
The main thing going wrong is that first.textContent = password is placed outside of generate(), so it will be set to the initial password value (empty string), but is never updated.

Without changing too much, I suggest splitting the code into two functions. One to generate a password, and one that assigns element contents to these randomly generated passwords.

function generatePassword() {
  const chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"];
  let password = "";
  for (let i = 0; i < 10; i++) {
    const passwordChar = Math.floor(Math.random() * chars.length);
    password += chars[passwordChar];
  }
  // I've moved the return down, because you return after generating only 1 character
  return password;
}

function loadPasswords() {
  document.getElementById("first").textContent = generatePassword();
  document.getElementById("second").textContent = generatePassword();
  document.getElementById("third").textContent = generatePassword();
  document.getElementById("fourth").textContent = generatePassword();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Generate a random password</h1>
<p id="description">Never use an insecure password again</p>
<button onclick="loadPasswords()">Generate passwords</button>
<p id="line"></p>
<p id="first"></p>
<p id="second"></p>
<p id="third"></p>
<p id="fourth"></p></code>```

Like already stated by other answers, I would personally avoid using inline handlers and use addEventListener() instead.

Title: Get random password in javascript

Body:
I'm making a course and one of the tasks is to generate four different passwords that should fill the four different paragraphs

,

,

,

I have created a script that creates a password but somehow it doesn't print the first password. When I do console.log(password) it shows that creates a password on the console. But when I try to put first.textContent = password it shows nothing.

let chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"]
let number = 10
let password = ""
let first = document.getElementById("first")
let second = document.getElementById("second")
let third = document.getElementById("third")
let fourth = document.getElementById("fourth")

function generate() {
  for (let i = 0; i < number; i++) {
    let passwordChar = Math.floor(Math.random() * chars.length)
    password += chars[passwordChar]
    return password
  }
}
first.textContent = password

  <link rel="stylesheet" href="index.css">

Generate a random password

Never use an insecure password again

  <button onclick="generate()">Generate passwords</button>

I'm also stuck to generate each time the function is running a new password and put it on the next paragraph. Like so:

first.textContent = password
second.textContent = password
third.textContent = password
fourth.textContent = password

Any help will be appreciated

Body:
The main thing going wrong is that first.textContent = password is placed outside of generate(), so it will be set to the initial password value (empty string), but is never updated.

Without changing too much, I suggest splitting the code into two functions. One to generate a password, and one that assigns element contents to these randomly generated passwords.

function generatePassword() {
  const chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"];
  let password = "";
  for (let i = 0; i < 10; i++) {
    const passwordChar = Math.floor(Math.random() * chars.length);
    password += chars[passwordChar];
  }
  // I've moved the return down, because you return after generating only 1 character
  return password;
}

function loadPasswords() {
  document.getElementById("first").textContent = generatePassword();
  document.getElementById("second").textContent = generatePassword();
  document.getElementById("third").textContent = generatePassword();
  document.getElementById("fourth").textContent = generatePassword();
}

<h1>Generate a random password</h1>
<p id="description">Never use an insecure password again</p>
<button onclick="loadPasswords()">Generate passwords</button>
<p id="line"></p>
<p id="first"></p>
<p id="second"></p>
<p id="third"></p>
<p id="fourth"></p>

Like already stated by other answers, I would personally avoid using inline handlers and use addEventListener() instead.


问:
How to use Image.file and Image.asset in the same list?
My friends, I am developing a sports app. An application where you can set up your own football team. When you click on the boxes, it lists the players and when you click on the player you choose, it comes into the container.
I have done this with Image.asset and I am displaying the players with GridView.

Now, what I want is for people using the application to choose a photo from their phone and be included in that list. However, when I do it with Image.file, it does not appear in the list. What path should I follow?

答:
try Use this package called Path Provider from https://pub.dev..

https://pub.dev/packages/path_provider

it will give you access and you have various location to put your assets accordingly... Try this it will let you help out from your issue


问:
C Pass By Reference Misconception
Specifics matter. Especially when talking about how something works, and even more so when we consider why something works. Currently, as I understand it, EVERYTHING in C is passed by value. NOTHING is passed by reference. Some programmers mention that arrays in C are passed by reference.
But as per my limited understanding,

Even if we pass an array to a function like this void traverse(int arr[4]);, it is actually being taken in as a copy of the pointer variable storing the location in memory of the first element in that array. It is then dereferenced inside the function, but the initial value being passed is actually a local variable. Since memory allocated to arrays in the program stack would be contiguous, the compiler is able to make square bracket notation work as well as pointer arithmetic.

This and passing by reference are not the same thing to me. I would think this is an important distinction.

But on the other hand, we can then just say that everything in computing is passed by value, since something like Java would do the same in a more subtle manner. And it is actually just simulating a pass by reference. Please advise.

答:
At the level of bits in the computer, arguments can only be passed by value. Bits representing some argument are written to a processor register or memory location designated as the place to pass an argument. Passing by reference is a construct built upon passing by value by using an address as the value that is passed. Passing an address can be implemented automatically or manually. Both methods are pass-by-reference.

When we pass some entity by passing its address instead of passing its value directly, that is called pass by reference. This terminology long antedates the creation of “references” in C++. In assembly language, when we load the address of some thing into a register to pass it to a function, that was, and is, called pass by reference. The C standard specifies a pointer provides a reference to an entity (C 2018 6.2.5 20). So, when we have a pointer to an object, we have a reference to an object, and when we pass the pointer to a function, we are passing a reference to the object to the function.

Some languages automated pass-by-reference. FORTRAN passes everything by reference except for some special syntax for calling routines outside FORTRAN. However, whether passing-by-reference is implemented as an automatic feature of the programming language, by a programmer manually loading an address in assembly language, or by a programmer manually requesting an address with a language operator such as C’s &, when a reference to an object is passed, then the object is passed by reference.

C++ created a new type that it called a “reference,” but this was a new use of the word. The C++ meaning of “reference” applies to C++ only. It does not change the existing use of that word outside the context of C++. Outside of C++, “reference” has its ordinary English meaning of providing information on another thing.

Regarding your specific question about passing an array in C,
in C, an array argument is automatically converted to the address of its first element, and this address is typically used to access the entire array. So the array is in fact passed by reference. Describing this as an automatic conversion to a pointer is merely documenting the details. The effect is the same: The function is given access to the object the caller designated by providing a reference to it.

Further, any dispute over the meaning of “pass by reference” is merely one about terminology, not about the actual mechanisms used in the computer.

Title: C Pass By Reference Misconception


问:
Split Connection String
In a WinForm Application I Store My ConnectionString in App.Confing File.How Can I split this connectionstring to some Data like username,DataBaseName,Password and other thing Dynamically?</p>

答:
This topic from msdn library might be help you :-

http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx

Title: Split Connection String


问:
Pass template function to std::bind?
I want to use std::bind with template function. Is it somehow possible?

P.S. It is IMPORTANT to use std::bind, because I know at least one solution through lambdas and want to find out if there is std::bind solution.

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo : std::enable_shared_from_this<foo>
{
    void f()
    {
        // doesn't compile, error : no matching function for call to 'bind'
        auto cb = std::bind(&foo::handle, shared_from_this(), placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}
```

答:
handle is not a template function. There are no "template functions". handle is a function template, ie it is a template, it is not a function. You cannot std::bind to a template. You can only std::bind to a callable.

The trick is to defer instantiation of the template and deduction of the template parameters to when the function is actually called:

```<code>#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo {

    struct handle_caller {
        template <typename T,typename U>
        void operator()(foo* f, T t,U u){
            f->handle(t,u);
        }
    };

    void f()
    {
        auto cb = std::bind(handle_caller{},this, placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}
</code>```

The callable passed to bind is an object of a concrete type handle_caller. It is not a template. Only when cb is called the parameters are forwarded to handle_caller::operator() where the template arguments can be deduced.

Lambdas can do this out-of-the box, because a lambda with auto arguments is of a concrete type and only its operator() is a template:

```<code>#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo {
    void f()
    {
        auto cb = std::bind([](auto f,auto t,auto u){ f->handle(t,u);},this, placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}
</code>```

However, once you use the lambda there is no need for std::bind anymore, because you can bind the parameters via a lambda capture. std::bind is the ancient way to bind parameters, it is convoluted and has clunky syntax. I have read of cases that can be done with std::bind but not with a lambda, but I have never encountered one.

PS: Note that I removed the shared_from_this stuff from your code, because I know it can be used wrong easily, but I am not sure how to use it correctly. As cb is only local to foo::f there is no need to worry about the lifetime of this in the example code.

Title: Pass template function to std::bind?

Body:
handle is not a template function. There are no "template functions". handle is a function template, ie it is a template, it is not a function. You cannot std::bind to a template. You can only std::bind to a callable.

The trick is to defer instantiation of the template and deduction of the template parameters to when the function is actually called:

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo {

    struct handle_caller {
        template <typename T,typename U>
        void operator()(foo* f, T t,U u){
            f->handle(t,u);
        }
    };

    void f()
    {
        auto cb = std::bind(handle_caller{},this, placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}

The callable passed to bind is an object of a concrete type handle_caller. It is not a template. Only when cb is called the parameters are forwarded to handle_caller::operator() where the template arguments can be deduced.

Lambdas can do this out-of-the box, because a lambda with auto arguments is of a concrete type and only its operator() is a template:

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo {
    void f()
    {
        auto cb = std::bind([](auto f,auto t,auto u){ f->handle(t,u);},this, placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}

However, once you use the lambda there is no need for std::bind anymore, because you can bind the parameters via a lambda capture. std::bind is the ancient way to bind parameters, it is convoluted and has clunky syntax. I have read of cases that can be done with std::bind but not with a lambda, but I have never encountered one.

PS: Note that I removed the shared_from_this stuff from your code, because I know it can be used wrong easily, but I am not sure how to use it correctly. As cb is only local to foo::f there is no need to worry about the lifetime of this in the example code.


问:
Fast Algorithm for partial sums on a list
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

```<code>def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result
</code>```

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

答:
You don't have to compute the sum of a slice at each step, all you have to do is subtract one number from the previous sum.

Here's a pretty naive but straight forward solution, subject to further optimizations.

```<code>def part_sums(ls):
    result = [sum(ls)]
    for x in ls:
        result.append(result[-1] - x)
    return result
</code>```

Body:
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

Body:
You don't have to compute the sum of a slice at each step, all you have to do is subtract one number from the previous sum.

Here's a pretty naive but straight forward solution, subject to further optimizations.

def part_sums(ls):
    result = [sum(ls)]
    for x in ls:
        result.append(result[-1] - x)
    return result


问:
I cound'nt find buildscript in build.gradle(Project)
This is build.gradle(Project) what i knew.

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
</code>```

But my Project's build.gradle(Project) is that.

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I tried to link Firebase with Android, but build.gradle(Project) was different from the file I knew.

I tried to modify it by force, but it didn't sync...

How can I access the Top-Level Gradle file??

答:
For Android Studio Bumblebee they are changed build.gradle structure.

You can add your buildscript above plugins

```<code>buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
    // Add More
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}
</code>```

Body:
This is build.gradle(Project) what i knew.

buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

But my Project's build.gradle(Project) is that.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I tried to link Firebase with Android, but build.gradle(Project) was different from the file I knew.

I tried to modify it by force, but it didn't sync...

How can I access the Top-Level Gradle file??

Body:
For Android Studio Bumblebee they are changed build.gradle structure.

You can add your buildscript above plugins

buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
    // Add More
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}


问:
Flutter - Token error on publishing package update
I'm trying to update my package on pub.dev, I suddenly start getting this message which i didnt get before

```<code>https://pub.flutter-io.cn package repository requested authentication! You can provide credential using:
    pub token add https://pub.flutter-io.cn
</code>```

I tried running :

```<code>dart pub token add https://pub.flutter-io.cn
</code>```

which will be successful. But if i try running the publish command again

```<code>dart pub publish
</code>```

I get :

```<code>Invalid token for https://pub.flutter-io.cn deleted.
https://pub.flutter-io.cn package repository requested authentication! You can provide credential using:
    pub token add https://pub.flutter-io.cn
</code>```

I'm actually stuck here.

NB: My package repo is public and I've also added it(as token) but didn't work. What am I missing?

答:
that because of https://pub.flutter-io.cn,
so upload to https://pub.dartlang.org

```<code> dart pub publish --server=https://pub.dartlang.org
</code>```

https://pub.flutter-io.cn  URI, I think for china so check your pc where from coming.

see this answer

Body:
I'm trying to update my package on pub.dev, I suddenly start getting this message which i didnt get before

https://pub.flutter-io.cn package repository requested authentication! You can provide credential using:
    pub token add https://pub.flutter-io.cn

I tried running :

dart pub token add https://pub.flutter-io.cn

which will be successful. But if i try running the publish command again

dart pub publish

I get :

Invalid token for https://pub.flutter-io.cn deleted.
https://pub.flutter-io.cn package repository requested authentication! You can provide credential using:
    pub token add https://pub.flutter-io.cn

I'm actually stuck here.

NB: My package repo is public and I've also added it(as token) but didn't work. What am I missing?

Body:
that because of https://pub.flutter-io.cn,
so upload to https://pub.dartlang.org

 dart pub publish --server=https://pub.dartlang.org

https://pub.flutter-io.cn  URI, I think for china so check your pc where from coming.

see this answer


问:
Ignore properties in data model while keeping them in EF Core migrations
I am creating a greenfield application that uses EF Core which must talk to a legacy database. I want EF to ignore some of the columns in the database because they will eventually be deprecated and I don't want them in the new entity model. I can't remove them yet as the legacy system still relies on them.

For an unwanted database column called DeprecatedFeature, I want to do something like:

```<code>modelBuilder.Entity<MyEntity>(entity => {
   entity.HasKey(t => t.Id);
   entity.ToTable("MyEntity");
   entity.ColumnIgnore("DeprecatedFeature"); // <-- this is what I want to do
})
</code>```

Right now, the best I can do is include the property and mark it as obsolete:

```<code>public class MyEntity
{
    public int Id { get; set; }

    [Obsolete("Deprecated in latest version")]
    public string DeprecatedFeature { get; set; }
}
</code>```

But that means I can't turn on "warnings as errors". I still need to run migrations on my database.

Similar questions: EF 4.x, EF Core skip column on load, Using EF Designer/EDMX and duplicate

Edit

I can see by the answers that there is some confusion about my question:

NotMapped is NOT the answer

NotMapped is used when you have a property in your model that you don't want in the database. My problem is the other way around. I have a column in my database that I don't want in my model.

答:
I have similar requirement, where I need the property in code but db populates the field. I used the following attribute under
System.ComponentModel.DataAnnotations.Schema namespace

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
</code>```

This way, the property is mapped but is not populated when using entityframework.

Body:
I am creating a greenfield application that uses EF Core which must talk to a legacy database. I want EF to ignore some of the columns in the database because they will eventually be deprecated and I don't want them in the new entity model. I can't remove them yet as the legacy system still relies on them.

For an unwanted database column called DeprecatedFeature, I want to do something like:

modelBuilder.Entity<MyEntity>(entity => {
   entity.HasKey(t => t.Id);
   entity.ToTable("MyEntity");
   entity.ColumnIgnore("DeprecatedFeature"); // <-- this is what I want to do
})

Right now, the best I can do is include the property and mark it as obsolete:

public class MyEntity
{
    public int Id { get; set; }

    [Obsolete("Deprecated in latest version")]
    public string DeprecatedFeature { get; set; }
}

But that means I can't turn on "warnings as errors". I still need to run migrations on my database.

Similar questions: EF 4.x, EF Core skip column on load, Using EF Designer/EDMX and duplicate

Edit

I can see by the answers that there is some confusion about my question:

NotMapped is NOT the answer

NotMapped is used when you have a property in your model that you don't want in the database. My problem is the other way around. I have a column in my database that I don't want in my model.

Body:
I have similar requirement, where I need the property in code but db populates the field. I used the following attribute under
System.ComponentModel.DataAnnotations.Schema namespace

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

This way, the property is mapped but is not populated when using entityframework.


问:
Redux toolkit filter() not working when wanting to display new array at the same time
I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.

so I've made a Slice for cart in redux. the 'addProduct' part works fine, but the 'deleteProduct' reducer which uses filter() doesn't work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)

my slice:

```<code>const selectedProductsSlice = createSlice({
    name:'selectedProducts',
    initialState:{
        productList:[],
        checkoutPrice:0,
    },
    reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
}});
</code>```

my button and handleDelete:

```<code><button className="btn-delete" onClick={handleDelete(product)}>Delete</button>

  function handleDelete(p) {
    console.log(p)
    dispatch(deleteProduct(p.product))
  }

</code>```

edit:
filter didnt work in every possible way i tried. so i changed my way and did this instead to work. but still i wonder why didnt filter() method work properly.

```<code>        deleteProduct: (state, { payload }) => {
            const foundIndex = state.productList.findIndex((p) => {
                return p.product.id === payload.id
            })
            state.productList.splice(foundIndex,1)

        }
</code>```

答:
Filter methods returns new array so you have to update your existing array tool. Please update your slice:</p>
```<code>const selectedProductsSlice = createSlice({
        name:'selectedProducts',
        initialState:{
        productList:[],
        checkoutPrice:0,
        },
        reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList=state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
    }});
</code>```

Body:
I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.

so I've made a Slice for cart in redux. the 'addProduct' part works fine, but the 'deleteProduct' reducer which uses filter() doesn't work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)

my slice:

const selectedProductsSlice = createSlice({
    name:'selectedProducts',
    initialState:{
        productList:[],
        checkoutPrice:0,
    },
    reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
}});

my button and handleDelete:

<button className="btn-delete" onClick={handleDelete(product)}>Delete</button>

  function handleDelete(p) {
    console.log(p)
    dispatch(deleteProduct(p.product))
  }

edit:
filter didnt work in every possible way i tried. so i changed my way and did this instead to work. but still i wonder why didnt filter() method work properly.

        deleteProduct: (state, { payload }) => {
            const foundIndex = state.productList.findIndex((p) => {
                return p.product.id === payload.id
            })
            state.productList.splice(foundIndex,1)

        }

Body:
Filter methods returns new array so you have to update your existing array tool. Please update your slice:

const selectedProductsSlice = createSlice({
        name:'selectedProducts',
        initialState:{
        productList:[],
        checkoutPrice:0,
        },
        reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList=state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
    }});


问:
Difference between EventHandler<T> and Progress<T>?
I would like to know the difference between using EventHandler<T> and Progress<T>. Are there any situations in which one is a better choice?

When dealing with async Tasks I often see an EventHandler<T> progressChangedCallback that people use to subscribe to a ProgressChanged event of an object and report progress change to e.g. a progress bar on the UI. I also see people passing IProgress<T> instances to the Tasks as parameters. The difference is that they don't invoke an event, they call the IProgress<T>.Report() method instead.

答:
They're different mechanisms. An event is defined on a class, and a IProgress<T> is passed to the async operation itself. An event might make more sense when only 1 async operation is happening at a time, and the progress of every such operation needs to be displayed in the same way, as the UI needs to subscribe to a single event once, and all progress updates from it are handled the same way. An IProgress<T> might make more sense when you can have multiple async operations on the go at once, as it lets you understand which progress is being reported by which operation.

Note that the Progress<T> does the nice thing of dispatching progress updates back to the UI thread (if used in the right way), but events don't do this.


问:
How to transfer eth from an account to a contract?
I'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.

```<code>    function addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {
    if(!members[msg.sender].alreadyExist) {
        Member memory newMember = Member(msg.sender, true);
        members[msg.sender] = newMember;
        bool sent = payable(address(this)).send(_stakeAmount);
        require(sent, "invalid balance");
        return true;
    } else {
        return false;
    }
}
</code>```

How could I transfer eth from my account to the smart contract?

答:
A smart contract is not able to pull a contract-specified amount of ETH from an address. The amount needs to always be specified and signed by the sender.

The contract can only validate the sent amount:

```<code>function addStaker() public payable {
    require(msg.value == 1 ether);
}
</code>```

How to chose the amount depends on the wallet software you're using. In case of Remix, there's the "Value" input in the "Deploy & Run Transactions" tab, where you specify the amount of ETH sent with the transaction.

Body:
I'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.

    function addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {
    if(!members[msg.sender].alreadyExist) {
        Member memory newMember = Member(msg.sender, true);
        members[msg.sender] = newMember;
        bool sent = payable(address(this)).send(_stakeAmount);
        require(sent, "invalid balance");
        return true;
    } else {
        return false;
    }
}

How could I transfer eth from my account to the smart contract?

Body:
A smart contract is not able to pull a contract-specified amount of ETH from an address. The amount needs to always be specified and signed by the sender.

The contract can only validate the sent amount:

function addStaker() public payable {
    require(msg.value == 1 ether);
}

How to chose the amount depends on the wallet software you're using. In case of Remix, there's the "Value" input in the "Deploy & Run Transactions" tab, where you specify the amount of ETH sent with the transaction.


问:
How to merge two publishers with Combine?
I have an token publisher. It returns a token value as string. I want to make a request using this token in request publisher. I have no idea how to do it. Maybe these codes will help.

Token Transactions:

```<code>// Token Publisher
func getAccessToken() -> AnyPublisher<String, Error> {
    let url = "it doesn't matter"
    var urlRequest = URLRequest(url: url)
    // some url request setups
    // ...
    return URLSession.shared
        .dataTaskPublisher(for: urlRequest)
        .map(\.data)
        .decode(type: AccessToken.self, decoder: JSONDecoder())
        .map({ $0.token ?? "" })
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
}
</code>```

Generic Request Transactions:

```<code>// Request Publisher (The T is decodable generic type.)
func request<T: Decodable>(ofType: T.Type, apiURL: APIURL, method: HTTPMethods) -> AnyPublisher<T, Error> {
    // This flatMap is not invoked. :/
    AuthManager.shared.getAccessToken()
        .flatMap({ accessToken -> AnyPublisher<T, Error> in
            guard let url = URL(string: apiURL.url) else {
                return Fail(error: NSError(domain: "Missing API URL", code: -10001, userInfo: nil)).eraseToAnyPublisher()
            }
            var urlRequest = URLRequest(url: url)
            urlRequest.httpMethod = method.rawValue
            urlRequest.setValue("Authorization", forHTTPHeaderField: "Bearer " + accessToken)
            return URLSession.shared
                .dataTaskPublisher(for: urlRequest)
                .map(\.data)
                .decode(type: T.self, decoder: JSONDecoder())
                .eraseToAnyPublisher()
        }).eraseToAnyPublisher()
}
</code>```

Example Request Transactions:

```<code>// Example Request
private var cancellables = Set<AnyCancellable>()

func getExampleRequest(id: String) {
    let url = "it doesn't matter"
    APIManager.shared.request(ofType: ExampleModel.self, apiURL: url, method: .get).sink { completion in
        switch completion {
        case .finished:
            break
        case .failure(let error):
            print(error)
        }
    } receiveValue: { exampleModelData in
        // print(exampleModelData)
    }.store(in: &cancellables)
}
</code>```

Thanks in advance.

答:
What you have here is a runtime problem that isn't reproducible given the code you presented. I can't give you an answer but I can help you find the problem.

The .print() operator is your friend. put it just before the flatMap and you should see that you aren't getting a next event, but you will likely see that you are getting a canceled or finished event.

If you are getting a finished event, move the print operator up the publisher chain until you figure out where the problem is. If you are getting a cancelled event, check to see why your cancellable is being deinted before completion.

Body:
I have an token publisher. It returns a token value as string. I want to make a request using this token in request publisher. I have no idea how to do it. Maybe these codes will help.

Token Transactions:

// Token Publisher
func getAccessToken() -> AnyPublisher<String, Error> {
    let url = "it doesn't matter"
    var urlRequest = URLRequest(url: url)
    // some url request setups
    // ...
    return URLSession.shared
        .dataTaskPublisher(for: urlRequest)
        .map(\.data)
        .decode(type: AccessToken.self, decoder: JSONDecoder())
        .map({ $0.token ?? "" })
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
}

Generic Request Transactions:

// Request Publisher (The T is decodable generic type.)
func request<T: Decodable>(ofType: T.Type, apiURL: APIURL, method: HTTPMethods) -> AnyPublisher<T, Error> {
    // This flatMap is not invoked. :/
    AuthManager.shared.getAccessToken()
        .flatMap({ accessToken -> AnyPublisher<T, Error> in
            guard let url = URL(string: apiURL.url) else {
                return Fail(error: NSError(domain: "Missing API URL", code: -10001, userInfo: nil)).eraseToAnyPublisher()
            }
            var urlRequest = URLRequest(url: url)
            urlRequest.httpMethod = method.rawValue
            urlRequest.setValue("Authorization", forHTTPHeaderField: "Bearer " + accessToken)
            return URLSession.shared
                .dataTaskPublisher(for: urlRequest)
                .map(\.data)
                .decode(type: T.self, decoder: JSONDecoder())
                .eraseToAnyPublisher()
        }).eraseToAnyPublisher()
}

Example Request Transactions:

// Example Request
private var cancellables = Set<AnyCancellable>()

func getExampleRequest(id: String) {
    let url = "it doesn't matter"
    APIManager.shared.request(ofType: ExampleModel.self, apiURL: url, method: .get).sink { completion in
        switch completion {
        case .finished:
            break
        case .failure(let error):
            print(error)
        }
    } receiveValue: { exampleModelData in
        // print(exampleModelData)
    }.store(in: &cancellables)
}

Thanks in advance.


问:
Angular Block Register Page
I was Wonderring is there a way to make register url not working when user is logged in. I am use Frontend Angular And Backend Django</p>

答:
If you use Token/JWT use Angular guard.

```<code>@Injectable({
  providedIn: 'root',
})
export class LoginGuard implements CanActivate {

  constructor(
    private router: Router,
    private auth: AuthService
  ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {

    if (this.service.isLoggedIn) {
      return this.router.navigate(['/login']);
    }
    return true;
  }

}
</code>```

And in routes

```<code>  {
    path: 'login',
    component: LoginComponent,
    canActivate: [LoginGuard],
  },
</code>```

isLoggedIn in AuthService only checks if auth token exists.

Title: Angular Block Register Page

Body:
If you use Token/JWT use Angular guard.

@Injectable({
  providedIn: 'root',
})
export class LoginGuard implements CanActivate {

  constructor(
    private router: Router,
    private auth: AuthService
  ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {

    if (this.service.isLoggedIn) {
      return this.router.navigate(['/login']);
    }
    return true;
  }

}

And in routes

  {
    path: 'login',
    component: LoginComponent,
    canActivate: [LoginGuard],
  },

isLoggedIn in AuthService only checks if auth token exists.


问:
subtract inside DataFrame columns
Would because maybe I did'n sleep this night but, given:

```<code>df1 = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], index=['rank1','rank2','rank3','rank4']}
df2 = {'Age':[28,34,29,42],'bubu':[98,33,3,30], index=['rank1','rank2','rank3','rank4']}
df_merged = = pd.concat([ df1, df2 ], axis = 1)
</code>```

now, for dynamically manage further arithmetic operation on the columns from a more column dense df:

```<code>a = ['Age']  #List
b = ['bubu'] #List
</code>```

the arithmetic operation:

```<code>df_merged['newCol'] = df_merged[a]-df_merged[b]
</code>```

or both

```<code>df_merged.assign(newCol = df_merged[a] - df_merged[b])
</code>```

I can't subtract the 2 columns because return such error

```<code>ValueError: Expected a 1D array, got an array with shape (556, 2)
</code>```

答:
Not sure if I understand, but try this:

```<code>a = 'Age'
b = 'bubu'
</code>```

then

```<code>df_merged['newCol'] = df_merged[a] - df_merged[b]
</code>```

produces:

```<code>        Name  Age  bubu  newCol
rank1    Tom   28    98     -70
rank2   Jack   34    33       1
rank3  Steve   29     3      26
rank4  Ricky   42    30      12
</code>```

is that what you were after?

Title: subtract inside DataFrame columns

Body:
Would because maybe I did'n sleep this night but, given:

df1 = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], index=['rank1','rank2','rank3','rank4']}
df2 = {'Age':[28,34,29,42],'bubu':[98,33,3,30], index=['rank1','rank2','rank3','rank4']}
df_merged = = pd.concat([ df1, df2 ], axis = 1)

now, for dynamically manage further arithmetic operation on the columns from a more column dense df:

a = ['Age']  #List
b = ['bubu'] #List

the arithmetic operation:

df_merged['newCol'] = df_merged[a]-df_merged[b]

or both

df_merged.assign(newCol = df_merged[a] - df_merged[b])

I can't subtract the 2 columns because return such error

ValueError: Expected a 1D array, got an array with shape (556, 2)

Body:
Not sure if I understand, but try this:

a = 'Age'
b = 'bubu'

then

df_merged['newCol'] = df_merged[a] - df_merged[b]

produces:

        Name  Age  bubu  newCol
rank1    Tom   28    98     -70
rank2   Jack   34    33       1
rank3  Steve   29     3      26
rank4  Ricky   42    30      12

is that what you were after?


问:
How to replace of a specific line number
I'm trying to replace line number 11 in a txt file using PowerShell.

Firstly I tried replacing a specific word, but it changed too much:

```<code>$output= (Resolve-DnsName -name name1).IPAddress

(Get-Content "C:\test\test.txt") -replace "IPADDRESS=","IPADDRESS=$output"  | Set-Content C:\test\test.txt
</code>```

答:
```<code>$content = Get-Content "$file"
$content[$line - 1] = ($content[$line - 1] -replace "IPADDRESS=","IPADDRESS=$output")
Set-Content "$file" $content
</code>```

This one worked for me.

Body:
I'm trying to replace line number 11 in a txt file using PowerShell.

Firstly I tried replacing a specific word, but it changed too much:

$output= (Resolve-DnsName -name name1).IPAddress

(Get-Content "C:\test\test.txt") -replace "IPADDRESS=","IPADDRESS=$output"  | Set-Content C:\test\test.txt

Body:
$content = Get-Content "$file"
$content[$line - 1] = ($content[$line - 1] -replace "IPADDRESS=","IPADDRESS=$output")
Set-Content "$file" $content

This one worked for me.


问:
Typing: Inferred type too general during class inheritance
I'm facing the following problem. Suppose I want to define generic class for Dataset and its Samples. Then, I want to create specific subclasses of these that will in the end be instantiated (E.g. DatasetOfSpecificSamples that contains MoreSpecificSample samples). To save some LoC, I want to implement common functionality in Dataset class.

Yet, I can't get the typehints in the inherited sublcasses right. They are too general. See the following example, where I would expect that __iter__ return type of DatasetOfSpecificSamples would be MoreSpecificSample, yet MyPy infers just Sample.

Is there a way to enforce more specific hint without redifining the method itself?

from typing import Mapping, Iterator

class Sample:
    pass

class MoreSpecificSample(Sample):
    pass

class Dataset:
    def __init__(self, samples: Mapping[str, Sample]):
        self.samples = samples

    def __iter__(self) -> Iterator[Sample]:
        yield from self.samples.values()

class DatasetOfSpecificSamples(Dataset):
    samples: Mapping[str, MoreSpecificSample]

    # def __iter__(self) -> Iterator[CommonCriteriaCert]: <-- This fixes the problem, as it specifies the type
    #     yield from self.certs.values()

dset = DatasetOfSpecificSamples()
for sample in dset: # <-- the inferred type of "sample" is Sample, not MoreSpecificSample
    pass
```

答:
Make Dataset class Generic:

```<code>T = TypeVar("T")

class Dataset(Generic[T]):

    def __init__(self, samples: Mapping[str, T]):
        self.samples = samples

    def __iter__(self) -> Iterator[T]:
        yield from self.samples.values()

class DatasetOfSpecificSamples(Dataset[MoreSpecificSample]):
    samples: Mapping[str, MoreSpecificSample]
</code>```

Body:
Make Dataset class Generic:

T = TypeVar("T")

class Dataset(Generic[T]):

    def __init__(self, samples: Mapping[str, T]):
        self.samples = samples

    def __iter__(self) -> Iterator[T]:
        yield from self.samples.values()

class DatasetOfSpecificSamples(Dataset[MoreSpecificSample]):
    samples: Mapping[str, MoreSpecificSample]


问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
For 2 dimenional Arrays:

```<code>for(var i = 0; i < parentArray.length; i++){
    for(var j = 0; j < parentArray[i].length; j++){

        console.log(parentArray[i][j]);
    }
}
</code>```

For arrays with an unknown number of dimensions you have to use recursion:

```<code>function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        if(arr[i] instanceof Array){
            printArray(arr[i]);
        }else{
            console.log(arr[i]);
        }
    }
}
</code>```

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
For 2 dimenional Arrays:

for(var i = 0; i < parentArray.length; i++){
    for(var j = 0; j < parentArray[i].length; j++){

        console.log(parentArray[i][j]);
    }
}

For arrays with an unknown number of dimensions you have to use recursion:

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        if(arr[i] instanceof Array){
            printArray(arr[i]);
        }else{
            console.log(arr[i]);
        }
    }
}


问:
Flutter Error on Real iOS Device: "module 'fluttertoast' not found"
My flutter app is working properly in iOS Simulator.

I have added fluttertoast by:

Adding it on pubspec.yaml

dependencies:
flutter:
sdk: flutter

cupertino_icons: ^0.1.3

fluttertoast: ^7.0.1

Importing in my dart file

import 'package:fluttertoast/fluttertoast.dart';

So far it works as intended. BUT, when I move to a REAL iOS device, my iPhone XS, It won't compile.
I get this error:

fatal error: module 'fluttertoast' not found
@import fluttertoast;

What am I missing?

答:
I have face this issue very recently and the way I fix is like this. I change the pod file min deployment to 11 as needed by some of the pacakges I  was using like flutter stripe. but the issue was that in Xcode the deployment was set to 9.0(not changing to 11.0). which was causing the issue to fix the issue follow the step.

1 : delete to /iOS/podfile.lock (if any)

2 : go to /iOS/podfile (platform :ios, '9.0') replace the 9.0 with version required for your packages/app.

3 : in terminal cd ios (pod install)

4 : edit the deployment info version here as well in Xcode

5 : run the app it will work if building archive build archive it will not throw the error.


问:
Add rows from another df based on keys pandas
EDITED*
I have a large df with many rows that share the same value in some of the columns.
I want to do the following:

new df = identify the rows in df that have a value in a certain column (not empty).

'''

```<code>df = pd.DataFrame({"a": [1, 2,2,2, 3, 4],
                   "b":['A','B','B', 'B','C','D'],
                   "c":[NaN, 2,NaN,NaN,NaN,NaN]})
</code>```

'''

```<code>df1=df[~df['c'].isnull()]
</code>```

'''

add to 'new_df' the rows from df that share 2 keys.

I tried to use merge:

```<code>df2 = pd.merge(df1,df,on=['a','b'], how='left')
</code>```

But the result was that It added the same row a few times and not the unique rows

```<code>    a   b   c_x c_y
0   2   B   2.0 2.0
1   2   B   2.0 NaN
2   2   B   2.0 NaN
</code>```

I want to keep only one 'c' column with all the values. Not sure what approach to use.

Hope I made it clear...
Thanks!

答:
As far as I understand, you would like to group by 'a' and 'b' and return only those groups where at least one row does not have a NaN in column 'c'. If that's the case. here you go

Load the df:

```<code>df = pd.DataFrame({"a": [1,1,1, 2,2,2, 3, 4], "b":['A','A','A','B','B', 'B','C','D'], "c":[None, None,None,2,None,None,None,None]})
</code>```

filter for any non-NaNs:

```<code>df.groupby(['a','b']).filter(lambda g: any(~g['c'].isna()))
</code>```

output:

```<code>
    a   b   c
3   2   B   2.0
4   2   B   NaN
5   2   B   NaN
</code>```

Body:
EDITED*
I have a large df with many rows that share the same value in some of the columns.
I want to do the following:

new df = identify the rows in df that have a value in a certain column (not empty).

'''

df = pd.DataFrame({"a": [1, 2,2,2, 3, 4],
                   "b":['A','B','B', 'B','C','D'],
                   "c":[NaN, 2,NaN,NaN,NaN,NaN]})

'''

df1=df[~df['c'].isnull()]

'''

add to 'new_df' the rows from df that share 2 keys.

I tried to use merge:

df2 = pd.merge(df1,df,on=['a','b'], how='left')

But the result was that It added the same row a few times and not the unique rows

    a   b   c_x c_y
0   2   B   2.0 2.0
1   2   B   2.0 NaN
2   2   B   2.0 NaN

I want to keep only one 'c' column with all the values. Not sure what approach to use.

Hope I made it clear...
Thanks!

Body:
As far as I understand, you would like to group by 'a' and 'b' and return only those groups where at least one row does not have a NaN in column 'c'. If that's the case. here you go

Load the df:

df = pd.DataFrame({"a": [1,1,1, 2,2,2, 3, 4], "b":['A','A','A','B','B', 'B','C','D'], "c":[None, None,None,2,None,None,None,None]})

filter for any non-NaNs:

df.groupby(['a','b']).filter(lambda g: any(~g['c'].isna()))

output:

    a   b   c
3   2   B   2.0
4   2   B   NaN
5   2   B   NaN


问:
mongodb how to convert _id to String in JAVA
I am reading mongo collection from java code. When I am trying to read the _id value, I am getting the following:

```<code>{"$oid":"541333629520f6e05b0cb410"}
</code>```

I am reading like: jsonObject.get("_id") from java code. I was expecting something like: "_id" : "541333629520f6e05b0cb410"

Here I am looking for a way so that I can get the _id as a string in one operation.

So far I have been trying the following:

```<code>        JSONObject idObj = (JSONObject)JSONObj.get("_id");
        ObjectId objectId = (ObjectId) idObj.get("$oid");
</code>```

答:
```<code>BsonObjectId bid = (BsonObjectId) result.get("_id");
String str = bId.getValue.toString();
</code>```

Body:
I am reading mongo collection from java code. When I am trying to read the _id value, I am getting the following:

{"$oid":"541333629520f6e05b0cb410"}

I am reading like: jsonObject.get("_id") from java code. I was expecting something like: "_id" : "541333629520f6e05b0cb410"

Here I am looking for a way so that I can get the _id as a string in one operation.

So far I have been trying the following:

        JSONObject idObj = (JSONObject)JSONObj.get("_id");
        ObjectId objectId = (ObjectId) idObj.get("$oid");