问:
How to insert multiple records into postgres database using go-pg
I went through the documentation to insert multiple records into postgres using the package pg https://pkg.go.dev/github.com/go-pg/pg/v10#example-DB.Model-BulkInsert .

```<code>db := modelDB()

book1 := &Book{
    Title: "new book 1",
}
book2 := &Book{
    Title: "new book 2",
}
_, err := db.Model(book1, book2).Insert()
if err != nil {
    panic(err)
}
fmt.Println(book1, book2)
</code>```

Honestly i dont like this solution since it does not allow me to pass an array of books. Cause the use case i have is that i wont know the number of books i need to insert.

Should i be using transactions here cause i might have to insert more than 20 record at once. If yes, please help as am not finding good examples for this one.

PS: Must use pg library.

答: Just put your book, in array of slices, and insert it, go-pg support insert batch</p>

Body:
I went through the documentation to insert multiple records into postgres using the package pg https://pkg.go.dev/github.com/go-pg/pg/v10#example-DB.Model-BulkInsert .

db := modelDB()

book1 := &Book{
    Title: "new book 1",
}
book2 := &Book{
    Title: "new book 2",
}
_, err := db.Model(book1, book2).Insert()
if err != nil {
    panic(err)
}
fmt.Println(book1, book2)

Honestly i dont like this solution since it does not allow me to pass an array of books. Cause the use case i have is that i wont know the number of books i need to insert.

Should i be using transactions here cause i might have to insert more than 20 record at once. If yes, please help as am not finding good examples for this one.

PS: Must use pg library.


来源: stackexchange

问:
How can I update the flow source data in android coroutine?
I am developing an android app using Coroutine.

Because I have an experience with the Rx, I can understand Coroutine Flow's concept.

But I don't know about emitting new data to the existing flow.

In Rx, I can use BehaviorSubject and it's onNext() function.

Producer:

class ProfileRepository(
    private val profileDao: ProfileDao
) {

    init {
        val profile = profileDao.getMyProfile()
        myProfile.onNext(profile)
    }

    val myProfile: PublishSubject<Profile> = BehaviorSubject.create()

    fun updateMyProfile(profile: Profile) {
        myProfile.onNext(profile)
    }

}
```
<p>Subscriber:</p>
<pre class="lang-kotlin prettyprint-override"><code>class ProfileViewModel(
    private val profileRepo: ProfileRepository
) {
    val myProfile = MutableLiveData<Profile>()

    fun loadMyProfile() {
        profileRepo.subscribe {
            myProfile.postValue(it)
        }
    }
}
</code>```

And other UI (like Dialog) can update the source data like:

class SignInDialog(
    private val profileRepo: ProfileRepository
) {

    fun onSignInSuccess() {
        profileRepo.updateMyProfile(profile)
    }
}
```

I want to do this using Coroutine Flow, Is this possible on Flow?

答:
You are using BehaviorSubject, which emits the most recently item at the time of subscription and then continues the sequence until complete. So basically it is a hot stream of data.

The similar behavior has SharedFlow:

A hotFlow that shares emitted values among all its collectors in a broadcast fashion, so that all collectors get all emitted values. A shared flow is called hot because its active instance exists independently of the presence of collectors.

For your case it will look something like the following:

```<code>class ProfileRepository(
    private val profileDao: ProfileDao
) {

    init {
        val profile = profileDao.getMyProfile()
        _myProfile.tryEmit(profile)
    }

    private val _myProfile = MutableSharedFlow<String>(replay = 1, extraBufferCapacity = 64)

    val myProfile: SharedFlow<Profile> = _myProfile

    fun updateMyProfile(profile: Profile) {
       _myProfile.tryEmit(profile)
    }
}

class ProfileViewModel(
    private val profileRepo: ProfileRepository
) {
    val myProfile = MutableLiveData<Profile>()

    fun loadMyProfile() = viewModelScope.launch {
        profileRepo.myProfile.collect {
            myProfile.postValue(it)
        }
    }
}
</code>```

viewModelScope - Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. For ViewModelScope, use

```<code>androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0 or higher.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing an android app using Coroutine.

Because I have an experience with the Rx, I can understand Coroutine Flow's concept.

But I don't know about emitting new data to the existing flow.

In Rx, I can use BehaviorSubject and it's onNext() function.

Producer:

class ProfileRepository(
    private val profileDao: ProfileDao
) {

    init {
        val profile = profileDao.getMyProfile()
        myProfile.onNext(profile)
    }

    val myProfile: PublishSubject<Profile> = BehaviorSubject.create()

    fun updateMyProfile(profile: Profile) {
        myProfile.onNext(profile)
    }

}

Subscriber:

class ProfileViewModel(
    private val profileRepo: ProfileRepository
) {
    val myProfile = MutableLiveData<Profile>()

    fun loadMyProfile() {
        profileRepo.subscribe {
            myProfile.postValue(it)
        }
    }
}

And other UI (like Dialog) can update the source data like:

class SignInDialog(
    private val profileRepo: ProfileRepository
) {

    fun onSignInSuccess() {
        profileRepo.updateMyProfile(profile)
    }
}

I want to do this using Coroutine Flow, Is this possible on Flow?

Body:
You are using BehaviorSubject, which emits the most recently item at the time of subscription and then continues the sequence until complete. So basically it is a hot stream of data.

The similar behavior has SharedFlow:

A hotFlow that shares emitted values among all its collectors in a broadcast fashion, so that all collectors get all emitted values. A shared flow is called hot because its active instance exists independently of the presence of collectors.

For your case it will look something like the following:

class ProfileRepository(
    private val profileDao: ProfileDao
) {

    init {
        val profile = profileDao.getMyProfile()
        _myProfile.tryEmit(profile)
    }

    private val _myProfile = MutableSharedFlow<String>(replay = 1, extraBufferCapacity = 64)

    val myProfile: SharedFlow<Profile> = _myProfile

    fun updateMyProfile(profile: Profile) {
       _myProfile.tryEmit(profile)
    }
}

class ProfileViewModel(
    private val profileRepo: ProfileRepository
) {
    val myProfile = MutableLiveData<Profile>()

    fun loadMyProfile() = viewModelScope.launch {
        profileRepo.myProfile.collect {
            myProfile.postValue(it)
        }
    }
}

viewModelScope - Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. For ViewModelScope, use

androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0 or higher.


问:
Call specific method on object depending on selected enum value
Let's assume we have an enum, that represents searchable fields:

enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}
```
<p>This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.</p>
<p>Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.</p>
<pre class="lang-java prettyprint-override"><code>class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}
</code>```

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:

private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}
```

This does work, however I feel like it's clunky.

Question:

Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)

答:
Enums can contain method definitions, so one way is to define the method that retrieves the field name based on the enum value. I assume you have the actual field name stored as a member field also. Then you can override the method for the special ALL value:

```<code>enum SearchableFields {
    ALL("all") { // all is just a placeholder in this case
        @Override
        String retrieveField(FieldPojo f) {
            // logic for all fields
        }
    },
    FIELD1("field1"),
    FIELD2("field2"),
    FIELD3("field3");

    SearchableFields(String fieldName) {
        this.fieldName = Optional.of(fieldName);
    }
    SearchableFields() {
        fieldName = Optional.empty();
    }
    private final Optional<String> fieldName;

    String retrieveField(FieldPojo f) {
        if (fieldName.isPresent()) {
            return (String) f.getClass().getField(fieldName.get()).get(f);
        } else {
           // ...
        }
    }
}
</code>```

Body:
Let's assume we have an enum, that represents searchable fields:

enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}

This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.

Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.

class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:

private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}

This does work, however I feel like it's clunky.

Question:

Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)

Body:
Enums can contain method definitions, so one way is to define the method that retrieves the field name based on the enum value. I assume you have the actual field name stored as a member field also. Then you can override the method for the special ALL value:

enum SearchableFields {
    ALL("all") { // all is just a placeholder in this case
        @Override
        String retrieveField(FieldPojo f) {
            // logic for all fields
        }
    },
    FIELD1("field1"),
    FIELD2("field2"),
    FIELD3("field3");

    SearchableFields(String fieldName) {
        this.fieldName = Optional.of(fieldName);
    }
    SearchableFields() {
        fieldName = Optional.empty();
    }
    private final Optional<String> fieldName;

    String retrieveField(FieldPojo f) {
        if (fieldName.isPresent()) {
            return (String) f.getClass().getField(fieldName.get()).get(f);
        } else {
           // ...
        }
    }
}


问:
Analyze Previous months data from logs using Awstats?
Hi I have configured Awstats on my ubuntu machine to analyze nginx access logs and the problem is Awstats gives me report only for the present day i want to analyze the previous months logs also and i have combine all logs to a single file and ran the update script still i dnt get the report for the previous months, i checked the log files the data for the previous months are in avilable what am i doing wrong</p>

答:
You can use a real-time log analyzer, such as GoAccess. It's really fast and you can combine all logs. apache & nginx

http://goaccess.prosoftcorp.com/

```<code>zcat -f access.log* | goaccess -a -s -b
</code>```

OR

```<code>zcat access.log.*.gz | goaccess -a -s -b
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use a real-time log analyzer, such as GoAccess. It's really fast and you can combine all logs. apache & nginx

