问:
Migrating .sqlproj to Sdk style breaks certain database options
I'm trying to migrate my existing .sqlproj targeting .NET Framework 4.7.2 to the new Sdk style project so that I can generate the .dacpac using the new .NET SDK. My new .csproj looks like this:

```<code><Project Sdk="MSBuild.Sdk.SqlProj/1.17.3">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <SqlServerVersion>SqlAzure</SqlServerVersion>
    <BundledNETCoreAppTargetFrameworkVersion>5.0</BundledNETCoreAppTargetFrameworkVersion>
  </PropertyGroup>

  <PropertyGroup>
    <SchemaVersion>2.0</SchemaVersion>

    <CompatibilityMode>130</CompatibilityMode>
    <AnsiNullDefault>False</AnsiNullDefault>
    <AnsiPadding>False</AnsiPadding>
    <AnsiWarnings>False</AnsiWarnings>
    <ArithAbort>False</ArithAbort>
    <ConcatNullYieldsNull>False</ConcatNullYieldsNull>
    <NumericRoundAbort>False</NumericRoundAbort>
    <RecursiveTriggersEnabled>False</RecursiveTriggersEnabled>
.......................
  </PropertyGroup>
</code>```

The second PropertyGroup is a 99% copy of the same element from the old .sqlproj - I want to be sure the new .dacpac is identical to the old one. The problem is a few of the configuration params are not respected by the new .csproj. If I generate a script from the new .dacpac with SqlPackage utility against the same database it contains the following which is not present in the old script:

```<code>IF EXISTS (SELECT 1
           FROM   [sys].[databases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ANSI_PADDING ON,
                ANSI_WARNINGS ON,
                ARITHABORT ON,
                QUOTED_IDENTIFIER ON,
                ANSI_NULL_DEFAULT ON
            WITH ROLLBACK IMMEDIATE;
    END
</code>```

In other words, the params like AnsiPadding and AnsiWarnings and a few others are ignored. Moreover, I had to comment a few other params that caused the build to fail like DbScopedConfigLegacyCardinalityEstimation:

System.ArgumentException: Unable to parse value for property with name
DbScopedConfigLegacyCardinalityEstimation: Off (Parameter 'value')

Why is this happening and how can I fix it? I need to be sure switching to Sdk style project doesn't break my database which would be a disaster in production.

答:
Apparently they renamed a lot of things. So if you want to migrate your .sqlproj to the new Sdk style .csproj you need to be careful. AnsiPadding is now AnsiPaddingOn, AnsiWarnings is AnsiWarningsOn, etc.

<AnsiPaddingOn>False</AnsiPaddingOn>
<AnsiWarningsOn>False</AnsiWarningsOn>
<ArithAbortOn>False</ArithAbortOn>
```
<p>Some non-boolean params are also changed. For example:</p>
<pre class="lang-xml prettyprint-override"><code><TargetRecoveryTimeUnit>SECONDS</TargetRecoveryTimeUnit>`
</code>```

Now needs to be (notice the casing, see Time Unit enum)

<TargetRecoveryTimeUnit>Seconds</TargetRecoveryTimeUnit>
```

Check the official Microsoft.SqlServer.Dac.Model documentation and always verify the generated script. I've successfully migrated my project and now use  .dacpac built from the new .csproj to apply my migrations.

Body:
I'm trying to migrate my existing .sqlproj targeting .NET Framework 4.7.2 to the new Sdk style project so that I can generate the .dacpac using the new .NET SDK. My new .csproj looks like this:

<Project Sdk="MSBuild.Sdk.SqlProj/1.17.3">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <SqlServerVersion>SqlAzure</SqlServerVersion>
    <BundledNETCoreAppTargetFrameworkVersion>5.0</BundledNETCoreAppTargetFrameworkVersion>
  </PropertyGroup>

  <PropertyGroup>
    <SchemaVersion>2.0</SchemaVersion>

    <CompatibilityMode>130</CompatibilityMode>
    <AnsiNullDefault>False</AnsiNullDefault>
    <AnsiPadding>False</AnsiPadding>
    <AnsiWarnings>False</AnsiWarnings>
    <ArithAbort>False</ArithAbort>
    <ConcatNullYieldsNull>False</ConcatNullYieldsNull>
    <NumericRoundAbort>False</NumericRoundAbort>
    <RecursiveTriggersEnabled>False</RecursiveTriggersEnabled>
.......................
  </PropertyGroup>

The second PropertyGroup is a 99% copy of the same element from the old .sqlproj - I want to be sure the new .dacpac is identical to the old one. The problem is a few of the configuration params are not respected by the new .csproj. If I generate a script from the new .dacpac with SqlPackage utility against the same database it contains the following which is not present in the old script:

IF EXISTS (SELECT 1
           FROM   [sys].[databases]
           WHERE  [name] = N'$(DatabaseName)')
    BEGIN
        ALTER DATABASE [$(DatabaseName)]
            SET ANSI_PADDING ON,
                ANSI_WARNINGS ON,
                ARITHABORT ON,
                QUOTED_IDENTIFIER ON,
                ANSI_NULL_DEFAULT ON
            WITH ROLLBACK IMMEDIATE;
    END

In other words, the params like AnsiPadding and AnsiWarnings and a few others are ignored. Moreover, I had to comment a few other params that caused the build to fail like DbScopedConfigLegacyCardinalityEstimation:

System.ArgumentException: Unable to parse value for property with name
DbScopedConfigLegacyCardinalityEstimation: Off (Parameter 'value')

Why is this happening and how can I fix it? I need to be sure switching to Sdk style project doesn't break my database which would be a disaster in production.

Body:
Apparently they renamed a lot of things. So if you want to migrate your .sqlproj to the new Sdk style .csproj you need to be careful. AnsiPadding is now AnsiPaddingOn, AnsiWarnings is AnsiWarningsOn, etc.

<AnsiPaddingOn>False</AnsiPaddingOn>
<AnsiWarningsOn>False</AnsiWarningsOn>
<ArithAbortOn>False</ArithAbortOn>

Some non-boolean params are also changed. For example:

<TargetRecoveryTimeUnit>SECONDS</TargetRecoveryTimeUnit>`

Now needs to be (notice the casing, see Time Unit enum)

<TargetRecoveryTimeUnit>Seconds</TargetRecoveryTimeUnit>

Check the official Microsoft.SqlServer.Dac.Model documentation and always verify the generated script. I've successfully migrated my project and now use  .dacpac built from the new .csproj to apply my migrations.


来源: stackexchange

问:
C#/VB.Net How to collapse specific values in a list
```<code>Column1 Column2 Column3
AAAA    a       07-02-2022
BBBB    a       07-02-2022
CCCC    a       07-02-2022
DDDD    a       07-02-2022
EEEE    a       07-02-2022
AAAA    b       07-02-2022
</code>```

I have a list like the above, how do I collapse(or take the first) when column 1 is "AAAA" or "BBBB", and the column2/column3 values are the same.
This rule only applies to "AAAA" and "BBBB".
I was thinking to group by column2/column3, and then I don't know what exactly I should proceed.

```<code>        Dim collapsed = list.GroupBy(Function(x) x.Column2 + x.Column3)
</code>```

The results I want is : (Second line of BBBB was removed)

```<code>Column1 Column2 Column3
AAAA    a       07-02-2022
CCCC    a       07-02-2022
DDDD    a       07-02-2022
EEEE    a       07-02-2022
AAAA    b       07-02-2022
</code>```

答:
You can use the Distinct method:

```<code>Imports ConsoleApp1

Module Module1

    Class X
        Property Column1 As String
        Property Column2 As String
        Property Column3 As String

        Sub New()
            ' Empty constructor
        End Sub

        Sub New(a As String, b As String, c As String)
            Column1 = a
            Column2 = b
            Column3 = c
        End Sub

        Public Shared Operator =(a As X, b As X) As Boolean
            If IsSpecialColumn(a.Column1) AndAlso IsSpecialColumn(b.Column1) Then
                Return (a.Column2 = b.Column2) AndAlso (a.Column3 = b.Column3)
            End If
            Return False
        End Operator

        Public Shared Operator <>(a As X, b As X) As Boolean
            If IsSpecialColumn(a.Column1) AndAlso IsSpecialColumn(b.Column1) Then
                Return (a.Column2 <> b.Column2) OrElse (a.Column3 <> b.Column3)
            End If
            Return False
        End Operator

        Public Overrides Function ToString() As String
            Return $"{Column1} {Column2} {Column3}"
        End Function

    End Class

    Public Class XComparer
        Implements IEqualityComparer(Of X)

        Public Function Equals1(ByVal a As X, ByVal b As X) As Boolean Implements IEqualityComparer(Of X).Equals

            Return a = b

        End Function

        Public Function GetHashCode1(ByVal a As X) As Integer Implements IEqualityComparer(Of X).GetHashCode

            If a Is Nothing Then Return 0

            If IsSpecialColumn(a.Column1) Then
                Return a.Column2.GetHashCode() Xor a.Column3.GetHashCode()
            End If

            Return a.Column1.GetHashCode() Xor a.Column2.GetHashCode() Xor a.Column3.GetHashCode()

        End Function

    End Class

    Function IsSpecialColumn(c As String) As Boolean
        Return c = "AAAA" OrElse c = "BBBB"
    End Function

    Sub Main()
        Dim q As New List(Of X) From {New X("AAAA", "a", "07-02-2022"),
                                      New X("BBBB", "a", "07-02-2022"),
                                      New X("CCCC", "a", "07-02-2022"),
                                      New X("DDDD", "a", "07-02-2022"),
                                      New X("EEEE", "a", "07-02-2022"),
                                      New X("AAAA", "b", "07-02-2022")}

        Dim r = q.Distinct(New XComparer())

        Console.WriteLine(String.Join(vbCrLf, r))

        Console.ReadLine()

    End Sub

