问:
Draw line within `text` attribute of a `QAction`
I have several QAction entries in a QMenu, each representing a color. Before the name of the respective color a short line in the respective color should be drawn.

For the implementation I thought about using Qt Style Sheets, but I didn't get far. How can this be implemented?

main.py

```<code>import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QActionGroup, QAction
from PyQt5.uic import loadUi

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        loadUi("mainwindow.ui", self)

        colors = ("blue", "green", "yellow", "orange", "red")

        group = QActionGroup(self.menuColor)
        for color in colors:
            text = f"<short {color} line>\t{color.capitalize()}"
            action = QAction(text, self)
            action.setCheckable(True)
            group.addAction(action)
            self.menuColor.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered)

    def onTriggered(self, action):
        print(action.text())

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

mainwindow.ui

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Colors</string>
  </property>
  <property name="locale">
   <locale language="English" country="UnitedKingdom"/>
  </property>
  <widget class="QWidget" name="centralwidget"/>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>26</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuMenu">
    <property name="title">
     <string>Menu</string>
    </property>
    <widget class="QMenu" name="menuColor">
     <property name="title">
      <string>Color</string>
     </property>
    </widget>
    <addaction name="menuColor"/>
   </widget>
   <addaction name="menuMenu"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
</code>```

答:
QActions cannot be uniquely stylized with stylesheets, and they only use plain text, not rich text (meaning that html tags are not supported).

The best solution is to create an icon for each action, based on the provided color:

```<code>from PyQt5.QtWidgets import (QApplication, QMainWindow, QActionGroup,
    QAction, QStyle)
from PyQt5.QtGui import QPixmap, QPainter, QColor, QIcon
from PyQt5.QtCore import Qt
from PyQt5.uic import loadUi

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        loadUi("mainwindow.ui", self)

        colors = ("blue", "green", "yellow", "orange", "red")

        group = QActionGroup(self.menuColor)
        # get the default size of a small icon, which is usually used for icons
        # in standard menu items
        size = self.style().pixelMetric(QStyle.PM_SmallIconSize)

        for color in colors:
            # create a pixmap based on the default size
            pm = QPixmap(size, size)
            # "clear" its content (this is *very* important, otherwise the pixmap
            # will use random data based on memory dump
            pm.fill(Qt.transparent)
            # create a QPainter for the pixmap, set the pen color and draw a line
            # placed in the middle using that color
            qp = QPainter(pm)
            qp.setPen(QColor(color))
            qp.drawLine(0, size / 2, size, size / 2)
            # end painting on the pixmap, this is important also!
            qp.end()
            # create the action with an icon based on the pixmap
            action = QAction(QIcon(pm), color, self)
            action.setCheckable(True)
            group.addAction(action)
            self.menuColor.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered)
</code>```

And this is the result:

Note that QColor(str) uses the SVG color name specification, like setNamedColor() does; this is important, as some colors don't match Qt Global Colors: for example, Qt green (QtCore.Qt.green) is rgb(0, 255, 0) (which is lime for SVG), while SVG green is rgb(0, 128, 0) (which is Qt's QtCore.Qt.darkGreen).

Body:
I have several QAction entries in a QMenu, each representing a color. Before the name of the respective color a short line in the respective color should be drawn.

For the implementation I thought about using Qt Style Sheets, but I didn't get far. How can this be implemented?

main.py

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QActionGroup, QAction
from PyQt5.uic import loadUi

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        loadUi("mainwindow.ui", self)

        colors = ("blue", "green", "yellow", "orange", "red")

        group = QActionGroup(self.menuColor)
        for color in colors:
            text = f"<short {color} line>\t{color.capitalize()}"
            action = QAction(text, self)
            action.setCheckable(True)
            group.addAction(action)
            self.menuColor.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered)

    def onTriggered(self, action):
        print(action.text())

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

mainwindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Colors</string>
  </property>
  <property name="locale">
   <locale language="English" country="UnitedKingdom"/>
  </property>
  <widget class="QWidget" name="centralwidget"/>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>26</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuMenu">
    <property name="title">
     <string>Menu</string>
    </property>
    <widget class="QMenu" name="menuColor">
     <property name="title">
      <string>Color</string>
     </property>
    </widget>
    <addaction name="menuColor"/>
   </widget>
   <addaction name="menuMenu"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Body:
QActions cannot be uniquely stylized with stylesheets, and they only use plain text, not rich text (meaning that html tags are not supported).

The best solution is to create an icon for each action, based on the provided color:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QActionGroup,
    QAction, QStyle)
from PyQt5.QtGui import QPixmap, QPainter, QColor, QIcon
from PyQt5.QtCore import Qt
from PyQt5.uic import loadUi

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        loadUi("mainwindow.ui", self)

        colors = ("blue", "green", "yellow", "orange", "red")

        group = QActionGroup(self.menuColor)
        # get the default size of a small icon, which is usually used for icons
        # in standard menu items
        size = self.style().pixelMetric(QStyle.PM_SmallIconSize)

        for color in colors:
            # create a pixmap based on the default size
            pm = QPixmap(size, size)
            # "clear" its content (this is *very* important, otherwise the pixmap
            # will use random data based on memory dump
            pm.fill(Qt.transparent)
            # create a QPainter for the pixmap, set the pen color and draw a line
            # placed in the middle using that color
            qp = QPainter(pm)
            qp.setPen(QColor(color))
            qp.drawLine(0, size / 2, size, size / 2)
            # end painting on the pixmap, this is important also!
            qp.end()
            # create the action with an icon based on the pixmap
            action = QAction(QIcon(pm), color, self)
            action.setCheckable(True)
            group.addAction(action)
            self.menuColor.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered)

And this is the result:

Note that QColor(str) uses the SVG color name specification, like setNamedColor() does; this is important, as some colors don't match Qt Global Colors: for example, Qt green (QtCore.Qt.green) is rgb(0, 255, 0) (which is lime for SVG), while SVG green is rgb(0, 128, 0) (which is Qt's QtCore.Qt.darkGreen).


来源: stackexchange

