问:
separate video from audio from ffmpeg stream
I already created a similar thread How to extract video and audio from ffmpeg stream in python , but within the framework of the consultations received, I could not implement what I asked about. I was not able to reopen the question and maybe formulate it in more detail. So I'm
asking the question here again.

I'm trying to implement a data parsing process (video and audio) from an ffmpeg stream for each frame. Ideally, I would like to get 1 numpy array per data type per unit of time. I studied an example with getting a numpy array from audio and video separately (when either one or the second is present in the stream)
and everything works successfully. Misunderstanding appears when there is both video and audio in the stream. It is not clear how many bytes to read information, and most importantly, what is in these bytes of audio, or is it video?

```<code>input_stream = ffmpeg.input(in_url)
video = input_stream.video.vflip()
out_stream = ffmpeg.output(
    input_stream.audio,
    video,
    filename='pipe:',
    format='rawvideo',
    pix_fmt='rgb24',
    acodec='pcm_s16le',
    ac=1,
    ar='16k'
)
process = out_stream.run_async(pipe_stdout=True)
while True:
    in_bytes = process.stdout.read(4096)
    # what next ?
</code>```

Thanks for help.

答:
For splitting the video and audio, you may map the video output to stderr pipe and map the audio output to stdout pipe.

                                            -----------
                                       --->| Raw Video | ---> stderr (pipe)
 -----------        -------------     |     -----------
| Input     |      | FFmpeg      |    |
| Video and | ---> | sub-process | ---
| Audio     |      |             |    |
 -----------        -------------     |     -----------
                                       --->| Raw Audio | ---> stdout (pipe)
                                            -----------
```
<hr />
<p>For creating a simple demonstration of the concept, the example uses synthetic video and audio as input.</p>
<p>The following FFmpeg CLI command may be used as reference:</p>
<pre class="lang-none prettyprint-override"><code>ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo vid.yuv -map 1:a -acodec pcm_s16le -ar 16384 -ac 1 -f:a s16le aud.pcm
</code>```

The above command creates synthetic video and synthetic audio, and maps the raw video to vid.yuv file, and maps the raw audio to aud.pcm file.

For testing, execute the above command, and keep vid.yuv and aud.pcm as references.

Instead of mapping the output to files, we may map the output to stderr and stdout:

ffmpeg -hide_banner -loglevel error -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo pipe:2 -acodec pcm_s16le -ar 16384 -ac 1 -map 1:a -f:a s16le pipe:1 -report
```
<p>Since we are using <code>stderr</code> for the video output, we need to avoid any printing to <code>stderr</code>, so we are adding <code>-hide_banner -loglevel error</code> arguments.</p>
<hr />
<p>The Python code sample, uses <code>subprocess</code> module, instead of using <code>ffmpeg-python</code>.<br />
I just couldn't figure out how to apply the mapping with <code>ffmpeg-python</code> module...</p>
<p>The Python code sample applies the following stages:</p>
<ul>
<li>Execute FFmpeg as sub-process using <code>sp.Popen</code>.<br />
Apply <code>stdout=sp.PIPE</code>, <code>stderr=sp.PIPE</code> for "capturing" <code>stdout</code> and <code>stderr</code> output pipes.</li>
<li>Start video reader thread.<br />
The video reader thread reads raw video frames from stderr.<br />
The thread writes the video to <code>video.yuv</code> binary file for testing.</li>
<li>Start audio reader thread.<br />
The audio reader thread reads raw audio samples from stdout.<br />
The thread writes the audio to <code>audio.pcm</code> binary file for testing.</li>
<li>Wait for the threads and the process to finish.</li>
</ul>
<hr />
<p>Here is a "stand alone" code sample:</p>
```import subprocess as sp
import shlex
import threading

# Reference command line (stores the video to vid.yuv and the audio to aud.pcm):
# sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo vid.yuv -acodec pcm_s16le -ar 16384 -ac 1 -map 1:a -f:a s16le aud.pcm'))

# Video reader thread.
def video_reader(pipe):
    f = open('video.yuv', 'wb')  # For testing - store the raw video to video.yuv (binary file)

    while True:
        frame = pipe.read(192*108*3)  # Read raw video frame

        # Break the loop when length is too small
        if len(frame) < 192*108*3:
            break

        f.write(frame)

    f.close()

# Audio reader thread.
def audio_reader(pipe):
    f = open('audio.pcm', 'wb')  # For testing - store the raw audio to audio.pcm (binary file)

    while True:
        samples = pipe.read(4096)  # Read raw audio packets (read 2048 samples in pcm_s16le format).

        # Break the loop when length is too small
        if len(samples) < 4096:
            break

        f.write(samples)

    f.close()

# Execute FFmpeg as sub-process
# Map the video to stderr and map the audio to stdout
process = sp.Popen(shlex.split('ffmpeg -hide_banner -loglevel error '                  # Set loglevel to error for disabling the prints ot stderr
                               '-f lavfi -i testsrc=size=192x108:rate=1:duration=10 '  # Synthetic video 192x108 at 1Hz (10 seconds)
                               '-f lavfi -i sine=frequency=400:r=16384:duration=10 '   # Synthetic audio mono, 16384 samples per second (10 seconds)
                               '-vcodec rawvideo -pix_fmt rgb24 '                      # Raw video codec with rgb24 pixel format
                               '-map 0:v -f:v rawvideo pipe:2 '                        # rawvideo format is mapped to stderr pipe
                               '-acodec pcm_s16le -ar 16384 -ac 1 '                    # Audio codec pcm_s16le (-ar 16k has no affect)
                               '-map 1:a -f:a s16le pipe:1 '                           # s16le audio format is mapped to stdout pipe
                               '-report'),                                             # Create a log file (because we can't the statuses that are usually printed to stderr).
                                stdout=sp.PIPE, stderr=sp.PIPE)

# Start video reader thread (pass stderr pipe as argument).
video_thread = threading.Thread(target=video_reader, args=(process.stderr,))
video_thread.start()

# Start audio reader thread (pass stdout pipe as argument).
audio_thread = threading.Thread(target=audio_reader, args=(process.stdout,))
audio_thread.start()