End Module
</code>```

Outputs:

```<code>AAAA a 07-02-2022
CCCC a 07-02-2022
DDDD a 07-02-2022
EEEE a 07-02-2022
AAAA b 07-02-2022
</code>```

However, I do not know if it will always remove later occurrences in preference to an earlier one.

ContentLicense: CC BY-SA 4.0

Body:
Column1 Column2 Column3
AAAA    a       07-02-2022
BBBB    a       07-02-2022
CCCC    a       07-02-2022
DDDD    a       07-02-2022
EEEE    a       07-02-2022
AAAA    b       07-02-2022

I have a list like the above, how do I collapse(or take the first) when column 1 is "AAAA" or "BBBB", and the column2/column3 values are the same.
This rule only applies to "AAAA" and "BBBB".
I was thinking to group by column2/column3, and then I don't know what exactly I should proceed.

        Dim collapsed = list.GroupBy(Function(x) x.Column2 + x.Column3)

The results I want is : (Second line of BBBB was removed)

Column1 Column2 Column3
AAAA    a       07-02-2022
CCCC    a       07-02-2022
DDDD    a       07-02-2022
EEEE    a       07-02-2022
AAAA    b       07-02-2022

Body:
You can use the Distinct method:

Imports ConsoleApp1

Module Module1

    Class X
        Property Column1 As String
        Property Column2 As String
        Property Column3 As String

        Sub New()
            ' Empty constructor
        End Sub

        Sub New(a As String, b As String, c As String)
            Column1 = a
            Column2 = b
            Column3 = c
        End Sub

        Public Shared Operator =(a As X, b As X) As Boolean
            If IsSpecialColumn(a.Column1) AndAlso IsSpecialColumn(b.Column1) Then
                Return (a.Column2 = b.Column2) AndAlso (a.Column3 = b.Column3)
            End If
            Return False
        End Operator

        Public Shared Operator <>(a As X, b As X) As Boolean
            If IsSpecialColumn(a.Column1) AndAlso IsSpecialColumn(b.Column1) Then
                Return (a.Column2 <> b.Column2) OrElse (a.Column3 <> b.Column3)
            End If
            Return False
        End Operator

        Public Overrides Function ToString() As String
            Return $"{Column1} {Column2} {Column3}"
        End Function

    End Class

    Public Class XComparer
        Implements IEqualityComparer(Of X)

        Public Function Equals1(ByVal a As X, ByVal b As X) As Boolean Implements IEqualityComparer(Of X).Equals

            Return a = b

        End Function

        Public Function GetHashCode1(ByVal a As X) As Integer Implements IEqualityComparer(Of X).GetHashCode

            If a Is Nothing Then Return 0

            If IsSpecialColumn(a.Column1) Then
                Return a.Column2.GetHashCode() Xor a.Column3.GetHashCode()
            End If

            Return a.Column1.GetHashCode() Xor a.Column2.GetHashCode() Xor a.Column3.GetHashCode()

        End Function

    End Class

    Function IsSpecialColumn(c As String) As Boolean
        Return c = "AAAA" OrElse c = "BBBB"
    End Function

    Sub Main()
        Dim q As New List(Of X) From {New X("AAAA", "a", "07-02-2022"),
                                      New X("BBBB", "a", "07-02-2022"),
                                      New X("CCCC", "a", "07-02-2022"),
                                      New X("DDDD", "a", "07-02-2022"),
                                      New X("EEEE", "a", "07-02-2022"),
                                      New X("AAAA", "b", "07-02-2022")}

        Dim r = q.Distinct(New XComparer())

        Console.WriteLine(String.Join(vbCrLf, r))

        Console.ReadLine()

    End Sub

End Module

Outputs:

AAAA a 07-02-2022
CCCC a 07-02-2022
DDDD a 07-02-2022
EEEE a 07-02-2022
AAAA b 07-02-2022

However, I do not know if it will always remove later occurrences in preference to an earlier one.


问:
Flask health error: {"status": 500, "title": "The live check function could not be imported"}
I am trying to add health liveness and readiness into Flask API as follows:

```<code>from flask import Flask
from flask_healthz import healthz
from flask_healthz import HealthError

app = Flask(__name__)
app.register_blueprint(healthz, url_prefix="/healthz")

def printok():
    print("Everything is fine")

def liveness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

def readiness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

app.config.update(
    HEALTHZ = {
        "live": "app.liveness",
        "ready": "app.readiness",
    }
)
@app.route("/")
def hello():
    return "Hello World"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
</code>```

but when I run curl to check it, I get the error "The live function could not be imported":

```<code>$ curl localhost:5000/healthz/live
{"status": 500, "title": "The live check function could not be imported"}
</code>```

or

```<code> $ curl localhost:5000/healthz/ready
{"status": 500, "title": "The ready check function could not be imported"}
</code>```

it is interesting that this example has already been suggested by this link healthz for flask as working

Any idea why this error occurs? and how can I resolve it?

答:
For me this was due to PYTHONPATH environment variable. The HEALTHZ map values needs to point to the liveliness and readiness methods, for which PYTHONPATH is required.

In my PyCharm's debug, this environment variable was set correctly while in run this was not set. Manual adding this to run fixed this. If you are Dockerizing the application, this will help - https://stackoverflow.com/a/49631407/2112865.

Body:
I am trying to add health liveness and readiness into Flask API as follows:

from flask import Flask
from flask_healthz import healthz
from flask_healthz import HealthError

app = Flask(__name__)
app.register_blueprint(healthz, url_prefix="/healthz")

def printok():
    print("Everything is fine")

def liveness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

def readiness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

app.config.update(
    HEALTHZ = {
        "live": "app.liveness",
        "ready": "app.readiness",
    }
)
@app.route("/")
def hello():
    return "Hello World"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

but when I run curl to check it, I get the error "The live function could not be imported":

$ curl localhost:5000/healthz/live
{"status": 500, "title": "The live check function could not be imported"}

or

 $ curl localhost:5000/healthz/ready
{"status": 500, "title": "The ready check function could not be imported"}

it is interesting that this example has already been suggested by this link healthz for flask as working

Any idea why this error occurs? and how can I resolve it?


问:
With WebApplicationFactory, add configuration source before Program.cs executes
I am using the new minimal .NET 6 hosting model, and I have an integration test.

Obviously Program.cs needs configuration values, so I want to use a custom appsettings.Test.json file. Docs say I can use ConfigureAppConfiguration but its delegate runs after Program, hence Program has no configuration. Here's the code added to the Minimal API Playground sample code:

internal class PlaygroundApplication : WebApplicationFactory<Program>
{
    private readonly string _environment;

    public PlaygroundApplication(string environment = "Development")
    {
        _environment = environment;
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseEnvironment(_environment);

        builder.ConfigureAppConfiguration(config =>
        {
            config.AddJsonFile(appSettings); // runs AFTER Program.cs
        });

        // Add mock/test services to the builder here
        builder.ConfigureServices(services =>
        {
        });

        return base.CreateHost(builder);
    }
}
```
<p>How can I provide configuration to <code>Program.cs</code>?</p>
<pre class="lang-cs prettyprint-override"><code>var builder = WebApplication.CreateBuilder(args);

var keyVaultName = builder.Configuration["KeyVaultName"]; // null

builder.Configuration.AddAzureKeyVault(new SecretClient(
    new Uri($"https://{keyVaultName}.vault.azure.net/"),
    new DefaultAzureCredential()), new KeyVaultSecretManager());
</code>```

I can set environment to Testand then in Program do:

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json");

var keyVaultName = builder.Configuration["KeyVaultName"]; // has value from json

builder.Configuration.AddAzureKeyVault(new SecretClient(
    new Uri($"https://{keyVaultName}.vault.azure.net/"),
    new DefaultAzureCredential()), new KeyVaultSecretManager());

```

But is that correct?

答:
I found a workaround that I detail here: https://github.com/dotnet/aspnetcore/issues/37680#issuecomment-1032922656

If you override WebApplicationFactory<T>.CreateHost() and call IHostBuilder.ConfigureHostConfiguration() before calling base.CreateHost() the configuration you add will be visible inbetween WebApplication.CreateBuilder() and builder.Build(). From my testing it's visible in all the various places you'd look at the config (callbacks, etc.).

Body:
I am using the new minimal .NET 6 hosting model, and I have an integration test.

Obviously Program.cs needs configuration values, so I want to use a custom appsettings.Test.json file. Docs say I can use ConfigureAppConfiguration but its delegate runs after Program, hence Program has no configuration. Here's the code added to the Minimal API Playground sample code:

internal class PlaygroundApplication : WebApplicationFactory<Program>
{
    private readonly string _environment;

    public PlaygroundApplication(string environment = "Development")
    {
        _environment = environment;
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseEnvironment(_environment);

        builder.ConfigureAppConfiguration(config =>
        {
            config.AddJsonFile(appSettings); // runs AFTER Program.cs
        });

        // Add mock/test services to the builder here
        builder.ConfigureServices(services =>
        {
        });

        return base.CreateHost(builder);
    }
}

How can I provide configuration to Program.cs?

var builder = WebApplication.CreateBuilder(args);

var keyVaultName = builder.Configuration["KeyVaultName"]; // null

builder.Configuration.AddAzureKeyVault(new SecretClient(
    new Uri($"https://{keyVaultName}.vault.azure.net/"),
    new DefaultAzureCredential()), new KeyVaultSecretManager());

I can set environment to Testand then in Program do:

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json");

var keyVaultName = builder.Configuration["KeyVaultName"]; // has value from json

builder.Configuration.AddAzureKeyVault(new SecretClient(
    new Uri($"https://{keyVaultName}.vault.azure.net/"),
    new DefaultAzureCredential()), new KeyVaultSecretManager());

But is that correct?


问:
PHP & Parsing a JSON response
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