问:
fatal: unknown value for config 'protocol.version': 2
I decided to turn on Git protocol 2nd ver (I suppose it's faster, noiseless), so I did:

```<code>git config --global protocol.version 2
</code>```

But when I try

```<code>git pull
</code>```

I get an error saying:

fatal: unknown value for config 'protocol.version': 2
```

My OS is Ubuntu 18.04. My friend on Ubuntu 16.04 did the same and it worked for him. Am I maybe missing some dependencies?

答:
With Git 2.26 (Q1 2020), The transport protocol version 2 (that I presented here before) becomes the default one.

(It was reverted in 2.27, but is the default again in Q4 2020 with Git 2.29: see below)

See commit 684ceae, commit 33166f3, commit 8a1b097, commit b9ab170, commit 07ef3c6 (24 Dec 2019) by Jonathan Nieder (artagnon).

(Merged by Junio C Hamano -- gitster -- in commit 0da63da, 14 Feb 2020)

config doc: protocol.version is not experimental

Signed-off-by: Jonathan Nieder

Git's protocol version 2 has been working well in production for over a year.

Simplify documentation by no longer referring to it as experimental.

And:

fetch: default to protocol version 2

Signed-off-by: Jonathan Nieder

The Git users at $DAYJOB have been using protocol v2 as a default for ~1.5 years now and others have been also reporting good experiences with it, so it seems like a good time to bump the default version.

It produces a significant performance improvement when fetching from repositories with many refs, such as https://chromium.googlesource.com/chromium/src.

This only affects the client, not the server.

(The server already defaults to supporting protocol v2.)

The protocol change is backward compatible, so this should produce no significant effect when contacting servers that only speak protocol v0.

Warning: before Git 2.27 (Q2 2020), those fetching over protocol v2 from linux-next and other kernel repositories are reporting that v2 often fetches way too much than needed.

See commit 11c7f2a (22 Apr 2020) by Jonathan Nieder (artagnon).

(Merged by Junio C Hamano -- gitster -- in commit e896a28, 28 Apr 2020)

Revert "fetch: default to protocol version 2"

Reported-by: Lubomir Rintel

Reported-by: "Dixit, Ashutosh"

Reported-by: Jiri Slaby

Reported-by: Konstantin Ryabitsev

Signed-off-by: Jonathan Nieder

This reverts commit 684ceae32dae726c6a5c693b257b156926aba8b7.

Users fetching from linux-next and other kernel remotes are reporting that the limited ref advertisement causes negotiation to reach MAX_IN_VAIN, resulting in too-large fetches.

With Git 2.29 (Q4 2020), The transport protocol v2 has become the default again.

See commit eb04975 (25 Sep 2020) by Jeff King (peff).

(Merged by Junio C Hamano -- gitster -- in commit e76ae33, 29 Sep 2020)

protocol: re-enable v2 protocol by default

Signed-off-by: Jeff King

Protocol v2 became the default in v2.26.0 via 684ceae32d ("fetch: default to protocol version 2", 2019-12-23, Git v2.26.0-rc0 -- merge listed in batch #5).

More widespread use turned up a regression in negotiation. That was fixed in v2.27.0 via 4fa3f00abb (fetch-pack: in protocol v2, in_vain only after ACK, 2020-04-27), but we also reverted the default to v0 as a precaution in 11c7f2a30b (Revert "fetch: default to protocol version 2", 2020-04-22).

In v2.28.0, we re-enabled it for experimental users with 3697caf4b9 ("config: let feature.experimental imply protocol.version=2", 2020-05-20, Git v2.28.0-rc0 -- merge listed in batch #2) and haven't heard any complaints.

v2.28 has only been out for 2 months, but I'd generally expect people turning on feature.experimental to also stay pretty up-to-date. So we're not likely to collect much more data by waiting. In addition, we have no further reports from people running v2.26.0, and of course some people have been setting protocol.version manually for ages.

Let's move forward with v2 as the default again. It's possible there are still lurking bugs, but we won't know until it gets more widespread use. And we can find and squash them just like any other bug at this point.

If unset, the default is 2.

ContentLicense: CC BY-SA 4.0

Body:
I decided to turn on Git protocol 2nd ver (I suppose it's faster, noiseless), so I did:

git config --global protocol.version 2

But when I try

git pull

I get an error saying:

fatal: unknown value for config 'protocol.version': 2

My OS is Ubuntu 18.04. My friend on Ubuntu 16.04 did the same and it worked for him. Am I maybe missing some dependencies?


问:
Undefined index: Title laravel 6.0
am trying to save items of an array to db am getting the error above

Am fetching the array from the omdb api using the function index

```<code> public function index()
    {
        $client = new Client();
        $uri = 'http://www.omdbapi.com/?s=water&apiKey=';
        $header = ['headers' => ['X-Auth-Token' => 'My-Token']];
        $res = $client->get($uri, $header);
        $data = json_decode($res->getBody()->getContents(), true);
  return $data;
    }
</code>```

then am storing them using the function store

```<code>public function store(Request $request)
    {
        $movies = $this->index();
//        dd($this->index());

        collect($movies['Search']);
//        dd($movies);

             foreach($movies as $movie) {
//                dd($movie);
                Movie::create([
                    'title' => $movie['Title'],
                     'year' =>$movie['Year'],
                    'type' =>$movie['Type'],
                    'cover_photo' => $movie['Poster'],
                ]);

            }

    }
This is the output of dd($movie)
array:10 [▼
  0 => array:5 [▼
    "Title" => "The Shape of Water"
    "Year" => "2017"
    "imdbID" => "tt5580390"
    "Type" => "movie"
    "Poster" => "https://m.media-amazon.com/images/M/MV5BNGNiNWQ5M2MtNGI0OC00MDA2LWI5NzEtMmZiYjVjMDEyOWYzXkEyXkFqcGdeQXVyMjM4NTM5NDY@._V1_SX300.jpg"
  ]
  1 => array:5 [▶]
  2 => array:5 [▶]
</code>```

This is the output of dd($this->index());

```<code>array:3 [▼
  "Search" => array:10 [▼
    0 => array:5 [▶]
    1 => array:5 [▶]
    2 => array:5 [▶]
    3 => array:5 [▶]
    4 => array:5 [▶]
    5 => array:5 [▶]
</code>```

答:
Change this

collect($movies['Search']);

To

$movies = collect($movies['Search']);

Title: Undefined index: Title laravel 6.0

Body:
am trying to save items of an array to db am getting the error above

Am fetching the array from the omdb api using the function index

 public function index()
    {
        $client = new Client();
        $uri = 'http://www.omdbapi.com/?s=water&apiKey=';
        $header = ['headers' => ['X-Auth-Token' => 'My-Token']];
        $res = $client->get($uri, $header);
        $data = json_decode($res->getBody()->getContents(), true);
  return $data;
    }

then am storing them using the function store

public function store(Request $request)
    {
        $movies = $this->index();
//        dd($this->index());

        collect($movies['Search']);
//        dd($movies);

             foreach($movies as $movie) {
//                dd($movie);
                Movie::create([
                    'title' => $movie['Title'],
                     'year' =>$movie['Year'],
                    'type' =>$movie['Type'],
                    'cover_photo' => $movie['Poster'],
                ]);

            }

    }
This is the output of dd($movie)
array:10 [▼
  0 => array:5 [▼
    "Title" => "The Shape of Water"
    "Year" => "2017"
    "imdbID" => "tt5580390"
    "Type" => "movie"
    "Poster" => "https://m.media-amazon.com/images/M/MV5BNGNiNWQ5M2MtNGI0OC00MDA2LWI5NzEtMmZiYjVjMDEyOWYzXkEyXkFqcGdeQXVyMjM4NTM5NDY@._V1_SX300.jpg"
  ]
  1 => array:5 [▶]
  2 => array:5 [▶]

This is the output of dd($this->index());

array:3 [▼
  "Search" => array:10 [▼
    0 => array:5 [▶]
    1 => array:5 [▶]
    2 => array:5 [▶]
    3 => array:5 [▶]
    4 => array:5 [▶]
    5 => array:5 [▶]


问:
Escaping URLs in an html attribute in PHP
I am currently working with some existing code that takes a URL out of the request and inputs it into the source of an anchor. This is clearly an opening for XSS and using urlencoding doesn't retain the sanity of the url inside the anchor. I'm curious what the safest way to escape the data without breaking the link would be.

i.e.

```<code> <?
    $url = $_REQUEST['url'];
    echo '<a href="' . $url . '">sometext</a>';
?>
</code>```

答:
There's also filter_var, which has a set of predefined filters you can use, one of which I believe is for URLs: http://php.net/manual/en/function.filter-var.php

Edit: Yup: Sanitize filters: http://www.php.net/manual/en/filter.filters.sanitize.php

ContentLicense: CC BY-SA 3.0

Body:
I am currently working with some existing code that takes a URL out of the request and inputs it into the source of an anchor. This is clearly an opening for XSS and using urlencoding doesn't retain the sanity of the url inside the anchor. I'm curious what the safest way to escape the data without breaking the link would be.

i.e.

 <?
    $url = $_REQUEST['url'];
    echo 'sometext';
?>


问:
python subprocess won't interleave stderr and stdout as what terminal does
A test program

#!/usr/bin/env python3

import sys

count = 0
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
count += 1
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
```

<p>when invoked through the terminal, the expected output is,</p>

```stderr, order 0
stdout, order 1
stderr, order 2
stdout, order 3
```

<p>In the interactive shell, when I redirect <code>stdout</code> to a PIPE, the output order is different from the output above, where Popen would group <code>stderr</code> and write them all and then do the same thing to <code>stdout</code>, instead of interleaving stdout and stderr.</p>

```In [29]: a = sp.run(['./test.py'], stderr=sp.STDOUT)
stderr, order 0
stdout, order 1
stderr, order 2
stdout, order 3

In [30]: a
Out[30]: CompletedProcess(args=['./test.py'], returncode=0)

In [33]: b = sp.Popen(['./test.py'], stderr=sp.STDOUT, stdout=sp.PIPE, encoding='utf-8')

In [34]: print(b.communicate()[0])
stderr, order 0
stderr, order 2
stdout, order 1
stdout, order 3

```

答:
In the C libraries (and thus c-based python), streams are handled differently depending on whether they are attached to interactive terminals (or something pretending to be) or not. For a tty, stdout is line buffered, otherwise its block buffered and only flushed to the file descriptor when some block boundary is hit. When you redirected to a PIPE, the stream is no longer a tty and block buffering is in effect.

The solution is to reopen stdout specifying that you want line buffering (1) regardless. At the C level, stderr is always line buffered but when I tested just reopening stdout the program acted as though stderr is block  buffered. I was quite surprised. Maybe this is the intermediate io.TextIO layer or some other odd thing, but I found I needed to fix both pipes.

Even though stdout and stderr go to the same pipe, they are separate file descriptors with separate buffers as far as the executed program is concerned. That's why interleaving doesn't happen naturally in the output buffer even in block mode.

```<code>#!/usr/bin/env python3

import sys
import os

# reopen stdout line buffered
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)

# this surprises me, seems like we have to reopen stderr
# line buffered, but i thought it was line buffered anywy.
# perhaps its the intermediate python TextIO layer?
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1)

count = 0
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
count += 1
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
</code>```

Body:
A test program

#!/usr/bin/env python3

import sys

count = 0
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
count += 1
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)

when invoked through the terminal, the expected output is,

stderr, order 0
stdout, order 1
stderr, order 2
stdout, order 3

In the interactive shell, when I redirect stdout to a PIPE, the output order is different from the output above, where Popen would group stderr and write them all and then do the same thing to stdout, instead of interleaving stdout and stderr.

In [29]: a = sp.run(['./test.py'], stderr=sp.STDOUT)
stderr, order 0
stdout, order 1
stderr, order 2
stdout, order 3

In [30]: a
Out[30]: CompletedProcess(args=['./test.py'], returncode=0)

In [33]: b = sp.Popen(['./test.py'], stderr=sp.STDOUT, stdout=sp.PIPE, encoding='utf-8')

In [34]: print(b.communicate()[0])
stderr, order 0
stderr, order 2
stdout, order 1
stdout, order 3

Body:
In the C libraries (and thus c-based python), streams are handled differently depending on whether they are attached to interactive terminals (or something pretending to be) or not. For a tty, stdout is line buffered, otherwise its block buffered and only flushed to the file descriptor when some block boundary is hit. When you redirected to a PIPE, the stream is no longer a tty and block buffering is in effect.

The solution is to reopen stdout specifying that you want line buffering (1) regardless. At the C level, stderr is always line buffered but when I tested just reopening stdout the program acted as though stderr is block  buffered. I was quite surprised. Maybe this is the intermediate io.TextIO layer or some other odd thing, but I found I needed to fix both pipes.

Even though stdout and stderr go to the same pipe, they are separate file descriptors with separate buffers as far as the executed program is concerned. That's why interleaving doesn't happen naturally in the output buffer even in block mode.

#!/usr/bin/env python3

import sys
import os

# reopen stdout line buffered
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)

# this surprises me, seems like we have to reopen stderr
# line buffered, but i thought it was line buffered anywy.
# perhaps its the intermediate python TextIO layer?
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1)

count = 0
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)
count += 1
sys.stderr.write('stderr, order %d\n' % count)
count += 1
sys.stdout.write('stdout, order %d\n' % count)


问:
Dgraph: Is it a best practice to always use omitempty in your Golang struct fields?
For example, there's this snippet in the dgo doc

```<code>// If omitempty is not set, then edges with empty values (0 for int/float, "" for string, false
// for bool) would be created for values not specified explicitly.

type Person struct {
    Uid      string     `json:"uid,omitempty"`
    Name     string     `json:"name,omitempty"`
    Age      int        `json:"age,omitempty"`
    Dob      *time.Time `json:"dob,omitempty"`
    Married  bool       `json:"married,omitempty"`
    Raw      []byte     `json:"raw_bytes,omitempty"`
    Friends  []Person   `json:"friend,omitempty"`
    Location loc        `json:"loc,omitempty"`
    School   []School   `json:"school,omitempty"`
    DType    []string   `json:"dgraph.type,omitempty"`
}
</code>```

The comment is stated as if omitting omitempty is a bad thing.

答:
As always, it depends... on your specific use-case and data model.