# Wait for threads (and process) to finish.
video_thread.join()
audio_thread.join()
process.wait()
```

For validation, compare video.yuv with vid.yuv and audio.pcm with aud.pcm.

The files should be identical.

Notes:

The answer is just a "proof of concept" template.

For adding filters (like) flip, and for getting the input from in_url there is still some work.

When having only one input, the mapping is: -map 0:v and -map 0:a.

The resolution of the input video should be known from advance.

In case the audio source is not mono audio with 16384 samples per second, you may need to use aresample filter (-ar 16k may not work).

Body:
I already created a similar thread How to extract video and audio from ffmpeg stream in python , but within the framework of the consultations received, I could not implement what I asked about. I was not able to reopen the question and maybe formulate it in more detail. So I'm
asking the question here again.

I'm trying to implement a data parsing process (video and audio) from an ffmpeg stream for each frame. Ideally, I would like to get 1 numpy array per data type per unit of time. I studied an example with getting a numpy array from audio and video separately (when either one or the second is present in the stream)
and everything works successfully. Misunderstanding appears when there is both video and audio in the stream. It is not clear how many bytes to read information, and most importantly, what is in these bytes of audio, or is it video?

input_stream = ffmpeg.input(in_url)
video = input_stream.video.vflip()
out_stream = ffmpeg.output(
    input_stream.audio,
    video,
    filename='pipe:',
    format='rawvideo',
    pix_fmt='rgb24',
    acodec='pcm_s16le',
    ac=1,
    ar='16k'
)
process = out_stream.run_async(pipe_stdout=True)
while True:
    in_bytes = process.stdout.read(4096)
    # what next ?

Thanks for help.

Body:
For splitting the video and audio, you may map the video output to stderr pipe and map the audio output to stdout pipe.

                                            -----------
                                       --->| Raw Video | ---> stderr (pipe)
 -----------        -------------     |     -----------
| Input     |      | FFmpeg      |    |
| Video and | ---> | sub-process | ---
| Audio     |      |             |    |
 -----------        -------------     |     -----------
                                       --->| Raw Audio | ---> stdout (pipe)
                                            -----------

For creating a simple demonstration of the concept, the example uses synthetic video and audio as input.

The following FFmpeg CLI command may be used as reference:

ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo vid.yuv -map 1:a -acodec pcm_s16le -ar 16384 -ac 1 -f:a s16le aud.pcm

The above command creates synthetic video and synthetic audio, and maps the raw video to vid.yuv file, and maps the raw audio to aud.pcm file.

For testing, execute the above command, and keep vid.yuv and aud.pcm as references.

Instead of mapping the output to files, we may map the output to stderr and stdout:

ffmpeg -hide_banner -loglevel error -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo pipe:2 -acodec pcm_s16le -ar 16384 -ac 1 -map 1:a -f:a s16le pipe:1 -report

Since we are using stderr for the video output, we need to avoid any printing to stderr, so we are adding -hide_banner -loglevel error arguments.

The Python code sample, uses subprocess module, instead of using ffmpeg-python.

I just couldn't figure out how to apply the mapping with ffmpeg-python module...

The Python code sample applies the following stages:

Execute FFmpeg as sub-process using sp.Popen.

Apply stdout=sp.PIPE, stderr=sp.PIPE for "capturing" stdout and stderr output pipes.

Start video reader thread.

The video reader thread reads raw video frames from stderr.

The thread writes the video to video.yuv binary file for testing.

Start audio reader thread.

The audio reader thread reads raw audio samples from stdout.

The thread writes the audio to audio.pcm binary file for testing.

Wait for the threads and the process to finish.

Here is a "stand alone" code sample:

import subprocess as sp
import shlex
import threading

# Reference command line (stores the video to vid.yuv and the audio to aud.pcm):
# sp.run(shlex.split('ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -f lavfi -i sine=frequency=400:r=16384:duration=10 -vcodec rawvideo -pix_fmt rgb24 -map 0:v -f:v rawvideo vid.yuv -acodec pcm_s16le -ar 16384 -ac 1 -map 1:a -f:a s16le aud.pcm'))

# Video reader thread.
def video_reader(pipe):
    f = open('video.yuv', 'wb')  # For testing - store the raw video to video.yuv (binary file)

    while True:
        frame = pipe.read(192*108*3)  # Read raw video frame

        # Break the loop when length is too small
        if len(frame) < 192*108*3:
            break

        f.write(frame)

    f.close()

# Audio reader thread.
def audio_reader(pipe):
    f = open('audio.pcm', 'wb')  # For testing - store the raw audio to audio.pcm (binary file)

    while True:
        samples = pipe.read(4096)  # Read raw audio packets (read 2048 samples in pcm_s16le format).

        # Break the loop when length is too small
        if len(samples) < 4096:
            break

        f.write(samples)

    f.close()

# Execute FFmpeg as sub-process
# Map the video to stderr and map the audio to stdout
process = sp.Popen(shlex.split('ffmpeg -hide_banner -loglevel error '                  # Set loglevel to error for disabling the prints ot stderr
                               '-f lavfi -i testsrc=size=192x108:rate=1:duration=10 '  # Synthetic video 192x108 at 1Hz (10 seconds)
                               '-f lavfi -i sine=frequency=400:r=16384:duration=10 '   # Synthetic audio mono, 16384 samples per second (10 seconds)
                               '-vcodec rawvideo -pix_fmt rgb24 '                      # Raw video codec with rgb24 pixel format
                               '-map 0:v -f:v rawvideo pipe:2 '                        # rawvideo format is mapped to stderr pipe
                               '-acodec pcm_s16le -ar 16384 -ac 1 '                    # Audio codec pcm_s16le (-ar 16k has no affect)
                               '-map 1:a -f:a s16le pipe:1 '                           # s16le audio format is mapped to stdout pipe
                               '-report'),                                             # Create a log file (because we can't the statuses that are usually printed to stderr).
                                stdout=sp.PIPE, stderr=sp.PIPE)

# Start video reader thread (pass stderr pipe as argument).
video_thread = threading.Thread(target=video_reader, args=(process.stderr,))
video_thread.start()

# Start audio reader thread (pass stdout pipe as argument).
audio_thread = threading.Thread(target=audio_reader, args=(process.stdout,))
audio_thread.start()

# Wait for threads (and process) to finish.
video_thread.join()
audio_thread.join()
process.wait()

For validation, compare video.yuv with vid.yuv and audio.pcm with aud.pcm.

The files should be identical.

Notes:

The answer is just a "proof of concept" template.

For adding filters (like) flip, and for getting the input from in_url there is still some work.

When having only one input, the mapping is: -map 0:v and -map 0:a.

The resolution of the input video should be known from advance.

In case the audio source is not mono audio with 16384 samples per second, you may need to use aresample filter (-ar 16k may not work).


来源: stackexchange

问:
Check if a string is null or empty in XSLT
How can I check if a value is null or empty with XSL?

For example, if categoryName is empty? I'm using a when choosing construct.

For example:

```<code><xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>
</code>```

答:
Something like this works for me:

```<code><xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when>
  <xsl:otherwise>
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>
</code>```

Or the other way around:

```<code><xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when>
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>
</code>```

Note: If you don't check null values or handle null values, IE7 returns -2147483648 instead of NaN.

ContentLicense: CC BY-SA 3.0

Body:
How can I check if a value is null or empty with XSL?

For example, if categoryName is empty? I'm using a when choosing construct.

For example:

<xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

Body:
Something like this works for me:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when>
  <xsl:otherwise>
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

Or the other way around:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when>
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

Note: If you don't check null values or handle null values, IE7 returns -2147483648 instead of NaN.


问:
How to separate just 'and' item from function ? React JS
I need to single out “and” within the array.

```<code>  useEffect(() => {
    if (!initialValues) {
      let filteredCommaNames = users
        .filter((user) => selectedUsers?.includes(user.uuid))
        .map((item) => {
          return item.name;
        })

        .join(", ");

      const replaceLastNameWithAnd = filteredCommaNames.replace(
        /,(?=[^,]*$)/,
        " and"
      );

      //result is like -> Michael, John, Ivan and Ronald ( in string )
      setNames(replaceLastNameWithAnd);
    }
  }, []);
</code>```

Here i separate all names into single array and just show it

```<code>   <strong>
    {selectedNames}
   </strong >
</code>```

And this is work good...
Result is bolded names example:

Michael, John, Ivan and Ronald

What i need ?

To bold only names without and and to be:

Michael, John, Ivan and Ronald

How to do it ?

答:
You might be able to use Intl.Listformat  (note lack of IE support)

const names = ["Michael", "John", "Ivan", "Ronald"]
const formatter = new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction'
});
console.log(formatter.format(names));

console.log(formatter.formatToParts(names))```
</div>
</div>
</p>
```export default function App() {
  return (

      {formatter.formatToParts(names).map(({ type, value }, i) => {
        if (type === "element") {
          return {value};
        }
        if (type === "literal") {
          return i === formatter.formatToParts(names).length - 2
            ? removeComma(value)
            : value;
        }
      })}

  );
}

function removeComma(literalValue) {
  return literalValue.replace(/,/, "");
}

```

ContentLicense: CC BY-SA 4.0

Body:
I need to single out “and” within the array.

  useEffect(() => {
    if (!initialValues) {
      let filteredCommaNames = users
        .filter((user) => selectedUsers?.includes(user.uuid))
        .map((item) => {
          return item.name;
        })

        .join(", ");

      const replaceLastNameWithAnd = filteredCommaNames.replace(
        /,(?=[^,]*$)/,
        " and"
      );

      //result is like -> Michael, John, Ivan and Ronald ( in string )
      setNames(replaceLastNameWithAnd);
    }
  }, []);

Here i separate all names into single array and just show it

    {selectedNames}

And this is work good...
Result is bolded names example:

Michael, John, Ivan and Ronald

What i need ?

To bold only names without and and to be:

Michael, John, Ivan and Ronald

How to do it ?

Body:
You might be able to use Intl.Listformat  (note lack of IE support)

const names = ["Michael", "John", "Ivan", "Ronald"]
const formatter = new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction'
});
console.log(formatter.format(names));

console.log(formatter.formatToParts(names))

export default function App() {
  return (
    <div className="App">
      {formatter.formatToParts(names).map(({ type, value }, i) => {
        if (type === "element") {
          return <strong>{value}</strong>;
        }
        if (type === "literal") {
          return i === formatter.formatToParts(names).length - 2
            ? removeComma(value)
            : value;
        }
      })}
    </div>
  );
}

function removeComma(literalValue) {
  return literalValue.replace(/,/, "");
}


问:
React function arrow
I am new to react and arrow function,  I have the following code

```<code>const users = (props) => {
   return (props.users);
}
</code>```

here is props

```<code>userDialogs.propTypes = {
   users: Proptypes.array.isRequired
};
</code>```

and this how I use, but it gives me error, map is not function

```<code>{users.map((username, index) => {
   return <b>{username}</b>
})}
</code>```

答:
.map() is a function of an Array - but users does not contain an Array here. Your code assigns an anonymous function to users, so an error is thrown when you try to access its non-existent map() function. As long as props.users is already an Array, just assign it directly to users:

```<code>const users = props.users;
</code>```

Title: React function arrow

Body:
I am new to react and arrow function,  I have the following code

const users = (props) => {
   return (props.users);
}

here is props

userDialogs.propTypes = {
   users: Proptypes.array.isRequired
};

and this how I use, but it gives me error, map is not function

{users.map((username, index) => {
   return {username}
})}

Body:
.map() is a function of an Array - but users does not contain an Array here. Your code assigns an anonymous function to users, so an error is thrown when you try to access its non-existent map() function. As long as props.users is already an Array, just assign it directly to users:

const users = props.users;


问:
foreach on parsing xml but shows only one record
```<code>foreach($xml1->results as $info) {
                    $title = $info->listing->title;
                    $favicon = $info->listing->favicon;

                    echo $favicon;
                    echo "<a href=".$redirect;
                    echo ">".$title."</a><BR>";

                }
</code>```

The output is all fine, but only showing one record.  What could be the problem.

XML Structure

```<code><listing>
   <title></title>
   <url></url>
   <description>[result-description]</description>
</listing>
</code>```

答:
This works for me:</p>

```<code>$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<results>
    <listing>
        <title>title 1</title>
        <favicon>fav1</favicon>
    </listing>
    <listing>
        <title>title 2</title>
        <favicon>fav2</favicon>
    </listing>
</results>
";

$xmlObj=simplexml_load_string($xml);

foreach($xmlObj as $info){
    $title = $info->title;
    $favicon = $info->favicon;

    echo $favicon;
    echo "<a href=''";
    echo ">".$title."</a><BR>";

}
</code>```

Body:
foreach($xml1->results as $info) {
                    $title = $info->listing->title;
                    $favicon = $info->listing->favicon;

                    echo $favicon;
                    echo "".$title."
";

                }

The output is all fine, but only showing one record.  What could be the problem.

XML Structure

<listing>
   <title></title>
   <url></url>
   <description>[result-description]</description>
</listing>

Body:
This works for me:

$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<results>
    <listing>
        <title>title 1</title>
        <favicon>fav1</favicon>
    </listing>
    <listing>
        <title>title 2</title>
        <favicon>fav2</favicon>
    </listing>
</results>
";

$xmlObj=simplexml_load_string($xml);

foreach($xmlObj as $info){
    $title = $info->title;
    $favicon = $info->favicon;

    echo $favicon;
    echo "<a href=''";
    echo ">".$title."</a><BR>";

}


问:
Why does jest mockResolvedValueOnce called multiple times returns the same value?
I have a class method where I trigger a @google-cloud/firestore multiple times. I would like to mock the call over the same .get() method multiple times.
Using a mockResolvedValueOnce multiple times with different values to return, the 2nd value is ignored.

