问:
How can I show "empty" if data is not there?
Because of this

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>
</code>```

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>
</code>```

答:
You can combine the optional chaining operator with the nullish coalescing operator like this :

<v-card-subtitle class="py-0 my-0">{{ vc_rule?.url ?? 'empty' }}</v-card-subtitle>
```

Body:
Because of this

<v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

<v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>


来源: stackexchange

问:
How can I get a file's P4-Path using its local path in C#?
For example, if a file is "E:\TMP\test.txt",and its P4 path is "//root/test.txt",how can I get the P4 path in C# as I know the local path?
Sorry for my poor English.</p>

答:
Most Perforce commands that accept a file path will accept either a depot path or a local path as the argument, and return the depot path as part of the output.

You probably want to run a command like p4 fstat to get information that includes (but is not limited to) the depot path, which in the C# API is wrapped by the GetFileMetadata function:

https://www.perforce.com/manuals/p4api.net/p4api.net_reference/html/M_Perforce_P4_Repository_GetFileMetaData.htm

ContentLicense: CC BY-SA 4.0


问:
pandas: combine columns if they share a partly similar name
I have a DataFrame as follows,

```<code>import pandas as pd
df = pd.DataFrame({'sent_a.1': [0, 3, 2, 1],
               'sent_a.2': [0, 1, 4, 0],
               'sent_b.3': [0, 6, 0, 8],
               'sent_b.4': [1, 1, 8, 6]
               })
</code>```

I want to combine the columns that share a name. so the desired output would be,

```<code>    sent_a  sent_b
0     0,0    0,1
1     3,1    6,1
2     2,4    0,8
3     1,0    8,6
</code>```

I have done the following and the code works, but since my original DataFrame has more than 200 columns, I am looking for a faster way of doing that.

```<code>df['sent_a'] = df['sent_a.1']+','+ df['sent_a.2']
df['sent_b'] = df['sent_b.1']+','+ df['sent_b.2']
df = df.drop(['sent_a.1', 'sent_a.2', 'sent_b.3', 'sent_b.4'], axis=1)
</code>```

答:
You can groupby the first part of the columns names, with axis=1 (to group column-wise instead of row-wise), and for each group, use the built-in functools.reduce to join all the columns together:

```<code>import functools as ft
new_df = df.groupby(df.columns.str.split('.').str[0], axis=1).apply(lambda g: ft.reduce(lambda x, y: x + ',' + y, [x[col].astype(str) for col in x]))
</code>```

Output:

```<code>>>> new_df
  sent_a sent_b
0    0,0    0,0
1    3,1    3,1
2    2,4    2,4
3    1,0    1,0
</code>```

Body:
I have a DataFrame as follows,

import pandas as pd
df = pd.DataFrame({'sent_a.1': [0, 3, 2, 1],
               'sent_a.2': [0, 1, 4, 0],
               'sent_b.3': [0, 6, 0, 8],
               'sent_b.4': [1, 1, 8, 6]
               })

I want to combine the columns that share a name. so the desired output would be,

    sent_a  sent_b
0     0,0    0,1
1     3,1    6,1
2     2,4    0,8
3     1,0    8,6

I have done the following and the code works, but since my original DataFrame has more than 200 columns, I am looking for a faster way of doing that.

df['sent_a'] = df['sent_a.1']+','+ df['sent_a.2']
df['sent_b'] = df['sent_b.1']+','+ df['sent_b.2']
df = df.drop(['sent_a.1', 'sent_a.2', 'sent_b.3', 'sent_b.4'], axis=1)

Body:
You can groupby the first part of the columns names, with axis=1 (to group column-wise instead of row-wise), and for each group, use the built-in functools.reduce to join all the columns together:

import functools as ft
new_df = df.groupby(df.columns.str.split('.').str[0], axis=1).apply(lambda g: ft.reduce(lambda x, y: x + ',' + y, [x[col].astype(str) for col in x]))

Output:

>>> new_df
  sent_a sent_b
0    0,0    0,0
1    3,1    3,1
2    2,4    2,4
3    1,0    1,0


问:
cv2.error: OpenCV(4.5.2) .error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Here is my code:

import cv2 #for image processing
import easygui #to open the filebox
import numpy as np #to store image
import imageio #to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image

top=tk.Tk()
top.geometry('400x400')
top.title('Cartoonify Your Image !')
top.configure(background='white')
label=Label(top,background='#CDCDCD', font=('calibri',20,'bold'))

def upload():
    ImagePath=easygui.fileopenbox()
    cartoonify(ImagePath)

def cartoonify(ImagePath):

    # read the image
    originalmage = cv2.imread(ImagePath)

    originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
    #print(image)  # image is stored in form of numbers
```

When I run these lines of code I get the following error:

cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-vi271kac\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

答:
I solved the same problem by adding:

data = cv2.imread('path_to_your_image', as_grey =True)

and then try to also add the flags = cv2.DFT_COMPLEX_OUTPUT to this line

dft = cv2.dft(np.float32('your_image'),flags = cv2.DFT_COMPLEX_OUTPUT)

there are many solutions for this issue out there.

Body:
Here is my code:

import cv2 #for image processing
import easygui #to open the filebox
import numpy as np #to store image
import imageio #to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image

top=tk.Tk()
top.geometry('400x400')
top.title('Cartoonify Your Image !')
top.configure(background='white')
label=Label(top,background='#CDCDCD', font=('calibri',20,'bold'))

def upload():
    ImagePath=easygui.fileopenbox()
    cartoonify(ImagePath)

def cartoonify(ImagePath):

    # read the image
    originalmage = cv2.imread(ImagePath)

    originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
    #print(image)  # image is stored in form of numbers

When I run these lines of code I get the following error:

cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-vi271kac\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'


问:
ASP.NET / MVC 1.0 Components and Ajax controls - Grid - Calendar - Search?
Hello I'm rather new to developing with MVC and I'm looking to find as many Ajax controls that integrate seamlessly into my new MVC 1.0 ASP.Net application. Specifically, tree controls, searching, outlook calendaresque, and inline updating.</p>

答: Telerik do some excellent controls at http://www.telerik.com. Their support is EXCELLENT.</p>

OwnerDisplayName: Jukeman

ContentLicense: CC BY-SA 2.5


问:
How to read an object's properties while using a recursive function in Javascript?
I wonder if someone can point me into the right direction on this. When I have an object, I usually read its properties via FOR IN LOOP. And since I know what the properties are because I created the very object, I know what keys and their values are. I would like to know if there are any other ways such as recursive approach to read through an object and its properties.

So here is the object for an example:

```<code>var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});
</code>```

As you can see, I have declared the mObj and within it, I have declared mArr as an Array. And then I am pushing three objects within mArr:

id

days

colors

if I wanted to find out mArr length, I would write something like:

```<code>alert(mObj.mArr.length);
</code>```

And if I wanted to loop through the object, I would have something like this:

```<code>for(var a in mObj.mArr[0])
{
   alert(mObj.mArr[0][a]);
}
</code>```

I wonder if I can just right one function and pass the parent object which happens to be "mObj" here, and this recursive function would through the "mObj" and list all of its properties from head to toe.

I would appreciate any input on this, please.

Thanks a lot.

答:
Here's a basic example:

```<code>var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mObj.mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});

function r(obj) {
    if (obj)
        for (var key in obj) {
            if (typeof obj[key] == "object")
                r(obj[key]);
            else if (typeof obj[key] != "function")
                console.log(obj[key])
        }

    return;
}

r(mObj);
</code>```

if there is an object not a function call the function again, else console log the value if it is not a function.

ContentLicense: CC BY-SA 3.0

Body:
I wonder if someone can point me into the right direction on this. When I have an object, I usually read its properties via FOR IN LOOP. And since I know what the properties are because I created the very object, I know what keys and their values are. I would like to know if there are any other ways such as recursive approach to read through an object and its properties.

So here is the object for an example:

var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});

As you can see, I have declared the mObj and within it, I have declared mArr as an Array. And then I am pushing three objects within mArr:

id

days

colors

if I wanted to find out mArr length, I would write something like:

alert(mObj.mArr.length);

And if I wanted to loop through the object, I would have something like this:

for(var a in mObj.mArr[0])
{
   alert(mObj.mArr[0][a]);
}

I wonder if I can just right one function and pass the parent object which happens to be "mObj" here, and this recursive function would through the "mObj" and list all of its properties from head to toe.

I would appreciate any input on this, please.

Thanks a lot.

Body:
Here's a basic example:

var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mObj.mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});

function r(obj) {
    if (obj)
        for (var key in obj) {
            if (typeof obj[key] == "object")
                r(obj[key]);
            else if (typeof obj[key] != "function")
                console.log(obj[key])
        }

    return;
}

r(mObj);

if there is an object not a function call the function again, else console log the value if it is not a function.


问:
Cant render API data, .map error using Google Books API
Pretty new to React, still learning. I was trying to make this Book Finder app using Google Books API, and then when I wanted to map the data, first time everything worked perfectly, but after that one time I started getting this error:

Keep in mind that the first time I ran the code everything worked, I was even fixing some CSS properties and it re-rendered fine.
I tried a lot of things, I do know that you can't use .map on objects, and I checked, the API data was and object.

Result of typeof() for the given API data

Heres the code:

MainContainer.tsx

import { useState } from "react";
import List from "./List";
import Search from "./Search";
import request from "superagent";

