问:
Strange problem with the length of the field gotten from database
I am using php 5.4 with this backwards compatibility script: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php

that shouldn't matter though, because I can get the hashing and verification process working in my registration function:

```<code>$hash = password_hash($pass, PASSWORD_DEFAULT);

echo $pass;
echo $hash;

if( password_verify($pass,$hash) )
    echo 'success';
else echo 'failure';

//success is always shown

//EXAMPLE INPUT
$pass = 'password';

//EXAMPLE OUTPUT
password$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYSsuccess
</code>```

but whenever I try to store the hash in a MySQL database and then retrieve it for the verify function, it always fails. Here is my login function:

```<code>function user_login( $mysqli, $email, $pass ){

        $err_msg = 'login: '.$mysqli->error.' | '.$email;

        if( $stmt = $mysqli->prepare('SELECT password FROM users WHERE email=?') ) :

            if( !$stmt->bind_param('s', $email) ) log_sql_error( $err_msg );
            if( !$stmt->execute() ) log_sql_error( $err_msg );
            if( !$stmt->bind_result( $hash ) ) log_sql_error( $err_msg );
            if( $stmt->fetch() === FALSE ) log_sql_error( $err_msg );
            if( !$stmt->close() ) log_sql_error( $err_msg );

            //I can see that these values are identical to the ones
            //echoed out in the registration function
            echo $pass;
            echo $hash;

            if( password_verify($pass,$hash) )
                echo 'success';
            else echo 'failure';

        else : log_sql_error( $err_msg );
        endif;
}
//failure is always shown

//EXAMPLE INPUT
$pass = 'password';

//EXAMPLE OUTPUT
password$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYSfailure
</code>```

My 'password' column has this datatype: VARCHAR(255) NOT NULL

No php errors show up so the only thing I can think of is that the hash value is not formatted in the same way when it comes out of the database as when it went in, but when I echo out the values, they appear to be identical.

How else can I debug this / what is wrong with my code?

Thanks

UPDATE:

This definitely has something to do with encoding:

```<code>$hardcode_hash = '$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS';

echo $hash;
echo '<br/>';
echo $hardcode_hash;
echo '<br/>';

if( $hash == $hardcode_hash )
    echo 'success';
else echo 'failure';

//OUTPUT
$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS
$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS
failure
</code>```

how do I reformat the SQL value to match the output of password_hash? Here's what I've tried:

```<code>(string)$hash
utf8_encode($hash)
</code>```

if I do:

```<code>$hash = settype($hash,"string");
</code>```

if($hash == $hardcode_hash) returns true, but password_verify($pass, $hash) still returns false

答: Just for future reference. I had the same issue with passwords failing for no reason. When I took a closer look at it I saw that the password field in the database was not big enough to store the full hash so some characters were cut off. After increasing the size of the database field it worked perfectly. </p>

Body:
I am using php 5.4 with this backwards compatibility script: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php

that shouldn't matter though, because I can get the hashing and verification process working in my registration function:

$hash = password_hash($pass, PASSWORD_DEFAULT);

echo $pass;
echo $hash;

if( password_verify($pass,$hash) )
    echo 'success';
else echo 'failure';

//success is always shown

//EXAMPLE INPUT
$pass = 'password';

//EXAMPLE OUTPUT
password$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYSsuccess

but whenever I try to store the hash in a MySQL database and then retrieve it for the verify function, it always fails. Here is my login function:

function user_login( $mysqli, $email, $pass ){

        $err_msg = 'login: '.$mysqli->error.' | '.$email;

        if( $stmt = $mysqli->prepare('SELECT password FROM users WHERE email=?') ) :

            if( !$stmt->bind_param('s', $email) ) log_sql_error( $err_msg );
            if( !$stmt->execute() ) log_sql_error( $err_msg );
            if( !$stmt->bind_result( $hash ) ) log_sql_error( $err_msg );
            if( $stmt->fetch() === FALSE ) log_sql_error( $err_msg );
            if( !$stmt->close() ) log_sql_error( $err_msg );

            //I can see that these values are identical to the ones
            //echoed out in the registration function
            echo $pass;
            echo $hash;

            if( password_verify($pass,$hash) )
                echo 'success';
            else echo 'failure';

        else : log_sql_error( $err_msg );
        endif;
}
//failure is always shown

//EXAMPLE INPUT
$pass = 'password';

//EXAMPLE OUTPUT
password$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYSfailure

My 'password' column has this datatype: VARCHAR(255) NOT NULL

No php errors show up so the only thing I can think of is that the hash value is not formatted in the same way when it comes out of the database as when it went in, but when I echo out the values, they appear to be identical.

How else can I debug this / what is wrong with my code?

Thanks

UPDATE:

This definitely has something to do with encoding:

$hardcode_hash = '$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS';

echo $hash;
echo '
';
echo $hardcode_hash;
echo '
';

if( $hash == $hardcode_hash )
    echo 'success';
else echo 'failure';

//OUTPUT
$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS
$2y$10$JK1jumvvSIm/gP3fWE3k9O98MzvHKDRYCjRPBniYg9riACyQw7WYS
failure

how do I reformat the SQL value to match the output of password_hash? Here's what I've tried:

(string)$hash
utf8_encode($hash)

if I do:

$hash = settype($hash,"string");

if($hash == $hardcode_hash) returns true, but password_verify($pass, $hash) still returns false


来源: stackexchange

问:
When should we use intern method of String on String literals
According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

So i tried this:

```<code>String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();

if ( s1 == s2 ){
    System.out.println("s1 and s2 are same");  // 1.
}

if ( s1 == s3 ){
    System.out.println("s1 and s3 are same" );  // 2.
}
</code>```

I was expecting that s1 and s3 are same will be printed as s3 is interned, and s1 and s2 are same will not be printed. But the result is: both lines are printed. So that means, by default String constants are interned. But if it is so, then why do we need the intern method? In other words when should we use this method?

答:
Learn Java String Intern - once for all

Strings in java are immutable objects by design. Therefore, two string objects even with same value will be different objects by default. However, if we wish to save memory, we could indicate to use same memory by a concept called string intern.
  The below rules would help you understand the concept in clear terms:

String class maintains an intern-pool which is initially empty. This pool must guarantee to contain string objects with only unique values.

All string literals having same value must be considered same memory-location object because they have otherwise no notion of distinction. Therefore, all such literals with same value will make a single entry in the intern-pool and will refer to same memory location.

