问:
How can I check if someone is replying to a message from someone specific
I am using Discord.js v13

My goal is in a message event, like this:

client.on('messageCreate', async message => {
   //Code comes here
})
```

to check if anyone, no matter who, is replying to any message from a specific person

答:
Using the reference field, you can get whether the message is a reply.
For example

client.on('messageCreate', async message => {
   if (message.reference.messageId) { // the message is a reply to another message
        let referenceMessage = message.channel.messages.cache.get(message.reference.messageId);
        if (referenceMessage.author.id == MY_USER_SNOWFLAKE) {
            // The reply was to the specific user!
        }
   }
})
```

Keep in mind that the reference message must be cached. If it isn't cached, you can use message.fetchReference().

Body:
I am using Discord.js v13

My goal is in a message event, like this:

client.on('messageCreate', async message => {
   //Code comes here
})

to check if anyone, no matter who, is replying to any message from a specific person

Body:
Using the reference field, you can get whether the message is a reply.
For example

client.on('messageCreate', async message => {
   if (message.reference.messageId) { // the message is a reply to another message
        let referenceMessage = message.channel.messages.cache.get(message.reference.messageId);
        if (referenceMessage.author.id == MY_USER_SNOWFLAKE) {
            // The reply was to the specific user!
        }
   }
})

Keep in mind that the reference message must be cached. If it isn't cached, you can use message.fetchReference().


来源: stackexchange

问:
Accidentally entered git stash pop instead of git stash--how to undo it?
I know there are similar questions but I am very much new to the whole 'git' scene. So I wanted to ask this question with my own contextual situation.

So I use git for work, where I use SmartGit to stage and commit files, gitbash to push/pull, and polygerrit to submit those commits into my work's repo.

My usual steps are:

open smartgit and select files in working tree to be staged

select all staged files and commit

enter description and click commit (I don't push from SmartGit because it's caused problems before)

go to PolyGerrit, +1 the commit myself, then submit

open gitbash and change directory

do "git push"

do "git stash"

do "git pull" then "git push"

do "git stash pop"

then, I'm usually all good to go.

I'm sure there's something unnecessary I'm doing, or an easier way, but after many a merge conflict and other issues, these exact steps have worked fine for a while now. But today I accidentally typed "git stash pop" before using "git stash". PolyGerrit doesn't show any mergeconflicts, but gitbash does? Is there any way at all to undo the "git stash pop"?

The files are either .png, .md, .ai, or .svg (if it helps at all?)

Any help is much appreciated. Thanks!

答:
First thing to do is to make a backup of the entire directory. Copy the whole lot to a thumb drive or at least another directory.

Step two is to find out what happened.

I would trust what git bash is telling you over over third party tools.

It could be that there is nothing to do. I created a scenario where popping the stash would create a merge conflict, as it sounds like you have.

One file checked in containing the String "aardvark".

A stash with the String "bat" in the file.

Working directory with the string "cat" in the file.

and this was the result of popping on the terminal:

```<code>$ git stash pop
error: Your local changes to the following files would be overwritten by merge:
    a.txt
Please commit your changes or stash them before you merge.
Aborting
The stash entry is kept in case you need it again.
</code>```

I checked the log and it looks like the stash is still there:

```<code>$ git log --oneline --graph --all
*   b4ae4c0 (refs/stash) WIP on master: 9e38acc File contains aardvark.
|\
| * c969465 index on master: 9e38acc File contains aardvark.
|/
* 9e38acc (HEAD -> master) File contains aardvark.
</code>```

I checked the diff between head and the stash and it looks as expected (hashes are copied from the above log output)

```<code>$ git diff 9e38acc b4ae4c0
diff --git a/a.txt b/a.txt
index c2625ca..1054901 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-aardvark
+bat
</code>```

Finally, checked the diff on the working directory and it is still as expected.

```<code>$ git diff
diff --git a/a.txt b/a.txt
index c2625ca..ef07ddc 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-aardvark
+cat
</code>```

You can use the above workflow to check what has gone on in your git repo. If it is like mine then there is nothing to do. Hopefully, that is the case.

Step three: If something has gone wrong, you will have more information to write a more specific question.

Step four: This is for the future. Practice good git hygiene. Commit often so that you never lose more than a couple of minutes work if something happens to your working directory. Push often so that you never lose more than half an hour of work if something happens to your computer.

ContentLicense: CC BY-SA 4.0

Body:
First thing to do is to make a backup of the entire directory. Copy the whole lot to a thumb drive or at least another directory.

Step two is to find out what happened.

I would trust what git bash is telling you over over third party tools.

It could be that there is nothing to do. I created a scenario where popping the stash would create a merge conflict, as it sounds like you have.

One file checked in containing the String "aardvark".

A stash with the String "bat" in the file.

Working directory with the string "cat" in the file.

and this was the result of popping on the terminal:

$ git stash pop
error: Your local changes to the following files would be overwritten by merge:
    a.txt
Please commit your changes or stash them before you merge.
Aborting
The stash entry is kept in case you need it again.

I checked the log and it looks like the stash is still there:

$ git log --oneline --graph --all
*   b4ae4c0 (refs/stash) WIP on master: 9e38acc File contains aardvark.
|\
| * c969465 index on master: 9e38acc File contains aardvark.
|/
* 9e38acc (HEAD -> master) File contains aardvark.

I checked the diff between head and the stash and it looks as expected (hashes are copied from the above log output)

$ git diff 9e38acc b4ae4c0
diff --git a/a.txt b/a.txt
index c2625ca..1054901 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-aardvark
+bat

Finally, checked the diff on the working directory and it is still as expected.

$ git diff
diff --git a/a.txt b/a.txt
index c2625ca..ef07ddc 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-aardvark
+cat

You can use the above workflow to check what has gone on in your git repo. If it is like mine then there is nothing to do. Hopefully, that is the case.

Step three: If something has gone wrong, you will have more information to write a more specific question.

Step four: This is for the future. Practice good git hygiene. Commit often so that you never lose more than a couple of minutes work if something happens to your working directory. Push often so that you never lose more than half an hour of work if something happens to your computer.


问:
VBA If with two conditions
I am trying to write a vba, which checks if column A is a specific string and column B is a specific string. If it's true, the cell in Column B should change its value to the string from column A. I think I am far away from the correct code.</p>
```<code>Sub NomenklaturDatum()

Dim cell As Range
Dim rng As Range

For Each cell In rng:

    if cell.Value in rng("J5:J175") = "2019" and cell.Value in rng("D5:D175") = ("Backlog") Then:

        cell.Value in rng("J5:J175") = "Backlog"

    End If

Next

End Sub
</code>```

答:
Something within these lines

```<code>Sub NomenklaturDatum()

    Dim cl As Range

    For Each cl In Range("J5:J175")
        If cl.Offset(0, -6).Value = "Backlog" And cl.Value = "2019" Then
            cl.Value = "Backlog"
        End If
    Next

End Sub
</code>```

Of course, you can make it more versatile - pass range as argument, or detect the last row, etc.

Title: VBA If with two conditions

Body:
I am trying to write a vba, which checks if column A is a specific string and column B is a specific string. If it's true, the cell in Column B should change its value to the string from column A. I think I am far away from the correct code.

Sub NomenklaturDatum()

Dim cell As Range
Dim rng As Range

