问:
Array slice ($data,1,2) what equivalence for my case?
Code:

```<code>$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));

Output:
Array
(
[0] => strawberry
[1] => mango
)
</code>```

in my case :

```<code>$data = array("vanilla", "strawberry", "mango", "peaches");
$sub_set_data = array( "strawberry", "mango");
</code>```

the Output will be the remain array:
     array("vanilla", "peaches");

EDIT:

NOT array diff it look like the minus operator 7-3 = 4 or $C = $A-$B

python concept:

```<code>>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>
</code>```

How Can I do for this case?

答:
Looks like you need array_diff

```<code><?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>
</code>```

Result:

```<code>Array
(
    [1] => blue
)
</code>```

http://www.php.net/manual/en/function.array-diff.php

Body:
Code:

$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));

Output:
Array
(
[0] => strawberry
[1] => mango
)

in my case :

$data = array("vanilla", "strawberry", "mango", "peaches");
$sub_set_data = array( "strawberry", "mango");

the Output will be the remain array:
     array("vanilla", "peaches");

EDIT:

NOT array diff it look like the minus operator 7-3 = 4 or $C = $A-$B

python concept:

>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>

How Can I do for this case?

Body:
Looks like you need array_diff

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Result:

Array
(
    [1] => blue
)

http://www.php.net/manual/en/function.array-diff.php


来源: stackexchange

问:
inputAccessoryView is stuck at bottom of screen
I have already looked at this solution.
I have created a sample project showing the bug.

The view has only one UITextField on it.

and here is my code:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var mm: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let x = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40))
        x.backgroundColor = .red
        mm.inputAccessoryView = x
    }
}
</code>```

When I tap on the textfield, here is what happens: --> The red view appears at the bottom and is just stuck there no matter if the keyboard is dismissed or not.
Any help please?

答:
You are just toggling the keyboard you are not actually dismissing the keyboard try to dismiss the keyboard.

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
        view.backgroundColor = .red
        textField.inputAccessoryView = view
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have already looked at this solution.
I have created a sample project showing the bug.

The view has only one UITextField on it.

and here is my code:

class ViewController: UIViewController {

    @IBOutlet weak var mm: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let x = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40))
        x.backgroundColor = .red
        mm.inputAccessoryView = x
    }
}

When I tap on the textfield, here is what happens: --> The red view appears at the bottom and is just stuck there no matter if the keyboard is dismissed or not.
Any help please?

Body:
You are just toggling the keyboard you are not actually dismissing the keyboard try to dismiss the keyboard.

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
        view.backgroundColor = .red
        textField.inputAccessoryView = view
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}


问:
IF NOT EXISTS query used to insert new rows throws error
I'm trying to use this query to insert the value kyckling into column Produkter and Sallader into column typ, but I get an error around IF NOT EXISTS:

```<code>BEGIN
    IF NOT EXISTS (SELECT *
                   FROM innehall
                   WHERE Produkter = 'kyckling'
                     AND typ = 'Sallader')
    BEGIN
        INSERT INTO innehall (Produkter, typ)
        VALUES ('kyckling', 'Sallader')
    END
END;
</code>```

答:
I think the problem is that control-flow logic such as the IF statement (NOT if() the function) is allowed only in programming blocks -- stored procedures, functions, and trigger.

You can do what you want with a query such as:

```<code>INSERT INTO innehall (Produkter, typ)
    SELECT Produkter, typ
    FROM (SELECT 'kyckling' as Produkter, 'Sallader' as typ) x
    WHERE NOT EXISTS (SELECT 1
                      FROM innehall i
                      WHERE i.Produkter = x.Produkter AND i.typ = x.typ
                     );
</code>```

But the better approach is to let the database ensure uniqueness rather than you having to do this.  So:

```<code>alter table innehall add constraint unq_innehall_produkter_typ
    unique (produkter, typ);
</code>```

And then phrase the insert like this:

```<code>insert into innehall (produkter, typ)
    values (kyckling', 'Sallader')
    on duplicate key update typ = values(typ);
</code>```

This attempts the update.  If the unique constraint is violated, then it ignores the error.

Body:
I'm trying to use this query to insert the value kyckling into column Produkter and Sallader into column typ, but I get an error around IF NOT EXISTS:

BEGIN
    IF NOT EXISTS (SELECT *
                   FROM innehall
                   WHERE Produkter = 'kyckling'
                     AND typ = 'Sallader')
    BEGIN
        INSERT INTO innehall (Produkter, typ)
        VALUES ('kyckling', 'Sallader')
    END
END;

Body:
I think the problem is that control-flow logic such as the IF statement (NOT if() the function) is allowed only in programming blocks -- stored procedures, functions, and trigger.

You can do what you want with a query such as:

INSERT INTO innehall (Produkter, typ)
    SELECT Produkter, typ
    FROM (SELECT 'kyckling' as Produkter, 'Sallader' as typ) x
    WHERE NOT EXISTS (SELECT 1
                      FROM innehall i
                      WHERE i.Produkter = x.Produkter AND i.typ = x.typ
                     );

But the better approach is to let the database ensure uniqueness rather than you having to do this.  So:

alter table innehall add constraint unq_innehall_produkter_typ
    unique (produkter, typ);

And then phrase the insert like this:

insert into innehall (produkter, typ)
    values (kyckling', 'Sallader')
    on duplicate key update typ = values(typ);

This attempts the update.  If the unique constraint is violated, then it ignores the error.


问:
OneToMany always is fetched even i use LazyLoad
I have one simple issue and i'm not sure why this does not work, i would like someone to explain me what and why i always get Roles fetched when queering Users.

Basically i created User class and i added LazyLoaded list of Roles, but when i execute query i always get Roles, and that is something that i do not want to do. Can someone explain me why that is happening ?

Basically what i want to achieve is to get Roles when i want, my understanding was, when i in query use LEFT JOIN FETCH with LazyLoad JUST THEN all roles SHOULD be fetched...

Bellow i added all classes and query that is fetching list of roles, even i did not use LEFT JOIN FETCH in query..

I have simple User class that looks like this:

```<code>@Entity
@Table(name = "users")
data class User (
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long?,

        var sponsorId: Long,

        var firstName: String,

        var lastName: String,

        var photo: String,

        @Column(nullable = false, unique = true)
        var username: String,

        @JsonIgnore
        var password: String,

        @JsonIgnore
        var enabled: Boolean
) {
        @OneToMany(mappedBy = "userId", fetch = FetchType.LAZY)
        var roles: Set<UserRole> = emptySet()
}
</code>```

Also i have second simple class:

```<code>@Entity
@Table(name = "user_role")
data class UserRole (
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long?,

        @JsonIgnore
        var userId: Long?,

        @Enumerated(EnumType.STRING)
        var role: Role
)
</code>```

And in my repository i have this Query, as you can see i did not JOIN FETCHED roles, but anyway i get list of users together with list of roles....

```<code>@Repository
interface UserRepository : JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.sponsorId = :sponsorId")
    fun findAllBySponsorId(@Param("sponsorId") sponsorId: Long): Set<User>

}
</code>```

答:
Jackson is probably the culprit here, as it was for me.

You need to make Jackson aware that you're using Hibernate.

Add this to your pom, so it can handle the lazy loading properly:

```<code><dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-hibernate5</artifactId>
</dependency>
</code>```

And create a Bean of it, add it for example to your application class:

```<code>@Bean
public Module hibernate5Module() {
    return new Hibernate5Module();
}
</code>```

Body:
I have one simple issue and i'm not sure why this does not work, i would like someone to explain me what and why i always get Roles fetched when queering Users.

Basically i created User class and i added LazyLoaded list of Roles, but when i execute query i always get Roles, and that is something that i do not want to do. Can someone explain me why that is happening ?

Basically what i want to achieve is to get Roles when i want, my understanding was, when i in query use LEFT JOIN FETCH with LazyLoad JUST THEN all roles SHOULD be fetched...

Bellow i added all classes and query that is fetching list of roles, even i did not use LEFT JOIN FETCH in query..

I have simple User class that looks like this:

@Entity
@Table(name = "users")
data class User (
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long?,

        var sponsorId: Long,

        var firstName: String,

        var lastName: String,

        var photo: String,

        @Column(nullable = false, unique = true)
        var username: String,

        @JsonIgnore
        var password: String,

        @JsonIgnore
        var enabled: Boolean
) {
        @OneToMany(mappedBy = "userId", fetch = FetchType.LAZY)
        var roles: Set<UserRole> = emptySet()
}

Also i have second simple class:

@Entity
@Table(name = "user_role")
data class UserRole (
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long?,

        @JsonIgnore
        var userId: Long?,

        @Enumerated(EnumType.STRING)
        var role: Role
)

And in my repository i have this Query, as you can see i did not JOIN FETCHED roles, but anyway i get list of users together with list of roles....

@Repository
interface UserRepository : JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.sponsorId = :sponsorId")
    fun findAllBySponsorId(@Param("sponsorId") sponsorId: Long): Set<User>

}

Body:
Jackson is probably the culprit here, as it was for me.

You need to make Jackson aware that you're using Hibernate.

Add this to your pom, so it can handle the lazy loading properly:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-hibernate5</artifactId>
</dependency>

And create a Bean of it, add it for example to your application class:

@Bean
public Module hibernate5Module() {
    return new Hibernate5Module();
}


问:
Spring Boot - Rest Controller is returning empty object when using Lombok
I am developing a simple Rest API with Spring Boot 2.1.4 and Gradle 5.0. I am using Lombok v1.18.6 to build my classes but when I call the services I am receiving an empty object

I tried adding the getters and setters methods manually and it fixed the problem but I would like to know why lombok is not working in my project.

Also, my IDE is identifying properly the lombok pluging. I am using IntelliJ IDEA

My gradle dependency:

    compileOnly 'org.projectlombok:lombok:1.18.6'
    annotationProcessor 'org.projectlombok:lombok:1.18.6'
```

