问:
detail: "Not Found" when running fastapi with uvicorn
I want to run my FastAPI for multiprocessing but when I try to run using uvicorn with reload and workers but it could not find my login endpoint.

It says "detail": "Not Found" when I hit the endpoint this is my object_counter_api.py

```<code>app = FastAPI(
    title="Object Counter API",
    description="REST API for Object Counter Service.",
    version="0.1",
    contact={   "name": "my_endpoint",
                "url": "https://my_endpoint.com",
                "email": "sales@my_endpoint.com"
            }
)

#  Allow cors error mitigation
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"]
)

class ObjectCounterAPI:
    def run_object_counter(self, host, port):
        ABLogger.info(self, "running object counter API!")
        self.setup()
        uvicorn.run("object_counter_api:app", host=self.vehicle_config.host,port=self.vehicle_config.port, reload=True, workers=2)

    def setup(self):
        @app.post("/vehicle/api/v1/login")
        async def login(request: LoginRequest):
            ABLogger.info(self, "login credentials check!")
            access_token = await self.authenticate_user(request.username, request.password)
            response = LoginResponse(access_token=access_token, token_type="bearer")
            return response
</code>```

this is my main.py

```<code>if __name__ == "__main__":
    @hydra.main(config_path=root / "hydra_config", config_name="debug", version_base=None)
    def main(hydra_config: DictConfig):
        api = ObjectCounterAPI(hydra_config)
        mp.Process(target = api.run_object_counter(host=hydra_config.api.vehicle_counter.host, port=hydra_config.api.vehicle_counter.port)).start()
    main()
</code>```

Body:
I want to run my FastAPI for multiprocessing but when I try to run using uvicorn with reload and workers but it could not find my login endpoint.

It says "detail": "Not Found" when I hit the endpoint this is my object_counter_api.py

app = FastAPI(
    title="Object Counter API",
    description="REST API for Object Counter Service.",
    version="0.1",
    contact={   "name": "my_endpoint",
                "url": "https://my_endpoint.com",
                "email": "sales@my_endpoint.com"
            }
)

#  Allow cors error mitigation
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"]
)

class ObjectCounterAPI:
    def run_object_counter(self, host, port):
        ABLogger.info(self, "running object counter API!")
        self.setup()
        uvicorn.run("object_counter_api:app", host=self.vehicle_config.host,port=self.vehicle_config.port, reload=True, workers=2)

    def setup(self):
        @app.post("/vehicle/api/v1/login")
        async def login(request: LoginRequest):
            ABLogger.info(self, "login credentials check!")
            access_token = await self.authenticate_user(request.username, request.password)
            response = LoginResponse(access_token=access_token, token_type="bearer")
            return response

this is my main.py

if __name__ == "__main__":
    @hydra.main(config_path=root / "hydra_config", config_name="debug", version_base=None)
    def main(hydra_config: DictConfig):
        api = ObjectCounterAPI(hydra_config)
        mp.Process(target = api.run_object_counter(host=hydra_config.api.vehicle_counter.host, port=hydra_config.api.vehicle_counter.port)).start()
    main()


来源: stackexchange

问:
How to create a custom std::ostream which has an override for each primitive type
I am creating a custom logger that I want to use as a drop-in replacement for a std::ostream.  I want to have overrides for each primitive type -- I do not want to implement a char-based streambuf thing (as you can see, I write to std::cerr anyway for now).

I'm getting a segfault with the following...  I am not sure why.  I've tried running in the debugger but even when I single-step through things, it's not clearly showing me why the segfault is occurring.

```<code>#include <iostream>

// A custom basic_ostream that has an implementation for each primitive type
struct Log : std::basic_ostream<char>
{
    Log& operator<<(int o) noexcept { std::cerr << "INT\n"; return *this; }
};

// I want my objects to keep using std::ostream
struct A
{
    friend std::ostream& operator<<(std::ostream& os, A const& o) noexcept
    {
        return os << o.x;
    }

private:
    int x;
};

int main()
{
    Log log;
    A a;
    log << a;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a custom logger that I want to use as a drop-in replacement for a std::ostream.  I want to have overrides for each primitive type -- I do not want to implement a char-based streambuf thing (as you can see, I write to std::cerr anyway for now).

I'm getting a segfault with the following...  I am not sure why.  I've tried running in the debugger but even when I single-step through things, it's not clearly showing me why the segfault is occurring.

#include <iostream>

// A custom basic_ostream that has an implementation for each primitive type
struct Log : std::basic_ostream<char>
{
    Log& operator<<(int o) noexcept { std::cerr << "INT\n"; return *this; }
};

// I want my objects to keep using std::ostream
struct A
{
    friend std::ostream& operator<<(std::ostream& os, A const& o) noexcept
    {
        return os << o.x;
    }

private:
    int x;
};

int main()
{
    Log log;
    A a;
    log << a;
}


问:
Redirect to login page and create new session when session expired
I published an asp.net mvc project on local Web Server (IIS)  and used IHttpContextAccessor to share logged in user data that i got from Azure to and other data to show it in _loginPartial view

```<code>var UserData = httpContextAccessor.HttpContext.Session.GetObject<List<UserDataType>>("UserData").FirstOrDefault();
</code>```

Here is the class SessionExtensions with method GetObject

```<code> public static T? GetObject<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
</code>```

The problem is when the session timeout expired i got an error on the page HTTP ERROR 500 and that is becuse UserData is null.
i tried to check  httpContextAccessor.HttpContext.Session.IsAvailable  but is always true even if the session is expired

Body:
I published an asp.net mvc project on local Web Server (IIS)  and used IHttpContextAccessor to share logged in user data that i got from Azure to and other data to show it in _loginPartial view

var UserData = httpContextAccessor.HttpContext.Session.GetObject<List<UserDataType>>("UserData").FirstOrDefault();

Here is the class SessionExtensions with method GetObject

 public static T? GetObject<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }

The problem is when the session timeout expired i got an error on the page HTTP ERROR 500 and that is becuse UserData is null.
i tried to check  httpContextAccessor.HttpContext.Session.IsAvailable  but is always true even if the session is expired


问:
Anchor links in iframe with fixed height don't work as expected
I have an iframe embedded in my page. This iframe contains an other page with a few sections and anchor links to corresponding sections (jump to links). The height of iframe is controlled with JS through "message" event.

```<code><style>
 .my-iframe {
 width: 100%;
 height: 100%;
 border: 0;
 box-shadow: none;
 }
</style>

<iframe class="my-iframe" src="https:/my-iframe/" title="My iframe" ></iframe>

<script>
 const frame = document.querySelector('.my-iframe');
 window.addEventListener('message', (e) => {
 frame.style.height = e.data.params.height + 'px'
 })
