问:
Angular 2 apache .htaccess file 404 on subpages
I have successfully installed and ran Angular 2 app on my apache server, I am able to navigate through the pages via [routerLink]="['/register']"

However when I refresh the page I get a 404 error on the register page. Is there something wrong with my rewrite rules:

```<code>Options +FollowSymLinks
<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
</ifModule>
</code>```

Also here is my apache VirtualHost

```<code><VirtualHost *:80>
    ServerName example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/front/dist/browser
    <Directory /var/www/html/front>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

答:
Try creating a .htaccess file on the root of your application with the below rules,

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html [L]
RewriteRule ^ /index.html
</code>```

Body:
I have successfully installed and ran Angular 2 app on my apache server, I am able to navigate through the pages via [routerLink]="['/register']"

However when I refresh the page I get a 404 error on the register page. Is there something wrong with my rewrite rules:

Options +FollowSymLinks
<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
</ifModule>

Also here is my apache VirtualHost

<VirtualHost *:80>
    ServerName example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/front/dist/browser
    <Directory /var/www/html/front>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Body:
Try creating a .htaccess file on the root of your application with the below rules,

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html [L]
RewriteRule ^ /index.html


来源: stackexchange

问:
CloudFlare and logging visitor IP addresses via in PHP
I'm trying to track and log users/visitors that are accessing my website using PHP's $_SERVER['REMOTE_ADDR'] to do so. A typical method for IP address tracking in PHP.

However, I am using CloudFlare for caching and such and receiving their IP addresses as CloudFlare's:

108.162.212.* - 108.162.239.*

What would be a correct method of retrieving the actual users/visitors IP address while still using CloudFlare?

答:
It's better to check cloudflare ip ranges online (because it may change anytime) then check it's from cloudflare or not.

Cloudflare IP txt

If the source is Cloudflare you can use $_SERVER['HTTP_CF_CONNECTING_IP'] to get your client request ip-address but it's not safe to use it for all requests because it can send by any user in request header to trick you.

You can use following code to get real ip-address of your client request:

```<code>function _getUserRealIP() {
    $ipaddress = '';
    if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

function _readCloudflareIps()
{
    $file = file("https://www.cloudflare.com/ips-v4",FILE_IGNORE_NEW_LINES);
    return $file;
}

function _checkIpInRange($ip, $range) {
    if (strpos($range, '/') == false)
        $range .= '/32';

    // $range is in IP/CIDR format eg 127.0.0.1/24
    list($range, $netmask) = explode('/', $range, 2);
    $range_decimal = ip2long($range);
    $ip_decimal = ip2long($ip);
    $wildcard_decimal = pow(2, (32 - $netmask)) - 1;
    $netmask_decimal = ~ $wildcard_decimal;
    return (($ip_decimal & $netmask_decimal) == ($range_decimal & $netmask_decimal));
}

function _checkIsCloudflare($ip) {
    $cf_ips = _readCloudflareIps();
    $is_cf_ip = false;
    foreach ($cf_ips as $cf_ip) {
        if (_checkIpInRange($ip, $cf_ip)) {
            $is_cf_ip = true;
            break;
        }
    }
    return $is_cf_ip;
}

function getRealIp()
{
    $httpIp = _getUserRealIP();
    $check = _checkIsCloudflare($httpIp);
    if ($check) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }else{
        return $httpIp;
    }
}
</code>```

After importing this functions to your code you just need to call getRealIp() function like:

```<code>$userIp = getRealIp();
echo $userIp();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's better to check cloudflare ip ranges online (because it may change anytime) then check it's from cloudflare or not.

Cloudflare IP txt

If the source is Cloudflare you can use $_SERVER['HTTP_CF_CONNECTING_IP'] to get your client request ip-address but it's not safe to use it for all requests because it can send by any user in request header to trick you.

You can use following code to get real ip-address of your client request:

function _getUserRealIP() {
    $ipaddress = '';
    if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

function _readCloudflareIps()
{
    $file = file("https://www.cloudflare.com/ips-v4",FILE_IGNORE_NEW_LINES);
    return $file;
}

function _checkIpInRange($ip, $range) {
    if (strpos($range, '/') == false)
        $range .= '/32';

    // $range is in IP/CIDR format eg 127.0.0.1/24
    list($range, $netmask) = explode('/', $range, 2);
    $range_decimal = ip2long($range);
    $ip_decimal = ip2long($ip);
    $wildcard_decimal = pow(2, (32 - $netmask)) - 1;
    $netmask_decimal = ~ $wildcard_decimal;
    return (($ip_decimal & $netmask_decimal) == ($range_decimal & $netmask_decimal));
}

function _checkIsCloudflare($ip) {
    $cf_ips = _readCloudflareIps();
    $is_cf_ip = false;
    foreach ($cf_ips as $cf_ip) {
        if (_checkIpInRange($ip, $cf_ip)) {
            $is_cf_ip = true;
            break;
        }
    }
    return $is_cf_ip;
}

function getRealIp()
{
    $httpIp = _getUserRealIP();
    $check = _checkIsCloudflare($httpIp);
    if ($check) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }else{
        return $httpIp;
    }
}

After importing this functions to your code you just need to call getRealIp() function like:

$userIp = getRealIp();
echo $userIp();

ContentLicense: CC BY-SA 4.0


问:
Argument list too long error for rm, cp, mv commands
I have several hundred PDFs under a directory in UNIX. The names of the PDFs are really long (approx. 60 chars).

When I try to delete all PDFs together using the following command:

```<code>rm -f *.pdf
</code>```

I get the following error:

```<code>/bin/rm: cannot execute [Argument list too long]
</code>```

What is the solution to this error?
Does this error occur for mv and cp commands as well? If yes, how to solve for these commands?

答:
For somone who doesn't have time.
Run the following command on terminal.

```<code>ulimit -S -s unlimited
</code>```

Then perform cp/mv/rm operation.

Body:
I have several hundred PDFs under a directory in UNIX. The names of the PDFs are really long (approx. 60 chars).

When I try to delete all PDFs together using the following command:

rm -f *.pdf

I get the following error:

/bin/rm: cannot execute [Argument list too long]

What is the solution to this error?
Does this error occur for mv and cp commands as well? If yes, how to solve for these commands?

Body:
For somone who doesn't have time.
Run the following command on terminal.

ulimit -S -s unlimited

Then perform cp/mv/rm operation.


问:
proxy to conan-center: Remote from remote is not json, but 'application/octet-stream'
I set up a jfrog artifactory with a conan "remote" repository to proxy the official conan-center repository.  I see three different conan-center URLs, depending on with source I read: center.conan.io, conan.io/center, and conan.bintray.com.  I used the latter, conan.bintray.com, as it's the default URL that artifactory proposes for a remote repository of type conan.  I didn't change any settings.

Then I tried to do a conan install .. as I'd do normally on my local builds, but I removed the official conan-center repository that comes by default, and added my proxy repository (remote repository, as jfrog calls it)

```<code>$ conan remote list
conan-center-remote: http://conan.foo.com:8081/artifactory/conan-center-remote/ [Verify SSL: True]
</code>```

And then I get this error:

```<code>$ conan install ..
Configuration:
[settings]
arch=x86_64
arch_build=x86_64
build_type=Release
compiler=gcc
compiler.libcxx=libstdc++
compiler.version=10
os=Linux
os_build=Linux
[options]
[build_requires]
[env]

libavrocpp/1.10.1: Not found in local cache, looking in remotes...
libavrocpp/1.10.1: Trying with 'conan-center-remote'...
ERROR: {
  "conan_export.tgz" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conan_export.tgz",
  "conan_sources.tgz" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conan_sources.tgz",
  "conanmanifest.txt" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conanmanifest.txt",
  "conanfile.py" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conanfile.py"
}