http://goaccess.prosoftcorp.com/

zcat -f access.log* | goaccess -a -s -b

OR

zcat access.log.*.gz | goaccess -a -s -b


问:
Print per 2 char in java arraylist (non static arraylist)
Im new with java. im getting struggle with printin something, this is my arraylist

```<code>arraylist = ['a','u','o','e']
</code>```

If my arraylist isnt a static length arraylist. How could I print that list into this

"Your Value: au, oe"

Im kinda confused

Thanks for advance

答:
So an array is a datatype that we use to store multiple values in a single variable. Arrays start at index 0 rather than 1. So this means the first element in the array has an index of 0

```<code>array = {0, 1, 2, 3, 4}
</code>```

So, for your example we would want to do this:

```<code>System.out.println("Your Value: " + arrayList.get(0) + arrayList.get(1) + "," + arrayList.get(2) + arrayList.get(3)
</code>```

Where we say arrayList.get(0) that is accessing the first letter in the array which is 'a'

Body:
Im new with java. im getting struggle with printin something, this is my arraylist

arraylist = ['a','u','o','e']

If my arraylist isnt a static length arraylist. How could I print that list into this

"Your Value: au, oe"

Im kinda confused

Thanks for advance

Body:
So an array is a datatype that we use to store multiple values in a single variable. Arrays start at index 0 rather than 1. So this means the first element in the array has an index of 0

array = {0, 1, 2, 3, 4}

So, for your example we would want to do this:

System.out.println("Your Value: " + arrayList.get(0) + arrayList.get(1) + "," + arrayList.get(2) + arrayList.get(3)

Where we say arrayList.get(0) that is accessing the first letter in the array which is 'a'


问:
Docker error for GUI app: qt.qpa.xcb: could not connect to display, qt.qpa.plugin: Could not load the Qt platform plugin "xcb" "" even though
I am trying to install a GUI based software called Dragonfly as a container, since the software has conflicts with my host OS RHEL7. So I thought installing as a Docker container could be a solution, even though I am completely new with Docker. My Dockerfile looks like below:

```<code>FROM ubuntu
COPY DragonflyInstaller /Dragonfly/
WORKDIR /Dragonfly/

# Dependent packages for Dragonfly
ARG DEBIAN_FRONTEND=noninteractive #
ENV TZ=Europe/Berlin
RUN apt-get update && apt-get install -y apt-utils \
                                         fontconfig \
                                         libxcb1 \
                                         libxcb-glx0 \
                                         x11-common \
                                         x11-apps \
                                         libx11-xcb-dev \
                                         libxrender1 \
                                         libxext6 \
                                         libxkbcommon-x11-0 \
                                         libglu1 \
                                         libxcb-xinerama0 \
                                         qt5-default \
                                         libxcb-icccm4 \
                                         libxcb-image0 \
                                         libxcb-render-util0 \
                                         libxcb-util1 \
                                         freeglut3-dev \
                                         python3-pip \
                                         xauth

CMD ./DragonflyInstaller
</code>```

After building the corresponding Docker image, it cannot launch GUI based installer-window of Dragonfly. I am using the two following commands:

```<code>xhost +local:docker
sudo docker run -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix: dragonfly
</code>```

I tried various suggestions posted on different forums, accordingly, I tried various arguments for docker run, however, I am getting two errors every time, as below:

```<code>No protocol specified
qt.qpa.xcb: could not connect to display :340.0
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: minimal, xcb.
</code>```

Could you please suggest me how to resolve this issue?

答:
In fact I was logging in my machine with X2Go remote desktop client that provides its own desktop after log in. However, I also tried another remote login software called NoMachine which does not create its own display or desktop, rather it keeps original desktop for the remote user. When I tried with NoMachine, there was no errors.

So I guess, the above two errors are caused by remote desktop software X2Go.

Body:
I am trying to install a GUI based software called Dragonfly as a container, since the software has conflicts with my host OS RHEL7. So I thought installing as a Docker container could be a solution, even though I am completely new with Docker. My Dockerfile looks like below:

FROM ubuntu
COPY DragonflyInstaller /Dragonfly/
WORKDIR /Dragonfly/

# Dependent packages for Dragonfly
ARG DEBIAN_FRONTEND=noninteractive #
ENV TZ=Europe/Berlin
RUN apt-get update && apt-get install -y apt-utils \
                                         fontconfig \
                                         libxcb1 \
                                         libxcb-glx0 \
                                         x11-common \
                                         x11-apps \
                                         libx11-xcb-dev \
                                         libxrender1 \
                                         libxext6 \
                                         libxkbcommon-x11-0 \
                                         libglu1 \
                                         libxcb-xinerama0 \
                                         qt5-default \
                                         libxcb-icccm4 \
                                         libxcb-image0 \
                                         libxcb-render-util0 \
                                         libxcb-util1 \
                                         freeglut3-dev \
                                         python3-pip \
                                         xauth

CMD ./DragonflyInstaller

After building the corresponding Docker image, it cannot launch GUI based installer-window of Dragonfly. I am using the two following commands:

xhost +local:docker
sudo docker run -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix: dragonfly

I tried various suggestions posted on different forums, accordingly, I tried various arguments for docker run, however, I am getting two errors every time, as below:

No protocol specified
qt.qpa.xcb: could not connect to display :340.0
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: minimal, xcb.

Could you please suggest me how to resolve this issue?


问:
Unable to find replacement for `DisposeListener` class
Upgrading to 7.21.2 from 6.20.  Having trouble finding a callback that replaces the com.teamdev.jxbrowser.chromium.events.DisposeListener class.

答:
There is a BrowserClosed event to track when a particular browser is closed:

```<code>browser.on(BrowserClosed.class, event -> { System.out.println("Bye") });
</code>```

And EngineClosed to detect when the whole engine has been closed:

```<code>engine.on(EngineClosed.class, event -> {});
</code>```

Body:
There is a BrowserClosed event to track when a particular browser is closed:

browser.on(BrowserClosed.class, event -> { System.out.println("Bye") });

And EngineClosed to detect when the whole engine has been closed:

engine.on(EngineClosed.class, event -> {});


问:
Flaky cypress test with Svelte: Button is sometimes clicked, sometimes not
I am testing my SvelteKit site with Cypress. I sometimes experience flaky tests, similar to what has been described here: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/. In short, Cypress sometimes finds and clicks a button before the event listeners are attached - as a result, the click goes nowhere. The proposed solution is to simply re-try clicking until the appropriate listeners have been attached. That works in my case as well. However, though I do understand why this can be an issue in the example given in the blog post (it's a large calendar modal), I find it hard to justify that this issue arises when using a simple Svelte button.

Here is a simple example of a button that reveals some content when clicked:

<button
  on:click={() => {
    console.log('clicked');
    hide = false;
  }}>
  Show
</button>

Content

```
<p>The corresponding test sometimes passes, sometimes fails:</p>
<pre class="lang-js prettyprint-override"><code>it('reveals content on click', () => {
  cy.contains('Show').click();
  cy.contains('Content').should('be.visible');
});
</code>```

Again, I am aware this can be fixed by re-trying to click the button. And if this is what it takes to make Cypress work with Svelte/SvelteKit, then that's fine with me. But I am wondering: Why would this even be an issue?

Minimal reproduction repo: https://github.com/sophiamersmann/test-svelte-kit-cypress

答:
SvelteKit will by default do server side rendering (SSR), which means the complete HTML is sent to the browser, including the button. That HTML then needs to be hydrated afterwards to become interactive. This means that some code runs so that Svelte connects to the HTML that already exists. Cypress is likely "too fast" here and clicks the button before that hydration step is completed, therefore nothing happens.

It does not happen with pure Svelte because there's no SSR involved. There's a blank index.html page initially which is completely filled by Svelte's JavaScript inside the browser, so the moment the button is visible, the event listener and everything else is already initialized by Svelte.

Comparison by steps:

SvelteKit with SSR:

Go to page X

Page X is rendered on the server

Page X is sent to the browser, with the complete HTML

Svelte hydrates the HTML (Race condition with Cypress' click test)

Completed

Pure Svelte or SvelteKit without SSR:

Go to page X

Blank page is sent to the browser

Svelte constructs and initializes the HTML inside the browser (No race condition with Cypress' click test)

Completed

Body:
I am testing my SvelteKit site with Cypress. I sometimes experience flaky tests, similar to what has been described here: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/. In short, Cypress sometimes finds and clicks a button before the event listeners are attached - as a result, the click goes nowhere. The proposed solution is to simply re-try clicking until the appropriate listeners have been attached. That works in my case as well. However, though I do understand why this can be an issue in the example given in the blog post (it's a large calendar modal), I find it hard to justify that this issue arises when using a simple Svelte button.

Here is a simple example of a button that reveals some content when clicked:

<button
  on:click={() => {
    console.log('clicked');
    hide = false;
  }}>
  Show
</button>

Content

The corresponding test sometimes passes, sometimes fails:

it('reveals content on click', () => {
  cy.contains('Show').click();
  cy.contains('Content').should('be.visible');
});

Again, I am aware this can be fixed by re-trying to click the button. And if this is what it takes to make Cypress work with Svelte/SvelteKit, then that's fine with me. But I am wondering: Why would this even be an issue?

Minimal reproduction repo: https://github.com/sophiamersmann/test-svelte-kit-cypress


问:
Cannot add the value in the table
Here I am trying to add the values of proId and userId in the table whose values I am getting through post method from my android app and I have also checked it by assigning a value 5 directly to the variable (which I have commented out in the table ) but it is still adding 0 in the table.
The problem here is that it is not adding the value of userId in the table instead its adding only 0 there.
I have checked in the android code , the value being passed there is fine.
I think something is wrong in the php code.
Kindly share the solution.
Here I have attached my php file and the MySQL table.

```<code><?php
$pro= $_POST['proId'];
$user = $_POST['userId'];
//$user = 5;
include "config.php";

$check_sql = "SELECT * FROM `savedProducts` WHERE `proId` = '{$pro}' AND `userId` =
'{$user}'";
$result_check =mysqli_query($conn,$check_sql) or die("result failed");

if(mysqli_num_rows($result_check)>0){
echo "Added already";
}else{
$sql="INSERT INTO `$db`.`savedProducts` (`proId`,`userId`)
VALUES ('{$pro}','{$user}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "Added successfully";
}
?>
</code>```

答:
Maybe work this:</p>
```<code>$sql="INSERT INTO `savedProducts` (`proId`, `userId`) VALUES ('" . $pro . "', '" . $user . "')";
</code>```

Title: Cannot add the value in the table

Body:
Here I am trying to add the values of proId and userId in the table whose values I am getting through post method from my android app and I have also checked it by assigning a value 5 directly to the variable (which I have commented out in the table ) but it is still adding 0 in the table.
The problem here is that it is not adding the value of userId in the table instead its adding only 0 there.
I have checked in the android code , the value being passed there is fine.
I think something is wrong in the php code.
Kindly share the solution.
Here I have attached my php file and the MySQL table.

<?php
$pro= $_POST['proId'];
$user = $_POST['userId'];
//$user = 5;
include "config.php";

$check_sql = "SELECT * FROM `savedProducts` WHERE `proId` = '{$pro}' AND `userId` =
'{$user}'";
$result_check =mysqli_query($conn,$check_sql) or die("result failed");

if(mysqli_num_rows($result_check)>0){
echo "Added already";
}else{
$sql="INSERT INTO `$db`.`savedProducts` (`proId`,`userId`)
VALUES ('{$pro}','{$user}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "Added successfully";
}
?>

Body:
Maybe work this:

$sql="INSERT INTO `savedProducts` (`proId`, `userId`) VALUES ('" . $pro . "', '" . $user . "')";


问:
Flutter gridview fill remaining height on screen
For the life of me I am not able to get the gridview.count to use the available height.
I have tried with the MediaQuery.of(context).size.height and width and tried with SafeArea but no luck.

Everything is contained in a Column.
The black bar is a container with a set height of 150 pixels. The grayblue bar is also a container with a set height of 50 pixels.

code:

```<code>  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: [
            DefaultTextStyle(
              style: const TextStyle(color: Colors.white, fontSize: 40.0),
              child: Container(
                width: double.infinity,
                height: 120.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(results),
                  ),
                ),
                color: Colors.black,
              ),
            ),
            DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white54,
                fontSize: 5.0,
              ),
              child: Container(
                width: double.infinity,
                height: 50.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(history),
                  ),
                ),
                color: Colors.blueGrey,
              ),
            ),
            Expanded(
              child: GridView.count(
                padding: const EdgeInsets.all(2.0),
                crossAxisCount: 4,
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                children: List.generate(
                  chars.length,
                  (index) {
                    return Material(
                      color: Colors.blueAccent,
                      child: InkWell(
                        // splashColor: Colors.amber,
                        onTap: () {
                          setState(() {

                          });
                        },
                        child: Center(
                          child: Text(chars[index]),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
</code>```

答:
GridView children size depends on screen size.

Child size screenWidth/crossAxisCount and the default aspect ratio is 1 that's why default view is square.  I will prefer calculating height for GridView then provide available height on top two containers.

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.purpleAccent,
    body: LayoutBuilder(
      builder: (context, constraints) {
        const crossAxisCount = 4;

        final gridViewHeight =
            (constraints.maxWidth / crossAxisCount) * 5; //5 for rows

        final double heightWithoutGridView =
            constraints.maxHeight - gridViewHeight;

        return Column(
          children: [
            Container(
              width: constraints.maxWidth,
              height: heightWithoutGridView * .75,
              color: Colors.black,
            ),
            Container(
              width: constraints.maxWidth,
              height: heightWithoutGridView * .25,
              color: Colors.grey,
            ),
            Expanded(
              child: GridView.count(
                crossAxisCount: crossAxisCount,
                children: List.generate(
                  44,
                  (index) => Container(
                    color: Colors.amber,
                  ),
                ),
              ),
            )
          ],
        );
      },
    ),
  );
}
```

Body:
For the life of me I am not able to get the gridview.count to use the available height.
I have tried with the MediaQuery.of(context).size.height and width and tried with SafeArea but no luck.

Everything is contained in a Column.
The black bar is a container with a set height of 150 pixels. The grayblue bar is also a container with a set height of 50 pixels.

code:

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: [
            DefaultTextStyle(
              style: const TextStyle(color: Colors.white, fontSize: 40.0),
              child: Container(
                width: double.infinity,
                height: 120.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(results),
                  ),
                ),
                color: Colors.black,
              ),
            ),
            DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white54,
                fontSize: 5.0,
              ),
              child: Container(
                width: double.infinity,
                height: 50.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(history),
                  ),
                ),
                color: Colors.blueGrey,
              ),
            ),
            Expanded(
              child: GridView.count(
                padding: const EdgeInsets.all(2.0),
                crossAxisCount: 4,
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                children: List.generate(
                  chars.length,
                  (index) {
                    return Material(
                      color: Colors.blueAccent,
                      child: InkWell(
                        // splashColor: Colors.amber,
                        onTap: () {
                          setState(() {

                          });
                        },
                        child: Center(
                          child: Text(chars[index]),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }


问:
Error callback always fired, even when it is successful
There should be a glitch in my syntax, or something I haven't understood, but when I am doing a save method on my model. The error callback is called whatever the outcome of the method.

```<code>    @new_activity = new Activity()

    @new_activity.save
        know: $('input#know').val()
        learn: $('input#learn').val()

        success: -> console.log 'success'
        error: -> console.log 'error'
</code>```

In my case, since I do not really know whether the new_activity has effectively passed the validation, I have to do an ugly trick to add the activity to the collection. (By the way, I do not use the create method since I do want to have the different errors, and not a simple "false".

```<code>    if @new_activity.has('know') and @new_activity.has('learn')
        app.collections.activities.add @new_activity
</code>```

When it is successful though; there is an alert of the created model.

Edit: Further details.
Here is my model:
    initialize: ->
        _.bindAll @, 'validate', 'errorHandler'
        @.bind 'error', @errorHandler

```<code>validate: (attrs) ->
    errors = []
    # We only support a certain number of languages, we enforce that the user does not select a wrong set.
    if _.isEmpty(_.intersection([attrs.know], ['en', 'fr'])) is true
        errors.push 'This language is not currently supported.'

    if _.isEmpty(_.intersection([attrs.learn], ['en', 'fr', 'de', 'es', 'zh', 'pt', 'ar', 'ja', 'ru'])) is true
        errors.push 'You cannot learn this language yet.'

    if _.isEmpty(errors) is false
        errors

errorHandler: (model, error) ->
    console.log error
</code>```

When the validation occurs, and if the validate method returns nothing, it still triggers the error event, and the error variable contains the model (but no error message).

答:
I'm not sure what the cause of your error is, but I think I can help you pin it down:

Looking at the annotated source for Backbone.js, you can see that save() defers to sync(), which in turn defers to jQuery's $.ajax. So ultimately, your error function (wrapped by Backbone's wrapError) is called from that.

Unfortunately, the wrapper discards all but the jqXHR argument, making debugging a bit tricky. So you might want to try hacking your local Backbone.js source file to replace the existing wrapErrorfunction with something like this:

```<code>var wrapError = function(onError, model, options) {
    return function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
      if (onError) {
        onError(model, jqXHR, options);
      } else {
        model.trigger('error', model, jqXHR, options);
      }
    };
  };
</code>```

Then, at least, you'll see all of the debugging data provided by jQuery on your console.

Body:
There should be a glitch in my syntax, or something I haven't understood, but when I am doing a save method on my model. The error callback is called whatever the outcome of the method.

    @new_activity = new Activity()

    @new_activity.save
        know: $('input#know').val()
        learn: $('input#learn').val()

        success: -> console.log 'success'
        error: -> console.log 'error'

In my case, since I do not really know whether the new_activity has effectively passed the validation, I have to do an ugly trick to add the activity to the collection. (By the way, I do not use the create method since I do want to have the different errors, and not a simple "false".

    if @new_activity.has('know') and @new_activity.has('learn')
        app.collections.activities.add @new_activity

When it is successful though; there is an alert of the created model.

Edit: Further details.
Here is my model:
    initialize: ->
        _.bindAll @, 'validate', 'errorHandler'
        @.bind 'error', @errorHandler

validate: (attrs) ->
    errors = []
    # We only support a certain number of languages, we enforce that the user does not select a wrong set.
    if _.isEmpty(_.intersection([attrs.know], ['en', 'fr'])) is true
        errors.push 'This language is not currently supported.'

    if _.isEmpty(_.intersection([attrs.learn], ['en', 'fr', 'de', 'es', 'zh', 'pt', 'ar', 'ja', 'ru'])) is true
        errors.push 'You cannot learn this language yet.'

    if _.isEmpty(errors) is false
        errors

errorHandler: (model, error) ->
    console.log error

When the validation occurs, and if the validate method returns nothing, it still triggers the error event, and the error variable contains the model (but no error message).

Body:
I'm not sure what the cause of your error is, but I think I can help you pin it down:

Looking at the annotated source for Backbone.js, you can see that save() defers to sync(), which in turn defers to jQuery's $.ajax. So ultimately, your error function (wrapped by Backbone's wrapError) is called from that.

Unfortunately, the wrapper discards all but the jqXHR argument, making debugging a bit tricky. So you might want to try hacking your local Backbone.js source file to replace the existing wrapErrorfunction with something like this:

var wrapError = function(onError, model, options) {
    return function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
      if (onError) {
        onError(model, jqXHR, options);
      } else {
        model.trigger('error', model, jqXHR, options);
      }
    };
  };

Then, at least, you'll see all of the debugging data provided by jQuery on your console.


问:
WinUI 2.6 without UWP restrictions?
I want to write an application for Windows 11 (using WinUI 2.6) without all the restrictions of UWP, which seems to be the only way to write apps with WinUI 2.6. The idea is I want to be able to distribute the application on its own instead of in an app package, and I want it to be able to run external programs. I just can't figure out if it's possible, let alone how to do it.</p>

答:
WinUI 2 is only supported with UWP.
The next iteration of WinUI is WinUI3 and it uses the same UWP XAML.</p>

Title: WinUI 2.6 without UWP restrictions?


问:
How to correctly time speed of writing to a disk (i.e. file) in C
I have a Zynq SoC which runs a Linux system and would like to time the speed at which I can write to its SD card in C.

I have tried out clock() and clock_gettime() where for the latter, I have done the following:

```<code>#define BILLION 1000000000.0
#define BUFFER_SIZE 2097152
...

for (int i=0; i<100; i++) {
    memcpy(buf, channel->dma + offset, BUFFER_SIZE);

    /* Open file for output */
    FILE *f = fopen(path, "w");

    /* Start timer */
    clock_gettime(CLOCK_MONOTONIC, &start);

    /* Write data from cpu ram to sd card*/
    fwrite(buf, 1, BUFFER_SIZE, f);
    fclose(f);

    /* Stop timer and report result */
    clock_gettime(CLOCK_MONOTONIC, &end);
    elapsed_time = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / BILLION;
    printf("%lf seconds\n", elapsed_time);
}
</code>```

The times that I'm getting are around 0.019 seconds for 2097152 bytes which I believe is wrong because the speed of writing to the SD card is quoted as 10 MB/s and can't possibly be the 110 MB/s that I appear to be getting. When I, instead put the timing code outside the loop and, basically, time how long it takes to write the whole 100*BUFFER_SIZE, I get a more reasonable 18 MB/s.

My question is, is it incorrect to try to time a single fwrite operation? Does clock_gettime() not give me the adequate accuracy/precision for that? I would like to have the most accurate value possible for how quickly I can write to the disk because it is a very important parameter in the design of the system and so this discrepancy I'm getting is rather disconcerting.

答:
The Linux Kernel often caches read write access to disk storage. That is, it returns from the write call and does the actual writing in the background. It does that transparently, so that if you would read the same file, just after writing, you would get the results you wrote, even if they are not yet transferred and written completely to disk.

To force a complete write you can call the fsync function. It blocks until all file IO for a specific file has completed. In your case a call to

```<code>#include <unistd.h>

...
fwrite(...);
fsync(fileno(f));
</code>```

should suffice.

Edit

as @pmg mentioned in the comments, there is also be buffering at stream level. Although it probably is not that large of a buffer, you can force the stream buffer to be written with a call to fflush() before the fsync.

Body:
I have a Zynq SoC which runs a Linux system and would like to time the speed at which I can write to its SD card in C.

I have tried out clock() and clock_gettime() where for the latter, I have done the following:

#define BILLION 1000000000.0
#define BUFFER_SIZE 2097152
...

for (int i=0; i<100; i++) {
    memcpy(buf, channel->dma + offset, BUFFER_SIZE);

    /* Open file for output */
    FILE *f = fopen(path, "w");

    /* Start timer */
    clock_gettime(CLOCK_MONOTONIC, &start);

    /* Write data from cpu ram to sd card*/
    fwrite(buf, 1, BUFFER_SIZE, f);
    fclose(f);

    /* Stop timer and report result */
    clock_gettime(CLOCK_MONOTONIC, &end);
    elapsed_time = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / BILLION;
    printf("%lf seconds\n", elapsed_time);
}

The times that I'm getting are around 0.019 seconds for 2097152 bytes which I believe is wrong because the speed of writing to the SD card is quoted as 10 MB/s and can't possibly be the 110 MB/s that I appear to be getting. When I, instead put the timing code outside the loop and, basically, time how long it takes to write the whole 100*BUFFER_SIZE, I get a more reasonable 18 MB/s.

My question is, is it incorrect to try to time a single fwrite operation? Does clock_gettime() not give me the adequate accuracy/precision for that? I would like to have the most accurate value possible for how quickly I can write to the disk because it is a very important parameter in the design of the system and so this discrepancy I'm getting is rather disconcerting.

Body:
The Linux Kernel often caches read write access to disk storage. That is, it returns from the write call and does the actual writing in the background. It does that transparently, so that if you would read the same file, just after writing, you would get the results you wrote, even if they are not yet transferred and written completely to disk.

To force a complete write you can call the fsync function. It blocks until all file IO for a specific file has completed. In your case a call to

#include <unistd.h>

...
fwrite(...);
fsync(fileno(f));

should suffice.

Edit

as @pmg mentioned in the comments, there is also be buffering at stream level. Although it probably is not that large of a buffer, you can force the stream buffer to be written with a call to fflush() before the fsync.


答:
you can simply loop the array and print each character, and when (index +1) % 2 == 0 && i != list.size() -1, which means it is the 2rd,4th,6th,... element and not the last one, print an extra ,.

  public void printArray() {
        List<Character> list = new ArrayList<>(Arrays.asList('a', 'u', 'o', 'e'));
        System.out.print("Your Value: ");
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i));
            if ((i + 1) % 2 == 0 && i != list.size() - 1) {
                System.out.print(",");
            }
        }
    }
```

Title: Print per 2 char in java arraylist (non static arraylist)


问:
solana@web3.js / program transfer
I'm trying to have a simple program written in Solana that, on user approval, runs and transfers a given amount of SOL into the program's owner account.

From JS side I've this based on the HelloWorld example from Solana repo

```<code>        ...
        const secretKeyString = await fs.readFile(filePath, {encoding: 'utf8'});
        const secretKey = Uint8Array.from(JSON.parse(secretKeyString))
        const keypair = Keypair.fromSecretKey(secretKey)

        const instruction = new TransactionInstruction({
            keys: [
              {pubkey: publicKey, isSigner: false, isWritable: true}, // from wallet
              {pubkey: keypair.publicKey, isSigner: false, isWritable: true} // from json file, program owner
            ],
            programId,
            data: Buffer.alloc(0)
          });

        const transaction = new Transaction().add(instruction);
        signature = await sendTransaction(transaction, connection);
        //toast('Transaction Sent');
</code>```

On the program side I've simple used an example in a C example from Solana repo (no edit) - therefore assume all is good

```<code>/**
 * @brief A program demonstrating the transfer of lamports
 */
#include <solana_sdk.h>

extern uint64_t transfer(SolParameters *params) {
  // As part of the program specification the first account is the source
  // account and the second is the destination account
  if (params->ka_num != 2) {
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }
  SolAccountInfo *source_info = &params->ka[0];
  SolAccountInfo *destination_info = &params->ka[1];

  // Withdraw five lamports from the source
  *source_info->lamports -= 100000000;
  // Deposit five lamports into the destination
  *destination_info->lamports += 100000000;

  return SUCCESS;
}

extern uint64_t entrypoint(const uint8_t *input) {
  SolAccountInfo accounts[2];
  SolParameters params = (SolParameters){.ka = accounts};

  if (!sol_deserialize(input, &params, SOL_ARRAY_SIZE(accounts))) {
    return ERROR_INVALID_ARGUMENT;
  }

  return transfer(&params);
}
</code>```

However this keeps failing with error ´-32003 Transaction creation failed.`

答:
The system level SOL transfer has a constraint that the from PublicKey must be a system owned account. This means accounts owned by programs or PDA will fail as they are owned by your program. https://solanacookbook.com/references/accounts.html#transfer

The transfer of lamports that your code shows can only happen if the from PublicKey is a program owned account. https://solanacookbook.com/references/programs.html#transferring-lamports

Title: solana@web3.js / program transfer

Body:
I'm trying to have a simple program written in Solana that, on user approval, runs and transfers a given amount of SOL into the program's owner account.

From JS side I've this based on the HelloWorld example from Solana repo

        ...
        const secretKeyString = await fs.readFile(filePath, {encoding: 'utf8'});
        const secretKey = Uint8Array.from(JSON.parse(secretKeyString))
        const keypair = Keypair.fromSecretKey(secretKey)

        const instruction = new TransactionInstruction({
            keys: [
              {pubkey: publicKey, isSigner: false, isWritable: true}, // from wallet
              {pubkey: keypair.publicKey, isSigner: false, isWritable: true} // from json file, program owner
            ],
            programId,
            data: Buffer.alloc(0)
          });

        const transaction = new Transaction().add(instruction);
        signature = await sendTransaction(transaction, connection);
        //toast('Transaction Sent');

On the program side I've simple used an example in a C example from Solana repo (no edit) - therefore assume all is good

/**
 * @brief A program demonstrating the transfer of lamports
 */
#include <solana_sdk.h>

extern uint64_t transfer(SolParameters *params) {
  // As part of the program specification the first account is the source
  // account and the second is the destination account
  if (params->ka_num != 2) {
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }
  SolAccountInfo *source_info = &params->ka[0];
  SolAccountInfo *destination_info = &params->ka[1];

  // Withdraw five lamports from the source
  *source_info->lamports -= 100000000;
  // Deposit five lamports into the destination
  *destination_info->lamports += 100000000;

  return SUCCESS;
}

extern uint64_t entrypoint(const uint8_t *input) {
  SolAccountInfo accounts[2];
  SolParameters params = (SolParameters){.ka = accounts};

  if (!sol_deserialize(input, &params, SOL_ARRAY_SIZE(accounts))) {
    return ERROR_INVALID_ARGUMENT;
  }

  return transfer(&params);
}

However this keeps failing with error ´-32003 Transaction creation failed.`


问:
Horizontal Ray from all weekly closes
I am trying to achieve a horizontal ray from the weekly close of the past 52 weeks that can be seen on all time frames. The below appears to achieve this on the weekly time frame.

```<code>//@version=4
study("Open Ray to right", overlay=true)
higherTF1 = input("W", type=input.resolution)

dailyopen = security(syminfo.tickerid, higherTF1, open)

line1 = line.new(x1=bar_index[1], y1=dailyopen, x2=bar_index, y2=dailyopen,
xloc=xloc.bar_index, style=line.style_solid,extend=extend.right, color=color.green)
</code>```

It produces the following:

However it doesn't seem to have the amount amount on lower time frames such as on the 1h:

I can get this to work with the following:

```<code>study("PCL", overlay=true)

prev_daily_close = security(tickerid, "W", close[1])
plot(prev_daily_close, title="PCL", trackprice=false, style=circles)
</code>```

However the lines are plotted with circles rather than horizontal rays. I would like them to run extended across the chart.

Thanks in advance.

答:
```<code>//@version=5
indicator("Weekly closes", overlay = true, max_lines_count = 500)

num_weekly_closes = input.int(52, title = "Number of weekly closes", minval = 1, maxval = 500)

weekly_close = time_close == time_close("W") and barstate.isconfirmed

var line[] weekly_close_lines = array.new_line()

if weekly_close
    array.push(weekly_close_lines, line.new(x1 = bar_index, y1 = close, x2 = bar_index + 1, y2 = close, color = color.blue, width = 2))

if array.size(weekly_close_lines) > num_weekly_closes
    line.delete(array.shift(weekly_close_lines))

if array.size(weekly_close_lines) > 0
    for i = 0 to array.size(weekly_close_lines) - 1
        line.set_x2(array.get(weekly_close_lines, i), x = bar_index)
</code>```

Title: Horizontal Ray from all weekly closes

Body:
I am trying to achieve a horizontal ray from the weekly close of the past 52 weeks that can be seen on all time frames. The below appears to achieve this on the weekly time frame.

//@version=4
study("Open Ray to right", overlay=true)
higherTF1 = input("W", type=input.resolution)

dailyopen = security(syminfo.tickerid, higherTF1, open)

line1 = line.new(x1=bar_index[1], y1=dailyopen, x2=bar_index, y2=dailyopen,
xloc=xloc.bar_index, style=line.style_solid,extend=extend.right, color=color.green)

It produces the following:

However it doesn't seem to have the amount amount on lower time frames such as on the 1h:

I can get this to work with the following:

study("PCL", overlay=true)

prev_daily_close = security(tickerid, "W", close[1])
plot(prev_daily_close, title="PCL", trackprice=false, style=circles)

However the lines are plotted with circles rather than horizontal rays. I would like them to run extended across the chart.

Thanks in advance.


问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答:
I think everyone hits this "issue" when first working with generic classes.

Your first problem is hinted at in your question phrasing: an open generic type is NOT the base class to a closed one. There is no OO relationship here, at all. The real base class is CustomerBase. An "open" generic type is like a half-completed class; specifying type arguments "closes" it, making it complete.

While you can do:

```<code>Type t = typeof(CustomerWithChildern<>)
</code>```

the condition

```<code>typeof(CustomerWithChildern<>).IsAssignableFrom(CustomerWithChildern<Foo>)
</code>```

will always be False.

-Oisin

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

Body:
I think everyone hits this "issue" when first working with generic classes.

Your first problem is hinted at in your question phrasing: an open generic type is NOT the base class to a closed one. There is no OO relationship here, at all. The real base class is CustomerBase. An "open" generic type is like a half-completed class; specifying type arguments "closes" it, making it complete.

While you can do:

Type t = typeof(CustomerWithChildern<>)

the condition

typeof(CustomerWithChildern<>).IsAssignableFrom(CustomerWithChildern<Foo>)

will always be False.

-Oisin


问:
PLINQ vs Sync Over Async: what is the difference?
I love PLINQ.  In all of my test cases on various parallelization patterns, it performs well and consistently.  But I recently ran into a question that has me a little bothered: what is the functional difference between these two examples?  What, hopefully if anything, qualifies the PLINQ example to not be similar or equivalent to the following anti-pattern?

PLINQ:

```<code>public int PLINQSum()
{
    return Enumerable.Range(0, N)
        .AsParallel()
        .Select((x) => x + 1)
        .Sum();
}
</code>```

Sync over async:

```<code>public int AsyncSum()
{
    var tasks = Enumerable.Range(0, N)
        .Select((x) => Task.Run(() => x + 1));

    return Task.WhenAll(tasks).Result.Sum();
}
</code>```

答:
The AsyncSum method is not an example of Sync over Async. It is an example of using the Task.Run method with the intention of parallelizing a calculation. You might think that Task = async, but it's not. The Task class was introduced with the .NET Framework 4.0 in 2010, as part of the Task Parallel Library, two years before the advent of the async/await technology with the  .NET Framework 4.5 in 2012.

What is Sync over Async: We use this term to describe a situation where an asynchronous API is invoked and then waited synchronously, causing a thread to be blocked until the completion of the asynchronous operation. It is implied that the asynchronous API has a truly asynchronous implementation, meaning that it uses no thread while the operation is in-flight. Most, but not all, of the asynchronous APIs that are built-in the .NET platform have truly asynchronous implementations.

The two examples in your question are technically different, but not because one of them is Sync over Async. None of them is. Both are parallelizing a synchronous operation (the mathematical addition x + 1), that cannot be performed without utilizing the CPU. And when we use the CPU, we use a thread.

Characterizing the AsyncSum method as anti-pattern might be fair, but not because it is Sync over Async. You might want to call it anti-pattern because:

It allocates and schedules a Task for each number in the sequence, incurring a gigantic overhead compared to the tiny computational work that has to be performed.

It saturates the ThreadPool for the whole duration of the parallel operation.

It forces the ThreadPool to create additional threads, resulting in oversubscription (more threads than CPUs). This results in the operating system having more work to do (switching between threads).

It has bad behavior in case of exceptions. Instead of stopping the operation as soon as possible after an error has occurred, it will invoke the lambda invariably for all elements in the sequence. As a result you'll have to wait for longer until you observe the error, and finally you might observe a huge number of errors.

It doesn't utilize the current thread. The current thread is blocked doing nothing, while all the work is done by ThreadPool threads. In comparison the PLINQ utilizes the current thread as one of its worker threads. This is something that you could also do manually, by creating some of the tasks with the Task constructor (instead of Task.Run), and then use the RunSynchronously method in order to run them on the current thread, while the rest of the tasks are scheduled on the ThreadPool.

```<code>var task1 = new Task<int>(() => 1 + 1); // Cold task
var task2 = Task.Run(() => 2 + 2); // Hot task scheduled on the ThreadPool
task1.RunSynchronously(); // Run the cold task on the current thread
int sum = Task.WhenAll(task1, task2).Result.Sum(); // Wait both tasks
</code>```

The name AsyncSum itself is inappropriate, since there is nothing asynchronous happening inside this method. A better name could be WhenAll_TaskRun_Sum.

Body:
I love PLINQ.  In all of my test cases on various parallelization patterns, it performs well and consistently.  But I recently ran into a question that has me a little bothered: what is the functional difference between these two examples?  What, hopefully if anything, qualifies the PLINQ example to not be similar or equivalent to the following anti-pattern?

PLINQ:

public int PLINQSum()
{
    return Enumerable.Range(0, N)
        .AsParallel()
        .Select((x) => x + 1)
        .Sum();
}

Sync over async:

public int AsyncSum()
{
    var tasks = Enumerable.Range(0, N)
        .Select((x) => Task.Run(() => x + 1));

    return Task.WhenAll(tasks).Result.Sum();
}

Body:
The AsyncSum method is not an example of Sync over Async. It is an example of using the Task.Run method with the intention of parallelizing a calculation. You might think that Task = async, but it's not. The Task class was introduced with the .NET Framework 4.0 in 2010, as part of the Task Parallel Library, two years before the advent of the async/await technology with the  .NET Framework 4.5 in 2012.

What is Sync over Async: We use this term to describe a situation where an asynchronous API is invoked and then waited synchronously, causing a thread to be blocked until the completion of the asynchronous operation. It is implied that the asynchronous API has a truly asynchronous implementation, meaning that it uses no thread while the operation is in-flight. Most, but not all, of the asynchronous APIs that are built-in the .NET platform have truly asynchronous implementations.

The two examples in your question are technically different, but not because one of them is Sync over Async. None of them is. Both are parallelizing a synchronous operation (the mathematical addition x + 1), that cannot be performed without utilizing the CPU. And when we use the CPU, we use a thread.

Characterizing the AsyncSum method as anti-pattern might be fair, but not because it is Sync over Async. You might want to call it anti-pattern because:

It allocates and schedules a Task for each number in the sequence, incurring a gigantic overhead compared to the tiny computational work that has to be performed.

It saturates the ThreadPool for the whole duration of the parallel operation.

It forces the ThreadPool to create additional threads, resulting in oversubscription (more threads than CPUs). This results in the operating system having more work to do (switching between threads).

It has bad behavior in case of exceptions. Instead of stopping the operation as soon as possible after an error has occurred, it will invoke the lambda invariably for all elements in the sequence. As a result you'll have to wait for longer until you observe the error, and finally you might observe a huge number of errors.

It doesn't utilize the current thread. The current thread is blocked doing nothing, while all the work is done by ThreadPool threads. In comparison the PLINQ utilizes the current thread as one of its worker threads. This is something that you could also do manually, by creating some of the tasks with the Task constructor (instead of Task.Run), and then use the RunSynchronously method in order to run them on the current thread, while the rest of the tasks are scheduled on the ThreadPool.

var task1 = new Task<int>(() => 1 + 1); // Cold task
var task2 = Task.Run(() => 2 + 2); // Hot task scheduled on the ThreadPool
task1.RunSynchronously(); // Run the cold task on the current thread
int sum = Task.WhenAll(task1, task2).Result.Sum(); // Wait both tasks

The name AsyncSum itself is inappropriate, since there is nothing asynchronous happening inside this method. A better name could be WhenAll_TaskRun_Sum.


问:
Flutter - How can I print all my data (fields) from firebase documents?
I would like to show all the fields of a document in firebase, but I'm having different troubles.

My intention is to show the info like a chat. I tried with a ListView.builder inside a StreamBuilder.

This is my Firestore document:

I managed to get the horizontal information using doc.data().toString but what I am trying to do is to get the whole information as a ListTile so when I add new messages they are automatically added to the ListView.builder.

This is my current code:

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class ChatScreen extends StatefulWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.only(left: 20.0),
        child: StreamBuilder(
            stream:
                FirebaseFirestore.instance.collection("messages").snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) {
                return Center(child: CircularProgressIndicator());
              }
              return ListView.builder(
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot doc = snapshot.data!.docs[index];
                  return ListTile(
                    title: Text(doc.data().toString()),
                  );
                },
              );
            }),
      ),
    );
  }
}
</code>```

And this is what I get with my current code: DeviceImage

P.S. I can get the data manually if I use this but it's not what I want:

```<code>return ListTile(
                    title: Text(doc['sender']),
                  );