export default function MainContainer() {

    const [books, setBooks] = useState([]);

    function handleChange(e: any) {
        setBooks(e.target.value);
    }

    function handleSearch(e: any) {
        e.preventDefault();
        request
            .get("https://www.googleapis.com/books/v1/volumes")
            .query({ q: setBooks })
            .then((data) => {
                setBooks([...books])
            })
    }

    return (

            <Search
                handleChange={handleChange}
                handleSearch={handleSearch}
            />
            <List books={books}/>

    )
}
```
<p>List.tsx</p>
<pre class="lang-js prettyprint-override"><code>import Card from "./Card"

export default function List(props: any) {

    return (
        <div className="list-container">

            {

                props.books && props.books.length > 0 ?
                    props.books.map(function (book: any) {
                        return (
                            <Card
                                key={book.id}
                                image={book.volumeInfo.imageLinks.smallThumbnail}
                                title={book.volumeInfo.title}
                                author={book.volumeInfo.authors}
                                published={book.volumeInfo.publishedDate}
                            />
                        )
                    }) : <p className="np-data">No books yet...</p>
            }

        </div>
    )
}
</code>```

Card.tsx

export default function Card(props: any) {
    return (

{props.title}

{props.author}

{props.published}

    )
}
```

Again, I'm still learning React, this might be some dumb-typo-begginer error so yeah. Thanks in advance!

答:
The problem is that you have two pieces of state here (the search query and the list of books), but you are using a single variable (books) to keep track of both.

In the MainContainer component, add this to create another state variable.

```<code>const [query, setQuery] = useState('');
</code>```

Update handleChange to this to update the search query variable.

```<code>function handleChange(e: any) {
  setQuery(e.target.value);
}
</code>```

Update handleSearch to this to make a request with the last entered query and correctly set the books state variable.

```<code>function handleSearch(e: any) {
  e.preventDefault();
  request
    .get("https://www.googleapis.com/books/v1/volumes")
    .query({ q: query})
    .then((data) => {
      setBooks(data.items)
    })
 }
</code>```

It should work as expected now.

Body:
Pretty new to React, still learning. I was trying to make this Book Finder app using Google Books API, and then when I wanted to map the data, first time everything worked perfectly, but after that one time I started getting this error:

Keep in mind that the first time I ran the code everything worked, I was even fixing some CSS properties and it re-rendered fine.
I tried a lot of things, I do know that you can't use .map on objects, and I checked, the API data was and object.

Result of typeof() for the given API data

Heres the code:

MainContainer.tsx

import { useState } from "react";
import List from "./List";
import Search from "./Search";
import request from "superagent";

export default function MainContainer() {

    const [books, setBooks] = useState([]);

    function handleChange(e: any) {
        setBooks(e.target.value);
    }

    function handleSearch(e: any) {
        e.preventDefault();
        request
            .get("https://www.googleapis.com/books/v1/volumes")
            .query({ q: setBooks })
            .then((data) => {
                setBooks([...books])
            })
    }

    return (

            <Search
                handleChange={handleChange}
                handleSearch={handleSearch}
            />
            <List books={books}/>

    )
}

List.tsx

import Card from "./Card"

export default function List(props: any) {

    return (

            {

                props.books && props.books.length > 0 ?
                    props.books.map(function (book: any) {
                        return (
                            <Card
                                key={book.id}
                                image={book.volumeInfo.imageLinks.smallThumbnail}
                                title={book.volumeInfo.title}
                                author={book.volumeInfo.authors}
                                published={book.volumeInfo.publishedDate}
                            />
                        )
                    }) :
No books yet...

            }

    )
}

Card.tsx

export default function Card(props: any) {
    return (

{props.title}

{props.author}

{props.published}

    )
}

Again, I'm still learning React, this might be some dumb-typo-begginer error so yeah. Thanks in advance!

Body:
The problem is that you have two pieces of state here (the search query and the list of books), but you are using a single variable (books) to keep track of both.

In the MainContainer component, add this to create another state variable.

const [query, setQuery] = useState('');

Update handleChange to this to update the search query variable.

function handleChange(e: any) {
  setQuery(e.target.value);
}

Update handleSearch to this to make a request with the last entered query and correctly set the books state variable.

function handleSearch(e: any) {
  e.preventDefault();
  request
    .get("https://www.googleapis.com/books/v1/volumes")
    .query({ q: query})
    .then((data) => {
      setBooks(data.items)
    })
 }

It should work as expected now.


问:
Measuring coverage in python threads
I am trying to measure code coverage with a code that uses threads created by the python threading module.
I am using coverage to measure coverage.
However I can not get the code that is run within a thread to get measured. I tried following the suggestion on the coverage docs to measure coverage in subprocesses but no luck.

Here is a minimal example file untitled.py:

import time, threading
import numpy as np

def thread():
    print(f'{threading.get_ident()}: started thread')
    time.sleep(np.random.uniform(1, 10))
    print(f'{threading.get_ident()}: done')

def run_threads():
    threads = [threading.Thread(target=thread)]
    for t in threads:
        t.start()

    print('started all threads')

    for t in threads:
        t.join()

    print('all threads done')

if __name__ == '__main__':

    run_threads()
```
```> coverage run untitled.py
139952541644544: started thread
started all threads
139952541644544: done
all threads done
> coverage combine
Combined data file .coverage.248973.677959
> coverage report -m
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
untitled.py      14      3    79%   6-8
-------------------------------------------
TOTAL            14      3    79%
>
```
<p>As you can see the lines 6-8 (the <code>thread()</code> function) is executed but not measured.</p>
<p>For context I am running on a linux machine, Python 3.9.0, <code>coverage</code> 6.2. The directory contains this <code>.coveragerc</code> file:</p>
```# .coveragerc to control coverage.py
[run]
source = ./
parallel = True
concurrency = multiprocessing

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    pragma: no cover

    # Don't complain about missing debug-only code:
    def __repr__
    if self\.debug

    # Don't complain if tests don't hit defensive assertion code:
    raise AssertionError
    raise NotImplementedError

    # Don't complain if non-runnable code isn't run:
    if 0:
    if __name__ == .__main__.:
```

I am very thankful for any suggestion!!

答:
You need to specify "thread" as part of your concurrency setting:

```<code>concurrency = multiprocessing,thread
</code>```

I'm not sure you need multiprocessing.  Your sample program doesn't use it, maybe your real program doesn't either.

Title: Measuring coverage in python threads

Body:
I am trying to measure code coverage with a code that uses threads created by the python threading module.
I am using coverage to measure coverage.
However I can not get the code that is run within a thread to get measured. I tried following the suggestion on the coverage docs to measure coverage in subprocesses but no luck.

Here is a minimal example file untitled.py:

import time, threading
import numpy as np

def thread():
    print(f'{threading.get_ident()}: started thread')
    time.sleep(np.random.uniform(1, 10))
    print(f'{threading.get_ident()}: done')

def run_threads():
    threads = [threading.Thread(target=thread)]
    for t in threads:
        t.start()

    print('started all threads')

    for t in threads:
        t.join()

    print('all threads done')

if __name__ == '__main__':

    run_threads()

> coverage run untitled.py
139952541644544: started thread
started all threads
139952541644544: done
all threads done
> coverage combine
Combined data file .coverage.248973.677959
> coverage report -m
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
untitled.py      14      3    79%   6-8
-------------------------------------------
TOTAL            14      3    79%
>

As you can see the lines 6-8 (the thread() function) is executed but not measured.

For context I am running on a linux machine, Python 3.9.0, coverage 6.2. The directory contains this .coveragerc file:

# .coveragerc to control coverage.py
[run]
source = ./
parallel = True
concurrency = multiprocessing

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    pragma: no cover

    # Don't complain about missing debug-only code:
    def __repr__
    if self\.debug

    # Don't complain if tests don't hit defensive assertion code:
    raise AssertionError
    raise NotImplementedError

    # Don't complain if non-runnable code isn't run:
    if 0:
    if __name__ == .__main__.:

I am very thankful for any suggestion!!

Body:
You need to specify "thread" as part of your concurrency setting:

concurrency = multiprocessing,thread

I'm not sure you need multiprocessing.  Your sample program doesn't use it, maybe your real program doesn't either.


问:
How to take snapshot in vlc using command line in ubuntu
I am using easycap DC60+ in ubuntu and watch easycap video on vlc using following command:

```<code>vlc -vvv v4l2:///dev/video1:input=1:norm=PAL-I:width=720:height=576 --input-slave=alsa://plughw:1,0 --v4l2-standard=PAL_I
</code>```

and i want to take snapshot of vlc using command line.

I use this command on another terminal but show error and my first instance of vlc not work properly

```<code>vlc -I dummy v4l2:///dev/video0 --video-filter scene --no-audio --scene-path /home/stoppal/test --scene-prefix image_prefix --scene-format png vlc://quit --run-time=1
</code>```

this error is occure

```<code>[0x19d6aa8] dummy interface: using the dummy interface module...
libv4l2: error set_fmt gave us a different result then try_fmt!
</code>```

答:
You don't need "dummy" it's for example purposes.
Here is the command you can use :</p>
```<code>vlc -I v4l2:///dev/video{id} --video-filter scene --no-audio --scene-path /home/stoppal/test --scene-prefix image_prefix --scene-format {format} vlc://quit --run-time=1
</code>```

Body:
I am using easycap DC60+ in ubuntu and watch easycap video on vlc using following command:

vlc -vvv v4l2:///dev/video1:input=1:norm=PAL-I:width=720:height=576 --input-slave=alsa://plughw:1,0 --v4l2-standard=PAL_I

and i want to take snapshot of vlc using command line.

I use this command on another terminal but show error and my first instance of vlc not work properly

vlc -I dummy v4l2:///dev/video0 --video-filter scene --no-audio --scene-path /home/stoppal/test --scene-prefix image_prefix --scene-format png vlc://quit --run-time=1

this error is occure

[0x19d6aa8] dummy interface: using the dummy interface module...
libv4l2: error set_fmt gave us a different result then try_fmt!

Body:
You don't need "dummy" it's for example purposes.
Here is the command you can use :

vlc -I v4l2:///dev/video{id} --video-filter scene --no-audio --scene-path /home/stoppal/test --scene-prefix image_prefix --scene-format {format} vlc://quit --run-time=1