Having omitempty for a field results in that field missing in the json.Marshal result if its value is the types default zero value. Without omitempty the json will always include that field, and it will be the types default zero value if not set to something else. For example having following struct missing omitempty for the age field:

```<code>type Person struct {
   Uid      string     `json:"uid,omitempty"`
   Name     string     `json:"name,omitempty"`
   Age      int        `json:"age"
}

p := Person{
  Uid: "0x1",
}

js, _ := json.Marshal(&p)
</code>```

The resulting json will have no name field, but age with the default zero value for an int, which is 0:

```<code>{"uid": "0x1", "age": 0}
</code>```

If you send this json to a Dgraph mutation, age will be set to 0 for that node and overwrite the nodes current age value, while name will be unchanged. So in this case, having omitempty for the age fields makes sense, otherwise you would have to always set the age field to the correct value before calling a mutation with the json, even if you only want to change the name field of the node.

If you want a field to always be set to its default zero value if not set otherwise in the struct, then you don't use omitempty for that field.

Body:
For example, there's this snippet in the dgo doc

// If omitempty is not set, then edges with empty values (0 for int/float, "" for string, false
// for bool) would be created for values not specified explicitly.

type Person struct {
    Uid      string     `json:"uid,omitempty"`
    Name     string     `json:"name,omitempty"`
    Age      int        `json:"age,omitempty"`
    Dob      *time.Time `json:"dob,omitempty"`
    Married  bool       `json:"married,omitempty"`
    Raw      []byte     `json:"raw_bytes,omitempty"`
    Friends  []Person   `json:"friend,omitempty"`
    Location loc        `json:"loc,omitempty"`
    School   []School   `json:"school,omitempty"`
    DType    []string   `json:"dgraph.type,omitempty"`
}

The comment is stated as if omitting omitempty is a bad thing.

Body:
As always, it depends... on your specific use-case and data model.

Having omitempty for a field results in that field missing in the json.Marshal result if its value is the types default zero value. Without omitempty the json will always include that field, and it will be the types default zero value if not set to something else. For example having following struct missing omitempty for the age field:

type Person struct {
   Uid      string     `json:"uid,omitempty"`
   Name     string     `json:"name,omitempty"`
   Age      int        `json:"age"
}

p := Person{
  Uid: "0x1",
}

js, _ := json.Marshal(&p)

The resulting json will have no name field, but age with the default zero value for an int, which is 0:

{"uid": "0x1", "age": 0}

If you send this json to a Dgraph mutation, age will be set to 0 for that node and overwrite the nodes current age value, while name will be unchanged. So in this case, having omitempty for the age fields makes sense, otherwise you would have to always set the age field to the correct value before calling a mutation with the json, even if you only want to change the name field of the node.

If you want a field to always be set to its default zero value if not set otherwise in the struct, then you don't use omitempty for that field.


问:
Check, whether an array contains an object with id that matches list of ids
is there an elegant way to determine, whether an array like this:

```<code>[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]
</code>```

contains an item with an id that is listed in another array like this:

```<code>[1,5]
</code>```

In this case only these values should be returned:

```<code>  {id: 1, value: false},
  {id: 5, value: true}
</code>```

I was trying to use includes(), but it's not working:

```<code>let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])
</code>```

答:
I'd suggest you use a Set. Since you are searching your data for specific keys, this will have much better performances on large search arrays:

const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

const search = (data, terms) => {
  terms = new Set(terms)
  return data.filter(({ id }) => terms.has(id))
}

console.log(search(data, [1, 5]))```
</div>
</div>
</p>

<p>Another note about performances. If your code is calling <code>search</code> with different terms many times, you can consider indexing your array in a <code>Map</code> (or an object):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

const indexedData = new Map(data.map((el) => [el.id, el]))

const search = (...terms) => {
  return terms.map((id) => indexedData.get(id)).filter(e => e)
}

console.log(search(1, 5, 10))</code>```

The latest script will iterate only once through your whole data, and then complexity will be o(n), n being your search terms.

EDIT: Here's a benchmark of all solutions for you to play with

Body:
is there an elegant way to determine, whether an array like this:

[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

contains an item with an id that is listed in another array like this:

[1,5]

In this case only these values should be returned:

  {id: 1, value: false},
  {id: 5, value: true}

I was trying to use includes(), but it's not working:

let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])

Body:
I'd suggest you use a Set. Since you are searching your data for specific keys, this will have much better performances on large search arrays:

const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

const search = (data, terms) => {
  terms = new Set(terms)
  return data.filter(({ id }) => terms.has(id))
}

console.log(search(data, [1, 5]))

Another note about performances. If your code is calling search with different terms many times, you can consider indexing your array in a Map (or an object):

const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

const indexedData = new Map(data.map((el) => [el.id, el]))

const search = (...terms) => {
  return terms.map((id) => indexedData.get(id)).filter(e => e)
}

console.log(search(1, 5, 10))

The latest script will iterate only once through your whole data, and then complexity will be o(n), n being your search terms.

EDIT: Here's a benchmark of all solutions for you to play with


问:
primeng checkbox with reactive form with array
I am trying to add my array of object to map the primeng checkbox and would like to get the values for selected check boxes.

I have tried FormControlName but it it's throwing undefined after submitting.

below is the rough code

```<code>data = [
    { type: dropdown
      text: 'drop',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'drop1
      },{
       value=2,
       text= 'drop2
      }
      ]
    },
    { type: checkbox
      text: 'check',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'check1
      },{
       value=2,
       text= 'check2
      }
      ]
    },
    { type: radio
      text: 'radio',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'radio1
      },{
       value=2,
       text= 'radio2
      }
      ]
    },
  ];
</code>```

Template:

```<code><form [formGroup]="group">

  <div *ngFor="let d of data">
  <div *ngSwitchCase = "checkbox">
    <p-checkbox *ngFor="let check of options"  [value]="check.value" [formControlName]="check.text"></p-checkbox>
    </div>
    <div *ngSwitchCase = "dropdown">
  <p-dropdown *ngFor="let drop of options" [value]="drop.value" [formControlName]="d.text"> {{drop.text}}
   </p-dropdown>
  </div>
   <div *ngSwitchCase = "radio">
    <p-radioButton  *ngFor="let radio of options"[value]="radio.value" [formControlName]="d.text"></p-radioButton >
  </div>
  </div>
 </form>
</code>```

How I can get the reference of my control and values the same for drop down and check boxes.

How to get the values for dynamic forms?

答:
for reactive dynamic form first thing we have to generate the formGroup base of the form control data

getFormGroup method will return a formGroup object by loop over the data and create a form controls with name base of the text value .

getFormGroup() {

    const formControls = this.data.reduce( (controls , f:FormControl)=>{

      controls[f.text] = this.formBuilder.control(null);
      return controls;

    },{});

    return this.formBuilder.group(formControls)
  }
```
<p>after we generate the form now we can render the form controls on the template</p>
<pre class="lang-js prettyprint-override"><code><form [formGroup]="form">

    <div *ngFor="let d of data">

        <ng-container [ngSwitch]="d.type">

            <label for="">{{d.text}}</label>
            <div *ngSwitchCase="'checkbox'">
                <p-checkbox *ngFor="let check of d.options" [label]="check.label" [value]="check.value"
                    [formControlName]="d.text"></p-checkbox>
            </div>

            <div *ngSwitchCase="'dropdown'">
                <p-dropdown [options]="d.options" [formControlName]="d.text">
                </p-dropdown>
            </div>

            <div *ngSwitchCase="'radio'">

                <p-radioButton *ngFor="let radio of d.options" [name]="d.text" [label]="radio.label"
                    [value]="radio.value" [formControlName]="d.text">
                </p-radioButton>

            </div>

        </ng-container>
    </div>
</form>
</code>```

stackblitz demo

Body:
I am trying to add my array of object to map the primeng checkbox and would like to get the values for selected check boxes.

I have tried FormControlName but it it's throwing undefined after submitting.

below is the rough code

data = [
    { type: dropdown
      text: 'drop',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'drop1
      },{
       value=2,
       text= 'drop2
      }
      ]
    },
    { type: checkbox
      text: 'check',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'check1
      },{
       value=2,
       text= 'check2
      }
      ]
    },
    { type: radio
      text: 'radio',
      num: 1.23,
      options: [
      {
       value=1,
       text= 'radio1
      },{
       value=2,
       text= 'radio2
      }
      ]
    },
  ];

Template:

<form [formGroup]="group">

 {{drop.text}}

 </form>

How I can get the reference of my control and values the same for drop down and check boxes.

How to get the values for dynamic forms?

Body:
for reactive dynamic form first thing we have to generate the formGroup base of the form control data

getFormGroup method will return a formGroup object by loop over the data and create a form controls with name base of the text value .

getFormGroup() {

    const formControls = this.data.reduce( (controls , f:FormControl)=>{

      controls[f.text] = this.formBuilder.control(null);
      return controls;

    },{});

    return this.formBuilder.group(formControls)
  }

after we generate the form now we can render the form controls on the template

<form [formGroup]="form">

    <div *ngFor="let d of data">

        <ng-container [ngSwitch]="d.type">

            <label for="">{{d.text}}</label>
            <div *ngSwitchCase="'checkbox'">
                <p-checkbox *ngFor="let check of d.options" [label]="check.label" [value]="check.value"
                    [formControlName]="d.text"></p-checkbox>
            </div>

            <div *ngSwitchCase="'dropdown'">
                <p-dropdown [options]="d.options" [formControlName]="d.text">
                </p-dropdown>
            </div>

            <div *ngSwitchCase="'radio'">

                <p-radioButton *ngFor="let radio of d.options" [name]="d.text" [label]="radio.label"
                    [value]="radio.value" [formControlName]="d.text">
                </p-radioButton>

            </div>

        </ng-container>
    </div>
</form>

stackblitz demo


问:
Check for proper list in Common Lisp
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

```<code>(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))
</code>```

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

```<code>(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))
</code>```

答:
(tailp l (cdr l)) is t for circular lists but nil for non-circular lists.

Credits to @tfp and @RainerJoswig who taught me this here .

So, your function would be:

```<code>(defun proper-listp (lst)
  (or (null lst)                           ; either a `'()` or:
      (and (consp lst)                     ; a cons
           (not (tailp lst (cdr lst)))     ; not circular
           (null (cdr (last lst))))))      ; not a dotted list
</code>```

By the way, I use proper-listp by purpose. Correct would be - by convetion proper-list-p. However, this name is already occupied in the CLISP implementation by SYSTEM::%PROPER-LIST-Pwhy the definition of the function raises a continuable error.

Conclusion of our discussion in the comment section:

The behavior of tailp for circular lists is undefined. Therefore this answer is wrong! Thank you @Lassi for figuring this out!

Title: Check for proper list in Common Lisp

Body:
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))

Body:
(tailp l (cdr l)) is t for circular lists but nil for non-circular lists.

Credits to @tfp and @RainerJoswig who taught me this here .

So, your function would be:

(defun proper-listp (lst)
  (or (null lst)                           ; either a `'()` or:
      (and (consp lst)                     ; a cons
           (not (tailp lst (cdr lst)))     ; not circular
           (null (cdr (last lst))))))      ; not a dotted list

By the way, I use proper-listp by purpose. Correct would be - by convetion proper-list-p. However, this name is already occupied in the CLISP implementation by SYSTEM::%PROPER-LIST-Pwhy the definition of the function raises a continuable error.

Conclusion of our discussion in the comment section:

The behavior of tailp for circular lists is undefined. Therefore this answer is wrong! Thank you @Lassi for figuring this out!


问:
SQL query that selects a group of students who's school year start and finish dates contain the start and finish date in another table?
Prompt:

Who were the Gryffindors who would have had Dolores Umbridge as DADA teacher
(assume all students take DADA, and all students are at school for the entire
school year starting in Fall and ending in Spring, keeping in mind that each
DADA teacher listed started in Fall and left the following Spring)?

DADA table

  last    |  first   | start | finish
----------+----------+-------+--------
 Quirrell | Quirinus |  1991 |   1992
 Lockhart | Gilderoy |  1992 |   1993
 Lupin    | Remus    |  1993 |   1994
 Moody    | Alastor  |  1994 |   1995
 Umbridge | Dolores  |  1995 |   1996
 Snape    | Severus  |  1996 |   1997
 Carrow   | Amycus   |  1997 |   1998

Students table

 last            |   first    |   house    | start | finish
-----------------+------------+------------+-------+--------
 Abbott          | Hannah     | Hufflepuff |       |
 Abercrombie     | Euan       | Gryffindor |  1995 |
 Ackerley        | Stewart    | Ravenclaw  |  1994 |
 Astoria         | Greengrass | Slytherin  |       |
 Baddock         | Malcolm    | Slytherin  |  1994 |
 Bell            | Katie      | Gryffindor |  1990 |   1997
 Black           | Bellatrix  | Slytherin  |  1962 |
 Black           | Narcissa   | Slytherin  |  1966 |   1973
 Black           | Phineas    | Slytherin  |       |
 Black           | Regulus    | Slytherin  |  1972 |
 Black           | Sirius     | Gryffindor |  1971 |   1978
 Bletchley       | Miles      | Slytherin  |       |
 Bones           | Susan      | Hufflepuff |  1991 |   1998
 Boot            | Terry      | Ravenclaw  |  1991 |   1998
 Branstone       | Eleanor    | Hufflepuff |  1994 |
 Brocklehurst    | Mandy      | Ravenclaw  |  1991 |
 Brown           | Lavender   | Gryffindor |  1991 |   1998
 Bulstrode       | Millicent  | Slytherin  |  1991 |
```

Tried using a WITH subquery, but was only getting students who's start year was the same start year as Delores Umbridge, rather than students who were in their 6th year that still would have had her as a DADA teacher. Any tips are appreciated.

答:
from my  understanding this is what you want:</p>

```<code>select a.* from Students a inner join DADA b
on a.start <= b.start and coalesce(a.finish, 2999) >= b.finish
where b.last = 'Umbridge' and b.first = 'Dolores'
and house = 'Gryffindor'
</code>```

Body:
Prompt:

Who were the Gryffindors who would have had Dolores Umbridge as DADA teacher
(assume all students take DADA, and all students are at school for the entire
school year starting in Fall and ending in Spring, keeping in mind that each
DADA teacher listed started in Fall and left the following Spring)?

DADA table

  last    |  first   | start | finish
----------+----------+-------+--------
 Quirrell | Quirinus |  1991 |   1992
 Lockhart | Gilderoy |  1992 |   1993
 Lupin    | Remus    |  1993 |   1994
 Moody    | Alastor  |  1994 |   1995
 Umbridge | Dolores  |  1995 |   1996
 Snape    | Severus  |  1996 |   1997
 Carrow   | Amycus   |  1997 |   1998

Students table

 last            |   first    |   house    | start | finish
-----------------+------------+------------+-------+--------
 Abbott          | Hannah     | Hufflepuff |       |
 Abercrombie     | Euan       | Gryffindor |  1995 |
 Ackerley        | Stewart    | Ravenclaw  |  1994 |
 Astoria         | Greengrass | Slytherin  |       |
 Baddock         | Malcolm    | Slytherin  |  1994 |
 Bell            | Katie      | Gryffindor |  1990 |   1997
 Black           | Bellatrix  | Slytherin  |  1962 |
 Black           | Narcissa   | Slytherin  |  1966 |   1973
 Black           | Phineas    | Slytherin  |       |
 Black           | Regulus    | Slytherin  |  1972 |
 Black           | Sirius     | Gryffindor |  1971 |   1978
 Bletchley       | Miles      | Slytherin  |       |
 Bones           | Susan      | Hufflepuff |  1991 |   1998
 Boot            | Terry      | Ravenclaw  |  1991 |   1998
 Branstone       | Eleanor    | Hufflepuff |  1994 |
 Brocklehurst    | Mandy      | Ravenclaw  |  1991 |
 Brown           | Lavender   | Gryffindor |  1991 |   1998
 Bulstrode       | Millicent  | Slytherin  |  1991 |

Tried using a WITH subquery, but was only getting students who's start year was the same start year as Delores Umbridge, rather than students who were in their 6th year that still would have had her as a DADA teacher. Any tips are appreciated.

Body:
from my  understanding this is what you want:

select a.* from Students a inner join DADA b
on a.start <= b.start and coalesce(a.finish, 2999) >= b.finish
where b.last = 'Umbridge' and b.first = 'Dolores'
and house = 'Gryffindor'


问:
SQL - Need help filtering results based on rows
I have a table that looks like this:

```<code>p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1
</code>```

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

答:
```<code> SELECT p_id FROM tbl WHERE EXISTS
 (SELECT p_id FROM tbl WHERE comp_id = 1)
 AND EXISTS (SELECT p_id FROM tbl WHERE comp_id = 2)
</code>```

Body:
I have a table that looks like this:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?


问:
What is the difference between useEffect and code in the body of a functional component?
Basically I'm wondering what the difference is between these two things:

```<code>const myComponent = (props) => {
    console.log('hi');
    return (
        <div>props: {props}</div>
    );
};

const myComponent = (props) => {
    useEffect(() => {
        console.log('hi');
    });
    return (
        <div>props: {props}</div>
    );
};
</code>```

What exactly would trigger the log statement in each case?

答:
useEffect will delay the log because it won't be immediately executed.

See this example:

```<code>const MyComponent1 = () => {
    console.log('Hello');
    console.log('World');
    return (
        <div></div>
    );
};
</code>```

This will output Hello world

```<code>
const MyComponent2 = () => {
    useEffect(() => {
        console.log('Hello');
    });
    console.log("world")
    return (
        <div></div>
    );
};
</code>```

This will output world Hello.

Watch this wonderful video about the event loop if you want to have a clear understanding about this

Body:
Basically I'm wondering what the difference is between these two things:

const myComponent = (props) => {
    console.log('hi');
    return (

props: {props}

    );
};

const myComponent = (props) => {
    useEffect(() => {
        console.log('hi');
    });
    return (

props: {props}

    );
};

What exactly would trigger the log statement in each case?

Body:
useEffect will delay the log because it won't be immediately executed.

See this example:

const MyComponent1 = () => {
    console.log('Hello');
    console.log('World');
    return (
        <div></div>
    );
};

This will output Hello world

const MyComponent2 = () => {
    useEffect(() => {
        console.log('Hello');
    });
    console.log("world")
    return (
        <div></div>
    );
};

This will output world Hello.

Watch this wonderful video about the event loop if you want to have a clear understanding about this


问:
Pass parameter to nested procedure or create temp table and check if table exists
I have the following structure of stored procedures:

```<code>exec A -> exec B -> exec C -> exec D
</code>```

where stored procedure A calls stored procedure B, B calls C and C calls D.

I need a special behavior to happen in stored procedure D based on a condition that is determined in stored procedure A. Of course one option is to pass param from A to B, then from B to C, then from C to D, but I was wondering if I can simply just create a temp table prior to executing A, then when I am in stored procedure D I can just check if temp table exists and perform my logic based on that.Finally in the line right after exec A, I will drop the temp table

EDIT: I am aware that if proc D is called from a different procedure the condition will be treated as not exists. Also I am aware of temp table name can clash with another temp table with the same name. Other than that...

Is there any unwanted side effects to doing the later solution?

答:
I usually use a persistent [Params] table. I have procedure:</p>

```<code>CREATE OR ALTER PROCEDURE SetParam @name VarChar(20), @value VarChar(50) AS BEGIN
    -- I don't like MERGE, but it could be used here as well.
    BEGIN TRY
        INSERT INTO [Params] ([Name], [Value])
        VALUES (@name, @value)
    END TRY
    BEGIN CATCH
        UPDATE [Params] SET [Value] = @Value
        WHERE [Name] = @name
    END CATCH
END
GO
CREATE OR ALTER PROCEDURE GetParam @name VarChar(20), @value VarChar(50) OutPut AS BEGIN
    SET @value = NULL
    -- Try - Catch could be here as well
    SELECT @value FROM [Params] WHERE [Name]=@name
END
GO

-- In A
EXEC SetParam 'Param','Value'