<p>My model class:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Data
public class Category implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_category")
    private int idCategory;

    @NotBlank
    private String name;

    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private List<Language> languages;
}
</code>```

My RestController:

@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping
    public ResponseEntity<List<Category>> findAllCategories(){
        List<Category> categories = categoryService.findAll();
        return new ResponseEntity<List<Category>>(categories, HttpStatus.OK);
    }
}
```

<p>I am receiving this response:</p>

```[
    {
        "languages": []
    }
]
```

<p>But what I am expecting to receive is:</p>

```[
    {
        "idCategory": 1,
        "name": "Backend"
        "languages": []
    }
]
```

<p>Actually, I find weird that the only attribute that is being shown is <code>languages</code>, that has the <code>@JsonProperty</code> annotation, why is this happening?</p>

<p><strong>UPDATE</strong></p>

<p>I just realized that my IDE (IntelliJ) is recognizing the lombok pluging and I also have annotation processing enabled but when I try to excecute my code using a getter or an setter, it throws an error:</p>

```Error:(18, 26) java: cannot find symbol
  symbol:   method setName(java.lang.String)
  location: class com.ramonparis.cvmanager.model.Category
```

答: Make sure enable the option annotation processing, re run your project that is all

Body:
I am developing a simple Rest API with Spring Boot 2.1.4 and Gradle 5.0. I am using Lombok v1.18.6 to build my classes but when I call the services I am receiving an empty object

I tried adding the getters and setters methods manually and it fixed the problem but I would like to know why lombok is not working in my project.

Also, my IDE is identifying properly the lombok pluging. I am using IntelliJ IDEA

My gradle dependency:

    compileOnly 'org.projectlombok:lombok:1.18.6'
    annotationProcessor 'org.projectlombok:lombok:1.18.6'

My model class:

@Entity
@Data
public class Category implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_category")
    private int idCategory;

    @NotBlank
    private String name;

    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private List<Language> languages;
}

My RestController:

@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping
    public ResponseEntity<List<Category>> findAllCategories(){
        List<Category> categories = categoryService.findAll();
        return new ResponseEntity<List<Category>>(categories, HttpStatus.OK);
    }
}

I am receiving this response:

[
    {
        "languages": []
    }
]

But what I am expecting to receive is:

[
    {
        "idCategory": 1,
        "name": "Backend"
        "languages": []
    }
]

Actually, I find weird that the only attribute that is being shown is languages, that has the @JsonProperty annotation, why is this happening?

UPDATE

I just realized that my IDE (IntelliJ) is recognizing the lombok pluging and I also have annotation processing enabled but when I try to excecute my code using a getter or an setter, it throws an error:

Error:(18, 26) java: cannot find symbol
  symbol:   method setName(java.lang.String)
  location: class com.ramonparis.cvmanager.model.Category


问:
Using a int value, which is in another class file?
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

```<code>/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}
</code>```

答:
If you really want to access a static variable directly, you could use:

```<code>Gui.gamestate--;
</code>```

However, I'd urge you to keep variables private (other than constants), and access them via properties. Mutable static variables are often a bad idea too.

ContentLicense: CC BY-SA 3.0

Body:
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}

Body:
If you really want to access a static variable directly, you could use:

Gui.gamestate--;

However, I'd urge you to keep variables private (other than constants), and access them via properties. Mutable static variables are often a bad idea too.


答:
```<code>sorted(data, key=lambda x: x[0])
</code>```

Or...

```<code>from operator import itemgetter
sort = sorted(data, key=itemgetter(0))
</code>```

Change the loop to this:

```<code>rotations = []
for seq1 in range(len(list1)):
    table1 = list1[seq1:] + list1[:seq1]
    rotations.append(table1)
rotations = sorted(rotations, key=lambda x: (x[0] not in string.ascii_letters, x[0]))
print([x[-1] for x in rotations])
</code>```

Title: How do I sort by the first element of each line?

Body:
I am attempting to sort the first element of each line alphabetically but struggling to get this to work.

[['^', 'G', 'A', 'T', 'T', 'A', 'C', 'A', '!']]
[['G', 'A', 'T', 'T', 'A', 'C', 'A', '!', '^']]
[['A', 'T', 'T', 'A', 'C', 'A', '!', '^', 'G']]
[['T', 'T', 'A', 'C', 'A', '!', '^', 'G', 'A']]
[['T', 'A', 'C', 'A', '!', '^', 'G', 'A', 'T']]
[['A', 'C', 'A', '!', '^', 'G', 'A', 'T', 'T']]
[['C', 'A', '!', '^', 'G', 'A', 'T', 'T', 'A']]
[['A', '!', '^', 'G', 'A', 'T', 'T', 'A', 'C']]
[['!', '^', 'G', 'A', 'T', 'T', 'A', 'C', 'A']]

Tried the sort and sorted function aswell as pandas but can't seem to make it work

with open ('BWT_test.txt','r') as seq1:
    sequence1 = seq1.read()
    seq1.read()
list1 = list(sequence1)
list1.insert(0,'^')
list1.append('!')
for seq1 in range(len(list1)):
    table1 = [list1[seq1:] + list1[:seq1]]
    sorted(table1)
    print(table1)

The code should organsie the list to this:

[['A', 'C', 'A', '!', '^', 'G', 'A', 'T', 'T']]
[['A', 'T', 'T', 'A', 'C', 'A', '!', '^', 'G']]
[['A', '!', '^', 'G', 'A', 'T', 'T', 'A', 'C']]
[['C', 'A', '!', '^', 'G', 'A', 'T', 'T', 'A']]
[['G', 'A', 'T', 'T', 'A', 'C', 'A', '!', '^']]
[['T', 'A', 'C', 'A', '!', '^', 'G', 'A', 'T']]
[['T', 'T', 'A', 'C', 'A', '!', '^', 'G', 'A']]
[['^', 'G', 'A', 'T', 'T', 'A', 'C', 'A', '!']]
[['!', '^', 'G', 'A', 'T', 'T', 'A', 'C', 'A']]

Body:
sorted(data, key=lambda x: x[0])

Or...

from operator import itemgetter
sort = sorted(data, key=itemgetter(0))

Change the loop to this:

rotations = []
for seq1 in range(len(list1)):
    table1 = list1[seq1:] + list1[:seq1]
    rotations.append(table1)
rotations = sorted(rotations, key=lambda x: (x[0] not in string.ascii_letters, x[0]))
print([x[-1] for x in rotations])


问:
Boost not recognizing itself as a class
boost is giving me the "error C2653 'boost': is not a class or namespace name" im trying to use the last_write_time() function from boost filesystem my usage is boost::filesystem::last_write_time(boost::filesystem::path("C:\file.txt"));
im using namespace std and the command is being ran in the main function
im also getting the error identifier not found but im pretty sure thats from it not detecting the class</p>

```<code>#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <iterator>
#include <algorithm>
#include "pch.h"
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include "Windows.h"
#include "psapi.h"
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <fileapi.h>
</code>```

答: Assuming pch.h is the precompiled header, #include "pch.h" should be the first non-comment line in the source file. The compiler ignores everything above it.

Title: Boost not recognizing itself as a class

Body:
boost is giving me the "error C2653 'boost': is not a class or namespace name" im trying to use the last_write_time() function from boost filesystem my usage is boost::filesystem::last_write_time(boost::filesystem::path("C:\file.txt"));
im using namespace std and the command is being ran in the main function
im also getting the error identifier not found but im pretty sure thats from it not detecting the class

#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <iterator>
#include <algorithm>
#include "pch.h"
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include "Windows.h"
#include "psapi.h"
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <fileapi.h>


问:
Adding row to Google Sheet with Nodejs
I have the following sheet

I'm using this nodejs module google-spreadsheet
I can read, edit the cells. No problem. But when I try to add a row I'm getting this error.

```<code>sheet #1: Sheet22 1000x26
Error: HTTP error 400 (Bad Request) - Blank rows cannot be written; use delete instead.
</code>```

I looked for answers, they are all about editing the headers? But I can't seem to understand what's missing here since headers are already there.

Thanks a lot!

This is my code