Concatenation of two or more literals is also a literal. (Therefore rule #2 will be applicable for them)

Each string created as object (i.e. by any other method except as literal) will have different memory locations and will not make any entry in the intern-pool

Concatenation of literals with non-literals will make a non-literal. Thus, the resultant object will have a new memory location and will NOT make an entry in the intern-pool.

Invoking intern method on a string object, either creates a new object that enters the intern-pool or return an existing object from the pool that has same value. The invocation on any object which is not in the intern-pool, does NOT move the object to the pool. It rather creates another object that enters the pool.

Example:

```<code>String s1=new String ("abc");
String s2=new String ("abc");
If (s1==s2)  //would return false  by rule #4
If ("abc" == "a"+"bc" )  //would return true by rules #2 and #3
If ("abc" == s1 )  //would return false  by rules #1,2 and #4
If ("abc" == s1.intern() )  //would return true  by rules #1,2,4 and #6
If ( s1 == s2.intern() )      //wound return false by rules #1,4, and #6
</code>```

Note: The motivational cases for string intern are not discussed here. However, saving of memory will definitely be one of the primary objectives.

ContentLicense: CC BY-SA 3.0

Body:
According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

So i tried this:

String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();

if ( s1 == s2 ){
    System.out.println("s1 and s2 are same");  // 1.
}

if ( s1 == s3 ){
    System.out.println("s1 and s3 are same" );  // 2.
}

I was expecting that s1 and s3 are same will be printed as s3 is interned, and s1 and s2 are same will not be printed. But the result is: both lines are printed. So that means, by default String constants are interned. But if it is so, then why do we need the intern method? In other words when should we use this method?

Body:
Learn Java String Intern - once for all

Strings in java are immutable objects by design. Therefore, two string objects even with same value will be different objects by default. However, if we wish to save memory, we could indicate to use same memory by a concept called string intern.
  The below rules would help you understand the concept in clear terms:

String class maintains an intern-pool which is initially empty. This pool must guarantee to contain string objects with only unique values.

All string literals having same value must be considered same memory-location object because they have otherwise no notion of distinction. Therefore, all such literals with same value will make a single entry in the intern-pool and will refer to same memory location.

Concatenation of two or more literals is also a literal. (Therefore rule #2 will be applicable for them)

Each string created as object (i.e. by any other method except as literal) will have different memory locations and will not make any entry in the intern-pool

Concatenation of literals with non-literals will make a non-literal. Thus, the resultant object will have a new memory location and will NOT make an entry in the intern-pool.

Invoking intern method on a string object, either creates a new object that enters the intern-pool or return an existing object from the pool that has same value. The invocation on any object which is not in the intern-pool, does NOT move the object to the pool. It rather creates another object that enters the pool.

Example:

String s1=new String ("abc");
String s2=new String ("abc");
If (s1==s2)  //would return false  by rule #4
If ("abc" == "a"+"bc" )  //would return true by rules #2 and #3
If ("abc" == s1 )  //would return false  by rules #1,2 and #4
If ("abc" == s1.intern() )  //would return true  by rules #1,2,4 and #6
If ( s1 == s2.intern() )      //wound return false by rules #1,4, and #6

Note: The motivational cases for string intern are not discussed here. However, saving of memory will definitely be one of the primary objectives.

ContentLicense: CC BY-SA 4.0


问:
I have 2,000,000 points in 100 dimensionality space. How can I cluster them to K (e.g., 1000) clusters?
The problem comes as follows. I have M images and extract N features for each image, and the dimensionality of each feature is L. Thus, I have M*N features (2,000,000 for my case) and each feature has L dimensionality (100 for my case). I need to cluster these M*N features into K clusters. How can I do it? Thanks.</p>

答:
Do you want 1000 clusters of images, or of features, or of (image, feature) pairs ?

In any case, it sounds as though you'll have to reduce the data
and use simpler methods.

One possibility is two-pass K-cluster:

a) split the 2 million data points into 32 clusters,

b) split each of these into 32 more.

If this works, the resulting 32^2 = 1024 clusters might be good enough for your purpose.

Then, do you really need 100 coordinates ?
Could you guess the 20 most important ones,
or just try random subsets of 20 ?

There's a huge literature:  Google +image "dimension reduction" gives ~ 70000 hits.

ContentLicense: CC BY-SA 2.5


问:
How to deal with this AttributeError in scipy? It's very strange
This code is just from SciPy.org:

```<code>import numpy as np
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
</code>```

But when I run it, it shows: AttributeError: module 'scipy.sparse' has no attribute 'save_npz'

And if I do this:

```<code>import numpy as np
import scipy.sparse.save_npz
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
</code>```

It shows: ModuleNotFoundError: No module named 'scipy.sparse.save_npz'

And if I do this:

```<code>import numpy as np
from scipy.sparse import csr_matrix, save_npz

sparse_matrix = csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
</code>```

It shows: ImportError: cannot import name 'save_npz'

So, how to fix it?

答:
Inspect scipy.__version__ and you'll see that the version is < 0.19, the first release in which the save_npz method is implemented.

You need to run pip install --upgrade scipy at a shell prompt.

If you're using iPython or Jupyter, you will need to restart the kernel before the change will take effect.

Body:
This code is just from SciPy.org:

import numpy as np
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

But when I run it, it shows: AttributeError: module 'scipy.sparse' has no attribute 'save_npz'

And if I do this:

import numpy as np
import scipy.sparse.save_npz
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

It shows: ModuleNotFoundError: No module named 'scipy.sparse.save_npz'

And if I do this:

import numpy as np
from scipy.sparse import csr_matrix, save_npz

sparse_matrix = csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

It shows: ImportError: cannot import name 'save_npz'

So, how to fix it?


问:
RAISERROR never caught using EF 6 with proper severity
I feel like I'm about to scrap this whole project and start over with the amount of frustration this is bringing me. So I definitely appreciate any insight anyone has...

I have SQL Server Stored Procedures that need to do certain logical checks in order to proceed. If these checks fail, RAISERROR() is called and the SP returns. Here's an example of one of these checks:

```<code>IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END
</code>```

This SP is imported into a C# project using EF 6 model-first. The SP is imported into the Function Imports section of the model. An example of the above SP imported  (simplified parameters):

```<code>public virtual ObjectResult<Nullable<int>> CreatePendingContact(string lastName)
    {
        var lastNameParameter = lastName != null ?
            new ObjectParameter("LastName", lastName) :
            new ObjectParameter("LastName", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("CreatePendingContact", lastNameParameter);
    }
</code>```

And this function can be called in C# code with a try/catch block is called like so (where _model is the EF-generated dbContext subclass):

```<code>try
    {
        var result = _model.CreatePendingContact(
            LastName
            );
    }
catch (SqlException ex)
    {
        Debug.WriteLine(ex.Message);
        throw;
    }
</code>```

Right now I should be able to pass LastName = "" (or anything else < 2 chars) and get back an SqlException with the above RAISERROR text - however nothing I have been able to do has gotten this SqlException to trigger when it should!

So far here are the things I've tried:

Using THROW keyword instead of simply RETURN (nothing caught)

Running SQL Server Profiler, grabbing the query the C# client sends, and manually executing it in SSMS (results in the error being shown correctly in output)

Modifying the EF generated to add a try/catch block at the ExecuteFunction<>() line (nothing caught)

Right now most threads online either fix the issue with a severity level set to 16, so I'm at a loss to what else I should be setting or looking for...

答:
Here is a solution I've implemented, but it doesn't feel clean. Also, I don't get why I would have to make these edits to the generated code in order to catch the SqlException - if anyone has improvements it would definitely be welcome:

Part 1: Ensure your imported function under "Function Imports" of your model is set to return a collection of 'none' as the option. (I haven't gotten to SPs that return objects yet)

Part 2: Modify your EF-generated function code from the return line above into:

```<code>try
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("CreatePendingContact", lastNameParameter);
}
catch (Exception ex)
{
    if (ex.InnerException is SqlException) { throw ex.InnerException; }
    else { throw; }
}
</code>```

This change will only forward SqlExceptions, while still throwing locally for all other exceptions. This is the super-simple case, but it seems to work so far...

Body:
I feel like I'm about to scrap this whole project and start over with the amount of frustration this is bringing me. So I definitely appreciate any insight anyone has...

I have SQL Server Stored Procedures that need to do certain logical checks in order to proceed. If these checks fail, RAISERROR() is called and the SP returns. Here's an example of one of these checks:

IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END

This SP is imported into a C# project using EF 6 model-first. The SP is imported into the Function Imports section of the model. An example of the above SP imported  (simplified parameters):

public virtual ObjectResult<Nullable<int>> CreatePendingContact(string lastName)
    {
        var lastNameParameter = lastName != null ?
            new ObjectParameter("LastName", lastName) :
            new ObjectParameter("LastName", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("CreatePendingContact", lastNameParameter);
    }

And this function can be called in C# code with a try/catch block is called like so (where _model is the EF-generated dbContext subclass):

try
    {
        var result = _model.CreatePendingContact(
            LastName
            );
    }
catch (SqlException ex)
    {
        Debug.WriteLine(ex.Message);
        throw;
    }

Right now I should be able to pass LastName = "" (or anything else < 2 chars) and get back an SqlException with the above RAISERROR text - however nothing I have been able to do has gotten this SqlException to trigger when it should!

So far here are the things I've tried:

Using THROW keyword instead of simply RETURN (nothing caught)

Running SQL Server Profiler, grabbing the query the C# client sends, and manually executing it in SSMS (results in the error being shown correctly in output)

Modifying the EF generated to add a try/catch block at the ExecuteFunction<>() line (nothing caught)

Right now most threads online either fix the issue with a severity level set to 16, so I'm at a loss to what else I should be setting or looking for...

Body:
Here is a solution I've implemented, but it doesn't feel clean. Also, I don't get why I would have to make these edits to the generated code in order to catch the SqlException - if anyone has improvements it would definitely be welcome:

Part 1: Ensure your imported function under "Function Imports" of your model is set to return a collection of 'none' as the option. (I haven't gotten to SPs that return objects yet)

Part 2: Modify your EF-generated function code from the return line above into:

try
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("CreatePendingContact", lastNameParameter);
}
catch (Exception ex)
{
    if (ex.InnerException is SqlException) { throw ex.InnerException; }
    else { throw; }
}

This change will only forward SqlExceptions, while still throwing locally for all other exceptions. This is the super-simple case, but it seems to work so far...


问:
Maximum number of vertical subplots in plotly figure
I can't seem to get the spacing right for vertical subplots in plotly. Currently, my figure looks like this:

There are a couple of things that I would like to fix:

1) Increase the amount of space between subplots, and just make the figure larger

2) Increase the size of each y-axis so that the tick labels aren't overlapping.