For Each cell In rng:

    if cell.Value in rng("J5:J175") = "2019" and cell.Value in rng("D5:D175") = ("Backlog") Then:

        cell.Value in rng("J5:J175") = "Backlog"

    End If

Next

End Sub

Body:
Something within these lines

Sub NomenklaturDatum()

    Dim cl As Range

    For Each cl In Range("J5:J175")
        If cl.Offset(0, -6).Value = "Backlog" And cl.Value = "2019" Then
            cl.Value = "Backlog"
        End If
    Next

End Sub

Of course, you can make it more versatile - pass range as argument, or detect the last row, etc.


问:
Error while adding ssis code check extension - VS 2017
I am trying to install the SSIS code check Extension from VS 2017

I am Getting error as

```<code>Prerequisites  Missing    :

Identifier   : Microsoft.Net.Component.4.5.1.TargetingPack

Name         : .NET Framework 4.5.1 targeting pack
Version      : [16.0.28517.75,17.0)
</code>```

I have tried to install the 4.5.1 framework alone, still same error.

Please suggest if you have come across this error or any alternative extension that we can use for the same.

答:
Based on the official documentation:

A targeting pack lets your app target a specific version of .NET Framework when developing in Visual Studio and some other development environments. A developer pack includes a specific version of .NET Framework and its accompanying SDK along with its corresponding targeting pack.

To download the Microsoft .NET Framework developer pack, you can refer to the following page:

Download .NET Framework 4.5.1

Body:
I am trying to install the SSIS code check Extension from VS 2017

I am Getting error as

Prerequisites  Missing    :

Identifier   : Microsoft.Net.Component.4.5.1.TargetingPack

Name         : .NET Framework 4.5.1 targeting pack
Version      : [16.0.28517.75,17.0)

I have tried to install the 4.5.1 framework alone, still same error.

Please suggest if you have come across this error or any alternative extension that we can use for the same.


问:
How to give a border as a background in css without using image and without adding anything to mark-up?
For example here http://jsfiddle.net/jitendravyas/5Wqn4/1/

I want to take
 over red area. How to make is possible without using image and another added more element.

using border is not necessary I just want background like this.

答:
Without using any extra markup, there's a couple of things you could do.

Apply a negative top margin on the h1:

```<code>h1{margin-top:-150px;}
</code>```

http://jsfiddle.net/5Wqn4/2/

Position the h1 absolutely:

```<code>h1{
 position:absolute;
 top:50px;
 left: 50px;
}
</code>```

http://jsfiddle.net/5Wqn4/3/

Without your body border:

Without using the border you've added to the body you can simply style the h1 as you require:

```<code>body {background:yellow;margin:0;padding:0;}

h1{
    background-color:red;
    margin:0;
    height:150px;

}
</code>```

http://jsfiddle.net/5Wqn4/5/

UPDATE

Further to your comments below, here's a sample that probably matches more what you need:

http://jsfiddle.net/SbGDQ/

ContentLicense: CC BY-SA 3.0

Body:
Without using any extra markup, there's a couple of things you could do.

Apply a negative top margin on the h1:

h1{margin-top:-150px;}

http://jsfiddle.net/5Wqn4/2/

Position the h1 absolutely:

h1{
 position:absolute;
 top:50px;
 left: 50px;
}

http://jsfiddle.net/5Wqn4/3/

Without your body border:

Without using the border you've added to the body you can simply style the h1 as you require:

body {background:yellow;margin:0;padding:0;}

h1{
    background-color:red;
    margin:0;
    height:150px;

}

http://jsfiddle.net/5Wqn4/5/

UPDATE

Further to your comments below, here's a sample that probably matches more what you need:

http://jsfiddle.net/SbGDQ/


问:
Change color of inactive IconButton
I have following widgets implemented:

Which parameter of ThemeData I should change to change grey color of IconButton?

Widget code:

```<code>TextFormField(
                    controller: _loginPageViewModel.emailTEC,
                    validator: _loginPageViewModel.validator.validateEmail,
                    decoration: InputDecoration(
                      hintText: S.of(context).email,
                      suffixIcon: IconButton(
                        onPressed: _loginPageViewModel.emailTEC.clear,
                        icon: const Icon(Icons.clear),
                      ),
                    )
                )
</code>```

ThemeData code:

```<code>ThemeData(
      brightness: Brightness.light,
      //primaryColor: const Color(0xFFF8C537),
      scaffoldBackgroundColor: const Color(0xFFFFDDA1),
      appBarTheme: const AppBarTheme(
        color: Color(0xFFE53935),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
            primary: const Color(0xFFFFD151),
            onPrimary: Colors.black,
            elevation: 0.5
        ),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        hintStyle: TextStyle(color: Color(0xFFFFD151)),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFEDB230))
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFFFFD151)),
        ),
      ),
colorScheme: ThemeData().colorScheme.copyWith(primary: Color(0xFFEDB230)),
  );
</code>```

答:
Did you try this :

```<code>IconButton(
            icon: const Icon(Icons.android),
            color: condition ? Colors.white : Colors.grey,
            onPressed: () {},
          ),
</code>```

Also here is a property:
https://api.flutter.dev/flutter/material/ThemeData/disabledColor.html

```<code>IconButton(
                  icon: Icon(Icons.play_arrow),
                  color: Colors.green,
                  iconSize: 50,
                  splashRadius: 40,
                  disabledColor: Colors.grey,
                  onPressed: null,
                )
</code>```

Title: Change color of inactive IconButton

Body:
I have following widgets implemented:

Which parameter of ThemeData I should change to change grey color of IconButton?

Widget code:

TextFormField(
                    controller: _loginPageViewModel.emailTEC,
                    validator: _loginPageViewModel.validator.validateEmail,
                    decoration: InputDecoration(
                      hintText: S.of(context).email,
                      suffixIcon: IconButton(
                        onPressed: _loginPageViewModel.emailTEC.clear,
                        icon: const Icon(Icons.clear),
                      ),
                    )
                )

ThemeData code:

ThemeData(
      brightness: Brightness.light,
      //primaryColor: const Color(0xFFF8C537),
      scaffoldBackgroundColor: const Color(0xFFFFDDA1),
      appBarTheme: const AppBarTheme(
        color: Color(0xFFE53935),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
            primary: const Color(0xFFFFD151),
            onPrimary: Colors.black,
            elevation: 0.5
        ),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        hintStyle: TextStyle(color: Color(0xFFFFD151)),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFEDB230))
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFFFFD151)),
        ),
      ),
colorScheme: ThemeData().colorScheme.copyWith(primary: Color(0xFFEDB230)),
  );

Body:
Did you try this :

IconButton(
            icon: const Icon(Icons.android),
            color: condition ? Colors.white : Colors.grey,
            onPressed: () {},
          ),

Also here is a property:
https://api.flutter.dev/flutter/material/ThemeData/disabledColor.html

IconButton(
                  icon: Icon(Icons.play_arrow),
                  color: Colors.green,
                  iconSize: 50,
                  splashRadius: 40,
                  disabledColor: Colors.grey,
                  onPressed: null,
                )


问:
Clear WebRTC Data Channel queue
I have been trying to use WebRTC Data Channel for a game, however, I am unable to consistently send live player data without hitting the queue size limit (8KB) after 50-70 secs of playing.