```<code>saveTransaction: function(transaction){
        var creds = require('./credentials.json');
        var doc = new GoogleSpreadsheet('xxxxxxxx');
        doc.useServiceAccountAuth(creds, function (err) {
          if (err) console.log(err);
          doc.getInfo(function (err, info) {
            console.log('Loaded doc: ' + info.title + ' by ' + info.author.email);
            sheet = info.worksheets[21];
            console.log('sheet #1: ' + sheet.title + ' ' + sheet.rowCount + 'x' + sheet.colCount);

            var newrow = {
                title: 'banana',
                type: 'fruit',
                url: 'http://example.com'
            };
            doc.addRow(17, newrow, function( err, rows ){
                if (err) console.log(err);
                console.log(rows);

              });

          })
        })
    },
</code>```

答:
GoogleSpreadsheet.addRow(worksheet_id, new_row, callback)

check worksheet_id

look this

Title: Adding row to Google Sheet with Nodejs

Body:
I have the following sheet

I'm using this nodejs module google-spreadsheet
I can read, edit the cells. No problem. But when I try to add a row I'm getting this error.

sheet #1: Sheet22 1000x26
Error: HTTP error 400 (Bad Request) - Blank rows cannot be written; use delete instead.

I looked for answers, they are all about editing the headers? But I can't seem to understand what's missing here since headers are already there.

Thanks a lot!

This is my code

saveTransaction: function(transaction){
        var creds = require('./credentials.json');
        var doc = new GoogleSpreadsheet('xxxxxxxx');
        doc.useServiceAccountAuth(creds, function (err) {
          if (err) console.log(err);
          doc.getInfo(function (err, info) {
            console.log('Loaded doc: ' + info.title + ' by ' + info.author.email);
            sheet = info.worksheets[21];
            console.log('sheet #1: ' + sheet.title + ' ' + sheet.rowCount + 'x' + sheet.colCount);

            var newrow = {
                title: 'banana',
                type: 'fruit',
                url: 'http://example.com'
            };
            doc.addRow(17, newrow, function( err, rows ){
                if (err) console.log(err);
                console.log(rows);

              });

          })
        })
    },


问:
Why SAP Hana DB ADO.NET DLL loading may fail?
For a .Net C# app that uses SAP.DATA.HANA.v4.5 v2.3.119 and is installed on the runtime machine with the libadonetHDB.dll v2.3.119 with the environment variable HDBADONET pointing to the app folder where libadonetHDB.dll exists. The application works as expected so far on several installations, however one new installation I am seeing it fail producing the The specified module could not be found error exception from HanaConnection below:

```<code>The type initializer for 'Sap.Data.Hana.HanaConnection' threw an exception.
System.Exception: The specified module could not be found
   at Sap.Data.Hana.HanaUnmanagedDll.LoadDll(String dllPath)
   at Sap.Data.Hana.HanaUnmanagedDll..ctor()
   at Sap.Data.Hana.HanaUnmanagedDll.get_Instance()
   at Sap.Data.Hana.HanaConnection..cctor()
</code>```

Also tried just moving the dll to the same folder where the application is installed and the same results are produced.

According to the documentation, the dll being in the same folder as the application or via the HDBADONET environment variable path location should work (and have experienced it working on several other installations). This is part of the general workflow for developing and using the ADO.NET library for non-native .NET apps documented here

I've been trying this as the "Administrator" user and this is a brand new Virtual Machine created (tried both new Windows10 x64 VM and new Windows Server 2016 x64 VM). Also confirmed .NET v4.5+ was installed.

Is it possible that a machine can have a permissions or other policy that affects loading of dlls?

Any clue as to why the SAP Hana ADO.NET DB Connection DLL loading will fail but not in all cases?

Is the libadonetHDB.dll still trying to find and load libSQLDBCHDB.dll or another dll on the machine for some reason? It has been my understanding that using the ADO.NET DLL allowed the machine to not need the other client installation and dlls installed.

Which module is it that can't be found specifically? Is there a way to get the Hana Connection DLL loading to generate more verbose output when it fails?

Update

To confirm that the libadonetHDB.dll is actually found using the HDBADONET environment variable definition, I removed the file and retested and I get a different message:

```<code>The type initializer for 'Sap.Data.Hana.HanaConnection' threw an exception.
System.IO.FileNotFoundException: Cannot find a matching libadonetHDB.dll
with version 2.3.119 - check the location in the HDBADONET or PATH
environment variables
   at Sap.Data.Hana.HanaUnmanagedDll.SearchNativeDlls()
   at Sap.Data.Hana.HanaUnmanagedDll..ctor()
   at Sap.Data.Hana.HanaUnmanagedDll.get_Instance()
   at Sap.Data.Hana.HanaConnection..cctor()
</code>```

So, the message posted in the original post is coming after libadonetHDB.dll has been found successfully. So it seems like the complaint in the exception message about unable to find or load a module is referring to some other resource or dll it is looking for, but the message is not verbose enough to know what that is. Any ideas?

Update (the solution)

The short answer:

Inspecting libadonetHDB.dll with Dependencies reveals that msvcr100.dll and msvcp100.dll were both missing on the runtime machine for some reason. Adding those missing DLLs to the app's installation package resolved the issue.

The longer answer:

Thanks to donjuedo for suggesting to interrogate the DLL to see its dependencies. The tool I used on the machine where it was failing is Dependencies (which requires installation of vc++ redistributable x64 as noted in the readme for it to work) revealed that msvcr100.dll and msvcp100.dll were both missing as dependencies when inspecting libadonetHDB.dll. Note that they were only found to be missing on this particular machine which was a freshly created virtual machine so the inspection and test case had to happen on that machine.

The solution for including the missing DLLs at installation time can be to add msvcr100.dll and msvcp100.dll to either of the following locations:

C:\Windows\System32 (probably not a preferred solution if you want your app to avoid installing things into the main system folder)

the folder where the app's exe also exists

an app's lib subfolder so long as you add the path to that subfolder to the PATH environment variable definition (i.e. set PATH=%PATH%;fullpath\to\app\lib)