I don't see any arguments in the plotly.tools.make_subplots function that controls the size of the figure. If there is some way to make the figure larger so that each plot has more space, that would be great.

答:
A minimal reproducible example

```<code>import plotly
plotly.offline.init_notebook_mode()
import random
rows = 10
traces = [[random.random() for j in range(100)] for i in range(rows)]

fig = plotly.tools.make_subplots(rows=rows, cols=1)
for i in range(1, rows + 1):
    p = plotly.graph_objs.Bar(y=traces[i - 1], showlegend=False)
    fig.append_trace(p, i, 1)
plotly.offline.iplot(fig)
</code>```

produces

1) Increase the amount of space between subplots, and just make the
  figure larger

2) Increase the size of each y-axis so that the tick labels aren't overlapping.

You can use vertical_spacing in combination with layout['height'] to address both issues at the same time.

```<code>fig = plotly.tools.make_subplots(rows=rows, cols=1, vertical_spacing=0.5/rows)
fig['layout'].update(height=1000)
</code>```

Body:
A minimal reproducible example

import plotly
plotly.offline.init_notebook_mode()
import random
rows = 10
traces = [[random.random() for j in range(100)] for i in range(rows)]

fig = plotly.tools.make_subplots(rows=rows, cols=1)
for i in range(1, rows + 1):
    p = plotly.graph_objs.Bar(y=traces[i - 1], showlegend=False)
    fig.append_trace(p, i, 1)
plotly.offline.iplot(fig)

produces

1) Increase the amount of space between subplots, and just make the
  figure larger

2) Increase the size of each y-axis so that the tick labels aren't overlapping.

You can use vertical_spacing in combination with layout['height'] to address both issues at the same time.

fig = plotly.tools.make_subplots(rows=rows, cols=1, vertical_spacing=0.5/rows)
fig['layout'].update(height=1000)


问:
shell - compare files and update matching string awk/sed/diff/grep/csv
I need to compare 2 csv files and make modifications to the second column. I wrote out the logic out of how I would want to achieve this however, it seems to confuse the thread a lot more than I wanted too so I'll just write out the example.

Any help would be appreciated. Thanks in advance.

file1

```<code>user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName3
user4,distinguishedName4
user5,distinguishedName5
</code>```

file2

```<code>user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4
</code>```

desired outcome:

```<code>user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4
</code>```

答:
awk to the rescue!

```<code>awk -F, '!a[$1]++' file2 file1

user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4
user2,distinguishedName2
user4,distinguishedName4
</code>```

this order is based on file2 and file1 record order, if you want sorted order just pipe to sort

```<code>awk ... | sort
</code>```

Body:
I need to compare 2 csv files and make modifications to the second column. I wrote out the logic out of how I would want to achieve this however, it seems to confuse the thread a lot more than I wanted too so I'll just write out the example.

Any help would be appreciated. Thanks in advance.

file1

user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName3
user4,distinguishedName4
user5,distinguishedName5

file2

user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4

desired outcome:

user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4

Body:
awk to the rescue!

awk -F, '!a[$1]++' file2 file1

user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4
user2,distinguishedName2
user4,distinguishedName4

this order is based on file2 and file1 record order, if you want sorted order just pipe to sort

awk ... | sort


问:
Java- How to manage a database connection in a large java project
The main question is that in a a large/big java project with multiple classes having multiple db connection,

Should we use a global Single Connection to db and run it till the program ends and close it at the end of program or
Should we use multiple db connections whenever it is required ?
which is better in terms of security , ease of access.

答:
In a "big" project I would use an application container to manage the database connections for me.
Security is not only depending on the connection to the database. For me this leads a bit too far. Security can always be an issue if the design has flaws, e.g. SQL Injections.</p>


问:
AWSIoT Android SDK fails to generate new certificate+key
I am pretty new to Android programming, so any guidance is highly appreciated.
I am trying to generate a key+certificate for connection to the AWS IoT server. It fails saying a certain URL in amazon domain has no domain-name -> address resolution.
The Android log message is :

```<code>I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
              OpenGL ES Shader Compiler Version: E031.25.03.00
              Build Date: 01/21/15 Wed
              Local Branch: mybranch7061829
              Remote Branch: quic/LA.BF.1.1.1_rb1.7
              Local Patches: NONE
              Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
D/Atlas: Validating map...
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=1024; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
E/MediaProfilesEx-JNI: register_com_lge_media_MediaProfilesEx
E/MediaRecorderEx-JNI: register_com_lge_media_MediaRecorderEx
D/AudioSystemEx: register_com_lge_media_LGAudioSystem
E/SurfaceControlEx: register_com_lge_view_SurfaceControlEx
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
D/LGMtpDatabaseJNI: register_android_mtp_LGMtpDatabase
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
D/LGMtpServerJNI: register_android_mtp_LGMtpServer
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
E/MediaPlayerEx-jni: register_com_lge_view_MediaPlayerEx
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"

       [ 12-29 22:00:44.433 14654:14654 D/         ]
       register_com_lge_emoji_EmojiUtil
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
W/System.err: com.amazonaws.AmazonClientException: Unable to execute HTTP request: Unable to resolve host "execute-api.eu-central-1.amazonaws.com": No address associated with hostname
W/System.err:     at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:424)
W/System.err:     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:199)
W/System.err:     at com.amazonaws.services.iot.AWSIotClient.invoke(AWSIotClient.java:3713)
W/System.err:     at com.amazonaws.services.iot.AWSIotClient.createKeysAndCertificate(AWSIotClient.java:754)
W/System.err:     at com.home.tukai.awsiottryout01.MainActivity$3.run(MainActivity.java:188)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: java.net.UnknownHostException: Unable to resolve host "execute-api.eu-central-1.amazonaws.com": No address associated with hostname
W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:435)
W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:255)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:218)
W/System.err:     at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:303)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:242)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:397)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:229)
W/System.err:     at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
W/System.err:     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
W/System.err:     at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:156)
W/System.err:     at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:70)
W/System.err:     at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:356)
W/System.err:   ... 5 more
E/AWS: Exception occurred when generating new private key and certificate.
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
</code>```

Now, interestingly, if I load a KeyStore into the phone into the location of the app's package, then it works fine. The (KeyStore==null) is not checked then.
The Keystore here is created out of downloaded certificates from my AWS account associated to this THING.
My question is: Am I doing anything wrong here ? If not, then what is it that I am missing out ?

I am trying to following this link to create my program : https://github.com/awslabs/aws-sdk-android-samples/blob/master/AndroidPubSub/src/com/amazonaws/demo/androidpubsub/PubSubActivity.java

The relevant section of my program :