Response from remote is not json, but 'application/octet-stream'. [Remote: conan-center-remote]
</code>```

Why do I get this error?

答:
My solution to this problem was to change the remote URL from https://your.jfrog.url/artifactory/your-conan-proxy-name/ to https://your.jfrog.url/artifactory/api/conan/your-conan-proxy-name/

Then change the conan local config: conan config set general.revisions_enabled=1

Body:
I set up a jfrog artifactory with a conan "remote" repository to proxy the official conan-center repository.  I see three different conan-center URLs, depending on with source I read: center.conan.io, conan.io/center, and conan.bintray.com.  I used the latter, conan.bintray.com, as it's the default URL that artifactory proposes for a remote repository of type conan.  I didn't change any settings.

Then I tried to do a conan install .. as I'd do normally on my local builds, but I removed the official conan-center repository that comes by default, and added my proxy repository (remote repository, as jfrog calls it)

$ conan remote list
conan-center-remote: http://conan.foo.com:8081/artifactory/conan-center-remote/ [Verify SSL: True]

And then I get this error:

$ conan install ..
Configuration:
[settings]
arch=x86_64
arch_build=x86_64
build_type=Release
compiler=gcc
compiler.libcxx=libstdc++
compiler.version=10
os=Linux
os_build=Linux
[options]
[build_requires]
[env]

libavrocpp/1.10.1: Not found in local cache, looking in remotes...
libavrocpp/1.10.1: Trying with 'conan-center-remote'...
ERROR: {
  "conan_export.tgz" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conan_export.tgz",
  "conan_sources.tgz" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conan_sources.tgz",
  "conanmanifest.txt" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conanmanifest.txt",
  "conanfile.py" : "https://conan.bintray.com/artifactory/api/conan/conan-center-legacy/v1/files/_/libavrocpp/1.10.1/_/5413c1d93780b9806d4ffcf0e9436409/export/conanfile.py"
}

Response from remote is not json, but 'application/octet-stream'. [Remote: conan-center-remote]

Why do I get this error?


问:
Laravel Lumen directly Download and Extract ZIP file to Google Cloud Storage
My goal is to download a large zip file (15 GB) and extract it to Google Cloud using Laravel Storage (https://laravel.com/docs/8.x/filesystem) and https://github.com/spatie/laravel-google-cloud-storage.

My "wish" is to sort of stream the file to Cloud Storage, so I do not need to store the file locally on my server (because it is running in multiple instances, and I want to have the disk size as small as possible).

Currently, there does not seem to be a way to do this without having to save the zip file on the server. Which is not ideal in my situation.

Another idea is to use a Google Cloud Function (eg with Python) to download, extract and store the file. However, it seems like Google Cloud Functions are limited to a max timeout of 9 mins (540 seconds). I don't think that will be enough time to download and extract 15GB...

Any ideas on how to approach this?

答:
You should be able to use streams for uploading big files. Here’s the example code to achieve it:

$disk = Storage::disk('gcs');

$disk->put($destFile, fopen($sourceZipFile, 'r+'));


问:
How to insert value in flag without using update statement
I am using the below query to insert data in the table, and at the end using an update statement to update the flag. Can I insert value without using update statement?

The update statement depends on the value of count_polls and total_count if they are equal then flag should be 1 otherwise 0

```<code>Declare @batchid varchar(4000)
set @batchid = (select batch id from polls_batch)
INSERT INTO [dbo]. [FeedSummary_test] (count_polls, total_count, BatchId, FeedLogStatus)

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_1] where batchid = @batchid

union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_2] where batchid = @Batchid

Union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_3] where batchid = @batchid

update [dbo].[FeedSummary_test]
set Flag = IIF(count_polls=total_count,1,0)

</code>```

I am getting these question marks from variables in SSIS, result should be something like this:

The query for these question marks is this:

```<code>select(select count(*) from dbo.AR_Feed_one) count_1,
(select count(*) from dbo.AR_Feed_two) count_2,
(select count(*) from dbo.AR_Feed_three )count_3
</code>```

And then I am storing these values in the variables and inserting them in the query using ?.

```<code>Final table should look like this
Count_polls,    TotalCount,     BatchID,    FeedLogStatus.  Flag
100 100 BUF 0   1
200 200 BUF 0   1
150 120 BUF 0   0
</code>```

And for a particular batchId there will be three rows with different total count and count polls.

答:
You could add your initial select into a common table expression, which allows you to use the result in your insert:

Declare @batchid varchar(4000)
set @batchid = (select batch id from polls_batch)

;WITH cte AS (
  SELECT COUNT(*) AS count_polls, ? AS total_count, 0 AS BatchId, 0 AS FeedLogStatus FROM [dbo].[PollsFeed_1] where batchid = @batchid

  UNION

  SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_2] where batchid = @Batchid

  UNION

  SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_3] where batchid = @batchid
)
INSERT INTO [dbo]. [FeedSummary_test] (count_polls, total_count, BatchId, FeedLogStatus, Flag )
SELECT count_polls, total_count, BatchId, FeedLogStatus, IIF(count_polls=total_count,1,0)
FROM cte

```

Body:
I am using the below query to insert data in the table, and at the end using an update statement to update the flag. Can I insert value without using update statement?

The update statement depends on the value of count_polls and total_count if they are equal then flag should be 1 otherwise 0

Declare @batchid varchar(4000)
set @batchid = (select batch id from polls_batch)
INSERT INTO [dbo]. [FeedSummary_test] (count_polls, total_count, BatchId, FeedLogStatus)

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_1] where batchid = @batchid

union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_2] where batchid = @Batchid

Union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_3] where batchid = @batchid

update [dbo].[FeedSummary_test]
set Flag = IIF(count_polls=total_count,1,0)

I am getting these question marks from variables in SSIS, result should be something like this:

The query for these question marks is this:

select(select count(*) from dbo.AR_Feed_one) count_1,
(select count(*) from dbo.AR_Feed_two) count_2,
(select count(*) from dbo.AR_Feed_three )count_3

And then I am storing these values in the variables and inserting them in the query using ?.

Final table should look like this
Count_polls,    TotalCount,     BatchID,    FeedLogStatus.  Flag
100 100 BUF 0   1
200 200 BUF 0   1
150 120 BUF 0   0

And for a particular batchId there will be three rows with different total count and count polls.


问:
Spring Data R2DBC Integration with Redshift Database
I'm trying to migrate to spring Data R2DBC, I couldn't find a support to Amazon Redshift database, can some one help me that if there is a support.

Here is the spring documentation url says that it supports few databases, but Redshift is not in the list.
https://spring.io/projects/spring-data-r2dbc

答:
I got an answer from 'Mark Paluch' below; this worked for me. So now I'm able to connect to Redshift using Postgres drivers.

Amazon Redshift is based on Postgres, so you should use the Postgres driver. This mailing list handles R2DBC specification aspects only. If you're looking for support for a specific library built on top of R2DBC, please reach out to the actual maintainers through their, e.g., GitHub project.

Pom.xml

```<code><dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-spi</artifactId>
    <version>0.9.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

application.properties:

spring.r2dbc.url=r2dbc:postgresql://hostName:portNumber/databaseName
spring.r2dbc.username=redshiftUserName
spring.r2dbc.password=password
</code>```

Body:
I got an answer from 'Mark Paluch' below; this worked for me. So now I'm able to connect to Redshift using Postgres drivers.

Amazon Redshift is based on Postgres, so you should use the Postgres driver. This mailing list handles R2DBC specification aspects only. If you're looking for support for a specific library built on top of R2DBC, please reach out to the actual maintainers through their, e.g., GitHub project.

Pom.xml

<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-spi</artifactId>
    <version>0.9.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

application.properties:

spring.r2dbc.url=r2dbc:postgresql://hostName:portNumber/databaseName
spring.r2dbc.username=redshiftUserName
spring.r2dbc.password=password