These two dlls were already on our development machine and are likely already part of many runtime/client machines that have been around a while and have had other software that needed them. If you don't have these around even in development then download them from Microsoft's official packages as noted here (avoid getting them from 3rd party dll websites if you want be sure they aren't malware hiding in a dll). Ideally the documentation for the SAP HanaDB ADO.NET library should mention the requirements of the runtime machine or that the .NET developer needs to provide these dependent DLLs.

答:
My suggestion is to use Dependency Walker (or other similar util) to determine what DLL the found DLL looking for.  It looks like one is found but not all symbol dependencies were satisfied in that case.

Streamline makes a great point:  the failure seen was a runtime failure, not a build time failure.  Runtime environments vary, so the DLL picked up to satisfy symbols required can be different.  Troubleshooting must be done on the particular system experiencing the exception.

Body:
For a .Net C# app that uses SAP.DATA.HANA.v4.5 v2.3.119 and is installed on the runtime machine with the libadonetHDB.dll v2.3.119 with the environment variable HDBADONET pointing to the app folder where libadonetHDB.dll exists. The application works as expected so far on several installations, however one new installation I am seeing it fail producing the The specified module could not be found error exception from HanaConnection below:

The type initializer for 'Sap.Data.Hana.HanaConnection' threw an exception.
System.Exception: The specified module could not be found
   at Sap.Data.Hana.HanaUnmanagedDll.LoadDll(String dllPath)
   at Sap.Data.Hana.HanaUnmanagedDll..ctor()
   at Sap.Data.Hana.HanaUnmanagedDll.get_Instance()
   at Sap.Data.Hana.HanaConnection..cctor()

Also tried just moving the dll to the same folder where the application is installed and the same results are produced.

According to the documentation, the dll being in the same folder as the application or via the HDBADONET environment variable path location should work (and have experienced it working on several other installations). This is part of the general workflow for developing and using the ADO.NET library for non-native .NET apps documented here

I've been trying this as the "Administrator" user and this is a brand new Virtual Machine created (tried both new Windows10 x64 VM and new Windows Server 2016 x64 VM). Also confirmed .NET v4.5+ was installed.

Is it possible that a machine can have a permissions or other policy that affects loading of dlls?

Any clue as to why the SAP Hana ADO.NET DB Connection DLL loading will fail but not in all cases?

Is the libadonetHDB.dll still trying to find and load libSQLDBCHDB.dll or another dll on the machine for some reason? It has been my understanding that using the ADO.NET DLL allowed the machine to not need the other client installation and dlls installed.

Which module is it that can't be found specifically? Is there a way to get the Hana Connection DLL loading to generate more verbose output when it fails?

Update

To confirm that the libadonetHDB.dll is actually found using the HDBADONET environment variable definition, I removed the file and retested and I get a different message:

The type initializer for 'Sap.Data.Hana.HanaConnection' threw an exception.
System.IO.FileNotFoundException: Cannot find a matching libadonetHDB.dll
with version 2.3.119 - check the location in the HDBADONET or PATH
environment variables
   at Sap.Data.Hana.HanaUnmanagedDll.SearchNativeDlls()
   at Sap.Data.Hana.HanaUnmanagedDll..ctor()
   at Sap.Data.Hana.HanaUnmanagedDll.get_Instance()
   at Sap.Data.Hana.HanaConnection..cctor()

So, the message posted in the original post is coming after libadonetHDB.dll has been found successfully. So it seems like the complaint in the exception message about unable to find or load a module is referring to some other resource or dll it is looking for, but the message is not verbose enough to know what that is. Any ideas?

Update (the solution)

The short answer:

Inspecting libadonetHDB.dll with Dependencies reveals that msvcr100.dll and msvcp100.dll were both missing on the runtime machine for some reason. Adding those missing DLLs to the app's installation package resolved the issue.

The longer answer:

Thanks to donjuedo for suggesting to interrogate the DLL to see its dependencies. The tool I used on the machine where it was failing is Dependencies (which requires installation of vc++ redistributable x64 as noted in the readme for it to work) revealed that msvcr100.dll and msvcp100.dll were both missing as dependencies when inspecting libadonetHDB.dll. Note that they were only found to be missing on this particular machine which was a freshly created virtual machine so the inspection and test case had to happen on that machine.

The solution for including the missing DLLs at installation time can be to add msvcr100.dll and msvcp100.dll to either of the following locations:

C:\Windows\System32 (probably not a preferred solution if you want your app to avoid installing things into the main system folder)

the folder where the app's exe also exists

an app's lib subfolder so long as you add the path to that subfolder to the PATH environment variable definition (i.e. set PATH=%PATH%;fullpath\to\app\lib)

These two dlls were already on our development machine and are likely already part of many runtime/client machines that have been around a while and have had other software that needed them. If you don't have these around even in development then download them from Microsoft's official packages as noted here (avoid getting them from 3rd party dll websites if you want be sure they aren't malware hiding in a dll). Ideally the documentation for the SAP HanaDB ADO.NET library should mention the requirements of the runtime machine or that the .NET developer needs to provide these dependent DLLs.


问:
How to convert Map to Java.util.Properties?
Is there a way to convert from Map to java.util.Properties?

For example, the following Map I would like to convert into java.util.Properties:

```<code>Map("x" -> 24, "y" -> 25, "z" -> 26)
</code>```

答:
Try the following

```<code>import java.util.Properties
val m = Map("x" -> 24, "y" -> 25, "z" -> 26)
val properties = new Properties
m.foreach { case (key, value) => properties.setProperty(key, value.toString) }
properties
</code>```

which should output

```<code>res1: java.util.Properties = {x=24, z=26, y=25}
</code>```

Body:
Is there a way to convert from Map to java.util.Properties?

For example, the following Map I would like to convert into java.util.Properties:

Map("x" -> 24, "y" -> 25, "z" -> 26)

Body:
Try the following

import java.util.Properties
val m = Map("x" -> 24, "y" -> 25, "z" -> 26)
val properties = new Properties
m.foreach { case (key, value) => properties.setProperty(key, value.toString) }
properties

which should output

res1: java.util.Properties = {x=24, z=26, y=25}


问:
CKEditor .focus() in instanceReady event is not working
I am having problems in setting the focus in instanceReady event of CKEditor 3.4.1. I have already tried the following two ways but both of them are not always working. </p>

```<code>CKEDITOR.on('instanceReady', function(e) { CKEDITOR.instances.editor1.focus(); });

CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            ev.editor.focus();
        }
    }
} );
</code>```

答:
here you go my friend

```<code>CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            CKEDITOR.instances.editor1.focus();
        }
    }
} );
</code>```

or

```<code>CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            this.focus();
        }
    }
} );
</code>```

Body:
I am having problems in setting the focus in instanceReady event of CKEditor 3.4.1. I have already tried the following two ways but both of them are not always working.

CKEDITOR.on('instanceReady', function(e) { CKEDITOR.instances.editor1.focus(); });

CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            ev.editor.focus();
        }
    }
} );

Body:
here you go my friend

CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            CKEDITOR.instances.editor1.focus();
        }
    }
} );

or

CKEDITOR.replace('editor1',
{
    on :
    {
        instanceReady : function( ev )
        {
            this.focus();
        }
    }
} );


问:
How to read a .txt file with multiple lines?
I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.

I use this code to write to the file:

```<code>Context context = getApplicationContext();
writedatatofile(context);

protected void writedatatofile(Context context){
        try
        {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
            String data;
            if (newstart){
                data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
            } else {
                data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
            }
            outputStreamWriter.append(data);
            outputStreamWriter.close();
            Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
</code>```

and this code to read the file:

```<code>Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);

private String readFromFile(Context context, String fileName){
        String ret = " ";
        try {
            InputStream inputStream = context.openFileInput(fileName);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();
                while ((receiveString = bufferedReader.readLine()) != null) {
                    Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
                    stringBuilder.append(receiveString);
                }
                inputStream.close();
                ret = stringBuilder.toString();
            } else {
                Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
            }
        } catch (FileNotFoundException e){
            Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        } catch (IOException e){
            Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
        }
        return ret;
    }
</code>```

As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.

答:
When you write the file:</p>

```<code>BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();
</code>```

Body:
I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.

I use this code to write to the file:

Context context = getApplicationContext();
writedatatofile(context);

protected void writedatatofile(Context context){
        try
        {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
            String data;
            if (newstart){
                data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
            } else {
                data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
            }
            outputStreamWriter.append(data);
            outputStreamWriter.close();
            Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }

and this code to read the file:

Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);

private String readFromFile(Context context, String fileName){
        String ret = " ";
        try {
            InputStream inputStream = context.openFileInput(fileName);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();
                while ((receiveString = bufferedReader.readLine()) != null) {
                    Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
                    stringBuilder.append(receiveString);
                }
                inputStream.close();
                ret = stringBuilder.toString();
            } else {
                Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
            }
        } catch (FileNotFoundException e){
            Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        } catch (IOException e){
            Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
        }
        return ret;
    }

As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.

Body:
When you write the file:

BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();


问:
Post-processing wrf output in python
I am trying to use python to post-process WRF output. The various scripts I have seen are too complicated for my elementary level of python. I managed to put together bits of code from here and there. However in my final plot i am not able to capture the data properly.
I would appreciate any assistance.
My code is below
The two lines which gives the wrong results are:

```<code>cs=m.pcolormesh(lons, lats, baseArray, shading='flat', latlon=True)

#cs=m.contourf(lons, lats, baseArray, shading='flat', latlon=True)
</code>```

Obviously my definition of the z component to contour

```<code>baseArray = np.fromfunction(lambda y,x: (1000.0 / (width + height)) * (y+x), (height, width), dtype = float)
</code>```

is incorrect.

I will appreciate assistance to define my variable so that what is plotted reflects what is in the input file.

```<code>from netCDF4 import Dataset
import numpy as np
from matplotlib.mlab import griddata

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from datetime import datetime, timedelta

fh = Dataset("wrfout_d01_2019-03-28_00:00:00", mode="r")
lons = fh.variables["XLONG"][:]
lats = fh.variables["XLAT"][:]
temp = fh.variables["T2"][:]
temp_units = fh.variables['T2'].units

fh.close()

# define map extent
lllon,lllat,urlon,urlat = 17.25,-21.90,38.44,-04.07

width = 300
height = 200

dlon = (urlon-lllon) / width
dLat = (urlat-lllat) / height
baseArray = np.fromfunction(lambda y,x: (1000.0 / (width + height)) * (y+x), (height, width), dtype = float)

lons = np.arange(lllon, urlon, dlon)
lats = np.arange(lllat, urlat, dLat)
lons, lats = np.meshgrid(lons, lats)

fig = plt.figure()

# Set up Basemap instance
m = Basemap(
projection = 'merc',
llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat,resolution='h')

# Plot Data
cs=m.pcolormesh(lons, lats, baseArray, shading='flat', latlon=True)
#cs=m.contourf(lons, lats, baseArray, shading='flat', latlon=True)

# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 5.), labels=[1,0,0,0], fontsize=10)
m.drawmeridians(np.arange(-180., 181., 5.), labels=[0,0,0,1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cb = plt.colorbar(cs ,shrink=1.0) #, extend='both')

# Add Title
plt.title("Temperature")

plt.savefig("Temp2s.png" , format="png", dpi=300, transparent=True)

plt.show()
</code>```

The following is code which is close to what should work. With this code, I have a problem with the numpy arrays of my longitude (x) and latitude (y). I hope someone conversant with numpy can assist me. I have added numpy in the tags.
This code gives me the error:

```<code>ValueError: operands could not be broadcast together with shapes (17,60,69) (17,60)
</code>```

What I know is that I have 69 points in x-direction and 60 in y-direction. My data file has 19 levels, and 9 time steps. I do not know where 17 comes
from.

```<code>from netCDF4 import Dataset
import numpy as np
from matplotlib.mlab import griddata

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, cm
from datetime import datetime, timedelta

fh = Dataset("wrfout_d01_2019-03-28_00:00:00", mode="r")
lons = fh.variables["XLONG"][:]
lats = fh.variables["XLAT"][:]
data = fh.variables["T2"][:]
data_units = fh.variables['T2'].units

fh.close()

# define map extent
lllon,lllat,urlon,urlat =  17.25,-21.90,38.44,-04.07

# Set up Basemap instance
m = Basemap(
    projection = 'merc', \
    llcrnrlon = lllon, llcrnrlat = lllat, \
    urcrnrlon = urlon, urcrnrlat = urlat, resolution='h')

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Grid Lines
# draw parallels.
parallels = np.arange(0.,90,10.)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)

# draw meridians
meridians = np.arange(180.,360.,10.)
m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)

 x,y = m(lons, lats) # compute map proj coordinates.

# draw filled contours.
cs = m.contourf(x,y,data)

# Add Colorbar
cb = plt.colorbar(cs ,shrink=1.0) #, extend='both')

# Add Title
plt.title("Surface Temperature")

plt.savefig("Temp2.png" , format="png", dpi=300, transparent=True)
plt.show()
</code>```