-- In D
DECLARE @ParamValue Int
EXEC GetParam 'ParamName', @ParamValue OutPut
</code>```

Body:
I have the following structure of stored procedures:

exec A -> exec B -> exec C -> exec D

where stored procedure A calls stored procedure B, B calls C and C calls D.

I need a special behavior to happen in stored procedure D based on a condition that is determined in stored procedure A. Of course one option is to pass param from A to B, then from B to C, then from C to D, but I was wondering if I can simply just create a temp table prior to executing A, then when I am in stored procedure D I can just check if temp table exists and perform my logic based on that.Finally in the line right after exec A, I will drop the temp table

EDIT: I am aware that if proc D is called from a different procedure the condition will be treated as not exists. Also I am aware of temp table name can clash with another temp table with the same name. Other than that...

Is there any unwanted side effects to doing the later solution?

Body:
I usually use a persistent [Params] table. I have procedure:

CREATE OR ALTER PROCEDURE SetParam @name VarChar(20), @value VarChar(50) AS BEGIN
    -- I don't like MERGE, but it could be used here as well.
    BEGIN TRY
        INSERT INTO [Params] ([Name], [Value])
        VALUES (@name, @value)
    END TRY
    BEGIN CATCH
        UPDATE [Params] SET [Value] = @Value
        WHERE [Name] = @name
    END CATCH
END
GO
CREATE OR ALTER PROCEDURE GetParam @name VarChar(20), @value VarChar(50) OutPut AS BEGIN
    SET @value = NULL
    -- Try - Catch could be here as well
    SELECT @value FROM [Params] WHERE [Name]=@name
END
GO

-- In A
EXEC SetParam 'Param','Value'

-- In D
DECLARE @ParamValue Int
EXEC GetParam 'ParamName', @ParamValue OutPut


问:
How to keep observable chain going after http error in one observable
I've got a chain of observables. Here is the piece of code:

```<code>        //get dynamic tree
      flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
      tap(res => this.dynamicTree = res),
        //get dynamic report
      flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),
</code>```

However when I got 500 API error from the first request(get dynamic tree), the chain stops and never enters the second flatMap(dynamic report).

Here is the function this.reportService.getDynamicTree():

```<code> get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.apiBaseUrl}${path}`, {headers: this.setHeaders(true), params: params}).pipe(
      catchError(error => this.processError(path, error)),
      map((res: Response) => res));
  }
</code>```

where this.processError returns observableThrowError(res);

What should I return in case of error to continue the chain? Or is the reason in other things?

答:
In case of an error, an Observable completes, so if you want to return a new Observable after an error occurs, you have to use the catchError operator like this:

```<code>//get dynamic tree
flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
tap(res => this.dynamicTree = res),
catchError(() => of({})),
//get dynamic report
flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),
</code>```

The tap operator safely doesn't execute the callback and just forwards errors when they occur so that will assign this.dynamicTree only in case of a success.

If you want to handle the error in the service instead of the component, you have to return something else than observableThrowError(res); from processError (for example of({})) but that will execute the tap callback and assign this.dynamicTree which is probably an unwanted behavior.

Body:
I've got a chain of observables. Here is the piece of code:

        //get dynamic tree
      flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
      tap(res => this.dynamicTree = res),
        //get dynamic report
      flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),

However when I got 500 API error from the first request(get dynamic tree), the chain stops and never enters the second flatMap(dynamic report).

Here is the function this.reportService.getDynamicTree():

 get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.apiBaseUrl}${path}`, {headers: this.setHeaders(true), params: params}).pipe(
      catchError(error => this.processError(path, error)),
      map((res: Response) => res));
  }

where this.processError returns observableThrowError(res);

What should I return in case of error to continue the chain? Or is the reason in other things?

Body:
In case of an error, an Observable completes, so if you want to return a new Observable after an error occurs, you have to use the catchError operator like this:

//get dynamic tree
flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
tap(res => this.dynamicTree = res),
catchError(() => of({})),
//get dynamic report
flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),

The tap operator safely doesn't execute the callback and just forwards errors when they occur so that will assign this.dynamicTree only in case of a success.

If you want to handle the error in the service instead of the component, you have to return something else than observableThrowError(res); from processError (for example of({})) but that will execute the tap callback and assign this.dynamicTree which is probably an unwanted behavior.


问:
Calculating the mean and standard deviation in C++ for single channeled histogram
I want calculate the mean and standard deviations for a histogram of a HSV image but I only want to do this histogram and calculations for the V channel.

I have been reading examples on how to do this for a set of channels and have tried these approaches but I am getting confused over whether my approach for initially creating the histogram is correct or not for just one channel because the program keeps crashing when i try to execute it.

Here is what I have at the moment (The variable test is a cv::Mat image and this can be any image you wish to use to recreate the issue). I have probably missed something obvious and the for loop might not be correct in terms of the range of values but I haven't done this in C++ before.

```<code>        cv::cvtColor(test, test, CV_BGR2HSV);

        int v_bins = 50;
        int histSize[] = { v_bins };
        cv::MatND hist;

        float v_ranges[] = { 0, 255};
        cv::vector<cv::Mat> channel(3);
        split(test, channel);

        const float* ranges[] = { v_ranges };
        int channels[] = {0};

        cv::calcHist(&channel[2], 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, false); //histogram calculation

        float mean=0;

        float rows= hist.size().height;
        float cols = hist.size().width;

        for (int v = 0; v < v_bins; v++)
        {
            std::cout << hist.at<float>(v, v) << std::endl;;
            mean = mean + hist.at<float>(v);
        }

        mean = mean / (rows*cols);
        std::cout << mean<< std::endl;;
</code>```

答:
Be careful about calculating statistics on a histogram. If you just run meanStdDev, you'll get the mean and stdev of the bin values. That doesn't tell you an awful lot.

Probably what you want is the mean and stdev intensity.

So, if you want to derive the image mean and standard deviation from a histogram (or set of histograms), then you can use the following code:

```<code>// assume histogram is of type cv::Mat and comes from cv::calcHist

double s = 0;
double total_hist = 0;

for(int i=0; i < histogram.total(); ++i){
    s += histogram.at<float>(i) * (i + 0.5); // bin centre
    total_hist += histogram.at<float>(i);
}

double mean = s / total_hist;