问:
three arguments in the mat-dialog open function
how to send three arguments from mat dialog open function I want to send dialogConfig but compilation gives me Expected 1-2 arguments, but got 3.

```<code>openEventModal(data?:object): void{
  const dialogConfig = new MatDialogConfig();

  dialogConfig.disableClose = true;
  dialogConfig.autoFocus = true;

  const dialogRef = this.dialog.open(EventModal,{data:data});
}
</code>```

答: I solved the problem for sending data the dialogConfig has a function for that the function name is dialogConfig.data={}</p>

Body:
how to send three arguments from mat dialog open function I want to send dialogConfig but compilation gives me Expected 1-2 arguments, but got 3.

openEventModal(data?:object): void{
  const dialogConfig = new MatDialogConfig();

  dialogConfig.disableClose = true;
  dialogConfig.autoFocus = true;

  const dialogRef = this.dialog.open(EventModal,{data:data});
}


问:
how can I make TV webapp using springboot with tizen?
I want to make a samsung smart tv app with tizen.
I've made an webpage using springboot.

I tried making the app using that webpage codes I made, but I've got to know Tizen doesn't support java but html, css,and javascript only.

So I used meta http-equip="refresh", and let index.html go to my webpage url,
but there were long loading time, and ugly ui for a waiting page..
also remote control's pointer was weird. (not focusing on a certain button, but there is a cursor)

is there no way to solve this problem?
I've tried to find a way but I couldn't. please help me...

答:
It seems that you are making a redirect to your website (hosted in internet).

Maybe would be better starting reading the basic concepts about Samsung Smart TV apps here

If you try to open external content (hosted websites) into your app the TV will use its web browser to open it.


问:
How To Pass ErrorMessage From API to MVC In Asp.Net Core
I've created an API. When you face an error, It shows you the type of error with it's message. But When I try to use that API in my MVC project, It just shows the type of error. I want to see the message in Modelstate.AddModelError

Here is API controller for Login

```<code>[HttpPost("login")]
        public async Task<IActionResult> LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve = await _applicationDbContext.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {
                ModelState.AddModelError("username", "Such a user doesn't exists! Enter the correct username please");
                return NotFound(ModelState);
            }
            if (!_userRepository.VerifyPasswordHash(user.Password, userToRetrieve.PasswordHash, userToRetrieve.PasswordSalt))
            {
                ModelState.AddModelError("password", "Wrong Password!");
                return BadRequest(ModelState);
            }
            await _userRepository.Login(userToRetrieve);
            return Ok(user);
        }
</code>```

Here is MVC Controller for Login

```<code>[HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/user/login");
            if (user != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(user),
                    System.Text.Encoding.UTF8, "application/json");
            }
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                ViewBag.StatusCode = System.Net.HttpStatusCode.OK;
                var apiString = await response.Content.ReadAsStringAsync();
                user = JsonConvert.DeserializeObject<User>(apiString);
            }
            else
            {
                ViewBag.StatusCode = response.StatusCode;
            }
            return View(user);

        }
</code>```

答:
I write a simple demo to show how to pass ErrorMessage From API to MVC In Asp.Net Core, you can reference to it.

API

```<code>    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

    //For testing convenience, I use hard code here

        List<UserDtoLogin> context = new List<UserDtoLogin>
        {
            new UserDtoLogin
            {
                UserName = "Mike"
            },

            new UserDtoLogin
            {
                UserName = "Jack"
            },

            new UserDtoLogin
            {
                UserName = "Lily"
            }
        };

        [HttpPost("login")]
        public IActionResult LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve =  context.FirstOrDefault(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {

                return BadRequest("Such a user doesn't exists! Enter the correct username please");
            }

            //your logic.....

            return Ok();
        }
    }
</code>```

MVC/Controller

```<code>        [HttpPost]
        public async Task<IActionResult> Privacy(UserDtoLogin todoItem)
        {
            var todoItemJson = new StringContent(JsonSerializer.Serialize(todoItem),Encoding.UTF8,Application.Json);

            using var httpResponseMessage = await _httpClient.PostAsync("your api url", todoItemJson);
            var errormessage = httpResponseMessage.Content.ReadAsStringAsync().Result;

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

Then you can see it can receive the errormessage successfully.

Body:
I've created an API. When you face an error, It shows you the type of error with it's message. But When I try to use that API in my MVC project, It just shows the type of error. I want to see the message in Modelstate.AddModelError

Here is API controller for Login

[HttpPost("login")]
        public async Task<IActionResult> LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve = await _applicationDbContext.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {
                ModelState.AddModelError("username", "Such a user doesn't exists! Enter the correct username please");
                return NotFound(ModelState);
            }
            if (!_userRepository.VerifyPasswordHash(user.Password, userToRetrieve.PasswordHash, userToRetrieve.PasswordSalt))
            {
                ModelState.AddModelError("password", "Wrong Password!");
                return BadRequest(ModelState);
            }
            await _userRepository.Login(userToRetrieve);
            return Ok(user);
        }

Here is MVC Controller for Login

[HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/user/login");
            if (user != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(user),
                    System.Text.Encoding.UTF8, "application/json");
            }
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                ViewBag.StatusCode = System.Net.HttpStatusCode.OK;
                var apiString = await response.Content.ReadAsStringAsync();
                user = JsonConvert.DeserializeObject<User>(apiString);
            }
            else
            {
                ViewBag.StatusCode = response.StatusCode;
            }
            return View(user);

        }

Body:
I write a simple demo to show how to pass ErrorMessage From API to MVC In Asp.Net Core, you can reference to it.

API

    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

    //For testing convenience, I use hard code here

        List<UserDtoLogin> context = new List<UserDtoLogin>
        {
            new UserDtoLogin
            {
                UserName = "Mike"
            },

            new UserDtoLogin
            {
                UserName = "Jack"
            },

            new UserDtoLogin
            {
                UserName = "Lily"
            }
        };

        [HttpPost("login")]
        public IActionResult LoginUser([FromBody] UserDtoLogin user)
        {
            var userToRetrieve =  context.FirstOrDefault(u => u.UserName == user.UserName);
            if (userToRetrieve == null)
            {

                return BadRequest("Such a user doesn't exists! Enter the correct username please");
            }

            //your logic.....

            return Ok();
        }
    }

MVC/Controller

        [HttpPost]
        public async Task<IActionResult> Privacy(UserDtoLogin todoItem)
        {
            var todoItemJson = new StringContent(JsonSerializer.Serialize(todoItem),Encoding.UTF8,Application.Json);

            using var httpResponseMessage = await _httpClient.PostAsync("your api url", todoItemJson);
            var errormessage = httpResponseMessage.Content.ReadAsStringAsync().Result;

            return View(todoItem);
        }

Then you can see it can receive the errormessage successfully.


问:
c program Warning the control reaches the end of non-void function
so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error</p>
```<code>#include <iostream>
//int sum = 1;

int powerOfNumber(int n, int p) {
    if (n != 0) {
        p--;
        return powerOfNumber(n , p) * n;
    }
    if (n == 0) {
        return 1;
    }
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;

}
</code>```

答: Your stop condition must be in terms of p, not n, because that's the variable you are substracting the value, either way you could substract the value of n</p>

Body:
so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error

#include <iostream>
//int sum = 1;

int powerOfNumber(int n, int p) {
    if (n != 0) {
        p--;
        return powerOfNumber(n , p) * n;
    }
    if (n == 0) {
        return 1;
    }
}

int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;

}


问:
HttpClient GetDiscoveryDocumentAsync() Method hanging
In ASP.NET Project I using web service that I get data from it by APIs,
I am using this code to connect with web service but it hanging:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {

        var result = ICDa.GetCodeResult().GetAwaiter().GetResult();

        return View();
    }

    private  async Task<string> GetCodeResult()
    {
        var client = new HttpClient();
        var disco = await
 client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
       if (disco.IsError)
       {
          return "error";
       }
       else
       {
           return "success";
       }
    }
}
</code>```

