问:
How to check if transaction is NFT using Web3j?
I'm using Web3j library to work with the blockchain. I want to resolve what tokens are transferred during specific transactions. What I have already tried:

Call Function with the name supportsInterface to check whether it supports NFT standards (ERC721, ERC1155 and etc.). Have not succeeded.

Tried to decoded Transaction Logs, found out how to retrieve Token ID, but I can't do anything with this information.

Any suggestions on this?

答:
You cannot get what token is used from the transaction hash: Here is my answer to see what information you can get from trnasaction hash if you decode it: How to know the cryptocurrency used in a transaction through the transaction hash?

However you can get which interface is used.

supportsInterface is used for this:

// I did not use web3j. I am not sure how you call methods in web3j
const is721 = await contract.methods.supportsInterface('0x80ac58cd').call();
if(is721) {
    return "ERC721";
}
```
<p>In order to call this your contract has to inherit from <code>ERC165</code>. if you are using contract from openzeppelin, it already inherits and it should work:</p>
```contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {}
```
<p>But if you are implementing your own ERC721, you have to make sure you inherit from ERC165. ERC165 is for detecting what interfaces a smart contract implements. ERC165 has only one function used to check if the contract signature meets the specified interface signature.</p>
```interface ERC165 {
/// @notice Query whether a contract implements some interface or
not
/// @param interfaceID Interface ID specified by ERC-165 standard
/// @dev Interface ID is defined in ERC-165 standard.
/// This function use GAS less than 30,000 gas.
/// @return If contract implements the specified interface, then
return
/// `true`
/// and `interfaceID` is not 0xffffffff, or return `false`
function supportsInterface(bytes4 interfaceID) external view
returns (bool);
}
```

Body:
You cannot get what token is used from the transaction hash: Here is my answer to see what information you can get from trnasaction hash if you decode it: How to know the cryptocurrency used in a transaction through the transaction hash?

However you can get which interface is used.

supportsInterface is used for this:

// I did not use web3j. I am not sure how you call methods in web3j
const is721 = await contract.methods.supportsInterface('0x80ac58cd').call();
if(is721) {
    return "ERC721";
}

In order to call this your contract has to inherit from ERC165. if you are using contract from openzeppelin, it already inherits and it should work:

contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {}

But if you are implementing your own ERC721, you have to make sure you inherit from ERC165. ERC165 is for detecting what interfaces a smart contract implements. ERC165 has only one function used to check if the contract signature meets the specified interface signature.

interface ERC165 {
/// @notice Query whether a contract implements some interface or
not
/// @param interfaceID Interface ID specified by ERC-165 standard
/// @dev Interface ID is defined in ERC-165 standard.
/// This function use GAS less than 30,000 gas.
/// @return If contract implements the specified interface, then
return
/// `true`
/// and `interfaceID` is not 0xffffffff, or return `false`
function supportsInterface(bytes4 interfaceID) external view
returns (bool);
}


来源: stackexchange

问:
How should I define a DAX measure to normalize dataset values by category in a time series visual?
I'm trying to obtain a plot of values by categories, normalized by
the category value at the earliest date not sooner than a selected date from a time slicer.

I tried to the following DAX measure:

```<code>Normalized =
    var mintime = CALCULATE(min(Data[Date]), ALLSELECTED(Data))
    var initial = SUMX(FILTER(ALLSELECTED(Data), Data[Date]=mintime), Data[Value])
    return DIVIDE(SUM(Data[Value]), initial)
</code>```

But this fails to correctly compute the initial values per category, and correspondingly the lines do not start at 1 on the graph.
For example, using a sample dataset Data defined as:

```<code>      Date Category  Value
2022-01-01        A    100
2022-01-01        B     95
2022-01-02        A     60
2022-01-02        B    115
2022-01-02        C     95
2022-01-03        A     36
2022-01-03        B     34
2022-01-03        C     54
2022-01-04        A     22
2022-01-04        B     10
2022-01-04        C     27
</code>```

I get the following incorrect plot:

How should I modify my measure to get the correct result?

For reference, I know I could separate the data in computed tables for each category:

```<code>TableA = FILTER(Data, Data[Category] == "A")
TableB = FILTER(Data, Data[Category] == "B")
TableC = FILTER(Data, Data[Category] == "C")
</code>```

Then define separate DAX measures for each category:

```<code>A =
    var mintime = CALCULATE(min(TableA[Date]), ALLSELECTED(TableA))
    var initial = SUMX(FILTER(ALLSELECTED(TableA), TableA[Date]=mintime), TableA[Value])
    return DIVIDE(SUM(TableA[Value]), initial)
B = ...
</code>```

Along with relationships to keep all the TableA[Date], TableB[Date], ... to refer to a common time base.
Stacking each of those measures into a line plot does produce the expected result:

However this quickly become fairly impractical as the number of categories increases (and my production dataset does have much more categories).
So I'm looking for an alternative approach involving a single measure, contextualized by the plot legend.

答:
The issue turns out to be related to the effect of ALLSELECTED when used as
either a CALCULATE modifier with a table argument, with a column argument or
as a table function.
For more information, a pretty detailed discussion on the topic can be found
in this blog on www.sqlbi.com.

Computing the earliest date of a category

The usage of ALLSELECTED(Data) when computing mintime as

```<code>var mintime = CALCULATE(min(Data[Date]), ALLSELECTED(Data))
</code>```

is a CALCULATE modifier with a table argument.
The behavior of ALLSELECTED is then to resolve to the the explicit filter of
the CALCULATE expression.
Since the only explicit filter in this case is the page's time slider, that's
the only filtering being applied.
This results in the variable mintime holding the minimum time over all
categories (subject only to the slider), regardless of the applicable category.

On the other hand, using ALLSELECTED with Data[Date] column argument
would make use of the implicit category filter created while the measure
evaluation iterates through the dates (as well as any explicit filter on the page).
Thus, to get the earliest date amongst the values of a given category,
the following should be used:

```<code>var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data[Date]))
</code>```

Computing the initial value at earliest date of a category

Similarly, the usage of ALLSELECTED(Data) when computing initial in

```<code>var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data))
var initial = SUMX(FILTER(ALLSELECTED(Data), Data[Date]=mintime), Data[Value])
</code>```

is a table function, which results in only the explicit slider filter to be
applied. This gives an initial value that is the sum over all categories.
To retain the implicit filter, we should consider using a Data[Date] column
argument instead. However in this expression this would also reduce the available dataset for the
SUMX function, rendering the Data[Value] reference invalid.
To get around this we can then rewrite the expression in two steps: first
filter the data based on the date, then use CALCULATE to compute the
corresponding value:

```<code>var initial = CALCULATE(SUM(Data[Value]), FILTER(ALL(Data[Date]),Data[Date]=mintime))
</code>```

We should note at this point that using ALL or ALLSELECTED as a table function
in the FILTER context yields the same result, since the actual filtering by
category occurs within the outer CALCULATE loop.
This brings us to the shorter equivalent form (as shown here):

```<code>var initial = CALCULATE(SUM(Data[Value]), Data[Date]=mintime)
</code>```

Conclusion

To get the correct result the measure can be modified as follows:

```<code>Normalized =
    var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data[Date]))
    var initial = CALCULATE(SUM(Data[Value]), Data[Date]=mintime)
    return DIVIDE(SUM(Data[Value]),initial)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to obtain a plot of values by categories, normalized by