```<code>    jest.doMock('@google-cloud/firestore', () => class {
      collection () {
        return {
          get: jest.fn().mockResolvedValue({
            docs: []
          }),
          doc: () => {
            return {
              set: jest.fn(),
              get: jest.fn().mockResolvedValueOnce({})
            }
          },
          limit: () => {
            return {
              get: jest.fn().mockResolvedValue({ empty: true })
            }
          },
          onSnapshot: jest.fn(),
          select: () => {
            return {
              get: jest.fn() // <------------ MULTIPLE CALLS CHAINED BELOW
                .mockResolvedValueOnce({
                  size: 1
                }).mockResolvedValueOnce({
                  size: 2
                })
            }
          }
        }
      }
    })
</code>```

When I console.log(snapshot.size) it returns me the same value "1" twice for both calls.

```<code>if (isEmptyModels || isStatsEmptyModels) {
  // ...
  console.log(' [STATS][MODELS] - Fulfilling the counters')
  await Database.collection('models').select('id').get().then(snapshot => {
    console.log(snapshot.size) // <--------- 1st call
    this.fields.models.count = snapshot.size
    this.fields.models.linked = snapshot.size
  })
  // ...
}

if (isEmptyProducts1P || isStatsEmptyProducts1P) {
  // ...
  console.log(' [STATS][PRODUCTS1P] - Fulfilling the counters')
  await Database.collection('products1P').select('isMaintained').get().then(snapshot => {
    console.log(snapshot.size) // <--------- 2nd call
    snapshot.forEach(doc => {
      if (doc.data().isMaintained) {
        // ...
      }
    })
    // ...
  })
  // ...
}
</code>```

Why is that, and what is done wrong here ?

Error message is:

```<code>  console.log
     [STATS][MODELS] - Fulfilling the counters

      at Statistics.fulfillProductsCount (app/services/statistics/index.js:95:15)

  console.log
    1

      at app/services/statistics/index.js:97:17

  console.log
     [STATS][PRODUCTS1P] - Fulfilling the counters

      at Statistics.fulfillProductsCount (app/services/statistics/index.js:106:15)

  console.log
    1

      at app/services/statistics/index.js:108:17

    TypeError: snapshot.forEach is not a function

      117 |       await Database.collection('products1P').select('isMaintained').get().then(snapshot => {
      118 |         console.log(snapshot.size)
    > 119 |         snapshot.forEach(doc => {
          |                  ^
      120 |           if (doc.data().isMaintained) {
      121 |             this.fields.products1P.maintained += 1
      122 |           } else {

      at app/services/statistics/index.js:119:18
</code>```

答:
This happens because each time you call Database.collection(), it creates a new object, and as a new object, this is the first time its properties are called. It is also valid for the others functions inside collection.

What I mean is that Database.collection is a function that returns an object that contains other functions that return object that contains properties mocked. By mocking this way, you will never be able to use mock...ValueOnce. But, I see two ways to "bypass" this problem :

1 - The short but conflicting way

You can use .mockReturnThis() to avoid entering into deep mock objects/functions, but in may be quickly conflicting when dealing with "fat" classes that have multiple times the same method names. In can also be helpful when mocking chainable methods (example: ORM queries with .find().filter().sort()...).

```<code>jest.doMock('@google-cloud/firestore', () => class {
  collection = jest.fn().mockReturnThis();
  select = jest.fn().mockReturnThis();
  get = jest.fn().mockResolvedValueOnce({ size: 1 }).mockResolvedValueOnce({ size: 2 });
})
</code>```

2 - The Long but working way

Mock the whole collection method Once instead of mocking only  collection().select().get().

```<code>Database.collection.prototype.mockReturnValueOnce({
  select: () => {
    get: () => ({ size: 1 })
  }
}).mockReturnValueOnce({
  select: () => {
    get: () => ({ size: 2 })
  }
})
</code>```

--> You will need access to the mocked Class and mock the method "collection" of the prototype (collection = jest.fn()).

Body:
I have a class method where I trigger a @google-cloud/firestore multiple times. I would like to mock the call over the same .get() method multiple times.
Using a mockResolvedValueOnce multiple times with different values to return, the 2nd value is ignored.

    jest.doMock('@google-cloud/firestore', () => class {
      collection () {
        return {
          get: jest.fn().mockResolvedValue({
            docs: []
          }),
          doc: () => {
            return {
              set: jest.fn(),
              get: jest.fn().mockResolvedValueOnce({})
            }
          },
          limit: () => {
            return {
              get: jest.fn().mockResolvedValue({ empty: true })
            }
          },
          onSnapshot: jest.fn(),
          select: () => {
            return {
              get: jest.fn() // <------------ MULTIPLE CALLS CHAINED BELOW
                .mockResolvedValueOnce({
                  size: 1
                }).mockResolvedValueOnce({
                  size: 2
                })
            }
          }
        }
      }
    })

When I console.log(snapshot.size) it returns me the same value "1" twice for both calls.

if (isEmptyModels || isStatsEmptyModels) {
  // ...
  console.log(' [STATS][MODELS] - Fulfilling the counters')
  await Database.collection('models').select('id').get().then(snapshot => {
    console.log(snapshot.size) // <--------- 1st call
    this.fields.models.count = snapshot.size
    this.fields.models.linked = snapshot.size
  })
  // ...
}

if (isEmptyProducts1P || isStatsEmptyProducts1P) {
  // ...
  console.log(' [STATS][PRODUCTS1P] - Fulfilling the counters')
  await Database.collection('products1P').select('isMaintained').get().then(snapshot => {
    console.log(snapshot.size) // <--------- 2nd call
    snapshot.forEach(doc => {
      if (doc.data().isMaintained) {
        // ...
      }
    })
    // ...
  })
  // ...
}

Why is that, and what is done wrong here ?