问:
Creating a fill animation in flutter
I need find a way to create an animation that will fill and dispense a liquid inside a tube. I will need some kind of variables, such as percentages where as the percentage goes up and down the liquid rises and falls. I'm not quite sure how to do such an animation in flutter, so any help is appreciated.

I have a few pictures posted below for when the tube is empty and when it is at 180 micro liters.

答:
Check this

LinearProgressIndicator,
Timer,
ClipPath

```<code>class _MyHomePageState extends State<MyHomePage> {
  Timer? _timer;
  int _start = 10000;

  void startTimer() {
    _start = 10000;
    _timer = Timer.periodic(
        const Duration(milliseconds: 1),
        (Timer timer) =>
            setState(() => (_start == 0 ? timer.cancel() : _start--)));
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
            Text('$_start'),
            RotatedBox(
                quarterTurns: 3,
                child: ClipPath(
                    clipper: MyClipper(),
                    child: Container(
                        width: 500,
                        height: 100,
                        child: LinearProgressIndicator(
                          color: Colors.blue,
                          value: (_start / 10000),
                        ))))
          ])),
      floatingActionButton: FloatingActionButton(
        onPressed: () => startTimer(),
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}

class MyClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(size.width, 0);
    path.lineTo(size.width * 0.2, 0);
    path.lineTo(0, size.height / 2);
    path.lineTo(size.width * 0.2, size.height);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    path.close();

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
</code>```

Title: Creating a fill animation in flutter

Body:
Check this

LinearProgressIndicator,
Timer,
ClipPath

class _MyHomePageState extends State<MyHomePage> {
  Timer? _timer;
  int _start = 10000;

  void startTimer() {
    _start = 10000;
    _timer = Timer.periodic(
        const Duration(milliseconds: 1),
        (Timer timer) =>
            setState(() => (_start == 0 ? timer.cancel() : _start--)));
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
            Text('$_start'),
            RotatedBox(
                quarterTurns: 3,
                child: ClipPath(
                    clipper: MyClipper(),
                    child: Container(
                        width: 500,
                        height: 100,
                        child: LinearProgressIndicator(
                          color: Colors.blue,
                          value: (_start / 10000),
                        ))))
          ])),
      floatingActionButton: FloatingActionButton(
        onPressed: () => startTimer(),
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}

class MyClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(size.width, 0);
    path.lineTo(size.width * 0.2, 0);
    path.lineTo(0, size.height / 2);
    path.lineTo(size.width * 0.2, size.height);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    path.close();

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}


问:
EF Code First With Two DbContexts
This should be a simple one involving EF Code first but I can't wrap my head around the documentation and all the examples I am finding are from older versions.  I am working with the latest (4.1).

Anyway I have some models like:

```<code>public class Foo
{
    public int ID { get; set; }
    public Bar Bar { get; set; }
}

public class Bar
{
    public int ID { get; set; }
    public string Value { get; set; }
}
</code>```

I used some scaffolding with Asp.Net MVC to create my controllers/repositories and when I create a 'Foo' object, it also creates a 'Bar' object even though I set the 'Bar' property from something stored in the database.

```<code>public class FooViewModel
{
    public int ID { get; set; }
    public int BarID { get; set; }
}

public ActionResult Create(FooViewModel foo)
{
    var entity = new Foo()
        {
            ID = foo.ID,
            Bar = _barRepository.Find(foo.BarID)
        };
    _fooRepository.InsertOrUpdate(entity);
    _fooRepository.Save();
    // more stuff
}
</code>```

How can I use fluent syntax for EF in order to stop it from creating a new 'Bar' row in the database?

Update

Here is the generated repository code:

```<code>    public void InsertOrUpdate(Foo foo)
    {
        if (foo.ID == default(int)) {
            // New entity
            context.Foo.Add(foo);
        } else {
            // Existing entity
            context.Foo(foo).State = EntityState.Modified;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }
</code>```

答: The problem must be somewhere in your repository layer - using the same model directly with EF 4.1 produces the expected result - a new row in the Foos table with a bar FK column pointing to the existing Bar.

Title: EF Code First With Two DbContexts

Body:
This should be a simple one involving EF Code first but I can't wrap my head around the documentation and all the examples I am finding are from older versions.  I am working with the latest (4.1).

Anyway I have some models like:

public class Foo
{
    public int ID { get; set; }
    public Bar Bar { get; set; }
}

public class Bar
{
    public int ID { get; set; }
    public string Value { get; set; }
}

I used some scaffolding with Asp.Net MVC to create my controllers/repositories and when I create a 'Foo' object, it also creates a 'Bar' object even though I set the 'Bar' property from something stored in the database.

public class FooViewModel
{
    public int ID { get; set; }
    public int BarID { get; set; }
}

public ActionResult Create(FooViewModel foo)
{
    var entity = new Foo()
        {
            ID = foo.ID,
            Bar = _barRepository.Find(foo.BarID)
        };
    _fooRepository.InsertOrUpdate(entity);
    _fooRepository.Save();
    // more stuff
}

How can I use fluent syntax for EF in order to stop it from creating a new 'Bar' row in the database?

Update

Here is the generated repository code:

    public void InsertOrUpdate(Foo foo)
    {
        if (foo.ID == default(int)) {
            // New entity
            context.Foo.Add(foo);
        } else {
            // Existing entity
            context.Foo(foo).State = EntityState.Modified;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }


问:
Using maven dependency management import scope with version ranges
We are trying to centralize the versions of all the artifacts that we are using in our code base to remove duplication and ease the task of bumping versions.

We have created a BOM pom with the versions of all of our artifacts and third party artifacts and imported it (scope import) in the dependencyManagement section of the poms of each of our artifacts.

To avoid having to update each artifact each time the bom version changes we have tried to use a version range when importing the bom.

```<code><dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.acme</groupId>
      <artifactId>bom</artifactId>
      <version>[1.0,)</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
</code>```

However maven does not seem to recognize version ranges in the dependencyManagement section of a pom.

I'm aware that if the relationship between our artifacts were hierarchical we could use modules and release from a parent POM. However unfortunately this is not the case.

This must be a common use case for maven. What are we doing wrong or what other solutions exist?

答:
Taking into account the number of relevant issues in Maven issues tracker, it looks like it was a long-lasting issue in Maven.

Based on the most recent and relevant ticket, this will be resolved in the next major Maven release (4.0.0).

Body:
We are trying to centralize the versions of all the artifacts that we are using in our code base to remove duplication and ease the task of bumping versions.

We have created a BOM pom with the versions of all of our artifacts and third party artifacts and imported it (scope import) in the dependencyManagement section of the poms of each of our artifacts.

To avoid having to update each artifact each time the bom version changes we have tried to use a version range when importing the bom.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.acme</groupId>
      <artifactId>bom</artifactId>
      <version>[1.0,)</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

However maven does not seem to recognize version ranges in the dependencyManagement section of a pom.

I'm aware that if the relationship between our artifacts were hierarchical we could use modules and release from a parent POM. However unfortunately this is not the case.

This must be a common use case for maven. What are we doing wrong or what other solutions exist?


问:
tidy data by replacing "<LOD" with NA in multiple columns
Ive got some scientific data that ive imported form a CSV to R

unfortuanly I have values that are "<LOD" like in the code below
I need to change them to NA so that the coumbs can be numeric and I can start calculating averages etc.

i know mutate and

```<code>tb<-tibble(
      Mg=c(1,2,4,5,"<LOD"),
      Hg=c(5,10,15,"<LOD",11),
      Fe=c(15,"<LOD",10,4,23)
    )
</code>```

I know something like this would work but I have 100 variables and I need to do this for all of them. Does anyone have any idea how I can apply it to all my columns quickly I tried Mutate_all but Str_replace needs the string to be defined.

```<code>tb%>%mutate(Mg=str_replace(Mg,string="<LOD", replacement = NA_character_))
</code>```

thanks

答:
na_if can do this column wise on the full dataset

```<code>library(dplyr)
tb <- tb %>%
   na_if("<LOD") %>%
   type.convert(as.is = TRUE)
</code>```

-output

```<code>tb
# A tibble: 5 × 3
     Mg    Hg    Fe
  <int> <int> <int>
1     1     5    15
2     2    10    NA
3     4    15    10
4     5    NA     4
5    NA    11    23
</code>```

It may also be done by looping with across

```<code>tb <- tb %>%
      mutate(across(everything(), ~ as.numeric(na_if(.x, "<LOD"))))
</code>```

Body:
Ive got some scientific data that ive imported form a CSV to R

unfortuanly I have values that are "<LOD" like in the code below
I need to change them to NA so that the coumbs can be numeric and I can start calculating averages etc.

i know mutate and

tb<-tibble(
      Mg=c(1,2,4,5,"<LOD"),
      Hg=c(5,10,15,"<LOD",11),
      Fe=c(15,"<LOD",10,4,23)
    )

I know something like this would work but I have 100 variables and I need to do this for all of them. Does anyone have any idea how I can apply it to all my columns quickly I tried Mutate_all but Str_replace needs the string to be defined.

tb%>%mutate(Mg=str_replace(Mg,string="<LOD", replacement = NA_character_))

thanks

Body:
na_if can do this column wise on the full dataset

library(dplyr)
tb <- tb %>%
   na_if("<LOD") %>%
   type.convert(as.is = TRUE)

-output

tb
# A tibble: 5 × 3
     Mg    Hg    Fe
  <int> <int> <int>
1     1     5    15
2     2    10    NA
3     4    15    10
4     5    NA     4
5    NA    11    23

It may also be done by looping with across

tb <- tb %>%
      mutate(across(everything(), ~ as.numeric(na_if(.x, "<LOD"))))


问:
How to wait for an API response for maximum 15 seconds in react
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

```<code>const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}
</code>```

How can I implement the same in react ?

答:
waiting for 15 seconds then execute another function is not a react feature but just pure javascript.</p>
```<code>const timer15sec = new Promise((resolve, reject) => {
  setTimeout(resolve, 1500, 'overtime');
});
const firstCall =  getData();

Promise.race([timer15sec , firstCall ]).then(async (value) => {
  let response;
  if(value === 'overtime') { //means timer exceeded 15secs
      response = await getSecondData()
  }else { //not exceeded 15secs
      response = value
  }
 return  response
}).then(result => {
   //you can have your result here!!
});
</code>```

Body:
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}

