问:
handle go back in initialRoute for deeplinking in react native nested stack
i'm trying to implement deep link in react native project now what i want is when a user opens app via deeplink it will be redirected to the specific page and then once he presses back he should go to HomeScreen now this perfectly works fine  when i open CommentsScreen or PodcastDetailScreen via deep link but when i open up BlogLikesUserListScreen or ManageConnectionsScreen it oepns though when i click on harware back button it exits the app how should i write the config for linking so that when i open BlogLikesUserListScreen via deeplink and press back button it should go to HomeScreen ?
i tried various combinations but i failed</p>
```<code>const App = () => {
return(
<NavigationContainer linking={linking}>
  <Stack.Navigator
    initialRouteName="SplashScreen"
    screenOptions={{headerShown: false}}>
    <Stack.Screen name="AppScreens" component={AppScreens} />

    <Stack.Screen name="ModalScreens" component={ModalScreens} />
  </Stack.Navigator>
</NavigationContainer>;
)

function AppScreens({navigation}) {
  return (
    <TabBar.Navigator initialRouteName={'NetworkTabBar'}>
      <TabBar.Screen name="NetworkTabBar" component={NetworkNavigator} />
    </TabBar.Navigator>
  );
}

function NetworkNavigator() {
  return (
    <NetworkBar.Navigator>
      <NetworkBar.Screen name="HomeScreens" component={HomeScreens} />
      <NetworkBar.Screen name="PodcastScreens" component={PodcastScreens} />
    </NetworkBar.Navigator>
  );
}

function HomeScreens({navigation}) {
  return (
    <Stack.Navigator initialRouteName="HomeScreen">
      <Stack.Screen name="HomeScreen" component={HomeScreen} />
      <Stack.Screen name="CommentsScreen" component={CommentsScreen} />
    </Stack.Navigator>
  );
}
function ModalScreens() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="BlogLikesUserListScreen"
        component={BlogLikesUserListScreen}
      />
    </Stack.Navigator>
  );
}

// configuration for deep_link

const config = {
  screens: {
    AppScreens: {
      screens: {
        NetworkTabBar: {
          screens: {
            HomeScreens: {
              initialRouteName: 'HomeScreen',
              screens: {
                CommentsScreen: 'social/blog/details/:blogId/',
              },
            },
            PodcastScreens: {
              initialRouteName: 'PodcastListScreen',
              screens: {
                PodcastDetailScreen: 'podcast/:podcastId/',
              },
            },
          },
        },
      },
    },
    ModalScreens: {
      initialRouteName: 'HomeScreen',
      screens: {
        ManageConnectionsScreen: {
          initialRouteName: 'FindConnectionsScreen',
          screens: {
            ManageConnectionsScreen: 'social/connected/:type/',
          },
        },
        BlogLikesUserListScreen: {
          initialRouteName: 'HomeScreen',
          screens: {
            BlogLikesUserListScreen: 'social/blog/likes/:blog_id',
          },
        },
      },
    },
  },
};
}
</code>```

Body:
i'm trying to implement deep link in react native project now what i want is when a user opens app via deeplink it will be redirected to the specific page and then once he presses back he should go to HomeScreen now this perfectly works fine  when i open CommentsScreen or PodcastDetailScreen via deep link but when i open up BlogLikesUserListScreen or ManageConnectionsScreen it oepns though when i click on harware back button it exits the app how should i write the config for linking so that when i open BlogLikesUserListScreen via deeplink and press back button it should go to HomeScreen ?
i tried various combinations but i failed

const App = () => {
return(
<NavigationContainer linking={linking}>
  <Stack.Navigator
    initialRouteName="SplashScreen"
    screenOptions={{headerShown: false}}>
    <Stack.Screen name="AppScreens" component={AppScreens} />

    <Stack.Screen name="ModalScreens" component={ModalScreens} />
  </Stack.Navigator>
</NavigationContainer>;
)

function AppScreens({navigation}) {
  return (
    <TabBar.Navigator initialRouteName={'NetworkTabBar'}>
      <TabBar.Screen name="NetworkTabBar" component={NetworkNavigator} />
    </TabBar.Navigator>
  );
}

function NetworkNavigator() {
  return (
    <NetworkBar.Navigator>
      <NetworkBar.Screen name="HomeScreens" component={HomeScreens} />
      <NetworkBar.Screen name="PodcastScreens" component={PodcastScreens} />
    </NetworkBar.Navigator>
  );
}

function HomeScreens({navigation}) {
  return (
    <Stack.Navigator initialRouteName="HomeScreen">
      <Stack.Screen name="HomeScreen" component={HomeScreen} />
      <Stack.Screen name="CommentsScreen" component={CommentsScreen} />
    </Stack.Navigator>
  );
}
function ModalScreens() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="BlogLikesUserListScreen"
        component={BlogLikesUserListScreen}
      />
    </Stack.Navigator>
  );
}

// configuration for deep_link

const config = {
  screens: {
    AppScreens: {
      screens: {
        NetworkTabBar: {
          screens: {
            HomeScreens: {
              initialRouteName: 'HomeScreen',
              screens: {
                CommentsScreen: 'social/blog/details/:blogId/',
              },
            },
            PodcastScreens: {
              initialRouteName: 'PodcastListScreen',
              screens: {
                PodcastDetailScreen: 'podcast/:podcastId/',
              },
            },
          },
        },
      },
    },
    ModalScreens: {
      initialRouteName: 'HomeScreen',
      screens: {
        ManageConnectionsScreen: {
          initialRouteName: 'FindConnectionsScreen',
          screens: {
            ManageConnectionsScreen: 'social/connected/:type/',
          },
        },
        BlogLikesUserListScreen: {
          initialRouteName: 'HomeScreen',
          screens: {
            BlogLikesUserListScreen: 'social/blog/likes/:blog_id',
          },
        },
      },
    },
  },
};
}


来源: stackexchange

问:
SAP Connector using Oracle JDBC and virtual host name "oracle" gives: Failed to obtain JDBC Connection: DataSource returned null from getConnection():
Using a working JDBC connect string for a connect to a remote Oracle database using Oracle JDBC like

jdbc:oracle:thin:@myremotehost:1521:mysid

and mapping it inside SAP Connector with nomenclature

jdbc:oracle:thin:@<virtual host name>:<virtual Port>:mysid

with

<virtual host name> = oracle

<virtual Port>= 61521

resulting in

jdbc:oracle:thin:@oracle:61521:mysid

will end up with error

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: DataSource returned null from getConnection(): org.ops4j.pax.jdbc.impl.DriverDataSource@45d186af

To check if the issue is related to a problem in the Oracle JDBC Driver we

Installed SAP JDK 8 on the remote database machine

Using Maven to create a standalone Spring-Boot/Spring-JDBC/HikariCP/Oracle JDBC JAR reflecting the stack of SAP Connector / SAP VM using with iFlows

Tested the JAR with connect string

jdbc:oracle:thin:@myremotehost:1521:mysid

succesfully

add on remote database machine to file /etc/hosts an entry like

oracle   XXX.XXX.XXX.XXX

where XXX.XXX.XXX.XXX is the IP of machine "myremotehost"

Tested the recreated JAR with new connect string

jdbc:oracle:thin:@oracle:1521:mysid

succesfully

Replacing "oracle" as virtual host name by "myoracle" like

jdbc:oracle:thin:@myoracle:61521:mysid

fixed the issue with SAP Connector

According to our finding we think the error is caused inside SAP Connector using Java String.replace() function replacing inside connect string

jdbc:oracle:thin:@oracle:61521:mysid

Any occurance of "oracle" (virtual host name) by the remote host name "myremotehost"

Any occurance of "61521"  (virtual port number) by the remote host port "1521"

ending up with a connect string like

jdbc:myremotehost:thin:@myremotehost:1521:mysid

which is invalid because the first occurance of "oracle" in original connect string is required to resolve classes giving the seen error because no connection could be established.

For Developers of the SAP Connector at SAP: Valid workaround in the Java code of SAP Connenctor would be using regexp or restrict replacement for substring right of at-Sign "@" in connect string so that class resolving is still possible ;-)

kind regards
Frank Scherie

Expectation:

SAP fixes the issue and creates a bug/note for the issue

ContentLicense: CC BY-SA 4.0


问:
OpenMP depend clause - rule on structure elements
I'm struggling to understand the rules in the 5.2 specifications regarding what is allowed in an OpenMP depend clause with respect to types in Fortran.

The basic code I'm testing is this clause (as a proxy for a larger example):

!$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)

e12c%e12f%e12t is a type containing a type containing an array.

Page 62 of the spec says:

Unless otherwise specified, a variable that is part of another variable (as an array element or a
structure element) cannot be a variable list item, an extended list item or locator list item.

I know that array elements are allowed as members of a depend clause (and the code works with both gfortran12 and ifort if its only e12c%e12t without the extra type in between), and I think I'd assumed structure members were as well (and at least for non-nested structure members this works).

If I try this code with gfortran 12 then it fails to compile, however with intel 2023.0.0 it compiles ok. Is it valid OpenMP code or do I need to find another way (is there another way?) to express such dependencies?
Notably the C equivalent (depend(out: e12c.e12f.e12t[j:j+32])) compiles ok with gcc12, so is this just gfortran lagging behind again?

Adressing the comment, the gfortran compiler just says a syntax error:

```<code>gfortran -fopenmp test.f90
test.f90:26:82:

   26 |   !$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)
      |                                                                                1
Error: Syntax error in OpenMP variable list at (1)
</code>```

For Ian's comment, to be explicit as to what everything is, here is the full Fortran file that fails with gcc:

```<code>module ax
    implicit none
type array_container
    real, dimension(500, 500) ::e12t
end type

type array_container2
    type(array_container) :: e12f
end type

end module ax

Program test
use ax
type(array_container2) :: e12c
integer, dimension(500,500):: dum
integer :: i, ii, j, jj, jj_end

e12c%e12f%e12t(:,:) = 1.0

!$omp parallel default(shared) private(j, jj_end)
!$omp single
DO j = 1, 500, 32
  jj_end =  MIN(j_out_var + (32 - 1), 500)

  !$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)
  Do jj = j, jj_end, 1
    Do i = 1, 500, 1
      e12c%e12f%e12t(i,j) = 1.0
    End Do
  End Do
  !$omp end task
End Do
!$omp end single
!$omp end parallel

End Program
</code>```

Body:
I'm struggling to understand the rules in the 5.2 specifications regarding what is allowed in an OpenMP depend clause with respect to types in Fortran.