答:
Here are a couple of Python WRF processing packages worth looking into for plotting and analysis. They're both fairly straightforward to use:

wrf-python (from NCAR)

salem

OwnerDisplayName: Zilore Mumba

Title: Post-processing wrf output in python

Body:
I am trying to use python to post-process WRF output. The various scripts I have seen are too complicated for my elementary level of python. I managed to put together bits of code from here and there. However in my final plot i am not able to capture the data properly.
I would appreciate any assistance.
My code is below
The two lines which gives the wrong results are:

cs=m.pcolormesh(lons, lats, baseArray, shading='flat', latlon=True)

#cs=m.contourf(lons, lats, baseArray, shading='flat', latlon=True)

Obviously my definition of the z component to contour

baseArray = np.fromfunction(lambda y,x: (1000.0 / (width + height)) * (y+x), (height, width), dtype = float)

is incorrect.

I will appreciate assistance to define my variable so that what is plotted reflects what is in the input file.

from netCDF4 import Dataset
import numpy as np
from matplotlib.mlab import griddata

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from datetime import datetime, timedelta

fh = Dataset("wrfout_d01_2019-03-28_00:00:00", mode="r")
lons = fh.variables["XLONG"][:]
lats = fh.variables["XLAT"][:]
temp = fh.variables["T2"][:]
temp_units = fh.variables['T2'].units

fh.close()

# define map extent
lllon,lllat,urlon,urlat = 17.25,-21.90,38.44,-04.07

width = 300
height = 200

dlon = (urlon-lllon) / width
dLat = (urlat-lllat) / height
baseArray = np.fromfunction(lambda y,x: (1000.0 / (width + height)) * (y+x), (height, width), dtype = float)

lons = np.arange(lllon, urlon, dlon)
lats = np.arange(lllat, urlat, dLat)
lons, lats = np.meshgrid(lons, lats)

fig = plt.figure()

# Set up Basemap instance
m = Basemap(
projection = 'merc',
llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat,resolution='h')

# Plot Data
cs=m.pcolormesh(lons, lats, baseArray, shading='flat', latlon=True)
#cs=m.contourf(lons, lats, baseArray, shading='flat', latlon=True)

# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 5.), labels=[1,0,0,0], fontsize=10)
m.drawmeridians(np.arange(-180., 181., 5.), labels=[0,0,0,1], fontsize=10)

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Colorbar
cb = plt.colorbar(cs ,shrink=1.0) #, extend='both')

# Add Title
plt.title("Temperature")

plt.savefig("Temp2s.png" , format="png", dpi=300, transparent=True)

plt.show()

The following is code which is close to what should work. With this code, I have a problem with the numpy arrays of my longitude (x) and latitude (y). I hope someone conversant with numpy can assist me. I have added numpy in the tags.
This code gives me the error:

ValueError: operands could not be broadcast together with shapes (17,60,69) (17,60)

What I know is that I have 69 points in x-direction and 60 in y-direction. My data file has 19 levels, and 9 time steps. I do not know where 17 comes
from.

from netCDF4 import Dataset
import numpy as np
from matplotlib.mlab import griddata

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, cm
from datetime import datetime, timedelta

fh = Dataset("wrfout_d01_2019-03-28_00:00:00", mode="r")
lons = fh.variables["XLONG"][:]
lats = fh.variables["XLAT"][:]
data = fh.variables["T2"][:]
data_units = fh.variables['T2'].units

fh.close()

# define map extent
lllon,lllat,urlon,urlat =  17.25,-21.90,38.44,-04.07

# Set up Basemap instance
m = Basemap(
    projection = 'merc', \
    llcrnrlon = lllon, llcrnrlat = lllat, \
    urcrnrlon = urlon, urcrnrlat = urlat, resolution='h')

# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
m.drawcountries()

# Add Grid Lines
# draw parallels.
parallels = np.arange(0.,90,10.)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)

# draw meridians
meridians = np.arange(180.,360.,10.)
m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)

 x,y = m(lons, lats) # compute map proj coordinates.

# draw filled contours.
cs = m.contourf(x,y,data)

# Add Colorbar
cb = plt.colorbar(cs ,shrink=1.0) #, extend='both')

# Add Title
plt.title("Surface Temperature")

plt.savefig("Temp2.png" , format="png", dpi=300, transparent=True)
plt.show()


问:
Find out how the height of a button was set
My code (full version):

        <form class="form-group">
          <form>
            <input type="text" class="form-control w-100 pr-0 mr-0" id="quick-add-task-control-text-area" placeholder="Task name">
          </form>
        </form>

        <button type="button" class="btn btn-secondary w-100 h-100 ml-0" id="schedule-button">Schedule</button>

    <button type="button" class="btn btn-primary btn-sm" id="add-task-modal-save">Save changes</button>

        Priority

      <select class="custom-select" id="inputGroupSelectPriority">
        <option selected>Choose...</option>
        <option value="Low">Low</option>
        <option value="Medium">Medium</option>
        <option value="High">High</option>
      </select>

```

After opening my modal on the navbar ("+" icon), I wanted the height of my input-group to be the same height as my "save changes" button on the left. After inspecting its styles (of the 'save button' I could not understand how it's height was calculated. I did not find any em or rem, or any reference to the parent element like the bootstrap class "h-100". So I had to do it using the height property and pixels, which I know is a terrible way of doing it.
So my question is, how do I set the height of my input-group element in the proper responsive-friendly way?

(For the modal footer I didn't set a container and a row and columns as I did in the modal body, is that terrible?)

答:
The button's height is not explicitly set by Bootstrap, it's automatically calculated from the size of the content plus its margin, padding and border.  The custom select's height, however, is explicitly set, so there is not a way to make it smaller without explicitly overriding that, as well as the properties on the label, unfortunately.

The way you're doing it is not really that bad, just indicative of what, in my opinion, is Bootstrap's biggest drawback: that if you need to even moderately customize your styles, you'll end up fighting and overriding its CSS for much longer than you save by making use of its grid system, though some of the components are quite useful.  You may just want to use a custom input element you style yourself, that way you can use flexbox to have it size up automatically.

Otherwise if you add h-100 to the select element it should be what you're looking for.  Note that if you do shrink the select's height, you will also need to override its padding and/or font size to prevent the text from being cut off.

Body:
My code (full version):

        <form class="form-group">
          <form>
            <input type="text" class="form-control w-100 pr-0 mr-0" id="quick-add-task-control-text-area" placeholder="Task name">
          </form>
        </form>

        <button type="button" class="btn btn-secondary w-100 h-100 ml-0" id="schedule-button">Schedule</button>

    <button type="button" class="btn btn-primary btn-sm" id="add-task-modal-save">Save changes</button>

        Priority

      <select class="custom-select" id="inputGroupSelectPriority">
        <option selected>Choose...</option>
        <option value="Low">Low</option>
        <option value="Medium">Medium</option>
        <option value="High">High</option>
      </select>

After opening my modal on the navbar ("+" icon), I wanted the height of my input-group to be the same height as my "save changes" button on the left. After inspecting its styles (of the 'save button' I could not understand how it's height was calculated. I did not find any em or rem, or any reference to the parent element like the bootstrap class "h-100". So I had to do it using the height property and pixels, which I know is a terrible way of doing it.
So my question is, how do I set the height of my input-group element in the proper responsive-friendly way?

(For the modal footer I didn't set a container and a row and columns as I did in the modal body, is that terrible?)


问:
Generate a new .txt file every 24 hour
I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.

Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file

```<code><?php

    $date = date('Y-m-d');

    $fp = fopen('dates/'.$date.'.txt', "r");

       $count = fread($fp, 1024);

   fclose($fp);

       $count = $count + 1;

       $fp = fopen('dates/'.$date.'.txt', "w");

                 fwrite($fp, $count);

     fclose($fp);

 ?>
</code>```

How to fix it?

答:
Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:

```<code>date_default_timezone_set("America/New_York");
</code>```

Then, our code would look like something similar to:

```<code>date_default_timezone_set("America/New_York");

$dir = 'dates';

if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

$count = 1;
$date = date('Y-m-d');
$filename = $dir . '/' . $date . '.txt';