How can I implement the same in react ?

Body:
waiting for 15 seconds then execute another function is not a react feature but just pure javascript.

const timer15sec = new Promise((resolve, reject) => {
  setTimeout(resolve, 1500, 'overtime');
});
const firstCall =  getData();

Promise.race([timer15sec , firstCall ]).then(async (value) => {
  let response;
  if(value === 'overtime') { //means timer exceeded 15secs
      response = await getSecondData()
  }else { //not exceeded 15secs
      response = value
  }
 return  response
}).then(result => {
   //you can have your result here!!
});


问:
Python memory management when creating variables that go into functions
I have two arrays A and B that have size (10000,100,100) (very large). I need to perform a series of operations to pass them to other functions. My question is: how can I save the most amount of memory? Let me give a specific example.

```<code>A = np.random.rand(10000,100,100)
B = np.random.rand(10000,100,100)

def ave_l2_error(diffs):
    for err in diffs:
        print(np.mean(err))

def ave_l1_error(diffs):
    for err in diffs:
        print(np.mean(err))

#Is there a difference in terms of memory usage between doing this:
L2 = [np.power(A-B, 2)]
L1 = [np.abs(A-B)]
ave_l2_error(L2)
ave_l1_error(L1)

#vs this:
ave_l2_error([np.power(A-B, 2)])
ave_l1_error([np.abs(A-B)])
</code>```

I would think the first case uses more memory because it saves L1 and L2. This reddit thread discusses renaming variables, but this is a slightly different situation (or maybe not). Would here the garbage collector detect L1 and L2 are not used anymore, and hence it deletes them? What if the code is run in IPython (instead of a shell), where one has access to variables? Would that case make a difference?

答:
In the first version, the arrays created by np.power() and np.abs() will stay in memory until the script ends, because the variables prevent them from becoming garbage.

In the second version, the arrays will be garbage collected when the function returns, because they were only assigned to the function parameters, which go away when the function exits. So this version will use less memory.

You can make the first version like the second if you reassign or delete the variables after using them in the function calls.

Body:
I have two arrays A and B that have size (10000,100,100) (very large). I need to perform a series of operations to pass them to other functions. My question is: how can I save the most amount of memory? Let me give a specific example.

A = np.random.rand(10000,100,100)
B = np.random.rand(10000,100,100)

def ave_l2_error(diffs):
    for err in diffs:
        print(np.mean(err))

def ave_l1_error(diffs):
    for err in diffs:
        print(np.mean(err))

#Is there a difference in terms of memory usage between doing this:
L2 = [np.power(A-B, 2)]
L1 = [np.abs(A-B)]
ave_l2_error(L2)
ave_l1_error(L1)

#vs this:
ave_l2_error([np.power(A-B, 2)])
ave_l1_error([np.abs(A-B)])

I would think the first case uses more memory because it saves L1 and L2. This reddit thread discusses renaming variables, but this is a slightly different situation (or maybe not). Would here the garbage collector detect L1 and L2 are not used anymore, and hence it deletes them? What if the code is run in IPython (instead of a shell), where one has access to variables? Would that case make a difference?


问:
how to show stars based on user rating?
i woud like to show star based on rating . i can only show one product with rating stars and the other products don't show any star only show rating number. could help to check which part need to change ?

```<code><%- include ('_layouts/header'); -%>
<h1>......Exciting Books.....</h1>
 <hr size="100" width="100%" align="center" color="black">
    <br>
 <div class="row products">

    <% savedexcit.forEach(function(products){ %>
            <div class="col-xs-12 col-md-4 p shop-item">
                 <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                    <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">
                    </a>
                <h3><%= products.title %></h3>
                <b>Rating: <span id=stars></span><%= products.rating %>/5</b>
                <a class="vd" href="/products/<%= products.category %>/<%= products.slug %>">View Details</a>
            </div>
        <% }); %>
</div>
<script>
 <% savedexcit.forEach(function(products){ %>
document.getElementById("stars").innerHTML = getStars(<%= products.rating %>);

function getStars(rating) {

  // Round to nearest half
  rating = Math.round(rating * 2) / 2;
  let output = [];

  // Append all the filled whole stars
  for (var i = rating; i >= 1; i--)
    output.push('<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i> ');

  // If there is a half a star, append it
  if (i == .5) output.push('<i class="fa fa-star-half-o" aria-hidden="true" style="color: gold;"></i> ');

  // Fill the empty stars
  for (let i = (5 - rating); i >= 1; i--)
    output.push('<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i> ');

  return output.join('');

}
<% }); %>
</script>
    <%- include ('_layouts/footer'); -%>
</code>```

output result:

答:
you can use jquery library:

https://www.jqueryscript.net/other/rating-star-icons.html

```<code><div id="dataReadonlyReview"
 data-rating-stars="5"
 data-rating-readonly="true"
 data-rating-value="3"
 data-rating-input="#dataReadonlyInput">
</code>```

and you can see :
Turn a number into star rating display using jQuery and CSS

Title: how to show stars based on user rating?

Body:
i woud like to show star based on rating . i can only show one product with rating stars and the other products don't show any star only show rating number. could help to check which part need to change ?

<%- include ('_layouts/header'); -%>

......Exciting Books.....

    <% savedexcit.forEach(function(products){ %>

                 <a class="pa" href="/products/<%= products.category %>/<%= products.slug %>">
                    <img class="pimage" src="/product_images/<%= products.id %>/<%= products.image %>" alt="">

<%= products.title %>

                Rating: <%= products.rating %>/5
                <a class="vd" href="/products/<%= products.category %>/<%= products.slug %>">View Details

        <% }); %>

    <%- include ('_layouts/footer'); -%>

output result:

Body:
you can use jquery library:

https://www.jqueryscript.net/other/rating-star-icons.html

<div id="dataReadonlyReview"
 data-rating-stars="5"
 data-rating-readonly="true"
 data-rating-value="3"
 data-rating-input="#dataReadonlyInput">

and you can see :
Turn a number into star rating display using jQuery and CSS


问:
WPF / DeferRefresh with bound listbox
I am trying to push in a number of updates to a collection to which I have bound a list box. Since the list can get quite big, i am trying to turn off updates (sorting, etc) until I finished inserting all the new items.

I figured:

```<code>using (col.DeferRefesh())
{
   .. add the items
}
</code>```

but this raises an exception saying that I cannot add/remove items while DeferRefresh() is on.
Is there a proper pattern for doing what I am trying to do?

答: To do this you will need to implement/derive your own collection and implement a defer refresh functionality at the collection level and then fire a collection changed event with reset as the change type when defer refresh completes</p>

Title: WPF / DeferRefresh with bound listbox

Body:
I am trying to push in a number of updates to a collection to which I have bound a list box. Since the list can get quite big, i am trying to turn off updates (sorting, etc) until I finished inserting all the new items.

I figured:

using (col.DeferRefesh())
{
   .. add the items
}

but this raises an exception saying that I cannot add/remove items while DeferRefresh() is on.
Is there a proper pattern for doing what I am trying to do?


问:
How to combine 2 arrays with the condition that 2 and 5 values will be from the second array?
There are two arrays:

```<code>$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
$newArr = [];
</code>```

How to merge to get like this;

$newArr = [1, 2, 3, 4, 5];

Now displays through one, this option is not suitable.

```<code>foreach ($arrOne as $k => $v) {
 $newArr[] = $v;
 $newArr[] = $arrTwo[$k];
}
</code>```

Here is another example. Tthe values can be different in the array.

```<code>$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];
</code>```

Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:

```<code>$newArr = [154, 682, 32, 15, 124];
</code>```

答:
```<code>$arrayOne = [12,23,45,56,65,78,99];
$arrayTwo = [2,5];

$mergedArray = [];

foreach($arrayOne as $key => $value) {

    $position = $key + 1;
    if ($position === 2) {

        $mergedArray[] = $arrayTwo[0];
    } else if ($position === 4) {

        $mergedArray[] = $arrayTwo[1];
    }

    $mergedArray[] = $value;
}
</code>```

Body:
There are two arrays:

$arrOne = [1, 3, 4];
$arrTwo = [2, 5,];
$newArr = [];

How to merge to get like this;

$newArr = [1, 2, 3, 4, 5];

Now displays through one, this option is not suitable.

foreach ($arrOne as $k => $v) {
 $newArr[] = $v;
 $newArr[] = $arrTwo[$k];
}

Here is another example. Tthe values can be different in the array.

$arrOne = [154, 32, 15];
$arrTwo = [682, 124,];

Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:

$newArr = [154, 682, 32, 15, 124];


问:
Kotlin: Subscribe to Firebase Cloud Messaging(FCM) Topic
I've used the Android (Java) way of doing things before for subscribing to a topic

```<code>FirebaseMessaging.getInstance().subscribeToTopic("weather")...
</code>```

But was looking at the Kotlin example

```<code>Firebase.messaging.subscribeToTopic("weather")...
</code>```

I'm not finding how to get this class to show to be able to write it like the above.

I can get the Java way to show but not the Kotlin.

Anyone know what needs to be added to the Gradle or other to do this?

Thanks

答:
My guess it that you forgot to add the Kotlin extensions, which means you only get the Java-level APIs.

To make the Kotlin extensions available, add the -ktx dependency to your Gradle file as shown in the documentation on setting up Kotlin.

Body:
I've used the Android (Java) way of doing things before for subscribing to a topic

FirebaseMessaging.getInstance().subscribeToTopic("weather")...

But was looking at the Kotlin example

Firebase.messaging.subscribeToTopic("weather")...