</code>```

答:
Try to use an Object like below.</p>
```<code>class Message {
  final String sender;
  final String text;

  const Message({
    required this.sender,
    required this.text,
  });

  Map<String, dynamic> toMap() {
    return {
      'sender': sender,
      'text': text,
    };
  }

  factory Message.fromMap(Map<String, dynamic> map) {
    return Message(
      sender: map['sender'] as String,
      text: map['text'] as String,
    );
  }
}

class ChatScreen extends StatelessWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Message>>(
        stream: FirebaseFirestore.instance
            .collection("messages")
            .snapshots()
            .map((query) =>
                query.docs.map((map) => Message.fromMap(map.data())).toList()),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          final msgList = snapshot.data!;
          return ListView.builder(
            itemCount: msgList.length,
            itemBuilder: (context, index) {
              final message = msgList[index];
              return ListTile(
                title: Text(message.text),
                leading: Text(message.sender),
              );
            },
          );
        });
  }
}
</code>```

Body:
I would like to show all the fields of a document in firebase, but I'm having different troubles.

My intention is to show the info like a chat. I tried with a ListView.builder inside a StreamBuilder.

This is my Firestore document:

I managed to get the horizontal information using doc.data().toString but what I am trying to do is to get the whole information as a ListTile so when I add new messages they are automatically added to the ListView.builder.

This is my current code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class ChatScreen extends StatefulWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.only(left: 20.0),
        child: StreamBuilder(
            stream:
                FirebaseFirestore.instance.collection("messages").snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) {
                return Center(child: CircularProgressIndicator());
              }
              return ListView.builder(
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot doc = snapshot.data!.docs[index];
                  return ListTile(
                    title: Text(doc.data().toString()),
                  );
                },
              );
            }),
      ),
    );
  }
}

And this is what I get with my current code: DeviceImage

P.S. I can get the data manually if I use this but it's not what I want:

return ListTile(
                    title: Text(doc['sender']),
                  );

Body:
Try to use an Object like below.

class Message {
  final String sender;
  final String text;

  const Message({
    required this.sender,
    required this.text,
  });

  Map<String, dynamic> toMap() {
    return {
      'sender': sender,
      'text': text,
    };
  }

  factory Message.fromMap(Map<String, dynamic> map) {
    return Message(
      sender: map['sender'] as String,
      text: map['text'] as String,
    );
  }
}

class ChatScreen extends StatelessWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Message>>(
        stream: FirebaseFirestore.instance
            .collection("messages")
            .snapshots()
            .map((query) =>
                query.docs.map((map) => Message.fromMap(map.data())).toList()),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          final msgList = snapshot.data!;
          return ListView.builder(
            itemCount: msgList.length,
            itemBuilder: (context, index) {
              final message = msgList[index];
              return ListTile(
                title: Text(message.text),
                leading: Text(message.sender),
              );
            },
          );
        });
  }
}


答:
You can create a static map instead of the switch-case.

```<code>private static final Map<SearchableFields,Supplier<String>> searchableFieldsToFieldPojo = Map.of(
    ALL, this::retrieveAll,
    FIELD1, FieldPojo::retrieveAll
    );