```<code>private static final String CUSTOMER_SPECIFIC_ENDPOINT = "a228q6docijn1f.iot.eu-central-1.amazonaws.com";
// Cognito pool ID. For this app, pool needs to be unauthenticated pool with
// AWS IoT permissions.
private static final String COGNITO_POOL_ID = "eu-central-1:36b201e2-d55e-4601-9430-031fc7990291";
// Name of the AWS IoT policy to attach to a newly created certificate
private static final String AWS_IOT_POLICY_NAME = "all-iot";

// Region of AWS IoT
private static final Regions MY_REGION = Regions.EU_CENTRAL_1;
// Filename of KeyStore file on the filesystem
private static final String KEYSTORE_NAME = "KeyStoreAlfred01.bks";
// Password for the private key in the KeyStore
private static final String KEYSTORE_PASSWORD = "<THIS I FILLED IN CORRECTLY>";
// Certificate and key aliases in the KeyStore
private static final String CERTIFICATE_ID = "keystorealfred01";

AWSIotClient mIotAndroidClient;
AWSIotMqttManager mqttManager;
String clientId;
String keystorePath;
String keystoreName;
String keystorePassword;

KeyStore clientKeyStore = null;
String certificateId;

CognitoCachingCredentialsProvider credentialsProvider;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    btnGenNumber = (Button) findViewById(R.id.btnGenNumber);
    btnConnect = (Button) findViewById(R.id.btnConnect);
    btnYoutubeSearch = (Button) findViewById(R.id.btnYoutubeSearch);

    btnGenNumber.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Random r = new Random();
            int num = r.nextInt(51);

            try {
                mqttManager.publishString(Integer.toString(num), "test", AWSIotMqttQos.QOS0);
                Toast.makeText(getApplicationContext(), "Published number " + Integer.toString(num), Toast.LENGTH_LONG).show();

                Log.i(LOG_TAG, "Publish done");
            } catch (Exception e) {
                Log.e(LOG_TAG, "Publish error.", e);
            }

            Log.i(LOG_TAG, "Button generated a new number" + num);
        }
    });

    btnYoutubeSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_SEARCH);
            intent.setPackage("com.google.android.youtube");
            intent.putExtra("query", "Android");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
    // Initialize the AWS Cognito credentials provider
    credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(), // context
            COGNITO_POOL_ID, // Identity Pool ID
            MY_REGION // Region
    );
    Log.i(LOG_TAG, "Credentials provider output " + credentialsProvider.toString());
    Region region = Region.getRegion(MY_REGION);
    mIotAndroidClient = new AWSIotClient(credentialsProvider);
    mIotAndroidClient.setRegion(region);

    //keystorePath = "/mnt/sdcard/awsIOTtryout01";
    keystorePath = getFilesDir().getPath();
    keystoreName = KEYSTORE_NAME;
    keystorePassword = KEYSTORE_PASSWORD;
    certificateId = CERTIFICATE_ID;

    Log.i(LOG_TAG, "Begin certificate load");

    // To load cert/key from keystore on filesystem
    try {
        if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
            if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath,
                    keystoreName, keystorePassword)) {
                Log.i(LOG_TAG, "Certificate " + certificateId
                        + " found in keystore - using for MQTT.");
                // load keystore from file into memory to pass on connection
                clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
                        keystorePath, keystoreName, keystorePassword);
                Log.i(LOG_TAG, "Certificate loading complete");
                //btnConnect.setEnabled(true);
            } else {
                Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
            }
        } else {
            Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
    }

    if (clientKeyStore == null) {
        Toast.makeText(getApplicationContext(),"Cert/key was not found in keystore - creating new key and certificate.",Toast.LENGTH_SHORT).show();
        Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Create a new private key and certificate. This call
                    // creates both on the server and returns them to the
                    // device.
                    CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
                            new CreateKeysAndCertificateRequest();
                    createKeysAndCertificateRequest.setSetAsActive(true);
                    Log.i(LOG_TAG,"keys + cert generation : "+createKeysAndCertificateRequest.toString());
                    final CreateKeysAndCertificateResult createKeysAndCertificateResult;
                    createKeysAndCertificateResult =mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);

                    //Log.i(LOG_TAG,"Cert ID: New certificate generation done.");
                    //Toast.makeText(getApplicationContext(),"New certificate created", Toast.LENGTH_SHORT).show();
                    // store in keystore for use in MQTT client
                    // saved as alias "default" so a new certificate isn't
                    // generated each run of this application
                    AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
                            createKeysAndCertificateResult.getCertificatePem(),
                            createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
                            keystorePath, keystoreName, keystorePassword);

                    // load keystore from file into memory to pass on connection

                    clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
                            keystorePath, keystoreName, keystorePassword);
                    // Attach a policy to the newly created certificate
                    // This flow assumes the policy was already created in
                    // AWS IoT and we are now just attaching it to the
                    // certificate.

                    AttachPrincipalPolicyRequest policyAttachRequest =
                            new AttachPrincipalPolicyRequest();
                    policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
                    policyAttachRequest.setPrincipal(createKeysAndCertificateResult.getCertificateArn());
                    mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
                } catch (Exception e) {
                   // Toast.makeText(getApplicationContext(),"Exception occured when generating new key+cert",Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                    Log.e(LOG_TAG,"Exception occurred when generating new private key and certificate.",e);
                }
            }
        }).start();
    }
</code>```

I am using ANdroid Studio 2.2.2 using Min API : 9 for the project. ANy help is highly appreciated !

Update : When the KeyStore file ( with certs ) is present inside the phone's mem location of this package, then the Android logs look like :

```<code>/CognitoCachingCredentia`enter code here`lsProvider: Loading credentials from SharedPreferences
I/AWS: Credentials provider output com.amazonaws.auth.CognitoCachingCredentialsProvider@2d7ae714
I/AmazonWebServiceClient: {execute-api, eu-central-1} was not found in region metadata, trying to construct an endpoint using the standard pattern for this region: 'execute-api.eu-central-1.amazonaws.com'.
I/AWS: Begin certificate load
I/AWS: Certificate keystorealfred01 found in keystore - using for MQTT.
I/AWS: Certificate loading complete
D/OpenGLRenderer: Render dirty regions requested: true
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
              OpenGL ES Shader Compiler Version: E031.25.03.00
              Build Date: 01/21/15 Wed
              Local Branch: mybranch7061829
              Remote Branch: quic/LA.BF.1.1.1_rb1.7
              Local Patches: NONE
              Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
D/Atlas: Validating map...
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@25603903 time:661926148
</code>```

答:
I can see following line in your exception logs:

Unable to resolve host "execute-api.eu-central-1.amazonaws.com"

This tells me that you are not hitting the right endpoint for IoT.

For calling CreateKeyAndCertificates in eu-central-1 you need to hit iot.eu-central-1.amazonaws.com

You can try setting this endpoint using:

mIotAndroidClient.setEndpoint("iot.eu-central-1.amazonaws.com");

Thanks
Ashutosh

Body:
I am pretty new to Android programming, so any guidance is highly appreciated.
I am trying to generate a key+certificate for connection to the AWS IoT server. It fails saying a certain URL in amazon domain has no domain-name -> address resolution.
The Android log message is :

I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
              OpenGL ES Shader Compiler Version: E031.25.03.00
              Build Date: 01/21/15 Wed
              Local Branch: mybranch7061829
              Remote Branch: quic/LA.BF.1.1.1_rb1.7
              Local Patches: NONE
              Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
D/Atlas: Validating map...
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=1024; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
E/MediaProfilesEx-JNI: register_com_lge_media_MediaProfilesEx
E/MediaRecorderEx-JNI: register_com_lge_media_MediaRecorderEx
D/AudioSystemEx: register_com_lge_media_LGAudioSystem
E/SurfaceControlEx: register_com_lge_view_SurfaceControlEx
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
D/LGMtpDatabaseJNI: register_android_mtp_LGMtpDatabase
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
D/LGMtpServerJNI: register_android_mtp_LGMtpServer
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"
E/MediaPlayerEx-jni: register_com_lge_view_MediaPlayerEx
I/art: Thread[1,tid=14654,WaitingForJniOnLoad,Thread*=0xb4827800,peer=0x75c35b48,"main"] recursive attempt to load library "/system/lib/libhook_jni.so"

       [ 12-29 22:00:44.433 14654:14654 D/         ]
       register_com_lge_emoji_EmojiUtil
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
W/System.err: com.amazonaws.AmazonClientException: Unable to execute HTTP request: Unable to resolve host "execute-api.eu-central-1.amazonaws.com": No address associated with hostname
W/System.err:     at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:424)
W/System.err:     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:199)
W/System.err:     at com.amazonaws.services.iot.AWSIotClient.invoke(AWSIotClient.java:3713)
W/System.err:     at com.amazonaws.services.iot.AWSIotClient.createKeysAndCertificate(AWSIotClient.java:754)
W/System.err:     at com.home.tukai.awsiottryout01.MainActivity$3.run(MainActivity.java:188)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: java.net.UnknownHostException: Unable to resolve host "execute-api.eu-central-1.amazonaws.com": No address associated with hostname
W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:435)
W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:255)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:218)
W/System.err:     at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:303)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:242)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:397)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:229)
W/System.err:     at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
W/System.err:     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
W/System.err:     at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:156)
W/System.err:     at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:70)
W/System.err:     at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:356)
W/System.err:   ... 5 more
E/AWS: Exception occurred when generating new private key and certificate.
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection

Now, interestingly, if I load a KeyStore into the phone into the location of the app's package, then it works fine. The (KeyStore==null) is not checked then.
The Keystore here is created out of downloaded certificates from my AWS account associated to this THING.
My question is: Am I doing anything wrong here ? If not, then what is it that I am missing out ?

I am trying to following this link to create my program : https://github.com/awslabs/aws-sdk-android-samples/blob/master/AndroidPubSub/src/com/amazonaws/demo/androidpubsub/PubSubActivity.java

The relevant section of my program :

private static final String CUSTOMER_SPECIFIC_ENDPOINT = "a228q6docijn1f.iot.eu-central-1.amazonaws.com";
// Cognito pool ID. For this app, pool needs to be unauthenticated pool with
// AWS IoT permissions.
private static final String COGNITO_POOL_ID = "eu-central-1:36b201e2-d55e-4601-9430-031fc7990291";
// Name of the AWS IoT policy to attach to a newly created certificate
private static final String AWS_IOT_POLICY_NAME = "all-iot";

// Region of AWS IoT
private static final Regions MY_REGION = Regions.EU_CENTRAL_1;
// Filename of KeyStore file on the filesystem
private static final String KEYSTORE_NAME = "KeyStoreAlfred01.bks";
// Password for the private key in the KeyStore
private static final String KEYSTORE_PASSWORD = "<THIS I FILLED IN CORRECTLY>";
// Certificate and key aliases in the KeyStore
private static final String CERTIFICATE_ID = "keystorealfred01";

AWSIotClient mIotAndroidClient;
AWSIotMqttManager mqttManager;
String clientId;
String keystorePath;
String keystoreName;
String keystorePassword;

KeyStore clientKeyStore = null;
String certificateId;

CognitoCachingCredentialsProvider credentialsProvider;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    btnGenNumber = (Button) findViewById(R.id.btnGenNumber);
    btnConnect = (Button) findViewById(R.id.btnConnect);
    btnYoutubeSearch = (Button) findViewById(R.id.btnYoutubeSearch);

    btnGenNumber.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Random r = new Random();
            int num = r.nextInt(51);

            try {
                mqttManager.publishString(Integer.toString(num), "test", AWSIotMqttQos.QOS0);
                Toast.makeText(getApplicationContext(), "Published number " + Integer.toString(num), Toast.LENGTH_LONG).show();

                Log.i(LOG_TAG, "Publish done");
            } catch (Exception e) {
                Log.e(LOG_TAG, "Publish error.", e);
            }

            Log.i(LOG_TAG, "Button generated a new number" + num);
        }
    });

    btnYoutubeSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_SEARCH);
            intent.setPackage("com.google.android.youtube");
            intent.putExtra("query", "Android");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
    // Initialize the AWS Cognito credentials provider
    credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(), // context
            COGNITO_POOL_ID, // Identity Pool ID
            MY_REGION // Region
    );
    Log.i(LOG_TAG, "Credentials provider output " + credentialsProvider.toString());
    Region region = Region.getRegion(MY_REGION);
    mIotAndroidClient = new AWSIotClient(credentialsProvider);
    mIotAndroidClient.setRegion(region);

    //keystorePath = "/mnt/sdcard/awsIOTtryout01";
    keystorePath = getFilesDir().getPath();
    keystoreName = KEYSTORE_NAME;
    keystorePassword = KEYSTORE_PASSWORD;
    certificateId = CERTIFICATE_ID;

    Log.i(LOG_TAG, "Begin certificate load");

    // To load cert/key from keystore on filesystem
    try {
        if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
            if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath,
                    keystoreName, keystorePassword)) {
                Log.i(LOG_TAG, "Certificate " + certificateId
                        + " found in keystore - using for MQTT.");
                // load keystore from file into memory to pass on connection
                clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
                        keystorePath, keystoreName, keystorePassword);
                Log.i(LOG_TAG, "Certificate loading complete");
                //btnConnect.setEnabled(true);
            } else {
                Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
            }
        } else {
            Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
    }

    if (clientKeyStore == null) {
        Toast.makeText(getApplicationContext(),"Cert/key was not found in keystore - creating new key and certificate.",Toast.LENGTH_SHORT).show();
        Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Create a new private key and certificate. This call
                    // creates both on the server and returns them to the
                    // device.
                    CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
                            new CreateKeysAndCertificateRequest();
                    createKeysAndCertificateRequest.setSetAsActive(true);
                    Log.i(LOG_TAG,"keys + cert generation : "+createKeysAndCertificateRequest.toString());
                    final CreateKeysAndCertificateResult createKeysAndCertificateResult;
                    createKeysAndCertificateResult =mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);

                    //Log.i(LOG_TAG,"Cert ID: New certificate generation done.");
                    //Toast.makeText(getApplicationContext(),"New certificate created", Toast.LENGTH_SHORT).show();
                    // store in keystore for use in MQTT client
                    // saved as alias "default" so a new certificate isn't
                    // generated each run of this application
                    AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
                            createKeysAndCertificateResult.getCertificatePem(),
                            createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
                            keystorePath, keystoreName, keystorePassword);

                    // load keystore from file into memory to pass on connection

                    clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
                            keystorePath, keystoreName, keystorePassword);
                    // Attach a policy to the newly created certificate
                    // This flow assumes the policy was already created in
                    // AWS IoT and we are now just attaching it to the
                    // certificate.

                    AttachPrincipalPolicyRequest policyAttachRequest =
                            new AttachPrincipalPolicyRequest();
                    policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
                    policyAttachRequest.setPrincipal(createKeysAndCertificateResult.getCertificateArn());
                    mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
                } catch (Exception e) {
                   // Toast.makeText(getApplicationContext(),"Exception occured when generating new key+cert",Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                    Log.e(LOG_TAG,"Exception occurred when generating new private key and certificate.",e);
                }
            }
        }).start();
    }

I am using ANdroid Studio 2.2.2 using Min API : 9 for the project. ANy help is highly appreciated !

Update : When the KeyStore file ( with certs ) is present inside the phone's mem location of this package, then the Android logs look like :

/CognitoCachingCredentia`enter code here`lsProvider: Loading credentials from SharedPreferences
I/AWS: Credentials provider output com.amazonaws.auth.CognitoCachingCredentialsProvider@2d7ae714
I/AmazonWebServiceClient: {execute-api, eu-central-1} was not found in region metadata, trying to construct an endpoint using the standard pattern for this region: 'execute-api.eu-central-1.amazonaws.com'.
I/AWS: Begin certificate load
I/AWS: Certificate keystorealfred01 found in keystore - using for MQTT.
I/AWS: Certificate loading complete
D/OpenGLRenderer: Render dirty regions requested: true
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
              OpenGL ES Shader Compiler Version: E031.25.03.00
              Build Date: 01/21/15 Wed
              Local Branch: mybranch7061829
              Remote Branch: quic/LA.BF.1.1.1_rb1.7
              Local Patches: NONE
              Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
D/Atlas: Validating map...
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@25603903 time:661926148


问:
How to run sonarqube on mac?
```<code>WrapperSimpleApp: Unable to locate the class org.sonar.application.App:
java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupported
major.minor version 52.0
</code>```

I'm trying to run the simplest sonarqube (2 minute intro) project and have gotten this error. From looking around I thought this error was supposed to occur when you don't have the latest version of java installed on mac. I have java version 8, installed via brew, am I missing something?

答:
You get this message when you are trying to run a Java application that requires Java 8, but you only have 7 or lower.

SonarQube requires Java 8 (bytecode version 52.0).
You can try to install Java 8, or try SonarQube 5.5 instead (5.6 was the first version to mandate Java 8).

Title: How to run sonarqube on mac?

Body:
WrapperSimpleApp: Unable to locate the class org.sonar.application.App:
java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupported
major.minor version 52.0

I'm trying to run the simplest sonarqube (2 minute intro) project and have gotten this error. From looking around I thought this error was supposed to occur when you don't have the latest version of java installed on mac. I have java version 8, installed via brew, am I missing something?


问:
Can't update or install package: An item with the same key has already been added

Problem

In a particular project, I can't update or install any NuGet packages. When I try to do so using the NuGet GUI, it does some work and then stops without saying anything. When I try to do so using the package manager console, I get this output:

```<code>PM> Update-Package –reinstall EntityFramework
Attempting to gather dependencies information for multiple packages with respect to project 'SmartCentre', targeting '.NETFramework,Version=v4.5.2'
Update-Package : An item with the same key has already been added.
At line:1 char:15
+ Update-Package <<<<  –reinstall EntityFramework
    + CategoryInfo          : NotSpecified: (:) [Update-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.UpdatePackageCommand
</code>```