</script>
</code>```

The problem is, after setting the iframe height from JS, the anchor links in it stop working, but when i remove dynamic height and leave it on default value, links work just fine.
The height value from event data is equal to the page height which is embedded in with iframe, can it be too much and cause the links not to work?

Body:
I have an iframe embedded in my page. This iframe contains an other page with a few sections and anchor links to corresponding sections (jump to links). The height of iframe is controlled with JS through "message" event.

The problem is, after setting the iframe height from JS, the anchor links in it stop working, but when i remove dynamic height and leave it on default value, links work just fine.
The height value from event data is equal to the page height which is embedded in with iframe, can it be too much and cause the links not to work?


问:
Is it possible to write this SQL query shorter?
I have excercise to get data from MySql. Two tables 'producers' and 'products'. Task content:

The name of the manufacturer will appear in the first column.
In the second column  will apear % of products
of a given manufacturer for all products. Third column
has the average number of products of a given manufacturer per day.
Products that do not have a manufacturer ID number (producer_id = NULL) belong
qualify as "Other"(there is not 'Other' in producers table) and present in the statement.
All data will depend on date which is selected by user for example, user need statement from '2017-03-28' to '2017-03-30' or another example from '2017-03-29' to '2017-03-29'

I wrote this query. This is working fine but in my opinion is too long.

```<code>SELECT producers.producer_name AS producer,
CONCAT(ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = producers.producer_id AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') * 100 /
(SELECT COUNT(products.product_name) FROM products where products.product_date BETWEEN '2017-03-28' AND '2017-03-30')), '%') AS '% share',
ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = producers.producer_id AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') /
(SELECT COUNT(DISTINCT products.product_date) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')) AS 'day avg'

FROM products, producers
GROUP BY producers.producer_name
UNION

SELECT 'other' AS producer,
CONCAT(ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = 'null'AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') * 100 /
(select COUNT(products.product_name) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')), '%') AS '% share',
ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = 'null' AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') /
(SELECT COUNT(DISTINCT products.product_date) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')) AS 'day avg'
FROM products
</code>```

tables:

```<code>CREATE TABLE `products` (
`product_id` INT(11) NOT NULL AUTO_INCREMENT,
`product_date` DATE NOT NULL,
`producer_id` INT(11) NULL,
`product_url` VARCHAR(300) NOT NULL,
`product_name` VARCHAR(300) NOT NULL,
`product_price` DECIMAL(11,2) NULL DEFAULT NULL,
`product_price_old` DECIMAL(11,2) NULL DEFAULT NULL,
`product_reviews` INT(11) NULL DEFAULT NULL,
`product_rating` FLOAT NULL DEFAULT NULL,
PRIMARY KEY (`product_id`),
INDEX `product_date_producer_id` (`producer_id`, `product_date`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

CREATE TABLE `producers` (
`producer_id` INT(11) NOT NULL AUTO_INCREMENT,
`producer_name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`producer_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
</code>```

Body:
I have excercise to get data from MySql. Two tables 'producers' and 'products'. Task content:

The name of the manufacturer will appear in the first column.
In the second column  will apear % of products
of a given manufacturer for all products. Third column
has the average number of products of a given manufacturer per day.
Products that do not have a manufacturer ID number (producer_id = NULL) belong
qualify as "Other"(there is not 'Other' in producers table) and present in the statement.
All data will depend on date which is selected by user for example, user need statement from '2017-03-28' to '2017-03-30' or another example from '2017-03-29' to '2017-03-29'

I wrote this query. This is working fine but in my opinion is too long.

SELECT producers.producer_name AS producer,
CONCAT(ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = producers.producer_id AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') * 100 /
(SELECT COUNT(products.product_name) FROM products where products.product_date BETWEEN '2017-03-28' AND '2017-03-30')), '%') AS '% share',
ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = producers.producer_id AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') /
(SELECT COUNT(DISTINCT products.product_date) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')) AS 'day avg'

FROM products, producers
GROUP BY producers.producer_name
UNION

SELECT 'other' AS producer,
CONCAT(ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = 'null'AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') * 100 /
(select COUNT(products.product_name) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')), '%') AS '% share',
ROUND((SELECT COUNT(products.product_name) FROM products WHERE products.producer_id = 'null' AND products.product_date BETWEEN '2017-03-28' AND '2017-03-30') /
(SELECT COUNT(DISTINCT products.product_date) FROM products WHERE products.product_date BETWEEN '2017-03-28' AND '2017-03-30')) AS 'day avg'
FROM products

tables:

CREATE TABLE `products` (
`product_id` INT(11) NOT NULL AUTO_INCREMENT,
`product_date` DATE NOT NULL,
`producer_id` INT(11) NULL,
`product_url` VARCHAR(300) NOT NULL,
`product_name` VARCHAR(300) NOT NULL,
`product_price` DECIMAL(11,2) NULL DEFAULT NULL,
`product_price_old` DECIMAL(11,2) NULL DEFAULT NULL,
`product_reviews` INT(11) NULL DEFAULT NULL,
`product_rating` FLOAT NULL DEFAULT NULL,
PRIMARY KEY (`product_id`),
INDEX `product_date_producer_id` (`producer_id`, `product_date`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

CREATE TABLE `producers` (
`producer_id` INT(11) NOT NULL AUTO_INCREMENT,
`producer_name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`producer_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;


问:
Using deeplink to open an Android app on Xamarin
I'm implementing the deeplink function in Xamarin. The function didn't work as I expeceted.

If I click on a link in my Google Keep App it won't navigate to my app whent it on PAUSED mode (app is in the background). Instead, it open an Activity right in the Google Keep app. So, is there a away to resume my app after click on the deeplink on Keep Note app.

My current config on the HomeActivity.cs:

```<code>[IntentFilter(new[] { Intent.ActionView },
              Categories = new[] { Intent.CategoryBrowsable, Intent.CategoryDefault },
              DataScheme = "https",
              DataHost = "example",
              DataPathPrefix = "",
              AutoVerify = true)

        ]
public class HomeActivity : BaseActivity
{
 ...
}

</code>```

Body:
I'm implementing the deeplink function in Xamarin. The function didn't work as I expeceted.

If I click on a link in my Google Keep App it won't navigate to my app whent it on PAUSED mode (app is in the background). Instead, it open an Activity right in the Google Keep app. So, is there a away to resume my app after click on the deeplink on Keep Note app.

My current config on the HomeActivity.cs:

[IntentFilter(new[] { Intent.ActionView },
              Categories = new[] { Intent.CategoryBrowsable, Intent.CategoryDefault },
              DataScheme = "https",
              DataHost = "example",
              DataPathPrefix = "",
              AutoVerify = true)

        ]
public class HomeActivity : BaseActivity
{
 ...
}


问:
Trying to run a powershell command "get-counter" that has variables over a public-key auth SSH
I am trying to connect to a Windows machine using SSH (it has OpenSSH installed) and I am trying to get the CPU usage of all the processes, by using this command (it's pretty much an answer to another question, that I was trying out):

```<code>.\ssh user@0.0.0.0 powershell Get-Counter "'\Process(*)\% Processor Time'^| Select-Object -ExpandProperty countersamples^| Sort-Object -Property cookedvalue -Descending^| Select-Object -First 25^| ft InstanceName,CookedValue"
</code>```

After looking at a couple of questions, I learned that by over remote I needed to use escaped pipes, that was one problem cleared, but now I am trying to see if there is a way to add this:

```<code>ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize
</code>```

Now if I run :

```<code>Get-Counter '\Process(*)\% Processor Time'| Select-Object -ExpandProperty countersamples| Sort-Object -Property cookedvalue -Descending| Select-Object -First 25| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize
</code>```

I get all the values neatly represented locally. But if I try to run something like this over an SSH using public key auth:

```<code>.\ssh user@0.0.0.0 powershell Get-Counter "'\Process(*)\% Processor Time'^| Select-Object -ExpandProperty countersamples^| Sort-Object -Property cookedvalue -Descending^| Select-Object -First 25^| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize"
</code>```

The values related to the CPU don't appear at all (Edit: The command doesn't fail, just the column that is suppose to show the CPU values returns blank, if I run the very first command, I get the values still but not converted), and I am guessing that what I am doing is having issues using variables, as it's the only part of the command that doesn't seem to work properly.  I am thinking it may be the $_.Cookedvalue and $env:NUMBER_OF_PROCESSORS , and was wondering if there is a way around this?  I tried escaping the $ as well as quoting it but the values just seem to get lost.

Basically, I went piece by piece of the command testing it via the remote connection, as it has a slightly different format requirements as it starts on a CMD prompt (was unable to pipe, needed escaped pipes), I tried simply connecting first, then executing the command, but given it's being done via an automated script, it establishes the connection but instantly closes it, forcing me to use it as part of the connection command.  Simpler stuff works flawlessly, like creating/deleting files and moving around.

Body:
I am trying to connect to a Windows machine using SSH (it has OpenSSH installed) and I am trying to get the CPU usage of all the processes, by using this command (it's pretty much an answer to another question, that I was trying out):

.\ssh user@0.0.0.0 powershell Get-Counter "'\Process(*)\% Processor Time'^| Select-Object -ExpandProperty countersamples^| Sort-Object -Property cookedvalue -Descending^| Select-Object -First 25^| ft InstanceName,CookedValue"

After looking at a couple of questions, I learned that by over remote I needed to use escaped pipes, that was one problem cleared, but now I am trying to see if there is a way to add this:

ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize

Now if I run :

Get-Counter '\Process(*)\% Processor Time'| Select-Object -ExpandProperty countersamples| Sort-Object -Property cookedvalue -Descending| Select-Object -First 25| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize

I get all the values neatly represented locally. But if I try to run something like this over an SSH using public key auth:

.\ssh user@0.0.0.0 powershell Get-Counter "'\Process(*)\% Processor Time'^| Select-Object -ExpandProperty countersamples^| Sort-Object -Property cookedvalue -Descending^| Select-Object -First 25^| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize"

The values related to the CPU don't appear at all (Edit: The command doesn't fail, just the column that is suppose to show the CPU values returns blank, if I run the very first command, I get the values still but not converted), and I am guessing that what I am doing is having issues using variables, as it's the only part of the command that doesn't seem to work properly.  I am thinking it may be the $_.Cookedvalue and $env:NUMBER_OF_PROCESSORS , and was wondering if there is a way around this?  I tried escaping the $ as well as quoting it but the values just seem to get lost.

Basically, I went piece by piece of the command testing it via the remote connection, as it has a slightly different format requirements as it starts on a CMD prompt (was unable to pipe, needed escaped pipes), I tried simply connecting first, then executing the command, but given it's being done via an automated script, it establishes the connection but instantly closes it, forcing me to use it as part of the connection command.  Simpler stuff works flawlessly, like creating/deleting files and moving around.


问:
Postgresql 13.9 pg_dump 12.12 server version mismatch
While taking the backup of the postgressql database I am getting below issue

pg_dump -Fc -h localhost -U postgres -d <user> -f <filename>`
pg_dump: error: server version: 13.9; pg_dump version: 12.12 (Ubuntu 12.12-0ubuntu0.20.04.1)
pg_dump: error: aborting because of server version mismatch
```

Can anyone help me with this issue and help us to take the appropriate backup?

Body:
While taking the backup of the postgressql database I am getting below issue

pg_dump -Fc -h localhost -U postgres -d <user> -f <filename>`
pg_dump: error: server version: 13.9; pg_dump version: 12.12 (Ubuntu 12.12-0ubuntu0.20.04.1)
pg_dump: error: aborting because of server version mismatch

Can anyone help me with this issue and help us to take the appropriate backup?


问:
Reword a commit using its SHA1 that has been pushed
How can I reword a commit message that has been pushed using its SHA1 hash?

Assuming that I'm on branch feature/abc and it hasn't been merged into main yet.

But the commit has been pushed to the remote.


问:
Why does a variable not work in NGINX `grpc_pass'?
Does a variable not work in grpc_pass, why?
What i do wrong?

This works:

```<code>location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        grpc_pass grpcs://cdpkat-dev_webuidev;
        }
</code>```

This doesn't work:

```<code>location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=10s;
        set $grpcwebuidev grpcs://cdpkat-dev_webuidev;
        grpc_pass $grpcwebuidev;
        }
</code>```

and doesn't work:

```<code>location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=10s;
        set $grpcwebuidev cdpkat-dev_webuidev;
        grpc_pass grpcs://$grpcwebuidev;
        }
</code>```

I get exception in grpc client:

```<code> Grpc.Net.Client.Internal.GrpcCall[3]
  Call failed with gRPC error status. Status code: 'Unknown', Message: 'Bad gRPC response. HTTP status code: 500'.
</code>```

and i get exception in nginx log:

```<code>2022-12-29T08:22:20.908699753Z nginx-web_nginxwww.1.hr7hlwilgz93@mss-docker00.myorg.local    | 10.0.0.2 - - [29/Dec/2022:08:22:20 +0000] "POST /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags HTTP/2.0" 500 177
</code>```

"-" "grpc-dotnet/2.46.0 (.NET 6.0.8; CLR 6.0.8; net6.0; windows; x86)" "-"

using a variable in proxy_pass and grps_pass will prevent NGINX startup errors when the upstream is not available.
In FAQ Nginx say "You can use variables (1.17.8) in the parameter value. In this case, if the address is specified as a domain name, the name is searched among the server groups described, and if not found, is determined using resolver."
http://nginx.org/en/docs/http/ngx_http_grpc_module.html

Body:
Does a variable not work in grpc_pass, why?
What i do wrong?

This works:

location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        grpc_pass grpcs://cdpkat-dev_webuidev;
        }

This doesn't work:

location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=10s;
        set $grpcwebuidev grpcs://cdpkat-dev_webuidev;
        grpc_pass $grpcwebuidev;
        }

and doesn't work:

location /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=10s;
        set $grpcwebuidev cdpkat-dev_webuidev;
        grpc_pass grpcs://$grpcwebuidev;
        }

I get exception in grpc client:

 Grpc.Net.Client.Internal.GrpcCall[3]
  Call failed with gRPC error status. Status code: 'Unknown', Message: 'Bad gRPC response. HTTP status code: 500'.

and i get exception in nginx log:

2022-12-29T08:22:20.908699753Z nginx-web_nginxwww.1.hr7hlwilgz93@mss-docker00.myorg.local    | 10.0.0.2 - - [29/Dec/2022:08:22:20 +0000] "POST /App.ControlRoom.Api.Contract.ApiService/UpdateOpcDaTags HTTP/2.0" 500 177

"-" "grpc-dotnet/2.46.0 (.NET 6.0.8; CLR 6.0.8; net6.0; windows; x86)" "-"

using a variable in proxy_pass and grps_pass will prevent NGINX startup errors when the upstream is not available.
In FAQ Nginx say "You can use variables (1.17.8) in the parameter value. In this case, if the address is specified as a domain name, the name is searched among the server groups described, and if not found, is determined using resolver."
http://nginx.org/en/docs/http/ngx_http_grpc_module.html


问:
Zipping nested directories with duplicate file names using ZIP command

The Scenario:

I am trying to zip the output of a program which generates a lot many nested directories with image and csv files in it. I am trying to zip it using zip -rj 2022-12-29.zip 2022-12-29 on a linux cluster over GCP.

The Problem:

Follow the structure below:

```<code>2022-12-29/
|
|---L1/
|   |---foo/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|   |---bar/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|---L2/
|   |---foo/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|   |---bar/
|        |--- metric_graph_dec.png
|        |---daily/
|        |   |--- outcomes.csv
|        |   |--- sales.png
|        |---weekly/
|            |--- outcomes.csv
|            |--- sales.png
|
.
</code>```

likewise I have around 16 folders with such depth of folders. I tried to maintain the folder structure while zipping by using -j parameter in command, but it doesn't seem to be working that way. I received a warning before zipping and while zipping, I get

zip error: Invalid command arguments (cannot repeat names in zip file)

Expected output:

Either I need to maintain the folder structure in Zip file OR

Adding a prefix of the folder so as to create a unique name for each file. Something like L1_foo_metric_graph_dec.png and L1_bar_metric_graph_dec.png and then zip the files.

Body:
The Scenario:

I am trying to zip the output of a program which generates a lot many nested directories with image and csv files in it. I am trying to zip it using zip -rj 2022-12-29.zip 2022-12-29 on a linux cluster over GCP.

The Problem:

Follow the structure below:

2022-12-29/
|
|---L1/
|   |---foo/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|   |---bar/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|---L2/
|   |---foo/
|   |    |--- metric_graph_dec.png
|   |    |---daily/
|   |    |   |--- outcomes.csv
|   |    |   |--- sales.png
|   |    |---weekly/
|   |        |--- outcomes.csv
|   |        |--- sales.png
|   |---bar/
|        |--- metric_graph_dec.png
|        |---daily/
|        |   |--- outcomes.csv
|        |   |--- sales.png
|        |---weekly/
|            |--- outcomes.csv
|            |--- sales.png
|
.

likewise I have around 16 folders with such depth of folders. I tried to maintain the folder structure while zipping by using -j parameter in command, but it doesn't seem to be working that way. I received a warning before zipping and while zipping, I get

zip error: Invalid command arguments (cannot repeat names in zip file)

Expected output:

Either I need to maintain the folder structure in Zip file OR

Adding a prefix of the folder so as to create a unique name for each file. Something like L1_foo_metric_graph_dec.png and L1_bar_metric_graph_dec.png and then zip the files.


问:
I have an issue with refresh tokens in react
I have an issue with refresh tokens in react and I am using axios interceptors for calling refresh token I am recieving refresh token from flask APIs and the timer of refresh token is 30sec

This is the frontpage of login:
This is the login page;
After login I am recieving this data from the api:
data reacieved:  After 30sec I am recieving this error and I am not able to call refresh tokens again for getting data from api

This is my code:`
This is the code where I am creating axios instance and interceptors for req and res:

```<code>import axios from 'axios';

const instance = axios.create({
  baseURL: "http://192.168.18.63:5000",
  headers: { "Content-Type": "application/json" },
});

instance.interceptors.request.use(config => {
  const accessToken = localStorage.getItem('access_token');
  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`;
  }
  return config;
});

instance.interceptors.response.use(
  response => {
    return response;

  },
  error => {
    // If the access token is expired, try to refresh it
    if (error.response.data.status === 403 && error.response.data.msg === 'Access token expired') {
      const refreshToken = localStorage.getItem('refresh_token');
      // Send a request to the server to refresh the access token
      return instance
        .post('/AdminRefreshToken', {
          refresh_token: refreshToken,
        })
        .then(response => {
          // Save the new access token
          localStorage.setItem('access_token', response.data.access_token);
          // Retry the original request
          const config = error.config;
          config.headers.Authorization = `Bearer ${response.data.access_token}`;
          return instance(config);
        });
    }
    return Promise.reject(error);
  }
);

export default instance;`
</code>```

This is the code where I am fetching the data from axios instance:

```<code>import React, { useState, useEffect } from "react";
import Logout from "./logout";
import api from "./Services/Api";

function MyComponent() {
  const [data, setData] = useState("");
`your text`
  useEffect(() => {
    api
      .get("/AdminDetails")
      .then((response) => {
        console.log(response);
        setData(response.data.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return <>

    <div>
      <h4>email: {data.email}</h4>
      <h4>first Name: {data.firstname}</h4>
      <h4>last Name: {data.lastname}</h4>
      <h4>user Name: {data.username}</h4>
      <Logout/>
    </div>

  </>;
}

export default MyComponent;
</code>```

Body:
I have an issue with refresh tokens in react and I am using axios interceptors for calling refresh token I am recieving refresh token from flask APIs and the timer of refresh token is 30sec

This is the frontpage of login:
This is the login page;
After login I am recieving this data from the api:
data reacieved:  After 30sec I am recieving this error and I am not able to call refresh tokens again for getting data from api

This is my code:`
This is the code where I am creating axios instance and interceptors for req and res:

import axios from 'axios';

const instance = axios.create({
  baseURL: "http://192.168.18.63:5000",
  headers: { "Content-Type": "application/json" },
});

instance.interceptors.request.use(config => {
  const accessToken = localStorage.getItem('access_token');
  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`;
  }
  return config;
});