The basic code I'm testing is this clause (as a proxy for a larger example):

!$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)

e12c%e12f%e12t is a type containing a type containing an array.

Page 62 of the spec says:

Unless otherwise specified, a variable that is part of another variable (as an array element or a
structure element) cannot be a variable list item, an extended list item or locator list item.

I know that array elements are allowed as members of a depend clause (and the code works with both gfortran12 and ifort if its only e12c%e12t without the extra type in between), and I think I'd assumed structure members were as well (and at least for non-nested structure members this works).

If I try this code with gfortran 12 then it fails to compile, however with intel 2023.0.0 it compiles ok. Is it valid OpenMP code or do I need to find another way (is there another way?) to express such dependencies?
Notably the C equivalent (depend(out: e12c.e12f.e12t[j:j+32])) compiles ok with gcc12, so is this just gfortran lagging behind again?

Adressing the comment, the gfortran compiler just says a syntax error:

gfortran -fopenmp test.f90
test.f90:26:82:

   26 |   !$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)
      |                                                                                1
Error: Syntax error in OpenMP variable list at (1)

For Ian's comment, to be explicit as to what everything is, here is the full Fortran file that fails with gcc:

module ax
    implicit none
type array_container
    real, dimension(500, 500) ::e12t
end type

type array_container2
    type(array_container) :: e12f
end type

end module ax

Program test
use ax
type(array_container2) :: e12c
integer, dimension(500,500):: dum
integer :: i, ii, j, jj, jj_end

e12c%e12f%e12t(:,:) = 1.0

!$omp parallel default(shared) private(j, jj_end)
!$omp single
DO j = 1, 500, 32
  jj_end =  MIN(j_out_var + (32 - 1), 500)

  !$omp task private(jj, i) firstprivate(j, jj_end) shared(e12c) depend(out: e12c%e12f%e12t)
  Do jj = j, jj_end, 1
    Do i = 1, 500, 1
      e12c%e12f%e12t(i,j) = 1.0
    End Do
  End Do
  !$omp end task
End Do
!$omp end single
!$omp end parallel

End Program


问:
Traffic between kubernetes API server and ETCD
We have a self managed kubernetes cluster deployed in AWS EC2 instances. For HA, we are running in 3 AZs - 3 API server nodes and 3 ETCD nodes (one node in each AZ). In API server, we have specified all 3 ETCD server's endpoints

--etcd-servers=https://0.etcd.com:2379,https://1.etcd.com:2379,https://2.etcd.com:2379
```

Currently the API server is sending request to any of the ETCD node randomly and we are getting charged with high cross AZ data transfer bill by AWS.

So, would like to know if we have some way to intelligently select ETCD node from API server - if the API server from AZ-1 wants to communicate, it selects ETCD from the same AZ (AZ-1) if available otherwise go cross AZ.

Amount of traffic - We analysed VPC flow logs and on a single day we see around 16T per day flowing from port 2379. This is the major contributor, trying if we can reduce this.

I searched on the internet if people have solved this couldn't find any. Also found ETCD client has only 2 values for EndpointSelectionMode one is Random which is the default behaviour and another one is PriotrizeLeader: https://pkg.go.dev/go.etcd.io/etcd/client#EndpointSelectionMode
So ETCD client is also not providing this flexibility

Body:
We have a self managed kubernetes cluster deployed in AWS EC2 instances. For HA, we are running in 3 AZs - 3 API server nodes and 3 ETCD nodes (one node in each AZ). In API server, we have specified all 3 ETCD server's endpoints

--etcd-servers=https://0.etcd.com:2379,https://1.etcd.com:2379,https://2.etcd.com:2379

Currently the API server is sending request to any of the ETCD node randomly and we are getting charged with high cross AZ data transfer bill by AWS.

So, would like to know if we have some way to intelligently select ETCD node from API server - if the API server from AZ-1 wants to communicate, it selects ETCD from the same AZ (AZ-1) if available otherwise go cross AZ.

Amount of traffic - We analysed VPC flow logs and on a single day we see around 16T per day flowing from port 2379. This is the major contributor, trying if we can reduce this.

I searched on the internet if people have solved this couldn't find any. Also found ETCD client has only 2 values for EndpointSelectionMode one is Random which is the default behaviour and another one is PriotrizeLeader: https://pkg.go.dev/go.etcd.io/etcd/client#EndpointSelectionMode
So ETCD client is also not providing this flexibility


问:
setting counter values in PIT hardware

A PC typically has a special chip called a programmable interval timer
(PIT). The input clock frequency of the PIT chip runs (roughly) at
1.193182 MHz, which is 1/12 the frequency of a
14.31818 MHz oscillator.

Each PIT channel is associated with a hardware counter (divider). Let
us use Counter0 to refer to the counter associated with channel 0.
Every pulse from the PIT input clock causes Counter0 to be decreased.
When Counter0 has reached zero, it is reset and a pulse is generated
on the output. The hardware timer frequency can be changed by setting
Counter0 to a desired value. For instance, if Counter0 is set to
11,931,then the PIT channel 0 output  frequency is 100 Hz, and timer
interrupt occurs every 10 ms.

My question is how we can calculate counter0 value?

In this example how author calculated frequency as 100 Hz and timer interrupt occurs every 10 msec by setting counter value to 11931.

Request your help in understanding.

Title: setting counter values in PIT hardware


问:
Handle Hash Collison in Stripe Read Write lock
We are using stripe lock for one of our implementation. We take readlock on some final constant and a writelock on key. We noticed that we ran into a deadlock because hash code of two different keys turned out to be same. And hence it is like upgrading a read lock to write lock and we ran into deadlock. Below is the code used by Stripe library to generate a hashcode. What is the best way to handle this deadlock?

Stripe code:

```<code>static int smear(int hashCode)
{
    hashCode ^= hashCode >>> 20 ^ hashCode >>> 12;
    return hashCode ^ hashCode >>> 7 ^ hashCode >>> 4;
}

static final int indexFor(Object key)
{
    int hash = smear(key.hashCode());
    int mask = ceilToPowerOfTwo(2003) -1;
    return hash & mask;
}

static int ceilToPowerOfTwo(int x)
{
    return 1 << IntMath.log2(x, RoundingMode.CEILING);
}

public static void main(String[] args) {
    String publicKey = "$public";
    int hash = indexFor(publicKey );

    for(int i=0;i<1000;i++) {
        String key = "key"+i;
        if(indexFor(key) == hash) {
            System.out.println("Hash of "+key + " is same as hash of public");
        }
    }
}
</code>```

Our Logic:

```<code>Take readLock on publicKey
Take writeLock on key
release the write lock
release the read lock
</code>```

Body:
We are using stripe lock for one of our implementation. We take readlock on some final constant and a writelock on key. We noticed that we ran into a deadlock because hash code of two different keys turned out to be same. And hence it is like upgrading a read lock to write lock and we ran into deadlock. Below is the code used by Stripe library to generate a hashcode. What is the best way to handle this deadlock?

Stripe code:

static int smear(int hashCode)
{
    hashCode ^= hashCode >>> 20 ^ hashCode >>> 12;
    return hashCode ^ hashCode >>> 7 ^ hashCode >>> 4;
}

static final int indexFor(Object key)
{
    int hash = smear(key.hashCode());
    int mask = ceilToPowerOfTwo(2003) -1;
    return hash & mask;
}

static int ceilToPowerOfTwo(int x)
{
    return 1 << IntMath.log2(x, RoundingMode.CEILING);
}

public static void main(String[] args) {
    String publicKey = "$public";
    int hash = indexFor(publicKey );

    for(int i=0;i<1000;i++) {
        String key = "key"+i;
        if(indexFor(key) == hash) {
            System.out.println("Hash of "+key + " is same as hash of public");
        }
    }
}

Our Logic:

Take readLock on publicKey
Take writeLock on key
release the write lock
release the read lock


问:
boost_system renaming and symlink issues on ldd
I have sample application that uses boost_system shared object. Now, because of certain scenarios, I have to support 2 different boost_system shared objects - one built with gcc and other with sun's cc in single directory - /home/mydir. Corresponding files are:-

```<code>libboost_system_v1.so --dependency for--- applicationv1.so
libboost_system_v2.so --dependency for--- applicationv2.so
</code>```

It is linked in the makefile as.

```<code>... $(BOOST_LIB_V1) -lboost_system_v1
</code>```

Hence I renamed libboost_system_1_41_0.so to libboost_system_v1.so and also removed the softlink from $BOOST_HOME_V1/stage/lib. Now, when I try to build application - I do not get any errors. However ldd fails with:-

```<code>ldd /home/mydir/applicationv1.so
    libboost_system.so.1.41.0 => not found
    .....................................
    .....................................
    .....................................
</code>```

BOOST_HOME_v1/stage/lib(=BOOST_LIB_v1) looks like:-

```<code>libboost_system_v1.so
libboost_system_v1.a
</code>```

I am unable to understand - why does ldD still show libboost_system.so.1.41.0 as dependency instead of libboost_system_v1.so.

I was expecting to see below o/p which is not what is obtained:-

```<code>ldd /home/mydir/applicationv1.so
     libboost_system_v1.so -> /home/mydir/libboost_system_v1.so