```<code><?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

<html>
    <title>Test Rhyme</title>
<body>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>
    <div id="results">
        <?php
            print_r(json_decode($result, true));
        ?>
    </div>
</body>

</html>
</code>```

答:
Here's a simplified way to do it without cURL</p>

```<code>function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        $json = file_get_contents($postURL);
        return $json;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP & Parsing a JSON response

Body:
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

<?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

    <title>Test Rhyme</title>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>

        <?php
            print_r(json_decode($result, true));
        ?>

Body:
Here's a simplified way to do it without cURL

function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        $json = file_get_contents($postURL);
        return $json;
    }


问:
Inverting a real-valued index grid
OpenCV's remap() uses a real-valued index grid to sample a grid of values from an image using bilinear interpolation, and returns the grid of samples as a new image.

To be precise, let:

```<code>A = an image
X = a grid of real-valued X coords into the image.
Y = a grid of real-valued Y coords into the image.
B = remap(A, X, Y)
</code>```

Then for all pixel coordinates i, j,

```<code>B[i, j] = A(X[i, j], Y[i, j])
</code>```

Where the round-braces notation A(x, y) denotes using bilinear interpolation to solve for the pixel value of image A using float-valued coords x and y.

My question is: given an index grid X, Y, how can I generate an "inverse grid" X^-1, Y^-1 such that:

```<code>X(X^-1[i, j], Y^-1[i, j]) = i
Y(X^-1[i, j], Y^-1[i, j]) = j
</code>```

And

```<code>X^-1(X[i, j], Y[i, j]) = i
Y^-1(X[i, j], Y[i, j]) = j
</code>```

For all integer pixel coordinates i, j?

FWIW, the image and index maps X and Y are the same shape. However, there is no a priori structure to the index maps X and Y. For example, they're not necessarily affine or rigid transforms. They may even be uninvertible, e.g. if X, Y maps multiple pixels in A to the same exact pixel coordinate in B. I'm looking for ideas for a method that will find a reasonable inverse map if one exists.

The solution need not be OpenCV-based, as I'm not using OpenCV, but another library that has a remap() implementation. While any suggestions are welcome, I'm particularly keen on something that's "mathematically correct", i.e. if my map M is perfectly invertible, the method should find the perfect inverse, within some small margin of machine precision.

答:
A KNNRegressor has all the necessary components to invert the grid mapping!

Here you go:

```<code>from sklearn.neighbors import KNeighborsRegressor

def get_inverse_maps(map1, map2):
    regressor = KNeighborsRegressor(3)
    X = np.concatenate((map2[..., None], map1[..., None]), axis=-1).reshape(-1, 2)
    y = np.indices(map1.shape).transpose((1, 2, 0)).reshape(-1, 2)
    regressor.fit(X, y)
    map_inv = regressor.predict(y).reshape(map1.shape + (2,)).astype(np.float32)
    map_inv2, map_inv1 = map_inv[..., 0], map_inv[..., 1]
    return map_inv1, map_inv2
</code>```

Title: Inverting a real-valued index grid

Body:
OpenCV's remap() uses a real-valued index grid to sample a grid of values from an image using bilinear interpolation, and returns the grid of samples as a new image.

To be precise, let:

A = an image
X = a grid of real-valued X coords into the image.
Y = a grid of real-valued Y coords into the image.
B = remap(A, X, Y)

Then for all pixel coordinates i, j,

B[i, j] = A(X[i, j], Y[i, j])

Where the round-braces notation A(x, y) denotes using bilinear interpolation to solve for the pixel value of image A using float-valued coords x and y.

My question is: given an index grid X, Y, how can I generate an "inverse grid" X^-1, Y^-1 such that:

X(X^-1[i, j], Y^-1[i, j]) = i
Y(X^-1[i, j], Y^-1[i, j]) = j

And

X^-1(X[i, j], Y[i, j]) = i
Y^-1(X[i, j], Y[i, j]) = j

For all integer pixel coordinates i, j?

FWIW, the image and index maps X and Y are the same shape. However, there is no a priori structure to the index maps X and Y. For example, they're not necessarily affine or rigid transforms. They may even be uninvertible, e.g. if X, Y maps multiple pixels in A to the same exact pixel coordinate in B. I'm looking for ideas for a method that will find a reasonable inverse map if one exists.

The solution need not be OpenCV-based, as I'm not using OpenCV, but another library that has a remap() implementation. While any suggestions are welcome, I'm particularly keen on something that's "mathematically correct", i.e. if my map M is perfectly invertible, the method should find the perfect inverse, within some small margin of machine precision.

Body:
A KNNRegressor has all the necessary components to invert the grid mapping!

Here you go:

from sklearn.neighbors import KNeighborsRegressor

def get_inverse_maps(map1, map2):
    regressor = KNeighborsRegressor(3)
    X = np.concatenate((map2[..., None], map1[..., None]), axis=-1).reshape(-1, 2)
    y = np.indices(map1.shape).transpose((1, 2, 0)).reshape(-1, 2)
    regressor.fit(X, y)
    map_inv = regressor.predict(y).reshape(map1.shape + (2,)).astype(np.float32)
    map_inv2, map_inv1 = map_inv[..., 0], map_inv[..., 1]
    return map_inv1, map_inv2


问:
Error 52134 Invalid APNs device token in Flutter "twilio_voice"
I'm using "twilio_voice" for a flutter application for generating and receiving call from app to real number and vice versa.
When I'm trying to call to a real number from app it's working fine. But when i'm trying to receive call within the app, it's not working.
When I checked at Twilio console I found "Error 52134 Invalid APNs device token".

I have already created the VOIP certificate in Appstore console and also generated a Push Credential in Twilio console. The SID also used in the backend.

In my applog I also found "Successfully registered for VoIP push notifications." as a confirmation.
But still not working.

答:
After your app has register for the push notification, you will need to create a binding with the Push Token to the Twilio server. For that you will need an intermediate server of your own(Can be a Node js/PHP/Python server application). First you will make a rest api request to your own server from the app. The server application will send a binding request to Twilio server. Once that is done, you will receive push notification every time there is an incoming call via didReceiveRemoteNotification() delegate in AppDelegate.

For the server application sample and Rest api sample for iOS app, follow this documentation from Twilio:
https://www.twilio.com/docs/notify/register-for-notifications-ios


问:
react native - dynamic reanimated2 entering and exiting animation
I am using reanimated2 for my react native project. I want to dynamically change the animation to ZoomInLeft or ZoomInRight based on the situation:

```<code>export default function SigninCard(props){
    const [zoomout,setZoomout] = useState('left')

    function handleExiting(s){
        console.log(s)
        setZoomout(s)
    }

    <Animated.View
        style={{flex:1, alignItems:'center'}}
        entering={ZoomInRight}
        exiting={zoomout=='left' ? ZoomOutLeft : ZoomOutRight}
        ...
        <Button title='Register' onPress={()=>{
            handleExiting('left');
            parentgoto('userdetails';
        )}}
    />
        <Button title='Login' onPress={()=>{
                handleExiting('right');
                parentgoto('userdetails';
            )}}
        />
    </Animated.View>
}
</code>```

Like to code above, I use zoomout variable to decide if I want the animation to go right or left, then set ternary condition in exiting. But somehow the animation will always go left. even I click on the right button.

After a few tests, I believe the decision factor is at the useState('left'). even though I setZoomOut('right'), it don't seems to change the state.

How can I resolve this? Or is there another way to achieve this?

答:
the <Animated.View /> seems to be the default one, so I assume that exiting={zoomout=='left' ? ZoomOutLeft : ZoomOutRight} is not being triggered since it's not a predefined property of the native <View /> element.

What you could do is use an useEffect() hook in which you check the state and apply the animation. Below you can find an example:

```<code>export default function SigninCard(props){
  const [zoomout,setZoomout] = useState(null);

  useEffect(() => {
    switch(zoomout) {
      case 'left':
      ZoomOutLeft();
      break;

      case 'right':
      ZoomOutRight();
      break;

      default:
      break;
    }
  }, [zoomout]);

  return (<Animated.View
      style={{flex:1, alignItems:'center'}}>
      <Button title='Register' onPress={()=>{
        setZoomout('left');
        parentgoto('userdetails');
      )}}

      <Button title='Login' onPress={()=>{
         setZoomout('right')
         parentgoto('userdetails');
      )}}
    />
  </Animated.View>);
}
</code>```

I also assume that entering={ZoomInRight} won't work either, to fix it you can apply the same logic as shown above.

Body:
I am using reanimated2 for my react native project. I want to dynamically change the animation to ZoomInLeft or ZoomInRight based on the situation:

export default function SigninCard(props){
    const [zoomout,setZoomout] = useState('left')

    function handleExiting(s){
        console.log(s)
        setZoomout(s)
    }

    <Animated.View
        style={{flex:1, alignItems:'center'}}
        entering={ZoomInRight}
        exiting={zoomout=='left' ? ZoomOutLeft : ZoomOutRight}
        ...
        <Button title='Register' onPress={()=>{
            handleExiting('left');
            parentgoto('userdetails';
        )}}
    />
        <Button title='Login' onPress={()=>{
                handleExiting('right');
                parentgoto('userdetails';
            )}}
        />
    </Animated.View>
}

Like to code above, I use zoomout variable to decide if I want the animation to go right or left, then set ternary condition in exiting. But somehow the animation will always go left. even I click on the right button.

After a few tests, I believe the decision factor is at the useState('left'). even though I setZoomOut('right'), it don't seems to change the state.

How can I resolve this? Or is there another way to achieve this?

Body:
the <Animated.View /> seems to be the default one, so I assume that exiting={zoomout=='left' ? ZoomOutLeft : ZoomOutRight} is not being triggered since it's not a predefined property of the native <View /> element.

What you could do is use an useEffect() hook in which you check the state and apply the animation. Below you can find an example:

export default function SigninCard(props){
  const [zoomout,setZoomout] = useState(null);

  useEffect(() => {
    switch(zoomout) {
      case 'left':
      ZoomOutLeft();
      break;

      case 'right':
      ZoomOutRight();
      break;

      default:
      break;
    }
  }, [zoomout]);

  return (<Animated.View
      style={{flex:1, alignItems:'center'}}>
      <Button title='Register' onPress={()=>{
        setZoomout('left');
        parentgoto('userdetails');
      )}}

      <Button title='Login' onPress={()=>{
         setZoomout('right')
         parentgoto('userdetails');
      )}}
    />
  </Animated.View>);
}

I also assume that entering={ZoomInRight} won't work either, to fix it you can apply the same logic as shown above.


问:
'virtualenv' is not recognized as an internal or external command, operable program or batch file
After I installed Python and Djangom, I'm trying to use virtualenv for django project purpose using virtualenv. I installed virtualenv using pip.

```<code>pip install virtualenv # got install successfully
</code>```

When I tried to run it, I got the error message

```<code>C:\Users\gshiv\Desktop\DjangoProject>virtualenv
'virtualenv' is not recognized as an internal or external command,
operable program or batch file.
</code>```

答:
Try to run</p>
```<code>    PowerShell.exe -command "./venv/Scripts/activate"
</code>```

Body:
After I installed Python and Djangom, I'm trying to use virtualenv for django project purpose using virtualenv. I installed virtualenv using pip.

pip install virtualenv # got install successfully

When I tried to run it, I got the error message

C:\Users\gshiv\Desktop\DjangoProject>virtualenv
'virtualenv' is not recognized as an internal or external command,
operable program or batch file.

Body:
Try to run

    PowerShell.exe -command "./venv/Scripts/activate"


问:
Excluding undefined Field Values in MariaDB TypeORM Queries
I have a basic Nest project using TypeORM. A model, Plate, has been contained in its own module and is imported into the main module.

The service for the Plate model contains the following method:

public query(params?: QueryPlateParams, limit: number = 100): Promise<Plate[]> {

    const findOp = PlatesService.FindOperatorMap[params.type];

    const whereObj = {
        // If a find operation is defined, apply it to the value. Otherwise, just use the
        // value itself.
        id: findOp?.(params.value) ?? params.value,
        available: params.isAvailable,
        state: params.state
    };
    console.log(whereObj);

    return this._platesRepository.find({
        where: whereObj,
        take: limit
    });
}
```
<p>The idea of this method is to take the query object, which could have any combination of the <code>value</code>, <code>isAvailable</code>, and <code>state</code> properties defined, then to apply the defined values to the query's <code>WHERE</code> clause with some modification, of course not defining filters for fields which had no value in the source query object.</p>
<p>When a query is made, the following logs are observed.</p>
```{ id: 'ABSOLVE', available: undefined, state: undefined }
query: SELECT `Plate`.`id` AS `Plate_id`, `Plate`.`state` AS `Plate_state`, `Plate`.`available` AS `Plate_available`, `Plate`.`lastChecked` AS `Plate_lastChecked` FROM `plates` `Plate` WHERE (`Plate`.`id` = ? AND `Plate`.`available` = ? AND `Plate`.`state` = ?) LIMIT 100 -- PARAMETERS: ["ABSOLVE",null,null]
```