But when I using this code in Console App, it work right, no problem

答:
Mason's comment is correct. I try to run in console application and webapi application, all work fine.

So my test results proved that GetDiscoveryDocumentAsync() in HttpClient is normal.

Test Code in Console Application

```<code>using System;
using System.Net.Http;
using System.Threading.Tasks;

using IdentityModel.Client;

using Newtonsoft.Json.Linq;

namespace ClientCredentialsConsoleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                await aa();
            }).GetAwaiter().GetResult();
        }
        public static async Task<string> aa()
        {
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
            if (disco.IsError)
            {
                return "error";
            }
            else {
                return "success";
            }
        }
    }
}
</code>```

And Result

Test Code in Webapi Application

```<code>[HttpGet("Test_HttpClient")]
public async Task<string> Test_HttpClient()
{
    string res=await aa();
    return res;
}
private  async Task<string> aa()
{
    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
    if (disco.IsError)
    {
        return "error";
    }
    else
    {
        return "success";
    }
}
</code>```

And Result

Body:
In ASP.NET Project I using web service that I get data from it by APIs,
I am using this code to connect with web service but it hanging:

public class HomeController : Controller
{
    public ActionResult Index()
    {

        var result = ICDa.GetCodeResult().GetAwaiter().GetResult();

        return View();
    }

    private  async Task<string> GetCodeResult()
    {
        var client = new HttpClient();
        var disco = await
 client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
       if (disco.IsError)
       {
          return "error";
       }
       else
       {
           return "success";
       }
    }
}

But when I using this code in Console App, it work right, no problem

Body:
Mason's comment is correct. I try to run in console application and webapi application, all work fine.

So my test results proved that GetDiscoveryDocumentAsync() in HttpClient is normal.

Test Code in Console Application

using System;
using System.Net.Http;
using System.Threading.Tasks;

using IdentityModel.Client;

using Newtonsoft.Json.Linq;

namespace ClientCredentialsConsoleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                await aa();
            }).GetAwaiter().GetResult();
        }
        public static async Task<string> aa()
        {
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
            if (disco.IsError)
            {
                return "error";
            }
            else {
                return "success";
            }
        }
    }
}

And Result

Test Code in Webapi Application

[HttpGet("Test_HttpClient")]
public async Task<string> Test_HttpClient()
{
    string res=await aa();
    return res;
}
private  async Task<string> aa()
{
    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync("https://icdaccessmanagement.who.int");
    if (disco.IsError)
    {
        return "error";
    }
    else
    {
        return "success";
    }
}

And Result


问:
animation: none on hover breaks animation
I'm working on a CSS only carousel. It uses a keyframes animation to scroll automatically. Because there are also arrow buttons to navigate manually I want to stop the animation on hover. Everything works fine up to this point. But after you release the hover it breaks in various ways and essentially stops sliding following the correct order and timing.

@charset "UTF-8";
*, *:after, *:before {
  box-sizing: border-box; }

@keyframes tonext {
  75% {
    left: 0; }
  95% {
    left: calc(100% + 150px); }
  98% {
    left: calc(100% + 150px); }
  99% {
    left: 0; } }
@keyframes snap {
  96% {
    scroll-snap-align: start; }
  97% {
    scroll-snap-align: none; }
  99% {
    scroll-snap-align: none; }
  100% {
    scroll-snap-align: start; } }
@keyframes tostart {
  75% {
    left: 0; }
  95% {
    left: calc(-300% - 450px); }
  98% {
    left: calc(-300% - 450px); }
  99% {
    left: 0; } }
/* Slider container size */
/* Slider container properties */
/* Slide size */
/* Slide properties */
/* Scrollbar properties */
ol, li {
  list-style: none;
  margin: 0;
  padding: 0; }