Sine the data is required to be real-time, I have no use for data that comes out of order. I have initialized the data channel with the following attributes:

negotiated: true,
id: id,
ordered: true,
maxRetransmits: 0,
maxPacketLifetime: 66
```

The MDN Docs said that the buffer cannot be altered in any way.

Is there anyway I can consistently send data without exceeding the buffer space? I don't mind purging the buffer space as it only contains data that has been clogged up over time.

NOTE: The data is transmitting until the buffer size exceeds the 8KB space.

EDIT: I forgot to add that this issue is only occurring when the two sides are on different networks. When both are within the same LAN, there is no buffering (since higher bandwidth, I presume). I tried to add multiple Data Channels (8 in parallel). However, this only increased the time before the failure occurred again. All 8 buffers were full. I also tried creating a new channel each time the buffer was close to being full and switched to the new DC while closing the previous one that was full, but I found out the hard way (reading Note in MDN Docs) that the buffer space is not released immediately, rather tries to transmit all data in the buffer taking away precious bandwidth.

Thanks in advance.

答:
The maxRetransmits value is ignored if the maxPacketLifetime value is set; thus, you've configured your channel to resend packets for up to 66ms.  For your application, it is probably better to use a pure unreliable channel by setting maxPacketLifetime to 0.

As Sean said, there is no way to flush the queue.  What you can do is to drop packets before sending them if the channel is congested:

```<code>if(dc.bufferedAmount > 0)
     return;
dc.send(data);
</code>```

Finally, you should realise that buffering may happen in the network as well as at the sender: any router can buffer packets when it is congested, and many routers have very large buffers (this is called BufferBloat).  The WebRTC stack should prevent you from buffering too much data in the network, but if WebRTC's behaviour is not aggressive enough for your needs, you will need to add explicit feedback from the sender to the receiver in order to avoid having too many packets in flight.

Title: Clear WebRTC Data Channel queue

Body:
I have been trying to use WebRTC Data Channel for a game, however, I am unable to consistently send live player data without hitting the queue size limit (8KB) after 50-70 secs of playing.

Sine the data is required to be real-time, I have no use for data that comes out of order. I have initialized the data channel with the following attributes:

negotiated: true,
id: id,
ordered: true,
maxRetransmits: 0,
maxPacketLifetime: 66

The MDN Docs said that the buffer cannot be altered in any way.

Is there anyway I can consistently send data without exceeding the buffer space? I don't mind purging the buffer space as it only contains data that has been clogged up over time.

NOTE: The data is transmitting until the buffer size exceeds the 8KB space.

EDIT: I forgot to add that this issue is only occurring when the two sides are on different networks. When both are within the same LAN, there is no buffering (since higher bandwidth, I presume). I tried to add multiple Data Channels (8 in parallel). However, this only increased the time before the failure occurred again. All 8 buffers were full. I also tried creating a new channel each time the buffer was close to being full and switched to the new DC while closing the previous one that was full, but I found out the hard way (reading Note in MDN Docs) that the buffer space is not released immediately, rather tries to transmit all data in the buffer taking away precious bandwidth.

Thanks in advance.

Body:
The maxRetransmits value is ignored if the maxPacketLifetime value is set; thus, you've configured your channel to resend packets for up to 66ms.  For your application, it is probably better to use a pure unreliable channel by setting maxPacketLifetime to 0.

As Sean said, there is no way to flush the queue.  What you can do is to drop packets before sending them if the channel is congested:

if(dc.bufferedAmount > 0)
     return;
dc.send(data);

Finally, you should realise that buffering may happen in the network as well as at the sender: any router can buffer packets when it is congested, and many routers have very large buffers (this is called BufferBloat).  The WebRTC stack should prevent you from buffering too much data in the network, but if WebRTC's behaviour is not aggressive enough for your needs, you will need to add explicit feedback from the sender to the receiver in order to avoid having too many packets in flight.


问:
Python does not see pygraphviz
I have installed pygraphviz using easy_install
But when i launch python i have an error:

```<code>>>>import pygraphviz as pgv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygraphviz
>>>
</code>```

Using Ubuntu 12.04 and gnome-terminal.

答:
In Colab,

```<code>!apt  install  libgraphviz - dev
!pip install pygraphviz
</code>```

Credits: https://gist.github.com/korakot/a80c04a1945b06e2f4a053f92fecfbf9

Title: Python does not see pygraphviz

Body:
I have installed pygraphviz using easy_install
But when i launch python i have an error:

>>>import pygraphviz as pgv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygraphviz
>>>

Using Ubuntu 12.04 and gnome-terminal.

Body:
In Colab,

!apt  install  libgraphviz - dev
!pip install pygraphviz

Credits: https://gist.github.com/korakot/a80c04a1945b06e2f4a053f92fecfbf9


问:
TypeScript can not recognise return type correctly
I'm trying to define a conditional type for the return value and I've faced with weird TS behavior. However, the function return object has the same shape as defined in conditional types the TS error occurred.

My dummy (example) code:

```<code>interface Order1 {
  id: number;
  consumerId: number,
  articleId: number,
  lastDate: string
}

interface Order2 {
  id: number;
  consumerId: number,
  articleId: number,
  firtsDate: string
}

type Article = {
  name: number;
  status: number;
  articleTypeId: number;
  description: Array<string>;
  id: number,
}

interface NormalizedOrder1 extends Omit<Order1, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

interface NormalizedOrder2 extends Omit<Order2, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

type ReturnType<T> = T extends Order1
  ? NormalizedOrder1[]
  : T extends Order2
    ? NormalizedOrder2[]
    : never;