double t = 0;
for(int i=0; i < histogram.total(); ++i){
    double x = (i - mean);
    t += histogram.at<float>(i)*x*x;
}
double stdev = std::sqrt(t / total_hist);
</code>```

From the definitions of the mean:

```<code>mean = sum(x * p(x)) // expectation
std = sqrt(sum( p(x)*(x - mean)**2 ) // sqrt(variance)
</code>```

The mean is the expectation value for x. So histogram[x]/sum(histogram) gives you p(x). The definition of standard deviation is similar and comes from the variance. The numbers are slightly simpler because pixels can only take integer values and are unit spaced.

Note this is also useful if you want to calculate normalisation statistics for a batch of images using the accumulate option.

Adapted from: How to calculate the standard deviation from a histogram? (Python, Matplotlib)

Body:
I want calculate the mean and standard deviations for a histogram of a HSV image but I only want to do this histogram and calculations for the V channel.

I have been reading examples on how to do this for a set of channels and have tried these approaches but I am getting confused over whether my approach for initially creating the histogram is correct or not for just one channel because the program keeps crashing when i try to execute it.

Here is what I have at the moment (The variable test is a cv::Mat image and this can be any image you wish to use to recreate the issue). I have probably missed something obvious and the for loop might not be correct in terms of the range of values but I haven't done this in C++ before.

        cv::cvtColor(test, test, CV_BGR2HSV);

        int v_bins = 50;
        int histSize[] = { v_bins };
        cv::MatND hist;

        float v_ranges[] = { 0, 255};
        cv::vector<cv::Mat> channel(3);
        split(test, channel);

        const float* ranges[] = { v_ranges };
        int channels[] = {0};

        cv::calcHist(&channel[2], 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, false); //histogram calculation

        float mean=0;

        float rows= hist.size().height;
        float cols = hist.size().width;

        for (int v = 0; v < v_bins; v++)
        {
            std::cout << hist.at<float>(v, v) << std::endl;;
            mean = mean + hist.at<float>(v);
        }

        mean = mean / (rows*cols);
        std::cout << mean<< std::endl;;

Body:
Be careful about calculating statistics on a histogram. If you just run meanStdDev, you'll get the mean and stdev of the bin values. That doesn't tell you an awful lot.

Probably what you want is the mean and stdev intensity.

So, if you want to derive the image mean and standard deviation from a histogram (or set of histograms), then you can use the following code:

// assume histogram is of type cv::Mat and comes from cv::calcHist

double s = 0;
double total_hist = 0;

for(int i=0; i < histogram.total(); ++i){
    s += histogram.at<float>(i) * (i + 0.5); // bin centre
    total_hist += histogram.at<float>(i);
}

double mean = s / total_hist;

double t = 0;
for(int i=0; i < histogram.total(); ++i){
    double x = (i - mean);
    t += histogram.at<float>(i)*x*x;
}
double stdev = std::sqrt(t / total_hist);

From the definitions of the mean:

mean = sum(x * p(x)) // expectation
std = sqrt(sum( p(x)*(x - mean)**2 ) // sqrt(variance)

The mean is the expectation value for x. So histogram[x]/sum(histogram) gives you p(x). The definition of standard deviation is similar and comes from the variance. The numbers are slightly simpler because pixels can only take integer values and are unit spaced.

Note this is also useful if you want to calculate normalisation statistics for a batch of images using the accumulate option.

Adapted from: How to calculate the standard deviation from a histogram? (Python, Matplotlib)


问:
How do I print all unique keys among dictionaries within a list?
After reading from a JSON file (Abbreviated example JSON file), I have a list named "liveData.plays.allPlays" containing many dicts with key-value pairings. The keys are similar across the dicts but some have additional keys. I want to print all unique keys with the eventual goal of using these as fieldnames when I write a header row in a CSV file. I will also need to write the corresponding values as rows underneath in the CSV file.

I am able to print all keys within any single dict with the following code and manipulation of the integer 0:

```<code>with open('nhlbigtest2.json', 'r') as read_file:
        data = json.load(read_file)
        for k in data["liveData.plays.allPlays"][0].keys():
            print(k)
</code>```

This yields:

```<code>about.dateTime
about.eventId
about.eventIdx
about.goals.away
about.goals.home
about.ordinalNum
about.period
about.periodTime
about.periodTimeRemaining
about.periodType
result.description
result.event
result.eventCode
result.eventTypeId
</code>```

Can I manipulate integer 0 to be a range or does this task require a different approach? (using Python 3.7)

答:
A set is a data structure intended to hold unique values. You could iterate over your list of dictionaries, and update a set with the keys from each one:

```<code>unique_keys = set()
for game_dict in data["liveData.plays.allPlays"]:
    unique_keys.update(game_dict.keys())
</code>```

When you go to writing your data out as a CSV file, I'd suggest using the csv.DictWriter class. You can pass it a sequence of fieldnames (e.g. the set of keys, from above, perhaps reordered and put into a list) and it will write out columns for each one. If a given dictionary doesn't have a specific key, its row in the CSV file will have a blank for that column, though you can customize that using the restval parameter (to put 'N/A' or something else if you prefer).

Body:
After reading from a JSON file (Abbreviated example JSON file), I have a list named "liveData.plays.allPlays" containing many dicts with key-value pairings. The keys are similar across the dicts but some have additional keys. I want to print all unique keys with the eventual goal of using these as fieldnames when I write a header row in a CSV file. I will also need to write the corresponding values as rows underneath in the CSV file.

I am able to print all keys within any single dict with the following code and manipulation of the integer 0:

with open('nhlbigtest2.json', 'r') as read_file:
        data = json.load(read_file)
        for k in data["liveData.plays.allPlays"][0].keys():
            print(k)

This yields:

about.dateTime
about.eventId
about.eventIdx
about.goals.away
about.goals.home
about.ordinalNum
about.period
about.periodTime
about.periodTimeRemaining
about.periodType
result.description
result.event
result.eventCode
result.eventTypeId

Can I manipulate integer 0 to be a range or does this task require a different approach? (using Python 3.7)

Body:
A set is a data structure intended to hold unique values. You could iterate over your list of dictionaries, and update a set with the keys from each one:

unique_keys = set()
for game_dict in data["liveData.plays.allPlays"]:
    unique_keys.update(game_dict.keys())

When you go to writing your data out as a CSV file, I'd suggest using the csv.DictWriter class. You can pass it a sequence of fieldnames (e.g. the set of keys, from above, perhaps reordered and put into a list) and it will write out columns for each one. If a given dictionary doesn't have a specific key, its row in the CSV file will have a blank for that column, though you can customize that using the restval parameter (to put 'N/A' or something else if you prefer).


问:
Oracle SQL Question, Looking for rows that don't contain specific values
I have seen answers to this that get close, but don't quite do it for me.

Imagine that you have a several strings. You want to find the rows in an existing table that contain these strings and the rows that don't.

To find the rows that do contain the strings in a column is, of course, easy, e.g. myTable has the following columns:

myTableID  varChar(3)

myTableValue varChar(20)

With the following rows:

ABC | The First Row
GHI | The Second Row
JKL | The Third Row
```

```select *
from myTable
where myTableID  in ('ABC','DEF','GHI','JKL');
```

<p>myTable doesn't contain a row with a value of 'DEF' in column myTableID. The answer set would correctly not contain a row for that. There isn't one!</p>

<p>However what I want to be able to do is treat this like a bit like like a LEFT OUTER JOIN with the value 'DEF' in front of a set of columns that contain nulls. Giving the following kind of result:</p>

<pre class="lang-none prettyprint-override"><code>ABC| ABC | The First Row
DEF| null|null
GHI| GHI|The Second Row
JKL| JKL|The Third Row
</code>```

I have several hundred key values that I need to look at.

Does anyone here have any thoughts about the best way to do this?

答:
Use a collection or a VARRAY and a table collection expression with a LEFT OUTER JOIN. SYS.ODCIVARCHAR2LIST is a built in VARRAY that you could use:

SELECT t.COLUMN_VALUE AS id,
       y.*
FROM   TABLE(
         SYS.ODCIVARCHAR2LIST( 'ABC', 'DEF', 'GHI', 'JKL' )
       ) t
       LEFT OUTER JOIN your_table y
       ON ( t.COLUMN_VALUE = y.id )
```

<p>Or you can define your own collection:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TYPE stringlist IS TABLE OF VARCHAR2(20);
</code>```

and use it:

SELECT t.COLUMN_VALUE AS id,
       y.*
FROM   TABLE(
         stringlist( 'ABC', 'DEF', 'GHI', 'JKL' )
       ) t
       LEFT OUTER JOIN your_table y
       ON ( t.COLUMN_VALUE = y.id )
```

<p>which would output:</p>

<blockquote>
```
ID  | ID   | VALUE
:-- | :--- | :-------------
ABC | ABC  | The First Row
DEF | null | null
GHI | GHI  | The Second Row
JKL | JKL  | The Third Row
```

db<>fiddle here

You can also pass the collection/VARRAY as a single bind variable.

Body:
I have seen answers to this that get close, but don't quite do it for me.

Imagine that you have a several strings. You want to find the rows in an existing table that contain these strings and the rows that don't.

To find the rows that do contain the strings in a column is, of course, easy, e.g. myTable has the following columns:

myTableID  varChar(3)

myTableValue varChar(20)

With the following rows:

ABC | The First Row
GHI | The Second Row
JKL | The Third Row

select *
from myTable
where myTableID  in ('ABC','DEF','GHI','JKL');

myTable doesn't contain a row with a value of 'DEF' in column myTableID. The answer set would correctly not contain a row for that. There isn't one!

However what I want to be able to do is treat this like a bit like like a LEFT OUTER JOIN with the value 'DEF' in front of a set of columns that contain nulls. Giving the following kind of result:

ABC| ABC | The First Row
DEF| null|null
GHI| GHI|The Second Row
JKL| JKL|The Third Row

I have several hundred key values that I need to look at.

Does anyone here have any thoughts about the best way to do this?

Body:
Use a collection or a VARRAY and a table collection expression with a LEFT OUTER JOIN. SYS.ODCIVARCHAR2LIST is a built in VARRAY that you could use:

SELECT t.COLUMN_VALUE AS id,
       y.*
FROM   TABLE(
         SYS.ODCIVARCHAR2LIST( 'ABC', 'DEF', 'GHI', 'JKL' )
       ) t
       LEFT OUTER JOIN your_table y
       ON ( t.COLUMN_VALUE = y.id )

Or you can define your own collection:

CREATE TYPE stringlist IS TABLE OF VARCHAR2(20);

and use it:

SELECT t.COLUMN_VALUE AS id,
       y.*
FROM   TABLE(
         stringlist( 'ABC', 'DEF', 'GHI', 'JKL' )
       ) t
       LEFT OUTER JOIN your_table y
       ON ( t.COLUMN_VALUE = y.id )

which would output:

ID  | ID   | VALUE
:-- | :--- | :-------------
ABC | ABC  | The First Row
DEF | null | null
GHI | GHI  | The Second Row
JKL | JKL  | The Third Row

db<>fiddle here

You can also pass the collection/VARRAY as a single bind variable.


答:
You want students whose scholarship period overlap a given teacher date range, but there are traps:

school years span over two years

a student might not have a finish date (I assume this is true for teachers too, although this is not showing in your sample data)

This should be close to what you want:

```<code>select s.*
from students s
inner join dada d
    on  (s.start <= d.finish - 1 or d.dinish is null)
    and (s.finish - 1 >= d.start or s.finish is null)
where
    s.house = 'Gryffindor'
    and d.first = 'Dolores' an d.last = 'Umbridge'
</code>```

Title: SQL query that selects a group of students who's school year start and finish dates contain the start and finish date in another table?

Body:
You want students whose scholarship period overlap a given teacher date range, but there are traps:

school years span over two years

a student might not have a finish date (I assume this is true for teachers too, although this is not showing in your sample data)

This should be close to what you want:

select s.*
from students s
inner join dada d
    on  (s.start <= d.finish - 1 or d.dinish is null)
    and (s.finish - 1 >= d.start or s.finish is null)
where
    s.house = 'Gryffindor'
    and d.first = 'Dolores' an d.last = 'Umbridge'


问:
Cannot clone RISC-V toolchain
When I try to recursively clone the riscv-tools using the following command:

```<code>git clone https://github.com/riscv/riscv-tools.git --recursive
</code>```

I get this error:

```<code>error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
fatal: clone of 'https://github.com/riscv/riscv-glibc.git' into submodule path '/home/joe/riscv-tools/riscv-gnu-toolchain/riscv-glibc' failed
Failed to clone 'riscv-glibc'. Retry scheduled
</code>```

Any help would be appreciated.

答: In the end, I fixed the problem by changing my DNS IP address to 8.8.8.8. I have not idea why this worked but for some reason it did.

Title: Cannot clone RISC-V toolchain

Body:
When I try to recursively clone the riscv-tools using the following command:

git clone https://github.com/riscv/riscv-tools.git --recursive

I get this error:

error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
fatal: clone of 'https://github.com/riscv/riscv-glibc.git' into submodule path '/home/joe/riscv-tools/riscv-gnu-toolchain/riscv-glibc' failed
Failed to clone 'riscv-glibc'. Retry scheduled

Any help would be appreciated.


问:
Unobtrusive validation doesn't work with ViewComponents
I'm implementing a form with ASP.NET Core v3.1.

I have code for a drop-down on a Razor page which looks like this:

```<code><div class="form-group">
    <label asp-for="MySelectedItem" class="m-b-none"></label>
    <help-text asp-for="MySelectedItem"></help-text>
    <div class="input-group">
        <select asp-for="MySelectedItem" asp-items="@Model.MyItems" class="form-control"></select>
        <partial name="_ValidationIcon" />
    </div>
    <span asp-validation-for="MySelectedItem" class="validation-message"></span>
</div>
</code>```

In my model class, I've included a validation rule to ensure that a valid option must be selected. This renders nicely:

Now, I want to genericise this as a View Component so that I don't have to paste this lump of code anytime I want a drop-down. Here is my implementation:

public class DropdownViewComponent : ViewComponent
{
    public IEnumerable<SelectListItem> Items { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, IEnumerable<SelectListItem> items)
    {
        Items = items;
        SelectedItem = selectedItem;
        return View(this);
    }
}
```

<p><strong>/Dropdown/Default.cshtml</strong></p>

```@model Web.ViewComponents.DropdownViewComponent

    <help-text asp-for="SelectedItem"></help-text>

        <select asp-for="SelectedItem" asp-items="@Model.Items" class="form-control"></select>
        <partial name="_ValidationIcon" />

```

<p>Usage: </p>

```<vc:dropdown selected-item="MySelectedItem" items="Model.MyItems"></vc:dropdown>
```

This code correctly renders the drop-down, but the validation attributes are missing from the rendered HTML. Why?

I'm also not sure how to get the DisplayName from the model expression that I passed to the View Component.

Where have I gone wrong?

Thanks.

答:
Presumably, your validation attributes are on the MyItems property of your parent model, which isn't listed here. E.g.,

public class ParentModel {
  [Required]
  public IEnumerable<SelectListItem> MyItems { get; set; }
}
```
<p>As such, the issue is that your view is no longer binding to that model or its <code>MyItems</code> property. Instead, it's binding to the <code>Items</code> property on the <code>DropdownViewComponent</code> model, which doesn't have any validation attributes on it. Those two properties may both be pointing to the same <code>IEnumerable<SelectListItem></code> <em>object reference</em>, but their <em>metadata</em> is entirely different. As such, ASP.NET Core is <em>correctly</em> displaying the validation attributes associated with the <code>DropdownViewComponent.Items</code> property.</p>
<p>I see this as an unfortunate limitation of view components—but one that's conceptually difficult to reason out of. For more information, see my answer to a similar question I previously posed, How to bind a <code>ModelExpression</code> to a <code>ViewComponent</code> in ASP.NET Core.</p>
<p>That said, given your particular requirements, you can work around this by passing the model which <em>contains</em> the target property to your view component—instead of passing the <em>value</em> of the target property itself—and then relaying <em>that</em> via your view component's view model:</p>
<pre class="lang-cs prettyprint-override"><code>public class DropdownViewComponent : ViewComponent
{
    public ParentModel ParentModel { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, ParentModel model)
    {
        ParentModel = model;
        SelectedItem = selectedItem;
        return View(this);
    }
}
</code>```

Note: I would typically create a separate, lightweight view model for your view component, instead of passing your view component object down to its view. But I'm maintaining this structure for consistency with your original code.

You would then be able to bind to the original property in your view component's view, thus maintaining all of the original validation attributes:

<select asp-for="SelectedItem" asp-items="@Model.ParentModel.MyItems"></select>
```
<p>On first approximation, this doesn't buy you much—and may even defeat your entire reason for pursuing a view component in the first place—as it forces you to operate against a single model. If multiple views with different models want to use this view component, that introduces some problems. You can mitigate these, however, by introducing a layer of abstraction.</p>
<p>There are a few approaches to this, such as establishing an interface, but the one I recommend is to develop a specialized list class which you use to model <code>IEnumerable<SelectListItem></code>:</p>
<pre class="lang-cs prettyprint-override"><code>public class DropdownList: List<SelectListItem> {
  public virtual IEnumerable<SelectListItem> Items { get; } = this;
}
</code>```

And then working off of that in your DropdownViewComponent:

public class DropdownViewComponent : ViewComponent
{
    public DropdownList DropdownList { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, DropdownList dropdownList)
    {
        DropdownList = dropdownList;
        SelectedItem = selectedItem;
        return View(this);
    }
}

```
<p>And, finally, implementing it as follows in your view component's view:</p>
<pre class="lang-cs prettyprint-override"><code><select asp-for="SelectedItem" asp-items="@Model.DropdownList.Items"></select>
</code>```

This would allow you to override this class in order to add attributes as needed. E.g.,

public class RequiredDropdownList : DropdownList {
  [Required]
  public override Items { get; } = this;
}
```

Note: if you have a need to use a variety of different collections on different view models, and were relying on IEnumerable<SelectListItem> to unify them, this approach won't work. In that case, creating something like an IDropdownList interface makes more sense. Regardless, the concept is virtually identical.

Body:
I'm implementing a form with ASP.NET Core v3.1.

I have code for a drop-down on a Razor page which looks like this:

    <help-text asp-for="MySelectedItem"></help-text>

        <select asp-for="MySelectedItem" asp-items="@Model.MyItems" class="form-control"></select>
        <partial name="_ValidationIcon" />

In my model class, I've included a validation rule to ensure that a valid option must be selected. This renders nicely:

Now, I want to genericise this as a View Component so that I don't have to paste this lump of code anytime I want a drop-down. Here is my implementation:

public class DropdownViewComponent : ViewComponent
{
    public IEnumerable<SelectListItem> Items { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, IEnumerable<SelectListItem> items)
    {
        Items = items;
        SelectedItem = selectedItem;
        return View(this);
    }
}

/Dropdown/Default.cshtml

@model Web.ViewComponents.DropdownViewComponent

    <help-text asp-for="SelectedItem"></help-text>

        <select asp-for="SelectedItem" asp-items="@Model.Items" class="form-control"></select>
        <partial name="_ValidationIcon" />

Usage:

<vc:dropdown selected-item="MySelectedItem" items="Model.MyItems"></vc:dropdown>

This code correctly renders the drop-down, but the validation attributes are missing from the rendered HTML. Why?

I'm also not sure how to get the DisplayName from the model expression that I passed to the View Component.

Where have I gone wrong?

Thanks.

Body:
Presumably, your validation attributes are on the MyItems property of your parent model, which isn't listed here. E.g.,

public class ParentModel {
  [Required]
  public IEnumerable<SelectListItem> MyItems { get; set; }
}

As such, the issue is that your view is no longer binding to that model or its MyItems property. Instead, it's binding to the Items property on the DropdownViewComponent model, which doesn't have any validation attributes on it. Those two properties may both be pointing to the same IEnumerable<SelectListItem> object reference, but their metadata is entirely different. As such, ASP.NET Core is correctly displaying the validation attributes associated with the DropdownViewComponent.Items property.

I see this as an unfortunate limitation of view components—but one that's conceptually difficult to reason out of. For more information, see my answer to a similar question I previously posed, How to bind a ModelExpression to a ViewComponent in ASP.NET Core.

That said, given your particular requirements, you can work around this by passing the model which contains the target property to your view component—instead of passing the value of the target property itself—and then relaying that via your view component's view model:

public class DropdownViewComponent : ViewComponent
{
    public ParentModel ParentModel { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, ParentModel model)
    {
        ParentModel = model;
        SelectedItem = selectedItem;
        return View(this);
    }
}

Note: I would typically create a separate, lightweight view model for your view component, instead of passing your view component object down to its view. But I'm maintaining this structure for consistency with your original code.

You would then be able to bind to the original property in your view component's view, thus maintaining all of the original validation attributes:

<select asp-for="SelectedItem" asp-items="@Model.ParentModel.MyItems"></select>

On first approximation, this doesn't buy you much—and may even defeat your entire reason for pursuing a view component in the first place—as it forces you to operate against a single model. If multiple views with different models want to use this view component, that introduces some problems. You can mitigate these, however, by introducing a layer of abstraction.

There are a few approaches to this, such as establishing an interface, but the one I recommend is to develop a specialized list class which you use to model IEnumerable<SelectListItem>:

public class DropdownList: List<SelectListItem> {
  public virtual IEnumerable<SelectListItem> Items { get; } = this;
}

And then working off of that in your DropdownViewComponent:

public class DropdownViewComponent : ViewComponent
{
    public DropdownList DropdownList { get; set; }

    public ModelExpression SelectedItem { get; set; }

    public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, DropdownList dropdownList)
    {
        DropdownList = dropdownList;
        SelectedItem = selectedItem;
        return View(this);
    }
}