instance.interceptors.response.use(
  response => {
    return response;

  },
  error => {
    // If the access token is expired, try to refresh it
    if (error.response.data.status === 403 && error.response.data.msg === 'Access token expired') {
      const refreshToken = localStorage.getItem('refresh_token');
      // Send a request to the server to refresh the access token
      return instance
        .post('/AdminRefreshToken', {
          refresh_token: refreshToken,
        })
        .then(response => {
          // Save the new access token
          localStorage.setItem('access_token', response.data.access_token);
          // Retry the original request
          const config = error.config;
          config.headers.Authorization = `Bearer ${response.data.access_token}`;
          return instance(config);
        });
    }
    return Promise.reject(error);
  }
);

export default instance;`

This is the code where I am fetching the data from axios instance:

import React, { useState, useEffect } from "react";
import Logout from "./logout";
import api from "./Services/Api";

function MyComponent() {
  const [data, setData] = useState("");
`your text`
  useEffect(() => {
    api
      .get("/AdminDetails")
      .then((response) => {
        console.log(response);
        setData(response.data.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return <>

email: {data.email}

first Name: {data.firstname}

last Name: {data.lastname}

user Name: {data.username}

      <Logout/>

  </>;
}

export default MyComponent;


问:
Hide CMD After opening VScode from Run window in Windows
I am trying to hide CMD After opening VSCode from Run window in Windows and  don't work, I test those solutions

How to exit Command Prompt after launching VSCode

But it didn't work.


问:
Jest mock Typeorm Datasource in unit tests (without nestjs)
I am working on creating unit tests for a project that uses Typeorm without Nestjs. The file I am creating unit tests for uses queryRunner to start a transaction. My problem is, I am not able to mock the Datasource. I tried multiple ways but the mock is never getting called to replace the actual Datasource that has access to the postgresql database. I saw some solutions to mock it, but they all use Nestjs, which I don't use in my case.

The error I am having in the tests right now is:

```<code>    Received promise rejected instead of resolved
    Rejected to value: [TypeORMError: Driver not Connected]