export default function useNormalizedOrders<T extends Order1 | Order2>(
  orders: T[],
  articles: Article[]
): ReturnType<T> {
  const consumers = [{id: 1, name: 'Consumer'}]

  return orders.map(
        ({ articleId, consumerId, ...rest }) => ({
          ...rest,
          consumerId,
          article: articles.find((article) => article.id === articleId),
          consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
        })
      )
}
</code>```

Error:

```<code>Type '(Omit<T, "articleId" | "consumerId"> & { consumerId: number; article: Article | undefined; consumerName: string | undefined; })[]' is not assignable to type 'ReturnType<T>'.(2322)
</code>```

Link to TS playground

TS version: 4.5.4

Maybe someone could explain to me what I'm doing wrong and how to reach expected behavior? Thank you!

答:
TypeScript does not support conditional types in a return type place. AFAIK, you have two options.

Overloading

interface Order1 {
  id: number;
  consumerId: number,
  articleId: number,
  lastDate: string
}

interface Order2 {
  id: number;
  consumerId: number,
  articleId: number,
  firtsDate: string
}

type Article = {
  name: number;
  status: number;
  articleTypeId: number;
  description: Array<string>;
  id: number,
}

interface NormalizedOrder1
  extends Omit<Order1, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

interface NormalizedOrder2
  extends Omit<Order2, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

type ReturnType<T> = T extends Order1
  ? NormalizedOrder1[]
  : T extends Order2
  ? NormalizedOrder2[]
  : never;

export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]): ReturnType<T>
export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]) {
  const consumers = [{ id: 1, name: 'Consumer' }]

  return orders.map(
    ({ articleId, consumerId, ...rest }) => ({
      ...rest,
      consumerId,
      article: articles.find((article) => article.id === articleId),
      consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
    })
  )
}
```
<p>Playground</p>
<ol start="2">
<li>Type assertion</li>
</ol>
<pre class="lang-js prettyprint-override"><code>export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]) {
  const consumers = [{ id: 1, name: 'Consumer' }]

  return orders.map(
    ({ articleId, consumerId, ...rest }) => ({
      ...rest,
      consumerId,
      article: articles.find((article) => article.id === articleId),
      consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
    })
  ) as any as ReturnType<T> // type assertion
}
</code>```

Body:
I'm trying to define a conditional type for the return value and I've faced with weird TS behavior. However, the function return object has the same shape as defined in conditional types the TS error occurred.

My dummy (example) code:

interface Order1 {
  id: number;
  consumerId: number,
  articleId: number,
  lastDate: string
}

interface Order2 {
  id: number;
  consumerId: number,
  articleId: number,
  firtsDate: string
}

type Article = {
  name: number;
  status: number;
  articleTypeId: number;
  description: Array<string>;
  id: number,
}

interface NormalizedOrder1 extends Omit<Order1, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

interface NormalizedOrder2 extends Omit<Order2, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

type ReturnType<T> = T extends Order1
  ? NormalizedOrder1[]
  : T extends Order2
    ? NormalizedOrder2[]
    : never;

export default function useNormalizedOrders<T extends Order1 | Order2>(
  orders: T[],
  articles: Article[]
): ReturnType<T> {
  const consumers = [{id: 1, name: 'Consumer'}]

  return orders.map(
        ({ articleId, consumerId, ...rest }) => ({
          ...rest,
          consumerId,
          article: articles.find((article) => article.id === articleId),
          consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
        })
      )
}

Error:

Type '(Omit<T, "articleId" | "consumerId"> & { consumerId: number; article: Article | undefined; consumerName: string | undefined; })[]' is not assignable to type 'ReturnType<T>'.(2322)

<a href="https://www.typescriptlang.org/play?ssl=8&ssc=1&pln=9&pc=1#code/JYOwLgpgTgZghgYwgAgPJQCbQIzIN4BQyywGAXMiAK4C2ARtANxHIID2IAzrdAJLmVaDKABoWcKGGAIANhH4Vq9aGOIy4nMABE4kCpqigA5gQC+BAqEixEKdFigAmfC1KKhTFuy48oCwcqi4pLScv5KwqrIMMCSnDp6yAbGZhZgAJ4ADigAgiGyKAC8LsQgcDQQ7oHMxJq6VJxVwjXIElIFACpZ8gIRnsRYnAiGmVIcFHlQcOkAPMkgRgB8LW4BkamW4NDwSMgAcmxQNHAywABeEBj2OCwQAB6QIBicaDTAYDPXUNgiyADkbVCPT+ixKrXycgmEJQAB9kFQnhAYiBLi1vNwKlA9uVKkkwIYFsg4QisMjLmJzJtrDsUAcjidzpcvo5bg8IE8Xqg3h9mb8AdD+CCwYCClD2nIifDEWSMGiOBjoNiKvp8cZJSSkaByRsMtlkAAlCBgKhQEBdbIzDqg4odZD3R7PNCYG7EAD8+0Ox1OFyuzu+AG0ALosCi2+3sx3Mljuulexm+hyOIMhygQABungI90yhzAyFJcCoMjzMARCDGIHhnAgsYZPq+nBmLDDbI5TocuDhUcWAApDg5GsgOkHfiK5IO8uKIEGAJQUQ3G03miCW0GEYjovPo3wvYr+vCrH6UHEUP4AYXlvj+pmDLCgRpNlf70E4ADpjpkeyxiD-kD28OCU78L826YsByCvpB96aMgpgzsghSgv+36-j+kGvtBYBRKhP6gXwGDYThgFAhQY4QG+yIYD2PZkfBiHEQUr6kAhhTFGR-AzoROF4ViJ6sJemKcK6r6UdRAHMXBCGgsxrHFDxHHCWUFRcT+cEocQM5mEAA" rel="nofollow noreferrer">Link to TS playground

TS version: 4.5.4

Maybe someone could explain to me what I'm doing wrong and how to reach expected behavior? Thank you!

Body:
TypeScript does not support conditional types in a return type place. AFAIK, you have two options.

Overloading

interface Order1 {
  id: number;
  consumerId: number,
  articleId: number,
  lastDate: string
}

interface Order2 {
  id: number;
  consumerId: number,
  articleId: number,
  firtsDate: string
}

type Article = {
  name: number;
  status: number;
  articleTypeId: number;
  description: Array<string>;
  id: number,
}

interface NormalizedOrder1
  extends Omit<Order1, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

interface NormalizedOrder2
  extends Omit<Order2, 'articleId'> {
  article: Article | undefined;
  consumerName: string | undefined,
}

type ReturnType<T> = T extends Order1
  ? NormalizedOrder1[]
  : T extends Order2
  ? NormalizedOrder2[]
  : never;

export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]): ReturnType<T>
export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]) {
  const consumers = [{ id: 1, name: 'Consumer' }]

  return orders.map(
    ({ articleId, consumerId, ...rest }) => ({
      ...rest,
      consumerId,
      article: articles.find((article) => article.id === articleId),
      consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
    })
  )
}

Playground

Type assertion

export default function useNormalizedOrders<
  T extends Order1 | Order2
>(orders: T[], articles: Article[]) {
  const consumers = [{ id: 1, name: 'Consumer' }]

  return orders.map(
    ({ articleId, consumerId, ...rest }) => ({
      ...rest,
      consumerId,
      article: articles.find((article) => article.id === articleId),
      consumerName: consumers?.find(({ id }) => id === consumerId)?.name,
    })
  ) as any as ReturnType<T> // type assertion
}


问:
Can get script compiled with CSharpScript (Roslyn)
I'm trying to get a script compiled with Roslyn but whatever I do it keeps complaining about this, at this moment I tried almost everything and have no idea what to try next.

This is the error I get :

'(11,7): error CS0246: The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)'

It is complaining that the namespace can't be found

I already added the references to the file and even added the assemblies to the InteractiveAssemblyLoader but still no luck.

```<code>        try
        {
#if (DEBUG)
            var metadataReferences = ApplicationSettings.Instance.GetValuesAsStringList("Script editor", "MetadataReferences_VOP");
#else
            var metadataReferences = ApplicationSettings.Instance.GetValuesAsStringList("Script editor", "MetadataReferences");
#endif

            var scriptOptions = ScriptOptions.Default.WithEmitDebugInformation(true);
            scriptOptions.AddReferences(metadataReferences);

            using var assemblyLoader = new InteractiveAssemblyLoader();

            foreach(var reference in metadataReferences)
                assemblyLoader.RegisterDependency(Assembly.Load(File.ReadAllBytes(reference)));

            scriptRunner = CSharpScript
                .Create<string>(script, scriptOptions, typeof(MainGlobals), assemblyLoader)
                .ContinueWith("new NewEmail().Main(Email)")
                .CreateDelegate();

            exception = null;
            return true;
        }
        catch (Exception e)
        {
            exception = e;
            scriptRunner = null;
            return false;
        }