the category value at the earliest date not sooner than a selected date from a time slicer.

I tried to the following DAX measure:

Normalized =
    var mintime = CALCULATE(min(Data[Date]), ALLSELECTED(Data))
    var initial = SUMX(FILTER(ALLSELECTED(Data), Data[Date]=mintime), Data[Value])
    return DIVIDE(SUM(Data[Value]), initial)

But this fails to correctly compute the initial values per category, and correspondingly the lines do not start at 1 on the graph.
For example, using a sample dataset Data defined as:

      Date Category  Value
2022-01-01        A    100
2022-01-01        B     95
2022-01-02        A     60
2022-01-02        B    115
2022-01-02        C     95
2022-01-03        A     36
2022-01-03        B     34
2022-01-03        C     54
2022-01-04        A     22
2022-01-04        B     10
2022-01-04        C     27

I get the following incorrect plot:

How should I modify my measure to get the correct result?

For reference, I know I could separate the data in computed tables for each category:

TableA = FILTER(Data, Data[Category] == "A")
TableB = FILTER(Data, Data[Category] == "B")
TableC = FILTER(Data, Data[Category] == "C")

Then define separate DAX measures for each category:

A =
    var mintime = CALCULATE(min(TableA[Date]), ALLSELECTED(TableA))
    var initial = SUMX(FILTER(ALLSELECTED(TableA), TableA[Date]=mintime), TableA[Value])
    return DIVIDE(SUM(TableA[Value]), initial)
B = ...

Along with relationships to keep all the TableA[Date], TableB[Date], ... to refer to a common time base.
Stacking each of those measures into a line plot does produce the expected result:

However this quickly become fairly impractical as the number of categories increases (and my production dataset does have much more categories).
So I'm looking for an alternative approach involving a single measure, contextualized by the plot legend.

Body:
The issue turns out to be related to the effect of ALLSELECTED when used as
either a CALCULATE modifier with a table argument, with a column argument or
as a table function.
For more information, a pretty detailed discussion on the topic can be found
in this blog on www.sqlbi.com.

Computing the earliest date of a category

The usage of ALLSELECTED(Data) when computing mintime as

var mintime = CALCULATE(min(Data[Date]), ALLSELECTED(Data))

is a CALCULATE modifier with a table argument.
The behavior of ALLSELECTED is then to resolve to the the explicit filter of
the CALCULATE expression.
Since the only explicit filter in this case is the page's time slider, that's
the only filtering being applied.
This results in the variable mintime holding the minimum time over all
categories (subject only to the slider), regardless of the applicable category.

On the other hand, using ALLSELECTED with Data[Date] column argument
would make use of the implicit category filter created while the measure
evaluation iterates through the dates (as well as any explicit filter on the page).
Thus, to get the earliest date amongst the values of a given category,
the following should be used:

var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data[Date]))

Computing the initial value at earliest date of a category

Similarly, the usage of ALLSELECTED(Data) when computing initial in

var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data))
var initial = SUMX(FILTER(ALLSELECTED(Data), Data[Date]=mintime), Data[Value])

is a table function, which results in only the explicit slider filter to be
applied. This gives an initial value that is the sum over all categories.
To retain the implicit filter, we should consider using a Data[Date] column
argument instead. However in this expression this would also reduce the available dataset for the
SUMX function, rendering the Data[Value] reference invalid.
To get around this we can then rewrite the expression in two steps: first
filter the data based on the date, then use CALCULATE to compute the
corresponding value:

var initial = CALCULATE(SUM(Data[Value]), FILTER(ALL(Data[Date]),Data[Date]=mintime))

We should note at this point that using ALL or ALLSELECTED as a table function
in the FILTER context yields the same result, since the actual filtering by
category occurs within the outer CALCULATE loop.
This brings us to the shorter equivalent form (as shown here):

var initial = CALCULATE(SUM(Data[Value]), Data[Date]=mintime)

Conclusion

To get the correct result the measure can be modified as follows:

Normalized =
    var mintime = CALCULATE(MIN(Data[Date]), ALLSELECTED(Data[Date]))
    var initial = CALCULATE(SUM(Data[Value]), Data[Date]=mintime)
    return DIVIDE(SUM(Data[Value]),initial)


问:
JSX element type 'ModalComponent' does not have any construct or call signatures

```<code>interface ModalType {
  component: JSX.Element;
  props: object;
}
function Modal({ title, message, onConfirm }: ModalProps) {
  const [modal, setModal] = useState<ModalType|{}>({});
  // useEffect(()=> {
  //   ModalServcie.on('open', (({ component, props })) => {
  //     setModal({
  //       component
  //       props,
  //       close: () => {
  //         setModal({});
  //       }
  //     })
  //   })
  // },[]);

  const ModalComponent = (modal as ModalType).component ? (modal as ModalType).component : null;
  return (
    <ModalContainer>
      {
        ModalComponent && (
          <ModalComponent
            { ...modal.props }
            close={ modal.close }
            className={ ModalComponent ? 'd-block' : '' }
          />
        )
      }
    </ModalContainer>
  );
}
</code>```

I think there's an error because the modal component can be null.

Is it a problem that the correct object value was not added when setting the model state for the first time?

I thought it’s ambiguous to initialize state to a specific value before receiving props in useEffect.

How should I fix this?

答:
Try declaring the type and only rendering the component if it actually exists:</p>
```<code>  const ModalComponent: React.Component | null = (modal as ModalType).component;
  if (ModalComponent) {
    return (
      <ModalContainer>
        <ModalComponent
          {...modal.props}
          close={modal.close}
          className='d-block'
        />
      </ModalContainer>
    );
  } else {
    return <ModalContainer></ModalContainer>;
  }
</code>```

Body:
interface ModalType {
  component: JSX.Element;
  props: object;
}
function Modal({ title, message, onConfirm }: ModalProps) {
  const [modal, setModal] = useState<ModalType|{}>({});
  // useEffect(()=> {
  //   ModalServcie.on('open', (({ component, props })) => {
  //     setModal({
  //       component
  //       props,
  //       close: () => {
  //         setModal({});
  //       }
  //     })
  //   })
  // },[]);

  const ModalComponent = (modal as ModalType).component ? (modal as ModalType).component : null;
  return (
    <ModalContainer>
      {
        ModalComponent && (
          <ModalComponent
            { ...modal.props }
            close={ modal.close }
            className={ ModalComponent ? 'd-block' : '' }
          />
        )
      }
    </ModalContainer>
  );
}

I think there's an error because the modal component can be null.

Is it a problem that the correct object value was not added when setting the model state for the first time?

I thought it’s ambiguous to initialize state to a specific value before receiving props in useEffect.

How should I fix this?

Body:
Try declaring the type and only rendering the component if it actually exists:

  const ModalComponent: React.Component | null = (modal as ModalType).component;
  if (ModalComponent) {
    return (
      <ModalContainer>
        <ModalComponent
          {...modal.props}
          close={modal.close}
          className='d-block'
        />
      </ModalContainer>
    );
  } else {
    return <ModalContainer></ModalContainer>;
  }