I'm not finding how to get this class to show to be able to write it like the above.

I can get the Java way to show but not the Kotlin.

Anyone know what needs to be added to the Gradle or other to do this?

Thanks


问:
Problems counting zeroes standing at the beginning of rows in a matrix
In Python I have tried to use the code below to fill a list with occurences of zeroes in rows of a matrix. These 0 must stand before all the non zero-numbers: for example in a row like [0,0,3,0] I would count only the first two zeroes.

```<code>occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      while matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")
</code>```

when I try to execute the code with previously defined dim and matrix, the console never spits out the result and freezes. Why?

答:
The problem is that you don't exit the while loop to increment j. Here's a fix to your code.

```<code>occurence_of_zeroes=[0]*dim
for i in range(dim):
    for j in range(dim):
        if matrix[i][j]!=0:
            break
        occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
    print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")
</code>```

Body:
In Python I have tried to use the code below to fill a list with occurences of zeroes in rows of a matrix. These 0 must stand before all the non zero-numbers: for example in a row like [0,0,3,0] I would count only the first two zeroes.

occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      while matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")

when I try to execute the code with previously defined dim and matrix, the console never spits out the result and freezes. Why?

Body:
The problem is that you don't exit the while loop to increment j. Here's a fix to your code.

occurence_of_zeroes=[0]*dim
for i in range(dim):
    for j in range(dim):
        if matrix[i][j]!=0:
            break
        occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
    print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")


问:
How can I forcefully change the padding inside a mat-expansion-panel-body?
so I just created an expansion panel and it's working fine (it's very hardcoded though). I need to, however, eliminate a padding entirely from the subpanel part and I can't find a proper way to do it.

Here's the panel:

https://i.stack.imgur.com/hLoKn.png

You can notice that there is a white border that I want to eliminate (upon inspection, in the div.mat-expansion-panel-body part, there is a padding. When I set it to 0, it fixes and the white borders vanish. I tried however the following in my .css:

```<code>div.mat-expansion-panel-body {
  padding: 0 !important;
}
</code>```

But it didn't work. If anyone's got a solution to fix that I'd be greatly appreciated.

答:
Add the styles to your styles.css which is the global style, but this will affect all of the mat-expansions throughout your application.

div.mat-expansion-panel-body {
  padding: 0 !important;
}
```
<p>The reason it's not working when you add it into the style of your components <em>vs</em> adding it in the global <code>styles.css</code> is that the styles are encapsulated and the <code>mat-expansion-body</code> is created outside the style of that component.</p>
<p>If you want to avoid that style appearing on every mat-expansion-panel-body you can create a class for example <code>remove-mat-expansion-padding</code> and give it to the mat-expansion-panel like this:</p>
```<mat-expansion-panel class="remove-mat-expansion-panel-padding">
```
<p>And then in your <code>styles.css</code></p>
<pre class="lang-css prettyprint-override"><code>.remove-mat-expansion-panel-padding .mat-expansion-panel-content .mat-expansion-panel-body{
    padding: 0 !important;
}
</code>```

So that the styles only apply on those mat-expansion-panel in which you add the class remove-mat-expansion-panel-padding instead of all the expansion panels throughout the app

Body:
so I just created an expansion panel and it's working fine (it's very hardcoded though). I need to, however, eliminate a padding entirely from the subpanel part and I can't find a proper way to do it.

Here's the panel:

https://i.stack.imgur.com/hLoKn.png