What's important here is the parameter interpolation at the end of the second line: PARAMETERS: ["ABSOLVE",null,null]. The values for isAvailable and state are undefined, but the SQL statement translated them to null, but undefined and null are distinct values in Javascript/Typescript. The intent, of course, is to ignore undefined values in the query, not interpret them as null.

I found an option for the MongoDB connector that will ignore these undefined values. I do not see the same for the MariaDB/MySQL connector, which is what is being used for this service.

Is there any option to ignore these undefined values instead of interpreting them as null? I'd like to use the IsNull() or null values to explicitly check for SQL NULL.

答:
Sadly you need just to not provide the undefined fields (add filter before passing whereObj into the find function.

Or you can read this thread with some other options dealing with the issue https://github.com/typeorm/typeorm/issues/2934

Basically - the issue is because creator thought that setting property of object to undefined removes the property from the object own properties therefore he treated undefined and null the same.

Body:
I have a basic Nest project using TypeORM. A model, Plate, has been contained in its own module and is imported into the main module.

The service for the Plate model contains the following method:

public query(params?: QueryPlateParams, limit: number = 100): Promise<Plate[]> {

    const findOp = PlatesService.FindOperatorMap[params.type];

    const whereObj = {
        // If a find operation is defined, apply it to the value. Otherwise, just use the
        // value itself.
        id: findOp?.(params.value) ?? params.value,
        available: params.isAvailable,
        state: params.state
    };
    console.log(whereObj);

    return this._platesRepository.find({
        where: whereObj,
        take: limit
    });
}

The idea of this method is to take the query object, which could have any combination of the value, isAvailable, and state properties defined, then to apply the defined values to the query's WHERE clause with some modification, of course not defining filters for fields which had no value in the source query object.

When a query is made, the following logs are observed.

{ id: 'ABSOLVE', available: undefined, state: undefined }
query: SELECT `Plate`.`id` AS `Plate_id`, `Plate`.`state` AS `Plate_state`, `Plate`.`available` AS `Plate_available`, `Plate`.`lastChecked` AS `Plate_lastChecked` FROM `plates` `Plate` WHERE (`Plate`.`id` = ? AND `Plate`.`available` = ? AND `Plate`.`state` = ?) LIMIT 100 -- PARAMETERS: ["ABSOLVE",null,null]

What's important here is the parameter interpolation at the end of the second line: PARAMETERS: ["ABSOLVE",null,null]. The values for isAvailable and state are undefined, but the SQL statement translated them to null, but undefined and null are distinct values in Javascript/Typescript. The intent, of course, is to ignore undefined values in the query, not interpret them as null.

I found an option for the MongoDB connector that will ignore these undefined values. I do not see the same for the MariaDB/MySQL connector, which is what is being used for this service.

Is there any option to ignore these undefined values instead of interpreting them as null? I'd like to use the IsNull() or null values to explicitly check for SQL NULL.


问:
tree visualization with libgraphviz / dot
does anyone have some experience with libgraphviz using the standard c library?

For my current project i would like to write a simple tool which visualize one of my abstract syntax tree in a jpg image or maybe even on a small X11 window. Graphviz itself provides
seven, different libraries i could use and link to my application:

cdt

cgraph

gvc

pack

pathplan

xdot

Unfortanetly, i have no idea which library is necessary for my task. I also don't need to translate my tree representation to the dot language and would like write it directly to an image. (Of course, it Would be also great using an API that abstracts the transformation to the dot language).

Thanks for each advice :)

答:
Please take a look at the libguide.pdf on the graphviz web site. The guide explains how to use graphviz as a library and contains sample programs in c.

The examples also show how to add nodes and edges, and depending on your tree representation, it may be relatively simple to translate it to node and edge creation calls.


问:
How to change HTML Attribude with JavaScript
I have a div where is an HTML Attribute called data-theme inside. I want to ask how do I change the value of the Attribute called data-theme. For example: From: data-theme="dark" to data-theme="light". The value is stored in a variable as a string.

My div:

```

I want to use normal JavaScript.

Body:
I have a div where is an HTML Attribute called data-theme inside. I want to ask how do I change the value of the Attribute called data-theme. For example: From: data-theme="dark" to data-theme="light". The value is stored in a variable as a string.

My div:

I want to use normal JavaScript.

Body: document.getElementById("myId").setAttribute("data-theme", "newValue")


问:
How to add missing images as per warning in "styleimagemissing" event in azure maps? And how to find out which images/icons are missing?
I'm adding a number of icons created from imageSprite.createFromTemplate() method however sometimes I'm receiving the following error . How to resolve it using "styleimagemissing" event? How to find out which image is missing to add in the callback ?. And the symbol layer created using the icons sometimes overlaps over the bubble layer(cluster layer) too in some clusters. I don't know if that is caused due to missing images. Thanks in advance.</p>
```<code> atlas.min.js:55 Image "Scaffold Builder_Inactive_Icon" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.
</code>```

答:
The styleimagemissing event will tell you the ID of the image that is missing. It won't tell you which symbol layer is trying to use that image however as a single image may be used by multiple layers.

Here is an example of how to use this event:

```<code>var iconLoaded = {};