Environment

Visual Studio Professional 2015 Update 1

NuGet 3.3.0.167

What I've tried

Deleting the packages folder

Restarting Visual Studio

Restarting the computer

答:
I tried everything and then;

Made sure the Framework was up to date. (for the MVC package I was upgrading)

Uninstalled NuGet and reinstalled it.

It might be worth a try. Doesn't take too long.

Body:
Problem

In a particular project, I can't update or install any NuGet packages. When I try to do so using the NuGet GUI, it does some work and then stops without saying anything. When I try to do so using the package manager console, I get this output:

PM> Update-Package –reinstall EntityFramework
Attempting to gather dependencies information for multiple packages with respect to project 'SmartCentre', targeting '.NETFramework,Version=v4.5.2'
Update-Package : An item with the same key has already been added.
At line:1 char:15
+ Update-Package <<<<  –reinstall EntityFramework
    + CategoryInfo          : NotSpecified: (:) [Update-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.UpdatePackageCommand

Environment

Visual Studio Professional 2015 Update 1

NuGet 3.3.0.167

What I've tried

Deleting the packages folder

Restarting Visual Studio

Restarting the computer


问:
How do I return the smallest value using a for loop?
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

```<code>public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}
</code>```

The output would be:

1 : 1

4 : 3

10 : 4

答:
You get avoid the loop to compute the sum of the n first integers, using:

Thus the inequality becomes:

Notice that the left-hand side is positive (if n is negative, the sum is empty) and strictly increasing. Notice also that you are looking for the first integer satisfying the inequality. The idea here is first to replace the inequality by an equality which will allow us to solve the equation for n. In a second step, the possibly non-integer solution will be rounder to the closest integer.

Solving this equation for n should give you two solutions. The negative one can be discarded (remember n is positive). That is:

Finally, let's round this solution to the closest integer that will also satisfy the inequality:

NB: it can be overkilled for small inputs

Body:
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}

The output would be:

1 : 1

4 : 3

10 : 4


问:
javaScript - Find the sum of all divisors of a given integer
i'm doing some coding exercises and i'm not being able to solve this one.

Find the sum of all divisors of a given integer.
For n = 12, the  input should be
sumOfDivisors(n) = 28.

example: 1 + 2 + 3 + 4 + 6 + 12 = 28.

Constraints:
1 ≤ n ≤ 15.

how can i solve this exercise? i'm not being able to.

```<code>function(n){
    var arr = [],
        finalSum;

    if(n <= 1 || n => 16){
       return false ;
   }
   for(var i = 0; i < n; i++){
       var tmp= n/2;
       arr.push(tmp)
       // i need to keep on dividing n but i can't get the way of how to
   }
  return finalSum;
}
</code>```

答:
You have to check if specified number is or not a divisor of given integer. You can use modulo % - if there's no rest, specified number is the divisor of the given integer - add it to the sum.

function sumDivisors(num){
  var sum = 0;
  for (var i = 1; i <= num; i++){
    if (!(num % i)) {
      sum += i;
    }
  }
  console.log(sum);
}

sumDivisors(6);
sumDivisors(10);```

Body:
i'm doing some coding exercises and i'm not being able to solve this one.

Find the sum of all divisors of a given integer.
For n = 12, the  input should be
sumOfDivisors(n) = 28.

example: 1 + 2 + 3 + 4 + 6 + 12 = 28.

Constraints:
1 ≤ n ≤ 15.

how can i solve this exercise? i'm not being able to.

function(n){
    var arr = [],
        finalSum;

    if(n <= 1 || n => 16){
       return false ;
   }
   for(var i = 0; i < n; i++){
       var tmp= n/2;
       arr.push(tmp)
       // i need to keep on dividing n but i can't get the way of how to
   }
  return finalSum;
}


问:
web api - posting object returns internal server error 500
I have a simple web api that uses a database first ADO SQL server entity, with one table in it that has an auto-incrementing identity column and a nvarchar column.  My GET functions work fine, but I'm having trouble with POST.

Here is my controller, which was largely automatically generated:

```<code>public class CustomersController : ApiController
{
    private MyEntities db = new MyEntities();

    // GET: api/Customers
    public IQueryable<Customer> GetCustomers()
    {
        return db.Customers;
    }

    // GET: api/Customers/5
    [ResponseType(typeof(Customer))]
    public IHttpActionResult GetCustomer(int id)
    {
        Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
        if (customer == null)
        {
            return NotFound();
        }

        return Ok(customer);
    }

    // PUT: api/Customers/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutCustomer(int id, Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != customer.CustomerPk)
        {
            return BadRequest();
        }

        db.Entry(customer).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CustomerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Customers
    [ResponseType(typeof(Customer))]
    public IHttpActionResult PostCustomer(Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Customers.Add(customer);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = customer.CustomerPk }, customer);
    }

    // DELETE: api/Customers/5
    [ResponseType(typeof(Customer))]
    public IHttpActionResult DeleteCustomer(int id)
    {
        Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
        if (customer == null)
        {
            return NotFound();
        }

        db.Customers.Remove(customer);
        db.SaveChanges();

        return Ok(customer);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool CustomerExists(int id)
    {
        return db.Customers.Count(e => e.CustomerPk == id) > 0;
    }
}
</code>```

In an HTML page I am calling the following jquery ajax:

```<code>    var customer = { "CustomerPk": 0, "CustomerName": "TEST2" };

        $.ajax(
        {
            url: "http://serverurl/site/api/customers",
            type: "POST",
            contentType: "application/json; charset=UTF-8",
            data: JSON.stringify(customer),
            dataType: "json",
            success: function (data, textStatus, xhr) { alert("Success"); },
            error: function (xhr, textStatus, errorThrown)
            {
                var msg = "Code: " + xhr.status + "\n";
                msg += "Text: " + xhr.statusText + "\n";
                if (xhr.responseJSON != null)
                {
                    msg += "JSON Message: " + xhr.responseJSON.Message + "\n";
                }

                alert(msg);
            }
        });
</code>```

Like I mentioned, when I call the GET methods from this page, everything works.  I've tried different variations of the ajax method based on countless examples of posting an object to web api online, mostly changing the object I'm posting, leaving out the identity column and just sending the CustomerName column, or setting the Pk to null, but none of those worked.  I always get a 500 internal server error.

Does it not work with auto-incrementing identity columns?  The examples I've seen don't seem to have those as part of the model, so I'm wondering if that's my problem.

Any help or advice would be greatly appreciated, thank you.

答: Do you have access to any server-side error-logs since a 500 internal error can have many causes. </p>

Body:
I have a simple web api that uses a database first ADO SQL server entity, with one table in it that has an auto-incrementing identity column and a nvarchar column.  My GET functions work fine, but I'm having trouble with POST.

Here is my controller, which was largely automatically generated:

public class CustomersController : ApiController
{
    private MyEntities db = new MyEntities();

    // GET: api/Customers
    public IQueryable<Customer> GetCustomers()
    {
        return db.Customers;
    }

    // GET: api/Customers/5
    [ResponseType(typeof(Customer))]
    public IHttpActionResult GetCustomer(int id)
    {
        Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
        if (customer == null)
        {
            return NotFound();
        }

        return Ok(customer);
    }

    // PUT: api/Customers/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutCustomer(int id, Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != customer.CustomerPk)
        {
            return BadRequest();
        }

        db.Entry(customer).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CustomerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Customers
    [ResponseType(typeof(Customer))]
    public IHttpActionResult PostCustomer(Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Customers.Add(customer);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = customer.CustomerPk }, customer);
    }

    // DELETE: api/Customers/5
    [ResponseType(typeof(Customer))]
    public IHttpActionResult DeleteCustomer(int id)
    {
        Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
        if (customer == null)
        {
            return NotFound();
        }

        db.Customers.Remove(customer);
        db.SaveChanges();

        return Ok(customer);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool CustomerExists(int id)
    {
        return db.Customers.Count(e => e.CustomerPk == id) > 0;
    }
}

In an HTML page I am calling the following jquery ajax:

    var customer = { "CustomerPk": 0, "CustomerName": "TEST2" };

        $.ajax(
        {
            url: "http://serverurl/site/api/customers",
            type: "POST",
            contentType: "application/json; charset=UTF-8",
            data: JSON.stringify(customer),
            dataType: "json",
            success: function (data, textStatus, xhr) { alert("Success"); },
            error: function (xhr, textStatus, errorThrown)
            {
                var msg = "Code: " + xhr.status + "\n";
                msg += "Text: " + xhr.statusText + "\n";
                if (xhr.responseJSON != null)
                {
                    msg += "JSON Message: " + xhr.responseJSON.Message + "\n";
                }

                alert(msg);
            }
        });

Like I mentioned, when I call the GET methods from this page, everything works.  I've tried different variations of the ajax method based on countless examples of posting an object to web api online, mostly changing the object I'm posting, leaving out the identity column and just sending the CustomerName column, or setting the Pk to null, but none of those worked.  I always get a 500 internal server error.

Does it not work with auto-incrementing identity columns?  The examples I've seen don't seem to have those as part of the model, so I'm wondering if that's my problem.

Any help or advice would be greatly appreciated, thank you.


问:
can a sql 2005 ssis package be scheduled?
I have a data dump that I manually initiate and I want to automate things now that they are working well. I have a system that exports data into Excel that I ultimately want to import into a SQL table.

I have a ssis package that I used for the import and saved it for re-use later. I just manually ran it and it works well. Now I would like to have it run either when invoked by a file watcher or schedule or some thing so that all I need to do is over-write the excel file and have it trigger the ssis to run its import.

Any ideas on how to make this happen?

答: SQL Server does its scheduling with SQL Agent, so try creating a schedule in that to do what you want.</p>


问:
Why am I getting a TransactionRequiredException in @PostConstruct method in JTA EJB?
I have Java EE project where I want to use an injected JTA EntityManager in the @PostConstruct method. EntityManager.persist fails due to javax.persistence.TransactionRequiredException. It succeeds when called through an EJB instance injected into a  JSF managed bean. Manually starting a transaction with @Resource UserTransaction and UserTransaction.begin/commit or EntityManager.getTransaction.begin/commit because it's a JTA EntityManager.

The EJB interface

```<code>@Local
public interface UserService extends Serializable {