</code>```

Any help would be highly appreciated since I'm not an expert in unit tests.

Here's an example of the code that I am having the issue with (replaced some names tho):

datasource.ts

```<code>//database config is defined in this file
export const datasource: DataSource = new DataSource(some_config);
</code>```

dummy.service.ts

```<code>export const dummyService = () => {
    //datasource is imported from the above file
    const queryRunner = datasource.createQueryRunner();
    await queryRunner.startTransaction();

    try {
      const foundObject = await queryRunner.manager.getRepository(MyObject).findOne({
        where: { id: someId },
        lock: { mode: 'pessimistic_write' },
      });
      //some more database calls
    } catch (error) {
      await queryRunner.rollbackTransaction();
    } finally {
      await queryRunner.release();
    }
}
</code>```

mock.datasource.ts

```<code>import { DataSource } from 'typeorm';

export const dataSourceMockFactory: () => MockType<DataSource> = jest.fn(
  () => ({
    createQueryRunner: jest.fn().mockImplementation(() => ({
      connect: jest.fn(),
      startTransaction: jest.fn(),
      release: jest.fn(),
      rollbackTransaction: jest.fn(),
      manager: {
        getRepository: jest.fn().mockImplementation(() => ({
          create: jest.fn(),
          findOne: jest.fn(() => {
            return getMyDummyObject();
          }),
        })),
        save: jest.fn(),
      },
    })),
  }),
);

export type MockType<T> = {
  // eslint-disable-next-line @typescript-eslint/ban-types
  [P in keyof T]?: jest.Mock<{}>;
};

</code>```

dummy.unit.test.ts

```<code>describe('dummy service test', () => {
  let dataSourceMock: MockType<Typeorm.DataSource>;

  beforeEach(async () => {

    // This method did not work
    jest.mock('typeorm', () => {
      const actual = jest.requireActual('typeorm');
      return {
        ...actual,
        DataSource: dataSourceMockFactory(),
      };
    });

    // The below method did not work either
    jest.mock('./../../db/datasource', () => ({
      datasource: dataSourceMockFactory(),
    }));
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should test dummy service with transaction', async () => {
    // getting an error here
    await expect(
      dummyFunction(),
    ).resolves.not.toThrow();
  });

});

</code>```

Body:
I am working on creating unit tests for a project that uses Typeorm without Nestjs. The file I am creating unit tests for uses queryRunner to start a transaction. My problem is, I am not able to mock the Datasource. I tried multiple ways but the mock is never getting called to replace the actual Datasource that has access to the postgresql database. I saw some solutions to mock it, but they all use Nestjs, which I don't use in my case.

The error I am having in the tests right now is:

    Received promise rejected instead of resolved
    Rejected to value: [TypeORMError: Driver not Connected]

Any help would be highly appreciated since I'm not an expert in unit tests.

Here's an example of the code that I am having the issue with (replaced some names tho):

datasource.ts

//database config is defined in this file
export const datasource: DataSource = new DataSource(some_config);

dummy.service.ts

export const dummyService = () => {
    //datasource is imported from the above file
    const queryRunner = datasource.createQueryRunner();
    await queryRunner.startTransaction();

    try {
      const foundObject = await queryRunner.manager.getRepository(MyObject).findOne({
        where: { id: someId },
        lock: { mode: 'pessimistic_write' },
      });
      //some more database calls
    } catch (error) {
      await queryRunner.rollbackTransaction();
    } finally {
      await queryRunner.release();
    }
}

mock.datasource.ts

import { DataSource } from 'typeorm';

export const dataSourceMockFactory: () => MockType<DataSource> = jest.fn(
  () => ({
    createQueryRunner: jest.fn().mockImplementation(() => ({
      connect: jest.fn(),
      startTransaction: jest.fn(),
      release: jest.fn(),
      rollbackTransaction: jest.fn(),
      manager: {
        getRepository: jest.fn().mockImplementation(() => ({
          create: jest.fn(),
          findOne: jest.fn(() => {
            return getMyDummyObject();
          }),
        })),
        save: jest.fn(),
      },
    })),
  }),
);

export type MockType<T> = {
  // eslint-disable-next-line @typescript-eslint/ban-types
  [P in keyof T]?: jest.Mock<{}>;
};

dummy.unit.test.ts

describe('dummy service test', () => {
  let dataSourceMock: MockType<Typeorm.DataSource>;

  beforeEach(async () => {

    // This method did not work
    jest.mock('typeorm', () => {
      const actual = jest.requireActual('typeorm');
      return {
        ...actual,
        DataSource: dataSourceMockFactory(),
      };
    });

    // The below method did not work either
    jest.mock('./../../db/datasource', () => ({
      datasource: dataSourceMockFactory(),
    }));
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should test dummy service with transaction', async () => {
    // getting an error here
    await expect(
      dummyFunction(),
    ).resolves.not.toThrow();
  });

});


问:
Error: could not handle the request comes up when I deploy firebase from my local
On firebase console, it says my files are successfully deployed but in actual web page, it is just a black page with one senetence "Error: could not handle the request"

i did not started this project i am working on, and i have no idea what to do.

BTW, no errors are loged in firebase-debug.log
All things are clear, except for the web page.

As far as i know, this is based on Next.js, if you would care to know.

I opened up the file from the root folder, used "cd (myfilename)" command to go into the actual project, and then executed firebase deploy.

I googled thousands of times, and I doubted these:

node js version problem?

os problem? (i work on Window, and the first start was from Mac)

number one i solved. number two? i dont know.

Please help me out if you have any idea or can guess why this happens.


问:
Automate deletion of Bots messages through CHECK CONSTRAIN or TRIGGER
I have been a few days trying to automate the deletion of annoying bot's messages in my web page. I have set Google recaptcha and they have slowed a lot, however, some bots still post messages and I'd like to automate something in my phpMyAdmin database to automate the deletion. In example: if they say 'buy my pills', I am trying to say: 'If my table has pills word in this column, delete the row.'

So far I have tried 2 methods in my table 'commentsmain' with no success:

TRIGGER (Just impedes every single message from being posted)

DELETE FROM commentsmain WHERE message LIKE '%pills%'
This is the whole trigger code: DROP TRIGGER IF EXISTS spamMain;CREATE DEFINER=u956484391_database@127.0.0.1 TRIGGER spamMain AFTER INSERT ON commentsmain FOR EACH ROW DELETE FROM commentsmain WHERE message LIKE '%HTTP%'

CHECK CONSTRAIN (Just say the code is incorrect)

a) ALTER TABLE commentsmain
ADD CHECK (message NOT LIKE '%pills%');

b) ADD CONSTRAINT checkHTTP CHECK (message NOT LIKE '%pills%');

I expect to automate the deletion of bots messages in my phpMyAdmin pages


问:
How can I go back from expo-web-browser
I am using the payment merchant where I need to give the return_url which will redirect the user back on the application

```<code> if (initiatePaymentResponse?.data?.response?.payment_url) {
    const url = initiatePaymentResponse?.data?.response?.payment_url
    WebBrowser.openBrowserAsync(url)
 }
</code>```

I want to close the browser and redirect back to the application when the user clicks on the given URL

Title: How can I go back from expo-web-browser

Body:
I am using the payment merchant where I need to give the return_url which will redirect the user back on the application

 if (initiatePaymentResponse?.data?.response?.payment_url) {
    const url = initiatePaymentResponse?.data?.response?.payment_url
    WebBrowser.openBrowserAsync(url)
 }

I want to close the browser and redirect back to the application when the user clicks on the given URL


问:
I'm getting Runtime Error when submitting answer to online judge. What could be the cause?
Link to the problem : https://vjudge.net/problem/UVA-1665

This is my code so far it works on my end with the sample input provided by the problem statement, i already tried to change the class name from class problemb to public class Main as someone else did with a similar issue but no luck. Any help would be appreciated.

```<code>import java.io.BufferedReader;
import java.io.InputStreamReader;

class problemb {
  static int dx[] = {-1, 0, 1, 0};
  static int dy[] = {0, 1, 0, -1};

  static int[][] map;
  static boolean[][] visited;

  static int n, m;
  static int t;
  static int[] years;

  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int z = Integer.parseInt(br.readLine());