#pSlider {
  width: 500px;
  height: 100px;
  position: relative;
  margin: 50px;
  /* Left, Right Navigation Arrows */
  /* Scrollbar */ }
  #pSlider #slider-container {
    display: flex;
    height: 100%;
    width: 100%;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth; }
    #pSlider #slider-container .li_slide {
      position: relative;
      width: 500px;
      border-radius: 10px;
      background-color: khaki;
      flex: none;
      margin-right: 150px; }
      #pSlider #slider-container .li_slide:last-child {
        margin-right: 0; }
      #pSlider #slider-container .li_slide:nth-child(even) {
        background-color: aqua; }
      #pSlider #slider-container .li_slide .slide-snapper {
        scroll-snap-align: start;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        animation: tonext 4s ease infinite, snap 4s ease infinite; }
        #pSlider #slider-container .li_slide .slide-snapper:hover {
          animation-name: none; }
      #pSlider #slider-container .li_slide:last-child .slide-snapper {
        animation-name: tostart, snap; }
  #pSlider:before, #pSlider:after, #pSlider .prev_slide, #pSlider .next_slide {
    display: inline-block;
    position: absolute;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    top: 50%;
    z-index: 2;
    cursor: pointer; }
  #pSlider:before, #pSlider:after {
    background-color: #333;
    color: #DDD;
    text-align: center; }
  #pSlider:before, #pSlider .prev_slide {
    content: "←";
    left: -10px; }
  #pSlider:after, #pSlider .next_slide {
    content: "→";
    right: -10px; }
  #pSlider:after {
    z-index: 1;
    /* set underneath .next_slide (z: 2)*/ }
  #pSlider #slider-container::-webkit-scrollbar {
    display: none;
    height: 5px; }
  #pSlider #slider-container::-webkit-scrollbar-thumb {
    background-color: #000;
    border-radius: 50px; }
  #pSlider #slider-container::-webkit-scrollbar-track {
    background-color: transparent; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div id="pSlider">
        <ol id="slider-container" dir="ltr">
            <li class="li_slide">
                <p>1</p>
                <div id="slide_1" class="slide-snapper"></div>
                  </li>
            <li class="li_slide">
                <p>2</p>
                <div id="slide_2" class="slide-snapper"></div>
                  </li>
            <li class="li_slide">
                <p>3</p>
                <div id="slide_3" class="slide-snapper"></div>
                  </li>
            <li class="li_slide">
                <p>4</p>
                <div id="slide_4" class="slide-snapper"></div>
                  </li>
        </ol>
    </div></code>```

答:
This part in the SCSS

```<code>#pSlider {
  #slider-container {
    .li_slide {
      .slide-snapper {
        &:hover {
          animation-name: none;
        }
      }
    }
  }
}
</code>```

stops the animation only for the hovered slide, while the other slides keep being animated out of the viewport, which ends up in a mismatch. Looks like it can be solved by applying it a bit different:

```<code>#pSlider {
  #slider-container {
    &:hover .li_slide .slide-snapper {
      animation-name: none;
    }
  }
}
</code>```

(I skipped the other parts in the SCSS but make sure the declaration of stopping the animation comes below the declration of the original animation)

By means of plain/compiled CSS, the change should be from

```<code>#pSlider #slider-container .li_slide .slide-snapper:hover {
  animation-name: none;
}
</code>```

to

```<code>#pSlider #slider-container:hover .li_slide .slide-snapper {
  animation-name: none;
}
</code>```

Body:
I'm working on a CSS only carousel. It uses a keyframes animation to scroll automatically. Because there are also arrow buttons to navigate manually I want to stop the animation on hover. Everything works fine up to this point. But after you release the hover it breaks in various ways and essentially stops sliding following the correct order and timing.

@charset "UTF-8";
*, *:after, *:before {
  box-sizing: border-box; }

@keyframes tonext {
  75% {
    left: 0; }
  95% {
    left: calc(100% + 150px); }
  98% {
    left: calc(100% + 150px); }
  99% {
    left: 0; } }
@keyframes snap {
  96% {
    scroll-snap-align: start; }
  97% {
    scroll-snap-align: none; }
  99% {
    scroll-snap-align: none; }
  100% {
    scroll-snap-align: start; } }
@keyframes tostart {
  75% {
    left: 0; }
  95% {
    left: calc(-300% - 450px); }
  98% {
    left: calc(-300% - 450px); }
  99% {
    left: 0; } }
/* Slider container size */
/* Slider container properties */
/* Slide size */
/* Slide properties */
/* Scrollbar properties */
ol, li {
  list-style: none;
  margin: 0;
  padding: 0; }

#pSlider {
  width: 500px;
  height: 100px;
  position: relative;
  margin: 50px;
  /* Left, Right Navigation Arrows */
  /* Scrollbar */ }
  #pSlider #slider-container {
    display: flex;
    height: 100%;
    width: 100%;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth; }
    #pSlider #slider-container .li_slide {
      position: relative;
      width: 500px;
      border-radius: 10px;
      background-color: khaki;
      flex: none;
      margin-right: 150px; }
      #pSlider #slider-container .li_slide:last-child {
        margin-right: 0; }
      #pSlider #slider-container .li_slide:nth-child(even) {
        background-color: aqua; }
      #pSlider #slider-container .li_slide .slide-snapper {
        scroll-snap-align: start;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        animation: tonext 4s ease infinite, snap 4s ease infinite; }
        #pSlider #slider-container .li_slide .slide-snapper:hover {
          animation-name: none; }
      #pSlider #slider-container .li_slide:last-child .slide-snapper {
        animation-name: tostart, snap; }
  #pSlider:before, #pSlider:after, #pSlider .prev_slide, #pSlider .next_slide {
    display: inline-block;
    position: absolute;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    top: 50%;
    z-index: 2;
    cursor: pointer; }
  #pSlider:before, #pSlider:after {
    background-color: #333;
    color: #DDD;
    text-align: center; }
  #pSlider:before, #pSlider .prev_slide {
    content: "←";
    left: -10px; }
  #pSlider:after, #pSlider .next_slide {
    content: "→";
    right: -10px; }
  #pSlider:after {
    z-index: 1;
    /* set underneath .next_slide (z: 2)*/ }
  #pSlider #slider-container::-webkit-scrollbar {
    display: none;
    height: 5px; }
  #pSlider #slider-container::-webkit-scrollbar-thumb {
    background-color: #000;
    border-radius: 50px; }
  #pSlider #slider-container::-webkit-scrollbar-track {
    background-color: transparent; }

1

2

3

4

Body:
This part in the SCSS

#pSlider {
  #slider-container {
    .li_slide {
      .slide-snapper {
        &:hover {
          animation-name: none;
        }
      }
    }
  }
}

stops the animation only for the hovered slide, while the other slides keep being animated out of the viewport, which ends up in a mismatch. Looks like it can be solved by applying it a bit different:

#pSlider {
  #slider-container {
    &:hover .li_slide .slide-snapper {
      animation-name: none;
    }
  }
}

(I skipped the other parts in the SCSS but make sure the declaration of stopping the animation comes below the declration of the original animation)

By means of plain/compiled CSS, the change should be from

#pSlider #slider-container .li_slide .slide-snapper:hover {
  animation-name: none;
}

to

#pSlider #slider-container:hover .li_slide .slide-snapper {
  animation-name: none;
}


问:
Extracting substring with awk if the string includes regular expressions
I have many strings like this

```<code>i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt
</code>```

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

答:
You could try following awk programs.

To get FCT likewise strings try: Since position of string is NOT fixed as well as only /F is fixed, so I am trying to match /F till next occurrence of / so it will catch any value after /F but before next occurrence of / here.

```<code>echo "$i" | awk 'match($0,/\/F[^/]*/){print substr($0,RSTART+1,RLENGTH-1)}'
</code>```

To get M1 try following awk program, since position of M1 is always fixed(as per OP in question), so I am using 2 substitute calls here, where first one is removing starting ./ with NULL and 2nd substitute call is removing everything from / to till last of line with NULL and then printing the line which will give M1 part.

```<code>echo "$i" | awk '{sub(/^\.\//,"");sub(/\/.*/,"")} 1'
</code>```

Body:
I have many strings like this

i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

Body:
You could try following awk programs.

To get FCT likewise strings try: Since position of string is NOT fixed as well as only /F is fixed, so I am trying to match /F till next occurrence of / so it will catch any value after /F but before next occurrence of / here.

echo "$i" | awk 'match($0,/\/F[^/]*/){print substr($0,RSTART+1,RLENGTH-1)}'

To get M1 try following awk program, since position of M1 is always fixed(as per OP in question), so I am using 2 substitute calls here, where first one is removing starting ./ with NULL and 2nd substitute call is removing everything from / to till last of line with NULL and then printing the line which will give M1 part.

echo "$i" | awk '{sub(/^\.\//,"");sub(/\/.*/,"")} 1'


问:
Getting empty test suite when running with pytest from pycharm
I'm having issues with running pytest tests from inside PyCharm

I have a file x_tests.py inside a folder called agents_automation_2 in C:\Temp, the content of the file is

```<code>import pytest
def test_mytest():
    assert  False
</code>```

When I run I get the following output

C:\Python36-32\python.exe "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pycharm_jb_pytest_runner.py" --path C:/Temp/agents_automation_2
Launching py.test with arguments C:/Temp/agents_automation_2 in C:\Temp\agents_automation_2
============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0
rootdir: C:\Temp\agents_automation_2, inifile:
plugins: xdist-1.22.0, forked-0.2
collected 0 items
======================== no tests ran in 0.01 seconds =========================

However, when I run from a regular windows command line inside the folder the test runs OK

Any idea of what might be the issue ?

Thanks !!!

答:
Make sure your conftest.py file is in same folder.

If you are using fixtures. Add "Test" keyword in class name (example = TestClass)

@pytest.mark.usefixtures("setup1")

class TestClass:
      def test_abc(self):
          print("testcase execution")
```

Body:
I'm having issues with running pytest tests from inside PyCharm

I have a file x_tests.py inside a folder called agents_automation_2 in C:\Temp, the content of the file is

import pytest
def test_mytest():
    assert  False

When I run I get the following output

C:\Python36-32\python.exe "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pycharm_jb_pytest_runner.py" --path C:/Temp/agents_automation_2
Launching py.test with arguments C:/Temp/agents_automation_2 in C:\Temp\agents_automation_2
============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0
rootdir: C:\Temp\agents_automation_2, inifile:
plugins: xdist-1.22.0, forked-0.2
collected 0 items
======================== no tests ran in 0.01 seconds =========================

However, when I run from a regular windows command line inside the folder the test runs OK

Any idea of what might be the issue ?

Thanks !!!


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答:
```<code>import module
</code>```

Is best when you will use many functions from the module.

```<code>from module import function
</code>```

Is best when you want to avoid polluting the global namespace with all the functions and types from a module when you only need function.

OwnerDisplayName: kRON

Body:
import module

Is best when you will use many functions from the module.

from module import function

Is best when you want to avoid polluting the global namespace with all the functions and types from a module when you only need function.

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5


问:
I want to define a variable with superglobal scope in php
I want to define a variable in php with in a global scope. That variable should be accessible for each user, so it should not depend on the session.

I want to do something like the following: I have a php script, and that script usually takes about 5 to 15 minutes to execute, but it can take more than one hour in some special cases. This script is being run using a cron job with a 15 minutes interval. This script can also be run manually by any user.

Now it's possible to run any number of scripts at the same time. I want to limit this number of scripts.

So, I want a variable to store the number of currently executing scripts. I don't want to use a DB or files to store a single value.

Thanks in advance.

答: Without DB or files this isn't possible as far as I am aware of. Instead, if you have access to the server (root access) you could check with the ps command (if running a linux OS) if the script is already running and if so, you could see how much instances of it.