问:
Interact with deployed contract with ABI using Remix
How can I interact with an already deployed contract on ether(not mine) using Remix without the source code, but I have the ABI.

The reason I want to do it is because some contract has more than 20 .sol files which I dont want to manually copy and paste into Remix.

答: If you have the address of where the contract is deployed, in the "deploy and run" section of the remix, click on AtAdress under the Deploy button and enter your address. It will show you the deployed contracts.</p>


问:
Attempting to clean up python installation in a Debian 10 instance
I received the following error message when I installed some python packages in a debian instance:
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

There are packages installed under /usr/local/lib/python3.7, /usr/local/lib/python2.7 and /home/oliver/.local/lib/python3.7
The packages under /usr/local/lib are owned by root and the packages under /home/oliver/.local/lib are owned by oliver

Some version information:

Debian: 10

python3 -V : 3.7.3

python -V : 2.7.16

pip3 -V (and pip -V): 22.0.3

The primary question I have at this point is where should the python 3 packages ideally reside (and with what permissions) so as to be accessible to all users?

答:
The packages are correctly installed. The reason it asks for root permission in order to use pip is that there are two main ways to install/uninstall python packages. The first is through the package manager of the linux distro and the other through pip.
When we want to code/experiment with Python and need some new Python package it's recommended to use Virtualenv which creates an isolated Python installation that doesn't interfere with your Linux installation. So you can do whatever you want with this and if something goes wrong you just delete it and there is no problem.
As you see this is just a WARNING that you got from Debian. If you insist you can login as root and use pip to install without Virtualenv.</p>


问:
how to make this grouped list with this animation in flutter
How to make this grouped List view with the grouped date animation. I have already familiar and tried with the grouped list view but that was for header and adjusting vertically header, I want grouped header should be horizontally adjusted with the items as it's in the video and it should scroll double as it's in the video.

答:
Try sticky_infinite_list:</p>
```<code>import 'package:sticky_infinite_list/sticky_infinite_list.dart';

class Example extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return InfiniteList(
      builder: (BuildContext context, int index) {
        /// Builder requires [InfiniteList] to be returned
        return InfiniteListItem(
          /// Header builder
          headerBuilder: (BuildContext context) {
            return Container(
              ///...
            );
          },
          /// Content builder
          contentBuilder: (BuildContext context) {
            return Container(
              ///...
            );
          },
        );
      }
    );
  }
}
</code>```

Body:
Try sticky_infinite_list:

import 'package:sticky_infinite_list/sticky_infinite_list.dart';

class Example extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return InfiniteList(
      builder: (BuildContext context, int index) {
        /// Builder requires [InfiniteList] to be returned
        return InfiniteListItem(
          /// Header builder
          headerBuilder: (BuildContext context) {
            return Container(
              ///...
            );
          },
          /// Content builder
          contentBuilder: (BuildContext context) {
            return Container(
              ///...
            );
          },
        );
      }
    );
  }
}


问:
Pass variable name as argument dynamically on svydesign and dplyr::select functions
I'm newbie with R. There is a code like the following, and for that code, variable name wt_itvex_divided_by_4 should be dynamically replaced with wt_itvex_divided_by_3 or wt_itvex_divided_by_2

```<code>df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~wt_itvex_divided_by_4,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, wt_itvex_divided_by_4) %>%
  subset(ID %in% df_odds$ID)
</code>```

To implement dynamical change, I tried something like the following by using temp variable, but it didn't work

```<code>temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~temp,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)
</code>```

Or, by some search on this problem, I saw someone recommended to use get(), so I tried like the following. It didn't create the error but wt_itvex_divided_by_3 column wasn't selected

```<code>s<-'wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~get(s),
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, get(s)) %>%
  subset(ID %in% df_odds$ID)
</code>```

Referencing Ronak Shah's answer, I solved the issue by the following code (note that I used arguments differently for svydesign's weights and dplyr::select)

```<code>temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~data_sd1013[[temp]],
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)
</code>```

答:
You may try subsetting from the dataframe directly with [[.

Using apistrat data as an example.

```<code>library(survey)
library(srvyr)
data(api)

temp= "pw"

dstrat1 <- svydesign(id=~1,strata=~stype, weights= ~apistrat[[temp]],
                     data=apistrat, fpc=~fpc)
</code>```

Body:
I'm newbie with R. There is a code like the following, and for that code, variable name wt_itvex_divided_by_4 should be dynamically replaced with wt_itvex_divided_by_3 or wt_itvex_divided_by_2

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~wt_itvex_divided_by_4,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, wt_itvex_divided_by_4) %>%
  subset(ID %in% df_odds$ID)

To implement dynamical change, I tried something like the following by using temp variable, but it didn't work

temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~temp,
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)

Or, by some search on this problem, I saw someone recommended to use get(), so I tried like the following. It didn't create the error but wt_itvex_divided_by_3 column wasn't selected

s<-'wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~get(s),
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, get(s)) %>%
  subset(ID %in% df_odds$ID)

Referencing Ronak Shah's answer, I solved the issue by the following code (note that I used arguments differently for svydesign's weights and dplyr::select)

temp='wt_itvex_divided_by_3'

df_odds_sv <- as_survey(
  svydesign(id = ~psu+ID_fam,
            strata = ~kstrata,
            weights = ~data_sd1013[[temp]],
            data = data_sd1013
            )) %>%
  dplyr::select(ID, ID_fam, psu, kstrata, temp) %>%
  subset(ID %in% df_odds$ID)