    for (int i = 0; i < z; i++) {
      String[] nm = br.readLine().split(" ");
      n = Integer.parseInt(nm[0]);
      m = Integer.parseInt(nm[1]);

      map = new int[n][m];
      visited = new boolean[n][m];

      for (int j = 0; j < n; j++) {
        String[] row = br.readLine().split(" ");
        for (int k = 0; k < m; k++) {
          map[j][k] = Integer.parseInt(row[k]);
        }
      }

      t = Integer.parseInt(br.readLine());
      years = new int[t];

      String[] tValues = br.readLine().split(" ");
      for (int j = 0; j < t; j++) {
        years[j] = Integer.parseInt(tValues[j]);
      }
      br.close();

      int[] results = new int[t];

      for (int j = 0; j < t; j++) {
        int year = years[j];
        int areas = 0;

        // Reset the visited array for the current year
        visited = new boolean[n][m];

        for (int y = 0; y < n; y++) {
          for (int x = 0; x < m; x++) {
            if (!visited[y][x] && map[y][x] > year) {
              areas++;
              bfs(y, x, year);
            }
          }
        }

        results[j] = areas;
      }

      for (int j = 0; j < results.length; j++) {
        System.out.print(results[j]);
        if (j < results.length - 1) {
          System.out.print(" ");
        }
      }
      System.out.println();
    }
  }
  static void bfs(int y, int x, int year) {
    int[][] queue = new int[n * m][2];
    int head = 0, tail = 0;
    queue[tail][0] = y;
    queue[tail][1] = x;
    tail++;
    visited[y][x] = true;

    while (head < tail) {
      int yy = queue[head][0];
      int xx = queue[head][1];
      head++;

      for (int i = 0; i < 4; i++) {
        int ny = yy + dy[i];
        int nx = xx + dx[i];

        if (ny < 0 || ny >= n || nx < 0 || nx >= m || visited[ny][nx] || map[ny][nx] <= year) {
          continue;
        }

        visited[ny][nx] = true;
        queue[tail][0] = ny;
        queue[tail][1] = nx;
        tail++;
      }
    }
  }
}
</code>```

Body:
Link to the problem : https://vjudge.net/problem/UVA-1665

This is my code so far it works on my end with the sample input provided by the problem statement, i already tried to change the class name from class problemb to public class Main as someone else did with a similar issue but no luck. Any help would be appreciated.

import java.io.BufferedReader;
import java.io.InputStreamReader;

class problemb {
  static int dx[] = {-1, 0, 1, 0};
  static int dy[] = {0, 1, 0, -1};

  static int[][] map;
  static boolean[][] visited;

  static int n, m;
  static int t;
  static int[] years;

  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int z = Integer.parseInt(br.readLine());

    for (int i = 0; i < z; i++) {
      String[] nm = br.readLine().split(" ");
      n = Integer.parseInt(nm[0]);
      m = Integer.parseInt(nm[1]);

      map = new int[n][m];
      visited = new boolean[n][m];

      for (int j = 0; j < n; j++) {
        String[] row = br.readLine().split(" ");
        for (int k = 0; k < m; k++) {
          map[j][k] = Integer.parseInt(row[k]);
        }
      }

      t = Integer.parseInt(br.readLine());
      years = new int[t];

      String[] tValues = br.readLine().split(" ");
      for (int j = 0; j < t; j++) {
        years[j] = Integer.parseInt(tValues[j]);
      }
      br.close();

      int[] results = new int[t];

      for (int j = 0; j < t; j++) {
        int year = years[j];
        int areas = 0;

        // Reset the visited array for the current year
        visited = new boolean[n][m];

        for (int y = 0; y < n; y++) {
          for (int x = 0; x < m; x++) {
            if (!visited[y][x] && map[y][x] > year) {
              areas++;
              bfs(y, x, year);
            }
          }
        }

        results[j] = areas;
      }

      for (int j = 0; j < results.length; j++) {
        System.out.print(results[j]);
        if (j < results.length - 1) {
          System.out.print(" ");
        }
      }
      System.out.println();
    }
  }
  static void bfs(int y, int x, int year) {
    int[][] queue = new int[n * m][2];
    int head = 0, tail = 0;
    queue[tail][0] = y;
    queue[tail][1] = x;
    tail++;
    visited[y][x] = true;

    while (head < tail) {
      int yy = queue[head][0];
      int xx = queue[head][1];
      head++;

      for (int i = 0; i < 4; i++) {
        int ny = yy + dy[i];
        int nx = xx + dx[i];

        if (ny < 0 || ny >= n || nx < 0 || nx >= m || visited[ny][nx] || map[ny][nx] <= year) {
          continue;
        }

        visited[ny][nx] = true;
        queue[tail][0] = ny;
        queue[tail][1] = nx;
        tail++;
      }
    }
  }
}


问:
E/GooglePlayServicesUtil( 7963): GooglePlayServices not available due to error 9, FLUTTER, FIREBASE (I tried in my physical phone and it doesnt work)
```<code>class ProfileScreen extends StatefulWidget {
  final String documentId;

  const ProfileScreen({super.key, required this.documentId});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {

  CollectionReference customers =
  FirebaseFirestore.instance.collection('customers');

@override
  Widget build(BuildContext context) {

 return FutureBuilder<DocumentSnapshot>(

  future: customers.doc(widget.documentId).get(),
  builder:
      (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (snapshot.hasError) {
      return const  Text("Something went wrong");
    }

    if (snapshot.hasData && !snapshot.data!.exists) {
      return const Text("Document does not exist");
    }

    if (snapshot.connectionState == ConnectionState.done) {
      Map<String, dynamic> data =
          snapshot.data!.data() as Map<String, dynamic>;
      return /* Text("Full Name: ${data['full_name']} ${data['last_name']}"); */

          Scaffold(
        backgroundColor: Colors.grey.shade300,
        body: Stack(
          children: [
            Container(
              decoration: const BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xff4A506A), Color(0xffF3BC85)])),

</code>```

I builted the app and I installed in my phone and the problem keep , Im sure  that the problem is in the code

Body:
class ProfileScreen extends StatefulWidget {
  final String documentId;

  const ProfileScreen({super.key, required this.documentId});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {

  CollectionReference customers =
  FirebaseFirestore.instance.collection('customers');

@override
  Widget build(BuildContext context) {

 return FutureBuilder<DocumentSnapshot>(

  future: customers.doc(widget.documentId).get(),
  builder:
      (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (snapshot.hasError) {
      return const  Text("Something went wrong");
    }

    if (snapshot.hasData && !snapshot.data!.exists) {
      return const Text("Document does not exist");
    }

    if (snapshot.connectionState == ConnectionState.done) {
      Map<String, dynamic> data =
          snapshot.data!.data() as Map<String, dynamic>;
      return /* Text("Full Name: ${data['full_name']} ${data['last_name']}"); */

          Scaffold(
        backgroundColor: Colors.grey.shade300,
        body: Stack(
          children: [
            Container(
              decoration: const BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xff4A506A), Color(0xffF3BC85)])),

I builted the app and I installed in my phone and the problem keep , Im sure  that the problem is in the code


问:
Trying to implement swiftui preview on uikit project
Why my preview crashes when I apply this code at the bottom of my viewController?
I am on iMac M1. Is it something related to M1? Because I copied the exact code from the tutorial on YouTube.</p>
```<code>import UIKit

final class ViewController: UIViewController {

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .systemBlue
        button.setTitle("Button", for: .normal)
        view.addSubview(button)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }
}

#if canImport(SwiftUI) && DEBUG
import SwiftUI
struct UIViewControllerPreview<ViewController: UIViewController>: UIViewControllerRepresentable {
    let viewController: ViewController

    init(_ builder: @escaping () -> ViewController) {
        viewController = builder()
    }

    // MARK: - UIViewControllerRepresentable
    func makeUIViewController(context: Context) -> ViewController {
        viewController
    }

    func updateUIViewController(_ uiViewController: ViewController, context: UIViewControllerRepresentableContext<UIViewControllerPreview<ViewController>>) {
        return
    }
}
#endif

#if canImport(SwiftUI) && DEBUG
import SwiftUI

let deviceNames: [String] = [
    "iPhone SE",
    "iPhone 11 Pro Max",
    "iPad Pro (11-inch)"
]

@available(iOS 13.0, *)
struct ViewController_Preview: PreviewProvider {
  static var previews: some View {
    ForEach(deviceNames, id: \.self) { deviceName in
      UIViewControllerPreview {
        ViewController()
      }.previewDevice(PreviewDevice(rawValue: deviceName))
        .previewDisplayName(deviceName)
    }
  }
}
#endif
</code>```

Body:
Why my preview crashes when I apply this code at the bottom of my viewController?
I am on iMac M1. Is it something related to M1? Because I copied the exact code from the tutorial on YouTube.

import UIKit

final class ViewController: UIViewController {

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .systemBlue
        button.setTitle("Button", for: .normal)
        view.addSubview(button)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }
}

#if canImport(SwiftUI) && DEBUG
import SwiftUI
struct UIViewControllerPreview<ViewController: UIViewController>: UIViewControllerRepresentable {
    let viewController: ViewController

    init(_ builder: @escaping () -> ViewController) {
        viewController = builder()
    }

    // MARK: - UIViewControllerRepresentable
    func makeUIViewController(context: Context) -> ViewController {
        viewController
    }

    func updateUIViewController(_ uiViewController: ViewController, context: UIViewControllerRepresentableContext<UIViewControllerPreview<ViewController>>) {
        return
    }
}
#endif

#if canImport(SwiftUI) && DEBUG
import SwiftUI

let deviceNames: [String] = [
    "iPhone SE",
    "iPhone 11 Pro Max",
    "iPad Pro (11-inch)"
]

@available(iOS 13.0, *)
struct ViewController_Preview: PreviewProvider {
  static var previews: some View {
    ForEach(deviceNames, id: \.self) { deviceName in
      UIViewControllerPreview {
        ViewController()
      }.previewDevice(PreviewDevice(rawValue: deviceName))
        .previewDisplayName(deviceName)
    }
  }
}
#endif


问:
how to integrate an angular bundle/build to a another app
I would like to integrate a build/bundle files of an app to use in a another angular app. is possible to implement on that way?

Sample:
App A - in bundles
App B - will use App A in bundles

solution and idea in my existing issue


问:
How do I sync data between PostgreSQL and Elasticsearch using kibana in nodejs?
Ultimately I want to have a scalable search engine solution for the data in PostgreSql. I want to connect postgreSQL and elasticsearch data. My finding points me towards using Logstash or docker to  write events from Postgres to ElasticSearch, however I have not found a usable solution.

I want a scalable solution for that i hope you guys share your comments on this and give me some clues to proceed further.


问:
Android Listen Mute Events on a VoIP Call
I'm developing a voip call app via Android Telecom framework. I have a self-managed ConnectionService class.
On a voip call, my smartwatch sends a mute signal but could not find how to listen this event.
I’m looking forward to hearing from you, best regards

I could not find a useful method on the documentation


问:
Anchor tag is not getting clicked when using with Area - ASP.NET CORE MVC
I have toolbar in my project. Suddenly list items are not being clicked on it since I have added area in project and moved controllers and views in respective folders.

Home and Category are not clickable. This is my code in _Layout.cshtml

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RegistrationApp</title>
    <link rel="stylesheet" href="~/css/BoostwatchTheme.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/RegistrationApp.styles.css" asp-append-version="true" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
</head>
<body>

    <header>
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">Navbar</a>

                <div class="collapse navbar-collapse" id="navbarColor02">

                    <ul class="navbar-nav me-auto">

                        <li class="nav-item">
                            <a class="nav-link" asp-area="Customer" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">

                            <a class="nav-link" asp-area="Admin" asp-controller="Category" asp-action="Index">Category</a>
                        </li>
                    </ul>

                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>
</code>```

This is _ViewImports.cshtml which is there in the both areas folder Admin and Category

```<code>@using RegistrationApp
@using RegistrationApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</code>```

This is my project structure

These two Home and Category options are not getting clicked

How can I fix this issue ?

Body:
I have toolbar in my project. Suddenly list items are not being clicked on it since I have added area in project and moved controllers and views in respective folders.

Home and Category are not clickable. This is my code in _Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RegistrationApp</title>
    <link rel="stylesheet" href="~/css/BoostwatchTheme.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/RegistrationApp.styles.css" asp-append-version="true" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />

                Navbar

                            Home

                            Category

            @RenderBody()

    @await RenderSectionAsync("Scripts", required: false)

This is _ViewImports.cshtml which is there in the both areas folder Admin and Category

@using RegistrationApp
@using RegistrationApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

This is my project structure

These two Home and Category options are not getting clicked

How can I fix this issue ?


问:
Shift between anaconda and miniconda
I have both conda environments: anaconda3 and miniconda.
How can I use both interchangeably? Now if I create a new environment it will be created in miniconda, but I wanted to create a new environment in anaconda3 only.

```<code># conda environments:

                     /home/name/anaconda3
                     /home/name/anaconda3/envs/Flask_Prac
                     /home/name/anaconda3/envs/new_git
base                     /home/name/miniconda3
cling                    /home/name/miniconda3/envs/cling
image_captioning      *  /home/name/miniconda3/envs/image_captioning
</code>```

Here the image captioning environment I tried to create by using
conda create -n image_camptioning
but its getting created in miniconda and some of the packages are not supporting.

Title: Shift between anaconda and miniconda

Body:
I have both conda environments: anaconda3 and miniconda.
How can I use both interchangeably? Now if I create a new environment it will be created in miniconda, but I wanted to create a new environment in anaconda3 only.

# conda environments:

                     /home/name/anaconda3
                     /home/name/anaconda3/envs/Flask_Prac
                     /home/name/anaconda3/envs/new_git
base                     /home/name/miniconda3
cling                    /home/name/miniconda3/envs/cling
image_captioning      *  /home/name/miniconda3/envs/image_captioning

Here the image captioning environment I tried to create by using
conda create -n image_camptioning
but its getting created in miniconda and some of the packages are not supporting.


问:
Kafka headers are not converted in batch-mode with Spring Cloud 3.0
My question is coming from this discussion: https://stackoverflow.com/a/74306116/3551820

I've added the proper configurations to enable batching consumption but Spring still doesn't work with batch converter to convert the headers of each message (kafka_batchConvertedHeaders).

```<code>  @StreamListener(
    target = "command-my-setup-input-channel"
  )
  public void handleMySetup(Message<List<MySetupDTO>> messages) {
    //here Headers are arriving as bytes[]
    List<?> batchHeaders = messages.getHeaders().get(KafkaHeaders.BATCH_CONVERTED_HEADERS, List.class);
    log.warn("Messages received: {}", messages.getPayload().size()); //size of 2
</code>```

The bean responsible to convert:

```<code>@Bean("batchConverter")
BatchMessageConverter batchConverter(KafkaHeaderMapper kafkaHeaderMapperCustom) {
    BatchMessagingMessageConverter batchConv = new BatchMessagingMessageConverter();
    batchConv.setHeaderMapper(kafkaHeaderMapperCustom);
    return batchConv;
}
</code>```

The configurations below:

```<code>spring.cloud.stream:
  kafka:
    binder:
      autoCreateTopics: true
      autoAddPartitions: true
      healthTimeout: 10
      requiredAcks: 1
      minPartitionCount: 1
      replicationFactor: 1
      headerMapperBeanName: customHeaderMapper
    bindings:
      command-my-setup-input-channel:
        consumer:
          autoCommitOffset: false
          batch-mode: true # enabling batch-mode
          startOffset: earliest
          resetOffsets: true
          converter-bean-name: batchConverter # bean mapping
          ackMode: manual
          configuration:
            heartbeat.interval.ms: 1000
            max.poll.records: 2
            max.poll.interval.ms: 890000
            value.deserializer: com.xpto.MySetupDTODeserializer
  bindings:
    command-my-setup-input-channel:
      destination: command.my.setup
      content-type: application/json
      binder: kafka
      configuration:
        value:
          deserializer: com.xpto.MySetupDTODeserializer
      consumer:
        batch-mode: true
        startOffset: earliest
        resetOffsets: true
</code>```

Error:

```<code>Bean named 'batchConverter' is expected to be of type 'org.springframework.kafka.support.converter.MessagingMessageConverter' but was actually of type 'org.springframework.kafka.support.converter.BatchMessagingMessageConverter'
</code>```

Version: spring-cloud-stream 3.0.12.RELEASE

Body:
My question is coming from this discussion: https://stackoverflow.com/a/74306116/3551820

I've added the proper configurations to enable batching consumption but Spring still doesn't work with batch converter to convert the headers of each message (kafka_batchConvertedHeaders).

  @StreamListener(
    target = "command-my-setup-input-channel"
  )
  public void handleMySetup(Message<List<MySetupDTO>> messages) {
    //here Headers are arriving as bytes[]
    List<?> batchHeaders = messages.getHeaders().get(KafkaHeaders.BATCH_CONVERTED_HEADERS, List.class);
    log.warn("Messages received: {}", messages.getPayload().size()); //size of 2

The bean responsible to convert:

@Bean("batchConverter")
BatchMessageConverter batchConverter(KafkaHeaderMapper kafkaHeaderMapperCustom) {
    BatchMessagingMessageConverter batchConv = new BatchMessagingMessageConverter();
    batchConv.setHeaderMapper(kafkaHeaderMapperCustom);
    return batchConv;
}

The configurations below:

spring.cloud.stream:
  kafka:
    binder:
      autoCreateTopics: true
      autoAddPartitions: true
      healthTimeout: 10
      requiredAcks: 1
      minPartitionCount: 1
      replicationFactor: 1
      headerMapperBeanName: customHeaderMapper
    bindings:
      command-my-setup-input-channel:
        consumer:
          autoCommitOffset: false
          batch-mode: true # enabling batch-mode
          startOffset: earliest
          resetOffsets: true
          converter-bean-name: batchConverter # bean mapping
          ackMode: manual
          configuration:
            heartbeat.interval.ms: 1000
            max.poll.records: 2
            max.poll.interval.ms: 890000
            value.deserializer: com.xpto.MySetupDTODeserializer
  bindings:
    command-my-setup-input-channel:
      destination: command.my.setup
      content-type: application/json
      binder: kafka
      configuration:
        value:
          deserializer: com.xpto.MySetupDTODeserializer
      consumer:
        batch-mode: true
        startOffset: earliest
        resetOffsets: true

Error:

Bean named 'batchConverter' is expected to be of type 'org.springframework.kafka.support.converter.MessagingMessageConverter' but was actually of type 'org.springframework.kafka.support.converter.BatchMessagingMessageConverter'

Version: spring-cloud-stream 3.0.12.RELEASE


问:
Start Springboot without any Undertow Configuration
I have a project which mixes 2 dependencies:

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-installed-adapter</artifactId>
            <version>11.0.2</version>
        </dependency>
</code>```

I'm getting a transitiv dependency for Undertow, which comes from

```<code>keycloak-installed-adapter
</code>```

As far as I understood, Undertow is used internally within the KeyCloak libraries.

I don't want my Springboot Application to start with Undertow, nor I want that anything related with Undertow gets configured at Springboot level.

I can't find to completely exclude any Undertow configuration for Springboot. Does anyone have an idea?

Update

I now have the following:

```<code>@SpringBootApplication
@EnableAutoConfiguration(exclude = {EmbeddedUndertow.class})
public class SpringbootTest {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootTest.class, args);
    }
}
</code>```

But i'm getting following exception when starting my service:

```<code>org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory]: Factory method 'undertowEmbeddedServletContainerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/undertow/servlet/api/SessionPersistenceManager
</code>```

Knowing that the EmbeddedUndertow Class lokks like:

```<code>   @Configuration
   @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
   @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
   public static class EmbeddedUndertow {

    @Bean
    public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
        return new UndertowEmbeddedServletContainerFactory();
    }

}
</code>```

How would you ignore this calss from the scanning?

Body:
I have a project which mixes 2 dependencies:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-installed-adapter</artifactId>
            <version>11.0.2</version>
        </dependency>

I'm getting a transitiv dependency for Undertow, which comes from

keycloak-installed-adapter

As far as I understood, Undertow is used internally within the KeyCloak libraries.

I don't want my Springboot Application to start with Undertow, nor I want that anything related with Undertow gets configured at Springboot level.

I can't find to completely exclude any Undertow configuration for Springboot. Does anyone have an idea?

Update

I now have the following:

@SpringBootApplication
@EnableAutoConfiguration(exclude = {EmbeddedUndertow.class})
public class SpringbootTest {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootTest.class, args);
    }
}

But i'm getting following exception when starting my service:

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory]: Factory method 'undertowEmbeddedServletContainerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/undertow/servlet/api/SessionPersistenceManager

Knowing that the EmbeddedUndertow Class lokks like:

   @Configuration
   @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
   @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
   public static class EmbeddedUndertow {

    @Bean
    public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
        return new UndertowEmbeddedServletContainerFactory();
    }

}

How would you ignore this calss from the scanning?


问:
JS/CSS Animate Nav Indicator
I have to build a small interesting navigation using ReactJs & Tailwind. Everything is almost done except animating an indicator when changing a position.
So everything is associated with an absolute position indicator, so I will only share information about it.

So it has 2 states (in order to dynamically define the position and width of the menu item):

```<code>const [indicatorWidth, setIndicatorWidth] = useState('');
const [indicatorPosition, setIndicatorPosition] = useState('');
</code>```

and selecting menu items like:

```<code>const items: any = document.querySelectorAll(".menuItem");
</code>```

So, in order to select a link from navigation, I have a click event on the link:

```<code>onClick={() => setActiveNav(i)}
</code>```

And here is the function that will make it work:

```<code>const setActiveNav = async (index: number) => {
        if (items[index]) {
            setActive(index)
            await new Promise(r => setTimeout(r, 0));
            setIndicatorPosition(items[index].offsetLeft)
            setIndicatorWidth(items[index].offsetWidth)
        }
    }
</code>```

So at that point, only thing to define is style of the indicator like:

```<code><span className={`nav-indicator`} style={{width: indicatorWidth, left: indicatorPosition}}/>
</code>```

And to make it beautiful:

```<code>.nav-indicator{
  position: absolute;
  background: linear-gradient(90deg, #F27261 0%, #A63121 100%);
  box-shadow: 0 0 300px 24px rgba(225, 63, 50, 0.6);
  border-radius: 80px;
  top: 0.70rem;
  height: 70%;
  transition: ease-in-out 0.3s;
}
</code>```

So the problem comes in the end... I'm managing to animate the transition between changing the navigation. I should only make it to rotate it a bit before finalizing the select.
Should I use before and after? What would be the best way here?

Title: JS/CSS Animate Nav Indicator

Body:
I have to build a small interesting navigation using ReactJs & Tailwind. Everything is almost done except animating an indicator when changing a position.
So everything is associated with an absolute position indicator, so I will only share information about it.

So it has 2 states (in order to dynamically define the position and width of the menu item):

const [indicatorWidth, setIndicatorWidth] = useState('');
const [indicatorPosition, setIndicatorPosition] = useState('');

and selecting menu items like:

const items: any = document.querySelectorAll(".menuItem");

So, in order to select a link from navigation, I have a click event on the link:

onClick={() => setActiveNav(i)}

And here is the function that will make it work:

const setActiveNav = async (index: number) => {
        if (items[index]) {
            setActive(index)
            await new Promise(r => setTimeout(r, 0));
            setIndicatorPosition(items[index].offsetLeft)
            setIndicatorWidth(items[index].offsetWidth)
        }
    }

So at that point, only thing to define is style of the indicator like:

<span className={`nav-indicator`} style={{width: indicatorWidth, left: indicatorPosition}}/>

And to make it beautiful:

.nav-indicator{
  position: absolute;
  background: linear-gradient(90deg, #F27261 0%, #A63121 100%);
  box-shadow: 0 0 300px 24px rgba(225, 63, 50, 0.6);
  border-radius: 80px;
  top: 0.70rem;
  height: 70%;
  transition: ease-in-out 0.3s;
}

So the problem comes in the end... I'm managing to animate the transition between changing the navigation. I should only make it to rotate it a bit before finalizing the select.
Should I use before and after? What would be the best way here?


问:
Unable to connect to sts endpoint url
I have setup EKS cluster and have configured the OIDC. I have then created the IAM role with the below trust relationship

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::<account-id>:oidc-provider/oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195:sub": "system:serviceaccount:default:aws-test",
                    "oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195:aud": "sts.amazonaws.com"
                }
            }
        }
    ]
}
</code>```

When I use the service account in the pod, and from within the Pod, when I run the aws s3 ls, I am getting the below error:

Could not connect to the endpoint URL: "https://sts.ap-south-1.amazonaws.com/"

How to troubleshoot this error

Title: Unable to connect to sts endpoint url

Body:
I have setup EKS cluster and have configured the OIDC. I have then created the IAM role with the below trust relationship

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::<account-id>:oidc-provider/oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195:sub": "system:serviceaccount:default:aws-test",
                    "oidc.eks.ap-south-1.amazonaws.com/id/55A76A4197643C67E88FD47738722195:aud": "sts.amazonaws.com"
                }
            }
        }
    ]
}