    public void saveUser(AUser user);
}

@Entity
public class AUser implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    private String username;

    public AUser() {
    }

    public AUser(String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
</code>```

The EJB implementation:

```<code>@Stateless
public class DefaultUserService implements UserService {
    private static final long serialVersionUID = 1L;
    @PersistenceContext
    private EntityManager entityManager;

    public DefaultUserService() {
    }

    @PostConstruct
    private void init() {
        AUser user = new AUser("initUser");
        saveUser(user);
    }

    @Override
    public void saveUser(AUser user) {
        entityManager.persist(user);
    }
}
</code>```

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="richtercloud_javaee-persist-in-postconstruct-jar_jar_1.0-SNAPSHOTPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/example1</jta-data-source>
    <class>richtercloud.javaee.persist.in.postconstruct.jar.entities.AUser</class>
    <properties>
      <property name="eclipselink.target-database" value="Derby"/>
      <!-- necessary in order to avoid syntax errors -->
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
      <property name="eclipselink.target-server" value="Glassfish"/>
      <!-- avoid non-severe NullPointerException being logged in GlasFish
            <ref>https://java.net/jira/browse/GLASSFISH-21468f</ref>-->
    </properties>
  </persistence-unit>
</persistence>
</code>```

I didn't know how to provide the jdbc/example1 data source (it's GlassFish 4.1 JDBC resource based on a JDBC connection pool referring to a Derby database with network driver). Everything else it available at https://github.com/krichter722/javaee-persist-in-postconstruct.

I read Persisting in @PostConstruct: javax.persistence.TransactionRequiredException which exceeds the example of a simple EntityManager.persist call in @PostConstruct and http://www.tikalk.com/java/doing-transactional-work-spring-service-using-postconstruct-method/ which refers to Spring which I'm not using. I found no statement that @PersistenceContext EntityManager behaves differently in @PostConstruct.

答:
§8.6.2 of the EJB 3.2 specification states:

The term “an unspecified transaction context” is used in the EJB specification to refer to the cases in which the EJB architecture does not fully define the transaction semantics of an enterprise bean method execution.

  This includes the following cases:

  ...

   •  The execution of a PostConstruct or PreDestroy callback method of a stateless session bean with container-managed transaction demarcation.

An alternative solution may be to specify the javax.persistence.sql-load-script-source property in your persistence.xml file. It points at a SQL script that will preload your database. This can be a resource embedded in your application or a file URL.

Body:
I have Java EE project where I want to use an injected JTA EntityManager in the @PostConstruct method. EntityManager.persist fails due to javax.persistence.TransactionRequiredException. It succeeds when called through an EJB instance injected into a  JSF managed bean. Manually starting a transaction with @Resource UserTransaction and UserTransaction.begin/commit or EntityManager.getTransaction.begin/commit because it's a JTA EntityManager.

The EJB interface

@Local
public interface UserService extends Serializable {

    public void saveUser(AUser user);
}

@Entity
public class AUser implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    private String username;

    public AUser() {
    }

    public AUser(String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

The EJB implementation:

@Stateless
public class DefaultUserService implements UserService {
    private static final long serialVersionUID = 1L;
    @PersistenceContext
    private EntityManager entityManager;

    public DefaultUserService() {
    }

    @PostConstruct
    private void init() {
        AUser user = new AUser("initUser");
        saveUser(user);
    }

    @Override
    public void saveUser(AUser user) {
        entityManager.persist(user);
    }
}

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="richtercloud_javaee-persist-in-postconstruct-jar_jar_1.0-SNAPSHOTPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/example1</jta-data-source>
    <class>richtercloud.javaee.persist.in.postconstruct.jar.entities.AUser</class>
    <properties>
      <property name="eclipselink.target-database" value="Derby"/>

      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
      <property name="eclipselink.target-server" value="Glassfish"/>

    </properties>
  </persistence-unit>
</persistence>

I didn't know how to provide the jdbc/example1 data source (it's GlassFish 4.1 JDBC resource based on a JDBC connection pool referring to a Derby database with network driver). Everything else it available at https://github.com/krichter722/javaee-persist-in-postconstruct.

I read Persisting in @PostConstruct: javax.persistence.TransactionRequiredException which exceeds the example of a simple EntityManager.persist call in @PostConstruct and http://www.tikalk.com/java/doing-transactional-work-spring-service-using-postconstruct-method/ which refers to Spring which I'm not using. I found no statement that @PersistenceContext EntityManager behaves differently in @PostConstruct.


问:
How to store sorted records in python, with log (n) access time?
I need to store records arranged in ascending order, with log(n) access time. I come from C++ background and if I had to use C++, I would have gone for std::map which implements red-black tree internally. This guaranties the records to always be stored in ascending order of the keys, and also guaranties log(n) access time. But what's the best way to do this in Python3.5?

One way to solve this problem will be to use the bintrees library, but is there a dedicated library for storing sorted records?

答:
You can use sortedContainers which can allow you maintain an always sorted data-structures (list, dict, dictWithKeys, set).

You can install using

pip install sortedcontainers

Here is a quick example

```<code>import sortedcontainers
g = {'B': ['A', 'C'],
     'C': ['D'],
    'A': ['B', 'C'],
     'D': [],
     }

l = sortedcontainers.SortedDict(g)

>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': []})
>>> l['G']=['A','B']
>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': [], 'G': ['A', 'B']})
>>> l['E']=['C','D','G']
>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': [], 'E': ['C', 'D', 'G'], 'G': ['A', 'B']})
>>>
</code>```

Body:
You can use sortedContainers which can allow you maintain an always sorted data-structures (list, dict, dictWithKeys, set).

You can install using

pip install sortedcontainers

Here is a quick example

import sortedcontainers
g = {'B': ['A', 'C'],
     'C': ['D'],
    'A': ['B', 'C'],
     'D': [],
     }

l = sortedcontainers.SortedDict(g)

>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': []})
>>> l['G']=['A','B']
>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': [], 'G': ['A', 'B']})
>>> l['E']=['C','D','G']
>>> l
SortedDict(None, 1000, {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['D'], 'D': [], 'E': ['C', 'D', 'G'], 'G': ['A', 'B']})
>>>


问:
Mvvm light messenger, communication between viewmodels