//Add an event to handle the situation when an image is missing from the sprite.
map.events.add('styleimagemissing', function (id) {
    //Check to see if the image is has been or is being loaded. Don't try and load the image multiple times.
    if (!iconLoaded[id]) {
        iconLoaded[id] = true;
        //Load the custom image icon into the map resources.
        map.imageSprite.add(id, '../Common/images/icons/showers.png').then();
    }
});
</code>```

A complete sample is available here: https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/Symbol%20Layer/Load%20missing%20image%20into%20sprite.html

Body:
I'm adding a number of icons created from imageSprite.createFromTemplate() method however sometimes I'm receiving the following error . How to resolve it using "styleimagemissing" event? How to find out which image is missing to add in the callback ?. And the symbol layer created using the icons sometimes overlaps over the bubble layer(cluster layer) too in some clusters. I don't know if that is caused due to missing images. Thanks in advance.

 atlas.min.js:55 Image "Scaffold Builder_Inactive_Icon" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.

Body:
The styleimagemissing event will tell you the ID of the image that is missing. It won't tell you which symbol layer is trying to use that image however as a single image may be used by multiple layers.

Here is an example of how to use this event:

var iconLoaded = {};

//Add an event to handle the situation when an image is missing from the sprite.
map.events.add('styleimagemissing', function (id) {
    //Check to see if the image is has been or is being loaded. Don't try and load the image multiple times.
    if (!iconLoaded[id]) {
        iconLoaded[id] = true;
        //Load the custom image icon into the map resources.
        map.imageSprite.add(id, '../Common/images/icons/showers.png').then();
    }
});

A complete sample is available here: https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/Symbol%20Layer/Load%20missing%20image%20into%20sprite.html


问:
Snowflake 403 error using Google as Identity Provider IdP
I'm trying to configure google IdP on my Snowflake following this tutorial from Snowflake community:
https://community.snowflake.com/s/article/configuring-g-suite-as-an-identity-provider?t=1630354048853

After the whole configuration is complete when I click on the SSO button on the login page
SSO Screen

I receive the following error:
Error Message

I have already double-checked the SAML configuration on both platforms
SAML Configurations

And APP configuration on Google seems correct
Google Snowflake App configurations
Google Snowflake App configurations

But the 403 error still persists.
How can I identify exactly where is the problem (Snowflake or Google) and how to fix it?
Is there any log I should be checking or any configuration missing?
Thanks!

答:
We ran into this error as well, but fortunately the solution was rather simple in our case:

Either use incognito mode

Or log out & back in to the Google account

Afterwards, it works flawlessly!


问:
React.js/React-Native how to skip Map() iteration if condition is falsy?
I have this simple component in React-Native, My goal is to skip the iteration if the given argument gradeIsMandatory is false, it should only iterate over warranty and price,
How can I achieve this result without affecting performance? I will take any advice thanks

import React, { useCallback } from 'react';
import { View, Text, SafeAreaView, SectionList, StyleSheet, Image, TouchableOpacity, Alert} from 'react-native';

export const ModalHeader: React.FC<{}> = () => {
    const gradeIsMandatory = false

    //code I tried to use
    useEffect(()=>{
        if(!gradeIsMandatory){
            let appendGrade =  { key: 'grade', title: 'Grade' }
            modalTabs.push(appendGrade)
        }
    },[])
    return (
        <View>
            <View>
                <View>
                    {modalTabs.map((tab, i) => (
                        <TouchableOpacity>
                          <Text>{tab.title}</Text>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>
        </View>
    );
}

const modalTabs = [
    { key: 'warranty', title: 'Your Waranty' },
    { key: 'price', title: 'Your price' }
]```

答:
this useEffect will run once just after the first render of the component, manipulating modalTabs there will do nothing becuase modalTabs is not a State of this component. the correct way is:

```<code>import { useState, useEffect } from "react";

const modalTabsInitialValue = [
  { key: "warranty", title: "Your Waranty" },
  { key: "price", title: "Your price" }
];

export default (props) => {
  const [modalTabs, setModalTabs] = useState(modalTabsInitialValue);

  useEffect(() => {
    if (props.gradeIsMandatory) {
      setModalTabs((prevModalTabs) => {
        const appendGrade = { key: "grade", title: "Grade" };
        return [...prevModalTabs, appendGrade];
      });
    }
  }, [props.gradeIsMandatory, setModalTabs]);

  return {
    ...
  }
};
</code>```

send the gradeIsMandatory as a property to this component

define modalTabs as state

use a useEffect hook with props.gradeIsMandatory as a dependency

inside the useEffect based on the value of gradeIsMandatory create a new array and change the modalTabs state forcing the component to reRender

Update: this is not the best solution for this problem, the correct answer as windowsill said is a simple const: answer

Body:
this useEffect will run once just after the first render of the component, manipulating modalTabs there will do nothing becuase modalTabs is not a State of this component. the correct way is:

import { useState, useEffect } from "react";

const modalTabsInitialValue = [
  { key: "warranty", title: "Your Waranty" },
  { key: "price", title: "Your price" }
];

export default (props) => {
  const [modalTabs, setModalTabs] = useState(modalTabsInitialValue);

  useEffect(() => {
    if (props.gradeIsMandatory) {
      setModalTabs((prevModalTabs) => {
        const appendGrade = { key: "grade", title: "Grade" };
        return [...prevModalTabs, appendGrade];
      });
    }
  }, [props.gradeIsMandatory, setModalTabs]);

  return {
    ...
  }
};

send the gradeIsMandatory as a property to this component

define modalTabs as state

use a useEffect hook with props.gradeIsMandatory as a dependency

inside the useEffect based on the value of gradeIsMandatory create a new array and change the modalTabs state forcing the component to reRender

Update: this is not the best solution for this problem, the correct answer as windowsill said is a simple const: answer


问:
Filter rows from group by clause postgresql
I have below table, Now I want group by on col_1, and want to select data of that group which has  col_2='ValueNet' and col_3='no' and also want to exclude row which satisfy before said condition. (i.e col_2='ValueNet' and col_3='no')

```<code>col_1  | col_2     |   col_3 <br>
1     | Community1 |  ACSNET
1     | Community2 |  ACSNET
1     | ValueNet   |  yes
2     | Community3 |  ACSNET
2     | Community4 |  ACSNET
2     | ValueNet   |  no
</code>```

my result table should be:

```<code>col_1    | col_2    |   col_3 <br>
2     | Community3 |  ACSNET
2     | Community4 |  ACSNET
</code>```

答:
One option is to make a query that finds from the table all the results according to the condition you mention: "col_2='ValueNet' and col_3='no'", and then to make an except clause for what you want to exclude:</p>
```<code>select * from [Table_1] where col_1 in
(select col_1 from [Table_1]
where col_2 ='ValueNet' and col_3='no')
except
(select * from [Table_1]
 where col_2 ='ValueNet' and col_3='no')
</code>```

Body:
I have below table, Now I want group by on col_1, and want to select data of that group which has  col_2='ValueNet' and col_3='no' and also want to exclude row which satisfy before said condition. (i.e col_2='ValueNet' and col_3='no')

col_1  | col_2     |   col_3

1     | Community1 |  ACSNET
1     | Community2 |  ACSNET
1     | ValueNet   |  yes
2     | Community3 |  ACSNET
2     | Community4 |  ACSNET
2     | ValueNet   |  no

my result table should be:

col_1    | col_2    |   col_3

2     | Community3 |  ACSNET
2     | Community4 |  ACSNET

Body:
One option is to make a query that finds from the table all the results according to the condition you mention: "col_2='ValueNet' and col_3='no'", and then to make an except clause for what you want to exclude:

select * from [Table_1] where col_1 in
(select col_1 from [Table_1]
where col_2 ='ValueNet' and col_3='no')
except
(select * from [Table_1]
 where col_2 ='ValueNet' and col_3='no')


问:
Access Default Value with Today's Date specified time
Real quick question.
I'm trying to set a default value in an Access table that gives me today's date and 8AM as the time.

I attempted to use =Date() & "8:00:00 AM" but I am getting a type mismatch error. I changed the format of the column to General Date to be able to have date and time but still no go.

Any help would be greatly appreciated.

答:
You were nearly there. A date isn't a string, so you add time with + and delimit with #:

```<code>=Date() + #8:00:00 AM#
</code>```

Of course, building with parts is fine too but a little too overcomplicated imo

Body:
You were nearly there. A date isn't a string, so you add time with + and delimit with #:

=Date() + #8:00:00 AM#

Of course, building with parts is fine too but a little too overcomplicated imo


问:
Question on jsLint error: "Don't make functions within a loop"
I'm reading DOM Scripting by Jeremy Keith and testing the code in jsLint

In the code sample here it i'm getting an error that says ""Don't make functions within a loop".

When I try to fix it, I seem to be losing the scope of this

I need to see an example of how to fix this error.

Here is the jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/

Thanks In Advance

sleeper

答:
maybe something like this:

```<code>var initMouseover = function() {
    return function () {
        this.style.backgroundColor = "crimson";
        this.style.color = "#ffffff";
    };
};
</code>```

and then in for loop you have:

```<code>current_row.onmouseover = initMouseover();
</code>```

I test it on link you post and it seems to work and also doesn't show this error anymore.

Body:
maybe something like this:

var initMouseover = function() {
    return function () {
        this.style.backgroundColor = "crimson";
        this.style.color = "#ffffff";
    };
};

and then in for loop you have:

current_row.onmouseover = initMouseover();

I test it on link you post and it seems to work and also doesn't show this error anymore.


问:
Passing multiple parameters to django url template
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes :

A snippet from the template from where the parameters will be passed onto :

```<code><a href="{% url 'coordinator_assign_project_recommendations' group_id=row.group client_id=row.client  project_id=row.project_id %}" class="btn btn-primary">Assign</a>
</code>```

The view function :

```<code>def assign_recommended_project(request, group_id, client_id, project_id):
    group = StudentGroup.objects.get(id=group_id)
    group.client = client_id
    group.project = project_id
    group.save()
    project = Project.objects.get(id=project_id)
    project.is_assigned = True
    project.save()
    return redirect("coordinator_view_groups")
</code>```

The  url of the view function :

```<code> path(
        "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id",
        assign_recommended_project,
        name="coordinator_assign_project_recommendations",
    ),
</code>```

This is the error that is shown :

Can someone please help me solve this. Thanks.

答:
```<code>path(
        "coordinator/assign_recommended_project/<str:group_id>/<str:client_id>/<str:project_id>",
        assign_recommended_project,
        name="coordinator_assign_project_recommendations",
    )
</code>```

Body:
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes :

A snippet from the template from where the parameters will be passed onto :

Assign

The view function :

def assign_recommended_project(request, group_id, client_id, project_id):
    group = StudentGroup.objects.get(id=group_id)
    group.client = client_id
    group.project = project_id
    group.save()
    project = Project.objects.get(id=project_id)
    project.is_assigned = True
    project.save()
    return redirect("coordinator_view_groups")

The  url of the view function :

 path(
        "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id",
        assign_recommended_project,
        name="coordinator_assign_project_recommendations",
    ),

This is the error that is shown :

Can someone please help me solve this. Thanks.