</code>```

Is there somebody that has an idea about what to try next?

答:
It seems that the AddReferences returns a new scriptOptions object that is the one with the added references :-)

So the solution was easy, just do this

scriptOptions = scriptOptions.AddReferences(metadataReferences);

Body:
I'm trying to get a script compiled with Roslyn but whatever I do it keeps complaining about this, at this moment I tried almost everything and have no idea what to try next.

This is the error I get :

'(11,7): error CS0246: The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)'

It is complaining that the namespace can't be found

I already added the references to the file and even added the assemblies to the InteractiveAssemblyLoader but still no luck.

        try
        {
#if (DEBUG)
            var metadataReferences = ApplicationSettings.Instance.GetValuesAsStringList("Script editor", "MetadataReferences_VOP");
#else
            var metadataReferences = ApplicationSettings.Instance.GetValuesAsStringList("Script editor", "MetadataReferences");
#endif

            var scriptOptions = ScriptOptions.Default.WithEmitDebugInformation(true);
            scriptOptions.AddReferences(metadataReferences);

            using var assemblyLoader = new InteractiveAssemblyLoader();

            foreach(var reference in metadataReferences)
                assemblyLoader.RegisterDependency(Assembly.Load(File.ReadAllBytes(reference)));

            scriptRunner = CSharpScript
                .Create<string>(script, scriptOptions, typeof(MainGlobals), assemblyLoader)
                .ContinueWith("new NewEmail().Main(Email)")
                .CreateDelegate();

            exception = null;
            return true;
        }
        catch (Exception e)
        {
            exception = e;
            scriptRunner = null;
            return false;
        }

Is there somebody that has an idea about what to try next?


问:
Button text only visible when hovered over with mouse
The text on the button (Remove in this case) is only visible when hovered over with mouse. It's an angular project and it won't get overridden even if I try to give css for .btn as

```<code>background-color: blue;
</code>```

Button's text not visible
Button's text visible only when hovered over with mouse

This is my html code for the button :

```<code><button (click)="remove(item)" class="btn btn-primary btn-sm mt-2" style="color: white;">Remove</button>
</code>```

This is the css for buttons in style.css :

```<code> .btn-info{
    color:#fff;
    background-color:#0da8e4!important;
    border-color:#0da8e4!important
}

a.primary-btn{
    background:#05143f;
    padding:7px 20px;
    text-align:center;
    display:inline-block;
    color:#fff;
    border-radius:2px;
    font-size:14px;
    margin-top:5px
}
a.primary-btn:hover{
    background:#0da8e4;
    color:#fff
}

.active-link {
  font-weight: bold;
}
</code>```

答:
I had a similar issue when the button was inside a table. Bootstrap classes for the table were interfering with the button bootstrap classes.

Please put the button inside

 or

```<code><table class="table table-hover" style="cursor:pointer">
  <thead>
    <tr>
      <th style="width: 20%;"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <button (click)="remove(item)" class="btn btn-primary">Remove</button>
      </td>
    </tr>
  </tbody>
</table>
</code>```

Body:
The text on the button (Remove in this case) is only visible when hovered over with mouse. It's an angular project and it won't get overridden even if I try to give css for .btn as

background-color: blue;

Button's text not visible
Button's text visible only when hovered over with mouse

This is my html code for the button :

<button (click)="remove(item)" class="btn btn-primary btn-sm mt-2" style="color: white;">Remove</button>

This is the css for buttons in style.css :

 .btn-info{
    color:#fff;
    background-color:#0da8e4!important;
    border-color:#0da8e4!important
}

a.primary-btn{
    background:#05143f;
    padding:7px 20px;
    text-align:center;
    display:inline-block;
    color:#fff;
    border-radius:2px;
    font-size:14px;
    margin-top:5px
}
a.primary-btn:hover{
    background:#0da8e4;
    color:#fff
}

.active-link {
  font-weight: bold;
}

Body:
I had a similar issue when the button was inside a table. Bootstrap classes for the table were interfering with the button bootstrap classes.

Please put the button inside <thead></thead> or <tbody></tbody>

<table class="table table-hover" style="cursor:pointer">
  <thead>
    <tr>
      <th style="width: 20%;"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <button (click)="remove(item)" class="btn btn-primary">Remove</button>
      </td>
    </tr>
  </tbody>
</table>


问:
How to skip browser default print preview and print content directly to printer in jquery/javascript?
As, we know in C# windows form application we can print content directly to print without any preview. I want to print content in jQuery/JavaScript when user click a button, browser does not show any print preview and content printed to printer.

I am also having the same issue.

答:
It is actually possible by following plugins, and then call java script while printing.

1- QZ Tray ( https://qz.io )

2- JS Print Manager ( https://www.neodynamic.com/articles/Print-HTML-from-Javascript-to-client-printer-without-print-dialog-silently/ )


答:
Digressing: see Raymond Chen's How many ways are there to sort GUIDs?

Summarized as:

Algorithm
Byte array
String

memcmp
00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
{33221100-5544-7766-8899-AABBCCDDEEFF}

System.Guid / string
33 22 11 00 55 44 77 66 88 99 AA BB CC DD EE FF
{00112233-4455-6677-8899-AABBCCDDEEFF}

SqlGuid
CC DD EE FF AA BB 88 99 66 77 00 11 22 33 44 55
{FFEEDDCC-BBAA-9988-6677-001122334455}

Platform::Guid
33 22 11 00 77 66 55 44 BB AA 99 88 FF EE DD CC
{00112233-6677-4455-BBAA-9988FFEEDDCC}

And Java treats each GUID as a pair of signed 64-bit integers in big-endian format, see Another way to sort GUIDs: Java.
In two columns (bits 0 and 64) the sort order is 89ABCDEF01234567. In the other columns, the sort order is 0123456789ABCDEF.

Title: How to sort sequential GUIDs in C#?

Body:
Sequential GUIDs are unique but are created with an order; that order is slightly unusual and is different to the order achieved when using the standard .NET Guid comparer.

I'm looking for a C# Guid comparer that will sort by the rules of sequential GUIDs.

== UPDATE==

I'm specifically referring to sequential GUIDs created by NewSequentialId() in SQL Server, although I realise now that the standard Win32 API call UuidCreateSequential() uses a different scheme to SQL Server (I assumed they were the same when I wrote the question).

== UPDATE 2==

petelids gives the answer below, using e.g. List<System.Data.SqlGuid>.Sort() gives the following sequence (using an initial list of GUIDs with a 1 in each 4 bit location)...

01000000-0000-0000-0000-000000000000
10000000-0000-0000-0000-000000000000
00010000-0000-0000-0000-000000000000
00100000-0000-0000-0000-000000000000
00000100-0000-0000-0000-000000000000
00001000-0000-0000-0000-000000000000
00000001-0000-0000-0000-000000000000
00000010-0000-0000-0000-000000000000
00000000-0100-0000-0000-000000000000
00000000-1000-0000-0000-000000000000
00000000-0001-0000-0000-000000000000
00000000-0010-0000-0000-000000000000
00000000-0000-0100-0000-000000000000
00000000-0000-1000-0000-000000000000
00000000-0000-0001-0000-000000000000
00000000-0000-0010-0000-000000000000
00000000-0000-0000-0001-000000000000
00000000-0000-0000-0010-000000000000
00000000-0000-0000-0100-000000000000
00000000-0000-0000-1000-000000000000
00000000-0000-0000-0000-000000000001
00000000-0000-0000-0000-000000000010
00000000-0000-0000-0000-000000000100
00000000-0000-0000-0000-000000001000
00000000-0000-0000-0000-000000010000
00000000-0000-0000-0000-000000100000
00000000-0000-0000-0000-000001000000
00000000-0000-0000-0000-000010000000
00000000-0000-0000-0000-000100000000
00000000-0000-0000-0000-001000000000
00000000-0000-0000-0000-010000000000
00000000-0000-0000-0000-100000000000

As opposed to the following order returned by List<System.Guid>.Sort()

00000000-0000-0000-0000-000000000001
00000000-0000-0000-0000-000000000010
00000000-0000-0000-0000-000000000100
00000000-0000-0000-0000-000000001000
00000000-0000-0000-0000-000000010000
00000000-0000-0000-0000-000000100000
00000000-0000-0000-0000-000001000000
00000000-0000-0000-0000-000010000000
00000000-0000-0000-0000-000100000000
00000000-0000-0000-0000-001000000000
00000000-0000-0000-0000-010000000000
00000000-0000-0000-0000-100000000000
00000000-0000-0000-0001-000000000000
00000000-0000-0000-0010-000000000000
00000000-0000-0000-0100-000000000000
00000000-0000-0000-1000-000000000000
00000000-0000-0001-0000-000000000000
00000000-0000-0010-0000-000000000000
00000000-0000-0100-0000-000000000000
00000000-0000-1000-0000-000000000000
00000000-0001-0000-0000-000000000000
00000000-0010-0000-0000-000000000000
00000000-0100-0000-0000-000000000000
00000000-1000-0000-0000-000000000000
00000001-0000-0000-0000-000000000000
00000010-0000-0000-0000-000000000000
00000100-0000-0000-0000-000000000000
00001000-0000-0000-0000-000000000000
00010000-0000-0000-0000-000000000000
00100000-0000-0000-0000-000000000000
01000000-0000-0000-0000-000000000000
10000000-0000-0000-0000-000000000000


问:
Inbuilt method for element wise comparison of 2 struct arrays in Go?
I have a struct with the below structure,

```<code>//Number A struct that represents a new number to be addeded
type Number struct {
    Country   string `json:"country"`
    Number    string `json:"number"`
    CreatedAt string `json:"created_at"`
}
</code>```

and I a getting a response array of this struct from the REST call and I need to do an element-wise comparison. Is there any inbuilt method to do the same or more efficient way to do it instead of using a for loop and iterating through the elements?

答:
Is there any inbuilt method to do the same or more efficient way to do it instead of using a for loop and iterating through the elements?

Values of type Number can be compared with == directly.

Body:
I have a struct with the below structure,

//Number A struct that represents a new number to be addeded
type Number struct {
    Country   string `json:"country"`
    Number    string `json:"number"`
    CreatedAt string `json:"created_at"`
}

and I a getting a response array of this struct from the REST call and I need to do an element-wise comparison. Is there any inbuilt method to do the same or more efficient way to do it instead of using a for loop and iterating through the elements?


问:
Spring Boot controller - Upload Multipart and JSON to DTO
I want to upload a file inside a form to a Spring Boot API endpoint.

The UI is written in React:

```<code>export function createExpense(formData) {
  return dispatch => {
    axios.post(ENDPOINT,
      formData,
      headers: {
        'Authorization': //...,
        'Content-Type': 'application/json'
      }
      ).then(({data}) => {
        //...
      })
      .catch(({response}) => {
        //...
      });
    };
}

  _onSubmit = values => {
    let formData = new FormData();
    formData.append('title', values.title);
    formData.append('description', values.description);
    formData.append('amount', values.amount);
    formData.append('image', values.image[0]);
    this.props.createExpense(formData);
  }