When I use the service account in the pod, and from within the Pod, when I run the aws s3 ls, I am getting the below error:

Could not connect to the endpoint URL: "https://sts.ap-south-1.amazonaws.com/"

How to troubleshoot this error


问:
Vue 2 Router - how to copy custom hashparams from previous page in history mode
I open my project locally like this

http://localhost/#{"id":5}

but once I navigate somewhere via router-link the /#{"id":5} disapears from URL and I am left with something like this

http://localhost/page

but I would like it to be like

http://localhost/page/#{"id":5}

These ARE NOT params provided by vue router, but custom "global" params that our team utilizes.
Basically I want whatever was provided after the hashtag to be copied over to whenever I navigate with router but I can't wrap my head around Router.afterEach and modifying window.location.href directly leads to all sorts of disaster

Note that these are not vue router params, but basically custom text, I DO have routes WITH params like http://localhost/page/1/#{"id":5} and it works just fine so all I need is to copy my own json at the end of the link and paste it to next route somehow.


问:
How to use RemoteMediator while loading from a local cache?
I am implementing a use-case where I am using Paging library to load a list of Books from my remote api. The remote api gives a list of Books for a particular page number.I am adding a simple local cache using a Map data structure to cache the list so that if the List for a particular page is already present in the cache we don't do a remote api call. If the List of Books for a particular page in not present in the cache we do a remote api request using my Repository implementation as given below. For the time being I am not handling cache invalidation