问:
when first if statement true continue with next if statement
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

```<code>numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"
</code>```

答:
```<code>numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():
    solu=""
    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'

    if numberB < 20 or numberB > 30:
        solu = solu+' numberB is okay'

    if numberC < 20 or numberC > 30:
        solu = solu+' numberC is okay'

    if numberD < 20 or numberD > 30:
        solu = solu+' numberD is okay'

    else:
        return "NO number is okay"

    return solu

print(num_okay())

</code>```

It's not that it is not entering other if statements you return  it in 1st if so it doesn't go to the rest here I have simply concated the string so it give 1 string with all the data from if statements hope this does what you were looking for

Body:
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"

Body:
numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():
    solu=""
    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'

    if numberB < 20 or numberB > 30:
        solu = solu+' numberB is okay'

    if numberC < 20 or numberC > 30:
        solu = solu+' numberC is okay'

    if numberD < 20 or numberD > 30:
        solu = solu+' numberD is okay'

    else:
        return "NO number is okay"

    return solu

print(num_okay())

It's not that it is not entering other if statements you return  it in 1st if so it doesn't go to the rest here I have simply concated the string so it give 1 string with all the data from if statements hope this does what you were looking for


问:
TypeError: send_mail() missing 3 required positional arguments: 'message', 'from_email', and 'recipient_list'
so I'm wanting to make this form where the client fills their name, email and a message. Then that message and their name is sent to my mail address and another mail is sent from my address to the clients one telling that their mail was sent successfully.
I already did this on another project and literally just copied changing the name of the functions n stuff but it doesn't work.

views.py

```<code>def send_email(email):
    context = {'email': email}
    template = get_template('emails/message-confirmation.html')
    content = template.render(context)
    email = EmailMultiAlternatives(
        'Test email',
        'AmiSalta message confirmation',
        settings.EMAIL_HOST_USER,
        [email]
    )
    email.attach_alternative(content, 'text/html')
    email.send()

def function(request):
    form = ContactForm_es()
    if request.method == 'POST':
        email = request.POST.get('email')
        send_mail(email)
        form = ContactForm_es(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            full_name = form.cleaned_data['full_name']
            body = form.cleaned_data['body']
            send_mail(full_name,body,email, ['******@gmail.com'])

    return render(request, 'es/home.html', {
            'form': form,
    })
</code>```

I'm going crazy bc is the last thing I need to do and I already did once but I just can't make it work. Please if someone knows what's wrong let me know, thanks in advance.

答: Check if you use your send_email in urls.py instead of send_mail. The name of your function is very similar to the django's send_mail() function. You can easily confuse yourself.

Body:
so I'm wanting to make this form where the client fills their name, email and a message. Then that message and their name is sent to my mail address and another mail is sent from my address to the clients one telling that their mail was sent successfully.
I already did this on another project and literally just copied changing the name of the functions n stuff but it doesn't work.

views.py

def send_email(email):
    context = {'email': email}
    template = get_template('emails/message-confirmation.html')
    content = template.render(context)
    email = EmailMultiAlternatives(
        'Test email',
        'AmiSalta message confirmation',
        settings.EMAIL_HOST_USER,
        [email]
    )
    email.attach_alternative(content, 'text/html')
    email.send()

def function(request):
    form = ContactForm_es()
    if request.method == 'POST':
        email = request.POST.get('email')
        send_mail(email)
        form = ContactForm_es(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            full_name = form.cleaned_data['full_name']
            body = form.cleaned_data['body']
            send_mail(full_name,body,email, ['******@gmail.com'])

    return render(request, 'es/home.html', {
            'form': form,
    })

I'm going crazy bc is the last thing I need to do and I already did once but I just can't make it work. Please if someone knows what's wrong let me know, thanks in advance.


问:
Remove all occurrences of a value from a list?
In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is what I have in mind:

```<code>>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
</code>```

答:
A lot of answers are really good. Here is a simple approach if you are a beginner in python in case you want to use the remove() method for sure.

```<code>rawlist = [8, 1, 8, 5, 8, 2, 8, 9, 8, 4]

ele_remove = 8

for el in rawlist:
    if el == ele_remove:
        rawlist.remove(ele_remove)
</code>```

It may be slower for too large lists.

Body:
In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is what I have in mind:

>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]

Body:
A lot of answers are really good. Here is a simple approach if you are a beginner in python in case you want to use the remove() method for sure.

rawlist = [8, 1, 8, 5, 8, 2, 8, 9, 8, 4]

ele_remove = 8

for el in rawlist:
    if el == ele_remove:
        rawlist.remove(ele_remove)

It may be slower for too large lists.


问:
NoCredentialProviders error when running "docker compose up" with AWS ECS integration
I'm getting the following error when I try to run docker compose up to deploy my infrastructure to AWS using Docker's ECS integration. Note that I'm running this on Pop!_OS 21.10, which is based on Ubuntu.

NoCredentialProviders: no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors

Things I've tried, based on an exhaustive search of SO and other sites:

Verified the proper format of my ~/.aws/config and ~/.aws/credentials files are formatted correctly, are in the proper place, and have the correct permissions

Verified that the aws cli works fine

Verify that AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION are all set correctly

Tried copying the config and credentials to /root/.aws

Tried setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION in the root user's environment

Created /etc/systemd/system/docker.service.d/aws-credentials.conf and populated it with:

```<code>[Service]
Environment="AWS_ACCESS_KEY_ID=********************"
Environment="AWS_SECRET_ACCESS_KEY=****************************************"
</code>```