问:
Pattern to Orchestrate sequence of API calls C#
I have 3 microservices exposing APIs for interaction.

The order microservice receives order from UI and makes an API call to Inventory microservice to update the inventory details to reduce the itemCount.

Once the above operation succeeds, the order microservice will make calls to Payment microservice to initiate payments. If payment succeeds, the order microservice will return success to UI. If payment fails, the order microservice has to rollback the itemCount by calling Inventory microservice.

I know that this is a typical Saga based pattern and can be achieved using messaging bus. But all the microservices in this case are capable of only handling API calls. Thinking about other patterns, I am not sure this scenario fits into a state pattern .

Note: For the sake of example, I have used Order,Payment and Inventory microservices. But typically my question is about orchestrating sequence of API calls without excessive if-else. Failure of one of the API call should rollback the other API call by calling appropriate API (eg: If PATCH call succeeds on service A , but not on service B, then the PATCH call on service A has to be rolled back on Service A)

答:
The SAGA pattern is not exclusive to message bus and can be implemented via API calls as well.

The important thing with SAGA is to ensure that all the transactions can be rolled back to the previous state in a controlled manner via a compensation action.  So you need an API call to reverse the transaction and in your case restore the items to the inventory.

Another alternative is 2-phase commit.
So here your Inventory MS would effectively first Reserve the items, and once payment is successful, then you call it again to confirm and actually book them.

If it is not successful, or if not confirmed within xx minutes (or once every x hours), then you rollback the reservation.

Both patterns have their pros and cons, and the important thing is to select the one which suits your use case best.


问:
regular expression in python to extract words that contain @ but not dot
I am using Python to extract words from a text. I want to extract word that contain@ but not dot.

Regular expression should match following: @bob, cat@bob

Regular expression should not match: xyz@bob.com.

I tried following: (?:\w+)?@\w+(?!\.) - but it extracts @bob, cat@bob and xyz@bo.

Just  to elaborate, if I have text "hi @bob and cat@bob my email is xyz@bob.com" I want to extract @bob and cat@bob only from this text. My regular expression above extracts part of xyz@bob.com (precisely it extracts xyz@bo). How can I avoid extracting xyz@bob.com completely.

答: I was finally able to find a solution. The following expression worked for me: (?:\w+)?@\w+\b(?!.)</p>


答:
You have a bug that the condition needed to be

```<code>    if (p != 0) {
    ...
    }
    if ( p == 0)
        return 0;
</code>```

rather than     if (n != 0) { ... } if ( n == 0) ....

But you might still get the same warning though if the compiler couldn't deduce
that there'll be always be a return.

You could simply rewrite it to:

```<code>int powerOfNumber(int n, int p) {
   if (p != 0) {
       p--;
       return powerOfNumber(n , p) * n;
   }

   return 1;
}
</code>```

so that there's always a return statement unconditionally.

P.S.: Be aware that if you are using a large input for either n or p, you might run to integer overflow.

Title: c program Warning the control reaches the end of non-void function

Body:
You have a bug that the condition needed to be

    if (p != 0) {
    ...
    }
    if ( p == 0)
        return 0;

rather than     if (n != 0) { ... } if ( n == 0) ....

But you might still get the same warning though if the compiler couldn't deduce
that there'll be always be a return.

You could simply rewrite it to:

int powerOfNumber(int n, int p) {
   if (p != 0) {
       p--;
       return powerOfNumber(n , p) * n;
   }

   return 1;
}

so that there's always a return statement unconditionally.

P.S.: Be aware that if you are using a large input for either n or p, you might run to integer overflow.


问:
how to get value of more than one text box in a loop
I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.

Is there any option to work by loop

答:
yes, you can put your controls in panel and then iterate and get value. e.g.</p>

```<code>foreach (Control ctrl in Panel1.Controls)
    {
        if (ctrl.GetType().Name == "TextBox")
        {
            if (((TextBox)ctrl).Text != string.Empty)
            {
                // do stuff here
            }
       }
   }
</code>```

Body:
yes, you can put your controls in panel and then iterate and get value. e.g.

foreach (Control ctrl in Panel1.Controls)
    {
        if (ctrl.GetType().Name == "TextBox")
        {
            if (((TextBox)ctrl).Text != string.Empty)
            {
                // do stuff here
            }
       }
   }


问:
Not allowed to load local resource in console for using live server at vs studio

I've tried by changing the IP address and also changed the default browser, but still not working.

答:
Check if you have written a nasty code which blocks some of the function of live server. Just go on element tab in dev tools and scroll down to check the script written after <-- Code Injected by Live Server -->.
See whether you have used the same name for any function in your any js file. If so just change their names. If this does not work then try to reinstall live server extension.


问:
"Lock cont." column in WinDbg heap stats output
Does anyone know the meaning of the "Lock cont." column in WinDbg's "!heap -s" output?

Background: I have a running server process on Win10 that seems to have a significant heap leaks (several hundred MB) that occur every few hours. UMDH snapshots seemed to have reasonable data but did not show any significant leak. Internal object counters of the running software are pretty constant also. I must not stop the running process in its environment and can't reproduce it on other machines yet. So I'm looking for clues in process dumps that could help reproducing the problem.

Below are two heap stat outputs of two dumps taken during 3 days of uptime. The "Lock cont." column looks suspicious to me. I can't find any member that would correspond to it in the _HEAP structure of that heap.

```<code>************************************************************************************************************************
                                              NT HEAP STATS BELOW
************************************************************************************************************************
NtGlobalFlag enables following debugging aids for new heaps:
    stack back traces
LFH Key                   : 0x3f35bc5ac7ba9927
Termination on corruption : ENABLED
          Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast
                            (k)     (k)    (k)     (k) length      blocks cont. heap
-------------------------------------------------------------------------------------
000002565ca90000 08000002  113596  99912 113492   1879   453    11    1     34   LFH
0000025656610000 08008000      64      4     64      2     1     1    0      0
000002565e8a0000 08001002    3228   2448   3124    543    27     3    0      0   LFH
    External fragmentation  22 % (27 free blocks)
000002565ef70000 08001002      60      8     60      5     1     1    0      0
000002565ef40000 08001002     164     36     60     10     3     1    0      0   LFH
000002565f760000 08001002      60      8     60      1     1     1    0      0
0000025661af0000 08001002    1184    652   1080    272    20     2    0      0   LFH
-------------------------------------------------------------------------------------

************************************************************************************************************************
                                              NT HEAP STATS BELOW
************************************************************************************************************************
NtGlobalFlag enables following debugging aids for new heaps:
    stack back traces
LFH Key                   : 0x3f35bc5ac7ba9927
Termination on corruption : ENABLED
          Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast
                            (k)     (k)    (k)     (k) length      blocks cont. heap
-------------------------------------------------------------------------------------
000002565ca90000 08000002  680176 676160 680072  13730  1262    65    2  12c41   LFH
0000025656610000 08008000      64      4     64      2     1     1    0      0
000002565e8a0000 08001002    7320   5120   7216   1983    76     4    0      c   LFH
    External fragmentation  38 % (76 free blocks)
000002565ef70000 08001002      60      8     60      5     1     1    0      0
000002565ef40000 08001002     164     36     60     10     3     1    0      0   LFH
000002565f760000 08001002      60      8     60      1     1     1    0      0
0000025661af0000 08001002    1184    652   1080    269    22     2    0      0   LFH
-------------------------------------------------------------------------------------
</code>```

答:
"cont." is the abbreviation for "contention", so "Lock cont." is "lock contention".

The global heap is multithreaded, but access is behind a lock; if a thread tries to access the global heap while another has a lock on it, then it has to wait (the contention). So this number is the number of times that several threads tried to use the heap at the same time.

For the data structure, look at dt nt!_HEAP_COUNTERS, maybe +0x024 LockCollisions   : Uint4B.

For the UMDH part: you might need to increase the size of the user mode stack trace database using gflags.