Body:
You may try subsetting from the dataframe directly with [[.

Using apistrat data as an example.

library(survey)
library(srvyr)
data(api)

temp= "pw"

dstrat1 <- svydesign(id=~1,strata=~stype, weights= ~apistrat[[temp]],
                     data=apistrat, fpc=~fpc)


问:
Android Word-Wrap EditText text
I have been trying to get my EditText box to word wrap, but can't seem to do it.

I have dealt with much more complicated issues while developing Android applications, and this seems like it should be a straightforward process.

However, the issue remains, and I have a large text box that is only allowing me to enter text on one line, continuing straight across, scrolling horizontally as I enter text.

Here is the XML code for the EditText object from my layout file.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/myWidget48"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
 <ScrollView
    android:id="@+id/myScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    >
    <LinearLayout
        android:id="@+id/widget37"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
    >

<EditText
        android:id="@+id/txtNotes"
        android:layout_width="300px"
        android:layout_height="120px"
        android:scrollbars="vertical"
        android:textSize="18sp"
        android:gravity="left"
        android:layout_marginTop="10dip"
        android:inputType="textCapSentences"
        >
    </EditText>
</LinearLayout>
</ScrollView>
</LinearLayout>
</code>```

答:
Try this. It works in my edittext.</p>
```<code> android:gravity="top|start"
</code>```

Title: Android Word-Wrap EditText text

Body:
I have been trying to get my EditText box to word wrap, but can't seem to do it.

I have dealt with much more complicated issues while developing Android applications, and this seems like it should be a straightforward process.

However, the issue remains, and I have a large text box that is only allowing me to enter text on one line, continuing straight across, scrolling horizontally as I enter text.

Here is the XML code for the EditText object from my layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/myWidget48"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
 <ScrollView
    android:id="@+id/myScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    >
    <LinearLayout
        android:id="@+id/widget37"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
    >

<EditText
        android:id="@+id/txtNotes"
        android:layout_width="300px"
        android:layout_height="120px"
        android:scrollbars="vertical"
        android:textSize="18sp"
        android:gravity="left"
        android:layout_marginTop="10dip"
        android:inputType="textCapSentences"
        >
    </EditText>
</LinearLayout>
</ScrollView>
</LinearLayout>

Body:
Try this. It works in my edittext.

 android:gravity="top|start"


问:
AWS cron job converting images in S3 bucket to WebP
I have a client who wants the image files for their website (stored in an S3 bucket) converted to WebP. Since their customers often upload images (and don't use WebP), they wanted some script that would run periodically to search through the bucket for un-converted image files and convert them to WebP. The script would detect whether or not there was an extant WebP version of a file and, if not, create one; then, some server-side code would preferentially load the WebP version of each image if it were available.

From my research, it seems like AWS scheduled/cron jobs are done with Lambda functions via EventBridge.

Can I do this using a BASH script, or am I limited to the supported languages for Lambda functions (.NET, Go, Java, Node.js, Python, or Ruby)?

Do I have to install something in AWS in order to do the WebP processing (and how do I do that)?

Also, Lambda functions can only run for 15 minutes maximum. This probably won't be an issue once everything's set up, but the initial conversion of the images already in the bucket (easily over 1000) might well take over 15 minutes. What's a good way to convert the images that are already there?

答:
What's a good way to convert the images that are already there?

For the images which are already there, you can use AWS batch with spot instances to be cost-effective.

Can I do this using a BASH script?
you can, but for that you need to use custom runtime https://aws.amazon.com/about-aws/whats-new/2018/11/aws-lambda-now-supports-custom-runtimes-and-layers/ or different approach will be to upload your bash script as a zip inside lambda and ask lambda to execute it. https://stackoverflow.com/a/38337076/13126651

And now the question when should lambda run?
If the client wants to run periodically go for event bridge + cron + lambda architecture otherwise go for s3 upload trigger to invoke lambda https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html


问:
c++ How to call yourself in singleton construction
```<code>#include <iostream>

class demo1
{
public:
    demo1();
};

class Singleton
{
private:
    Singleton();
public:
    static Singleton* getInstance();
};

Singleton* Singleton::getInstance()
{
    static Singleton s;
    return &s;
}

Singleton::Singleton()
{
    demo1 d1;
}

demo1::demo1()
{
    Singleton::getInstance();
}

int main()
{
    std::cout << "vs2017 begin" << std::endl;
    Singleton::getInstance();
    std::cout << "vs2017 end" << std::endl;
}

</code>```

visual studio 2017 not responding
But can run in visual studio 2005

This project is a problem that arises when VS2005 is upgraded to vs2017. I'm curious why it can be done in VS2005

visual studio 2005
visual studio 2017

答:
You have initialization recursion since your getInstance() function uses the constructor to create an object which then calls getInstance().

Dynamic initialization of a block variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

"Working in VS2005" is one possible outcome of undefined behavior.

In this case, your constructor doesn't need to do anything and then everything will be ok:

```<code>Singleton::Singleton() = default;
</code>```

Out of scope of the question: I suggest that you return the instance by reference instead. It makes integrating with most other code easier:

```<code>Singleton& Singleton::getInstance()
{
    static Singleton s;
    return s;
}
</code>```

Body:
#include <iostream>

class demo1
{
public:
    demo1();
};

class Singleton
{
private:
    Singleton();
public:
    static Singleton* getInstance();
};

Singleton* Singleton::getInstance()
{
    static Singleton s;
    return &s;
}

Singleton::Singleton()
{
    demo1 d1;
}

demo1::demo1()
{
    Singleton::getInstance();
}

int main()
{
    std::cout << "vs2017 begin" << std::endl;
    Singleton::getInstance();
    std::cout << "vs2017 end" << std::endl;
}

visual studio 2017 not responding
But can run in visual studio 2005

This project is a problem that arises when VS2005 is upgraded to vs2017. I'm curious why it can be done in VS2005

visual studio 2005
visual studio 2017

Body:
You have initialization recursion since your getInstance() function uses the constructor to create an object which then calls getInstance().

Dynamic initialization of a block variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

"Working in VS2005" is one possible outcome of undefined behavior.

In this case, your constructor doesn't need to do anything and then everything will be ok:

Singleton::Singleton() = default;

Out of scope of the question: I suggest that you return the instance by reference instead. It makes integrating with most other code easier:

Singleton& Singleton::getInstance()
{
    static Singleton s;
    return s;
}


问:
How to send an Email with a locally running SMTP/IMAP Server using Reactjs?
I've have been searching online for sending emails using reactjs and they all seem to be working by installling email.js and registering it through their domain.

However, I have a locally running SMTP server on my server that can send and receive emails though my domain.

I was wondering how I can use this service via ReactJs and JavaScript?

I also on the same server have a Nextlcloud Instance running and it can send out emails successfully without any outside configuration done for password resets and other things.

Any help or links would be much appreciated to help solve this. If I need to clarify anything more, please let me know. I was thinking of having some text boxes that a person can type into and they click submit and it will send out a specific email from my domain.

答:
The only network protocols you can use client-side JS to communicate with are HTTP and Websockets.

You cannot connect directly to an SMTP server from a web browser.

(If you could, and you handed over the credentials to send an email from your server using raw SMTP then you’d effectively turn your mail server into a spam relay, so this wouldn’t be desirable anyway).

You need a webservice that accepts an HTTP request from the browser and sends the email.

smtp.js is a third-party service which does this.

You can write you own so that you don’t need to give your mail server credentials to a third-party.


问:
How to determine if a pandas column type can be reduced from int64 to int32 or from float64 to float32?
I have a dataframe which is huge(8 gb). I am trying to find if i will loose any information if i downsize the columns from int64 to int32 or from float64 to float32.

How to find out if the information in dataframe will be lost or not in conversion?

答:
You can easily check integers, e.g.:

```<code>df.abs().ge(2 ** 32).to_numpy().any()
</code>```

If it's False, you're safe. Otherwise you might have to check column-wise and handle accordingly.

Like @anon01 mentioned, when it comes to floats it really depends on your use case.

Body:
You can easily check integers, e.g.:

df.abs().ge(2 ** 32).to_numpy().any()

If it's False, you're safe. Otherwise you might have to check column-wise and handle accordingly.

Like @anon01 mentioned, when it comes to floats it really depends on your use case.


问:
Android Camera application - error when pausing/exiting
Every time I exit/pause my camera activity, my application crashes. I think it may have something to do with releasing the camera on pause/exit, but I'm not sure where exactly to do it. An explanation would be much appreciated. Thanks!

CameraActivity.java

```<code>public class CameraActivity extends Activity {
Preview preview;
Button buttonClick;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    preview = new Preview(this);

    ((FrameLayout) findViewById(R.id.preview)).addView(preview);

    buttonClick = (Button) findViewById(R.id.buttonClick);

    buttonClick.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            preview.camera.takePicture(shutterCallback, rawCallback,
                    jpegCallback);
        }
    });
}