And, finally, implementing it as follows in your view component's view:

<select asp-for="SelectedItem" asp-items="@Model.DropdownList.Items"></select>

This would allow you to override this class in order to add attributes as needed. E.g.,

public class RequiredDropdownList : DropdownList {
  [Required]
  public override Items { get; } = this;
}

Note: if you have a need to use a variety of different collections on different view models, and were relying on IEnumerable<SelectListItem> to unify them, this approach won't work. In that case, creating something like an IDropdownList interface makes more sense. Regardless, the concept is virtually identical.


问:
How do I visualize a net in Pytorch?
```<code>import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz import make_dot

batch_size = 3
learning_rate =0.0002
epoch = 50

resnet = models.resnet50(pretrained=True)
print resnet
make_dot(resnet)
</code>```

I want to visualize resnet from the pytorch models. How can I do it? I tried to use torchviz but it gives an error:

```<code>'ResNet' object has no attribute 'grad_fn'
</code>```

答:
Here is how you do it with torchviz if you want to save the image:

```<code># http://www.bnikolic.co.uk/blog/pytorch-detach.html

import torch
from torchviz import make_dot

x=torch.ones(10, requires_grad=True)
weights = {'x':x}

y=x**2
z=x**3
r=(y+z).sum()

make_dot(r).render("attached", format="png")
</code>```

screenshot of image you get:

source: http://www.bnikolic.co.uk/blog/pytorch-detach.html

Title: How do I visualize a net in Pytorch?

Body:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz import make_dot

batch_size = 3
learning_rate =0.0002
epoch = 50

resnet = models.resnet50(pretrained=True)
print resnet
make_dot(resnet)

I want to visualize resnet from the pytorch models. How can I do it? I tried to use torchviz but it gives an error:

'ResNet' object has no attribute 'grad_fn'

Body:
Here is how you do it with torchviz if you want to save the image:

# http://www.bnikolic.co.uk/blog/pytorch-detach.html

import torch
from torchviz import make_dot

x=torch.ones(10, requires_grad=True)
weights = {'x':x}

y=x**2
z=x**3
r=(y+z).sum()

make_dot(r).render("attached", format="png")

screenshot of image you get:

source: http://www.bnikolic.co.uk/blog/pytorch-detach.html