The components of my implementation is as follows,

A model class for Book

data class Book(val name: String, val imageUrl: String)

A RemoteMediator to load data from remote api. It is responsible for loading List from remote api and save it in local cache.

class BookRemoteMediator(val remoteRepository: Repository) : RemoteMediator<Int, Book>{
override suspend fun load(loadType: LoadType, state: PagingState<Int, Book>): MediatorResult {

```<code> }
</code>```

}

class Repository(val apiClient: ApiClient){

```<code>suspend fun doRequest(page : Int) : List<Book>{
  //Get data from remote using apiClient
}
</code>```

}

PagingSource to load data from local cache.

class LocalCache(){
val cache: Map<Int, List> = mutableMapOf()

fun addToCache(page : Int, books : List){
cache.put(page, books)
}

fun getFromCache(int page){
cache.get(page)
}

}

class BookPagingSource(val cache : LocalCache): PagingSource<Int, Book>(){
override fun getRefreshKey(state: PagingState<Int, String>): Int? {
TODO("Not yet implemented")
}

```<code> override suspend fun load(params: PagingSource.LoadParams<Int>): PagingSource.LoadResult<Int, Book> {
</code>```

//Get data from cache here
}

}

A Pager instance which returns a flow.

val pager: Flow<PagingData> =
Pager(PagingConfig(pageSize = 20), initialKey = 0, pagingSourceFactory = {

```<code>         BookPagingSource(cache)
     }, remoteMediator = BookRemoteMediator()).flow
</code>```

How do my PagingSource trigger to load List from RemoteMediator in this case?
What should I return from load methods of RemoteMediator and PagingSource?

Body:
I am implementing a use-case where I am using Paging library to load a list of Books from my remote api. The remote api gives a list of Books for a particular page number.I am adding a simple local cache using a Map data structure to cache the list so that if the List for a particular page is already present in the cache we don't do a remote api call. If the List of Books for a particular page in not present in the cache we do a remote api request using my Repository implementation as given below. For the time being I am not handling cache invalidation

The components of my implementation is as follows,

A model class for Book

data class Book(val name: String, val imageUrl: String)

A RemoteMediator to load data from remote api. It is responsible for loading List from remote api and save it in local cache.

class BookRemoteMediator(val remoteRepository: Repository) : RemoteMediator<Int, Book>{
override suspend fun load(loadType: LoadType, state: PagingState<Int, Book>): MediatorResult {

 }

}

class Repository(val apiClient: ApiClient){

suspend fun doRequest(page : Int) : List<Book>{
  //Get data from remote using apiClient
}

}

PagingSource to load data from local cache.

class LocalCache(){
val cache: Map<Int, List> = mutableMapOf()

fun addToCache(page : Int, books : List){
cache.put(page, books)
}

fun getFromCache(int page){
cache.get(page)
}

}

class BookPagingSource(val cache : LocalCache): PagingSource<Int, Book>(){
override fun getRefreshKey(state: PagingState<Int, String>): Int? {
TODO("Not yet implemented")
}

 override suspend fun load(params: PagingSource.LoadParams<Int>): PagingSource.LoadResult<Int, Book> {

//Get data from cache here
}

}

A Pager instance which returns a flow.

val pager: Flow<PagingData> =
Pager(PagingConfig(pageSize = 20), initialKey = 0, pagingSourceFactory = {

         BookPagingSource(cache)
     }, remoteMediator = BookRemoteMediator()).flow

How do my PagingSource trigger to load List from RemoteMediator in this case?
What should I return from load methods of RemoteMediator and PagingSource?


问:
Laravel - Upsert with Case Sensitive Search Field
I'm using Laravel to synchronise a set of third-party data that has an ID of a case-sensitive column.

I'm using Laravel's Model::upsert($data, ['third_party_id'], ['field1', 'field2']) method to update this all and it's working except for the fact that it's case insensive, so it's not putting in a good portion of the data.

Is there any way around this, using MySQL?


问:
Script issue creating mailbox in exchange management shell
I'm running a script in exchange management shell, using variables to output a command for creating user email accounts. Write-Host does a nice job showing the command string in the management shell, but of course does not execute it.   I've had success using Invoke-Expression followed by a variable representing a string using commandlets such as New-Addresslists and New-Accepteddomain, but when using Invoke-Expression with a variable containing the New-Mailbox commandlet, I get error messages.  How do I properly run a variable string from scripts specifically into the exchange management shell to create user email accounts?

Powershell / Exchange 2019

```<code> $COMMAND = "New-Mailbox -Name $CustomerFirstName $CustomerLastName$ -UserPrincipalName $EmailPrefix@$CustomerDomainName -Password (ConvertTo-SecureString -String '$CustomerMailPassword' -AsPlainText -Force) -FirstName $CustomerFirstName -LastName $CustomerLastName"

  Invoke-Expression $COMMAND

</code>```

Body:
I'm running a script in exchange management shell, using variables to output a command for creating user email accounts. Write-Host does a nice job showing the command string in the management shell, but of course does not execute it.   I've had success using Invoke-Expression followed by a variable representing a string using commandlets such as New-Addresslists and New-Accepteddomain, but when using Invoke-Expression with a variable containing the New-Mailbox commandlet, I get error messages.  How do I properly run a variable string from scripts specifically into the exchange management shell to create user email accounts?

Powershell / Exchange 2019

 $COMMAND = "New-Mailbox -Name $CustomerFirstName $CustomerLastName$ -UserPrincipalName $EmailPrefix@$CustomerDomainName -Password (ConvertTo-SecureString -String '$CustomerMailPassword' -AsPlainText -Force) -FirstName $CustomerFirstName -LastName $CustomerLastName"

  Invoke-Expression $COMMAND


问:
authenticate user to windows and get windows username
User entering username and password for login in project. But customer want passwordless login with windows authenticated for every employee. I changed authentication mode from anonymous authentication to windows authentication. Now required windows authenticated before the application run.But entering the windows credential same username and password every time, which containing project published in iis.

Question 1. How i do required only client windows username and password in windows authentication?

Assuming i used client windows username and password for authentication. IsAuthenticated = true;

Here my new question.

Question 2. How i do catch client windows username?

Now use 2 different way for catch windows username.

Way 1.

```<code>
var name = _username.HttpContext.User.Identity.Name;

            var isactive = _username.HttpContext.User.Identity.IsAuthenticated;

            return $"name: " + name + " | IsAuthenticated: " + isactive;
</code>```

Return this -> name: URCTEST01\Ziya Mammadov | IsAuthenticated: True

Way 2.

```<code>
            WindowsIdentityHelper wih = new WindowsIdentityHelper();

            var name = wih.GetLoginUserName();

            return name;
</code>```
```<code> public class WindowsIdentityHelper
    {
        public WindowsPrincipal GetWindowsPrincipal()
        {
            //Get Current AppDomain
            AppDomain myDomain = Thread.GetDomain();
            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            return (WindowsPrincipal)Thread.CurrentPrincipal;
        }

        public bool IsUserBelongsToWindowsAdministratorGroup()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();

            if (myPrincipal.IsInRole("Administrators"))
                return true;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                return true;
            else
                return false;
        }

        public string GetFullDomainLoginUserName()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();
            return myPrincipal.Identity.Name.ToString();
        }

        public string GetLoginUserName()
        {
            string authenticatedUser = string.Empty;
            string userName = GetFullDomainLoginUserName();

                authenticatedUser = userName;
            return authenticatedUser;
        }
    }

</code>```

Return this -> IIS APPPOOL\timesheet

Way 1 return username which windows contain project.
Way 2 return IIS APPPOOL.

How to catch correct username?

Body:
User entering username and password for login in project. But customer want passwordless login with windows authenticated for every employee. I changed authentication mode from anonymous authentication to windows authentication. Now required windows authenticated before the application run.But entering the windows credential same username and password every time, which containing project published in iis.

Question 1. How i do required only client windows username and password in windows authentication?

Assuming i used client windows username and password for authentication. IsAuthenticated = true;

Here my new question.

Question 2. How i do catch client windows username?

Now use 2 different way for catch windows username.

Way 1.

var name = _username.HttpContext.User.Identity.Name;

            var isactive = _username.HttpContext.User.Identity.IsAuthenticated;

            return $"name: " + name + " | IsAuthenticated: " + isactive;

Return this -> name: URCTEST01\Ziya Mammadov | IsAuthenticated: True

Way 2.

            WindowsIdentityHelper wih = new WindowsIdentityHelper();

            var name = wih.GetLoginUserName();

            return name;

 public class WindowsIdentityHelper
    {
        public WindowsPrincipal GetWindowsPrincipal()
        {
            //Get Current AppDomain
            AppDomain myDomain = Thread.GetDomain();
            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            return (WindowsPrincipal)Thread.CurrentPrincipal;
        }

        public bool IsUserBelongsToWindowsAdministratorGroup()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();

            if (myPrincipal.IsInRole("Administrators"))
                return true;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                return true;
            else
                return false;
        }

        public string GetFullDomainLoginUserName()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();
            return myPrincipal.Identity.Name.ToString();
        }

        public string GetLoginUserName()
        {
            string authenticatedUser = string.Empty;
            string userName = GetFullDomainLoginUserName();

                authenticatedUser = userName;
            return authenticatedUser;
        }
    }