ShutterCallback shutterCallback = new ShutterCallback() {
    @Override
    public void onShutter() {
    }
};

PictureCallback rawCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
    }
};

PictureCallback jpegCallback = new PictureCallback() { // <8>
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
                    doSomeStuff();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            camera.stopPreview();
            camera.startPreview();
        }
    }
};
}
</code>```

Preview.java

```<code>public class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
public Camera camera;

Preview(Context context) {
    super(context);

    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    camera = Camera.open();
    camera.setDisplayOrientation(90);

    try {

        camera.setPreviewDisplay(holder);
        camera.setPreviewCallback(new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Preview.this.invalidate();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    camera.stopPreview();
    camera.release();
    camera = null;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    camera.startPreview();
}

}
</code>```

edit: here's the exception

```<code>08-18 01:18:50.242: ERROR/AndroidRuntime(10222): FATAL EXCEPTION: main
08-18 01:18:50.242: ERROR/AndroidRuntime(10222): java.lang.RuntimeException: Method called after release()
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera.setHasPreviewCallback(Native Method)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera.access$600(Camera.java:114)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera$EventHandler.handleMessage(Camera.java:545)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.os.Looper.loop(Looper.java:143)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.app.ActivityThread.main(ActivityThread.java:4196)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at java.lang.reflect.Method.invoke(Method.java:507)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Edit: Sorry, I take back the previous solution.
The problem is with the onPreviewFrame callback, why do you need it? Once you set the preview display you don't need to invalidate the view, it is done automatically by the camera.</p>

ContentLicense: CC BY-SA 3.0

Body:
Every time I exit/pause my camera activity, my application crashes. I think it may have something to do with releasing the camera on pause/exit, but I'm not sure where exactly to do it. An explanation would be much appreciated. Thanks!

CameraActivity.java

public class CameraActivity extends Activity {
Preview preview;
Button buttonClick;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    preview = new Preview(this);

    ((FrameLayout) findViewById(R.id.preview)).addView(preview);

    buttonClick = (Button) findViewById(R.id.buttonClick);

    buttonClick.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            preview.camera.takePicture(shutterCallback, rawCallback,
                    jpegCallback);
        }
    });
}

ShutterCallback shutterCallback = new ShutterCallback() {
    @Override
    public void onShutter() {
    }
};

PictureCallback rawCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
    }
};

PictureCallback jpegCallback = new PictureCallback() { // <8>
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
                    doSomeStuff();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            camera.stopPreview();
            camera.startPreview();
        }
    }
};
}

Preview.java

public class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
public Camera camera;

Preview(Context context) {
    super(context);

    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    camera = Camera.open();
    camera.setDisplayOrientation(90);

    try {

        camera.setPreviewDisplay(holder);
        camera.setPreviewCallback(new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Preview.this.invalidate();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    camera.stopPreview();
    camera.release();
    camera = null;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    camera.startPreview();
}

}

edit: here's the exception

08-18 01:18:50.242: ERROR/AndroidRuntime(10222): FATAL EXCEPTION: main
08-18 01:18:50.242: ERROR/AndroidRuntime(10222): java.lang.RuntimeException: Method called after release()
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera.setHasPreviewCallback(Native Method)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera.access$600(Camera.java:114)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.hardware.Camera$EventHandler.handleMessage(Camera.java:545)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.os.Looper.loop(Looper.java:143)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at android.app.ActivityThread.main(ActivityThread.java:4196)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at java.lang.reflect.Method.invoke(Method.java:507)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-18 01:18:50.242: ERROR/AndroidRuntime(10222):     at dalvik.system.NativeStart.main(Native Method)


问:
int io.jsonwebtoken.SignatureAlgorithm.getMinKeyLength()' no such method error while generating a token key for authentication
Hello all I am trying to use JJWT to generate a security token for authenticating users. But getting this error. Here is my pom.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>angular-spring-crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>angular-spring-crud</name>
    <description>Angular-Spring crud project</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Here is my method to generate a token if needed

```<code>protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        Date exp = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        Key key = Keys.hmacShaKeyFor(KEY.getBytes());

        Claims claims = Jwts.claims().setSubject(((User) auth.getPrincipal()).getUsername());
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).setExpiration(exp).compact();
        res.addHeader("token", token);

    }
</code>```

How to solve this problem? I tryed before to changed version of jjwt to 0.11.2 but got a build eror it couldn't find a jar file.

My full stack trace

```<code>java.lang.NoSuchMethodError: 'int io.jsonwebtoken.SignatureAlgorithm.getMinKeyLength()'
    at io.jsonwebtoken.security.Keys.hmacShaKeyFor(Keys.java:84) ~[jjwt-api-0.11.2.jar:0.11.2]
    at com.example.angularspringcrud.security.AuthenticationFilter.successfulAuthentication(AuthenticationFilter.java:53) ~[classes/:na]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:233) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:213) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

2022-01-29 16:55:37.395 DEBUG 14992 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={}
2022-01-29 16:55:37.395 DEBUG 14992 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-01-29 16:55:37.396 DEBUG 14992 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2022-01-29 16:55:37.396 DEBUG 14992 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Sat Jan 29 16:55:37 EET 2022, status=500, error=Internal Server Error, path=/login}]
2022-01-29 16:55:37.397 DEBUG 14992 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 500
</code>```

答:
You did not implement right io.jsonwebtoken dependencies.

These are the three dependencies you have to implement correctly;

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.2</version>
      </dependency>
```

Body:
Hello all I am trying to use JJWT to generate a security token for authenticating users. But getting this error. Here is my pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>angular-spring-crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>angular-spring-crud</name>
    <description>Angular-Spring crud project</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Here is my method to generate a token if needed

protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        Date exp = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        Key key = Keys.hmacShaKeyFor(KEY.getBytes());

        Claims claims = Jwts.claims().setSubject(((User) auth.getPrincipal()).getUsername());
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).setExpiration(exp).compact();
        res.addHeader("token", token);

    }

How to solve this problem? I tryed before to changed version of jjwt to 0.11.2 but got a build eror it couldn't find a jar file.

My full stack trace

java.lang.NoSuchMethodError: 'int io.jsonwebtoken.SignatureAlgorithm.getMinKeyLength()'
    at io.jsonwebtoken.security.Keys.hmacShaKeyFor(Keys.java:84) ~[jjwt-api-0.11.2.jar:0.11.2]
    at com.example.angularspringcrud.security.AuthenticationFilter.successfulAuthentication(AuthenticationFilter.java:53) ~[classes/:na]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:233) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:213) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.15.jar:5.3.15]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

2022-01-29 16:55:37.395 DEBUG 14992 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={}
2022-01-29 16:55:37.395 DEBUG 14992 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-01-29 16:55:37.396 DEBUG 14992 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2022-01-29 16:55:37.396 DEBUG 14992 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Sat Jan 29 16:55:37 EET 2022, status=500, error=Internal Server Error, path=/login}]
2022-01-29 16:55:37.397 DEBUG 14992 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 500


问:
Animated screen between a navigation of two screens in flutter
I have three screens.
FirstScreen, SecondScreen and a GreenScreen,
im using custom navigation in my navigation routes like so (im using named routes),

```<code>case secondScreenUIRoute:
        return Platform.isIOS
            ? CupertinoPageRoute(
                builder: (context) => const SecondScreen())
            : CustomPageRoute(
                builder: (context) => const SecondScreen());

</code>```

my green screen looks like so

```<code>class GreenScreen extends StatelessWidget {
  const GreenScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      color: CustomColors.greenLight,
    );
  }
}