</code>```

And then you can access via:

```<code>searchableFieldsToFieldPojo.get(selectedField).get();
</code>```

Title: Call specific method on object depending on selected enum value

Body:
Let's assume we have an enum, that represents searchable fields:

enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}

This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.

Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.

class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:

private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}

This does work, however I feel like it's clunky.

Question:

Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)

Body:
You can create a static map instead of the switch-case.

private static final Map<SearchableFields,Supplier<String>> searchableFieldsToFieldPojo = Map.of(
    ALL, this::retrieveAll,
    FIELD1, FieldPojo::retrieveAll
    );

And then you can access via:

searchableFieldsToFieldPojo.get(selectedField).get();


问:
Programming using NVDA screen reader
I want NVDA to speak out whenever I start a for loop in my python code. How can I do this programmatically as an addon? Any kind of help appreciated.

For instance,
I type in the text editor:

for i in range(0,3):
print "hello world"

As soon as I am done writing for, NVDA should speak out that the for loop has started.

答: While you might need to work with a specific TTS module of some sorts, to produce spoken output, a trick I use to let me know when tasks/activities have finished off in background is to use print(chr(7)) - evokes windows default beep sound, if you are working under windows, but, presume you are if you mention using NVDA - I use it myself, currently under windows 10</p>

Title: Programming using NVDA screen reader


问:
C# Entity Framework Core: unable to resolve service
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>
</code>```