You can notice that there is a white border that I want to eliminate (upon inspection, in the div.mat-expansion-panel-body part, there is a padding. When I set it to 0, it fixes and the white borders vanish. I tried however the following in my .css:

div.mat-expansion-panel-body {
  padding: 0 !important;
}

But it didn't work. If anyone's got a solution to fix that I'd be greatly appreciated.

Body:
Add the styles to your styles.css which is the global style, but this will affect all of the mat-expansions throughout your application.

div.mat-expansion-panel-body {
  padding: 0 !important;
}

The reason it's not working when you add it into the style of your components vs adding it in the global styles.css is that the styles are encapsulated and the mat-expansion-body is created outside the style of that component.

If you want to avoid that style appearing on every mat-expansion-panel-body you can create a class for example remove-mat-expansion-padding and give it to the mat-expansion-panel like this:

<mat-expansion-panel class="remove-mat-expansion-panel-padding">

And then in your styles.css

.remove-mat-expansion-panel-padding .mat-expansion-panel-content .mat-expansion-panel-body{
    padding: 0 !important;
}

So that the styles only apply on those mat-expansion-panel in which you add the class remove-mat-expansion-panel-padding instead of all the expansion panels throughout the app


答:
You are reaching an infinite loop in that while because inside it you don't update any variable for it's condition

I assume what you want is something like below.

```<code>matrix = [
    [0, 2, 3],
    [0, 0, 3],
    [0, 1, 0],
]
dim = 3 # 3 rows 3 columns I suppose
occurence_of_zeroes=[[] for _ in range(dim)]
for i in range(dim):
    j = 0
    while matrix[i][j]==0:
        occurence_of_zeroes[i].append(j)
        j+=1

print(occurence_of_zeroes)
"""
[
    [0],
    [0, 1],
    [0]
]
"""
</code>```

Title: Problems counting zeroes standing at the beginning of rows in a matrix

Body:
You are reaching an infinite loop in that while because inside it you don't update any variable for it's condition

I assume what you want is something like below.

matrix = [
    [0, 2, 3],
    [0, 0, 3],
    [0, 1, 0],
]
dim = 3 # 3 rows 3 columns I suppose
occurence_of_zeroes=[[] for _ in range(dim)]
for i in range(dim):
    j = 0
    while matrix[i][j]==0:
        occurence_of_zeroes[i].append(j)
        j+=1

print(occurence_of_zeroes)
"""
[
    [0],
    [0, 1],
    [0]
]
"""


问:
How to set conditional types for object properties
I have an object with two values. I would like to type check one value conditionally based on the value of its peer. I have looked at various solutions but I cannot get it to work how I would like it to.

I can do something like this (source):

```<code>type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";

type InterfaceItem =
  | {
      item: "fruit";
      type: TypeFruit;
    }
  | {
      event: "metal";
      type: TypeMetal;
    };

type ItemTypeParameters = InterfaceItem["type"];

type Item = {
  item: "fruit" | "metal";
  type: ItemTypeParameters;
};
</code>```

But that produces:

```<code>// ✅ Correct
assignItem({
  item: "fruit",
  type: "apples",
});

// ✅ Correct
assignItem({
  item: "fruit",
  type: "copper",
});
</code>```

What I would like to do is set up the code so that the outcome would be like this:

// ✅ Correct
assignItem({
  item: "fruit",
  type: "apples",
});

// ❌ Wrong
assignItem({
  item: "fruit",
  type: "copper",
});
```

Is there a way to do this? I've looked at ConditionalTypes, which seems like what I would want, but found them confusing and it seemed like they were for other scenarios like extending types conditionally.

答:
Your original InterfaceItem is already giving you the shape you're looking for - where item: "fruit" is necessarily paired with (and only paired with) a TypeFruit. All you need is that, and nothing else.

```<code>type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";
type InterfaceItem =
  | {
      item: "fruit";
      type: TypeFruit;
    }
  | {
      event: "metal";
      type: TypeMetal;
    };

declare const assignItem: (item: InterfaceItem) => null;

assignItem({ // Works
  item: "fruit",
  type: "apples",
});

assignItem({ // Fails
  item: "fruit",
  type: "copper",
});
</code>```

Body:
I have an object with two values. I would like to type check one value conditionally based on the value of its peer. I have looked at various solutions but I cannot get it to work how I would like it to.

I can do something like this (source):

type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";

type InterfaceItem =
  | {
      item: "fruit";
      type: TypeFruit;
    }
  | {
      event: "metal";
      type: TypeMetal;
    };

type ItemTypeParameters = InterfaceItem["type"];

type Item = {
  item: "fruit" | "metal";
  type: ItemTypeParameters;
};

But that produces:

// ✅ Correct
assignItem({
  item: "fruit",
  type: "apples",
});

// ✅ Correct
assignItem({
  item: "fruit",
  type: "copper",
});

What I would like to do is set up the code so that the outcome would be like this:

// ✅ Correct
assignItem({
  item: "fruit",
  type: "apples",
});

// ❌ Wrong
assignItem({
  item: "fruit",
  type: "copper",
});

Is there a way to do this? I've looked at ConditionalTypes, which seems like what I would want, but found them confusing and it seemed like they were for other scenarios like extending types conditionally.

Body:
Your original InterfaceItem is already giving you the shape you're looking for - where item: "fruit" is necessarily paired with (and only paired with) a TypeFruit. All you need is that, and nothing else.

type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";
type InterfaceItem =
  | {
      item: "fruit";
      type: TypeFruit;
    }
  | {
      event: "metal";
      type: TypeMetal;
    };

declare const assignItem: (item: InterfaceItem) => null;

assignItem({ // Works
  item: "fruit",
  type: "apples",
});

assignItem({ // Fails
  item: "fruit",
  type: "copper",
});


答:
```<code>while matrix[i][j]==0:
     occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
</code>```

is an infinite loop. Simply use if statement instead.

```<code>occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      if matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")
</code>```

Body:
while matrix[i][j]==0:
     occurence_of_zeroes[i]=occurence_of_zeroes[i]+1

is an infinite loop. Simply use if statement instead.

occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      if matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")


问:
How to read ArrayList<String> field from database with PostgreSQL JDBC
I'm having an issue with getting the value of stored ArrayList<String> as VARCHAR[] in the database.

Somehow, when I'm debugging, I can see that the value returning from the database is:

I am expecting to store an ArrayList<String> by converting it to VARCHAR[] and when reading from the DB I expect to convert VARCHAR[] to ArrayList<String>

Code:

 public Message<ArrayList<String>> getPlayersInSession(Object data) throws SQLException, ClassNotFoundException {
        String sessionCode = (String) data;
        Session session = PostgreSQLJDBC.sessionJDBCInstance().getSession(sessionCode);

        //session.getPlayers() is the problem I have
        return new Message<>(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, session.getPlayers());
(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, players);
    }
```
<pre class="lang-java prettyprint-override"><code>public class Session {

    private int _id;
    private String _code;
    private ArrayList<String> _players;
    private ArrayList<Pair<String, String>> _leaderboard;

    public Session() {
        _code = "";
        _players = new ArrayList<>();
        _leaderboard = new ArrayList<>();
    }

    ...

}

</code>```

public class SessionJDBC implements SessionSQL {

    private final Connection _connection;

    public SessionJDBC(String url, String user, String password) throws ClassNotFoundException, SQLException {
        Class.forName("org.postgresql.Driver");

        _connection = DriverManager.getConnection(url, user, password);

        if (!sessionTableExists()) createTable();
    }

    @Override
    public void createTable() throws SQLException {
        String sql = "CREATE TABLE session(" +
                "id SERIAL PRIMARY KEY," +
                "code VARCHAR," +
                "players VARCHAR[]," +
                "leaderboard VARCHAR[]" +
                ")";
        PreparedStatement ps = _connection.prepareStatement(sql);

        ps.executeUpdate();
    }

    @Override
    public void addSession(Session session) throws SQLException {
        String sql = "INSERT INTO session(code, players, leaderboard)"
                + "VALUES (?,?,?)";

        PreparedStatement ps = _connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        ps.setString(1, session.getCode());
        ps.setArray(2, _connection.createArrayOf("VARCHAR", session.getPlayers().toArray()));
        ps.setArray(3, _connection.createArrayOf("VARCHAR", session.getLeaderboard().toArray()));

        ps.executeUpdate();

        ResultSet generatedKeys = ps.getGeneratedKeys();

        if (generatedKeys.next()) {
            session.setId(generatedKeys.getInt(1));
        }
    }

    @Override
    public void removeSession(Session session) throws SQLException {
        String sql = "DELETE FROM session WHERE id = ?";
        PreparedStatement ps = _connection.prepareStatement(sql);

        ps.setInt(1, session.getId());
        ps.executeUpdate();
    }

    @Override
    public Session getSession(String code) throws SQLException {
        return getAllSessions().stream().filter(session -> session.getCode().equals(code)).findFirst().orElse(null);
    }

    @Override
    public ArrayList<Session> getAllSessions() throws SQLException {
        ArrayList<Session> array = new ArrayList<>();

        ResultSet result = _connection.prepareStatement("SELECT * FROM session").executeQuery();

        while (result.next()) {
            Session session = new Session();

            session.setCode(result.getString("code"));
            session.setId(result.getInt("id"));
            session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
            session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));

            array.add(session);
        }

        result.close();

        return array;
    }

    @Override
    public boolean sessionTableExists() throws SQLException {
        DatabaseMetaData dbm = _connection.getMetaData();
        ResultSet tables = dbm.getTables(null, null, "session", null);

        return tables.next();
    }

}

```

答:
I don't know how the code example compiles given that the ArrayList shown in the debugger is actually of type ArrayList<PgArray> rather than ArrayList<String>.

The problem is occurring in these lines:

```<code>session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));
</code>```

For a start result.getArray("players") is returning a java.sql.Array object, more specifically a PgArray implementation. To get the real underlying data you need to do:

```<code>(String[])result.getArray("players").getArray();
</code>```

The next problem is that you are using Collections.singletonList(). What this does is produce an ArrayList with only one element. Instead what you should use is Arrays.asList. Full solution:

```<code>session.setPlayers(new ArrayList(Arrays.asList((String[])result.getArray("players").getArray)));
session.setLeaderboard(new ArrayList(Arrays.asList((String[])result.getArray("leaderboard").getArray)));
</code>```

Another thing that is interesting about this code is that you are selecting all rows from the table and then filtering in memory by streaming over the results. Why not select on the code field in an SQL query?

Body:
I'm having an issue with getting the value of stored ArrayList<String> as VARCHAR[] in the database.

Somehow, when I'm debugging, I can see that the value returning from the database is:

I am expecting to store an ArrayList<String> by converting it to VARCHAR[] and when reading from the DB I expect to convert VARCHAR[] to ArrayList<String>

Code:

 public Message<ArrayList<String>> getPlayersInSession(Object data) throws SQLException, ClassNotFoundException {
        String sessionCode = (String) data;
        Session session = PostgreSQLJDBC.sessionJDBCInstance().getSession(sessionCode);

        //session.getPlayers() is the problem I have
        return new Message<>(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, session.getPlayers());
(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, players);
    }

public class Session {

    private int _id;
    private String _code;
    private ArrayList<String> _players;
    private ArrayList<Pair<String, String>> _leaderboard;

    public Session() {
        _code = "";
        _players = new ArrayList<>();
        _leaderboard = new ArrayList<>();
    }

    ...

}

public class SessionJDBC implements SessionSQL {

    private final Connection _connection;

    public SessionJDBC(String url, String user, String password) throws ClassNotFoundException, SQLException {
        Class.forName("org.postgresql.Driver");

        _connection = DriverManager.getConnection(url, user, password);

        if (!sessionTableExists()) createTable();
    }

    @Override
    public void createTable() throws SQLException {
        String sql = "CREATE TABLE session(" +
                "id SERIAL PRIMARY KEY," +
                "code VARCHAR," +
                "players VARCHAR[]," +
                "leaderboard VARCHAR[]" +
                ")";
        PreparedStatement ps = _connection.prepareStatement(sql);

        ps.executeUpdate();
    }

    @Override
    public void addSession(Session session) throws SQLException {
        String sql = "INSERT INTO session(code, players, leaderboard)"
                + "VALUES (?,?,?)";

        PreparedStatement ps = _connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        ps.setString(1, session.getCode());
        ps.setArray(2, _connection.createArrayOf("VARCHAR", session.getPlayers().toArray()));
        ps.setArray(3, _connection.createArrayOf("VARCHAR", session.getLeaderboard().toArray()));

        ps.executeUpdate();

        ResultSet generatedKeys = ps.getGeneratedKeys();

        if (generatedKeys.next()) {
            session.setId(generatedKeys.getInt(1));
        }
    }

    @Override
    public void removeSession(Session session) throws SQLException {
        String sql = "DELETE FROM session WHERE id = ?";
        PreparedStatement ps = _connection.prepareStatement(sql);

        ps.setInt(1, session.getId());
        ps.executeUpdate();
    }

    @Override
    public Session getSession(String code) throws SQLException {
        return getAllSessions().stream().filter(session -> session.getCode().equals(code)).findFirst().orElse(null);
    }

    @Override
    public ArrayList<Session> getAllSessions() throws SQLException {
        ArrayList<Session> array = new ArrayList<>();

        ResultSet result = _connection.prepareStatement("SELECT * FROM session").executeQuery();

        while (result.next()) {
            Session session = new Session();

            session.setCode(result.getString("code"));
            session.setId(result.getInt("id"));
            session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
            session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));

            array.add(session);
        }

        result.close();

        return array;
    }

    @Override
    public boolean sessionTableExists() throws SQLException {
        DatabaseMetaData dbm = _connection.getMetaData();
        ResultSet tables = dbm.getTables(null, null, "session", null);

        return tables.next();
    }

}

Body:
I don't know how the code example compiles given that the ArrayList shown in the debugger is actually of type ArrayList<PgArray> rather than ArrayList<String>.

The problem is occurring in these lines:

session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));

For a start result.getArray("players") is returning a java.sql.Array object, more specifically a PgArray implementation. To get the real underlying data you need to do:

(String[])result.getArray("players").getArray();

The next problem is that you are using Collections.singletonList(). What this does is produce an ArrayList with only one element. Instead what you should use is Arrays.asList. Full solution:

session.setPlayers(new ArrayList(Arrays.asList((String[])result.getArray("players").getArray)));
session.setLeaderboard(new ArrayList(Arrays.asList((String[])result.getArray("leaderboard").getArray)));

Another thing that is interesting about this code is that you are selecting all rows from the table and then filtering in memory by streaming over the results. Why not select on the code field in an SQL query?


问:
Check if array value is between two array values within an array
I have an array containing another array of numbers such as:

```<code>[[0, 1350], [1350, 2700], [2700, 3375]]
</code>```

What I want to do loop though this array and check a given value is in between the two values and if it is add this to a new array.

For example say I have the value of 1320, the desired result would be this.

```<code>[0, 1350]
</code>```

I am a little stuck on how to achieve this I know it requires two loops however im unsure on how to match the value to the elements.

What I have so far

```<code>const exampleFunction = (number: number) => {
    const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]];
      const array = [];
        numberArray.map((element, index) => {
          element.map((value) => {
    // do something here?
          });
        });
}

exampleFunction(1320);
</code>```

答:
```<code>const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]]
let number = 1320;
let newArray : any = []
 numberArray.forEach((numArray) => {
    if(numArray[0] <= number && numArray[1] >= number){
        newArray.push(numArray)
    }
 })

 console.log(newArray)
</code>```

Body:
I have an array containing another array of numbers such as:

[[0, 1350], [1350, 2700], [2700, 3375]]

What I want to do loop though this array and check a given value is in between the two values and if it is add this to a new array.

For example say I have the value of 1320, the desired result would be this.

[0, 1350]

I am a little stuck on how to achieve this I know it requires two loops however im unsure on how to match the value to the elements.

What I have so far

const exampleFunction = (number: number) => {
    const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]];
      const array = [];
        numberArray.map((element, index) => {
          element.map((value) => {
    // do something here?
          });
        });
}

exampleFunction(1320);


答:
const exampleFunction = (number) => {
 const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]]
        var num = numberArray.find((element) => {
          return (element[0]>=number && element[1]<=number) || (element[1]>=number && element[0]<=number)
        });