</code>```

My basic idea was to have this GreenScreen in between FirstScreen and SecondScreen on navigation(from first to second), but as a fade in fade out effect. Plainly I like to give the user an impression like, when going from FirstScreen to SecondScreen, there seems to be a subtle animation where a green screen is faded in and faded out before reaching SecondScreen.

how Can i achieve this in flutter?

答:
you can use animations package:

https://pub.dev/packages/animations#fade-through

This package contains pre-canned animations for commonly-desired effects. The animations can be customized with your content and dropped into your application to delight your users.

this is an example source code of using the package:

https://github.com/flutter/packages/tree/master/packages/animations/example

if you want to learn from youtube, you can learn here:

https://www.youtube.com/watch?v=3GMq45zRVLo

I've used this package before, and I recommend this package because it's easy to use and this package was made by the flutter team

Body:
I have three screens.
FirstScreen, SecondScreen and a GreenScreen,
im using custom navigation in my navigation routes like so (im using named routes),

case secondScreenUIRoute:
        return Platform.isIOS
            ? CupertinoPageRoute(
                builder: (context) => const SecondScreen())
            : CustomPageRoute(
                builder: (context) => const SecondScreen());

my green screen looks like so

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

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      color: CustomColors.greenLight,
    );
  }
}

My basic idea was to have this GreenScreen in between FirstScreen and SecondScreen on navigation(from first to second), but as a fade in fade out effect. Plainly I like to give the user an impression like, when going from FirstScreen to SecondScreen, there seems to be a subtle animation where a green screen is faded in and faded out before reaching SecondScreen.

how Can i achieve this in flutter?


问:
React/Typescript Property 'data' does not exist on type 'IntrinsicAttributes & [Interface]'
I have created a Component where I am accessing a local json file and passing the array of objects to another component.

Code snippet for the first component -

import statement -
import TvData from './Data/TVData.json';

for the second component I am passing the data like so,
I am getting the Error for this line saying

```<code>Type '{ data: { id: number; name: string; price: number; imageUrl: string; }[]; }' is not assignable to type 'IntrinsicAttributes & dataProps'.
  Property 'data' does not exist on type 'IntrinsicAttributes & dataProps'.
</code>```

 <SecondComponent data={TvData} />

Code Snippet for the second component -

here I defined interface like so,

```<code>interface dataProp {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type dataProps = dataProp[];
</code>```

and the functional Component with parameters like so,

function SecondComponent(data: dataProps)

inside which I am mapping through the array of objects from the json file

```<code>{
  data.map((item : dataProp) =>
   {
    return (
     <Item key={item.id}>
        {item.name}
      </Item>
           )
    }
  )}
</code>```

I am new to React with Typescript so any sort of help would be appreciated.

答:
component props must be an object, not an array. Try putting the array inside of one of the input props, like this:</p>
```<code>interface Item {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type Props = { data: Item[] };

...

function SecondComponent(props: Props) {
  return props.data.map(item => (
     <Item key={item.id}>
        {item.name}
      </Item>
    ));
}

</code>```

Body:
I have created a Component where I am accessing a local json file and passing the array of objects to another component.

Code snippet for the first component -

import statement -
import TvData from './Data/TVData.json';

for the second component I am passing the data like so,
I am getting the Error for this line saying

Type '{ data: { id: number; name: string; price: number; imageUrl: string; }[]; }' is not assignable to type 'IntrinsicAttributes & dataProps'.
  Property 'data' does not exist on type 'IntrinsicAttributes & dataProps'.

 <SecondComponent data={TvData} />

Code Snippet for the second component -

here I defined interface like so,

interface dataProp {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type dataProps = dataProp[];

and the functional Component with parameters like so,

function SecondComponent(data: dataProps)

inside which I am mapping through the array of objects from the json file

{
  data.map((item : dataProp) =>
   {
    return (
     <Item key={item.id}>
        {item.name}
      </Item>
           )
    }
  )}

I am new to React with Typescript so any sort of help would be appreciated.

Body:
component props must be an object, not an array. Try putting the array inside of one of the input props, like this:

interface Item {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type Props = { data: Item[] };

...

function SecondComponent(props: Props) {
  return props.data.map(item => (
     <Item key={item.id}>
        {item.name}
      </Item>
    ));
}


问:
SQL Query Checking if Row's Date is Within X Amount of Days Of Previous Row
I want to use SQL measure how effective a technician is at resolving an issue, by preventing another call-back to the equipment within 14 days. I would appreciate help on how to generate the last column of this table using a SQL query. (Assume dates are in format d/m/yyyy) (the descriptions in round brackets are only for your help in understanding the problem).

Tech Last Name | Equipment Number | Notifications Date | Is Within 14 Days of Previous
Bob Anderson   | 10111231111      | 1/3/2021           | N
Bob Anderson   | 10111231111      | 28/2/2021          | Y (since the 28th of feb is within 14 days of first March)
Bob Anderson   | 10111231111      | 1/2/2021           | N
Bob Anderson   | 10000000001      | 28/1/2021          | N (since the equipment number is different from the previous)

Example of Table Layout

The problem I have is generating the results of the last column [Is Within 14 Days of Previous], since this requires access to the data in the previous row which SQL was not designed to do. I am currently working on this problem in Microsoft Access, or there is also the option of using VBA. Thank you for the help :)

答:
Here some possible solution.

Created on Access.
Demo table
DemoTable

Created a query as follows

```<code>SELECT d1.name
    ,d1.machine
    ,d1.maintenance_date
    ,(d1.maintenance_date-(select max(d2.maintenance_date)
            from demo d2 where d2.name = d1.name and d2.machine = d1.machine
            and d2.maintenance_date < d1.maintenance_date)) AS days_between
    FROM DEMO AS d1;
</code>```

Results.

QueryResults

Body:
Here some possible solution.

Created on Access.
Demo table
DemoTable

Created a query as follows

SELECT d1.name
    ,d1.machine
    ,d1.maintenance_date
    ,(d1.maintenance_date-(select max(d2.maintenance_date)
            from demo d2 where d2.name = d1.name and d2.machine = d1.machine
            and d2.maintenance_date < d1.maintenance_date)) AS days_between
    FROM DEMO AS d1;

Results.

QueryResults


问:
Laravel 5.4 field doesn't have a default value
I am having this error and none of the googled result i checked is similar to my problem.

I have an application with class Deal, User, and Matches

A deal has many matches.
A user has many matches.
A user has many deals.

I am attempting to create a new Match using my Deal object

```<code>$deal->matches()->create(['user_id'=>$id]);
</code>```

This is my match class, i have defined all needed relationships

```<code>class Match extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    public $timestamps = false;
    public $expired_on = "";

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->matched_on = $model->freshTimestamp();
        });
    }

    public function __construct(){
        $d = (new \DateTime($this->matched_on))->modify('+1 day');
        $this->expired_on = $d->format('Y-m-d H:i:s');
    }

    /**
     * Get the user that owns the match.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Get the deal that owns the match.
     */
    public function deal()
    {
        return $this->belongsTo('App\Deal');
    }
}
</code>```

And i keep getting this error when i attempt to create a new match.

QueryException in Connection.php line 647:
  SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into matches (deal_id) values (1))

I have my guarded to be an empty array, what could be the problem?

答:
changing your "config/database.php" won't help.
If you're getting this error, you're not sending the data to database correctly.
check your function in your controller, the create() method is probably being blocked by an if statement or something.
or

if it's an API, check the post request from the frontend that's where your issue is.
make sure the form is correctly passed into to request.

Body:
I am having this error and none of the googled result i checked is similar to my problem.

I have an application with class Deal, User, and Matches

A deal has many matches.
A user has many matches.
A user has many deals.

I am attempting to create a new Match using my Deal object

$deal->matches()->create(['user_id'=>$id]);

This is my match class, i have defined all needed relationships

class Match extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    public $timestamps = false;
    public $expired_on = "";

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->matched_on = $model->freshTimestamp();
        });
    }

    public function __construct(){
        $d = (new \DateTime($this->matched_on))->modify('+1 day');
        $this->expired_on = $d->format('Y-m-d H:i:s');
    }

    /**
     * Get the user that owns the match.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Get the deal that owns the match.
     */
    public function deal()
    {
        return $this->belongsTo('App\Deal');
    }
}

And i keep getting this error when i attempt to create a new match.

QueryException in Connection.php line 647:
  SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into matches (deal_id) values (1))

I have my guarded to be an empty array, what could be the problem?


问:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE productID = '1'' at line 6 in C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php:31 Stack trace: #0 C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php(31): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php on line 31

```<code><?php
// Get the product data
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);