</code>```

This is the java side code:

```<code>@RequestMapping(path = "/{groupId}", method = RequestMethod.POST)
public ExpenseSnippetGetDto create(@RequestBody ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
   //..
}
</code>```

But I get this exception on the Java side:

```<code>org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryapHVvBsdZYc6j4Af;charset=UTF-8' not supported
</code>```

How should I resolve this issue? The similar API endpoints and JavaScript side code is already working.

Note

I've seen a solution where it suggests that the request body should have 2 attributes: one which the JSON section goes under, another for the image. I'd like to see if it is possible to have it automatically converted to DTO.

Update 1

The upload payload sent by the client should be converted to the following DTO:

```<code>public class ExpensePostDto extends ExpenseBaseDto {

    private MultipartFile image;

    private String description;

    private List<Long> sharers;

}
</code>```

So you can say it's a mix of JSON and multipart.

Solution

The solution to the problem is to use FormData on the front-end and ModelAttribute on the backend:

```<code>@RequestMapping(path = "/{groupId}", method = RequestMethod.POST,
        consumes = {"multipart/form-data"})
public ExpenseSnippetGetDto create(@ModelAttribute ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal) throws IOException {
   //...
}
</code>```

and on the front-end, get rid of Content-Type as it should be determined by the browser itself, and use FormData (standard JavaScript). That should solve the problem.

答:
In my case the problem was the DTO class having public fields and not getter/setter methods

```<code>public class MyDTO {
    public MultipartFile[] files;
    public String user;
    public String text;
}
</code>```

The DTO class MUST have getters/setters, otherwise it won't work.

Body:
I want to upload a file inside a form to a Spring Boot API endpoint.

The UI is written in React:

export function createExpense(formData) {
  return dispatch => {
    axios.post(ENDPOINT,
      formData,
      headers: {
        'Authorization': //...,
        'Content-Type': 'application/json'
      }
      ).then(({data}) => {
        //...
      })
      .catch(({response}) => {
        //...
      });
    };
}

  _onSubmit = values => {
    let formData = new FormData();
    formData.append('title', values.title);
    formData.append('description', values.description);
    formData.append('amount', values.amount);
    formData.append('image', values.image[0]);
    this.props.createExpense(formData);
  }

This is the java side code:

@RequestMapping(path = "/{groupId}", method = RequestMethod.POST)
public ExpenseSnippetGetDto create(@RequestBody ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
   //..
}

But I get this exception on the Java side:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryapHVvBsdZYc6j4Af;charset=UTF-8' not supported

How should I resolve this issue? The similar API endpoints and JavaScript side code is already working.

Note

I've seen a solution where it suggests that the request body should have 2 attributes: one which the JSON section goes under, another for the image. I'd like to see if it is possible to have it automatically converted to DTO.

Update 1

The upload payload sent by the client should be converted to the following DTO:

public class ExpensePostDto extends ExpenseBaseDto {

    private MultipartFile image;

    private String description;

    private List<Long> sharers;

}

So you can say it's a mix of JSON and multipart.

Solution

The solution to the problem is to use FormData on the front-end and ModelAttribute on the backend:

@RequestMapping(path = "/{groupId}", method = RequestMethod.POST,
        consumes = {"multipart/form-data"})
public ExpenseSnippetGetDto create(@ModelAttribute ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal) throws IOException {
   //...
}

and on the front-end, get rid of Content-Type as it should be determined by the browser itself, and use FormData (standard JavaScript). That should solve the problem.

Body:
In my case the problem was the DTO class having public fields and not getter/setter methods

public class MyDTO {
    public MultipartFile[] files;
    public String user;
    public String text;
}

The DTO class MUST have getters/setters, otherwise it won't work.


问:
Pentaho Kettle : How to use the same database connection in both Job and transformation
I have a job and multiple transformations. If i wanted to define a database connection in the Job , and use the same database connection for all the transformations , how do I go about it ? I am using a community edition Pentaho 5.0 version .

I am creating the jobs locally using spoon and moving them to a Linux server where I will be using kitchen.sh to execute the job and transformations .

Thanks.

答:
If you are not connected to a Pentaho Server Repository (you are working locally), open the transformation where yoy have already configured the connection, now in the "View" tab, "Database connections" element, select the connection and rigthclick to open contextual menu then select "Share", now the connection is available in all other open locally transformations and you can reuse it.

PDI Version 9.2


问:
How to update Dart on VS Code?
enter image description hereenter image description hereToday VS Code sent me an error:

Version 2.16.1 of the Dart SDK is available (you have 2.16.0). Some features of Dart Code may not work correctly with an old SDK.

Do I have to download it again as ZIP and add it to PATH for the update?

答:
For linux try this,

```<code>flutter channel stable
flutter upgrade
</code>```

or this

```<code>flutter channel master
flutter upgrade
</code>```

Title: How to update Dart on VS Code?

Body:
For linux try this,

flutter channel stable
flutter upgrade

or this

flutter channel master
flutter upgrade


问:
Thymeleaf add value in style
I have a div block that has styles. I need to add another style with a substitution value. I imagined it like this:

th:styleappend="background-position:-${value}%"

But it doesn't work. Is there a possibility to do this?

答:
Most probably you are having a syntax issue here. Try the following code:</p>
```<code>th:styleappend="'background-position:-' + @{${value}} + '%'"
</code>```

Title: Thymeleaf add value in style

Body:
Most probably you are having a syntax issue here. Try the following code:

th:styleappend="'background-position:-' + @{${value}} + '%'"


问:
Requested bean is currently in creation: Is there an unresolvable circular reference?
i am using spring 3, and i have two beans of view scope:

1- Bean1:

```<code>@Component("bean1")
@Scope("view")
public class Bean1 {

@Autowired
private Bean2 bean2;

}
</code>```

2- Bean2:

```<code>@Component("bean2")
@Scope("view")
public class Bean2 {

@Autowired
private Bean1 bean1;

}
</code>```

the view is a custom scope:

```<code><bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="view">
                    <bean class="${project.groupId}.utils.ViewScope" />
                </entry>
            </map>
        </property>
    </bean>