Error message is:

  console.log
     [STATS][MODELS] - Fulfilling the counters

      at Statistics.fulfillProductsCount (app/services/statistics/index.js:95:15)

  console.log
    1

      at app/services/statistics/index.js:97:17

  console.log
     [STATS][PRODUCTS1P] - Fulfilling the counters

      at Statistics.fulfillProductsCount (app/services/statistics/index.js:106:15)

  console.log
    1

      at app/services/statistics/index.js:108:17

    TypeError: snapshot.forEach is not a function

      117 |       await Database.collection('products1P').select('isMaintained').get().then(snapshot => {
      118 |         console.log(snapshot.size)
    > 119 |         snapshot.forEach(doc => {
          |                  ^
      120 |           if (doc.data().isMaintained) {
      121 |             this.fields.products1P.maintained += 1
      122 |           } else {

      at app/services/statistics/index.js:119:18

Body:
This happens because each time you call Database.collection(), it creates a new object, and as a new object, this is the first time its properties are called. It is also valid for the others functions inside collection.

What I mean is that Database.collection is a function that returns an object that contains other functions that return object that contains properties mocked. By mocking this way, you will never be able to use mock...ValueOnce. But, I see two ways to "bypass" this problem :

1 - The short but conflicting way

You can use .mockReturnThis() to avoid entering into deep mock objects/functions, but in may be quickly conflicting when dealing with "fat" classes that have multiple times the same method names. In can also be helpful when mocking chainable methods (example: ORM queries with .find().filter().sort()...).

jest.doMock('@google-cloud/firestore', () => class {
  collection = jest.fn().mockReturnThis();
  select = jest.fn().mockReturnThis();
  get = jest.fn().mockResolvedValueOnce({ size: 1 }).mockResolvedValueOnce({ size: 2 });
})

2 - The Long but working way

Mock the whole collection method Once instead of mocking only  collection().select().get().

Database.collection.prototype.mockReturnValueOnce({
  select: () => {
    get: () => ({ size: 1 })
  }
}).mockReturnValueOnce({
  select: () => {
    get: () => ({ size: 2 })
  }
})

--> You will need access to the mocked Class and mock the method "collection" of the prototype (collection = jest.fn()).


问:
How to return empty array in a case block?
working on a trigger in Postgres. Currently running into an issue where I'm trying to set a value as either an empty array or an array with just the one NEW value, depending on if there is a NEW value or not:

project_ids =
  CASE NEW.project_tracking_id
    WHEN null THEN ARRAY
    ELSE ARRAY[NEW.project_tracking_id]
  END
```
<p>"Set <code>project_ids</code> to either <code>[]</code> (if null) or <code>[NEW.project_tracking_id]</code>"</p>
<p>The else block works as expected and will store that new value as the first element in a new array. The <code>WHEN null THEN ARRAY</code> part does not work for me though. It just adds <code>null</code> to the array, producing <code>[null]</code>.</p>
<p>How do I specify that it should just be an empty array in that case? Not sure if this helps, but my <code>sequelize</code> type for that field is:</p>
<pre class="lang-js prettyprint-override"><code>type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: [],
</code>```

答:
```<code>project_ids =
  CASE NEW.project_tracking_id
    WHEN null THEN ARRAY[]::XXX[]   //XXX is the type of the array.
    ELSE ARRAY[NEW.project_tracking_id]
  END
</code>```

Body:
working on a trigger in Postgres. Currently running into an issue where I'm trying to set a value as either an empty array or an array with just the one NEW value, depending on if there is a NEW value or not:

project_ids =
  CASE NEW.project_tracking_id
    WHEN null THEN ARRAY
    ELSE ARRAY[NEW.project_tracking_id]
  END

"Set project_ids to either [] (if null) or [NEW.project_tracking_id]"

The else block works as expected and will store that new value as the first element in a new array. The WHEN null THEN ARRAY part does not work for me though. It just adds null to the array, producing [null].

How do I specify that it should just be an empty array in that case? Not sure if this helps, but my sequelize type for that field is:

type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: [],


问:
Mobile Scrolling Bug
I was developing a small one page next app when I discovered a "bug".

And I don't know how to fix it. Mobile Screen

Link to the site: Preview

Current behaviour:

Screen Glitches when scrolling on mobile.

Expected behaviour:

No white space on the bottom part

Steps to reproduce:

Scroll up until the Chrome header hides

The white space appears on the bottom while the header fades away

For some reason it glitches when scrolling.
I tried setting the body to calc(100vh + 60px) (Header height)

But this doesn't fix the behavior.

Short snippet:

```<code><main>
  <section className={'wrapper'}/>
  <section className={'wrapper'}/>
  <section className={'wrapper'}/>
  <section className={'wrapper'}/>
<main>
</code>```

the corresponding CSS:

```<code>body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  background-attachment: fixed;
  animation: gradient 15s ease infinite;
  height: calc(100vh + 60px);
  margin: 0;
  padding: 0;
}
html {
  scroll-behavior: smooth;
}
main {
  min-height: 100vh;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper {
  height: calc(100vh - 100px);
  width: 100%;
  max-width: 1000px;
  padding-top: 80px;
}
</code>```

The white space in the picture linked above fixes itself after the scroll.
It matches the height of the Chrome header
It seems that the Chromeheader does not affect the height: 100vh
Is my CSS wrong or is it a Bug?

I use a OnePlus 6
OxygenOS 11.1.2.2
Chrome: 98.0.4758.87

答:
If the header is fixed, you don't need make the calc, Even if the header if not fixed, you have to subtract and not add.

try it:

```<code>body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  background-attachment: fixed;
  animation: gradient 15s ease infinite;
  height: 100vh;
  margin: 0;
  padding: 0;
}
html {
  scroll-behavior: smooth;
}
main {
  min-height: 100vh;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper {
  height: calc(100vh - 100px);
  width: 100%;
  max-width: 1000px;
  padding-top: 80px;
}
</code>```

Title: Mobile Scrolling Bug

Body:
I was developing a small one page next app when I discovered a "bug".

And I don't know how to fix it. Mobile Screen

Link to the site: Preview

Current behaviour:

Screen Glitches when scrolling on mobile.

Expected behaviour:

No white space on the bottom part

Steps to reproduce:

Scroll up until the Chrome header hides

The white space appears on the bottom while the header fades away

For some reason it glitches when scrolling.
I tried setting the body to calc(100vh + 60px) (Header height)

But this doesn't fix the behavior.

Short snippet:

the corresponding CSS:

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  background-attachment: fixed;
  animation: gradient 15s ease infinite;
  height: calc(100vh + 60px);
  margin: 0;
  padding: 0;
}
html {
  scroll-behavior: smooth;
}
main {
  min-height: 100vh;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper {
  height: calc(100vh - 100px);
  width: 100%;
  max-width: 1000px;
  padding-top: 80px;
}

The white space in the picture linked above fixes itself after the scroll.
It matches the height of the Chrome header
It seems that the Chromeheader does not affect the height: 100vh
Is my CSS wrong or is it a Bug?

I use a OnePlus 6
OxygenOS 11.1.2.2
Chrome: 98.0.4758.87

Body:
If the header is fixed, you don't need make the calc, Even if the header if not fixed, you have to subtract and not add.

try it:

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  background-attachment: fixed;
  animation: gradient 15s ease infinite;
  height: 100vh;
  margin: 0;
  padding: 0;
}
html {
  scroll-behavior: smooth;
}
main {
  min-height: 100vh;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper {
  height: calc(100vh - 100px);
  width: 100%;
  max-width: 1000px;
  padding-top: 80px;
}


问:
Prometheus no metric clears alert
We use Prometheus to watch metrics of our own application. The API of our application offers an endpoint to deliver the metrics to Prometheus. Prometheus is scraping the information every 30s.

Based on the metrics we defined some alerts, which are firing to Alertmanager and then trigger email alerting, Slack messages or are shown in Alerta.

From time to time our application can't deliver the metrics and the Prometheus scraper is running in a timeout. Whenever a metric is missing in such a moment, the corresponding alert gets cleared (within Email, Slack, Alerta).

After 30sec our application delivers metrics again and a new alert is raised by Prometheus (which again triggers Emails, Slack messages and shows up a new alert in Alerta).

A missing metric is no reason to clear out an alert if no metric is given, on which the clearance of an alert might be based on (at least in our opinion).

Is there any option to configure Prometheus or Alertmanager in a way, that an alert is only solved/cleared if a metric leads to that (instead of interpreting the lack of metric as a clearance of an alert)?

答:
This can be done by using the aggregation function last_over_time().

For example, say your metric of interest is: probe_success

And your alert expression currently is: probe_success == 0

This will return no value if the metric is absent, and thus your alert clears creating the issue you described.

Instead change your alert expression to: last_over_time(probe_success[12h]) == 0

That will instead return the last metric value that was recorded in the past 12 hours.  Adjust the time range to however long you are willing to tolerate that metric being absent while still assuming it will return.

Title: Prometheus no metric clears alert


问:
Python if statement optimisation
I am making a pretty basic password generator which asks the user for certain things they want in the password (e.g. the user can choose whether or not they want punctuation ). I've completed the program, and it runs perfectly fine, but it includes a section of if and statements:

```<code>if p == "N" and ucl == "N" and lcl == "N":
    print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
    x = lclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
    x = uclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
    x = uclList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
    x = pList + uclList + lclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
    x = pList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
    x = pList + uclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
    x = pList
    generate(x)
</code>```

As I said, it runs fine, but looks real messy and inefficient - I can already imagine how convoluted it would have to be if I used 4 requirements, and god forbid any more. Is there another way of programming this that would make it repeatable and more efficient?

Side note, this is pretty much the first fully functioning program I've wrote, so don't be shocked if I've broken some programming Geneva convention.

答:
You could initialize x as an empty list and then, depending on the choices of the user, add the things they want to add to it:

```<code>x = []

if lcl == "Y":
    x += lclList
if ucl == "Y":
    x += uclList
if p == "Y":
    x += pList

generate(x)
</code>```

Title: Python if statement optimisation

Body:
I am making a pretty basic password generator which asks the user for certain things they want in the password (e.g. the user can choose whether or not they want punctuation ). I've completed the program, and it runs perfectly fine, but it includes a section of if and statements:

if p == "N" and ucl == "N" and lcl == "N":
    print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
    x = lclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
    x = uclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
    x = uclList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
    x = pList + uclList + lclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
    x = pList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
    x = pList + uclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
    x = pList
    generate(x)

As I said, it runs fine, but looks real messy and inefficient - I can already imagine how convoluted it would have to be if I used 4 requirements, and god forbid any more. Is there another way of programming this that would make it repeatable and more efficient?

Side note, this is pretty much the first fully functioning program I've wrote, so don't be shocked if I've broken some programming Geneva convention.

Body:
You could initialize x as an empty list and then, depending on the choices of the user, add the things they want to add to it:

x = []

if lcl == "Y":
    x += lclList
if ucl == "Y":
    x += uclList
if p == "Y":
    x += pList

generate(x)


问:
Using remote MySQL database on Heroku running Django app
I've been struggling with the following problem:
I have a MySQL database running on a remote web host. I connect to the MySQL database in my Django app (I use it as the main database). The Django app is running on a Heroku server but I get different data results  compared to running it locally.

Am I missing something, or are changes done on Heroku not committed to the database?

MySQL settings:

```<code>DATABASES = {
 #   'default': {
  #      'ENGINE': 'django.db.backends.sqlite3',
   #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}
</code>```

答: I just see that if you delete the ad-on provided by heroku, it will use the DB you put on the settings of your project</p>

Body:
I've been struggling with the following problem:
I have a MySQL database running on a remote web host. I connect to the MySQL database in my Django app (I use it as the main database). The Django app is running on a Heroku server but I get different data results  compared to running it locally.

Am I missing something, or are changes done on Heroku not committed to the database?

MySQL settings:

DATABASES = {
 #   'default': {
  #      'ENGINE': 'django.db.backends.sqlite3',
   #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}


问:
What exact sequence of control characters ends a comment in C++?
The book A Tour of C++ states that

The double slash, //, begins a comment that extends to the end of the line.

What exact sequence of control characters constitutes the "end of line".

According to this wikipedia article, there are four different ways to represent a new line in ASCII.

These are the following sequences:

LF

CR

LF CR

CR LF

Will all of these work to separate the end of a comment from the beginning of the next line of code?

答:
According to the C++ 14 Standard (2.2 Phases of translation)

1 The precedence among the syntax rules of translation is specified by
the following phases.

Physical source file characters are mapped, in an implementation-defined manner, to the basic source  character set
(introducing new-line characters for end-of-line indicators) if
necessary.

So the end of a line is indicated by the new line character '\n'.


问:
Need help changing jquery to javascript for an on change function
I am trying to change some jQuery code to plain JS for an on call function. I keep getting the following error - Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.

Old

```<code>$(document).on('change', '.js-variant-radio', onVariantRadioChange);

</code>```

New

```<code>document.querySelector('.js-variant-radio').addEventListener("change", onVariantRadioChange);
</code>```

Complete code block here

```<code>(function(){
  //START QUANTITY INPUT VALIDATION FUNCTION
  let
    onVariantRadioChange = function(event) {
      let
        $radio = document.querySelector(this),
        $form = $radio.closest('form'),
        max = $radio.attr('data-inventory-quantity'),
        $quantity = $form.querySelector('.js-quantity-field'),
        $addToCartButton = $form.querySelector('.add-to-cart-button');

      if($addToCartButton.prop('disabled') === true) {
        $addToCartButton.prop('disabled', false);
      }

      $quantity.attr('max', max);

      if (parseInt($quantity.value) > max) {
        $quantity.val(max).change();
      }
    };

    //END QUANTITY INPUT VALIDATION FUNCTION
})();
</code>```

答:
Here is your code in vanillaJS. The only thing I didn't do is mimic the change() trigger that was appended

document.addEventListener('DOMContentLoaded', () => {
  let
    onVariantRadioChange = function(event) {
      let
        $radio = event.target,
        $form = $radio.closest('form'),
        max = $radio.dataset['inventory-quantity'],
        $quantity = $form.querySelector('.js-quantity-field'),
        $addToCartButton = $form.querySelector('.add-to-cart-button');

      if ($addToCartButton.getAttribute('disabled')) {
        $addToCartButton.removeAttribute('disabled');
      }

      $quantity.setAttribute('max', max);

      if (parseInt($quantity.value) > max) {
        $quantity.value = max;
      }
    };

  document.querySelectorAll('.js-variant-radio').foreach(el => el.addEventListener("change", onVariantRadioChange));
})```

Body:
I am trying to change some jQuery code to plain JS for an on call function. I keep getting the following error - Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.

Old

$(document).on('change', '.js-variant-radio', onVariantRadioChange);

New

document.querySelector('.js-variant-radio').addEventListener("change", onVariantRadioChange);

Complete code block here

(function(){
  //START QUANTITY INPUT VALIDATION FUNCTION
  let
    onVariantRadioChange = function(event) {
      let
        $radio = document.querySelector(this),
        $form = $radio.closest('form'),
        max = $radio.attr('data-inventory-quantity'),
        $quantity = $form.querySelector('.js-quantity-field'),
        $addToCartButton = $form.querySelector('.add-to-cart-button');

      if($addToCartButton.prop('disabled') === true) {
        $addToCartButton.prop('disabled', false);
      }

      $quantity.attr('max', max);

      if (parseInt($quantity.value) > max) {
        $quantity.val(max).change();
      }
    };

    //END QUANTITY INPUT VALIDATION FUNCTION
})();


问:
Maintain Two Types Of User
So I have a requirement where I have to maintain two types of users.

A company and all of its users, to manage day-to-day work. And also create public data like showing a few items and related images and set availability for meetings and more.

Public user who can see the items, images. and can book the meetings.

Now for the first case, every user is created by official email and password as registeruser endpoint from rest-framework. there is user profile and other company data.

For the second type of user (public), I have to give access for social login as well as login by email/mobile (maybe).

I am confused as how to configure this in the best possible way. the company datas' are important.

Should I create both user types in the same database (differentiating by user types)? or should I use a seprerate database then how to fetch data from two databases (never done this)?  Also to keep my datas safe from unauthorized access.

Or is there a better way to manage all of my requirements which I'm totally unaware of? Like a better approach.

Looking for an explanation from an experienced person.
Thanks

答:
Maybe what you want is creating a custom User model (or even keep the default one) and implement permissions on views/ressource. This can be implemented by groups, for instance, the public group, in which everyone is (can be public or even no groups) and the private group.

Once you can differentiate between your users, you can add a reference to a ressource and its subressource to the group (ForeignKey on the group) and filters necessary queryset laters on your view. On certain view, you can also restrict some endpoints, through permissions.

Another way would be to use Object Permissions.
Anyway here are the ressources :

https://www.django-rest-framework.org/api-guide/permissions/ (and django-guardian for object-level permission)

and

https://docs.djangoproject.com/en/4.0/topics/auth/default/#permissions-and-authorization

Also, you can take a look on how it is implemented on a opensource project like Sentry: https://github.com/getsentry/sentry/blob/master/src/sentry/api/endpoints/api_applications.py

Title: Maintain Two Types Of User


问:
Regex to truncate last 4 characters and make sure it doesn't contain specific words
I get strings such as "BumpCardV2Resource.getInstance.Time" or "BumpCardWebResource.getInstance.Time" or "BumpCardResource.getInstance.Time". I need a regex expression to obtain only "BumpCardResource.getInstance"

Currently, I'm using a negative look ahead to make sure the string does not contain V2 or Web but not sure how to truncate the last 5 characters (.Time) along with that.

Regex I'm using: /^(?!.*V2|.*WebResource).*$/

PS - The resource and the API endpoint keeps changing. It need not be necessarily only BumpCard or getInstance

答:
You can use a regex where you match the whole string and capture any text from the start of the string till .Time at the end of it:

/^(?!.*V2|.*WebResource)(.*)\.Time$/
```

See the regex demo. Details:

^ - start of string

(?!.*V2|.*WebResource)  - no V2 or WebResource allowed anywhere in the string

(.*) - Capturing group 1: any zero or more chars other than line break chars as many as possible

\.Time - .Time string

$ - end of string.

Body:
You can use a regex where you match the whole string and capture any text from the start of the string till .Time at the end of it:

/^(?!.*V2|.*WebResource)(.*)\.Time$/

See the regex demo. Details:

^ - start of string

(?!.*V2|.*WebResource)  - no V2 or WebResource allowed anywhere in the string

(.*) - Capturing group 1: any zero or more chars other than line break chars as many as possible

\.Time - .Time string

$ - end of string.


问:
Using Set instead of List cause "Could not write JSON: Infinite recursion" exception
I was getting the error "Could not write JSON: Infinite recursion" when trying to access the endpoint http://localhost:8080/categoryOfPermissions. I've researched and found various solutions here (@JsonManagedReference / @JsonBackReference, @JsonIgnore, @JsonIdentityInfo), but none of them seemed to work. Finally, I found an answer stating that it was necessary to change from Set to List, in order for the @JsonIdentityInfo solution to work. I tested it an it really starts to work after changing from Set to List.

I thought that it was strange, but I found out something even stranger: after changing from Set to List, I removed the @JsonIdentityInfo annotations and everything continued to work. In other words, all that I really needed to do was changing from Set to List to get rid of the exception. Nothing else. No need of any of the solutions :@JsonManagedReference / @JsonBackReference, @JsonIgnore, @JsonIdentityInfo.

Below is the code that was producing the exception. All I had to do was changing private Set<Permission> permission to private List<Permission> permission.

I would like to know why, especially because I would prefer to use Set, in order to avoid Hibernate to use the "Bags" paradigm (which may cause some undesirable behaviors).

Permission.java :

```<code>@Entity
@Data
public class Permission{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank
    private String name;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_of_permission_id")
    private CategoryOfPermission categoryOfPermission;
}
</code>```

CategoryOfPermission.java :

```<code>@Entity
@Data
public class CategoryOfPermission{

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

    @NotBlank
    private String name;

    @NotNull
    @OneToMany(mappedBy = "categoryOfPermission", fetch=FetchType.LAZY)
    private Set<Permission> permission;
}
</code>```

CategoryOfPermissionRepo.java :

```<code>public interface CategoryOfPermissionRepo extends CrudRepository<CategoryOfPermission, Integer>{
}
</code>```

答:
It is because Set in Java uses equals contract to determine whether two objects are the same or not, and the way equals method in Permission class is implemented(using lombok) causes infinite recursion.

it is part of the generated code for equals method in  Permission

```<code>    Object this$categoryOfPermission = this.getCategoryOfPermission();
    Object other$categoryOfPermission = other.getCategoryOfPermission();
    if (this$categoryOfPermission == null) {
      if (other$categoryOfPermission != null) {
        return false;
      }
    } else if (!this$categoryOfPermission.equals(other$categoryOfPermission)) {
      return false;
    }
</code>```

and it is the generated code for the CategoryOfPermission class

```<code>public boolean equals(final Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof CategoryOfPermission)) {
      return false;
    } else {
      CategoryOfPermission other = (CategoryOfPermission)o;
      if (!other.canEqual(this)) {
        return false;
      } else {
        Object this$id = this.getId();
        Object other$id = other.getId();
        if (this$id == null) {
          if (other$id != null) {
            return false;
          }
        } else if (!this$id.equals(other$id)) {
          return false;
        }

        Object this$permission = this.getPermission();
        Object other$permission = other.getPermission();
        if (this$permission == null) {
          if (other$permission != null) {
            return false;
          }
        } else if (!this$permission.equals(other$permission)) {
          return false;
        }

        return true;
      }
    }
  }
</code>```

as you see Permission class calls equals method of CategoryOfPermission class and CategoryOfPermission calls equals method of Permision class which finally causes stackoverflow problem!.

Body:
I was getting the error "Could not write JSON: Infinite recursion" when trying to access the endpoint http://localhost:8080/categoryOfPermissions. I've researched and found various solutions here (@JsonManagedReference / @JsonBackReference, @JsonIgnore, @JsonIdentityInfo), but none of them seemed to work. Finally, I found an answer stating that it was necessary to change from Set to List, in order for the @JsonIdentityInfo solution to work. I tested it an it really starts to work after changing from Set to List.

I thought that it was strange, but I found out something even stranger: after changing from Set to List, I removed the @JsonIdentityInfo annotations and everything continued to work. In other words, all that I really needed to do was changing from Set to List to get rid of the exception. Nothing else. No need of any of the solutions :@JsonManagedReference / @JsonBackReference, @JsonIgnore, @JsonIdentityInfo.

Below is the code that was producing the exception. All I had to do was changing private Set<Permission> permission to private List<Permission> permission.

I would like to know why, especially because I would prefer to use Set, in order to avoid Hibernate to use the "Bags" paradigm (which may cause some undesirable behaviors).

Permission.java :

@Entity
@Data
public class Permission{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank
    private String name;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_of_permission_id")
    private CategoryOfPermission categoryOfPermission;
}

CategoryOfPermission.java :

@Entity
@Data
public class CategoryOfPermission{

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

    @NotBlank
    private String name;

    @NotNull
    @OneToMany(mappedBy = "categoryOfPermission", fetch=FetchType.LAZY)
    private Set<Permission> permission;
}

CategoryOfPermissionRepo.java :

public interface CategoryOfPermissionRepo extends CrudRepository<CategoryOfPermission, Integer>{
}

Body:
It is because Set in Java uses equals contract to determine whether two objects are the same or not, and the way equals method in Permission class is implemented(using lombok) causes infinite recursion.

it is part of the generated code for equals method in  Permission

    Object this$categoryOfPermission = this.getCategoryOfPermission();
    Object other$categoryOfPermission = other.getCategoryOfPermission();
    if (this$categoryOfPermission == null) {
      if (other$categoryOfPermission != null) {
        return false;
      }
    } else if (!this$categoryOfPermission.equals(other$categoryOfPermission)) {
      return false;
    }

and it is the generated code for the CategoryOfPermission class

public boolean equals(final Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof CategoryOfPermission)) {
      return false;
    } else {
      CategoryOfPermission other = (CategoryOfPermission)o;
      if (!other.canEqual(this)) {
        return false;
      } else {
        Object this$id = this.getId();
        Object other$id = other.getId();
        if (this$id == null) {
          if (other$id != null) {
            return false;
          }
        } else if (!this$id.equals(other$id)) {
          return false;
        }

        Object this$permission = this.getPermission();
        Object other$permission = other.getPermission();
        if (this$permission == null) {
          if (other$permission != null) {
            return false;
          }
        } else if (!this$permission.equals(other$permission)) {
          return false;
        }

        return true;
      }
    }
  }

as you see Permission class calls equals method of CategoryOfPermission class and CategoryOfPermission calls equals method of Permision class which finally causes stackoverflow problem!.


问:
How to write a select Query inside a CASE condition in MS SQL
I have an Sql Query. It does not have any compilation error but in runtime it shows

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

```<code> SELECT a.UserID FROM USERGROUPS a WHERE a.GroupID IN
                      (CASE WHEN @group_id IS NULL THEN (select groupid from usergroups) ELSE
                       CASE WHEN @group_id=0 THEN (select groupid from usergroups  where userid = @userid)ELSE
                      @group_id END END )
</code>```

Thanks in advance.

答:
Try this instead:</p>

```<code>SELECT a.UserID
  FROM USERGROUPS a
  WHERE
    (@groupid is NUll and a.GroupID IN   (select groupid from usergroups))
     or (@groupid = 0 and a.GroupID IN  (select groupid from usergroups  where (userid = @userid)))
      or a.GroupID IN  (@groupid)
</code>```

Body:
I have an Sql Query. It does not have any compilation error but in runtime it shows

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

 SELECT a.UserID FROM USERGROUPS a WHERE a.GroupID IN
                      (CASE WHEN @group_id IS NULL THEN (select groupid from usergroups) ELSE
                       CASE WHEN @group_id=0 THEN (select groupid from usergroups  where userid = @userid)ELSE
                      @group_id END END )

Thanks in advance.

Body:
Try this instead:

SELECT a.UserID
  FROM USERGROUPS a
  WHERE
    (@groupid is NUll and a.GroupID IN   (select groupid from usergroups))
     or (@groupid = 0 and a.GroupID IN  (select groupid from usergroups  where (userid = @userid)))
      or a.GroupID IN  (@groupid)


问:
Click inside Loop issue - Remove dynamically created elements
The following code takes all the links onto the page that contains "https" and not "google.com" and turns them into iFrames. While that works, the close button that each is iFrame is supposed to be paired with does not work. When you click close, it only closes the last iFrame element on the page. I prefer to be able to do this in vanilla JavaScript, as opposed to jQuery.

total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 &&
 link.href.indexOf("google.com") == -1) {
    var hey = (links[i].href);
    console.log(link.href);
    total.push(links[i].href);
    var iframe = document.createElement('iframe');
    iframe.src = hey;
    document.body.appendChild(iframe);
    var close = document.createElement('button');
    document.body.appendChild(close);
    close.innerHTML = "close";
    close.addEventListener('click',function(){
      console.log("click");
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}
```

答:
If I understand correctly you want to create an  based on the href of pre-existing s. You also want a <button> for each  that closes it.

In the example below are two functions:

linksToIframes(urlFrag)

Creates a box to put s and <button>s into. Throwing them on  is messy:

```<code>document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
const box = document.querySelector('fieldset');
</code>```

Given a fragment of a url, it will collect all  into a HTMLCollection:

```<code>const links = document.links
</code>```

Convert HTMLCollection into an array and iterate through it finding any matches of href and urlFrag:

```<code> [...links].forEach(link => {
   if (link.href.includes(urlFrag)) {...
</code>```

Any match create the <frame> and <button> in the <fieldset> (the box):

```<code>   let iF = document.createElement('iframe');
   iF.src = link.href;
   box.appendChild(iF);
   ...
</code>```

closeIframe(event)

An event handler that enables any <button> to remove the <frame> before it and itself:

```<code>const clicked = e.target; // This is the tag user actually clicked
if (clicked.matches('button')) { /* <button> is the only
                                tag that's accepted (that's
                                Event Delegation) */
 clicked.previousElementSibling.remove();
 clicked.remove();
 ...
</code>```

Because of event bubbling we can bind the event handler on the parent element of all of the <button>s and then delegate how they react to a click. That's far better than an event handler on each <button>.

If you stick to your OP code, .previousElementSibling.remove(); applied to each <button> and .remove() to itself should fix it.

const linksToIframes = urlFrag => {
  document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
  const box = document.querySelector('fieldset');
  const links = document.links;
  [...links].forEach(link => {
    if (link.href.includes(urlFrag)) {
      let iF = document.createElement('iframe');
      iF.src = link.href;
      box.appendChild(iF);
      let btn = document.createElement('button');
      btn.textContent = 'Close';
      box.appendChild(btn);
    }
  });
};
const closeIframe = e => {
  const clicked = e.target;
  if (clicked.matches('button')) {
    clicked.previousElementSibling.remove();
    clicked.remove();
  }
}

linksToIframes('https://example.com');
document.querySelector('fieldset').onclick = closeIframe;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a,
iframe,
button {
  display: block
}

iframe {
  width: 95%;
  max-height: 50px;
}</code>```

EXAMPLE
SO
EXAMPLE
EXAMPLE```

Body:
If I understand correctly you want to create an <iframe> based on the href of pre-existing <a>s. You also want a <button> for each <iframe> that closes it.

In the example below are two functions:

linksToIframes(urlFrag)

Creates a box to put <iframe>s and <button>s into. Throwing them on <body> is messy:

document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
const box = document.querySelector('fieldset');

Given a fragment of a url, it will collect all <a> into a HTMLCollection:

const links = document.links

Convert HTMLCollection into an array and iterate through it finding any matches of href and urlFrag:

 [...links].forEach(link => {
   if (link.href.includes(urlFrag)) {...

Any match create the <frame> and <button> in the <fieldset> (the box):

   let iF = document.createElement('iframe');
   iF.src = link.href;
   box.appendChild(iF);
   ...

closeIframe(event)

An event handler that enables any <button> to remove the <frame> before it and itself:

const clicked = e.target; // This is the tag user actually clicked
if (clicked.matches('button')) { /* <button> is the only
                                tag that's accepted (that's
                                Event Delegation) */
 clicked.previousElementSibling.remove();
 clicked.remove();
 ...

Because of event bubbling we can bind the event handler on the parent element of all of the <button>s and then delegate how they react to a click. That's far better than an event handler on each <button>.

If you stick to your OP code, .previousElementSibling.remove(); applied to each <button> and .remove() to itself should fix it.

const linksToIframes = urlFrag => {
  document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
  const box = document.querySelector('fieldset');
  const links = document.links;
  [...links].forEach(link => {
    if (link.href.includes(urlFrag)) {
      let iF = document.createElement('iframe');
      iF.src = link.href;
      box.appendChild(iF);
      let btn = document.createElement('button');
      btn.textContent = 'Close';
      box.appendChild(btn);
    }
  });
};
const closeIframe = e => {
  const clicked = e.target;
  if (clicked.matches('button')) {
    clicked.previousElementSibling.remove();
    clicked.remove();
  }
}

linksToIframes('https://example.com');
document.querySelector('fieldset').onclick = closeIframe;

a,
iframe,
button {
  display: block
}

iframe {
  width: 95%;
  max-height: 50px;
}

<a href='https://example.com'>EXAMPLE</a>
<a href='https://stackoverflow'>SO</a>
<a href='https://example.com'>EXAMPLE</a>
<a href='https://example.com'>EXAMPLE</a>


问:
Minimize windows, application startup
Is there a way to minimize all windows automatically when launching an application?

I tried to call a .vbs file with the content above:

```<code>Set shell = wscript.CreateObject("Shell.Application")
Shell.MinimizeAll
</code>```

But doing this, application is minimized too.

答: What you want to do is first minimize all applications or toggle the desktop; THEN (perhaps even after a delay) open your application.</p>

Title: Minimize windows, application startup

Body:
Is there a way to minimize all windows automatically when launching an application?

I tried to call a .vbs file with the content above:

Set shell = wscript.CreateObject("Shell.Application")
Shell.MinimizeAll

But doing this, application is minimized too.


问:
How do you find the sum of specific items in a 2d array with a foreach loop?
I have this list:
my_list = [('a',1), ('b',2), ('c',3)]

How can i write a foreach loop to find the sum of 1+2+3?

答:
Simplest approach:

```<code>list = [('a',1), ('b',2), ('c',3)]

summ = 0 # variable to store sum
for i in list:
    summ = summ + i[1]

print(summ)
</code>```

This returns 6

Body:
Simplest approach:

list = [('a',1), ('b',2), ('c',3)]

summ = 0 # variable to store sum
for i in list:
    summ = summ + i[1]

print(summ)

This returns 6


问:
How can I edit web scraped text data using python?
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

```<code>import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)
</code>```

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

答:
Not sure, cause question do not provide an expected result, but you can "isolate" the information with stripped_strings.

This will give you a list of "isolated" values you can process:

```<code>list(soup.find('h3', class_ = 'Maw(160px)').stripped_strings)

#Output
['S&P 500', '4,587.18', '+65.64', '(+1.45%)']
</code>```

For example stripping following characters "()%":

```<code>[x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings]

#Output
['S&P 500', '4,587.18', '+65.64', '+1.45']
</code>```

Simplest way to print the data not that sloppy way, is to join() the values by whitespace:

```<code>' '.join([x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings])

#Output
S&P 500 4,587.18 +65.64 +1.45
</code>```

You can also create dict() and print the key / value pairs:

```<code>for k, v in dict(zip(['Symbol','Last Price','Change','% Change'], [x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings])).items():
    print(f'{k}: {v}')

#Output
Symbol: S&P 500
Last Price: 4,587.18
Change: +65.64
% Change: +1.45
</code>```

Body:
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

Body:
Not sure, cause question do not provide an expected result, but you can "isolate" the information with stripped_strings.

This will give you a list of "isolated" values you can process:

list(soup.find('h3', class_ = 'Maw(160px)').stripped_strings)

#Output
['S&P 500', '4,587.18', '+65.64', '(+1.45%)']

For example stripping following characters "()%":

[x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings]

#Output
['S&P 500', '4,587.18', '+65.64', '+1.45']

Simplest way to print the data not that sloppy way, is to join() the values by whitespace:

' '.join([x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings])

#Output
S&P 500 4,587.18 +65.64 +1.45

You can also create dict() and print the key / value pairs:

for k, v in dict(zip(['Symbol','Last Price','Change','% Change'], [x.strip('\(|\)|%') for x in soup.find('h3', class_ = 'Maw(160px)').stripped_strings])).items():
    print(f'{k}: {v}')

#Output
Symbol: S&P 500
Last Price: 4,587.18
Change: +65.64
% Change: +1.45


问:
Powershell/Forms - how to anchor listview within a tab control?
I'm trying to anchor a listview within a tab page in Forms, such that the listview resizes along with the tab and the other controls are also anchored to allow this, but it looks like it's anchoring to the parent form, not the tab - example code:

```<code>Add-Type -AssemblyName System.Windows.Forms
#
$form = New-Object System.Windows.Forms.Form
$form.MinimumSize = '585,700'
$form.StartPosition = 'CenterScreen'
$form.MaximizeBox = $false
$form.CancelButton = $ExitButton
#Autoscaling settings
$form.AutoScale = $true
$form.AutoScaleMode = "Font"
$ASsize = New-Object System.Drawing.SizeF(7,15)
$form.AutoScaleDimensions = $ASsize
#
#
$MainTab = New-Object System.Windows.Forms.TabControl
$MainTab.Size = '540,465'
$MainTab.Location = '15,95'
$MainTab.Multiline = $True
$MainTab.Name = 'TabPage'
$MainTab.SelectedIndex = 0
$MainTab.Anchor = 'Top,Left,Bottom,Right'
#
$TabPage1 = New-Object System.Windows.Forms.TabPage
$Tabpage1.Name = 'TabPage1'
$Tabpage1.Padding = '5,5,5,5'
$Tabpage1.TabIndex = 1
$Tabpage1.Text = 'Host SSH'
$Tabpage1.UseVisualStyleBackColor = $True
$TabPage1.Enabled = $false
#
$ESXhostList = New-Object System.Windows.Forms.ListView
$ESXhostList.View = [System.Windows.Forms.View]::Details
$ESXhostList.Location = '10,15'
$ESXhostList.Size = '510,150'
$ESXhostList.Columns.Add('Host Name',420) | Out-Null
$ESXhostList.Columns.Add('SSH Status',80) | Out-Null
$ESXhostList.Anchor = 'Top,Left,Right'
#
$ConnectBtn = New-Object System.Windows.Forms.Button
$ConnectBtn.Location = '20,190'
$ConnectBtn.Size = '54,24'
$ConnectBtn.Text = 'Connect'
$ConnectBtn.BackgroundImageLayout = 'Center'
$ConnectBtn.Enabled = $true
$ConnectBtn.Anchor = 'Left,Bottom'
#
$TabPage1.Controls.AddRange(@($ESXhostList,$ConnectBtn))
################################################################################
# TabPage 2
################################################################################
$TabPage2 = New-Object System.Windows.Forms.TabPage
$Tabpage2.Name = 'TabPage2'
$Tabpage2.Padding = '5,5,5,5'
$Tabpage2.TabIndex = 2
$Tabpage2.Text = 'Datastores'
$Tabpage2.UseVisualStyleBackColor = $True
$TabPage2.Enabled = $false
#
$DSList = New-Object System.Windows.Forms.ListView
$DSList.View = [System.Windows.Forms.View]::Details
$DSList.Location ='10,15'
$DSList.Size = '510,150'
$DSList.Columns.Add('Name',160) | Out-Null
$DSList.Columns.Add('FreeGB',65) | Out-Null
#
$ConnectBtn2 = New-Object System.Windows.Forms.Button
$ConnectBtn2.Location = '20,190'
$ConnectBtn2.Size = '54,24'
$ConnectBtn2.Text = 'Connect'
$ConnectBtn2.BackgroundImageLayout = 'Center'
$ConnectBtn2.Enabled = $true
#
$TabPage2.Controls.AddRange(@($DSList,$ConnectBtn2))
#
#
$MainTab.Controls.AddRange(@($TabPage1,$TabPage2))
#
# Info/Logging Window
$ProgressLog = New-Object System.Windows.Forms.TextBox
$ProgressLog.Location = '15,570'
$ProgressLog.Size = '540,80'
$ProgressLog.Multiline = $true
$ProgressLog.Anchor = 'Left,Bottom,Right'
$ProgressLog.TabStop = $false
$ProgressLog.ScrollBars = "Vertical"
$ProgressLog.ReadOnly = $true
#
# Add all the Form controls
$form.Controls.AddRange(@($MainTab,$ProgressLog))
#
#End
# Show form
$form.ShowDialog() | Out-Null
$form.Dispose()
</code>```

In the above example, the only difference between the tabs is that I'm trying to anchor the listview and button controls in the first tab but there's no anchoring in the second tab.

Here's Tab 1 - the listview is outside the bounds of the tab instead of being anchored within it and the button is completely off the tab area

Here's the identical Tab 2 with no anchoring. Correct layout but no anchoring therefore resizing form does not resize the listview or reposition the button:

Can anyone explain how to do this, as everything I read says that anchoring the tab then anchoring controls within it should work?

答:
It's an older question but I managed to figure it out.
You only have to explicitly set the Size of the TabPage itself and nothing more.
For the default windows drawing style, the Size paramater is as follows: System.Drawing.Size(WidthOfParentTabControl - 8, HeightOfParentTabControl - 28)

Tested under PS 5.1

Edit: added some more Controls to demonstrate it better

Here is the full code, just save it and run:

```<code>using namespace System.Windows.Forms
using namespace System.Drawing
using namespace System.Collections.Generic

Add-Type -AssemblyName System.Windows.Forms

[System.Windows.Forms.Application]::EnableVisualStyles()

#region Initialize Components
    #Mainwindow
    $Form = New-Object System.Windows.Forms.Form
    $Form.ClientSize = New-Object Point(1280,720)
    $Form.text = "Resolution"
    $Form.TopMost = $false

    #region MainTabControl
    [TabControl] $tabControl = New-Object TabControl
    $tabControl.Location = New-Object Point(12, 12)
    #Size(1248, 668) so I have a 12-12-12-12 "margin" on the tabcontrol
    $tabControl.Size = New-Object Size(1256, 696)
    $tabControl.Anchor = "top,right,bottom,left"
    #endregion

    #region Sample Tab
    [TabPage] $tabSample = New-Object TabPage
    $tabSample.Text = "Sample Tab"
    $tabSample.TabIndex = 0
    #Size(WParent - 8, HParent - 28)
    $tabSample.Size = New-Object Size(1248, 668)

        #region Controls
        [ListBox] $lbSample = New-Object ListBox
        [Button] $bSample = New-Object Button
        [Label] $lSample = New-Object Label

        $lbSample.Anchor = "left,bottom"
        $lbSample.Size = New-Object Size(800, 600)
        $lbSample.Location = New-Object Point(12, 50)

        $bSample.Anchor = "top,left,bottom,right"
        $bSample.Location = New-Object Point(12, 12)
        $bSample.Size = New-Object Size("80, 30")
        $bSample.Text = "Resizing button"

        $lSample.Text = "Anchor (right,bottom)"
        $lSample.Anchor = "right,bottom"
        $lSample.Location = New-Object Point(1150, 630)
        #endregion

    $tabSample.Controls.Add($lbSample)
    $tabSample.Controls.Add($bSample)
    $tabSample.Controls.Add($lSample)
    #endregion

    #Adding tabs to MainTabControl
    $tabControl.Controls.Add($tabSample)

    $tabControl.SelectedIndex = 0;
    $Form.Controls.Add($tabControl)
#endregion

[void]$Form.ShowDialog()
</code>```

Body:
I'm trying to anchor a listview within a tab page in Forms, such that the listview resizes along with the tab and the other controls are also anchored to allow this, but it looks like it's anchoring to the parent form, not the tab - example code:

Add-Type -AssemblyName System.Windows.Forms
#
$form = New-Object System.Windows.Forms.Form
$form.MinimumSize = '585,700'
$form.StartPosition = 'CenterScreen'
$form.MaximizeBox = $false
$form.CancelButton = $ExitButton
#Autoscaling settings
$form.AutoScale = $true
$form.AutoScaleMode = "Font"
$ASsize = New-Object System.Drawing.SizeF(7,15)
$form.AutoScaleDimensions = $ASsize
#
#
$MainTab = New-Object System.Windows.Forms.TabControl
$MainTab.Size = '540,465'
$MainTab.Location = '15,95'
$MainTab.Multiline = $True
$MainTab.Name = 'TabPage'
$MainTab.SelectedIndex = 0
$MainTab.Anchor = 'Top,Left,Bottom,Right'
#
$TabPage1 = New-Object System.Windows.Forms.TabPage
$Tabpage1.Name = 'TabPage1'
$Tabpage1.Padding = '5,5,5,5'
$Tabpage1.TabIndex = 1
$Tabpage1.Text = 'Host SSH'
$Tabpage1.UseVisualStyleBackColor = $True
$TabPage1.Enabled = $false
#
$ESXhostList = New-Object System.Windows.Forms.ListView
$ESXhostList.View = [System.Windows.Forms.View]::Details
$ESXhostList.Location = '10,15'
$ESXhostList.Size = '510,150'
$ESXhostList.Columns.Add('Host Name',420) | Out-Null
$ESXhostList.Columns.Add('SSH Status',80) | Out-Null
$ESXhostList.Anchor = 'Top,Left,Right'
#
$ConnectBtn = New-Object System.Windows.Forms.Button
$ConnectBtn.Location = '20,190'
$ConnectBtn.Size = '54,24'
$ConnectBtn.Text = 'Connect'
$ConnectBtn.BackgroundImageLayout = 'Center'
$ConnectBtn.Enabled = $true
$ConnectBtn.Anchor = 'Left,Bottom'
#
$TabPage1.Controls.AddRange(@($ESXhostList,$ConnectBtn))
################################################################################
# TabPage 2
################################################################################
$TabPage2 = New-Object System.Windows.Forms.TabPage
$Tabpage2.Name = 'TabPage2'
$Tabpage2.Padding = '5,5,5,5'
$Tabpage2.TabIndex = 2
$Tabpage2.Text = 'Datastores'
$Tabpage2.UseVisualStyleBackColor = $True
$TabPage2.Enabled = $false
#
$DSList = New-Object System.Windows.Forms.ListView
$DSList.View = [System.Windows.Forms.View]::Details
$DSList.Location ='10,15'
$DSList.Size = '510,150'
$DSList.Columns.Add('Name',160) | Out-Null
$DSList.Columns.Add('FreeGB',65) | Out-Null
#
$ConnectBtn2 = New-Object System.Windows.Forms.Button
$ConnectBtn2.Location = '20,190'
$ConnectBtn2.Size = '54,24'
$ConnectBtn2.Text = 'Connect'
$ConnectBtn2.BackgroundImageLayout = 'Center'
$ConnectBtn2.Enabled = $true
#
$TabPage2.Controls.AddRange(@($DSList,$ConnectBtn2))
#
#
$MainTab.Controls.AddRange(@($TabPage1,$TabPage2))
#
# Info/Logging Window
$ProgressLog = New-Object System.Windows.Forms.TextBox
$ProgressLog.Location = '15,570'
$ProgressLog.Size = '540,80'
$ProgressLog.Multiline = $true
$ProgressLog.Anchor = 'Left,Bottom,Right'
$ProgressLog.TabStop = $false
$ProgressLog.ScrollBars = "Vertical"
$ProgressLog.ReadOnly = $true
#
# Add all the Form controls
$form.Controls.AddRange(@($MainTab,$ProgressLog))
#
#End
# Show form
$form.ShowDialog() | Out-Null
$form.Dispose()

In the above example, the only difference between the tabs is that I'm trying to anchor the listview and button controls in the first tab but there's no anchoring in the second tab.

Here's Tab 1 - the listview is outside the bounds of the tab instead of being anchored within it and the button is completely off the tab area

Here's the identical Tab 2 with no anchoring. Correct layout but no anchoring therefore resizing form does not resize the listview or reposition the button:

Can anyone explain how to do this, as everything I read says that anchoring the tab then anchoring controls within it should work?

Body:
It's an older question but I managed to figure it out.
You only have to explicitly set the Size of the TabPage itself and nothing more.
For the default windows drawing style, the Size paramater is as follows: System.Drawing.Size(WidthOfParentTabControl - 8, HeightOfParentTabControl - 28)

Tested under PS 5.1

Edit: added some more Controls to demonstrate it better

Here is the full code, just save it and run:

using namespace System.Windows.Forms
using namespace System.Drawing
using namespace System.Collections.Generic

Add-Type -AssemblyName System.Windows.Forms

[System.Windows.Forms.Application]::EnableVisualStyles()

#region Initialize Components
    #Mainwindow
    $Form = New-Object System.Windows.Forms.Form
    $Form.ClientSize = New-Object Point(1280,720)
    $Form.text = "Resolution"
    $Form.TopMost = $false

    #region MainTabControl
    [TabControl] $tabControl = New-Object TabControl
    $tabControl.Location = New-Object Point(12, 12)
    #Size(1248, 668) so I have a 12-12-12-12 "margin" on the tabcontrol
    $tabControl.Size = New-Object Size(1256, 696)
    $tabControl.Anchor = "top,right,bottom,left"
    #endregion

    #region Sample Tab
    [TabPage] $tabSample = New-Object TabPage
    $tabSample.Text = "Sample Tab"
    $tabSample.TabIndex = 0
    #Size(WParent - 8, HParent - 28)
    $tabSample.Size = New-Object Size(1248, 668)

        #region Controls
        [ListBox] $lbSample = New-Object ListBox
        [Button] $bSample = New-Object Button
        [Label] $lSample = New-Object Label

        $lbSample.Anchor = "left,bottom"
        $lbSample.Size = New-Object Size(800, 600)
        $lbSample.Location = New-Object Point(12, 50)

        $bSample.Anchor = "top,left,bottom,right"
        $bSample.Location = New-Object Point(12, 12)
        $bSample.Size = New-Object Size("80, 30")
        $bSample.Text = "Resizing button"

        $lSample.Text = "Anchor (right,bottom)"
        $lSample.Anchor = "right,bottom"
        $lSample.Location = New-Object Point(1150, 630)
        #endregion

    $tabSample.Controls.Add($lbSample)
    $tabSample.Controls.Add($bSample)
    $tabSample.Controls.Add($lSample)
    #endregion

    #Adding tabs to MainTabControl
    $tabControl.Controls.Add($tabSample)

    $tabControl.SelectedIndex = 0;
    $Form.Controls.Add($tabControl)
#endregion

[void]$Form.ShowDialog()


问:
How do I compare users from SQL query to AD then insert them?
```<code>Import-Module ActiveDirectory
$ADUSER = Get-Aduser -Filter * -Properties SamAccountName | Select-Object SamAccountName
$SQLQUERY = Invoke-Sqlcmd -Query "SELECT username AS SamAccountName FROM test.dbo.ad" -Database "TEST" -Server "DB-1"
$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{.SideIndicator -Eq '=>'} | SELECT SamAccountName
$Insert = "INSERT INTO TEST.dbo.ad SELECT $user" -Database "TEST" -Server "DB-1"
Foreach ($user in $Compare){
    Invoke-Sqlcmd -Query $Insert
}
</code>```

I am using Powershell 5.0 and when I run this I get an error ".SideIndicator : The term '.SideIndicator' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again." What am I doing wrong? I am trying to pull AD users then a query and then compare AD to SQL and insert in.

答:
As Olaf pointed out, you are missing the $_ from your Where statement on the fourth line. It should read:

```<code>$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{$_.SideIndicator -Eq '=>'} | SELECT SamAccountName
</code>```

Body:
Import-Module ActiveDirectory
$ADUSER = Get-Aduser -Filter * -Properties SamAccountName | Select-Object SamAccountName
$SQLQUERY = Invoke-Sqlcmd -Query "SELECT username AS SamAccountName FROM test.dbo.ad" -Database "TEST" -Server "DB-1"
$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{.SideIndicator -Eq '=>'} | SELECT SamAccountName
$Insert = "INSERT INTO TEST.dbo.ad SELECT $user" -Database "TEST" -Server "DB-1"
Foreach ($user in $Compare){
    Invoke-Sqlcmd -Query $Insert
}

I am using Powershell 5.0 and when I run this I get an error ".SideIndicator : The term '.SideIndicator' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again." What am I doing wrong? I am trying to pull AD users then a query and then compare AD to SQL and insert in.

Body:
As Olaf pointed out, you are missing the $_ from your Where statement on the fourth line. It should read:

$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{$_.SideIndicator -Eq '=>'} | SELECT SamAccountName


问:
Is there a way I could get a email when someone submits my contact form using JavaScript?
I made a contact form using HTML and JavaScript. The text editor I am using right now only supports HTML and JavaScript CSS and markdown files. I made contact form using HTML and JavaScript but I don’t know how to make the users content go into my mailbox. Like I don’t know how the email could come to my mailbox so I could see their issue. Here’s my code for the contact form.
HTML:

```<code>
<!DOCTYPE html>
<html>
<head>
<title>Contact Form using JavaScript</title> <!-- Include CSS file here -->
<link href="css/form.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>Contact Form using JavaScript</h1>
<div id="form_sample"></div> <!-- Include JS file here -->
<script src="form.js"></script>
</div>
</body>
</html>
</code>```

Here’s the JavaScript.

```<code>// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);

var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);

var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);

var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text"); inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);

var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);

var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);

var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);

var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);

var messagebreak = document.createElement('br'); createform.appendChild(messagebreak);

var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement); ```

Any help is appreciated.
```

答:
There is a much easier way to do it than to use PHP. While PHP is the most reliable, there are javascript and Jquery apps that make it very easy to do. Basicly, just go to this website.
Once there, follow the instructions to implement it into your HTML website.</p>

Body:
I made a contact form using HTML and JavaScript. The text editor I am using right now only supports HTML and JavaScript CSS and markdown files. I made contact form using HTML and JavaScript but I don’t know how to make the users content go into my mailbox. Like I don’t know how the email could come to my mailbox so I could see their issue. Here’s my code for the contact form.
HTML:

<!DOCTYPE html>

<title>Contact Form using JavaScript</title>
<link href="css/form.css" rel="stylesheet">

Contact Form using JavaScript

Here’s the JavaScript.

// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);

var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);