Ran docker -l debug compose up (Only extra information it provides is DEBUG deploying on AWS with region="us-east-1"

I'm running out of options. If anyone has any other ideas to try, I'd love to hear it. Thanks!

Update: I've also now tried the following, with no luck:

Tried setting Environment="AWS_SHARED_CREDENTIALS_FILE=/home/kespan/.aws/credentials

Tried setting Environment="AWS_SHARED_CREDENTIALS_FILE=/home/kespan/.aws/credentials in /etc/systemd/system/docker.service.d/override.conf

After remembering my IAM account has MFA enabled, generated a token and added Environment="AWS_SESSION_TOKEN=..." to override.conf

Also to note - each time after I've added/modified files under /etc/systemd/system/docker.service.d/ I've run:

```<code>sudo systemctl daemon-reload
sudo systemctl restart docker
</code>```

Edit:

Here's one of the Dockerfiles (both the scraper and scheduler use an identical Dockerfile):

```<code>FROM denoland/deno:alpine
WORKDIR /app
USER deno
COPY deps.ts .
RUN deno cache --unstable --no-check deps.ts
COPY . .
RUN deno cache --unstable --no-check mod.ts
RUN mkdir -p /var/tmp/log
CMD ["run", "--unstable", "--allow-all", "--no-check", "mod.ts"]
</code>```

Here's my docker-compose (some bits redacted):

```<code>version: '3'
services:
  grafana:
    container_name: grafana
    image: grafana/grafana
    ports:
      - "3000:3000"
    volumes:
      - grafana:/var/lib/grafana
    deploy:
      replicas: 1
  scheduler:
    image: scheduler
    x-aws-pull-credentials: "arn..."
    container_name: scheduler
    environment:
      DB_CONNECTION_STRING: "postgres://..."
      SQS_URL: "..."
      SQS_REGION: "us-east-1"
      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
    deploy:
      replicas: 1
  scraper:
    image: scraper
    x-aws-pull-credentials: "arn..."
    container_name: scraper
    environment:
      DB_CONNECTION_STRING: "postgres://..."
      SQS_URL: "..."
      SQS_REGION: "us-east-1"
      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
    deploy:
      replicas: 1
volumes:
  grafana:
</code>```

答:
Have you attempted to use the Amazon ECS Local Container Endpoints tool that AWS Labs provides? It allows you to create an override file for you docker-compose configurations, and it will simulate the ECS endpoints and IAM roles you would be using in AWS.

This is done using the local AWS credentials you have on your workstation. More information is available on the AWS Blog.

Body:
I'm getting the following error when I try to run docker compose up to deploy my infrastructure to AWS using Docker's ECS integration. Note that I'm running this on Pop!_OS 21.10, which is based on Ubuntu.

NoCredentialProviders: no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors

Things I've tried, based on an exhaustive search of SO and other sites:

Verified the proper format of my ~/.aws/config and ~/.aws/credentials files are formatted correctly, are in the proper place, and have the correct permissions

Verified that the aws cli works fine

Verify that AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION are all set correctly

Tried copying the config and credentials to /root/.aws

Tried setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION in the root user's environment

Created /etc/systemd/system/docker.service.d/aws-credentials.conf and populated it with:

[Service]
Environment="AWS_ACCESS_KEY_ID=********************"
Environment="AWS_SECRET_ACCESS_KEY=****************************************"

Ran docker -l debug compose up (Only extra information it provides is DEBUG deploying on AWS with region="us-east-1"

I'm running out of options. If anyone has any other ideas to try, I'd love to hear it. Thanks!

Update: I've also now tried the following, with no luck:

Tried setting Environment="AWS_SHARED_CREDENTIALS_FILE=/home/kespan/.aws/credentials

Tried setting Environment="AWS_SHARED_CREDENTIALS_FILE=/home/kespan/.aws/credentials in /etc/systemd/system/docker.service.d/override.conf

After remembering my IAM account has MFA enabled, generated a token and added Environment="AWS_SESSION_TOKEN=..." to override.conf

Also to note - each time after I've added/modified files under /etc/systemd/system/docker.service.d/ I've run:

sudo systemctl daemon-reload
sudo systemctl restart docker

Edit:

Here's one of the Dockerfiles (both the scraper and scheduler use an identical Dockerfile):

FROM denoland/deno:alpine
WORKDIR /app
USER deno
COPY deps.ts .
RUN deno cache --unstable --no-check deps.ts
COPY . .
RUN deno cache --unstable --no-check mod.ts
RUN mkdir -p /var/tmp/log
CMD ["run", "--unstable", "--allow-all", "--no-check", "mod.ts"]

Here's my docker-compose (some bits redacted):

version: '3'
services:
  grafana:
    container_name: grafana
    image: grafana/grafana
    ports:
      - "3000:3000"
    volumes:
      - grafana:/var/lib/grafana
    deploy:
      replicas: 1
  scheduler:
    image: scheduler
    x-aws-pull-credentials: "arn..."
    container_name: scheduler
    environment:
      DB_CONNECTION_STRING: "postgres://..."
      SQS_URL: "..."
      SQS_REGION: "us-east-1"
      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
    deploy:
      replicas: 1
  scraper:
    image: scraper
    x-aws-pull-credentials: "arn..."
    container_name: scraper
    environment:
      DB_CONNECTION_STRING: "postgres://..."
      SQS_URL: "..."
      SQS_REGION: "us-east-1"
      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
    deploy:
      replicas: 1
volumes:
  grafana:


问:
Convert an ftrace trace.dat file to CTF format to use with TraceCompass
I can generate ftrace data either manually (and then trace-cmd extract it) or via the convenient trace-cmd(1) front-end utility.

With trace-cmd, the output file is trace.dat by default; I know I can visually view it via kernelshark but would much prefer to use the Trace Compass GUI to do so. AFAIK, TraceCompass uses the .ctf file format. My question therefore:

How can I convert the ftrace or trace.dat file from trace-cmd to .ctf format?

(I know there's Q&A on converting perf(1) to CTF).

答:
Trace Compass developer here.

I want to announce Trace Compass natively supports version 6 of the ftrace trace.dat format. This is the trace generated by trace-cmd. Here is a video announcing and demoing the feature.

Also, feel free to ask trace compass questions on our mailing list or on the eclipse bugzilla (within trace compass, click on the help menu, report bug...) as we do not check stack overflow very often.


问:
How to get EXIF data of post images in WordPress
I understand that the EXIF data extracted from uploaded images are stored in the WordPress database, but i am not finding the proper way to find them or get them in a post for instance. I was looking around on web but all solutions found didn't work.

Do you know an efficient way to get the EXIF data of a picture from post? I don't mind if is a php or jQuery solution as long it does the job.

Thanks for your time.

LATER EDIT: actually i found the reason for my problem. I managed to call the wp_get_attachment_metadata but except the width and height of image, i receive zero for camera, aperture, ISO, focal lenght, shutter speed etc. The call is something like $imgmeta['image_meta']['camera']

is there something i am missing?

LATER LATER EDIT: Found the issue. server extension php_exif wasn't enabled. thanks for your time

答:
you can use EXIF Read Data from php.net. Folow first example and you should be able to extract whatever you want ...

EDIT: or you can use jQuery EXIF
EDIT 2: for jQuery you must use same domain as the Same Origin Policy applies to EXIF reader as it uses HTTP Requests


问:
Is the use of while loops ok here? Or it's excesive
I want to know if it is ok to use as much while loops as I want or it is just not conventional. Also searhing for another solution to check only if the user enters the two symbols of the tic tac toe (X, O), but only one user can have each of them.

In other words, when the user is prompted for choosing the symbol he wants for playing, if he introduces an invalid one, keep asking till it's one of the both above. Then, for the second player he can only choose, for example, the 'O' if the first player have chosen the 'X', and also ensuring it's only one of the two symbols and not an invalid one.

```<code>    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String playerName, playerMove;

        System.out.print("Introduce el nombre del primer jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        playerMove = playerMove.toUpperCase();

        Player player1 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player1.name + "!");

        System.out.println();
        System.out.print("Introduce el nombre del segundo jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        while (playerMove.equalsIgnoreCase(player1.moveType)) {
            System.out.print("Introduce un símbolo distinto al del otro jugador: ");
            playerMove = sc.next();

            while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
                System.out.print("Introduce un símbolo válido: ");
                playerMove = sc.next();
            }
        }

        playerMove = playerMove.toUpperCase();

        Player player2 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player2.name + "!");
        System.out.println();

        System.out.println("El símbolo de " + player1.name + " es " + player1.moveType + ".");
        System.out.println("El símbolo de " + player2.name + " es " + player2.moveType + ".");

        System.out.println();

        Board board = new Board();

        System.out.println("El tablero es: ");
        System.out.println();

        board.displayBoard();
        System.out.println();
    }
}
</code>```

答: There are absolutely alternatives / more efficient ways to solve this program but to answer your question, nested loops are not at all uncommon or unconventional in Java and this would be acceptable. The negative effect of using nested loops would be the algorithm runtime which you likely don't need to worry about for this problem!</p>

Body:
I want to know if it is ok to use as much while loops as I want or it is just not conventional. Also searhing for another solution to check only if the user enters the two symbols of the tic tac toe (X, O), but only one user can have each of them.

In other words, when the user is prompted for choosing the symbol he wants for playing, if he introduces an invalid one, keep asking till it's one of the both above. Then, for the second player he can only choose, for example, the 'O' if the first player have chosen the 'X', and also ensuring it's only one of the two symbols and not an invalid one.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String playerName, playerMove;

        System.out.print("Introduce el nombre del primer jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        playerMove = playerMove.toUpperCase();

        Player player1 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player1.name + "!");

        System.out.println();
        System.out.print("Introduce el nombre del segundo jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        while (playerMove.equalsIgnoreCase(player1.moveType)) {
            System.out.print("Introduce un símbolo distinto al del otro jugador: ");
            playerMove = sc.next();

            while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
                System.out.print("Introduce un símbolo válido: ");
                playerMove = sc.next();
            }
        }

        playerMove = playerMove.toUpperCase();

        Player player2 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player2.name + "!");
        System.out.println();

        System.out.println("El símbolo de " + player1.name + " es " + player1.moveType + ".");
        System.out.println("El símbolo de " + player2.name + " es " + player2.moveType + ".");

        System.out.println();

        Board board = new Board();

        System.out.println("El tablero es: ");
        System.out.println();

        board.displayBoard();
        System.out.println();
    }
}


问:
codeigniter session expires frequently
I'm using codeigniter for my app

what my problem is session is expiring even though user is active on the site.

These are the session settings.. i'm using DB session

```<code>$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']      = 'edu_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;
</code>```

any solution for this.

help me i have to fix it

here is the codeigniter  forum link

答:
Remove bellow line from config.php

```<code>$config['cookie_path']      = '/';
</code>```

Title: codeigniter session expires frequently

Body:
I'm using codeigniter for my app

what my problem is session is expiring even though user is active on the site.

These are the session settings.. i'm using DB session

$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']      = 'edu_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;

any solution for this.

help me i have to fix it

here is the codeigniter  forum link

Body:
Remove bellow line from config.php

$config['cookie_path']      = '/';


问:
Django, Vue and WebSocket - getting client side to work
There was a similar question on SO about this some time ago, though I tried the answers with no luck.

I am implementing a SPA using Django backend and Vue front end with Vue cli. Django is using channels to send JSON via a WebSocket to the frontend, the frontend receives this data and is supposed to update a table.

The Django part is working. A connection to the WebSocket is confirmed and data is received in Vue, though I have two problems that I have not been able to find a way to solve:

The data, while in a variable, is not being shown on the table and

The front end only receives the data once - I don't know how to apply a listener to the WebSocket, or in which part of my Vue app, so that new payloads (I hope I am saying that correctly) are received and updated accordingly.

Below I have provided the Django consumers.py file, the Signals.vue view file, and the console.log output showing that the variable does contain the JSON object despite the table remaining blank.

Does anyone have an idea of where I am going wrong and how I can solve problems 1 and 2?
Thanks

Django consumers.py

```<code>import json
from channels.generic.websocket import WebsocketConsumer

class WSConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

        self.send(json.dumps({
            'id': 1,
            'date': "date",
            'marketOpen': "marketOpen",
            'symbol': "symbol",
            'trade': "trade",
            'bias': "bias",
            'status': "status"
            }))
</code>```

Signals.vue

```<code><template>
    <div class="container">
        <div class="columns is-multiline">
            <div class="column is-12">
                <h1 class="title"> Signals</h1>
            </div>

            <div class="column is-12">
                <table class="table is-fullwidth">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Market Open</th>
                            <th>Symbol</th>
                            <th>Trade</th>
                            <th>Bias</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for= "signal in signals" v-bind:key="signal.id">
                            <td>{{ signal.date }} </td>
                            <td>{{ signal.marketOpen }} </td>
                            <td>{{ signal.symbol }} </td>
                            <td>{{ signal.trade }} </td>
                            <td>{{ signal.bias }} </td>
                            <td>{{ signal.status }} </td>
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>
    </div>
</template>

<script>
export default {
    name: 'Signals',
    data() {
        return {
            signals: [],
            connection: null
        }
    },
    created() {
        this.getSignals()
    },
    methods: {
        getSignals() {
            console.log("Starting connection to websocket")
            this.connection = new WebSocket('ws://localhost:8000/ws/signals/')
            this.connection.onmessage = (event) => {
                this.signals = event.data
                console.log("Successfully retrieved message from websocket")
                console.log(this.signals)
            }
        }
    }
}
</script>
</code>```

Console

```<code>[HMR] Waiting for update signal from WDS... log.js?1afd

Starting connection to websocket Signals.vue?1d80

Unchecked runtime.lastError: The message port closed before a response was received. signals:1

Successfully retrieved message from websocket Signals.vue?1d80

{"id": 1, "date": "date", "marketOpen": "marketOpen", "symbol": "symbol", "trade": "trade", "bias": "bias", "status": "status"} Signals.vue?1d80
</code>```