</code>```

and here's the code for the custom view scope:

```<code>public class ViewScope implements Scope {

    @SuppressWarnings("rawtypes")
    public Object get(String name, ObjectFactory objectFactory) {
        Map<String, Object> viewMap = FacesContext.getCurrentInstance()
                .getViewRoot().getViewMap();

        if (viewMap.containsKey(name)) {
            return viewMap.get(name);
        } else {
            Object object = objectFactory.getObject();
            viewMap.put(name, object);

            return object;
        }
    }

    public Object remove(String name) {
        return FacesContext.getCurrentInstance().getViewRoot().getViewMap()
                .remove(name);
    }

    public String getConversationId() {
        return null;
    }

    public void registerDestructionCallback(String name, Runnable callback) {
        // Not supported
    }

    public Object resolveContextualObject(String key) {
        return null;
    }
}
</code>```

when opening the page that uses both beans, i get the exception:

```<code>org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'agencyBean': Requested bean is currently in creation: Is there an unresolvable circular reference?
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:252)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
    at com.myapp.utils.ViewScope.get(ViewScope.java:20)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
    at com.xeno.xecamp.webManagement.utils.ViewScope.get(ViewScope.java:20)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
    at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:56)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
    at org.apache.el.parser.AstValue.getTarget(AstValue.java:94)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:244)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:128)
    at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2508)
    at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
    at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2139)
    at com.sun.faces.application.ApplicationImpl.invokeComponentListenersFor(ApplicationImpl.java:2087)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:286)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:244)
    at org.springframework.faces.webflow.Jsf2FlowApplication.publishEvent(Jsf2FlowApplication.java:94)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:99)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:60)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:57)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:110)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
</code>```

please advise how to fix this exception.

EDIT: i tried to use the setter injection as referenced in the answer here

Understanding Spring context initialization order

but it doesn's work too.

1- Bean1:

```<code>@Component("bean1")
@Scope("view")
public class Bean1 {

private Bean2 bean2;

@Autowired
public void setBean2 (Bean2 bean2) {
    this.bean2= bean2;
}

}
</code>```

2- Bean2:

```<code>@Component("bean2")
@Scope("view")
public class Bean2 {

private Bean1 bean1;

@Autowired
public void setBean1 (Bean1 bean1) {
    this.bean1= bean1;
}

}
</code>```

but it gives me the exception:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.myapp.beans.Bean1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
</code>```

答:
My solution was to move the bean definition to another class of configuration</p>
```<code>@Configuration
public class EncoderConfig {
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
</code>```

Body:
i am using spring 3, and i have two beans of view scope:

1- Bean1:

@Component("bean1")
@Scope("view")
public class Bean1 {

@Autowired
private Bean2 bean2;

}

2- Bean2:

@Component("bean2")
@Scope("view")
public class Bean2 {

@Autowired
private Bean1 bean1;

}

the view is a custom scope:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="view">
                    <bean class="${project.groupId}.utils.ViewScope" />
                </entry>
            </map>
        </property>
    </bean>

and here's the code for the custom view scope:

public class ViewScope implements Scope {

    @SuppressWarnings("rawtypes")
    public Object get(String name, ObjectFactory objectFactory) {
        Map<String, Object> viewMap = FacesContext.getCurrentInstance()
                .getViewRoot().getViewMap();

        if (viewMap.containsKey(name)) {
            return viewMap.get(name);
        } else {
            Object object = objectFactory.getObject();
            viewMap.put(name, object);

            return object;
        }
    }

    public Object remove(String name) {
        return FacesContext.getCurrentInstance().getViewRoot().getViewMap()
                .remove(name);
    }

    public String getConversationId() {
        return null;
    }

    public void registerDestructionCallback(String name, Runnable callback) {
        // Not supported
    }

    public Object resolveContextualObject(String key) {
        return null;
    }
}

when opening the page that uses both beans, i get the exception:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'agencyBean': Requested bean is currently in creation: Is there an unresolvable circular reference?
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:252)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
    at com.myapp.utils.ViewScope.get(ViewScope.java:20)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
    at com.xeno.xecamp.webManagement.utils.ViewScope.get(ViewScope.java:20)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
    at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:56)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
    at org.apache.el.parser.AstValue.getTarget(AstValue.java:94)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:244)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:128)
    at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2508)
    at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
    at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2139)
    at com.sun.faces.application.ApplicationImpl.invokeComponentListenersFor(ApplicationImpl.java:2087)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:286)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:244)
    at org.springframework.faces.webflow.Jsf2FlowApplication.publishEvent(Jsf2FlowApplication.java:94)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:99)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:60)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:57)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:110)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

please advise how to fix this exception.

EDIT: i tried to use the setter injection as referenced in the answer here

Understanding Spring context initialization order

but it doesn's work too.