Body:
Does anyone know the meaning of the "Lock cont." column in WinDbg's "!heap -s" output?

Background: I have a running server process on Win10 that seems to have a significant heap leaks (several hundred MB) that occur every few hours. UMDH snapshots seemed to have reasonable data but did not show any significant leak. Internal object counters of the running software are pretty constant also. I must not stop the running process in its environment and can't reproduce it on other machines yet. So I'm looking for clues in process dumps that could help reproducing the problem.

Below are two heap stat outputs of two dumps taken during 3 days of uptime. The "Lock cont." column looks suspicious to me. I can't find any member that would correspond to it in the _HEAP structure of that heap.

************************************************************************************************************************
                                              NT HEAP STATS BELOW
************************************************************************************************************************
NtGlobalFlag enables following debugging aids for new heaps:
    stack back traces
LFH Key                   : 0x3f35bc5ac7ba9927
Termination on corruption : ENABLED
          Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast
                            (k)     (k)    (k)     (k) length      blocks cont. heap
-------------------------------------------------------------------------------------
000002565ca90000 08000002  113596  99912 113492   1879   453    11    1     34   LFH
0000025656610000 08008000      64      4     64      2     1     1    0      0
000002565e8a0000 08001002    3228   2448   3124    543    27     3    0      0   LFH
    External fragmentation  22 % (27 free blocks)
000002565ef70000 08001002      60      8     60      5     1     1    0      0
000002565ef40000 08001002     164     36     60     10     3     1    0      0   LFH
000002565f760000 08001002      60      8     60      1     1     1    0      0
0000025661af0000 08001002    1184    652   1080    272    20     2    0      0   LFH
-------------------------------------------------------------------------------------

************************************************************************************************************************
                                              NT HEAP STATS BELOW
************************************************************************************************************************
NtGlobalFlag enables following debugging aids for new heaps:
    stack back traces
LFH Key                   : 0x3f35bc5ac7ba9927
Termination on corruption : ENABLED
          Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast
                            (k)     (k)    (k)     (k) length      blocks cont. heap
-------------------------------------------------------------------------------------
000002565ca90000 08000002  680176 676160 680072  13730  1262    65    2  12c41   LFH
0000025656610000 08008000      64      4     64      2     1     1    0      0
000002565e8a0000 08001002    7320   5120   7216   1983    76     4    0      c   LFH
    External fragmentation  38 % (76 free blocks)
000002565ef70000 08001002      60      8     60      5     1     1    0      0
000002565ef40000 08001002     164     36     60     10     3     1    0      0   LFH
000002565f760000 08001002      60      8     60      1     1     1    0      0
0000025661af0000 08001002    1184    652   1080    269    22     2    0      0   LFH
-------------------------------------------------------------------------------------


问:
I want to change values in Odoo
Here I want to change calculate the cost of merge and then calculate the sales price but result is wrong .. please help me

list_price = Sales Price

standard_price = cost

mrg= marge

cost=marge %

list_price = standard_price*(1+mrg)

from odoo import models, fields, api

class Marge_product_template(models.Model):
    _name = "product.template"
    _inherit = "product.template"
    mrg = fields.Integer(string="Marge")
    standard_price = fields.Float(string="Cost", store=True)

    @api.onchange("list_price", "standard_price", "mrg")
    def _onchange_cost(self):
        # set auto-changing field
        if self.mrg != 0:
            self.standard_price = (self.mrg * self.list_price) / 100

    @api.onchange("list_price", "standard_price", "mrg")
    def _onchange_vente(self):
        # set auto-changing field
        if self.standard_price != 0 and self.mrg != 0:
            self.list_price = self.standard_price * (1 + self.mrg)
```

答:
This is speculation… I've been reading the tutorial and the reference but have never heard of Odoo before today. Quite intrigued by it, though!

The arguments for @api.onchange decorator mean "when these fields change, call this method", right?

If that's true, is it a mistake to have "standard_price" in the decorator when the function is to update self.standard_price?

    @api.onchange("list_price", "standard_price", "mrg")
    #                           ^^^^ error? ^^^^
    def _onchange_cost(self):
        if self.mrg != 0:
            self.standard_price = (self.mrg * self.list_price) / 100
            # ^^ recursion? ^^
```
<p>And by the same logic, <code>"list_price"</code> should not be in the <code>_onchange_vente</code> decorator.</p>
<p>Can you try this change and see if it works?</p>
<pre class="lang-py prettyprint-override"><code>    @api.onchange("list_price", "mrg") # removed "standard_price"
    def _onchange_cost(self):
        if self.mrg != 0:
            self.standard_price = (self.mrg * self.list_price) / 100

    @api.onchange("standard_price", "mrg") # removed "list_price"
    def _onchange_vente(self):
        if self.standard_price != 0 and self.mrg != 0:
            self.list_price = self.standard_price * (1 + self.mrg)
</code>```

Edit: Further reading of the tutorial, it has this to say:

In many cases, both computed fields and onchanges may be used to achieve the same result. Always prefer computed fields since they are also triggered outside of the context of a form view. Never ever use an onchange to add business logic to your model. This is a very bad idea since onchanges are not automatically triggered when creating a record programmatically; they are only triggered in the form view.

Therefore you might want to make list_price be computed using the @api.depends decorator, assuming this is business logic:

class Marge_product_template(models.Model):
    _name = "product.template"
    _inherit = "product.template"
    mrg = fields.Integer(string="Marge")
    standard_price = fields.Float(string="Cost", store=True)
    list_price = fields.Float(string="List price", calculate=_onchange_vente)

    @api.depends("standard_price", "mrg")
    def _onchange_vente(self):
            self.list_price = self.standard_price * (1 + self.mrg)
```

Title: I want to change values in Odoo

Body:
This is speculation… I've been reading the tutorial and the reference but have never heard of Odoo before today. Quite intrigued by it, though!

The arguments for @api.onchange decorator mean "when these fields change, call this method", right?

If that's true, is it a mistake to have "standard_price" in the decorator when the function is to update self.standard_price?

    @api.onchange("list_price", "standard_price", "mrg")
    #                           ^^^^ error? ^^^^
    def _onchange_cost(self):
        if self.mrg != 0:
            self.standard_price = (self.mrg * self.list_price) / 100
            # ^^ recursion? ^^

And by the same logic, "list_price" should not be in the _onchange_vente decorator.

Can you try this change and see if it works?

    @api.onchange("list_price", "mrg") # removed "standard_price"
    def _onchange_cost(self):
        if self.mrg != 0:
            self.standard_price = (self.mrg * self.list_price) / 100

    @api.onchange("standard_price", "mrg") # removed "list_price"
    def _onchange_vente(self):
        if self.standard_price != 0 and self.mrg != 0:
            self.list_price = self.standard_price * (1 + self.mrg)

Edit: Further reading of the tutorial, it has this to say:

In many cases, both computed fields and onchanges may be used to achieve the same result. Always prefer computed fields since they are also triggered outside of the context of a form view. Never ever use an onchange to add business logic to your model. This is a very bad idea since onchanges are not automatically triggered when creating a record programmatically; they are only triggered in the form view.

Therefore you might want to make list_price be computed using the @api.depends decorator, assuming this is business logic:

class Marge_product_template(models.Model):
    _name = "product.template"
    _inherit = "product.template"
    mrg = fields.Integer(string="Marge")
    standard_price = fields.Float(string="Cost", store=True)
    list_price = fields.Float(string="List price", calculate=_onchange_vente)

    @api.depends("standard_price", "mrg")
    def _onchange_vente(self):
            self.list_price = self.standard_price * (1 + self.mrg)


问:
Annotation-specified bean name conflicts with existing, non-compatible bean def
I'm having a problem with some Spring bean definitions. I have a couple of context xml files that are being loaded by my main() method, and both of them contain almost exclusively a context:component-scan tag. When my main method starts up, I get this error from Spring:

```<code>Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'converterDAO' for bean class [my.package.InMemoryConverterDaoImpl] conflicts with existing, non-compatible bean definition of same name and class [my.other.package.StaticConverterDAOImpl]
</code>```

Both DAO classes are annotated this way:

```<code>@Repository("converterDAO")
public class StaticConverterDAOImpl implements ConverterDAO {
...
}
</code>```

The in-memory dao also has the @Repository("converterDAO") annotation. The dao is referenced in other classes like this:

```<code>...
private @Autowired @Qualifier("converterDAO") ConverterDAO converterDAO;
...
</code>```

I want one DAO to override the definition of the other one, which as I always understood it was one of the principal reasons to use a DI framework in the first place. I've been doing this with xml  definitions for years and never had any problems. But not so with component scans and annotated bean definitions? And what does Spring mean when it says they are not "compatible"? They implement the same interface, and they are autowired into fields that are of that interface type. Why the heck are they not compatible?

Can someone provide me with a way for one annotated, component-scanned bean to override another?

答:
In my case, issue was with pom.xml
I had dependency added in my application pom.xml for two different packages, which were reflecting to same class name.

Check your pom.xml or annotations which can be the possible injection point for same class.

Body:
I'm having a problem with some Spring bean definitions. I have a couple of context xml files that are being loaded by my main() method, and both of them contain almost exclusively a context:component-scan tag. When my main method starts up, I get this error from Spring:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'converterDAO' for bean class [my.package.InMemoryConverterDaoImpl] conflicts with existing, non-compatible bean definition of same name and class [my.other.package.StaticConverterDAOImpl]

Both DAO classes are annotated this way:

@Repository("converterDAO")
public class StaticConverterDAOImpl implements ConverterDAO {
...
}

The in-memory dao also has the @Repository("converterDAO") annotation. The dao is referenced in other classes like this:

...
private @Autowired @Qualifier("converterDAO") ConverterDAO converterDAO;
...

I want one DAO to override the definition of the other one, which as I always understood it was one of the principal reasons to use a DI framework in the first place. I've been doing this with xml  definitions for years and never had any problems. But not so with component scans and annotated bean definitions? And what does Spring mean when it says they are not "compatible"? They implement the same interface, and they are autowired into fields that are of that interface type. Why the heck are they not compatible?

Can someone provide me with a way for one annotated, component-scanned bean to override another?


问:
JHipster connect to H2 DB with external SQL editor
I can connect to my H2 DB in my browser:

```<code>http://localhost:8081/h2-console/login.jsp?jsessionid=649273874cf6ca550067b7f4bc033497
</code>```

With Dbvisualizer I can connect but my schema and tables are not there?

Connect string for browser:

```<code>jdbc:h2:file:./target/h2db/db/my;DB_CLOSE_DELAY=-1
</code>```

I have tried:

```<code>jdbc:h2:file:./target/h2db/db/my;DB_CLOSE_DELAY=-1
jdbc:h2:file:<absolute path>/my;DB_CLOSE_DELAY=-1
jdbc:h2:tcp://localhost:9092/my;DB_CLOSE_DELAY=-1
jdbc:h2:tcp://localhost:9092/<absolute path>/my;DB_CLOSE_DELAY=-1
</code>```

What JDBC string should I use for an external tool?

答:
Here you go!

Here is how to configure it in IntelliJ Idea.

Body:
I can connect to my H2 DB in my browser:

http://localhost:8081/h2-console/login.jsp?jsessionid=649273874cf6ca550067b7f4bc033497

With Dbvisualizer I can connect but my schema and tables are not there?

Connect string for browser:

jdbc:h2:file:./target/h2db/db/my;DB_CLOSE_DELAY=-1

I have tried:

jdbc:h2:file:./target/h2db/db/my;DB_CLOSE_DELAY=-1
jdbc:h2:file:<absolute path>/my;DB_CLOSE_DELAY=-1
jdbc:h2:tcp://localhost:9092/my;DB_CLOSE_DELAY=-1
jdbc:h2:tcp://localhost:9092/<absolute path>/my;DB_CLOSE_DELAY=-1

What JDBC string should I use for an external tool?


问:
PHP Regular expressions problem
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

```<code>$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/<TR[^>]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data <br />");

}
}
</code>```

HTML DATA:

```<code><TR class=" light ">
Stuff in here
</TR>
</code>```

Any help would be appreciated,

Thanks!

答:
Try this one instead

http://sandbox.phpcode.eu/g/bba70.php

```<code>if(preg_match_all('/<TR[^>]*>(.*?)<\/TR>/msU', $printable, $matches)) {
     foreach($matches[1] as $match) {
          echo("$match <br />");
      }
}
</code>```

Title: PHP Regular expressions problem

Body:
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/
]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data
");

}
}

HTML DATA:

Stuff in here

Any help would be appreciated,

Thanks!

Body:
Try this one instead

http://sandbox.phpcode.eu/g/bba70.php

if(preg_match_all('/<TR[^>]*>(.*?)<\/TR>/msU', $printable, $matches)) {
     foreach($matches[1] as $match) {
          echo("$match <br />");
      }
}


问:
Laravel:Error when Implementing JWT authentication
I am experiencing an error when trying to post the API through Postman to authenticate users in the site.

login function:

```<code>    public function login(Request $request)
    {

     $credentials = $request->only('email', 'password');

     if ($token = $this->guard()->attempt($credentials)) {
        return $this->respondWithToken($token);
     }
     return response()->json(['error' => 'Unauthorized'], 401);

  }
</code>```

the guard function

```<code>  public function guard()
  {
   return Auth::guard();
  }
</code>```

The error shown on postman

```<code>"message": "Call to undefined method Tymon\\JWTAuth\\Contracts\\Providers\\Auth::guard()",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
</code>```

How to solve this?

答:
I have faced this problem continuously. But the solution was when I used bcrypt() on the password.

```<code>bcrypt($password);
</code>```

Body:
I am experiencing an error when trying to post the API through Postman to authenticate users in the site.

login function:

    public function login(Request $request)
    {

     $credentials = $request->only('email', 'password');

     if ($token = $this->guard()->attempt($credentials)) {
        return $this->respondWithToken($token);
     }
     return response()->json(['error' => 'Unauthorized'], 401);

  }

the guard function

  public function guard()
  {
   return Auth::guard();
  }

The error shown on postman

"message": "Call to undefined method Tymon\\JWTAuth\\Contracts\\Providers\\Auth::guard()",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",

How to solve this?

Body:
I have faced this problem continuously. But the solution was when I used bcrypt() on the password.

bcrypt($password);


问:
AWS Lambda: 'MemorySize' value failed to satisfy constraint
I have a really weird problem while trying to change Lambda's memory size. It's clearly stated in the UI that we can Set memory to between 128 MB and 10240 MB, but when I set 8192 value and click Apply, I am getting the following error message:

'MemorySize' value failed to satisfy constraint: Member must have value less than or equal to 3008

Already checked the Quotas and it's all good there. Honestly, I am stuck

Thanks

答:
I got an answer from AWS support:

Lambda functions with memory configuration greater than 3GB are currently unavailable for first time use in multiple regions. We are working on restoring this feature and mitigations are in progress. If you urgently require to use your function with memory greater than 3GB, please provide your account and region details so we can expedite access internally.


问:
How to call current temperature from openweathermap with axios
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

```<code>function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}
</code>```

Any advice on what im doing wrong would be great!

答:
You can call your getWeather function like below:

const getWeather = () => {
             axios.get(`https://api.openweathermap.org/data/2.5/weather?
                  lat=${latitude}&lon=${longitude}&appid=${api_key}`)
            .then((response)=>setData(response.data.main.temp))
            .catch((err)=> consol.log(err))
                         }

```

Body:
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}

Any advice on what im doing wrong would be great!