if (!file_exists($filename)) {
    $fp = fopen($filename, "w");
    fwrite($fp, $count);
    fclose($fp);
} else {
    $count = (int) file_get_contents($filename) + 1;
    if ($count) {
        file_put_contents($filename, $count);
    } else {
        print("Something is not right!");
    }

}
</code>```

Title: Generate a new .txt file every 24 hour

Body:
I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.

Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file

<?php

    $date = date('Y-m-d');

    $fp = fopen('dates/'.$date.'.txt', "r");

       $count = fread($fp, 1024);

   fclose($fp);

       $count = $count + 1;

       $fp = fopen('dates/'.$date.'.txt', "w");

                 fwrite($fp, $count);

     fclose($fp);

 ?>

How to fix it?

Body:
Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:

date_default_timezone_set("America/New_York");

Then, our code would look like something similar to:

date_default_timezone_set("America/New_York");

$dir = 'dates';

if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

$count = 1;
$date = date('Y-m-d');
$filename = $dir . '/' . $date . '.txt';

if (!file_exists($filename)) {
    $fp = fopen($filename, "w");
    fwrite($fp, $count);
    fclose($fp);
} else {
    $count = (int) file_get_contents($filename) + 1;
    if ($count) {
        file_put_contents($filename, $count);
    } else {
        print("Something is not right!");
    }

}


问:
For every father of only a leaf node, remove the leaf and add its value with the father
If I find a father with only a leaf as a child I have to remove the leaf and add its value with the father

This is my solution but I have a problem when I try to remove the leaf

```<code>bool isLeaf(tree a){ //function to verify if the node is a leaf

if(a->left==NULL && a->right==NULL)
    return true;
else
    return false;
}

void removeLeaves(tree* a){

if(*a == NULL) return;

//verify if the node has only a child
 if(((*a)->left==NULL&&(*a)->right!=NULL) || ((*a)->right==NULL&&(*a)->left!=NULL)){

    if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);

        }
    }
    if((*a)->left==NULL){ //if has only right child,verify  if it is a leaf
        if(isLeaf((*a)->right)){
            (*a)->info = (*a)->info + (*a)->right->info;
            free((*a)->right);

        }
    }
}

removeLeaves(&((*a)->left));
removeLeaves(&((*a)->right));
}
</code>```

Minimal:

```<code>if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);
</code>```

If I reach this point (there's only a child to the left and it is a leaf), I sum its value with the father and then free it. without the free I obtain the sum but with the free I get segmentation fault. Same thing with only a child to the right.

Edit1:
I changed the condition to:

```<code>if(((*a)->right==NULL&&(*a)->left!=NULL) && isLeaf((*a)->left)){

        (*a)->info = (*a)->info + (*a)->left->info;

        free((*a)->left);
        (*a)->left = NULL;

}
</code>```

And this works but I don't understand why.

Edit2:(implementation with struct)

```<code>    #include <stdio.h>
#include <cstdlib>

typedef int InfoTree;

typedef struct StructTree {
  InfoTree info;
  struct StructTree* right;
  struct StructTree* left;
} NodeTree;

typedef NodeTree* Tree;

//functions
Tree createTree(InfoTree infoRoot,Tree left,Tree right);
Tree emptyTree();
void print_tree(Tree a);
bool isLeaf(Tree a);
void removeLeaves(Tree* a);

int main(){

    /* Binary Tree:                */
    /*          3               */
    /*       /     \           */
    /*      7       5          */
    /*    /   \      \         */
    /*   4    2       9        */
    /*       /                     */
    /*      6                      */

    Tree A = createTree( 6  , emptyTree(), emptyTree() ) ;
    Tree B = createTree( 2 , emptyTree(), emptyTree() ) ;
    Tree C = createTree( 9 , emptyTree(), emptyTree() ) ;

    Tree D = createTree( 5 , emptyTree(), C);
    Tree E = createTree( 4  , A, emptyTree());

    Tree F = createTree( 7 , E, B);

    Tree H = createTree( 3  , F, D);
    Tree t = H;
    print_tree(t);
    removeLeaves(&t);
    printf("\n");
    print_tree(t);
    return 0;

}

Tree createTree(InfoTree infoRoot,
              Tree left,
              Tree right) {
  Tree a = (Tree) malloc(sizeof(Tree));
  a->info = infoRoot;
  a->left = left;
  a->right = right;
  return a;
}

Tree emptyTree() {
  return NULL;
}

void print_tree(Tree a) {
    if (a==NULL) {
        printf("()");
    }
    else {
        printf("( %d ",a->info);
        print_tree(a->left);
        printf(" ");
        print_tree(a->right);
        printf(" )");
    }
}

bool isLeaf(Tree a){ //function to verify if the node is a leaf

if(a->left==NULL && a->right==NULL)
    return true;
else
    return false;
}

void removeLeaves(Tree* a){

if(*a == NULL) return;

//verify if the node has only a child
 if(((*a)->left==NULL&&(*a)->right!=NULL) || ((*a)->right==NULL&&(*a)->left!=NULL)){

    if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);
        (*a)->left = NULL;

        }
    }
    if((*a)->left==NULL){ //if has only right child,verify  if it is a leaf
        if(isLeaf((*a)->right)){
            (*a)->info = (*a)->info + (*a)->right->info;
            free((*a)->right);
            (*a)->right = NULL;

        }
    }
}