问:
React app freezing in chrome after several hours of being open
Not a specific programming query but more in relation to a javascript app as a whole having a general problem and looking for any possible solutions to debug it.

I'm using React and have a single page app which is receiving streaming data from a websocket about 40 times a second. The user display is updated a similar amount of times each second to show the updates.

The problem I'm having is that after running the page for more than 12 hours not only google chrome, but all of other applications start to freeze momentarily. If I start trying to do too much with the other applications, sometimes all windows on chrome will turn black and it can freeze for up to 30 seconds.  The more processing/memory used by other applications and the more versions of the react app I have open, the faster the freezing starts, but in any case only starts after a few hours.

The only fix is currently to restart the whole of windows because even after closing chrome the problem persists.

I've tried using google chrome profiling to inspect the heap type to see a memory leak but the memory size is the same as when I first launched the app.
I've tried reinstalling chrome but this didn't fix the problem either.
I read somewhere online that freezing like this could be due to too much garbage collection? But what would be triggering this to happen in excess? And I don't understand why that would persist after I close google chrome.

A possible solution would be to build in an auto-refresher to refresh the page every hour once the user has been idle for at least 5 minute, but this seems a bit overkill if its a problem which can be solved.

Any tips/advice for debugging this kind of issue or obvious places I should search for a solution? as its very much un-shipable in its current state

答:
The issue was due to one of the two following things on windows 10. I performed both and one of them has caused the freezing to stop:
1) In control Panel -> Power options -> additional power settings -> change plan settings -> change advanced settings-> change the hard-drive sleep option to never or 0
2) Updated chip-set drivers from the motherboard manufacturers website.</p>


问:
Not getting any output when using filestreams in java
I've been stuck on this one section of my programming homework for a while and I can't seem to understand what's wrong. I'm supposed to use scanners to take in grades from an input file and put them into an array (not ArrayList). Then it should calculate the average, maximum and minimum and then print those out into a new separate text file. The program runs with no errors, but I get no output in my output file. Am I overthinking this?
Excuse the messy code, I'll fix it later.

```<code>import java.util.Scanner;
import java.io.*;
public class GradeStatistics {

public static void main(String[] args) throws FileNotFoundException {
    Scanner scanNum = new Scanner(new File("grades.txt"));
    double total = 0;
    int numStudents = 0;

    //traverse the file, counting the number of lines and save into numStudents
    while(scanNum.hasNextInt())
    {
        numStudents += 1;
    }

    int grades[] = new int[numStudents];    //create grades array

    Scanner scan2 = new Scanner("grades.txt");

    //populate the array
    for(int i = 0; i < grades.length; i++)
    {
        grades[i] = scan2.nextInt();
    }

    int max = grades[0];
    int min = grades[0];

    //find the max and min
    for(int i = 0; i < grades.length; i++)
    {
        total = total + grades[i];
        if(grades[i] > max)
        max = grades[i];
    }
    for(int i = 0; i < grades.length; i++)
    {
        if(grades[i] < min)
            min = grades[i];
    }
    double average = total / grades.length;     //calculate the average

    //create a new file "results.txt" to print our results
    FileOutputStream f = new FileOutputStream("results.txt");
    System.setOut(new PrintStream(f));
    System.out.printf("The average is: %.2f\n", average);
    System.out.println("The minimum is: " + min);
    System.out.println("The maximum is: " + max);
    scan2.close();
    scanNum.close();

}
</code>```

}

答:
This is an endless loop because it does not advance the file pointer:

```<code>while(scanNum.hasNextInt())
{
    numStudents += 1;
}
</code>```

This line contains also an error:

```<code>Scanner scan2 = new Scanner("grades.txt");
</code>```

Should be

```<code>Scanner scan2 = new Scanner(new File("grades.txt"));
</code>```

Body:
I've been stuck on this one section of my programming homework for a while and I can't seem to understand what's wrong. I'm supposed to use scanners to take in grades from an input file and put them into an array (not ArrayList). Then it should calculate the average, maximum and minimum and then print those out into a new separate text file. The program runs with no errors, but I get no output in my output file. Am I overthinking this?
Excuse the messy code, I'll fix it later.

import java.util.Scanner;
import java.io.*;
public class GradeStatistics {

public static void main(String[] args) throws FileNotFoundException {
    Scanner scanNum = new Scanner(new File("grades.txt"));
    double total = 0;
    int numStudents = 0;

    //traverse the file, counting the number of lines and save into numStudents
    while(scanNum.hasNextInt())
    {
        numStudents += 1;
    }

    int grades[] = new int[numStudents];    //create grades array

    Scanner scan2 = new Scanner("grades.txt");

    //populate the array
    for(int i = 0; i < grades.length; i++)
    {
        grades[i] = scan2.nextInt();
    }

    int max = grades[0];
    int min = grades[0];

    //find the max and min
    for(int i = 0; i < grades.length; i++)
    {
        total = total + grades[i];
        if(grades[i] > max)
        max = grades[i];
    }
    for(int i = 0; i < grades.length; i++)
    {
        if(grades[i] < min)
            min = grades[i];
    }
    double average = total / grades.length;     //calculate the average

    //create a new file "results.txt" to print our results
    FileOutputStream f = new FileOutputStream("results.txt");
    System.setOut(new PrintStream(f));
    System.out.printf("The average is: %.2f\n", average);
    System.out.println("The minimum is: " + min);
    System.out.println("The maximum is: " + max);
    scan2.close();
    scanNum.close();

}

}

Body:
This is an endless loop because it does not advance the file pointer:

while(scanNum.hasNextInt())
{
    numStudents += 1;
}

This line contains also an error:

Scanner scan2 = new Scanner("grades.txt");

Should be

Scanner scan2 = new Scanner(new File("grades.txt"));


问:
In NetLogo, how to access the coordinates and value of variables of neighbouring patches for a turtle?
For example, I would like to get the coordinates of the first patch above, below, to the left and right of the patch the turtle is currently on, as well as the value of a variable for each of those patches, such as plabel or pcolor. Essentially I would like to use this information so that then the agent can make a decision as to which patch to move to.

I think neighbors4 might be how to do this but I'm not quite sure of the code needed. For accessing variable values, I have been trying

```<code>let LabelsOfPatches neighbors4 [plabel]
</code>```

or

```<code>let ColorOfPatches neighbors4 [pcolor]
</code>```

But I get an error saying a command was expected in between the square brackets.

答:
A one-liner that does the same thing would be

```<code>let NeighborList [(list pxcor pycor pcolor plabel)] of neighbors4
</code>```

It can be run by either a turtle or a patch. of is great for making lists of values drawn from another agent or agentset.

Body:
For example, I would like to get the coordinates of the first patch above, below, to the left and right of the patch the turtle is currently on, as well as the value of a variable for each of those patches, such as plabel or pcolor. Essentially I would like to use this information so that then the agent can make a decision as to which patch to move to.

I think neighbors4 might be how to do this but I'm not quite sure of the code needed. For accessing variable values, I have been trying

let LabelsOfPatches neighbors4 [plabel]

or

let ColorOfPatches neighbors4 [pcolor]

But I get an error saying a command was expected in between the square brackets.

Body:
A one-liner that does the same thing would be

let NeighborList [(list pxcor pycor pcolor plabel)] of neighbors4

It can be run by either a turtle or a patch. of is great for making lists of values drawn from another agent or agentset.


问:
How to implement spacy lemmatizer with univ_pos argument
```<code>tokens = [The, wage, productivity, nexus, the, process, of, development,....]
</code>```

I am trying to convert a list of tokens into their lemmatized form using SpaCy's Lemmatizer. Here is the documentation I am using.

My code:

```<code>from spacy.lemmatizer import Lemmatizer
from spacy.lookups import Lookups
lookups = Lookups()
lookups.add_table("lemma_rules")
lemmatizer = Lemmatizer(lookups)
lemmas = []
for tokens in filtered_tokens:
    lemmas.append(lemmatizer(tokens))
</code>```

error message

```<code>TypeError                                 Traceback (most recent call last)
 in
      7 lemmas = []
      8 for tokens in filtered_tokens:
----> 9     lemmas.append(lemmatizer(tokens))

TypeError: __call__() missing 1 required positional argument: 'univ_pos'
</code>```

I understood in this discussion how SpaCy's Lemmatizer works and understand it in theory. However, I am not sure how I can implement this.

How can I find out the univ_pos for my tokens?

答:
Here's an example adapted from the spaCy documentation...

```<code>import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying U.K. startup for $1 billion")
for token in doc:
    print(token.text, token.pos_, token.lemma_)
</code>```

Here the .pos_ gives you the universal dependencies part of speech you're looking for in your original question.

However, tagging, lemmatizing, etc.. requires a full pipeline of components.  There is a tagger for adding the pos data.  If the Tokenizer is the only function in your pipeline then you probably won't have the pos info.

Body:
tokens = [The, wage, productivity, nexus, the, process, of, development,....]

I am trying to convert a list of tokens into their lemmatized form using SpaCy's Lemmatizer. Here is the documentation I am using.

My code:

from spacy.lemmatizer import Lemmatizer
from spacy.lookups import Lookups
lookups = Lookups()
lookups.add_table("lemma_rules")
lemmatizer = Lemmatizer(lookups)
lemmas = []
for tokens in filtered_tokens:
    lemmas.append(lemmatizer(tokens))

error message

TypeError                                 Traceback (most recent call last)
 in
      7 lemmas = []
      8 for tokens in filtered_tokens:
----> 9     lemmas.append(lemmatizer(tokens))

TypeError: __call__() missing 1 required positional argument: 'univ_pos'

I understood in this discussion how SpaCy's Lemmatizer works and understand it in theory. However, I am not sure how I can implement this.

How can I find out the univ_pos for my tokens?

Body:
Here's an example adapted from the spaCy documentation...

import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying U.K. startup for $1 billion")
for token in doc:
    print(token.text, token.pos_, token.lemma_)

Here the .pos_ gives you the universal dependencies part of speech you're looking for in your original question.

However, tagging, lemmatizing, etc.. requires a full pipeline of components.  There is a tagger for adding the pos data.  If the Tokenizer is the only function in your pipeline then you probably won't have the pos info.