// Validate inputs
if ($category_id == null || $category_id == false ||
    $product_id == null || $product_id == false ||
    $code == null || $name == null || $price == null || $price == false) {
$error = "Invalid product data. Check all fields and try again.";
include('error.php');
} else {
require_once('database.php');

// Add the product to the database
$query = 'UPDATE products
            SET categoryID = :category_id,
                productCode = :code,
                productName = :name,
                listPrice = :price,
            WHERE productID = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(':product_id', $product_id);
$statement->bindValue(':category_id', $category_id);
$statement->bindValue(':code', $code);
$statement->bindValue(':name', $name);
$statement->bindValue(':price', $price);
$statement->execute();
$statement->closeCursor();

// Display the Product List page
include('index.php');
}
?>
</code>```

I'm stuck trying to figure out what is wrong. Any help would be greatly appreciated!

答:
Remove the comma after last field set.</p>
```<code>$query = 'UPDATE products
            SET categoryID = :category_id,
                productCode = :code,
                productName = :name,
                listPrice = :price           -- no comma here
            WHERE productID = :product_id';
</code>```

Body:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE productID = '1'' at line 6 in C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php:31 Stack trace: #0 C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php(31): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\ex_starts\ch04_ex1\edit_product.php on line 31

<?php
// Get the product data
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);

// Validate inputs
if ($category_id == null || $category_id == false ||
    $product_id == null || $product_id == false ||
    $code == null || $name == null || $price == null || $price == false) {
$error = "Invalid product data. Check all fields and try again.";
include('error.php');
} else {
require_once('database.php');

// Add the product to the database
$query = 'UPDATE products
            SET categoryID = :category_id,
                productCode = :code,
                productName = :name,
                listPrice = :price,
            WHERE productID = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(':product_id', $product_id);
$statement->bindValue(':category_id', $category_id);
$statement->bindValue(':code', $code);
$statement->bindValue(':name', $name);
$statement->bindValue(':price', $price);
$statement->execute();
$statement->closeCursor();

// Display the Product List page
include('index.php');
}
?>

I'm stuck trying to figure out what is wrong. Any help would be greatly appreciated!

Body:
Remove the comma after last field set.

$query = 'UPDATE products
            SET categoryID = :category_id,
                productCode = :code,
                productName = :name,
                listPrice = :price           -- no comma here
            WHERE productID = :product_id';


问:
I have a .txt file and I should scroll and print each element on the screen (list of strings)
I have a .txt file and I should scroll and print each element on the screen (list of strings).
I am new and inexperienced, can you please help me write the file ndex.cshtml (view)?

(Class.cs)

```<code>public class Reader
{
    public static List<string> Read(string path)
     {
            var result = new List<string>();
            String line;

        try
            {
                StreamReader sr = new StreamReader(path);
                line = sr.ReadLine();
            while (line != null)
                {
                    result.Add(line);
                    line = sr.ReadLine();

            }
            }
        catch (Exception e)
        {
            result = new List<string>();
        }

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

}

(HomeController.cs)
{

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        var result = Reader.Reader.Read("......txt");

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

答:
I just created a demo project in github, to display text lines in html. The OP also mentioned scroll and print, but that should be considered only after succcesfully display those lines. So this demo can be a start for the OP.
Also paste main code here. I'm using Razor pages.

Code behind

    public class IndexModel : PageModel
    {
        //other lines...
        public string[] Lines { get; set; }

        public void OnGet()
        {
            // you need change the fullName, and may need some exception handling
            string fullName = Path.Combine(_hostEnvironment.WebRootPath, "js/site.js");
            Lines = System.IO.File.ReadAllLines(fullName);
        }
    }
```
<ul>
<li>Razor</li>
</ul>
<pre class="lang-cs prettyprint-override"><code><div class="text-center">
    <h1 class="display-4">This is text lines</h1>
    @foreach (string line in @Model.Lines)
    {
        <p>@line</p>
        @*add a hr to distinguish lines*@
        <hr />
    }
</div>
</code>```

Body:
I have a .txt file and I should scroll and print each element on the screen (list of strings).
I am new and inexperienced, can you please help me write the file ndex.cshtml (view)?

(Class.cs)

public class Reader
{
    public static List<string> Read(string path)
     {
            var result = new List<string>();
            String line;

        try
            {
                StreamReader sr = new StreamReader(path);
                line = sr.ReadLine();
            while (line != null)
                {
                    result.Add(line);
                    line = sr.ReadLine();

            }
            }
        catch (Exception e)
        {
            result = new List<string>();
        }

        return result;
    }
}

}

(HomeController.cs)
{

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var result = Reader.Reader.Read("......txt");

        return View(result);
    }

Body:
I just created a demo project in github, to display text lines in html. The OP also mentioned scroll and print, but that should be considered only after succcesfully display those lines. So this demo can be a start for the OP.
Also paste main code here. I'm using Razor pages.

Code behind

    public class IndexModel : PageModel
    {
        //other lines...
        public string[] Lines { get; set; }

        public void OnGet()
        {
            // you need change the fullName, and may need some exception handling
            string fullName = Path.Combine(_hostEnvironment.WebRootPath, "js/site.js");
            Lines = System.IO.File.ReadAllLines(fullName);
        }
    }

Razor

<div class="text-center">
    <h1 class="display-4">This is text lines</h1>
    @foreach (string line in @Model.Lines)
    {
        <p>@line</p>
        @*add a hr to distinguish lines*@
        <hr />
    }
</div>


问:
Excel Line Chart with separate data points for a single line
I have a weird problem that google's not being too kind on results (mostly basic things on how to create a line chart, or combination charts, neither of which I'm after).