removeLeaves(&((*a)->left));
removeLeaves(&((*a)->right));
}
</code>```

This is the original source code with the tree structure and the functions to work on the tree. If I modify it with the above conditions (first Edit1) it works but I don't understand why.
Thank you

答:
After freeing the leaf you need to set its entry in the father to null.

Your function is recursive. If it finds a single leaf its memory is freed, but at the end of the function it tries to access that memory. This is known as "dangling pointer."

Edit:

There is another issue, here shown at your initial source:

```<code>if((*a)->right==NULL){
    if(isLeaf((*a)->left)){
        // ... irrelevant lines removed ...
        (*a)->left = NULL;
    }
}
if((*a)->left==NULL){ // <== see text below
    if(isLeaf((*a)->right)){ // BOOM!
</code>```

If a leaf is found in the first part then the right pointer is NULL. After setting the left pointer to NULL the marked if evaluates to true, and isLeaf() is called with a NULL pointer giving you the segmentation fault.

Body:
If I find a father with only a leaf as a child I have to remove the leaf and add its value with the father

This is my solution but I have a problem when I try to remove the leaf

bool isLeaf(tree a){ //function to verify if the node is a leaf

if(a->left==NULL && a->right==NULL)
    return true;
else
    return false;
}

void removeLeaves(tree* a){

if(*a == NULL) return;

//verify if the node has only a child
 if(((*a)->left==NULL&&(*a)->right!=NULL) || ((*a)->right==NULL&&(*a)->left!=NULL)){

    if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);

        }
    }
    if((*a)->left==NULL){ //if has only right child,verify  if it is a leaf
        if(isLeaf((*a)->right)){
            (*a)->info = (*a)->info + (*a)->right->info;
            free((*a)->right);

        }
    }
}

removeLeaves(&((*a)->left));
removeLeaves(&((*a)->right));
}

Minimal:

if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);

If I reach this point (there's only a child to the left and it is a leaf), I sum its value with the father and then free it. without the free I obtain the sum but with the free I get segmentation fault. Same thing with only a child to the right.

Edit1:
I changed the condition to:

if(((*a)->right==NULL&&(*a)->left!=NULL) && isLeaf((*a)->left)){

        (*a)->info = (*a)->info + (*a)->left->info;

        free((*a)->left);
        (*a)->left = NULL;

}

And this works but I don't understand why.

Edit2:(implementation with struct)

    #include <stdio.h>
#include <cstdlib>

typedef int InfoTree;

typedef struct StructTree {
  InfoTree info;
  struct StructTree* right;
  struct StructTree* left;
} NodeTree;

typedef NodeTree* Tree;

//functions
Tree createTree(InfoTree infoRoot,Tree left,Tree right);
Tree emptyTree();
void print_tree(Tree a);
bool isLeaf(Tree a);
void removeLeaves(Tree* a);

int main(){

    /* Binary Tree:                */
    /*          3               */
    /*       /     \           */
    /*      7       5          */
    /*    /   \      \         */
    /*   4    2       9        */
    /*       /                     */
    /*      6                      */

    Tree A = createTree( 6  , emptyTree(), emptyTree() ) ;
    Tree B = createTree( 2 , emptyTree(), emptyTree() ) ;
    Tree C = createTree( 9 , emptyTree(), emptyTree() ) ;

    Tree D = createTree( 5 , emptyTree(), C);
    Tree E = createTree( 4  , A, emptyTree());

    Tree F = createTree( 7 , E, B);

    Tree H = createTree( 3  , F, D);
    Tree t = H;
    print_tree(t);
    removeLeaves(&t);
    printf("\n");
    print_tree(t);
    return 0;

}

Tree createTree(InfoTree infoRoot,
              Tree left,
              Tree right) {
  Tree a = (Tree) malloc(sizeof(Tree));
  a->info = infoRoot;
  a->left = left;
  a->right = right;
  return a;
}

Tree emptyTree() {
  return NULL;
}

void print_tree(Tree a) {
    if (a==NULL) {
        printf("()");
    }
    else {
        printf("( %d ",a->info);
        print_tree(a->left);
        printf(" ");
        print_tree(a->right);
        printf(" )");
    }
}

bool isLeaf(Tree a){ //function to verify if the node is a leaf

if(a->left==NULL && a->right==NULL)
    return true;
else
    return false;
}

void removeLeaves(Tree* a){

if(*a == NULL) return;

//verify if the node has only a child
 if(((*a)->left==NULL&&(*a)->right!=NULL) || ((*a)->right==NULL&&(*a)->left!=NULL)){

    if((*a)->right==NULL){ //if has only left child,verify  if it is a leaf
        if(isLeaf((*a)->left)){
            (*a)->info = (*a)->info + (*a)->left->info;
            free((*a)->left);
        (*a)->left = NULL;

        }
    }
    if((*a)->left==NULL){ //if has only right child,verify  if it is a leaf
        if(isLeaf((*a)->right)){
            (*a)->info = (*a)->info + (*a)->right->info;
            free((*a)->right);
            (*a)->right = NULL;

        }
    }
}

removeLeaves(&((*a)->left));
removeLeaves(&((*a)->right));
}

This is the original source code with the tree structure and the functions to work on the tree. If I modify it with the above conditions (first Edit1) it works but I don't understand why.
Thank you

Body:
After freeing the leaf you need to set its entry in the father to null.

Your function is recursive. If it finds a single leaf its memory is freed, but at the end of the function it tries to access that memory. This is known as "dangling pointer."

Edit:

There is another issue, here shown at your initial source:

if((*a)->right==NULL){
    if(isLeaf((*a)->left)){
        // ... irrelevant lines removed ...
        (*a)->left = NULL;
    }
}
if((*a)->left==NULL){ // <== see text below
    if(isLeaf((*a)->right)){ // BOOM!

If a leaf is found in the first part then the right pointer is NULL. After setting the left pointer to NULL the marked if evaluates to true, and isLeaf() is called with a NULL pointer giving you the segmentation fault.


问:
Image in flex container not centering after defining width and height
I'm doing some personal portfolio using css flex box. what I'm trying to do is to center the image horizontally, It did center but the problem is after I defined width and height to img the image is at the start or left now not in the center.

This is what it looks like when centered and not defining the width and height

.center-img{
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png" alt="user">
  <h1>User</h1>
</div></code>```

And this is what it look liked after defining width and height

.center-img{
  width:100px;
  height:100px;
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png" alt="user">
  <h1>User</h1>
</div></code>```

I expect that after defining the width and height of the image it would not affect the position of the image. so it should be in the center.
thank you!

答:
Few things to consider:

You were never centering the image.

In your first code sample, the image was occupying the entire viewport width, so it just appeared centered. When you reduced the size of the image with width and height, it aligned left, per the default value. Use align-items to horizontally center flex items in a column-direction container.

Don't use images as flex items. There are lots of bugs.

Images as flex items are known to have rendering problems across different browsers. Instead, wrap the image in a div, and make the div the flex item.

Align the image inside a nested container with flex properties.

Use a nested flex container to center the image.

.center-img {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: lightgray;
}

.center-img > div {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  border: 1px dashed red;

}

.center-img > div > img {
  width: 100%;
}

h1 {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center-img">
  <div>
    <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
      alt="user">
  </div>
  <h1>User</h1>
</div></code>```

Body:
I'm doing some personal portfolio using css flex box. what I'm trying to do is to center the image horizontally, It did center but the problem is after I defined width and height to img the image is at the start or left now not in the center.

This is what it looks like when centered and not defining the width and height

.center-img{
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}

User

And this is what it look liked after defining width and height

.center-img{
  width:100px;
  height:100px;
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}

User

I expect that after defining the width and height of the image it would not affect the position of the image. so it should be in the center.
thank you!

Body:
Few things to consider:

You were never centering the image.

In your first code sample, the image was occupying the entire viewport width, so it just appeared centered. When you reduced the size of the image with width and height, it aligned left, per the default value. Use align-items to horizontally center flex items in a column-direction container.

Don't use images as flex items. There are lots of bugs.

Images as flex items are known to have rendering problems across different browsers. Instead, wrap the image in a div, and make the div the flex item.

Align the image inside a nested container with flex properties.

Use a nested flex container to center the image.

.center-img {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: lightgray;
}

.center-img > div {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  border: 1px dashed red;

}

.center-img > div > img {
  width: 100%;
}

h1 {
  margin: 0;
}

<div class="center-img">
  <div>
    <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
      alt="user">
  </div>
  <h1>User</h1>
</div>


问:
Integrate authorization(eg: facebook) after user has logged into the application
In my application, the user would login into the application and then authorize facebook(by clicking a button in a secure area) to allow the application to get facebook posts etc. The application however always redirects the user to the login screen. I believe this has to do with the application configuring the CookiePolicyOptions with CheckConsentNeeded = true but setting it to false does not help.
What am I missing?

Page after user has logged in:

```<code><form asp-area="Identity" asp-page="/Account/ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<button type="submit" class="btn btn-sm btn-facebook btn-icon-label" value="Facebook">
<span class="btn-inner--icon">
<i class="fab fa-facebook"></i>
</span>
</button>
</div>
</div>
</code>```

Identity/Account/ExternalLogin.cshtml.cs

```<code>[AllowAnonymous]
    public class ExternalLoginModel : PageModel
    {
        public IActionResult OnPost(string provider, string returnUrl = null)
        {
          var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
          var authenticationProperties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
          return new ChallengeResult(provider, authenticationProperties);
        }
</code>```

StartUp.cs:

```<code>public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
      services.Configure<CookiePolicyOptions>(options =>
      {
        options.CheckConsentNeeded = context => true;<= I believe that this could be one of the issues
        options.MinimumSameSitePolicy = SameSiteMode.None;
      });
      services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnectionString")));
      services.AddIdentity<ApplicationUser, IdentityRole>(config =>
      {
        config.SignIn.RequireConfirmedEmail = true;
      })
      .AddEntityFrameworkStores<ApplicationDbContext>()
      .AddDefaultTokenProviders();

      services
        .AddAuthentication(
        )
        .AddCookie()
      .AddFacebook(facebookOptions =>
      {
        facebookOptions.AppId = Configuration["FacebookAuthSettings:AppId"];
        facebookOptions.AppSecret = Configuration["FacebookAuthSettings:AppSecret"];
        facebookOptions.SaveTokens = true;
        facebookOptions.Events.OnCreatingTicket = oAuthCreatingTicketContext =>
        {
          var authenticationTokens = oAuthCreatingTicketContext.Properties.GetTokens().ToList();
          var authenticationToken = new AuthenticationToken()
          {
            Name = "TicketCreated",
            Value = DateTime.UtcNow.ToString()
          };
          authenticationTokens.Add(authenticationToken);
          oAuthCreatingTicketContext.Properties.StoreTokens(authenticationTokens);
          return Task.CompletedTask;
        };
      });

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).
          AddRazorPagesOptions(options =>
      {
        options.AllowAreas = true;
        options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
      });
      services.ConfigureApplicationCookie(options =>
      {
          options.LoginPath = $"/Identity/Account/Login";
          options.LogoutPath = $"/Identity/Account/Logout";
          options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
      });

      services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
      services.AddMvc().AddJsonOptions(options =>
      {
        options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
      });
      //enforce HTTPS globally in the app.
      services.Configure<MvcOptions>(mvcOptions =>
      {
        mvcOptions.Filters.Add(new RequireHttpsAttribute());
      });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
          app.UseDatabaseErrorPage();
      }
      else
      {
          app.UseExceptionHandler("/Error");
          // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
          app.UseHsts();
      }
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseCookiePolicy();
      app.UseAuthentication();
      app.UseMvc();
    }
  }
</code>```

答:
Somehow I am always able to figure out answers immediately after I post to stackoverflow. @KirkLarkin is right, I need to specify the name="provider" in my facebook button. </p>

```<code><form asp-area="Identity" asp-page="/Account/ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<button type="submit" name="provider" value="Facebook">
<span class="btn-inner--icon">
<i class="fab fa-facebook"></i>
</span>
</button>
</div>
</div>
</code>```

Body:
In my application, the user would login into the application and then authorize facebook(by clicking a button in a secure area) to allow the application to get facebook posts etc. The application however always redirects the user to the login screen. I believe this has to do with the application configuring the CookiePolicyOptions with CheckConsentNeeded = true but setting it to false does not help.
What am I missing?

Page after user has logged in:

<form asp-area="Identity" asp-page="/Account/ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post">

<button type="submit" class="btn btn-sm btn-facebook btn-icon-label" value="Facebook">

</button>

Identity/Account/ExternalLogin.cshtml.cs

[AllowAnonymous]
    public class ExternalLoginModel : PageModel
    {
        public IActionResult OnPost(string provider, string returnUrl = null)
        {
          var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
          var authenticationProperties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
          return new ChallengeResult(provider, authenticationProperties);
        }

StartUp.cs:

public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
      services.Configure<CookiePolicyOptions>(options =>
      {
        options.CheckConsentNeeded = context => true;<= I believe that this could be one of the issues
        options.MinimumSameSitePolicy = SameSiteMode.None;
      });
      services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnectionString")));
      services.AddIdentity<ApplicationUser, IdentityRole>(config =>
      {
        config.SignIn.RequireConfirmedEmail = true;
      })
      .AddEntityFrameworkStores<ApplicationDbContext>()
      .AddDefaultTokenProviders();

      services
        .AddAuthentication(
        )
        .AddCookie()
      .AddFacebook(facebookOptions =>
      {
        facebookOptions.AppId = Configuration["FacebookAuthSettings:AppId"];
        facebookOptions.AppSecret = Configuration["FacebookAuthSettings:AppSecret"];
        facebookOptions.SaveTokens = true;
        facebookOptions.Events.OnCreatingTicket = oAuthCreatingTicketContext =>
        {
          var authenticationTokens = oAuthCreatingTicketContext.Properties.GetTokens().ToList();
          var authenticationToken = new AuthenticationToken()
          {
            Name = "TicketCreated",
            Value = DateTime.UtcNow.ToString()
          };
          authenticationTokens.Add(authenticationToken);
          oAuthCreatingTicketContext.Properties.StoreTokens(authenticationTokens);
          return Task.CompletedTask;
        };
      });

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).
          AddRazorPagesOptions(options =>
      {
        options.AllowAreas = true;
        options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
      });
      services.ConfigureApplicationCookie(options =>
      {
          options.LoginPath = $"/Identity/Account/Login";
          options.LogoutPath = $"/Identity/Account/Logout";
          options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
      });

      services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
      services.AddMvc().AddJsonOptions(options =>
      {
        options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
      });
      //enforce HTTPS globally in the app.
      services.Configure<MvcOptions>(mvcOptions =>
      {
        mvcOptions.Filters.Add(new RequireHttpsAttribute());
      });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
          app.UseDatabaseErrorPage();
      }
      else
      {
          app.UseExceptionHandler("/Error");
          // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
          app.UseHsts();
      }
      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseCookiePolicy();
      app.UseAuthentication();
      app.UseMvc();
    }
  }