</code>```

Can someone please explain if there is a solution to actually rename shared object and not deal with boost's default symlink? I checked src/build.jam - looks like linkage is done here - but I thought as long as I remove the softlink, rename the shared object and link with renamed shared object in makefile - there shouldn't be any issues.

ContentLicense: CC BY-SA 3.0

Body:
I have sample application that uses boost_system shared object. Now, because of certain scenarios, I have to support 2 different boost_system shared objects - one built with gcc and other with sun's cc in single directory - /home/mydir. Corresponding files are:-

libboost_system_v1.so --dependency for--- applicationv1.so
libboost_system_v2.so --dependency for--- applicationv2.so

It is linked in the makefile as.

... $(BOOST_LIB_V1) -lboost_system_v1

Hence I renamed libboost_system_1_41_0.so to libboost_system_v1.so and also removed the softlink from $BOOST_HOME_V1/stage/lib. Now, when I try to build application - I do not get any errors. However ldd fails with:-

ldd /home/mydir/applicationv1.so
    libboost_system.so.1.41.0 => not found
    .....................................
    .....................................
    .....................................

BOOST_HOME_v1/stage/lib(=BOOST_LIB_v1) looks like:-

libboost_system_v1.so
libboost_system_v1.a

I am unable to understand - why does ldD still show libboost_system.so.1.41.0 as dependency instead of libboost_system_v1.so.

I was expecting to see below o/p which is not what is obtained:-

ldd /home/mydir/applicationv1.so
     libboost_system_v1.so -> /home/mydir/libboost_system_v1.so

Can someone please explain if there is a solution to actually rename shared object and not deal with boost's default symlink? I checked src/build.jam - looks like linkage is done here - but I thought as long as I remove the softlink, rename the shared object and link with renamed shared object in makefile - there shouldn't be any issues.


问:
PHP - dynamiclly set array params to extended class
In my PHP project, I'm implementing PHP through OOP.
I have class A which defines hardcoded path string and an array of params.
Class B extends class A and in __construct() method, I define that path and also define two parameters that I want to pass.

In my prepare() method I don't know how to dynamically set those two params so I can get them when calling $this->classB->getParams() method.

```<code>abstract class A
{
    public function __construct(
        private string $path,
        private array $params
    ) {
    }

    public function getPath(): string
    {
        return $this->path;
    }

    public function getParams(): array
    {
        return $this->params;
    }

   public function setParams(?array $params)
   {
        $this->params = $params;
   }
</code>```

.

```<code>class B extends A
{
    private ?string $name;

    private ?string $address;

    public function __construct(?string $name = null, ?string $address = null )
    {
        $this->name = $name;
        $this->address = $address;
        parent::__construct(
            'path/to/some/file',
            [
                'name' => $name,
                'address' => $address
            ]
        );
    }

public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(?string $name)
    {
        $this->name = $name;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(?string $address)
    {
        $this->address = $address;

        return $this;
    }
}
</code>```

..

```<code>class C
{
   public function __construct(B $classB) {
       $this->classB = $classB;
    }

public function prepare()
{
    $arrayParams =  ["John Doe", "Forgotten Lane 007"];

    $this->classB->setParams(arrayParams);

    $path   = $this->classB->getPath();
    $params = $this->classB->getParams();

     $c = new B('', ''); //?

    $this->execute($path, $params);
}
</code>```

Result is:

```<code>array(2) {
  [0]=>
  string(8) "John Doe"
  [1]=>
  string(18) "Forgotten Lane 007"
}
</code>```

and I want:

```<code>array(2) {
  ["name]=>
  string(8) "John Doe"
  ["address"]=>
  string(18) "Forgotten Lane 007"
}
</code>```

As I defined it in B class.

The example posted here: https://3v4l.org/msoSh

I am new to PHP so help with this will be appreciated. Thanks

Body:
In my PHP project, I'm implementing PHP through OOP.
I have class A which defines hardcoded path string and an array of params.
Class B extends class A and in __construct() method, I define that path and also define two parameters that I want to pass.

In my prepare() method I don't know how to dynamically set those two params so I can get them when calling $this->classB->getParams() method.

abstract class A
{
    public function __construct(
        private string $path,
        private array $params
    ) {
    }

    public function getPath(): string
    {
        return $this->path;
    }

    public function getParams(): array
    {
        return $this->params;
    }

   public function setParams(?array $params)
   {
        $this->params = $params;
   }

.

class B extends A
{
    private ?string $name;

    private ?string $address;

    public function __construct(?string $name = null, ?string $address = null )
    {
        $this->name = $name;
        $this->address = $address;
        parent::__construct(
            'path/to/some/file',
            [
                'name' => $name,
                'address' => $address
            ]
        );
    }

public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(?string $name)
    {
        $this->name = $name;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(?string $address)
    {
        $this->address = $address;

        return $this;
    }
}

..

class C
{
   public function __construct(B $classB) {
       $this->classB = $classB;
    }

public function prepare()
{
    $arrayParams =  ["John Doe", "Forgotten Lane 007"];

    $this->classB->setParams(arrayParams);

    $path   = $this->classB->getPath();
    $params = $this->classB->getParams();

     $c = new B('', ''); //?

    $this->execute($path, $params);
}

Result is:

array(2) {
  [0]=>
  string(8) "John Doe"
  [1]=>
  string(18) "Forgotten Lane 007"
}

and I want:

array(2) {
  ["name]=>
  string(8) "John Doe"
  ["address"]=>
  string(18) "Forgotten Lane 007"
}

As I defined it in B class.

The example posted here: https://3v4l.org/msoSh

I am new to PHP so help with this will be appreciated. Thanks


问:
Why is the following block not thread safe?
We have a Spring Boot application where we fetch data from a database and keep it in a concurrent Hashmap tempMap. Then we use it to fetch details based on the incoming keys. But keys are in the form of arrays. Now, once loaded we don't refresh the map until the scheduler hits. But we can see empty optional being returned but the map was never refreshed. The method is being accessed by many threads in the application. Seems some kind of memory leak is there. Please, anyone can help to point what might be the issue.

This is the function body accessed by many threads that throws No value present exception:

```<code>if (sender.length == 1) {
    return getSingle(sender[0]).get();
} else {
    return getMultiple(sender).get();
}
</code>```

These are the implementations for functions:

```<code>private Optional<DummyClassEntity> getSingle(String value) {
    Optional<DummyClassEntity> dummyClass;
    dummyClass = Optional.of(tempMap.get(value));
    return dummyClass;
}

private Optional<DummyClassEntity> getMultiple(String[] values) {
    return Arrays.stream(values)
        .filter(value -> tempMap.containsKey(value))
        .findFirst()
        .map(s -> tempMap.get(s));
}
</code>```

I tried using synchronized block. But that still impacts the performance. And this part is being used for an high performance application.

Body:
We have a Spring Boot application where we fetch data from a database and keep it in a concurrent Hashmap tempMap. Then we use it to fetch details based on the incoming keys. But keys are in the form of arrays. Now, once loaded we don't refresh the map until the scheduler hits. But we can see empty optional being returned but the map was never refreshed. The method is being accessed by many threads in the application. Seems some kind of memory leak is there. Please, anyone can help to point what might be the issue.

This is the function body accessed by many threads that throws No value present exception:

if (sender.length == 1) {
    return getSingle(sender[0]).get();
} else {
    return getMultiple(sender).get();
}

These are the implementations for functions:

private Optional<DummyClassEntity> getSingle(String value) {
    Optional<DummyClassEntity> dummyClass;
    dummyClass = Optional.of(tempMap.get(value));
    return dummyClass;
}

private Optional<DummyClassEntity> getMultiple(String[] values) {
    return Arrays.stream(values)
        .filter(value -> tempMap.containsKey(value))
        .findFirst()
        .map(s -> tempMap.get(s));
}

I tried using synchronized block. But that still impacts the performance. And this part is being used for an high performance application.


问:
Mongo / Mongoose - Can I throw an error from a schema method or is it bad practice?
I wonder if its bad practise to throw an error inside a schema method or whether I should do it from my controller?</p>
```<code>userSchema.methods.comparePassword = function (candidatePassword) {
    const user = this;
    return new Promise((resolve, reject) => {
        bcrypt.compare(candidatePassword, user.password, (err, isMatch) => {
            if (err) {
                return reject(err);
            }
            if (!isMatch) {
                throw new Error(...)
            //or
                return reject(false);
            }
            resolve(true);
        });
    })
};
</code>```

Body:
I wonder if its bad practise to throw an error inside a schema method or whether I should do it from my controller?

userSchema.methods.comparePassword = function (candidatePassword) {
    const user = this;
    return new Promise((resolve, reject) => {
        bcrypt.compare(candidatePassword, user.password, (err, isMatch) => {
            if (err) {
                return reject(err);
            }
            if (!isMatch) {
                throw new Error(...)
            //or
                return reject(false);
            }
            resolve(true);
        });
    })
};


问:
Get part of yaml file with terraform
I have a yaml file as given below

```<code> apiVersion: helm.toolkit.gitops.io/v2beta1
 kind: HelmRelease
 metadata:
   name: "test"
   namespace: "test-system"
 spec:
   chart:
     spec:
       chart: "test-environment"
       version: "0.1.10"
   values:
     key1: "value1"
     key2: "value2"
     key3: "value3"
     key4: "value4"
     gitRepository:
       url: https://github.com/test-eng/test.git
       helmRepositories:
        - name: testplatform
          url: https://test-platform/charts
</code>```

How I can read only part of it using terraform. Read all the contents below ".spec.values".

```<code>      key1: "value1"
      key2: "value2"
      key3: "value3"
      key4: "value4"
      gitRepository:
        url: https://github.com/test-eng/test.git
      helmRepositories:
       - name: testplatform
         url: https://test-platform/charts
</code>```

I tried with yamldecode function as given below

```<code>flux_config       = yamldecode((data.github_repository_file.my_file.content)[".spec.values"])
</code>```

but it failed with below error

```<code>  This value does not have any indices.
</code>```

Title: Get part of yaml file with terraform

Body:
I have a yaml file as given below

 apiVersion: helm.toolkit.gitops.io/v2beta1
 kind: HelmRelease
 metadata:
   name: "test"
   namespace: "test-system"
 spec:
   chart:
     spec:
       chart: "test-environment"
       version: "0.1.10"
   values:
     key1: "value1"
     key2: "value2"
     key3: "value3"
     key4: "value4"
     gitRepository:
       url: https://github.com/test-eng/test.git
       helmRepositories:
        - name: testplatform
          url: https://test-platform/charts

How I can read only part of it using terraform. Read all the contents below ".spec.values".

      key1: "value1"
      key2: "value2"
      key3: "value3"
      key4: "value4"
      gitRepository:
        url: https://github.com/test-eng/test.git
      helmRepositories:
       - name: testplatform
         url: https://test-platform/charts

I tried with yamldecode function as given below

flux_config       = yamldecode((data.github_repository_file.my_file.content)[".spec.values"])

but it failed with below error

  This value does not have any indices.


问:
What is the difference between using --save-exact and a package-lock.json file during npm install?
In the docs for Prettier (a code formatter), they install it with the --save-exact flag (1):

```<code>npm install --save-dev --save-exact prettier
</code>```

Since I have never heard of this flag, I looked it up in the npm docs (2):

-E, --save-exact: Saved dependencies will be configured with an exact version rather than using npm's default semver range operator.

I can see why they want every developer using the same version. But why does this seem to require the --save-exact flag? As soon as package.lock file is committed, shouldn't this serve the same purpose?

Body:
In the docs for Prettier (a code formatter), they install it with the --save-exact flag (1):

npm install --save-dev --save-exact prettier

Since I have never heard of this flag, I looked it up in the npm docs (2):

-E, --save-exact: Saved dependencies will be configured with an exact version rather than using npm's default semver range operator.

I can see why they want every developer using the same version. But why does this seem to require the --save-exact flag? As soon as package.lock file is committed, shouldn't this serve the same purpose?


Title: VueCompilerError: Tags with side effect (<script> and <style>) are ignored in client component templates in SVG case

Body:
I understand that normally the script and style tag must not be in temlpate part of Vue component, but that about svg content? The below SVG has been drawn by Illustrator; the cls-1 class has not been created manually.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
    <defs>

    </defs>
</svg>

I has been told:

VueCompilerError: Tags with side effect (


问:
Keycloak and ReactJS: Timeout when waiting for 3rd party check iframe message
I copied this repo with a working example of Keycloak inside ReactJS: https://github.com/Qodestackr/keycloak-app

The difference is that my Keycloak server is not running locally but on an external amazon server. I logged on to the admin console and exported the Keycloak OICD JSON adapter config (some info removed for security reasons):

```<code>{
  "realm": "*******-employees",
  "auth-server-url": "https://dev.iam.******.com/",
  "ssl-required": "external",
  "resource": "serviceapp",
  "verify-token-audience": true,
  "credentials": {
    "secret": "***************************"
  },
  "use-resource-role-mappings": true,
  "confidential-port": 0
}
</code>```

First thing I noticed was that the secret is in the keycloak.json file. This cannot be intended in ReactJS because it runs client side and the users could download the file and figure out the client-secret. Second thing I noticed, when running the project, was that without manually adding the clientId to keycloak.json it throws a missing clientId error.

Anyhow, when I run this code and click login, it says "Initializing Keycloak..." for about 20-30 seconds and then the console throws the following warning and error respectively:

```<code>No routes matched location "/undefined/protocol/openid-connect/3p-cookies/step1.html"
</code>```

.

```<code>Uncaught (in promise) {error: 'Timeout when waiting for 3rd party check iframe message.'}
</code>```

In my Resources.jsx I tried setting checkLoginIFrame to false (this seems to solve the problem for most people), but this only removes the "Initializing Keycloak..." message and still nothing happens.

I also tried updating my keycloak.json to camel casing as suggested by some:

```<code>{
  "realm": "*******-employees",
  "authServerUrl": "https://dev.iam.******.com/",
  "sslRequired": "external",
  "resource": "serviceapp",
  "verifyTokenAudience": true,
  "credentials": {
    "secret": "***************************"
  },
  "useResourceRoleMappings": true,
  "confidentialPort": 0,
  "clientId": "serviceapp"
}
</code>```

Body:
I copied this repo with a working example of Keycloak inside ReactJS: https://github.com/Qodestackr/keycloak-app

The difference is that my Keycloak server is not running locally but on an external amazon server. I logged on to the admin console and exported the Keycloak OICD JSON adapter config (some info removed for security reasons):

{
  "realm": "*******-employees",
  "auth-server-url": "https://dev.iam.******.com/",
  "ssl-required": "external",
  "resource": "serviceapp",
  "verify-token-audience": true,
  "credentials": {
    "secret": "***************************"
  },
  "use-resource-role-mappings": true,
  "confidential-port": 0
}

First thing I noticed was that the secret is in the keycloak.json file. This cannot be intended in ReactJS because it runs client side and the users could download the file and figure out the client-secret. Second thing I noticed, when running the project, was that without manually adding the clientId to keycloak.json it throws a missing clientId error.

Anyhow, when I run this code and click login, it says "Initializing Keycloak..." for about 20-30 seconds and then the console throws the following warning and error respectively:

No routes matched location "/undefined/protocol/openid-connect/3p-cookies/step1.html"

.

Uncaught (in promise) {error: 'Timeout when waiting for 3rd party check iframe message.'}

In my Resources.jsx I tried setting checkLoginIFrame to false (this seems to solve the problem for most people), but this only removes the "Initializing Keycloak..." message and still nothing happens.

I also tried updating my keycloak.json to camel casing as suggested by some:

{
  "realm": "*******-employees",
  "authServerUrl": "https://dev.iam.******.com/",
  "sslRequired": "external",
  "resource": "serviceapp",
  "verifyTokenAudience": true,
  "credentials": {
    "secret": "***************************"
  },
  "useResourceRoleMappings": true,
  "confidentialPort": 0,
  "clientId": "serviceapp"
}


问:
How to create an application in Nx that has no pre-existing generator?
The various community Vue application generators for Nx will not work for me, so I'd like to start a new empty app in Nx. But it seems a pre-existing generator is always required (?). When I don't specify one, it defaults to @nrwl/web:application.

Ideally I have an empty app in which I can run "pnpm create vuetify", and set it up from there. This always provides a very solid foundation for my Vue/Vuetify apps.

I must be missing something, Nx claims to be able to hold any kind of software project, but the list of application generators is really limited.


问:
django.db.utils.IntegrityError: duplicate key
I have a model for Logs which is as follows:

```<code>class Log(TimeStampMixin):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    start_time = models.CharField(max_length=80, null=True, blank=True, default=None)
    end_time = models.CharField(max_length=80, null=True, blank=True, default=None)
    message = models.CharField(max_length=80, null=True, blank=True, default=None)

    def __str__(self):
        return str(self.message)
</code>```

I just changed message field length to max_length=1000 . After doing makemigrations when I did migrate, it giving me this error.

django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
DETAIL:  Key (id)=(32) already exists.

I tried many solution but none of them making sense for my code

I also saw other similar questions but they told to write null=True, blank=True,  but I already have it in my code

Body:
I have a model for Logs which is as follows:

class Log(TimeStampMixin):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    start_time = models.CharField(max_length=80, null=True, blank=True, default=None)
    end_time = models.CharField(max_length=80, null=True, blank=True, default=None)
    message = models.CharField(max_length=80, null=True, blank=True, default=None)

    def __str__(self):
        return str(self.message)

I just changed message field length to max_length=1000 . After doing makemigrations when I did migrate, it giving me this error.

django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
DETAIL:  Key (id)=(32) already exists.

I tried many solution but none of them making sense for my code

I also saw other similar questions but they told to write null=True, blank=True,  but I already have it in my code


问:
System.FormatException: 'The short switch is not defined in the switch mappings.'
At this point of my OnStartup method… :

```<code>_host = Host.CreateDefaultBuilder(e.Args).ConfigureAppConfiguration(c => { c.SetBasePath(appLocation); })
            .ConfigureServices(ConfigureServices).Build();
</code>```

… I get this exception:

But I don't use short switches and the -l=de is just a parameter which is defined in the launch profile. Does anyone know why this exception occurred and how to solve it?

Body:
At this point of my OnStartup method… :

_host = Host.CreateDefaultBuilder(e.Args).ConfigureAppConfiguration(c => { c.SetBasePath(appLocation); })
            .ConfigureServices(ConfigureServices).Build();

… I get this exception:

But I don't use short switches and the -l=de is just a parameter which is defined in the launch profile. Does anyone know why this exception occurred and how to solve it?


问:
Convert List<Map<DateTime, int>> of every day of the year to total sum per month on the form Map<int, int>?
First map contains any day of the year, I want to sort them them by month which maps to sum of that month.

What is the cleanest way to do this?

Map<DateTime, int> data = [{DateTime(2023, 1, 5, 2): 1}, {DateTime(2023, 2, 5, 2): 3}, {DateTime(2023, 2, 7, 2): 2}]

=> Map<int, int> monthlyData = {1: 1, 2: 5}


问:
Why cannot a const struct field be used as an initializer in C?
Consider the following example:

#include <stdio.h>
#include <stdint.h>

struct mystruct_s {
  uint16_t first;
};
typedef struct mystruct_s mystruct_t;

#define THEVALUE 5
const mystruct_t mytester = {
  .first = THEVALUE,
};

struct otherstruct_s {
  uint16_t initial;
};
typedef struct otherstruct_s otherstruct_t;

otherstruct_t othertester = {
  .initial = mytester.first,
};

int main() {
  printf("Hello, world %d!\n", othertester.initial);
  return 0;
}
```
<p>When I build this in https://replit.com/languages/c I get:</p>
<pre class="lang-none prettyprint-override"><code>> clang-7 -pthread -lm -o main main.c
main.c:20:23: error: initializer element is not a
      compile-time constant
  .initial = mytester.first,
             ~~~~~~~~~^~~~~
1 error generated.
exit status 1
</code>```

I was kind of hoping, that since mytester is declared const, and its its .first field is initialized through a define, the compiler would have figured out that I want the same initialization applied to othertester.initial, but apparently not.

In my actual code, gcc was highlighting mytester, while here clang did in fact point to the field by highlighting, which indeed is not const - is this why I cannot initialize in this case?

Anyways, I have a similar (though much more convoluted) actual case; and while I'm aware that I can just use the define to initialize, I would really like to instead initialize via mytester.first for readability. Is there any workaround where I can use that, without having to define a copy of mystruct_s where the .first field is const?

Body:
Consider the following example:

#include <stdio.h>
#include <stdint.h>

struct mystruct_s {
  uint16_t first;
};
typedef struct mystruct_s mystruct_t;

#define THEVALUE 5
const mystruct_t mytester = {
  .first = THEVALUE,
};

struct otherstruct_s {
  uint16_t initial;
};
typedef struct otherstruct_s otherstruct_t;

otherstruct_t othertester = {
  .initial = mytester.first,
};

int main() {
  printf("Hello, world %d!\n", othertester.initial);
  return 0;
}

When I build this in https://replit.com/languages/c I get:

> clang-7 -pthread -lm -o main main.c
main.c:20:23: error: initializer element is not a
      compile-time constant
  .initial = mytester.first,
             ~~~~~~~~~^~~~~
1 error generated.
exit status 1

I was kind of hoping, that since mytester is declared const, and its its .first field is initialized through a define, the compiler would have figured out that I want the same initialization applied to othertester.initial, but apparently not.

In my actual code, gcc was highlighting mytester, while here clang did in fact point to the field by highlighting, which indeed is not const - is this why I cannot initialize in this case?

Anyways, I have a similar (though much more convoluted) actual case; and while I'm aware that I can just use the define to initialize, I would really like to instead initialize via mytester.first for readability. Is there any workaround where I can use that, without having to define a copy of mystruct_s where the .first field is const?


问:
Aggregated value from last 6 months in Kafka
I have a topic with messages in Kafka. Each message contains duration, resourceId and a list of tags.

In other part of the system I need to have for each pair resourceId and tag a value representing sum of all durations from messages (having that resourceId and tag) from the last 6 months. For each pair I'm only interested in the last value. It may be not the most up to date (for example: computed one day before is acceptable).

Is it something that could be aggregated in Kafka using Kafka Streams/KSQL or it's better to search for a solution outside Kafka? If it can be done in Kafka how to approach it?


问:
How to upload to MINIO using multipart/formdata POST request in python with a presigned url
I have a presigned url policy. But when I try to upload to it using:

```<code>data = {
    'policy': '<policy_str>',
    'x-amz-algorithm': '<algo>',
    'x-amz-credential': '<cred>',
    'x-amz-date': '20230111T110342Z',
    'x-amz-signature': '<sign>',
    'bucket': 'temp',
    'key': 'object.txt',
}

files = {
    'json': (None, json.dumps(data), 'application/json'),
    'file': ('a.txt', open('a.txt', 'rb'), 'application/octet-stream')
}

r = requests.post('https://<minio_url>/temp/', data=data, verify=False)
print(r.status_code)
print(r.text)
</code>```

But I'm getting:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AuthorizationQueryParametersError</Code><Message>Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting "<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request".</Message><BucketName>temp</BucketName><Resource>/temp/</Resource><RequestId>773531234560CB56</RequestId><HostId>6ea96d23-c563-77a1-4038-d995deda5437</HostId></Error>
</code>```

I have tried the above approach. But I'm getting the malformed credentials error. I need to use the POST request itself as I want to be able to control the max content size.

Body:
I have a presigned url policy. But when I try to upload to it using:

data = {
    'policy': '<policy_str>',
    'x-amz-algorithm': '<algo>',
    'x-amz-credential': '<cred>',
    'x-amz-date': '20230111T110342Z',
    'x-amz-signature': '<sign>',
    'bucket': 'temp',
    'key': 'object.txt',
}

files = {
    'json': (None, json.dumps(data), 'application/json'),
    'file': ('a.txt', open('a.txt', 'rb'), 'application/octet-stream')
}

r = requests.post('https://<minio_url>/temp/', data=data, verify=False)
print(r.status_code)
print(r.text)

But I'm getting:

<?xml version="1.0" encoding="UTF-8"?>
<Error>AuthorizationQueryParametersError<Message>Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting "<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request".</Message><BucketName>temp</BucketName><Resource>/temp/</Resource><RequestId>773531234560CB56</RequestId><HostId>6ea96d23-c563-77a1-4038-d995deda5437</HostId></Error>

I have tried the above approach. But I'm getting the malformed credentials error. I need to use the POST request itself as I want to be able to control the max content size.


问:
Laravel Jetstream can't verify email
I am using Laravel 9.47 and Laravel Jetstream 2.7 for Authentifcation. I enabled Features::emailVerification() as well. The notification mail sent but the email_verified_at column was still NULL after clicking on activation link. It looked like the route

/email/verify/{id}/{hash}

doesn not work.

Here are my codes:

config/fortify.php

```<code>'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirm' => true,
        'confirmPassword' => true,
    ]),
],
</code>```

App\Models\User.php

```<code>class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    ...
}
</code>```

Any ideas?

Title: Laravel Jetstream can't verify email

Body:
I am using Laravel 9.47 and Laravel Jetstream 2.7 for Authentifcation. I enabled Features::emailVerification() as well. The notification mail sent but the email_verified_at column was still NULL after clicking on activation link. It looked like the route

/email/verify/{id}/{hash}

doesn not work.

Here are my codes:

config/fortify.php

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirm' => true,
        'confirmPassword' => true,
    ]),
],

App\Models\User.php

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    ...
}