return num
}
console.log(exampleFunction(1320))```

Title: Check if array value is between two array values within an array


问:
String arrays methods and if statement
here, it gives b's element as null rather than storing array a's value. Basically, I can't go inside the if statement</p>
```<code>public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==i){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}
</code>```

答:
I think thats more like what u wanted:

```<code>public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==((char)(i + '0'))){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}
</code>```

But that just works if 0<=i<=9

Title: String arrays methods and if statement

Body:
here, it gives b's element as null rather than storing array a's value. Basically, I can't go inside the if statement

public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==i){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}

Body:
I think thats more like what u wanted:

public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==((char)(i + '0'))){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}

But that just works if 0<=i<=9


问:
How to synch Model with Database after code first using EF4.1and MVC3?

Possible Duplicate:

  How to manually update Entity framework Code first model so that it updates a database (with a new column)?

Can somebody please tell me how I can add a new field to a class (my model) and have it update my database after I have already created the database using entiry framework 4.1 and mvc3?

I realize that I can set the following:

```<code>Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ImpressiionTrackerContext>());
</code>```

but I don't won't my data deleted from the database.

Also if I update my database (add a column to an existing table) after I have already created the database using entity framework 4.1 and mvc3...how can I synch my model with the changes (new col) I made to the DB...and keep the data that is already in the database?

I'm pretty new to EF so I will submit to ridicule here but I have yet to find an elegant solution that keeps the existing data around.

Thanks!

答:
If you are going to be using code-first and changing your model during development it is better to have some dummy data in your creation method until you have your model set in stone.

You could also generate some data scripts and run them after you regenerate the database although this isn't an automatic process, you would have to do it manually or build it into your application.

Body:
Possible Duplicate:

  How to manually update Entity framework Code first model so that it updates a database (with a new column)?

Can somebody please tell me how I can add a new field to a class (my model) and have it update my database after I have already created the database using entiry framework 4.1 and mvc3?

I realize that I can set the following:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ImpressiionTrackerContext>());

but I don't won't my data deleted from the database.

Also if I update my database (add a column to an existing table) after I have already created the database using entity framework 4.1 and mvc3...how can I synch my model with the changes (new col) I made to the DB...and keep the data that is already in the database?

I'm pretty new to EF so I will submit to ridicule here but I have yet to find an elegant solution that keeps the existing data around.

Thanks!


问:
How do I pass R.drawable.XXX value to a function in kotlin?
Here's my code:

```<code>private fun roomChange(animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(R.drawable.animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}
</code>```

I have anim.xml file and would like to pass it to a function but "animation" is an unresolved reference. How would I go about passing it correctly? Thanks in advance!

答:
R.drawable.whatever is just an Int. That's all you need to pass along to setBackgroundResource().

If you want the IDE to help prevent you from accidentally passing the wrong kind of argument, you can also add @AnimRes. Then in certain cases when it can detect that you are passing an Int that is not an animation resource ID, it will show an error.

```<code>private fun roomChange(@AnimRes animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}`
</code>```

Body:
Here's my code:

private fun roomChange(animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(R.drawable.animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}

I have anim.xml file and would like to pass it to a function but "animation" is an unresolved reference. How would I go about passing it correctly? Thanks in advance!

Body:
R.drawable.whatever is just an Int. That's all you need to pass along to setBackgroundResource().

If you want the IDE to help prevent you from accidentally passing the wrong kind of argument, you can also add @AnimRes. Then in certain cases when it can detect that you are passing an Int that is not an animation resource ID, it will show an error.

private fun roomChange(@AnimRes animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}`


问:
@Autowire within a DTO object - produces NullPointerException
On a spring boot  2.4.3 application with Java:

I am using a DTO to construct the JSON response from the domain model of the application. The DTO is just a plain java object.

I am trying to property inject a new class that I created for data transformation using the @Autowired but I get a nullPointerException on the runtime.

```<code>@Data
@NoArgsConstructor
public class FetchSupplierDTO {
    private long id;
    private String name;
    private String description;
    private String info;
    private List<String> tags;

    @Autowired
    private TagTranslation tagTranslation;

    public FetchSupplierDTO(SupplierEntity supplier) {
        this.id = supplier.getId();
        this.name = supplier.getDisplayName();
        this.description = supplier.getGivenDescription();
        this.info = supplier.getInfo();

        if (supplier.getTags() != null) {
            this.tags = tagTranslation.extractTagsFromEntity(supplier.getTags());
        }
     }
}
</code>```

```<code>@Service
public class TagTranslation {

    public List<String> extractTagsFromEntity(List<TagEntity> tagEntityList) {
        List<String> tagStringList = new ArrayList<>();
        tagEntityList.forEach(productTag -> { tagStringList.add(productTag.getTag()); });
        return tagStringList;
    }
}
</code>```

答:
First of all, looking at the current code I would design it so that the caller of the constructor is responsible for calling the autowired service. Then the DTO really stays a DTO and is not at the same time responsible for calling a service.

If there is really no way around calling a Spring component from inside a DTO then you will have to get the component manually. And call SpringBeanLocator.getBean(TagTranslation.class) to get that component and insert it in your field.

Spring holds a single instance of each component, on initialization it scans for autowired annotations within annotated classes (@Component, @Service) and initializes those fields. Once you call the constructor of such a class separately, it will not return the instance that is maintained by Spring, it will construct a new instance. Therefore it's autowired fields will be null.

```<code>public class SpringBeanLocator implements ApplicationContextAware {

  private static ApplicationContext context;

  @Override
  public final void setApplicationContext(ApplicationContext context) {
    validate(getInternalContext());
    setContext(context);
  }

  public static <T> T getBean(Class<T> type) {
    context.getBean(type);
  }
}
</code>```

Body:
On a spring boot  2.4.3 application with Java:

I am using a DTO to construct the JSON response from the domain model of the application. The DTO is just a plain java object.

I am trying to property inject a new class that I created for data transformation using the @Autowired but I get a nullPointerException on the runtime.

@Data
@NoArgsConstructor
public class FetchSupplierDTO {
    private long id;
    private String name;
    private String description;
    private String info;
    private List<String> tags;

    @Autowired
    private TagTranslation tagTranslation;

    public FetchSupplierDTO(SupplierEntity supplier) {
        this.id = supplier.getId();
        this.name = supplier.getDisplayName();
        this.description = supplier.getGivenDescription();
        this.info = supplier.getInfo();

        if (supplier.getTags() != null) {
            this.tags = tagTranslation.extractTagsFromEntity(supplier.getTags());
        }
     }
}

@Service
public class TagTranslation {

    public List<String> extractTagsFromEntity(List<TagEntity> tagEntityList) {
        List<String> tagStringList = new ArrayList<>();
        tagEntityList.forEach(productTag -> { tagStringList.add(productTag.getTag()); });
        return tagStringList;
    }
}

Body:
First of all, looking at the current code I would design it so that the caller of the constructor is responsible for calling the autowired service. Then the DTO really stays a DTO and is not at the same time responsible for calling a service.

If there is really no way around calling a Spring component from inside a DTO then you will have to get the component manually. And call SpringBeanLocator.getBean(TagTranslation.class) to get that component and insert it in your field.

Spring holds a single instance of each component, on initialization it scans for autowired annotations within annotated classes (@Component, @Service) and initializes those fields. Once you call the constructor of such a class separately, it will not return the instance that is maintained by Spring, it will construct a new instance. Therefore it's autowired fields will be null.

public class SpringBeanLocator implements ApplicationContextAware {

  private static ApplicationContext context;

  @Override
  public final void setApplicationContext(ApplicationContext context) {
    validate(getInternalContext());
    setContext(context);
  }

  public static <T> T getBean(Class<T> type) {
    context.getBean(type);
  }
}


问:
C++20 concepts: How do I use concepts to check if an object can use shared_from_this()?
I was thinking I could maybe do this:

```<code>template <typename T>
concept CanMakeSharedFromThis = std::is_base_of<std::enable_shared_from_this<T>, T>::value;
</code>```

But I think it's not working.

EDIT:

I was asked for an example, so here's an example: The reasoning for doing the above is that I'm trying to serialize raw pointers that inherit enable_shared_from_this with boost::serialization by using this concept to make an override that can call shared_from_this and pass the shared_ptr through.

shared_from_this helper function:

```<code>template <typename T>
requires CanMakeSharedFromThis<T> std::shared_ptr<T> SharedFrom(T* raw) {
    if (raw == nullptr)
        return nullptr;

    return std::reinterpret_pointer_cast<T>(raw->shared_from_this());
}
</code>```

boost::serialization override:

```<code>namespace boost::serialization {

template <class Archive, CanMakeSharedFromThis T>
void serialize(Archive& ar, T*& value, const unsigned int file_version) {
    boost::serialization::split_free(ar, value, file_version);
}

template <class Archive, CanMakeSharedFromThis T>
void save(Archive& ar, const T*& value, const unsigned int file_version) {
    ar& SharedFrom(value);
}

template <class Archive, CanMakeSharedFromThis T>
void load(Archive& ar, T*& value, const unsigned int file_version) {
    std::shared_ptr<T> tmp;
    ar >> tmp;
    value = reinterpret_cast<T*>(tmp.get());
}

}
</code>```

Simple example using the above:

```<code>class foo : public std::enable_shared_from_this<foo> {
public:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int file_version) {}
}

int main() {
    foo* bar{};
    {
        std::ofstream ofs("data.bin", std::ios::binary);
        boost::archive::binary_oarchive ar(ofs);
        ar& bar;
    }
}
</code>```

However, the functions don't seem to be called, and I'm wondering if the object isn't fitting its concept.

EDIT 2:

Fixed a typo in the example.

答:
I would do this this without checking for inheritance, but just by checking if shared_from_this can be invoked:

template <typename T>
concept CanMakeSharedFromThis = requires(T* a)
{
    a->shared_from_this();
};

template<CanMakeSharedFromThis T>
auto test(T* a)
{
    return a->shared_from_this();
}
```

https://godbolt.org/z/odj6h6zT3

Body:
I was thinking I could maybe do this:

template <typename T>
concept CanMakeSharedFromThis = std::is_base_of<std::enable_shared_from_this<T>, T>::value;

But I think it's not working.

EDIT:

I was asked for an example, so here's an example: The reasoning for doing the above is that I'm trying to serialize raw pointers that inherit enable_shared_from_this with boost::serialization by using this concept to make an override that can call shared_from_this and pass the shared_ptr through.

shared_from_this helper function:

template <typename T>
requires CanMakeSharedFromThis<T> std::shared_ptr<T> SharedFrom(T* raw) {
    if (raw == nullptr)
        return nullptr;

    return std::reinterpret_pointer_cast<T>(raw->shared_from_this());
}

boost::serialization override:

namespace boost::serialization {

template <class Archive, CanMakeSharedFromThis T>
void serialize(Archive& ar, T*& value, const unsigned int file_version) {
    boost::serialization::split_free(ar, value, file_version);
}

template <class Archive, CanMakeSharedFromThis T>
void save(Archive& ar, const T*& value, const unsigned int file_version) {
    ar& SharedFrom(value);
}

template <class Archive, CanMakeSharedFromThis T>
void load(Archive& ar, T*& value, const unsigned int file_version) {
    std::shared_ptr<T> tmp;
    ar >> tmp;
    value = reinterpret_cast<T*>(tmp.get());
}

}

Simple example using the above:

class foo : public std::enable_shared_from_this<foo> {
public:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int file_version) {}
}