Body:
Somehow I am always able to figure out answers immediately after I post to stackoverflow. @KirkLarkin is right, I need to specify the name="provider" in my facebook button.

<form asp-area="Identity" asp-page="/Account/ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<button type="submit" name="provider" value="Facebook">
<span class="btn-inner--icon">
<i class="fab fa-facebook"></i>
</span>
</button>
</div>
</div>


答:
If Gui and DrawPanel are in the same package you could use

Gui.gamestate--

else you have to declare gamestate as public
and then call

Gui.gamestate--

Title: Using a int value, which is in another class file?

Body:
I want to use a int value, that is in Gui.class, in DrawPanel1.class, how can I pass over the int value easily from Class to Class file?
My int value:

/* Gui.java */
static int gamestate = 1;

I want to decrease gamestate by 1, in the DrawPanel.java, in a buttonHandler, like so:

/*DrawPanel.java */
    class StartNewGameHandler implements ActionListener{
     public void actionPerformed( ActionEvent e ){
                    gamestate--;
     }
}


问:
How do I integrate Flutter web with Firebase?
I need to integrate my Flutter web app with Firebase. I found information, but it is all about Flutter for mobile apps and I need it for Flutter for web.</p>

答:
The FlutterFire library wraps the native Firebase SDKs for iOS and Android, and is not available for the Flutter for the Web at the moment.

There is however a community library firebase-dart that wraps some of the Firebase products for Dart/Web users. From recent commits it seems that this library may be compatible with Flutter for the Web.


问:
Can I call separate function in useEffect?
Can I call another separate function in useEffect?

I am calling another function in useEffect but after saving the file it is automatically adding that function in array parameters of useEffect.

See the code below for proper understanding.

Before saving file:

useEffect(() => {
  getData()
  console.log("useEffect ran...");
}, [query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
  .then(response => response.json())
  .then(json => setData(json));
}
```
<p>after saving file:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  getData();
  console.log("useEffect ran...");
}, [getData, query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json())
    .then(json => setData(json));
}
</code>```

it is running again and again.

答:
Since you declare the getData function inside your React component it will be re-created on each render and thus the dependencies of your effect change on each render. This is the reason why the effect is executed on each render.

To prevent this you should declare the getData function outside of the component and then pass query. Like so:

```<code>function getData(query) {
  return fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json());
}

function YouComponent({ query }) {
  ...
  useEffect(() => {
    getData(query).then(setData);
    console.log("useEffect ran...");
  }, [query]);

  ...
</code>```

P.S: I'm not sure whether the eslint plugin will add getData to the dependencies automatically when doing it like this but even if it does so it doesn't hurt.

Body:
Can I call another separate function in useEffect?

I am calling another function in useEffect but after saving the file it is automatically adding that function in array parameters of useEffect.

See the code below for proper understanding.

Before saving file:

useEffect(() => {
  getData()
  console.log("useEffect ran...");
}, [query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
  .then(response => response.json())
  .then(json => setData(json));
}

after saving file:

useEffect(() => {
  getData();
  console.log("useEffect ran...");
}, [getData, query]);

function getData() {
  fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json())
    .then(json => setData(json));
}

it is running again and again.

Body:
Since you declare the getData function inside your React component it will be re-created on each render and thus the dependencies of your effect change on each render. This is the reason why the effect is executed on each render.

To prevent this you should declare the getData function outside of the component and then pass query. Like so:

function getData(query) {
  return fetch(`https://jsonplaceholder.typicode.com/${query}`)
    .then(response => response.json());
}

function YouComponent({ query }) {
  ...
  useEffect(() => {
    getData(query).then(setData);
    console.log("useEffect ran...");
  }, [query]);

  ...

P.S: I'm not sure whether the eslint plugin will add getData to the dependencies automatically when doing it like this but even if it does so it doesn't hurt.


问:
PHP and SQLite Service in Memory
I have a single page responsive HTML page.  One section of the page has a product search.  User can enter search criteria in a form and get back the results. The results are paged.

```<code><form id="filterform" name="filterform" method="post" action="./loaddata.php">
   ...
</form>
</code>```

The form is submitted by Ajax and the results are returned as an HTML fragment that gets dynamically inserted into the DOM to refresh the results.

That's all working OK, but sometimes the results from loaddata.php are very slow, usually the first time called from the page.

In loaddata.php I'm using a Sqlite3 database.  It is read only.  Something like the following:

```<code>$filename = "../datafile.sqlite3";
$db = new SQLite3($filename);
$q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
$results = $db->query($q);
while ($row = $results->fetchArray()) {
    echo "<h1>Results</h1>";
}
$db->close();
</code>```

Is there a way to make loaddata.php load and stay in memory to respond to the form submit?  It seems like it will reload every submit.

答:
Depending on the size of the datatable you can save it on SESSION, use functions like shmop_open/shmop_write/shmop_read or (better yet) use some cache service like redis, but in one way or another the data will be stored and processed every time you pass by that place. I would tere the page in pieces, create one webservice to deal with the form post and another to show the form.

The easiest (not necessary safest or best way to do) would be ...
PS: I assume you are working with PDO and (obviously) the code bellow is an elaboration, it will not actually work

```<code>if (isset($_SESSION['db_datatable'])) {
    foreach ($_SESSION['db_datatable'] AS $item) {
        echo "<h1>".$item['some_row']."</h1>";
    }
} else {
    $filename = "../datafile.sqlite3";
    $db = new SQLite3($filename);
    $q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
    $results = $db->query($q);
    while ($row = $results->fetchArray()) {
        $_SESSION['db_datatable'][] = $row;
        echo "<h1>Results</h1>";
    }
    $db->close();
}
</code>```

Hope I have been of some help. Cheers!

Title: PHP and SQLite Service in Memory

Body:
I have a single page responsive HTML page.  One section of the page has a product search.  User can enter search criteria in a form and get back the results. The results are paged.

<form id="filterform" name="filterform" method="post" action="./loaddata.php">
   ...
</form>

The form is submitted by Ajax and the results are returned as an HTML fragment that gets dynamically inserted into the DOM to refresh the results.

That's all working OK, but sometimes the results from loaddata.php are very slow, usually the first time called from the page.

In loaddata.php I'm using a Sqlite3 database.  It is read only.  Something like the following:

$filename = "../datafile.sqlite3";
$db = new SQLite3($filename);
$q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
$results = $db->query($q);
while ($row = $results->fetchArray()) {
    echo "
Results
";
}
$db->close();

Is there a way to make loaddata.php load and stay in memory to respond to the form submit?  It seems like it will reload every submit.

Body:
Depending on the size of the datatable you can save it on SESSION, use functions like shmop_open/shmop_write/shmop_read or (better yet) use some cache service like redis, but in one way or another the data will be stored and processed every time you pass by that place. I would tere the page in pieces, create one webservice to deal with the form post and another to show the form.

The easiest (not necessary safest or best way to do) would be ...
PS: I assume you are working with PDO and (obviously) the code bellow is an elaboration, it will not actually work

if (isset($_SESSION['db_datatable'])) {
    foreach ($_SESSION['db_datatable'] AS $item) {
        echo "<h1>".$item['some_row']."</h1>";
    }
} else {
    $filename = "../datafile.sqlite3";
    $db = new SQLite3($filename);
    $q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
    $results = $db->query($q);
    while ($row = $results->fetchArray()) {
        $_SESSION['db_datatable'][] = $row;
        echo "<h1>Results</h1>";
    }
    $db->close();
}

Hope I have been of some help. Cheers!