Any ideas?


问:
Can't get windows username correctly when deployed to IIS .net 6
I have a webapp and I deploy it on IIS. In app, I am getting the username of current user. I get the username with Environment.UserName. When I deploy it to IIS, it is giving me the site's name (application pool name) as the username. I enabled the windows authentication and disabled the anonymous authentication on IIS. What would be the problem and how can I achieve this?


问:
Accessing environment varaibles from NuGet.config on Docker Build Image
I need to use a NuGet PAT to restore nuget packages from a private feed.

```<code><packageSources>
    <clear />
    <add key="MyPrivatePackage" value="http://<PRIVATE_PACKAGE_URL>/index.json" />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<packageSourceCredentials>
    <PackageSTN>
        <add key="Username" value="%NUGET_USER%" />
        <add key="ClearTextPassword" value="%NUGET_PAT%" />
        <add key="ValidAuthenticationTypes" value="basic" />
    </PackageSTN>
</packageSourceCredentials>
<activePackageSource>
    <add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
</code>```

I have the following in my Docker file

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG pat_token
ENV NUGET_PAT="${pat_token}"

RUN echo "The ARG variable value is ${pat_token}"
RUN echo "ENV Variable is $NUGET_PAT"

WORKDIR /src
COPY ["NuGet.config", "."]
COPY ["MyProjFolder/myproj.csproj", "MyProjFolder/"]
RUN dotnet restore "MyProjFolder/myproj.csproj" -v d
</code>```

I pass the PAT token as follows:

```<code>docker build --build-args pat_token=$env:PAT_TOKEN
</code>```

Restore fails as the %NUGET_PAT% environment variable doesn't seem to be valid. If I hardcode the PAT Token it works.

I know the value NUGET_PAT is set as I echo it out and it's the correct value. However the restore fails.

I think where I've set ENV and ARG mean this is in the correct image layer i.e. Build. So what's going on?

Body:
I need to use a NuGet PAT to restore nuget packages from a private feed.

<packageSources>
    <clear />
    <add key="MyPrivatePackage" value="http://<PRIVATE_PACKAGE_URL>/index.json" />
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<packageSourceCredentials>
    <PackageSTN>
        <add key="Username" value="%NUGET_USER%" />
        <add key="ClearTextPassword" value="%NUGET_PAT%" />
        <add key="ValidAuthenticationTypes" value="basic" />
    </PackageSTN>
</packageSourceCredentials>
<activePackageSource>
    <add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>

I have the following in my Docker file

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG pat_token
ENV NUGET_PAT="${pat_token}"

RUN echo "The ARG variable value is ${pat_token}"
RUN echo "ENV Variable is $NUGET_PAT"

WORKDIR /src
COPY ["NuGet.config", "."]
COPY ["MyProjFolder/myproj.csproj", "MyProjFolder/"]
RUN dotnet restore "MyProjFolder/myproj.csproj" -v d

I pass the PAT token as follows:

docker build --build-args pat_token=$env:PAT_TOKEN

Restore fails as the %NUGET_PAT% environment variable doesn't seem to be valid. If I hardcode the PAT Token it works.

I know the value NUGET_PAT is set as I echo it out and it's the correct value. However the restore fails.

I think where I've set ENV and ARG mean this is in the correct image layer i.e. Build. So what's going on?


问:
Where to get details about `heroku ps:exec` failure?
I'm getting an error when trying to run heroku ps:exec on a docker container dyno.
Unfortunately the only thing I get is this:

```<code>heroku ps:exec --dyno web.1
Establishing credentials... done
Connecting to web.1 on ⬢ ghr-cichub-10...
 ▸    There was an error connecting to the dyno!