答:
To send messages asynchronously you should use async,
and write an async function to send data on the requirement, call the send function in view.py or a celery worker, if you want to send periodically celery beat is the way to go else use celery workers for on-demand data.

It's my first time answering in the stack if there is any mistake in my understanding of question or in my the answer please pardon me. and I am not sure about what is your first question.
(I have just started learning Vue js but I have worked for years on Django so I thought I could answer this as thank you to all people who helped me with responses in Stackoverflow.com)

below is a simple example of socket connection I have implemented:

```<code>class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
    # this only exicutes only once when a user gets connected to the socket
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = 'notification_%s' % self.room_name

    # Join room group
    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )

    await self.accept()

async def disconnect(self, close_code):
    # Leave room group
    await self.channel_layer.group_discard(
        self.room_group_name,
        self.channel_name
    )

Receive message from WebSocket
async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']
    print(message)
    print("message")

    # Send message to room group
    await self.channel_layer.group_send(
        self.room_group_name,
        {
            'type': 'snmpop_message',
            'message': message
        }
    )

async def send_notification(self, event):
    message = json.loads(event['message'])
    print(message)
    # Send message to WebSocket
    await self.send(text_data=json.dumps(message))
</code>```

#This is how I will send the data on requirement: from any other place:

```<code>channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
    "notification_broadcast",
    {
        'type': 'send_Notification',
        'message': json.dumps(outputdict)
    }
 )
</code>```

if any of you have queries you can reach out to me: amithkhul@gmail.com
Thank you
Amith K

Body:
There was a similar question on SO about this some time ago, though I tried the answers with no luck.

I am implementing a SPA using Django backend and Vue front end with Vue cli. Django is using channels to send JSON via a WebSocket to the frontend, the frontend receives this data and is supposed to update a table.

The Django part is working. A connection to the WebSocket is confirmed and data is received in Vue, though I have two problems that I have not been able to find a way to solve:

The data, while in a variable, is not being shown on the table and

The front end only receives the data once - I don't know how to apply a listener to the WebSocket, or in which part of my Vue app, so that new payloads (I hope I am saying that correctly) are received and updated accordingly.

Below I have provided the Django consumers.py file, the Signals.vue view file, and the console.log output showing that the variable does contain the JSON object despite the table remaining blank.

Does anyone have an idea of where I am going wrong and how I can solve problems 1 and 2?
Thanks

Django consumers.py

import json
from channels.generic.websocket import WebsocketConsumer

class WSConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

        self.send(json.dumps({
            'id': 1,
            'date': "date",
            'marketOpen': "marketOpen",
            'symbol': "symbol",
            'trade': "trade",
            'bias': "bias",
            'status': "status"
            }))

Signals.vue

<template>

 Signals

                            Date
                            Market Open
                            Symbol
                            Trade
                            Bias
                            Status

                            {{ signal.date }}
                            {{ signal.marketOpen }}
                            {{ signal.symbol }}
                            {{ signal.trade }}
                            {{ signal.bias }}
                            {{ signal.status }}

</template>

Console

[HMR] Waiting for update signal from WDS... log.js?1afd

Starting connection to websocket Signals.vue?1d80

Unchecked runtime.lastError: The message port closed before a response was received. signals:1

Successfully retrieved message from websocket Signals.vue?1d80

{"id": 1, "date": "date", "marketOpen": "marketOpen", "symbol": "symbol", "trade": "trade", "bias": "bias", "status": "status"} Signals.vue?1d80

Body:
To send messages asynchronously you should use async,
and write an async function to send data on the requirement, call the send function in view.py or a celery worker, if you want to send periodically celery beat is the way to go else use celery workers for on-demand data.

It's my first time answering in the stack if there is any mistake in my understanding of question or in my the answer please pardon me. and I am not sure about what is your first question.
(I have just started learning Vue js but I have worked for years on Django so I thought I could answer this as thank you to all people who helped me with responses in Stackoverflow.com)

below is a simple example of socket connection I have implemented:

class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
    # this only exicutes only once when a user gets connected to the socket
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = 'notification_%s' % self.room_name

    # Join room group
    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )

    await self.accept()

async def disconnect(self, close_code):
    # Leave room group
    await self.channel_layer.group_discard(
        self.room_group_name,
        self.channel_name
    )

Receive message from WebSocket
async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']
    print(message)
    print("message")

    # Send message to room group
    await self.channel_layer.group_send(
        self.room_group_name,
        {
            'type': 'snmpop_message',
            'message': message
        }
    )

async def send_notification(self, event):
    message = json.loads(event['message'])
    print(message)
    # Send message to WebSocket
    await self.send(text_data=json.dumps(message))

#This is how I will send the data on requirement: from any other place:

channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
    "notification_broadcast",
    {
        'type': 'send_Notification',
        'message': json.dumps(outputdict)
    }
 )

if any of you have queries you can reach out to me: amithkhul@gmail.com
Thank you
Amith K


问:
Row Number calculation
I would like to be able to SQL code the Cycle column in the picture below. If the same ID is used within 2 minutes, it will be part of that same cycle. I've used RowNumber() a lot but not sure it's that straight forward. I could create a new Time column that assigns the same number if the time is within 2 minutes of each other, but perhaps there is a better way.

答:
I'm certain there are better ways of doing this, but this is the one I landed on. If you change your time as integer column to time as time, it will be easier for you in the long run.

```<code>create table #t (id int, event_time_text nvarchar(6), event_time time);

insert into #t (id,event_time_text) values
(123456789,'070007'),
(123456789,'070048'),
(123456789,'162455'),
(123456789,'162542'),
(123456789,'184131'),
(123456789,'184207');

update #t set event_time = TIMEFROMPARTS(LEFT(event_time_text,2),SUBSTRING(event_time_text,3,2),SUBSTRING(event_time_text,5,2),0,0);

WITH dat --calculate the difference in minutes of one row from the previous row
AS
(
SELECT *
    ,CASE
        WHEN DATEDIFF(minute,LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time),event_time) <= 2
        THEN LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time)
        ELSE event_time
     END AS diff_index
FROM #t
)
SELECT *
    ,DENSE_RANK() OVER (PARTITION BY id ORDER BY diff_index) AS group_within_id
FROM dat;
</code>```

dbfiddle.uk

Title: Row Number calculation

Body:
I'm certain there are better ways of doing this, but this is the one I landed on. If you change your time as integer column to time as time, it will be easier for you in the long run.

create table #t (id int, event_time_text nvarchar(6), event_time time);

insert into #t (id,event_time_text) values
(123456789,'070007'),
(123456789,'070048'),
(123456789,'162455'),
(123456789,'162542'),
(123456789,'184131'),
(123456789,'184207');

update #t set event_time = TIMEFROMPARTS(LEFT(event_time_text,2),SUBSTRING(event_time_text,3,2),SUBSTRING(event_time_text,5,2),0,0);

WITH dat --calculate the difference in minutes of one row from the previous row
AS
(
SELECT *
    ,CASE
        WHEN DATEDIFF(minute,LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time),event_time) <= 2
        THEN LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time)
        ELSE event_time
     END AS diff_index
FROM #t
)
SELECT *
    ,DENSE_RANK() OVER (PARTITION BY id ORDER BY diff_index) AS group_within_id
FROM dat;

dbfiddle.uk


问:
gracefully stop azure container instance
I have a .net core 5.0 application wrapped in a docker image, I can run the image as a container under Docker Desktop with Linux Container mode, when I am stopping the container
app is able to catch following events, which is what I want.

```<code>System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
   Console.WriteLine("Unloading");
};

AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
   Console.WriteLine("Exitting");
};
</code>```

However once I push the docker image to the azure registry and start as Azure container instance, neither stopping or restart via button in portal.azure trigger these events.
Same issue for azure cloud shell commands.

```<code>az container restart --name gracefullApp --resource-group gracefullAppGroup
az container stop --name gracefullApp --resource-group gracefullAppGroup
</code>```

Any idea how can this be achieved?

The dockerfile is generated by VS2019

```<code>FROM mcr.microsoft.com/dotnet/runtime:5.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["gracefullApp/gracefullApp.csproj", "gracefullApp/"]
RUN dotnet restore "gracefullApp/gracefullApp.csproj"
COPY . .
WORKDIR "/src/gracefullApp"
RUN dotnet build "gracefullApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "gracefullApp.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "gracefullApp.dll"]
</code>```

答:
Unfortunately this is happening because when you run "docker stop", docker sends a Sigterm to the containers pid 1.

What the sigterm signal does is alert the process to shutdown but the process might might finish up whatever it waa doing during the signaling and then terminate itself once complete. Think of it as a graceful shutdown.

Azure container instances send the SIGKILL signal which is more destructive in a sense as it doesnt care what the process was doing or will do after, it will just terminate. This is why you having this issue but works fine in docker, I do know its currently an issue on their github board as well since 2021

Body:
I have a .net core 5.0 application wrapped in a docker image, I can run the image as a container under Docker Desktop with Linux Container mode, when I am stopping the container
app is able to catch following events, which is what I want.

System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
   Console.WriteLine("Unloading");
};

AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
   Console.WriteLine("Exitting");
};

However once I push the docker image to the azure registry and start as Azure container instance, neither stopping or restart via button in portal.azure trigger these events.
Same issue for azure cloud shell commands.

az container restart --name gracefullApp --resource-group gracefullAppGroup
az container stop --name gracefullApp --resource-group gracefullAppGroup

Any idea how can this be achieved?

The dockerfile is generated by VS2019

FROM mcr.microsoft.com/dotnet/runtime:5.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["gracefullApp/gracefullApp.csproj", "gracefullApp/"]
RUN dotnet restore "gracefullApp/gracefullApp.csproj"
COPY . .
WORKDIR "/src/gracefullApp"
RUN dotnet build "gracefullApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "gracefullApp.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "gracefullApp.dll"]