1- Bean1:

@Component("bean1")
@Scope("view")
public class Bean1 {

private Bean2 bean2;

@Autowired
public void setBean2 (Bean2 bean2) {
    this.bean2= bean2;
}

}

2- Bean2:

@Component("bean2")
@Scope("view")
public class Bean2 {

private Bean1 bean1;

@Autowired
public void setBean1 (Bean1 bean1) {
    this.bean1= bean1;
}

}

but it gives me the exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.myapp.beans.Bean1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

Body:
My solution was to move the bean definition to another class of configuration

@Configuration
public class EncoderConfig {
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}


问:
Converting Degrees Angle to Rotation Matrix C#
Basically I need to take the rotation of an object (X, Y and Z rotation) and convert it to a rotation matrix in C#. Basically what https://www.andre-gaschler.com/rotationconverter/ does except I'm not using three.js.

I've got the degrees value to a radian value, and have also converted that value to quaternion, but now I am stuck on how to get this into a rotation matrix form.

Any ideas?

答:
```<code>rotation3 r = rotation3.fromXyz(12, 45, 60);  //(in degree)
var m = r.getMatrix();
</code>```


问:
Grafana oauth with Gitlab
Environment:

Grafana version: 8.2.1
Deployed on GKE using the kube-promethues-stack

What happened:
I have one gke cluster where gitlab is running and exposed with two ingress: 1 with internal IP and 1 with external IP.

In a second cluster I have a grafana deployment that I would like to "connect" to gitlab in order to use gitlab as authentication provider.
Since the internal url of gitlab is not reachable from grafana, I use the external one, but something doesn't seem to work:
in the logs I see that a requests goes from grafana to the internal IP, and I can't understand why.
This is the grafana config:

```<code>    auth.gitlab:
      enabled: true
      allow_sign_up: true
      scopes: read_api
      auth_url: https://external-url/oauth/authorize
      token_url: https://external-url/oauth/token
      api_url: https://external-url/api/v4
</code>```

and these are the logs from grafana:

```<code>t=2021-12-01T12:36:30+0000 lvl=dbug msg="OAuthLogin Got token" logger=oauth token="&{AccessToken:redacted TokenType:Bearer RefreshToken:redacted Expiry:0001-01-01 00:00:00 +0000 UTC raw:map[access_token:redacted created_at:1.637755993e+09 refresh_token:redacted scope:read_api token_type:Bearer]}"
t=2021-12-01T12:36:30+0000 lvl=dbug msg="HTTP GET https://external-url/api/v4/user: 200 OK {redacted information}
t=2021-12-01T12:36:30+0000 lvl=dbug msg="HTTP GET https://external-ip/api/v4/groups: 200 OK {redacted information}
t=2021-12-03T07:20:42+0000 lvl=eror msg=login.OAuthLogin(NewTransportWithCode) logger=context userId=0 orgId=0 uname= error="oauth2: cannot fetch token: 400 Bad Request\nResponse: {\"error\":\"invalid_grant\",\"error_description\":\"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.\"}"
t=2021-12-03T07:20:42+0000 lvl=eror msg="Request Completed" logger=context userId=0 orgId=0 uname= method=GET path=/login/gitlab status=500 remote_addr=10.175.1.36 time_ms=58 size=1365 referer=https://EXTERNAL/

t=2021-12-01T12:38:42+0000 lvl=eror msg="Error getting groups from GitLab API" logger=oauth.gitlab err="Get \"https://INTERNAL-URL/api/v4/groups?order_by=name&owned=false&page=2&per_page=20&sort=asc&statistics=false&with_custom_attributes=false\": dial tcp internal-ip:443: connect: connection timed out"
t=2021-12-01T12:38:42+0000 lvl=dbug msg="OAuthLogin got user info" logger=oauth userInfo="&{redacted information}
</code>```

Can anyone help me with this?
Thanks in advance

答:
Was the gitlab's oauth client secret got changed after the upgrade/any activity?

I use Keycloak's oauth, where the client id and client secret can be changed and if it is changed, I have to update the client secret value at Grafana's ENV GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET or config oauth_client_secret

This is the cause for my login.OAuthLogin(NewTransportWithCode) error.

Try and let me know.

Title: Grafana oauth with Gitlab

Body:
Environment:

Grafana version: 8.2.1
Deployed on GKE using the kube-promethues-stack

What happened:
I have one gke cluster where gitlab is running and exposed with two ingress: 1 with internal IP and 1 with external IP.

In a second cluster I have a grafana deployment that I would like to "connect" to gitlab in order to use gitlab as authentication provider.
Since the internal url of gitlab is not reachable from grafana, I use the external one, but something doesn't seem to work:
in the logs I see that a requests goes from grafana to the internal IP, and I can't understand why.
This is the grafana config:

    auth.gitlab:
      enabled: true
      allow_sign_up: true
      scopes: read_api
      auth_url: https://external-url/oauth/authorize
      token_url: https://external-url/oauth/token
      api_url: https://external-url/api/v4

and these are the logs from grafana:

t=2021-12-01T12:36:30+0000 lvl=dbug msg="OAuthLogin Got token" logger=oauth token="&{AccessToken:redacted TokenType:Bearer RefreshToken:redacted Expiry:0001-01-01 00:00:00 +0000 UTC raw:map[access_token:redacted created_at:1.637755993e+09 refresh_token:redacted scope:read_api token_type:Bearer]}"
t=2021-12-01T12:36:30+0000 lvl=dbug msg="HTTP GET https://external-url/api/v4/user: 200 OK {redacted information}
t=2021-12-01T12:36:30+0000 lvl=dbug msg="HTTP GET https://external-ip/api/v4/groups: 200 OK {redacted information}
t=2021-12-03T07:20:42+0000 lvl=eror msg=login.OAuthLogin(NewTransportWithCode) logger=context userId=0 orgId=0 uname= error="oauth2: cannot fetch token: 400 Bad Request\nResponse: {\"error\":\"invalid_grant\",\"error_description\":\"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.\"}"
t=2021-12-03T07:20:42+0000 lvl=eror msg="Request Completed" logger=context userId=0 orgId=0 uname= method=GET path=/login/gitlab status=500 remote_addr=10.175.1.36 time_ms=58 size=1365 referer=https://EXTERNAL/

t=2021-12-01T12:38:42+0000 lvl=eror msg="Error getting groups from GitLab API" logger=oauth.gitlab err="Get \"https://INTERNAL-URL/api/v4/groups?order_by=name&owned=false&page=2&per_page=20&sort=asc&statistics=false&with_custom_attributes=false\": dial tcp internal-ip:443: connect: connection timed out"
t=2021-12-01T12:38:42+0000 lvl=dbug msg="OAuthLogin got user info" logger=oauth userInfo="&{redacted information}

Can anyone help me with this?
Thanks in advance


答:
You can use this CSS rule:</p>

```<code>h1 {
 border-top: 20px solid red;
 display: block;
}
</code>```

Title: How to give a border as a background in css without using image and without adding anything to mark-up?

Body:
For example here http://jsfiddle.net/jitendravyas/5Wqn4/1/

I want to take
 over red area. How to make is possible without using image and another added more element.

using border is not necessary I just want background like this.

Body:
You can use this CSS rule:

h1 {
 border-top: 20px solid red;
 display: block;
}