</code>```

Does anybody know where I can get more details about this error?

In Heroku activities, I see building and the deployment completed with success.

The dyno state (got from heroku ps:exec --dyno web.1 --status) is up.

heroku logs --tails doesn't show anything further than the change of status from starting  to up.

if relevant this is my Dockerfile:

```<code>FROM heroku/heroku:22

RUN rm /bin/sh && ln -s /bin/bash /bin/sh

COPY ./heroku/heroku-exec.sh /app/.profile.d/heroku-exec.sh

RUN apt update && apt upgrade

RUN apt install sudo -y

RUN curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash

RUN apt install nodejs vim -y

RUN npm install sfdx-cli --global

RUN npm install @salesforce/cli --global

ADD sfdx /sfdx

WORKDIR /runner-info-app/

COPY runner-info-app/* /runner-info-app/

RUN npm install

EXPOSE 8080

CMD bash /app/.profile.d/heroku-exec.sh && node server.js
</code>```

Body:
I'm getting an error when trying to run heroku ps:exec on a docker container dyno.
Unfortunately the only thing I get is this:

heroku ps:exec --dyno web.1
Establishing credentials... done
Connecting to web.1 on ⬢ ghr-cichub-10...
 ▸    There was an error connecting to the dyno!

Does anybody know where I can get more details about this error?

In Heroku activities, I see building and the deployment completed with success.

The dyno state (got from heroku ps:exec --dyno web.1 --status) is up.

heroku logs --tails doesn't show anything further than the change of status from starting  to up.

if relevant this is my Dockerfile:

FROM heroku/heroku:22

RUN rm /bin/sh && ln -s /bin/bash /bin/sh

COPY ./heroku/heroku-exec.sh /app/.profile.d/heroku-exec.sh

RUN apt update && apt upgrade

RUN apt install sudo -y

RUN curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash

RUN apt install nodejs vim -y

RUN npm install sfdx-cli --global

RUN npm install @salesforce/cli --global

ADD sfdx /sfdx

WORKDIR /runner-info-app/

COPY runner-info-app/* /runner-info-app/

RUN npm install

EXPOSE 8080

CMD bash /app/.profile.d/heroku-exec.sh && node server.js


问:
how to fix following errors. (React, IIS)
I created small web page, but struggle to set it up correctly. When i try to run i locally
i get following error.

when i run it with directory browsing it shows me this


问:
Add new terminal command that executes, after already running processes within other terminal tab finished?
I would like to add another command to already running processes. In my case:

I have running as example the following command:

```<code>mv /media/user/A_1/file1 /media/user/A_2/; date; mv /media/user/A_2/file2 /media/user/A_1/; cd folder/; . . /activate; start processname; mv /media/user/A_2/file3 /media/user/A_3/;
</code>```

(or something else, commonly ends with 'date' or 'mv XXX' processes).

Now I would like to add another command without canceling the current running tasks (in new terminal tab I guess?) after all these processes are done.

Is that possible or do I really need to cancel (strg + c), work with "sleep X" in new tab or wait until that processes are ready? Isnt there a better solution?

Best regards and thanks in advance

Body:
I would like to add another command to already running processes. In my case:

I have running as example the following command:

mv /media/user/A_1/file1 /media/user/A_2/; date; mv /media/user/A_2/file2 /media/user/A_1/; cd folder/; . . /activate; start processname; mv /media/user/A_2/file3 /media/user/A_3/;

(or something else, commonly ends with 'date' or 'mv XXX' processes).

Now I would like to add another command without canceling the current running tasks (in new terminal tab I guess?) after all these processes are done.

Is that possible or do I really need to cancel (strg + c), work with "sleep X" in new tab or wait until that processes are ready? Isnt there a better solution?

Best regards and thanks in advance


问:
Image not displaying in browser from Django project
I am trying out an ecommerce website where list of products are input in the admin section, everything works well aside the fact that the product image does not display in browser. Have check all the codes and everything seems ok. Displaying this message in my terminal "GET /media/photos/buy-1.jpg HTTP/1.1" 404 4187
Not Found: /media/photos/buy-2.jpg

```<code>`HTML
<h2 class="title">Latest Products</h2>
  <div class="row">
    {% for item in object_list %}
    <div class="col-4">
      <div>
        <a href="{{ item.get_absolute_url }}">
          {% if item.photo %}
            <img src="{{  item.photo.url }}" alt="" />
          {% else %}
            <img src="{% static 'images/product-1.jpg' %}" alt=""/>
          {% endif %}
          <h4>{{  item.title }}</h4>
        </a>
        <a href="{{ item.get_absolute_url }}" >
          <h6>{{ item.get_category_display }}</h6>
        </a>
      </div>
      <div class="rating">
        <i class="fa fa-star"></i>
        <i class="fa fa-star"></i>
        <i class="fa fa-star"></i>
        <i class="fa fa-star"></i>
        <i class="fa fa-star-o"></i>
      </div>

      <p class='lead'>
        {% if item.d_price %}
        <del><span>${{ item.price }}</span></del>
        <span>${{ item.d_price }}</span>
        {% else %}
        <p>${{ item.price }}</p>
        {% endif %}
      </p>
    </div>
    {% endfor %}

  </div>`
</code>```

Model fie

```<code>`class Item (models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
d_price = models.FloatField(blank=True, null=True)
tax = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
photo = models.ImageField(upload_to='photos', null=False, blank=False)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('base:product_details', kwargs={
        'slug': self.slug
    })

def get_add_to_cart_url(self):
    return reverse('base:add_to_cart', kwargs={
        'slug': self.slug
    })

def get_remove_from_cart_url(self):
    return reverse('base:remove_from_cart', kwargs={
        'slug': self.slug
    })

@property
def get_photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url`
</code>```

Body:
I am trying out an ecommerce website where list of products are input in the admin section, everything works well aside the fact that the product image does not display in browser. Have check all the codes and everything seems ok. Displaying this message in my terminal "GET /media/photos/buy-1.jpg HTTP/1.1" 404 4187
Not Found: /media/photos/buy-2.jpg

`HTML

Latest Products

    {% for item in object_list %}

          {% if item.photo %}

          {% else %}

          {% endif %}

{{  item.title }}

{{ item.get_category_display }}

        {% if item.d_price %}
        ${{ item.price }}
        ${{ item.d_price }}
        {% else %}

${{ item.price }}

        {% endif %}

    {% endfor %}

`

Model fie

`class Item (models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
d_price = models.FloatField(blank=True, null=True)
tax = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
photo = models.ImageField(upload_to='photos', null=False, blank=False)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('base:product_details', kwargs={
        'slug': self.slug
    })

def get_add_to_cart_url(self):
    return reverse('base:add_to_cart', kwargs={
        'slug': self.slug
    })

def get_remove_from_cart_url(self):
    return reverse('base:remove_from_cart', kwargs={
        'slug': self.slug
    })

@property
def get_photo_url(self):
    if self.photo and hasattr(self.photo, 'url'):
        return self.photo.url`


问:
How to change value of existing integer in the registry
I want to change the value of an existing integer in the registry (for example, EnableLUA, which is located in SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System) from 0 to 1. I know how to create a new integer value, but not how to edit an existing value.

I tried this code:

#include <windows.h>

using namespace std;

int main()
{
    HKEY hKey;
    LPCTSTR EnableLua = "EnableLUA";
    DWORD forLua = 1;
    RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", &hKey);
    RegSetValueEx(hKey, EnableLua, 0, REG_DWORD, (PBYTE)forLua, (DWORD)sizeof(forLua));
    RegCloseKey(hKey);
    return 0;
}
```
<p>I am getting the following warning:</p>
<pre class="lang-none prettyprint-override"><code>A:\dev\secret++\SeriesOfExperiments\test_g_1.cpp:20:54: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   RegSetValueEx(hKey, SecureDesktop, 0, REG_DWORD, (PBYTE)forLua, (DWORD)sizeof(forBehaviourAndSecure));
</code>```

I know that the problem is in the DWORD for Lua, but I don't know how to change the integer value in the parameter.

This warning doesn't allow my program to work correctly.

Any ideas?

Body:
I want to change the value of an existing integer in the registry (for example, EnableLUA, which is located in SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System) from 0 to 1. I know how to create a new integer value, but not how to edit an existing value.

I tried this code:

#include <windows.h>

using namespace std;

int main()
{
    HKEY hKey;
    LPCTSTR EnableLua = "EnableLUA";
    DWORD forLua = 1;
    RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", &hKey);
    RegSetValueEx(hKey, EnableLua, 0, REG_DWORD, (PBYTE)forLua, (DWORD)sizeof(forLua));
    RegCloseKey(hKey);
    return 0;
}

I am getting the following warning:

A:\dev\secret++\SeriesOfExperiments\test_g_1.cpp:20:54: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   RegSetValueEx(hKey, SecureDesktop, 0, REG_DWORD, (PBYTE)forLua, (DWORD)sizeof(forBehaviourAndSecure));

I know that the problem is in the DWORD for Lua, but I don't know how to change the integer value in the parameter.

This warning doesn't allow my program to work correctly.

Any ideas?


问:
Definition for rule 'import/no-cycle' was not found
I deleted my npm package and package.lock.json file, then I ran npm install and then npm update. So when I started my app using npm run start, I am getting an error

This is the error that is displaying on the screen when I start my app:

[eslint]
src\components\index.jsx
Line 4:1:  Definition for rule 'import/no-cycle' was not found  import/no-cycle


问:
Spark Stops indefinitely and does not process anything on when trying to connect to adls gen2 azure using java
I am trying to connect to Adls gen2 storage on azure using spark and java .
Here is my code</p>
```<code>public static void main(String[] args) {

        SparkConf sparkConf = new SparkConf().setAppName("Adls connection");
        SparkSession sparkSession = SparkSession.builder().config(sparkConf).master("local[*]").getOrCreate();

        sparkSession.sparkContext().hadoopConfiguration().set("fs.adl.impl", "org.apache.hadoop.fs.azure.NativeAzureFileSystem");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.auth.type.<account-name>.dfs.core.windows.net", "OAuth");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth.provider.type.<account-name>.dfs.core.windows.net", "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.id.<account-name>.dfs.core.windows.net", "<client-id>");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.secret.<account-name>.dfs.core.windows.net", "<client-secret>");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.endpoint.<account-name>.dfs.core.windows.net", "https://login.microsoftonline.com/<tenant-id>/oauth2/token");
        String path = "adl://<account-name>.azuredatalakestore.net/data/*.csv";

        sparkSession.read().format("csv").option("header",true).load(path);

    }

'''

But on running this spark after giving few log message gets stuck and nothing happens.
Could you please help me what i am doing wrong
</code>```

Body:
I am trying to connect to Adls gen2 storage on azure using spark and java .
Here is my code

public static void main(String[] args) {

        SparkConf sparkConf = new SparkConf().setAppName("Adls connection");
        SparkSession sparkSession = SparkSession.builder().config(sparkConf).master("local[*]").getOrCreate();

        sparkSession.sparkContext().hadoopConfiguration().set("fs.adl.impl", "org.apache.hadoop.fs.azure.NativeAzureFileSystem");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.auth.type.<account-name>.dfs.core.windows.net", "OAuth");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth.provider.type.<account-name>.dfs.core.windows.net", "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.id.<account-name>.dfs.core.windows.net", "<client-id>");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.secret.<account-name>.dfs.core.windows.net", "<client-secret>");
        sparkSession.sparkContext().hadoopConfiguration().set("fs.azure.account.oauth2.client.endpoint.<account-name>.dfs.core.windows.net", "https://login.microsoftonline.com/<tenant-id>/oauth2/token");
        String path = "adl://<account-name>.azuredatalakestore.net/data/*.csv";

        sparkSession.read().format("csv").option("header",true).load(path);

    }

'''

But on running this spark after giving few log message gets stuck and nothing happens.
Could you please help me what i am doing wrong


问:
Pass variable value from ViewModel A to ViewModel B - JetPack Compose
i have a problem.
I try pass a variable <ArrayList<List>> betwenne two ViewModels.

ViewModel A:

```<code>@HiltViewModel
class RouteTrackViewModel @Inject constructor(
    application: Application
) : ViewModel(){

    private val locationLiveData = LocationLiveData(application)
    private var finalRoute = ArrayList<List<Double>>()
    private var finalTime : Duration = Duration.ZERO

    fun getLocationLiveData() = locationLiveData
    fun getFinalRoute() = finalRoute

...
}
</code>```

ViewModel B:

```<code>@HiltViewModel
class RouteSaveViewModel @Inject constructor(
    private var routeTrackViewModel : RouteTrackViewModel
) : ViewModel() {

    fun getLocationLiveData() = routeTrackViewModel.getLocationLiveData()

    fun getRouteLocation() = routeTrackViewModel.getFinalRoute()

}
</code>```

if i use like that give me this error:

```<code>Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly.
  Access the ViewModel via the Android APIs (e.g. ViewModelProvider) instead.
  Injected ViewModel: com.xxxxxxxxxxxxxx.xxxxxxxxxxxx.presentation.routes.route_track.RouteTrackViewModel
</code>```

please can you help me to fine a good solution?

I expect to have access to final Route in Route Save ViewModel.
I need these values to show on Mapbox a polyline and create a form to save the route later in a JSON file and send it to my database.

Body:
i have a problem.
I try pass a variable <ArrayList<List>> betwenne two ViewModels.

ViewModel A:

@HiltViewModel
class RouteTrackViewModel @Inject constructor(
    application: Application
) : ViewModel(){

    private val locationLiveData = LocationLiveData(application)
    private var finalRoute = ArrayList<List<Double>>()
    private var finalTime : Duration = Duration.ZERO

    fun getLocationLiveData() = locationLiveData
    fun getFinalRoute() = finalRoute

...
}

ViewModel B:

@HiltViewModel
class RouteSaveViewModel @Inject constructor(
    private var routeTrackViewModel : RouteTrackViewModel
) : ViewModel() {

    fun getLocationLiveData() = routeTrackViewModel.getLocationLiveData()

    fun getRouteLocation() = routeTrackViewModel.getFinalRoute()

}

if i use like that give me this error:

Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly.
  Access the ViewModel via the Android APIs (e.g. ViewModelProvider) instead.
  Injected ViewModel: com.xxxxxxxxxxxxxx.xxxxxxxxxxxx.presentation.routes.route_track.RouteTrackViewModel

please can you help me to fine a good solution?

I expect to have access to final Route in Route Save ViewModel.
I need these values to show on Mapbox a polyline and create a form to save the route later in a JSON file and send it to my database.


问:
SSO with Google 2fa account in WKWebview using ASWebAuthenticationSession not working right
We have a web app which has two single sign-on options sign-in with apple and sign-in with google which all works fine in the browser. On iOS we have this web app in WKWebview app shell in which we use ASWebAuthenticationSession for sign-in with google.

The problem comes here only when the user has 2 factor authentication on his/her google account, the ASWebAuthenticationSession window doesn't close after 2 step verification, It loads the web app in its own content.

some how it seems like the ASWebAuthenticationSession configuration prefersEphemeralWebBrowserSession = true gets lost in the process.

Anyone with any Idea on how we can fix this problem?

Thanks.

here is the swift code

```<code>func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    guard let url = navigationAction.request.url else {
      decisionHandler(.cancel)
      return
    }
    if(Functions.getParameter(url: url.absoluteString, param: “code”) != nil){
      authSession.cancel() // close login window
      ......*webView load url*
    }
    else{
      if let url = webView.url, url.absoluteString.starts(with: “https://accounts.google.com”){
        let callbackScheme = “https”
        authSession = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme, completionHandler: { (callbackURL, error) in
          return
        })
        authSession.presentationContextProvider = self
        authSession.prefersEphemeralWebBrowserSession = true
        authSession.start()
        decisionHandler(.cancel)
        return
      }
    }
   decisionHandler(.allow)
  }
</code>```

Body:
We have a web app which has two single sign-on options sign-in with apple and sign-in with google which all works fine in the browser. On iOS we have this web app in WKWebview app shell in which we use ASWebAuthenticationSession for sign-in with google.

The problem comes here only when the user has 2 factor authentication on his/her google account, the ASWebAuthenticationSession window doesn't close after 2 step verification, It loads the web app in its own content.

some how it seems like the ASWebAuthenticationSession configuration prefersEphemeralWebBrowserSession = true gets lost in the process.

Anyone with any Idea on how we can fix this problem?

Thanks.

here is the swift code

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    guard let url = navigationAction.request.url else {
      decisionHandler(.cancel)
      return
    }
    if(Functions.getParameter(url: url.absoluteString, param: “code”) != nil){
      authSession.cancel() // close login window
      ......*webView load url*
    }
    else{
      if let url = webView.url, url.absoluteString.starts(with: “https://accounts.google.com”){
        let callbackScheme = “https”
        authSession = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme, completionHandler: { (callbackURL, error) in
          return
        })
        authSession.presentationContextProvider = self
        authSession.prefersEphemeralWebBrowserSession = true
        authSession.start()
        decisionHandler(.cancel)
        return
      }
    }
   decisionHandler(.allow)
  }


问:
react js npm googleapis,@googleapi/sheets package error for version (npm=9.2.0,node=v18.13.0)
React message error image links

My local PC is running Ubuntu 22.04.1 LTS.

When installing the package, there are no problems; there are a few warnings and a red error, but rendering works fine. But when I installed the Google package "npm install googleapis" or "npm install @googleapis/sheets" and imported the function, errors occurred. I commented on the import package line, and there is no error. to make sure, I uncommented the line again but errors(long 50 errors package) happen

--more detail about my pc [optional]--

I use Ubuntu, and when I install "sudo apt install npm," it downloads a far-old version "12.x.x." Then I remove it with apt autoremove and download the node file from the website, version 18.13.0. At the time, I'm not sure how to install the file, so I extract the node file, rename it to node, move it to /opt, and export it to $PATH:.../opt/node/bin. (if you don't mind please tell me how to install node properly)

I'm not sure what the cause of the error is.

Thank you for helping

Simon

Expect to understand the error to fix the core problem if there is a bad PC system configuration.


问:
Do we have any pre merge action or webhook in github?
I want to run the automation test before the final merge of code in the "main" branch. In microservices setup, services are changing frequently and need to ensure that the current changes are aligned with others.
Is there a way to run a check before merging the code?</p>


问:
Can i dispatch many actions in getServersideprops?
In my social media app in Home page i want to dispatch 3 actions from my api:
posts , users , userDetails

But this may show an error(500) on vercel because the request takes a lot of time to get all these data.

vercel Error

this error will not appear again after refreshing the page !!!
i think that's because the request takes a lot of time to get all the data.

-> getServersideProps Code

```<code>export const getServerSideProps = wrapper.getServerSideProps(
  store => async (context) =>
{
    const {req} = context
    const session = await getSession({ req });

    await store.dispatch(fetchPostsAction());
    await store.dispatch(fetchUsersAction(4));
    await store.dispatch(LoggedInUserAction({email:session.user.email}));
})
</code>```

-> fetchPostsAction Code

```<code>  "post/list",
  async (_, { rejectWithValue, getState, dispatch }) => {
    try
    {
      let link = `${URL}/api/posts`;
      const { data } = await axios.get(link,{
        headers: { "Accept-Encoding": "gzip,deflate,compress" }
    });
      console.log("#2 got the data",data)
      return data;
    } catch (error) {
      if (!error?.response) throw error;
      return rejectWithValue(error?.response?.data);
    }
  }
);
</code>```

-> extraReducer Code

```<code>builder.addCase(createpostAction.pending, (state, action) => {
      state.createPostLoading = true;
    });
    builder.addCase(createpostAction.fulfilled, (state, action) => {
      state.postLists = [...state.postLists, action.payload.post].sort((a, b) => b.createdAt > a.createdAt ? 1 : -1)
      state.createPostLoading = false;
      state.isCreated = true;
      state.appErr = null;
      state.serverErr = null;
    });
    builder.addCase(createpostAction.rejected, (state, action) => {
      state.createPostLoading = false;
      state.appErr =
        action?.payload?.message || action?.payload?.error?.message;
      state.serverErr = action?.error?.message;
    });
</code>```

-> get posts from api Code

```<code>handler.get(async (req, res) =>
{
    await db.connect();
    try {
        const posts = await Post.find().populate({
            path: 'user',
            model: 'User',
        }).populate({
            path:'comments',
            options: {sort: {'createdAt' : -1} }
        }).sort('-createdAt')
        res.status(200).json({
            success:true,
            posts
        });
    } catch (err) {
        res.status(500).json(err.message)
    }
    await db.disconnect();
})
</code>```

so what is the best way to fetch all these data in next js ?

I hope there is a way to solve this problem

Body:
In my social media app in Home page i want to dispatch 3 actions from my api:
posts , users , userDetails

But this may show an error(500) on vercel because the request takes a lot of time to get all these data.

vercel Error

this error will not appear again after refreshing the page !!!
i think that's because the request takes a lot of time to get all the data.

-> getServersideProps Code

export const getServerSideProps = wrapper.getServerSideProps(
  store => async (context) =>
{
    const {req} = context
    const session = await getSession({ req });

    await store.dispatch(fetchPostsAction());
    await store.dispatch(fetchUsersAction(4));
    await store.dispatch(LoggedInUserAction({email:session.user.email}));
})

-> fetchPostsAction Code

  "post/list",
  async (_, { rejectWithValue, getState, dispatch }) => {
    try
    {
      let link = `${URL}/api/posts`;
      const { data } = await axios.get(link,{
        headers: { "Accept-Encoding": "gzip,deflate,compress" }
    });
      console.log("#2 got the data",data)
      return data;
    } catch (error) {
      if (!error?.response) throw error;
      return rejectWithValue(error?.response?.data);
    }
  }
);

-> extraReducer Code

builder.addCase(createpostAction.pending, (state, action) => {
      state.createPostLoading = true;
    });
    builder.addCase(createpostAction.fulfilled, (state, action) => {
      state.postLists = [...state.postLists, action.payload.post].sort((a, b) => b.createdAt > a.createdAt ? 1 : -1)
      state.createPostLoading = false;
      state.isCreated = true;
      state.appErr = null;
      state.serverErr = null;
    });
    builder.addCase(createpostAction.rejected, (state, action) => {
      state.createPostLoading = false;
      state.appErr =
        action?.payload?.message || action?.payload?.error?.message;
      state.serverErr = action?.error?.message;
    });

-> get posts from api Code

handler.get(async (req, res) =>
{
    await db.connect();
    try {
        const posts = await Post.find().populate({
            path: 'user',
            model: 'User',
        }).populate({
            path:'comments',
            options: {sort: {'createdAt' : -1} }
        }).sort('-createdAt')
        res.status(200).json({
            success:true,
            posts
        });
    } catch (err) {
        res.status(500).json(err.message)
    }
    await db.disconnect();
})

so what is the best way to fetch all these data in next js ?

I hope there is a way to solve this problem


问:
How to create Stripe Product Mega menu TABs content transition effects
I am trying to add Stripe.com product mega menu transition effects to my Elementor Tabs Widgets in the content switching area. But I don't know how to do this? Please help me here

[Stripe transition effect:] (https://i.stack.imgur.com/k4m5h.gif)

For changing tabs in the elementor tabs widget I have added JavaScript mouseenter. Which is working.

[My Elementor Tabs - Layout:] (https://i.stack.imgur.com/CSnLJ.png)

But I am still looking for stripe product mega menu tabs switching transition effects.


问:
Angular Universal access cookie in server
What is the easiest way to access a cookie on the server of an angular universal app?
My goal is that when I set a cookie in the browser side, refresh the page, I can access the cookie on the server side.

I'm finding it hard to find an example for this, and the libraries that I've found are either outdated or not working.


问:
What is the best means to connect onprem and azure cloud resources
Am working to connect our onprem and cloud resources together using site to site vpn link,The question is , Do i have to setup point to side connection along side point to side connection? or just one works? Express route will be too expensive as we have a small footprint in Azure.

Migration of server from onprem to azure cloud is one of the reason why this is created & disaster
recovery back onprem is a condition as well. any solution with a good reason works,feel free to chip in.

Am concern about people that work remote, or if i travel and need to login into our network
just looking for information on best practices or any challenges that anyone that did similar work encountered


问:
How to clear selected options from react select?
I have implemented react select in my SPFx react project.

Below is the reference link for the react select control,

https://react-select.com/home

Below is the code snippet of the react select control.

```<code>                      <Select options={
                        (searchValue === null || searchValue) ?
                          filteredData?.map((item) => {
                            return {
                              value: item?.EncodedAbsUrl,
                              label: <a href={item?.EncodedAbsUrl} data-interception="off" target="_blank" rel="noopener noreferrer" className='link-name '>
                                {item?.FileLeafRef.split('.')[0]}
                              </a>
                            };
                          }) : []}
                        isMulti
                        className="ddl-search"
                        isClearable={true}
                        isSearchable={true}
                        placeholder={<><i className="fa fa-search"></i><span className='padding-left'>Search Forms & Templates</span></>}
                        onInputChange={(e) => filterDocuments(e)}
                        components={{ NoOptionsMessage }}
                        menuIsOpen={isOpenMenu}
                        onBlur={() => setIsOpenMenu(false)}
                        escapeClearsValue={true}
                        backspaceRemovesValue={true}
                        ref={ref}
                        openMenuOnFocus
                      />
</code>```

I need to remove all selected options programmatically without pressing any key or clicking a button.

Below is the screenshot for the same for more clarification.

Can anyone help me with the same?

Thanks

Body:
I have implemented react select in my SPFx react project.

Below is the reference link for the react select control,

https://react-select.com/home

Below is the code snippet of the react select control.

                      <Select options={
                        (searchValue === null || searchValue) ?
                          filteredData?.map((item) => {
                            return {
                              value: item?.EncodedAbsUrl,
                              label:
                                {item?.FileLeafRef.split('.')[0]}

                            };
                          }) : []}
                        isMulti
                        className="ddl-search"
                        isClearable={true}
                        isSearchable={true}
                        placeholder={<>Search Forms & Templates</>}
                        onInputChange={(e) => filterDocuments(e)}
                        components={{ NoOptionsMessage }}
                        menuIsOpen={isOpenMenu}
                        onBlur={() => setIsOpenMenu(false)}
                        escapeClearsValue={true}
                        backspaceRemovesValue={true}
                        ref={ref}
                        openMenuOnFocus
                      />

I need to remove all selected options programmatically without pressing any key or clicking a button.

Below is the screenshot for the same for more clarification.

Can anyone help me with the same?

Thanks


问:
The requested module '/node_modules/form-data/lib/browser.js' does not provide an export named 'default
I am currently working on a design system using storybook, vue3 and typescript.

My auth component makes a post to a sso provider. For this I use axios.
Now when i install my design system in another project and call my auth component, i get the error:

The requested module '/node_modules/form-data/lib/browser.js' does not provide an export named 'default

I do not use 'form-data' actively!

```<code>const fields = reactive({
  email: "",
  password: "",
  code: ""
});
const form: Form = reactive({
  action: ref(props.action),
  mfa: undefined
})
</code>```
```<code>axios.post(form.action, {
   email: fields.email,
   password: encrypt(fields.password),
   code: fields.code
}).then((response) => {
   success.value = true;
   form.mfa = response.data.mfa;
   form.action = response.data.action;
   if (fields.code && true === response.data.authenticated) {
       window.location.href = response.data.destination;
   } else {
       success.value = true;
       message.success("Valid");
     }
   }).catch(error => {
     console.error(error)
     if (error.response.status != 422) {
       reset();
     }
     message.error(error.message)
});
</code>```

Any advice would help me

Body:
I am currently working on a design system using storybook, vue3 and typescript.

My auth component makes a post to a sso provider. For this I use axios.
Now when i install my design system in another project and call my auth component, i get the error:

The requested module '/node_modules/form-data/lib/browser.js' does not provide an export named 'default

I do not use 'form-data' actively!

const fields = reactive({
  email: "",
  password: "",
  code: ""
});
const form: Form = reactive({
  action: ref(props.action),
  mfa: undefined
})

axios.post(form.action, {
   email: fields.email,
   password: encrypt(fields.password),
   code: fields.code
}).then((response) => {
   success.value = true;
   form.mfa = response.data.mfa;
   form.action = response.data.action;
   if (fields.code && true === response.data.authenticated) {
       window.location.href = response.data.destination;
   } else {
       success.value = true;
       message.success("Valid");
     }
   }).catch(error => {
     console.error(error)
     if (error.response.status != 422) {
       reset();
     }
     message.error(error.message)
});

Any advice would help me


问:
GIT fails "fatal: Authentication failed" (offline scenario)
When connecting to my git repo I have to add authentication header
git -c http.extraHeader="Authorization: Basic $b64pat" pull
instead of
git pull that fails

```<code>fatal: Authentication failed for 'https://xxxap01/xxxApps/xxxPreview/_git/xxxPreview/
</code>```

This is my first question so foregive me and help me approve quality, thanks.

How can I make my Windows credentials work and get rid of cumbersome usage of PAT in every request?

The git repo is located on an on-prem Azure DevOps Server 2020 (due to governmental requirements) which I connect to using VPN client. Once connected, I can no longer access www/internet.

I can access https://xxxap01/xxxApps using my local browser but are of course prompted to enter my 'mysecuredomainaccount@securedomain.dk' and 'password' (the SSL cert is self signed but has been add to cert store of "Trusted Root Certification Authorities" (User).

DevOps Server is hosted on a Windows Server 2019, and the IIS
IIS authentication - Basic Auth is not installed

I have added a generic credentials in the "Credential Manager" using the standard git syntax git:https://xxxap01/xxxApps and same 'mysecuredomainaccount@securedomain.dk' and 'password'

git credential-manager unconfigure

git config --global credential.helper wincred

git credential-manager azure-repos list https://xxxap01/xxxApps
OK: Shows ..> (global) -> mysecuredomainaccount@securedomain.dk

Running
git pull
results in this error in the log file gcm-diagnose.log:

```<code>ICredentialStore instance is of type: CredentialStore
Writing test credential... OK
Reading test credential... OK
Deleting test credential... OK
------------
Diagnostic: Microsoft authentication (AAD/MSA)
Skipped: False
Success: True
Exception: None
Log:
Broker not supported.
Flow type is: Auto
Gathering MSAL token cache data... OK
CacheDirectory: C:\Users\jrt\AppData\Local\.IdentityService
CacheFileName: msal.cache
CacheFilePath: C:\Users\jrt\AppData\Local\.IdentityService\msal.cache
Creating cache helper... OK
Verifying MSAL token cache persistence... OK
------------
Diagnostic: GitHub API
Skipped: False
Success: False
Exception:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote name could not be resolved: 'api.github.com'
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitHub.GitHubRestApi.<GetMetaInfoAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitHub.Diagnostics.GitHubApiDiagnostic.<RunInternalAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitCredentialManager.Diagnostics.Diagnostic.<RunAsync>d__5.MoveNext()
Log:
Using 'https://github.com/' as API target.
Querying '/meta' endpoint...
</code>```

Body:
When connecting to my git repo I have to add authentication header
git -c http.extraHeader="Authorization: Basic $b64pat" pull
instead of
git pull that fails

fatal: Authentication failed for 'https://xxxap01/xxxApps/xxxPreview/_git/xxxPreview/

This is my first question so foregive me and help me approve quality, thanks.

How can I make my Windows credentials work and get rid of cumbersome usage of PAT in every request?

The git repo is located on an on-prem Azure DevOps Server 2020 (due to governmental requirements) which I connect to using VPN client. Once connected, I can no longer access www/internet.

I can access https://xxxap01/xxxApps using my local browser but are of course prompted to enter my 'mysecuredomainaccount@securedomain.dk' and 'password' (the SSL cert is self signed but has been add to cert store of "Trusted Root Certification Authorities" (User).

DevOps Server is hosted on a Windows Server 2019, and the IIS
IIS authentication - Basic Auth is not installed

I have added a generic credentials in the "Credential Manager" using the standard git syntax git:https://xxxap01/xxxApps and same 'mysecuredomainaccount@securedomain.dk' and 'password'

git credential-manager unconfigure

git config --global credential.helper wincred

git credential-manager azure-repos list https://xxxap01/xxxApps
OK: Shows ..> (global) -> mysecuredomainaccount@securedomain.dk

Running
git pull
results in this error in the log file gcm-diagnose.log:

ICredentialStore instance is of type: CredentialStore
Writing test credential... OK
Reading test credential... OK
Deleting test credential... OK
------------
Diagnostic: Microsoft authentication (AAD/MSA)
Skipped: False
Success: True
Exception: None
Log:
Broker not supported.
Flow type is: Auto
Gathering MSAL token cache data... OK
CacheDirectory: C:\Users\jrt\AppData\Local\.IdentityService
CacheFileName: msal.cache
CacheFilePath: C:\Users\jrt\AppData\Local\.IdentityService\msal.cache
Creating cache helper... OK
Verifying MSAL token cache persistence... OK
------------
Diagnostic: GitHub API
Skipped: False
Success: False
Exception:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote name could not be resolved: 'api.github.com'
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitHub.GitHubRestApi.<GetMetaInfoAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitHub.Diagnostics.GitHubApiDiagnostic.<RunInternalAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at GitCredentialManager.Diagnostics.Diagnostic.<RunAsync>d__5.MoveNext()
Log:
Using 'https://github.com/' as API target.
Querying '/meta' endpoint...


问:
IllegalArgumentException (wrong user in context) in TileService in Android
I got a crash in my app, related to TileService#requestListeningState.

In particular: Caused by: java.lang.IllegalArgumentException: User 150 is not the current user.

Quoting the documentation: IllegalArgumentException if the user of the context is not the current user.

How can I be sure the user is always the same?

How is the user in Android managed? I did not find much documentation on this specific argument. I know what a Context is, but regarding the user in the context, I do not know.

I am calling that function using this as context in a Service.
Is there any official "good programming" documentation about the Context?

Sorry if I don't have more info, but actually I could not reproduce the problem, I just have a stacktrace from the users.