var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);

var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text"); inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);

var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);

var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);

var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);

var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);

var messagebreak = document.createElement('br'); createform.appendChild(messagebreak);

var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement); ```

Any help is appreciated.


问:
React function arrow
I am new to react and arrow function,  I have the following code

```<code>const users = (props) => {
   return (props.users);
}
</code>```

here is props

```<code>userDialogs.propTypes = {
   users: Proptypes.array.isRequired
};
</code>```

and this how I use, but it gives me error, map is not function

```<code>{users.map((username, index) => {
   return <b>{username}</b>
})}
</code>```

答:
In the first code block, you're defining an arrow function named users which is taking in props as a parameter. In order to return something from this function you'll need to call the defined function users like this:

users(props); // => this returns props.users which is an array
```
<p>Remember that the function <code>map</code> is callable only on iterable data structures and the function <code>users</code> defined in the first block doesn't have a <code>map</code> function. If the returned value <code>props.users</code> is an array, calling <code>map</code> on the invoked function will work. Like this:</p>
<pre class="lang-js prettyprint-override"><code>{users(props).map(({username}, index) => {
   return <b>{username}</b>
})}
</code>```

Title: React function arrow

Body:
I am new to react and arrow function,  I have the following code

const users = (props) => {
   return (props.users);
}

here is props

userDialogs.propTypes = {
   users: Proptypes.array.isRequired
};

and this how I use, but it gives me error, map is not function

{users.map((username, index) => {
   return {username}
})}

Body:
In the first code block, you're defining an arrow function named users which is taking in props as a parameter. In order to return something from this function you'll need to call the defined function users like this:

users(props); // => this returns props.users which is an array

Remember that the function map is callable only on iterable data structures and the function users defined in the first block doesn't have a map function. If the returned value props.users is an array, calling map on the invoked function will work. Like this:

{users(props).map(({username}, index) => {
   return <b>{username}</b>
})}