int main() {
    foo* bar{};
    {
        std::ofstream ofs("data.bin", std::ios::binary);
        boost::archive::binary_oarchive ar(ofs);
        ar& bar;
    }
}

However, the functions don't seem to be called, and I'm wondering if the object isn't fitting its concept.

EDIT 2:

Fixed a typo in the example.

Body:
I would do this this without checking for inheritance, but just by checking if shared_from_this can be invoked:

template <typename T>
concept CanMakeSharedFromThis = requires(T* a)
{
    a->shared_from_this();
};

template<CanMakeSharedFromThis T>
auto test(T* a)
{
    return a->shared_from_this();
}

https://godbolt.org/z/odj6h6zT3


答:
Modify your code like this :</p>
```<code>private fun roomChange(animation: Drawable) {
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        background = animation
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}
</code>```

Title: How do I pass R.drawable.XXX value to a function in kotlin?

Body:
Modify your code like this :

private fun roomChange(animation: Drawable) {
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        background = animation
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}


问:
NestJS Nats message ack
Is there a way to manually acknowledge a message if I use NATS for async communication in a NestJS app? This is very common use case where the message is acknowledge after a service is done processing it. If the message is not acknowledged, the server would need to redeliver (just like in the old NATS Streaming library).</p>
```<code>@EventPattern({ cmd: 'user:create' })
async createUser(@Payload() user: UserDto, @Ctx() context: NatsContext) {
  await this.emailsService.sendWelcomeEmail(user)
  // need to manually acknowledge the message here but the docs do not provide a way to do so.
}
</code>```

答:
when using nats-streaming
https://www.npmjs.com/package/@nestjs-plugins/nestjs-nats-streaming-transport</p>
```<code>@EventPattern(Patterns.UserCreated)
  public async stationCreatedHandler(@Payload() data: { id: number, name: string }, @Ctx() context: NatsStreamingContext) {
    console.log(`received message: ${JSON.stringify(data)}`)
    context.message.ack()
  }

//setup
    {
        durableName: 'user-queue-group',
        manualAckMode: true,
        deliverAllAvailable: true,
      } /* TransportSubscriptionOptions */ ,
    ),
</code>```

Title: NestJS Nats message ack

Body:
Is there a way to manually acknowledge a message if I use NATS for async communication in a NestJS app? This is very common use case where the message is acknowledge after a service is done processing it. If the message is not acknowledged, the server would need to redeliver (just like in the old NATS Streaming library).

@EventPattern({ cmd: 'user:create' })
async createUser(@Payload() user: UserDto, @Ctx() context: NatsContext) {
  await this.emailsService.sendWelcomeEmail(user)
  // need to manually acknowledge the message here but the docs do not provide a way to do so.
}

Body:
when using nats-streaming
https://www.npmjs.com/package/@nestjs-plugins/nestjs-nats-streaming-transport

@EventPattern(Patterns.UserCreated)
  public async stationCreatedHandler(@Payload() data: { id: number, name: string }, @Ctx() context: NatsStreamingContext) {
    console.log(`received message: ${JSON.stringify(data)}`)
    context.message.ack()
  }

//setup
    {
        durableName: 'user-queue-group',
        manualAckMode: true,
        deliverAllAvailable: true,
      } /* TransportSubscriptionOptions */ ,
    ),


问:
Why doesn't std::integral_constant<lambda> work the same way as std::integral_constant<function-ptr>?
(related to this question).

I am trying to combine unique_ptr and lambda via std::integral_constant (taking address of most std functions is outlawed in C++20, I am figuring out a convenient way to wrap them in lambda). I noticed weird behaviour of std::integral_constant that I can't explain (godbolt):

```<code>#include <type_traits>

template<auto L, class T = decltype(L)>
using constant = std::integral_constant<T, L>;

void dummy(void*);

int main()
{
    using C1 = constant<&dummy>;
    using C2 = constant<[](void* p){ dummy(p); }>;

    C1()()(nullptr);        // #1 works as expected
    C2()()(nullptr);        // #2 works as expected

    C1()(nullptr);          // #3 unexpectedly works
    C2()(nullptr);          // #4 fails as expected

    return 0;
}
</code>```

Can someone explain why line #3 compiles? This is what std::unique_ptr uses under cover (when you use std::integral_constant as deleter) and this is why my attempts to use lambda instead of function address fail.

P.S. Line #4 fails with following message:

```<code><source>: In function 'int main()':
<source>:17:17: error: no match for call to '(C2 {aka std::integral_constant<const main()::<lambda(void*)>, <lambda closure object>main()::<lambda(void*)>{}>}) (std::nullptr_t)'
   17 |     C2()(nullptr);          // #4 fails as expected
</code>```

答:
When performing a function call on an object, not only the call operators are considered. There is a special exception if a non-explicit conversion function to a function pointer type (or function reference type) with suitable cvref-qualifiers exists.

In these situations [over.call.object]/2 says that an additional overload is generated, a surrogate call function which takes the converted implicit object pointer as first argument and the function pointer/reference's parameters as further parameters. If this overload is chosen, it will use the conversion function to convert this to the function pointer/reference and then call it with the remaining provided arguments.

std::integral_constant has a non-explicit conversion function to value_type and so if value_type is a function pointer/reference, and only then, will this surrogate call exist, which essentially forwards the object function call to a call to the stored function pointer/reference.

Body:
(related to this question).

I am trying to combine unique_ptr and lambda via std::integral_constant (taking address of most std functions is outlawed in C++20, I am figuring out a convenient way to wrap them in lambda). I noticed weird behaviour of std::integral_constant that I can't explain (godbolt):

#include <type_traits>

template<auto L, class T = decltype(L)>
using constant = std::integral_constant<T, L>;

void dummy(void*);

int main()
{
    using C1 = constant<&dummy>;
    using C2 = constant<[](void* p){ dummy(p); }>;

    C1()()(nullptr);        // #1 works as expected
    C2()()(nullptr);        // #2 works as expected

    C1()(nullptr);          // #3 unexpectedly works
    C2()(nullptr);          // #4 fails as expected

    return 0;
}

Can someone explain why line #3 compiles? This is what std::unique_ptr uses under cover (when you use std::integral_constant as deleter) and this is why my attempts to use lambda instead of function address fail.

P.S. Line #4 fails with following message:

<source>: In function 'int main()':
<source>:17:17: error: no match for call to '(C2 {aka std::integral_constant<const main()::<lambda(void*)>, <lambda closure object>main()::<lambda(void*)>{}>}) (std::nullptr_t)'
   17 |     C2()(nullptr);          // #4 fails as expected


问:
apache2 how to rewrite to special scheme
I wonder if there's easy way to let apache2 support URL rewrite to special schemes like "macappstore", "itms" and so on.

```<code>RewriteRule ^/pbmac-test$  macappstore://itunes.apple.com/us/app/id420133782  [R,L]
</code>```

http://TLD/pbmac-test will be rewrote as http://TLD/macappstore://itunes.apple.com/us/app/id420133782

答:
mod_rewrite is not detecting macappstore as a valid protocol for an absolute URI. See is_absolute_uri in mod_rewrite.c for more details.

This leads it to treat your target URI as relative rather than absolute. The R flag will prepend the current protocol, server name and port to the relative URIs in order to produce RFC correct redirect headers as documented.

For redirects as simple as the one you presented, you can use mod_alias instead:

```<code>Redirect /pbmac-test macappstore://itunes.apple.com/us/app/id420133782
</code>```

Body:
I wonder if there's easy way to let apache2 support URL rewrite to special schemes like "macappstore", "itms" and so on.

RewriteRule ^/pbmac-test$  macappstore://itunes.apple.com/us/app/id420133782  [R,L]

http://TLD/pbmac-test will be rewrote as http://TLD/macappstore://itunes.apple.com/us/app/id420133782

Body:
mod_rewrite is not detecting macappstore as a valid protocol for an absolute URI. See is_absolute_uri in mod_rewrite.c for more details.

This leads it to treat your target URI as relative rather than absolute. The R flag will prepend the current protocol, server name and port to the relative URIs in order to produce RFC correct redirect headers as documented.

For redirects as simple as the one you presented, you can use mod_alias instead:

Redirect /pbmac-test macappstore://itunes.apple.com/us/app/id420133782