My DbContext:

```<code>internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}
</code>```

My user table:

```<code>internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}
</code>```

Here is my Program.cs (im using net6 so i dont have a startup.cs)

```<code>//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
</code>```

答:
im using net6 so i dont have a startup.cs

This is the root cause of the problem. From Design-time DbContext Creation documentation topic, even though not stated explicitly, looks like that "minimal API" style code is not supported, since they still need a special method

public static IHostBuilder CreateHostBuilder(string[] args)
```

in the Program class. Hence most likely you need to move most of your code (between CreateBuilder(args) and .Build()) into a method with the above signature. Or use other methods of creating db context at design time, for instance From a design-time factory and somehow get the settings needed to create the db context. I guess refactoring the startup code would be easier.

There is a (closed?!) issue on EF Core GitHub issue tracker - #3557: How to access to WebHostBuilder in Design-time DbContext Creation with top-level statements?. I posted a comment there asking for updating the documentation and providing an example for "minimal API" projects, and included a link to your question. You can watch EF Core team responses there and eventually see what is their vision on the subject.

Body:
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

My DbContext:

internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}

My user table:

internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}

Here is my Program.cs (im using net6 so i dont have a startup.cs)

//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Body:
im using net6 so i dont have a startup.cs

This is the root cause of the problem. From Design-time DbContext Creation documentation topic, even though not stated explicitly, looks like that "minimal API" style code is not supported, since they still need a special method

public static IHostBuilder CreateHostBuilder(string[] args)

in the Program class. Hence most likely you need to move most of your code (between CreateBuilder(args) and .Build()) into a method with the above signature. Or use other methods of creating db context at design time, for instance From a design-time factory and somehow get the settings needed to create the db context. I guess refactoring the startup code would be easier.

There is a (closed?!) issue on EF Core GitHub issue tracker - #3557: How to access to WebHostBuilder in Design-time DbContext Creation with top-level statements?. I posted a comment there asking for updating the documentation and providing an example for "minimal API" projects, and included a link to your question. You can watch EF Core team responses there and eventually see what is their vision on the subject.


问:
How to combine two tables into one using my sql statement
i'm new in Database, i want to get a result from both sql table.
Here is the example

Table 1

Item Code
Price

A001
5 Dollar

A002
6 Dollar

Table 2 - Item Code Information

Item Code
Item Description

A001
Fish

A002
Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code
Item Description
Price

A001
Fish
5 Dollar

A002
Chicken
6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

答:
Use join if you want to combine 2 or more table with sql.

```<code>SELECT Table1.itemcode, Table1.price, Table2.itemdescription FROM Table1 JOIN Tabel2 on Tabel1.itemcode = Tabel2.itemcode;
</code>```

where

```<code>SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key;
</code>```

if you want to combine 3 then just add another join

```<code>SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key JOIN third_table_name on table_name.primary_key = third_table_name.foreign_key;
</code>```

Body:
Use join if you want to combine 2 or more table with sql.

SELECT Table1.itemcode, Table1.price, Table2.itemdescription FROM Table1 JOIN Tabel2 on Tabel1.itemcode = Tabel2.itemcode;

where

SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key;

if you want to combine 3 then just add another join

SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key JOIN third_table_name on table_name.primary_key = third_table_name.foreign_key;


问:
Is this the correct way to save form values in MVC3?
Here's my code:

```<code>[HttpGet]
public ActionResult Register()
{
    RegisterViewModel model = new RegisterViewModel();
    using (CityRepository city = new CityRepository())
    {
        model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
    }

    using (CountryRepository country = new CountryRepository())
    {
        model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
    }

    return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        //Actually register the user here.
        RedirectToAction("Index", "Home");
    }

    //Something went wrong, redisplay the form for correction.
    return View(model);
}
</code>```

Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.

Anything here that screams out at you as wrong?

答:
Advised changes to [HttpGet]:

```<code>[HttpGet]
public ActionResult Register()
{
    // Get
    var cities = new List<City>();
    var countries = new List<Country>();

    using (CityRepository city = new CityRepository())
    {
       cities = city.FindAllCities().ToList();
    }

    using (CountryRepository country = new CountryRepository())
    {
       counties = country.FindAllCountries().ToList();
    }

    // Map.
    var aggregatedObjects = new SomePOCO(cities, countries);
    var model = Mapper.Map<SomePOCO,RegisterViewModel>(aggregatedObjects );

    // Return
    return View(model);
}
</code>```

Summary of changes:

Layout your logic in such a way the controller's job makes sense. Get - Map - Return. Exactly the tasks (in order) for which a Controller is designed for.

Use AutoMapper to do the heavy lifting of ViewModel creation for you.

Advised changes to your [HttpPost]:

```<code>[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (!ModelState.IsValid)
      return View(model);

    try
    {
       var dbObj = Mapper.Map<RegisterViewModel,SomeDomainObj>(model);
       _repository.Save(dbObj);
       return RedirectToAction("Index");
    }
    catch (Exception exc)
    {
       if (exc is BusinessError)
          ModelState.AddModelError("SomeKey", ((BusinessError)exc).FriendlyError);
       else
          ModelState.AddModelError("SomeKey", Resources.Global.GenericErrorMessage);
    }

    return View(model);
}
</code>```

Summary of changes:

Try/catch. Always need to capture exceptions, whether they are domain exceptions or lower-level (database ones)

Check ModelState validity first. As @Cymen says - do it first so you don't forget later

Add exceptions to ModelState. Use custom exception classes for business errors with descriptive, resource-based messages. If the error is too low-level for the user (foreign key constraint, etc), show a generic message

Body:
Here's my code:

[HttpGet]
public ActionResult Register()
{
    RegisterViewModel model = new RegisterViewModel();
    using (CityRepository city = new CityRepository())
    {
        model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
    }

    using (CountryRepository country = new CountryRepository())
    {
        model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
    }

    return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        //Actually register the user here.
        RedirectToAction("Index", "Home");
    }

    //Something went wrong, redisplay the form for correction.
    return View(model);
}

Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.

Anything here that screams out at you as wrong?

Body:
Advised changes to [HttpGet]:

[HttpGet]
public ActionResult Register()
{
    // Get
    var cities = new List<City>();
    var countries = new List<Country>();

    using (CityRepository city = new CityRepository())
    {
       cities = city.FindAllCities().ToList();
    }

    using (CountryRepository country = new CountryRepository())
    {
       counties = country.FindAllCountries().ToList();
    }

    // Map.
    var aggregatedObjects = new SomePOCO(cities, countries);
    var model = Mapper.Map<SomePOCO,RegisterViewModel>(aggregatedObjects );

    // Return
    return View(model);
}

Summary of changes:

Layout your logic in such a way the controller's job makes sense. Get - Map - Return. Exactly the tasks (in order) for which a Controller is designed for.

Use AutoMapper to do the heavy lifting of ViewModel creation for you.

Advised changes to your [HttpPost]:

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (!ModelState.IsValid)
      return View(model);

    try
    {
       var dbObj = Mapper.Map<RegisterViewModel,SomeDomainObj>(model);
       _repository.Save(dbObj);
       return RedirectToAction("Index");
    }
    catch (Exception exc)
    {
       if (exc is BusinessError)
          ModelState.AddModelError("SomeKey", ((BusinessError)exc).FriendlyError);
       else
          ModelState.AddModelError("SomeKey", Resources.Global.GenericErrorMessage);
    }

    return View(model);
}

Summary of changes:

Try/catch. Always need to capture exceptions, whether they are domain exceptions or lower-level (database ones)

Check ModelState validity first. As @Cymen says - do it first so you don't forget later

Add exceptions to ModelState. Use custom exception classes for business errors with descriptive, resource-based messages. If the error is too low-level for the user (foreign key constraint, etc), show a generic message


问:
Can I save register values inside of ISR code?
I am new to OS interrupts and wondering why do we need to save all the register values before going into ISR? Can we write the code to save register values inside of ISR code so that the register values can just get pushed to the stack by ISR's own code?</p>

答: Answer is clear,it will be to complex to add a part of code to save context before every ISR and restore it.It's easy to reuse every code by macro.Surely,when you write a ISR,you'd rather use C than ASM.But when you using a C code,every action expected depends on your complier, it means that C code will do more than you write.</p>


问:
AWS step function state transition failure
AWS step function execution guarantees tells that "The execution state is internally persisted on every state transition.".

What happens when the ProcessPayment lambda function succeeded but the state transition to UpdateCustomerAccount failed due to an internal AWS error?

I would appreciate to pointing me to the corresponding step function documentation.

答:
Step Functions does not fail on state transitions. If there are issues, the scheduling of the next state might get delayed, but step functions will always eventually schedule and run the next state.

The work done by each state might fail, such as failing to complete the work, fail to send/receive request, etc, but there will never be an error due to a state transition failing.


问:
How to compose a psycopg2 dynamic SQL statement that includes functions on column names? e.g.: json_col::text
I need to compose a dynamic SQL statement, which includes certain functions on column names.
E.g.: SELECT json_col::text, SUBSTRING ( string_col ,1 , 2 ) FROM TABLE

Since the column names are enclosed in "", I keep getting undefined column error.
What is the best way to compose a dynamic SQL with functions on column names?

答:
You could add the the SQL functions to your SQL statement:

```<code>cols = ["column1", "column2", "column3"]
table = "myTable"
query = sql.SQL(
    "select {0}::text, upper({1}), lower({2}), {3}::jsonb from {4} where id = %s").format(
        sql.Identifier("id"),
        sql.Identifier(cols[0]),
        sql.Identifier(cols[1]),
        sql.Identifier(cols[2]),
        sql.Identifier(table)
)
print(cur.mogrify(query, (240, )).decode('utf-8'))
</code>```

Out:

```<code>select "id"::text, upper("column1"), lower("column2"), "column3"::jsonb from "myTable" where id = 240
</code>```

Body:
You could add the the SQL functions to your SQL statement:

cols = ["column1", "column2", "column3"]
table = "myTable"
query = sql.SQL(
    "select {0}::text, upper({1}), lower({2}), {3}::jsonb from {4} where id = %s").format(
        sql.Identifier("id"),
        sql.Identifier(cols[0]),
        sql.Identifier(cols[1]),
        sql.Identifier(cols[2]),
        sql.Identifier(table)
)
print(cur.mogrify(query, (240, )).decode('utf-8'))

Out:

select "id"::text, upper("column1"), lower("column2"), "column3"::jsonb from "myTable" where id = 240


问:
SIGCHILD signal in java
I create a child process using 'Runtime.getRuntime().exec()' in java and want to detect when child process exits. so i want to know  is there any signal like 'SIGCHILD' in posix?</p>

答: No, not precisely. You can call Process.waitFor() to wait for the process to exit. If you did that from a dedicated thread, however, that would be quite similar to a signal handler. Alternatively, a more expensive method is to poll Process.exitValue(), which will throw an exception until the child has actually exited.

Title: SIGCHILD signal in java


问:
unable to find data in examples dashboard in apache superset
I just started working on apache superset. I wanted to try the example dataset that superset was offering. i ran the command

```<code>superset load_examples
</code>```

in the virtual environment. The execution->

```<code>No PIL installation found
2022-02-03 16:41:54,811:INFO:superset.utils.screenshots:No PIL installation found
Loading examples metadata and related data into examples
Creating default CSS templates
Loading [World Bank's Health Nutrition and Population Stats]
Creating table [World Bank Health Data] reference
Creating a World's Health Bank dashboard
Loading [Birth names]
Creating some slices
Creating a dashboard
Loading [Random long/lat data]
Creating table reference
Creating a slice
Loading [Country Map data]
Creating table reference
Creating a slice
Loading [San Francisco population polygons]
Creating table San Francisco Population Polygons reference
Loading [Flights data]
Done loading table!
Loading [BART lines]
Creating table San Franciso BART Lines reference
Loading [Multi Line]
Creating table [World Bank Health Data] reference
Creating a World's Health Bank dashboard
Creating some slices
Creating a dashboard
Loading [Misc Charts] dashboard
Creating the dashboard
Loading DECK.gl demo
Loading deck.gl dashboard
Creating Scatterplot slice
Creating Screen Grid slice
Creating Hex slice
Creating Grid slice
Creating Polygon slice
Creating Arc slice
Creating Path slice
Creating a dashboard
</code>```

Seems like it installed without any problems. Now when i go to my superset dashboard, i find  World Bank's Data i click on it, and all the charts say

```<code>No results were returned for this query. If you expected results to be returned, ensure any filters are configured properly and the datasource contains data for the selected time range.
</code>```

Then i check all the example dashboards, all of them have the same written on them.
I dont know what could be the issue. Can someone help?

答:
Run superset fab create-admin and create a user with Username(admin) to be able to load the examples.
Then superset init after load_examples

Body:
I just started working on apache superset. I wanted to try the example dataset that superset was offering. i ran the command

superset load_examples

in the virtual environment. The execution->

No PIL installation found
2022-02-03 16:41:54,811:INFO:superset.utils.screenshots:No PIL installation found
Loading examples metadata and related data into examples
Creating default CSS templates
Loading [World Bank's Health Nutrition and Population Stats]
Creating table [World Bank Health Data] reference
Creating a World's Health Bank dashboard
Loading [Birth names]
Creating some slices
Creating a dashboard
Loading [Random long/lat data]
Creating table reference
Creating a slice
Loading [Country Map data]
Creating table reference
Creating a slice
Loading [San Francisco population polygons]
Creating table San Francisco Population Polygons reference
Loading [Flights data]
Done loading table!
Loading [BART lines]
Creating table San Franciso BART Lines reference
Loading [Multi Line]
Creating table [World Bank Health Data] reference
Creating a World's Health Bank dashboard
Creating some slices
Creating a dashboard
Loading [Misc Charts] dashboard
Creating the dashboard
Loading DECK.gl demo
Loading deck.gl dashboard
Creating Scatterplot slice
Creating Screen Grid slice
Creating Hex slice
Creating Grid slice
Creating Polygon slice
Creating Arc slice
Creating Path slice
Creating a dashboard

Seems like it installed without any problems. Now when i go to my superset dashboard, i find  World Bank's Data i click on it, and all the charts say

No results were returned for this query. If you expected results to be returned, ensure any filters are configured properly and the datasource contains data for the selected time range.

Then i check all the example dashboards, all of them have the same written on them.
I dont know what could be the issue. Can someone help?