In my ViewmodelA I want to open a new window in ViewModelB, so i used the messenger class, but the probleme is that i need to reference ViewModelB inside the ViewModelA, so that ViewModelB can listen to the messages.

here is my implementation

in ViewModelA:

```<code> private void btnAddExecute()
 {
    // I need to instanciate ViewModelB otherwise it wont work/listen
    ViewModelB vb= new ViewModelB();

    Messenger.Default.Send(new NotificationMessage("ShowWindow"));
 }
</code>```

in ViewModelB i listen to the broadcasted messages in it's constructor.

is there anyway to decouple ViewmodelA from ViewmodelB ?

答:
I don't exactly see where the coupling is occurring if you are using the messenger properly.  There is no need to reference ViewModelB

Edit

Here is a way to do it without reference to an instance ViewModelB.  It uses a singleton to register for messages and create ViewModelBs when it receives the notification message.  I haven't tested this, it is just an idea.  Make sure ViewModelBCreator is used at some point so that the static constructor is called.

```<code>public class ViewModelBCreator()
{
    private static ViewModelBCreator instance;
    static ViewModelBCreator() { instance = new ViewModelBCreator(); }
    private ViewModelBCreator()
    {
        Messaging.Messenger.Default.Register<NotificationMessage>(this, true, NotificationMessageReceived);
    }
    private static void NotificationMessageReceived(NotificationMessage notification)
    {
        var vm = ViewModelB();
        //Do stuff with the new ViewModelB
    }
}

public class ViewModelB
{
    public ViewModelB()
    {
        //etc . . .
    }
}

public class ViewModelA
{
    public void OpenTheWindow()
    {
        Messenger.Default.Send(new NotificationMessage("ShowWindow"));
    }
}
</code>```

Body:
In my ViewmodelA I want to open a new window in ViewModelB, so i used the messenger class, but the probleme is that i need to reference ViewModelB inside the ViewModelA, so that ViewModelB can listen to the messages.

here is my implementation

in ViewModelA:

 private void btnAddExecute()
 {
    // I need to instanciate ViewModelB otherwise it wont work/listen
    ViewModelB vb= new ViewModelB();

    Messenger.Default.Send(new NotificationMessage("ShowWindow"));
 }

in ViewModelB i listen to the broadcasted messages in it's constructor.

is there anyway to decouple ViewmodelA from ViewmodelB ?

Body:
I don't exactly see where the coupling is occurring if you are using the messenger properly.  There is no need to reference ViewModelB

Edit

Here is a way to do it without reference to an instance ViewModelB.  It uses a singleton to register for messages and create ViewModelBs when it receives the notification message.  I haven't tested this, it is just an idea.  Make sure ViewModelBCreator is used at some point so that the static constructor is called.

public class ViewModelBCreator()
{
    private static ViewModelBCreator instance;
    static ViewModelBCreator() { instance = new ViewModelBCreator(); }
    private ViewModelBCreator()
    {
        Messaging.Messenger.Default.Register<NotificationMessage>(this, true, NotificationMessageReceived);
    }
    private static void NotificationMessageReceived(NotificationMessage notification)
    {
        var vm = ViewModelB();
        //Do stuff with the new ViewModelB
    }
}

public class ViewModelB
{
    public ViewModelB()
    {
        //etc . . .
    }
}

public class ViewModelA
{
    public void OpenTheWindow()
    {
        Messenger.Default.Send(new NotificationMessage("ShowWindow"));
    }
}


问:
ReSharper - Duplicate Resource (resx file)
After running ReSharper on our project we receive the following error multiple times in various resx files;

"Duplicate Resource"

Is there a way we can easily clean each forms resx file. For example, is there a way we can safely regenerate the resx file within VS2010?

This is a C# project.

答: I'm the author of a commercial localization product (see http://www.hexadigm.com). If your ".resx" files are code-behind files for a windows form or user control (created and managed by the VS forms designer), then you can normally fix the problem by setting the form's "Localizable" property to false and then immediately back to true again (in the VS forms designer). That will regenerate the ".resx" file and normally eliminate any duplicates (backup your files first however, just in case). For other ".resx" files however (non-code-behind files you manage yourself), I'm not aware of any tool that will fix this for you. Note that my own product however will trap this problem (and others) but doesn't fix it. It's too risky IMO. If you have a duplicate resource that is, then the entire ".resx" file is suspect so attempting to automate a fix could make things worse (since the file could potentially have more serious problems than just duplicates). In reality it normally is just a case of duplicates (nothing more serious) but IMO it's safer for the programmer to diagnose the situation so my app will report each duplicate and then abandon processing of the affected ".resx" file (which I report to the user accordingly, as well as record to the VS Output window).</p>


问:
PHP Date from Webhook
I can't seem to figure out how to format the webhook variable.  This is an SMS and it's texting Wed Dec 31st 1969 @ 7:00 PM as the date every time.  I can't seem to work out getting the webhook variable to be formatted.

The webhook variable for the date is old_date

$date=date('D M j @ g:i A', strtotime($old_date));

$content = "Hi ".$_POST[name]." this is a reminder that we have a meeting scheduled at ".$date."";//content of the SMS

Tried this way...

$date=date('D M j Y @ g:i A', strtotime($_POST['old_date']));

$content = "Hi ".$_POST[name]." this is a reminder that we have a meeting scheduled at ".$date."";//content of the SMS

And that way...

$date=date('D M j Y @ g:i A', strtotime($_POST[old_date]));

$content = "Hi ".$_POST[name]." this is a reminder that we have a meeting scheduled at ".$date."";//content of the SMS

The last two ways failed to send an SMS.

答:
Since it's a webhook should $old_date be loaded from
one of those variables ?
 $_POST['old_date']   $_GET['old_date']   $_REQUEST['old_date']  ?

It's not clear to me how you set $old_date

I think it's returning Dec31 1969 which means $old_date is null or zero

Try adding year to do further testing

```<code>$date=date('Y, D M j @ g:i A', strtotime($old_date));
</code>```

Title: PHP Date from Webhook

Body:
Since it's a webhook should $old_date be loaded from
one of those variables ?
 $_POST['old_date']   $_GET['old_date']   $_REQUEST['old_date']  ?

It's not clear to me how you set $old_date

I think it's returning Dec31 1969 which means $old_date is null or zero

Try adding year to do further testing

$date=date('Y, D M j @ g:i A', strtotime($old_date));


问:
In Rails 5, how access cookies method in a model or helper?
How does one access cookies inside a Rails model or helper?

Trying to dry up some controller methods, I am trying to move multiple controller calls to cookies() into application_helper.rb and/or a model.

What doesn't work in application_helper.rb:

```<code>cookies[:foo]
ActionDispatch::Cookies.cookies[:foo]
ActionController.cookies[:foo]
ActionDispatch::Cookies::ChainedCookieJars.cookie[:foo]
</code>```

All of which result in undefined method 'cookies'

Note: Well-meaning answers that simply regurgitate MVC dogma are mis-placed here... I've architected long enough (decades) to know when coloring outside the MVC lines (if possible) is the better route. But the precise syntax eludes me even after digging through Rails source. This question is prompted by a somewhat complex situation related to, among other things, inconsistent browser handling of cookies in cross-domain, ajax environment that sometimes includes local files (for which Chrome declines to manage cookies).

答: It's not a good idea :) Models are classes, and they shouldn't be aware of what is happening on a web level, and that's why cookies method is implemented in ActionController, but there's no such implementation in ActionModel or ActionHelper. If you need a cookie value in a model, pass a value from a controller then. This is how it should be done.

Body:
How does one access cookies inside a Rails model or helper?

Trying to dry up some controller methods, I am trying to move multiple controller calls to cookies() into application_helper.rb and/or a model.

What doesn't work in application_helper.rb:

cookies[:foo]
ActionDispatch::Cookies.cookies[:foo]
ActionController.cookies[:foo]
ActionDispatch::Cookies::ChainedCookieJars.cookie[:foo]

All of which result in undefined method 'cookies'

Note: Well-meaning answers that simply regurgitate MVC dogma are mis-placed here... I've architected long enough (decades) to know when coloring outside the MVC lines (if possible) is the better route. But the precise syntax eludes me even after digging through Rails source. This question is prompted by a somewhat complex situation related to, among other things, inconsistent browser handling of cookies in cross-domain, ajax environment that sometimes includes local files (for which Chrome declines to manage cookies).