Return this -> IIS APPPOOL\timesheet

Way 1 return username which windows contain project.
Way 2 return IIS APPPOOL.

How to catch correct username?


问:
Unable to properly handle objects’ events
```<code>Add-Type -AssemblyName System.Windows.Forms

$MenuItems = New-Object -TypeName 'System.Collections.Generic.List[System.Windows.Forms.MenuItem]'

$Apps = @('calc','mspaint','notepad')

foreach ($App in $Apps)
{
    $MenuItem = New-Object -TypeName System.Windows.Forms.MenuItem

    $MenuItem.Text = $App

    $Action = [System.Management.Automation.ScriptBlock]::Create(('Start-Process -FilePath {0}' -f $App))

    $null = Register-ObjectEvent -InputObject $MenuItem -EventName Click -Action $Action

    #$MenuItem.Add_Click($Action)

    $MenuItems.Add($MenuItem)
}

$ContextMenu = [System.Windows.Forms.ContextMenu]::New($MenuItems)

$MessageDuration = Get-ItemPropertyValue -Path 'Registry::HKEY_CURRENT_USER\Control
Panel\Accessibility' -Name MessageDuration

$Timeout = $MessageDuration * 1000

$NotifyIcon = New-Object -TypeName System.Windows.Forms.NotifyIcon

$NotifyIcon.BalloonTipTitle = 'Lorem ipsum'

$NotifyIcon.BalloonTipText = 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...'

$NotifyIcon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info

$NotifyIcon.Text = 'ToolTipText'

$NotifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)

$NotifyIcon.ContextMenu = $ContextMenu

$NotifyIcon.Visible = $true

$NotifyIcon.ShowBalloonTip($Timeout)
</code>```

Either by registering the Click event or by using the Add_Click method, the first click is "ignored" and a sort of queue of events is created in the background.
In the first case, the click event triggers the action.
In the second one, the click event raises an error, and it does not trigger the action.
Error:

I am sure I am missing something: can anyone out there help me out?

Body:
Add-Type -AssemblyName System.Windows.Forms

$MenuItems = New-Object -TypeName 'System.Collections.Generic.List[System.Windows.Forms.MenuItem]'

$Apps = @('calc','mspaint','notepad')

foreach ($App in $Apps)
{
    $MenuItem = New-Object -TypeName System.Windows.Forms.MenuItem

    $MenuItem.Text = $App

    $Action = [System.Management.Automation.ScriptBlock]::Create(('Start-Process -FilePath {0}' -f $App))

    $null = Register-ObjectEvent -InputObject $MenuItem -EventName Click -Action $Action

    #$MenuItem.Add_Click($Action)

    $MenuItems.Add($MenuItem)
}

$ContextMenu = [System.Windows.Forms.ContextMenu]::New($MenuItems)

$MessageDuration = Get-ItemPropertyValue -Path 'Registry::HKEY_CURRENT_USER\Control
Panel\Accessibility' -Name MessageDuration

$Timeout = $MessageDuration * 1000

$NotifyIcon = New-Object -TypeName System.Windows.Forms.NotifyIcon

$NotifyIcon.BalloonTipTitle = 'Lorem ipsum'

$NotifyIcon.BalloonTipText = 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...'

$NotifyIcon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info

$NotifyIcon.Text = 'ToolTipText'

$NotifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)

$NotifyIcon.ContextMenu = $ContextMenu

$NotifyIcon.Visible = $true

$NotifyIcon.ShowBalloonTip($Timeout)

Either by registering the Click event or by using the Add_Click method, the first click is "ignored" and a sort of queue of events is created in the background.
In the first case, the click event triggers the action.
In the second one, the click event raises an error, and it does not trigger the action.
Error:

I am sure I am missing something: can anyone out there help me out?


问:
Capacitor native menu with embedded website
I develop a platform used by teachers.

This platform uses "old" technologies like PHP, JS, JQuery etc ...
I want to offer a mobile application that would allow you to use the web platform (already responsive)

I already did two years ago a first version of the mobile application with Cordova:
The Cordova application requests a login and password, makes a token request to the platform then uses the token to load the pages with Window.cordova.inappbrowser.open in full screen
It works well (with some functions to manage the photo, downloads etc).

Today, I want to offer better: since Cordova is starting to be obsolete, I turned to Capacitor Ionic.
I want to use the same operation for the login (it already works) then load a native page with a menu and a space where the pages would be loaded according to the selection in the native menu.

But being new in Ionic / Capacitor / Angular, I am a little lost:

Use WebView

Make a routing to the web page

Use a JS function that loads the page in the div ...

Here is the current state the application:

I want to load a page like https://alpha.website.net/index.php?page=  in the white part when the user clicks on the menu on the menu

Thank you