I'm trying to automate a report we do each month, I've managed pretty well so far by having a linked excel chart and objects, I have a single sheet in excel I paste my formatted data (set format is consistent each month) then excel picks out the data, creates the charts and when opening powerpoint it reads it all in from there.

Great! Until I was given a new piece of information, there's monthly data and a yearly tally in my data, monthly data is shown with a particular "weighting" applied, year with a different one and it's this that's caused a problem.

The package that's exporting the data can't show these figures contiguously, so we have an export with all the monthly weights, then with annual weights.

So say originally we were looking at C83 to O83 for our data for this year, we're now looking at C83 to N83 and O1364.

I've tried to look at how I would add this to the chart, which currently has the reference:

```<code>='Monthly Data to Update'!$C$83:$O$83
</code>```

But doing anything + or & doesn't seem to work.

So, I decided to just pull all my data in to contiguous set to reference, (so ='Monthly Data to Update'!C83 one cell, ='Monthly Data to Update'!C84 next cell and so on).

This caused a problem for future months that're empty, having 0's in them, so I updated my code to check:

```<code>=IF('Monthly Data to Update'!C83=0,NA(),'Monthly Data to Update'!C83)
</code>```

And this works, my table below my chart is blank for the empty months, my chart doesn't try and plot these empty months. Hurrah!

Now, the wrinkle. The Yearly nets aren't charted but are displayed in the table (I'm not up on Excel charts so how this was originally setup, I just copied the charts from Powerpoint in to Excel and reset the data to where it needed to be before copying it back to Powerpoint as a data linked chart).

First chart I did, works fine, second chart I did it's decided to start plotting the annual net for two of the three lines = \

So, this is how my chart looks like, running off the contiguous (but wrong) data:

And this is how it looks running off the fetched contiguous (correct) data:

It's really baffling, Exceeded and Met now plot the Year to Date figure, whereas Not Met behaves as it should, and they all have the same data layout (on the right) using the same formulas (just pointing at different cells).

I am confused..

I'm hoping to keep this light and simple so have avoided using any macro's to date, so that down the line when I hand this project over to someone any maintenance should be easy to do (say add a chart) without them asking me and me then having to remember what the hell I did a few months ago.. - so if this is doable without going down that line (which, seems like it should be, given my first chart the two lines there worked fine, and one of the three in this is behaving itself).

Apologies for the long winded description, I've given full history so if there's a step further back I could've done better, then happy to fix it up there rather than where I got to.

答:
Ah, so apparently I could've had non-contiguous data with a comma, not a plus or ampersand, so the chart data would be:

```<code>=('Monthly Data to Update'!$C$83:$N$83,'Monthly Data to Update'!$O$1404)
</code>```

So I don't need to rebuild the data in to a contiguous set, and my charts don't cock up when selecting the data this way, win's all around.

Thank you for your time, hopefully this helps someone in the future. (as a saving grace for my lost morning)

Body:
I have a weird problem that google's not being too kind on results (mostly basic things on how to create a line chart, or combination charts, neither of which I'm after).

I'm trying to automate a report we do each month, I've managed pretty well so far by having a linked excel chart and objects, I have a single sheet in excel I paste my formatted data (set format is consistent each month) then excel picks out the data, creates the charts and when opening powerpoint it reads it all in from there.

Great! Until I was given a new piece of information, there's monthly data and a yearly tally in my data, monthly data is shown with a particular "weighting" applied, year with a different one and it's this that's caused a problem.

The package that's exporting the data can't show these figures contiguously, so we have an export with all the monthly weights, then with annual weights.

So say originally we were looking at C83 to O83 for our data for this year, we're now looking at C83 to N83 and O1364.

I've tried to look at how I would add this to the chart, which currently has the reference:

='Monthly Data to Update'!$C$83:$O$83

But doing anything + or & doesn't seem to work.

So, I decided to just pull all my data in to contiguous set to reference, (so ='Monthly Data to Update'!C83 one cell, ='Monthly Data to Update'!C84 next cell and so on).

This caused a problem for future months that're empty, having 0's in them, so I updated my code to check:

=IF('Monthly Data to Update'!C83=0,NA(),'Monthly Data to Update'!C83)

And this works, my table below my chart is blank for the empty months, my chart doesn't try and plot these empty months. Hurrah!

Now, the wrinkle. The Yearly nets aren't charted but are displayed in the table (I'm not up on Excel charts so how this was originally setup, I just copied the charts from Powerpoint in to Excel and reset the data to where it needed to be before copying it back to Powerpoint as a data linked chart).

First chart I did, works fine, second chart I did it's decided to start plotting the annual net for two of the three lines = \

So, this is how my chart looks like, running off the contiguous (but wrong) data:

And this is how it looks running off the fetched contiguous (correct) data:

It's really baffling, Exceeded and Met now plot the Year to Date figure, whereas Not Met behaves as it should, and they all have the same data layout (on the right) using the same formulas (just pointing at different cells).

I am confused..

I'm hoping to keep this light and simple so have avoided using any macro's to date, so that down the line when I hand this project over to someone any maintenance should be easy to do (say add a chart) without them asking me and me then having to remember what the hell I did a few months ago.. - so if this is doable without going down that line (which, seems like it should be, given my first chart the two lines there worked fine, and one of the three in this is behaving itself).

Apologies for the long winded description, I've given full history so if there's a step further back I could've done better, then happy to fix it up there rather than where I got to.

Body:
Ah, so apparently I could've had non-contiguous data with a comma, not a plus or ampersand, so the chart data would be:

=('Monthly Data to Update'!$C$83:$N$83,'Monthly Data to Update'!$O$1404)

So I don't need to rebuild the data in to a contiguous set, and my charts don't cock up when selecting the data this way, win's all around.

Thank you for your time, hopefully this helps someone in the future. (as a saving grace for my lost morning)


问:
How to make vim paste from (and copy to) system's clipboard?
Unlike other editors, vim stores copied text in its own clipboard. So, it's very hard for me to copy some text from a webpage and paste it into the current working file. It so happens I have to either open gedit or type it manually.

Can I make vim paste from and to the system's clipboard?

答:
These key combinations work on any OS.

Select target Text using the mouse, and refer to the key sequences  to copy, cut, and paste.

copy: Ctrl + Insert

paste: Shift + Insert

cut: Shift + Del

paste: Shift + Insert