问:
GoogleWebAuthorizationBroker is not working from IIS Host
I am using the following code to authenticate to Google using the Google .Net client library.

```<code>public static void auth()
{

string clientId = "xxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxx";

string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts.readonly" };     // view your basic profile info.
try
{
    // Use the current Google .net client library to get the Oauth2 stuff.
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "test"
                                                                                , CancellationToken.None
                                                                                , new FileDataStore("test")).Result;

    // Translate the Oauth permissions to something the old client libray can read
    OAuth2Parameters parameters = new OAuth2Parameters();
    parameters.AccessToken = credential.Token.AccessToken;
    parameters.RefreshToken = credential.Token.RefreshToken;
    RunContactsSample(parameters);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
</code>```

I am using my own client id and client secret key.
This code is perfectly working when I am running from visual studio, but is not working from after hosted in IIS.

And I mentioned redirected URI in google api console is
http://localhost/authorize/

My IIS host Url is
http://localhost/googleintegration.aspx

I am facing this issue by last one month, can anyone please give a solution for this..

答:
(Reposting from https://github.com/google/google-api-dotnet-client/issues/888)

GoogleWebAuthorizationBroker is for use in an application that is running locally on an end-user machine. It opens a web browser locally allowing the user to authenticate.
It sounds like you are trying to use GoogleWebAuthorizationBroker on a server machine, from within IIS; where it won't work, as it will try to open a web browser on that server machine - this will fail, and wouldn't be visible to the end-user anyway as it'll be on the server machine, not their machine.

I've not done this myself, but it looks like the instructions here (for an ASP.NET MVC web app) might help.

Body:
I am using the following code to authenticate to Google using the Google .Net client library.

public static void auth()
{

string clientId = "xxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxx";

string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts.readonly" };     // view your basic profile info.
try
{
    // Use the current Google .net client library to get the Oauth2 stuff.
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "test"
                                                                                , CancellationToken.None
                                                                                , new FileDataStore("test")).Result;

    // Translate the Oauth permissions to something the old client libray can read
    OAuth2Parameters parameters = new OAuth2Parameters();
    parameters.AccessToken = credential.Token.AccessToken;
    parameters.RefreshToken = credential.Token.RefreshToken;
    RunContactsSample(parameters);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

I am using my own client id and client secret key.
This code is perfectly working when I am running from visual studio, but is not working from after hosted in IIS.

And I mentioned redirected URI in google api console is
http://localhost/authorize/

My IIS host Url is
http://localhost/googleintegration.aspx

I am facing this issue by last one month, can anyone please give a solution for this..


来源: stackexchange

问:
How to add class on hover using jquery
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

```<code><div class="flItems"><a class="category_filter" data-value="Fitted bed Sheet " href="http://192.168.1.156/eles/bed-linen/fitted-bed-sheet"> Fitted bed Sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Flat bed sheet " href="http://192.168.1.156/eles/bed-linen/flat-bed-sheet"> Flat bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Full bed sheets  " href="http://192.168.1.156/eles/bed-linen/full-bed-sheets"> Full bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twin bed sheet " href="http://192.168.1.156/eles/bed-linen/twin-bed-sheet"> Twin bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twinxl bed sheets  " href="http://192.168.1.156/eles/bed-linen/twinxl-bed-sheets"> Twinxl bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Queen bed sheet " href="http://192.168.1.156/eles/bed-linen/queen-bed-sheet"> Queen bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King bed sheets " href="http://192.168.1.156/eles/bed-linen/king-bed-sheets"> King bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Cal king bed sheets " href="http://192.168.1.156/eles/bed-linen/cal-king-bed-sheets"> Cal king bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Duvet covers " href="http://192.168.1.156/eles/bed-linen/duvet-covers"> Duvet covers  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Bed skirts " href="http://192.168.1.156/eles/bed-linen/bed-skirts"> Bed skirts  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Standard Pillow cases " href="http://192.168.1.156/eles/bed-linen/standard-pillow-cases"> Standard Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King Pillow cases " href="http://192.168.1.156/eles/bed-linen/king-pillow-cases"> King Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Pillow shells " href="http://192.168.1.156/eles/bed-linen/pillow-shells"> Pillow shells  </a> </div>
</code>```

Jquery Code,

```<code>$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});
</code>```

答: If you want to style links that have been visited differently, it's best to use the :visited pseudo class and avoid using javascript.  </p>

ContentLicense: CC BY-SA 3.0

Title: How to add class on hover using jquery

Body:
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells

Jquery Code,

$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});


问:
External VS2013 build error "error MSB4019: The imported project <path> was not found"
I am building a project through the command line and not inside Visual Studio 2013. Note, I had upgraded my project from Visual Studio 2012 to 2013. The project builds fine inside the IDE. Also, I completely uninstalled VS2012 first, rebooted, and installed VS2013. The only version of Visual Studio that I have is 2013 Ultimate.

```<code>ValidateProjects:
    39>path_to_project.csproj(245,3): error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
    39>Done Building Project "path_to_project.csproj" (Clean target(s)) -- FAILED.
</code>```

Here are the two lines in question:

```<code><Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
</code>```

The original second line was v10.0, but I manually changed that to v12.0.

$(VSToolsPath) elongates from what I see to the v11.0 (VS2012) folder, which obviously is not there anymore. The path should have been to v12.0.

```<code>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\WebApplications\
</code>```

I tried specifying VSToolsPath in my system environment variables table, but the external build utility still uses v11.0. I tried searching through the registry and that came up with nothing.

Sadly, I do not see any easy way to get the exact command line used. I use a build tool.

Thoughts?

答:
In my case i just comment below line by opening .csproj file and did the trick

.

My problem may be different but i am dragged here, but this may help someone.

I picked a single web project from my solution and try to open it as a stand alone project which was making issue, after above heck am able to solve issue.

Body:
I am building a project through the command line and not inside Visual Studio 2013. Note, I had upgraded my project from Visual Studio 2012 to 2013. The project builds fine inside the IDE. Also, I completely uninstalled VS2012 first, rebooted, and installed VS2013. The only version of Visual Studio that I have is 2013 Ultimate.

ValidateProjects:
    39>path_to_project.csproj(245,3): error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
    39>Done Building Project "path_to_project.csproj" (Clean target(s)) -- FAILED.

Here are the two lines in question:

<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

The original second line was v10.0, but I manually changed that to v12.0.

$(VSToolsPath) elongates from what I see to the v11.0 (VS2012) folder, which obviously is not there anymore. The path should have been to v12.0.

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\WebApplications\

I tried specifying VSToolsPath in my system environment variables table, but the external build utility still uses v11.0. I tried searching through the registry and that came up with nothing.

Sadly, I do not see any easy way to get the exact command line used. I use a build tool.

Thoughts?

Body:
In my case i just comment below line by opening .csproj file and did the trick

.<!-- <Import Project="..\PRPJECTNAME.targets" /> -->

My problem may be different but i am dragged here, but this may help someone.

I picked a single web project from my solution and try to open it as a stand alone project which was making issue, after above heck am able to solve issue.


问:
Laravel. Model Factory. Many-To-Many relation
I have problem with many-to-many relation on model factory.

For example:

There are users, roles and user_role tables.
I have defined model factories for user and roles. Next I try to add role to user:

```<code>$role = factory(Role::class)->create();
config(['admin_group_id' => $role->id]);
$admin = factory(User::class)->create();
$admin->roles()->save($role);
</code>```

It's work, but when I get $admin->roles()->first()->id it not equal $role->id

答: Instead of using save() you should be using attach() and pass in the id of the role

Body:
I have problem with many-to-many relation on model factory.

For example:

There are users, roles and user_role tables.
I have defined model factories for user and roles. Next I try to add role to user:

$role = factory(Role::class)->create();
config(['admin_group_id' => $role->id]);
$admin = factory(User::class)->create();
$admin->roles()->save($role);

It's work, but when I get $admin->roles()->first()->id it not equal $role->id


问:
Check for changes to a SQL Server database?
is there a way to get database checksum using system SQL Server functions?

Or other way to quickly figure out if there are any changes in database?

I do not want to use any specific database analysis software for this.

I look for any changes in database (schema/object changes, data changes).

I use SQL Server 2008.

答:
Changes in the form of updates to tables in the form of updates/insertions/deletions can be tracked by use of a trigger which would update the timestamp in a master table. We have to maintain a table containing the name of tables and last updated time. Any change in the individual table would update this table in the corresponding row!

Schema changes can also be handled by way of triggers which would update the table of tables. May be in you case, we can have additional column(s) with BOOL data type that would specify if the change was in schema or the data.

ContentLicense: CC BY-SA 2.5


问:
joining points with smooth curves in opengl
I have a list of points say

a, b, c and d

that I want to join like

a - b - c - d.

Right now I'm just taking two points at a time and drawing a line between them. But the result is sharp corners. So I thought of joining them with curves so that corners are smooth. I read about Bezier curves to draw curves but that requires additional control points to draw the curve. I also couldn't get how to join multiple points in a row using curves. Is there some way of doing that or something that can I can do or work on to make this possible?

I am using both opengl and SVG to output the result.

答:
Catmull-Rom splines are perhaps the easiest way to join up points with curves without needing additional control points (well you need a couple of extra points at the beginning and end, but you can trivially make those up like e=d+(d-c)). This looks like a good primer: https://www.mvps.org/directx/articles/catmull/

I find it can be difficult to get aesthetically pleasing curves when the points are very unevenly spaced though.


问:
AWS API Gateway Custom Authorizer based on User Groups
I'm attempting to design a system where users are created in my AWS user pool and assigned to one of four user groups. These user groups have roles attached to them which specify the API Calls they are allowed to make. I've created a user for each group and I'm able to successfully log into them in my Android Application. My User Pool is also attached to an Identity Pool for handling Single Sign On with Identity Federation.

The problem is that rather than assuming the Role assigned to the user group, when I log into the user, the role assigned to the user seems to be coming from the Identity Pool rather than their User Group, and as a result they're unable to make the api calls that they should have access to.

I'm attempting to fix this by implementing a Custom Authorizer in Node.js, but the script appears to be running into some problems. Whenever it enters the ValidateToken() method, it fails saying that the token isn't a JWT token.

```<code>console.log('Loading function');

var jwt = require('jsonwebtoken');
var request = require('request');
var jwkToPem = require('jwk-to-pem');

var groupName = 'MY_GROUP_NAME';
var roleName = 'MY_ROLE_NAME';
var policyName = 'MY_POLICY_NAME';
var userPoolId = 'MY_USER_POOL_ID';
var region = 'MY_REGION';
var iss = 'https://cognito-idp.' + region + '.amazonaws.com/' + userPoolId;
var pems;

exports.handler = function(event, context) {
//Download PEM for your UserPool if not already downloaded
if (!pems) {
//Download the JWKs and save it as PEM
request({
   url: iss + '/.well-known/jwks.json',
   json: true
 }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        pems = {};
        var keys = body['keys'];
        for(var i = 0; i < keys.length; i++) {
            //Convert each key to PEM
            var key_id = keys[i].kid;
            var modulus = keys[i].n;
            var exponent = keys[i].e;
            var key_type = keys[i].kty;
            var jwk = { kty: key_type, n: modulus, e: exponent};
            var pem = jwkToPem(jwk);
            pems[key_id] = pem;
        }
        //Now continue with validating the token
        ValidateToken(pems, event, context);
    } else {
        //Unable to download JWKs, fail the call
        context.fail("error");
    }
});
} else {
    //PEMs are already downloaded, continue with validating the token
    ValidateToken(pems, event, context);
};
};

function ValidateToken(pems, event, context) {

var token = event.authorizationToken;
//Fail if the token is not jwt
var decodedJwt = jwt.decode(token, {complete: true});
if (!decodedJwt) {
    //THIS IS WHERE THE SCRIPT ENDS UP
    console.log("Not a valid JWT token");
    context.fail("Unauthorized - Invalid Token Provided");
    return;
}

//Fail if token is not from your UserPool
if (decodedJwt.payload.iss != iss) {
    console.log("invalid issuer");
    context.fail("Unauthorized - Invalid Issuer Provided");
    return;
}

//Reject the jwt if it's not an 'Access Token'
if (decodedJwt.payload.token_use != 'access') {
    console.log("Not an access token");
    context.fail("Unauthorized - Not an Access Token");
    return;
}

//Get the kid from the token and retrieve corresponding PEM
var kid = decodedJwt.header.kid;
var pem = pems[kid];
if (!pem) {
    console.log('Invalid access token');
    context.fail("Unauthorized - Invalid Access Token Provided");
    return;
}

//Verify the signature of the JWT token to ensure it's really coming from your User Pool
jwt.verify(token, pem, { issuer: iss }, function(err, payload) {
  if(err) {
        console.log(err, err.stack); // an error occurred
        context.fail("Unauthorized - Could not verify token signature");
  }
  else {
    //Valid token. Generate the API Gateway policy for the user
    //Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable
    //sub is UUID for a user which is never reassigned to another user.
    var principalId = payload.sub;
    var username = payload.username;

    var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
    var params = {
        UserPoolId: userPoolId, /* ID of the Target User Pool */
        Username: username, /* Provided by event object??? */
        Limit: 0,
        NextToken: ''       //May need actual token value
    };

    cognitoidentityserviceprovider.adminListGroupsForUser(params, function(err, data) {
        if (err){
            console.log(err, err.stack); // an error occurred
            context.fail("Unauthorized - Could not obtain Groups for User");
        }
        else{
            var groups = data.Groups;
            var numGroups = groups.length;
            var isFound = false;
            for(var i = 0; i < numGroups; i++){
                if(groups[i].GroupName == groupName){
                    isFound = true;
                }
            }

            if(isFound){
                var iam = new AWS.IAM();
                var iamParams = {
                    PolicyName: policyName, /* Name of the Policy in the User Group Role */
                    RoleName: roleName /* Name of the User Group Role */
                };

                iam.getRolePolicy(params, function(err, data) {
                    if (err){
                        console.log(err, err.stack); // an error occurred
                        context.fail("Unauthorized - Could not acquire Policy for User Group Role");
                    }
                    else {
                        var policy = data.PolicyDocument;
                        context.succeed(policy);        //May need to build policy
                    }
                });
            }
            else{
                context.fail("Unauthorized - Could not find the required User Group under the User");
            }
        }
    });
  }
});
}
</code>```

Can anybody identify the problem with this script, or perhaps help me identify why the tokens being set aren't valid JWT tokens? The tokens are sent by an Android Application using the AWS Cognito SDK.

EDIT: Upon further investigation, the token retrieved from event.authorizationToken is of the following format (the [VALUE] blocks are to hide potentially sensitive information):

```<code>AWS4-HMAC-SHA256 Credential=[VALUE1]/20170329/us-east-1/execute-api/aws4_request,
SignedHeaders=host;x-amz-date;x-amz-security-token,
Signature=[VALUE2]
</code>```

答:
I figured it out:
This document (specifically the bottom part) says "If you set roles for groups in an Amazon Cognito user pool, those roles are passed through the user's ID token. To use these roles, you must also set Choose role from token for the authenticated role selection for the identity pool."

All it takes is to set the appropriate Trust Policy on each role, adjust the Identity Pool to use "Choose role from token" with the user pool authentication provider, and the proper roles are now being assumed. For others running into this problem, here is my trust policy:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "[IDENTITY_POOL_ID]"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "authenticated"
        }
      }
    }
  ]
}
</code>```

Body:
I'm attempting to design a system where users are created in my AWS user pool and assigned to one of four user groups. These user groups have roles attached to them which specify the API Calls they are allowed to make. I've created a user for each group and I'm able to successfully log into them in my Android Application. My User Pool is also attached to an Identity Pool for handling Single Sign On with Identity Federation.

The problem is that rather than assuming the Role assigned to the user group, when I log into the user, the role assigned to the user seems to be coming from the Identity Pool rather than their User Group, and as a result they're unable to make the api calls that they should have access to.

I'm attempting to fix this by implementing a Custom Authorizer in Node.js, but the script appears to be running into some problems. Whenever it enters the ValidateToken() method, it fails saying that the token isn't a JWT token.

console.log('Loading function');

var jwt = require('jsonwebtoken');
var request = require('request');
var jwkToPem = require('jwk-to-pem');

var groupName = 'MY_GROUP_NAME';
var roleName = 'MY_ROLE_NAME';
var policyName = 'MY_POLICY_NAME';
var userPoolId = 'MY_USER_POOL_ID';
var region = 'MY_REGION';
var iss = 'https://cognito-idp.' + region + '.amazonaws.com/' + userPoolId;
var pems;

exports.handler = function(event, context) {
//Download PEM for your UserPool if not already downloaded
if (!pems) {
//Download the JWKs and save it as PEM
request({
   url: iss + '/.well-known/jwks.json',
   json: true
 }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        pems = {};
        var keys = body['keys'];
        for(var i = 0; i < keys.length; i++) {
            //Convert each key to PEM
            var key_id = keys[i].kid;
            var modulus = keys[i].n;
            var exponent = keys[i].e;
            var key_type = keys[i].kty;
            var jwk = { kty: key_type, n: modulus, e: exponent};
            var pem = jwkToPem(jwk);
            pems[key_id] = pem;
        }
        //Now continue with validating the token
        ValidateToken(pems, event, context);
    } else {
        //Unable to download JWKs, fail the call
        context.fail("error");
    }
});
} else {
    //PEMs are already downloaded, continue with validating the token
    ValidateToken(pems, event, context);
};
};

function ValidateToken(pems, event, context) {

var token = event.authorizationToken;
//Fail if the token is not jwt
var decodedJwt = jwt.decode(token, {complete: true});
if (!decodedJwt) {
    //THIS IS WHERE THE SCRIPT ENDS UP
    console.log("Not a valid JWT token");
    context.fail("Unauthorized - Invalid Token Provided");
    return;
}

//Fail if token is not from your UserPool
if (decodedJwt.payload.iss != iss) {
    console.log("invalid issuer");
    context.fail("Unauthorized - Invalid Issuer Provided");
    return;
}

//Reject the jwt if it's not an 'Access Token'
if (decodedJwt.payload.token_use != 'access') {
    console.log("Not an access token");
    context.fail("Unauthorized - Not an Access Token");
    return;
}

//Get the kid from the token and retrieve corresponding PEM
var kid = decodedJwt.header.kid;
var pem = pems[kid];
if (!pem) {
    console.log('Invalid access token');
    context.fail("Unauthorized - Invalid Access Token Provided");
    return;
}

//Verify the signature of the JWT token to ensure it's really coming from your User Pool
jwt.verify(token, pem, { issuer: iss }, function(err, payload) {
  if(err) {
        console.log(err, err.stack); // an error occurred
        context.fail("Unauthorized - Could not verify token signature");
  }
  else {
    //Valid token. Generate the API Gateway policy for the user
    //Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable
    //sub is UUID for a user which is never reassigned to another user.
    var principalId = payload.sub;
    var username = payload.username;

    var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
    var params = {
        UserPoolId: userPoolId, /* ID of the Target User Pool */
        Username: username, /* Provided by event object??? */
        Limit: 0,
        NextToken: ''       //May need actual token value
    };

    cognitoidentityserviceprovider.adminListGroupsForUser(params, function(err, data) {
        if (err){
            console.log(err, err.stack); // an error occurred
            context.fail("Unauthorized - Could not obtain Groups for User");
        }
        else{
            var groups = data.Groups;
            var numGroups = groups.length;
            var isFound = false;
            for(var i = 0; i < numGroups; i++){
                if(groups[i].GroupName == groupName){
                    isFound = true;
                }
            }

            if(isFound){
                var iam = new AWS.IAM();
                var iamParams = {
                    PolicyName: policyName, /* Name of the Policy in the User Group Role */
                    RoleName: roleName /* Name of the User Group Role */
                };

                iam.getRolePolicy(params, function(err, data) {
                    if (err){
                        console.log(err, err.stack); // an error occurred
                        context.fail("Unauthorized - Could not acquire Policy for User Group Role");
                    }
                    else {
                        var policy = data.PolicyDocument;
                        context.succeed(policy);        //May need to build policy
                    }
                });
            }
            else{
                context.fail("Unauthorized - Could not find the required User Group under the User");
            }
        }
    });
  }
});
}

Can anybody identify the problem with this script, or perhaps help me identify why the tokens being set aren't valid JWT tokens? The tokens are sent by an Android Application using the AWS Cognito SDK.

EDIT: Upon further investigation, the token retrieved from event.authorizationToken is of the following format (the [VALUE] blocks are to hide potentially sensitive information):

AWS4-HMAC-SHA256 Credential=[VALUE1]/20170329/us-east-1/execute-api/aws4_request,
SignedHeaders=host;x-amz-date;x-amz-security-token,
Signature=[VALUE2]

Body:
I figured it out:
This document (specifically the bottom part) says "If you set roles for groups in an Amazon Cognito user pool, those roles are passed through the user's ID token. To use these roles, you must also set Choose role from token for the authenticated role selection for the identity pool."

All it takes is to set the appropriate Trust Policy on each role, adjust the Identity Pool to use "Choose role from token" with the user pool authentication provider, and the proper roles are now being assumed. For others running into this problem, here is my trust policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "[IDENTITY_POOL_ID]"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "authenticated"
        }
      }
    }
  ]
}


问:
C# Configuration Manager- Format string on one line after Save
I am using ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); to open a configuration file, and then eventually calling Save() on that config to update the config.  The saving portion is working fine, but the resulting format is different than what the input was.

Is there a way to keep the formatting the same when calling Configuration.Save()?

In the code below, I essentialy want the "After" block to look like the "Before" block after I call Save() and update the value I need.

Before

```<code><items>
    <item domainName="DEV" url="http:/server1:8080" certificatePath="./cert1.cert" password="abc"/>
    <item domainName="QA" url="http://server2:8080" certificatePath="./cert2.cert" password="123"/>
    <item domainName="PROD" url="http://server3:8080" certificatePath="./cert3.cert" password="frt"/>
</items>
</code>```

After

```<code><items>
    <item domainName="DEV" url="http:/server1:8080"
        certificatePath="./cert1.cert" password="abc"/>
    <item domainName="QA" url="http://server2:8080"
        certificatePath="./cert2.cert" password="123"/>
    <item domainName="PROD" url="http://server3:8080"
        certificatePath="./cert3.cert" password="UpdatedProperty"/>
</items>
</code>```

答:
You can't control the formatting using the ConfigurationManager class. According to this StackOverflow question, the class simply does not look for things like whitespace or comments when it parses the document. Likewise, the class is sealed so you can't derive your own solution to the problem.

You could parse it with XDocument or XmlDocument to find the keys you need to update and save them while preserving the whitespace. Obviously not ideal but at the moment it seems like that is the only option.

Body:
I am using ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); to open a configuration file, and then eventually calling Save() on that config to update the config.  The saving portion is working fine, but the resulting format is different than what the input was.

Is there a way to keep the formatting the same when calling Configuration.Save()?

In the code below, I essentialy want the "After" block to look like the "Before" block after I call Save() and update the value I need.

Before

<items>
    <item domainName="DEV" url="http:/server1:8080" certificatePath="./cert1.cert" password="abc"/>
    <item domainName="QA" url="http://server2:8080" certificatePath="./cert2.cert" password="123"/>
    <item domainName="PROD" url="http://server3:8080" certificatePath="./cert3.cert" password="frt"/>
</items>

After

<items>
    <item domainName="DEV" url="http:/server1:8080"
        certificatePath="./cert1.cert" password="abc"/>
    <item domainName="QA" url="http://server2:8080"
        certificatePath="./cert2.cert" password="123"/>
    <item domainName="PROD" url="http://server3:8080"
        certificatePath="./cert3.cert" password="UpdatedProperty"/>
</items>


问:
Jackson read value as string
I have an object with unknown values, say

```<code>{
 "data": [
    {"a":...,
    "dont_know_what_else_is_here":....}
 ]
}
</code>```

And I just want to store the value of "data" as a string into a variable/database.

How should I read it from the streaming API?

答:
Assuming you've got a parser already and it points to "data" token (e.g. from custom deserializer) you can do the following:

```<code>ObjectMapper mapper = new ObjectMapper();
JsonNode treeNode = mapper.readTree(parser);
return treeNode.toString();
</code>```

This will get you String containing the value of the "data".

Title: Jackson read value as string

Body:
I have an object with unknown values, say

{
 "data": [
    {"a":...,
    "dont_know_what_else_is_here":....}
 ]
}

And I just want to store the value of "data" as a string into a variable/database.

How should I read it from the streaming API?

Body:
Assuming you've got a parser already and it points to "data" token (e.g. from custom deserializer) you can do the following:

ObjectMapper mapper = new ObjectMapper();
JsonNode treeNode = mapper.readTree(parser);
return treeNode.toString();

This will get you String containing the value of the "data".


问:
Deleting an object declared on the stack
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

```<code>#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}
</code>```

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??

答:
There are three reasons:

The destructor does not deallocate the object, it performs whatever cleanup operation you find useful (and by default, nothing). It is implicitly called before a variable goes out of scope or is explicitly deleted, but you are free to call it as well.

Deallocation usually does not cause memory to cease existing nor to be inaccessible. It is rather marked as reusable. (Anyway, double deallocation should raise a memory management error condition.)

Last but not least, an object allocated on the stack is not deallocated (when you exit the function, the stack pointer moves to the previous frame, leaving the stack unchanged).

Body:
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??


问:
Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single line
Let me give a python analogy of what I am looking for:

```<code>fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)
</code>```

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

```<code>var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);
</code>```

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

答:
There's really nothing wrong with the code you have, but it would be slightly more terse to write

```<code>num_oranges = ("orange" in fruits_obj) && fruits_obj.orange || null;
</code>```

This would also find a property called "orange" in the object's prototype chain, if that's important (probably not). Also, note that

```<code>num_oranges = fruits_obj.orange;
</code>```

will assign undefined to num_oranges if there's no "oranges" property, and for many practical purposes undefined and null are interchangeable. (For example, undefined == null is true.)

Body:
Let me give a python analogy of what I am looking for:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

Body:
There's really nothing wrong with the code you have, but it would be slightly more terse to write

num_oranges = ("orange" in fruits_obj) && fruits_obj.orange || null;

This would also find a property called "orange" in the object's prototype chain, if that's important (probably not). Also, note that

num_oranges = fruits_obj.orange;

will assign undefined to num_oranges if there's no "oranges" property, and for many practical purposes undefined and null are interchangeable. (For example, undefined == null is true.)


问:
Issue with MYSQL lc_time_names
I want to the retrieve the time as '3:30 م' instead of '3:30 PM' from Mysql (like CultureInfo in .NET)

By setting the lc_time_names = 'ar_EG' it still the same.

Here what i did

```<code>SET lc_time_names = 'ar_EG';
SELECT TIME_FORMAT(NOW(),'%h:%i %p') AS 'Time';
</code>```

https://dev.mysql.com/doc/refman/5.7/en/locale-support.html

I don't know why 0 rows is affected ? Any help is highly appreciated.

答: Zero rows effected means zero database rows effected.  You have not changed the data.  The set commands is setting a variable but not changing table data.</p>

Title: Issue with MYSQL lc_time_names

Body:
I want to the retrieve the time as '3:30 م' instead of '3:30 PM' from Mysql (like CultureInfo in .NET)

By setting the lc_time_names = 'ar_EG' it still the same.

Here what i did

SET lc_time_names = 'ar_EG';
SELECT TIME_FORMAT(NOW(),'%h:%i %p') AS 'Time';

https://dev.mysql.com/doc/refman/5.7/en/locale-support.html

I don't know why 0 rows is affected ? Any help is highly appreciated.


问:
Why doesn't logcat show anything in my Android?
Why doesn't logcat show anything in my Android (while developing apps with Eclipse)?

It just doesn't print anything. It's empty.

答:
Maybe the log is not enabled in your device.
Try to run the following command.</p>

```<code>adb shell
echo 1 > /sys/kernel/logger/log_main/enable
</code>```

Body:
Maybe the log is not enabled in your device.
Try to run the following command.

adb shell
echo 1 > /sys/kernel/logger/log_main/enable


问:
Map mixed arrays of elements from XML to a model
I have an XML element that has lists of 2 types of child elements that are mixed. This precludes me from using lists directly.

For example, let's say I have XML like this:

```<code><country>
    <city>...</city>
    <village>...</village>
    <village>...</village>
    <city>...</city>
    <village>...</village>
</country>
</code>```

Instead of this:

```<code><country>
    <cities>
        <city>...</city>
        <city>...</city>
    </cities>
    <villages>
        <village>...</village>
        <village>...</village>
        <village>...</village>
    </villages>
</country>
</code>```

And I want to map it to this model:

```<code>public class Country
{
    public List<string> Cities { get; set; }
    public List<string> Villages { get; set; }
}
</code>```

This would be easy with the second example but how do I do it for the first?

答:
I don't think you can without implementing IXmlSerializable manually. If you have to keep the XML in that form, then the model would need to look something like this:

```<code>[XmlRoot("country")]
public class Country
{
    [XmlElement("city", typeof(City))]
    [XmlElement("village", typeof(Village))]
    public List<object> CitiesAndVillages { get; set; }
}

public class City
{
    [XmlText]
    public string Value { get; set; }
}

public class Village
{
    [XmlText]
    public string Value { get; set; }
}
</code>```

See this fiddle for a demo. Note you could also use a single List<string> with an associated choice identifier, but I I usually prefer this sort of approach.

One further tip for this sort of problem is to copy your XML to the clipboard and use Edit |> Paste Special |> Paste XML As Classes in Visual Studio. This magically generates some classes that will deserialise the given XML.

Body:
I have an XML element that has lists of 2 types of child elements that are mixed. This precludes me from using lists directly.

For example, let's say I have XML like this:

<country>
    <city>...</city>
    <village>...</village>
    <village>...</village>
    <city>...</city>
    <village>...</village>
</country>

Instead of this:

<country>
    <cities>
        <city>...</city>
        <city>...</city>
    </cities>
    <villages>
        <village>...</village>
        <village>...</village>
        <village>...</village>
    </villages>
</country>

And I want to map it to this model:

public class Country
{
    public List<string> Cities { get; set; }
    public List<string> Villages { get; set; }
}

This would be easy with the second example but how do I do it for the first?

Body:
I don't think you can without implementing IXmlSerializable manually. If you have to keep the XML in that form, then the model would need to look something like this:

[XmlRoot("country")]
public class Country
{
    [XmlElement("city", typeof(City))]
    [XmlElement("village", typeof(Village))]
    public List<object> CitiesAndVillages { get; set; }
}

public class City
{
    [XmlText]
    public string Value { get; set; }
}

public class Village
{
    [XmlText]
    public string Value { get; set; }
}

See this fiddle for a demo. Note you could also use a single List<string> with an associated choice identifier, but I I usually prefer this sort of approach.

One further tip for this sort of problem is to copy your XML to the clipboard and use Edit |> Paste Special |> Paste XML As Classes in Visual Studio. This magically generates some classes that will deserialise the given XML.


问:
Can I set Neo4j on Docker to import CSV file on the first run, not after that?
Is there a way to set docker to make neo4j import specific CSV file import only once?

or I should do that with javascript to check if neo4j is empty then load?

Of course, doing with javascript is easy. Just wondering can I do it with docker?

答:
The neo4j import tool (http://neo4j.com/docs/operations-manual/current/tutorial/import-tool/) runs independently of neo4j.

Load data when building image

You could inherit from the neo4j base image and use RUN /path/to/neo4j-import ... to load your data upon image creation.

This will of course load data only once.

Load data when running container

To load data when you run the container you have to override the script executed to run start neo4j. See docker_entrypoint.sh here https://github.com/neo4j/docker-neo4j/tree/master/src/3.1

The import tool works only if the database does not exist. You could maybe catch the error when it tries to load data into an existing database to have it run only once.


问:
didSelectItemAt not working from SCLAlertView
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

```<code>    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}
</code>```

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

答:
First of all you need to update like:

```<code>class YourViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
}
</code>```

And then in viewDidLoad:

```<code>collectionView.delegate = self
collectionView.dataSource = self
collectionView.reloadData()
</code>```

And make sure that your objects are properly connected.

Body:
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

Body:
First of all you need to update like:

class YourViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
}

And then in viewDidLoad:

collectionView.delegate = self
collectionView.dataSource = self
collectionView.reloadData()

And make sure that your objects are properly connected.


问:
Infinite $digest() loop AngularJS with filter expression on html attribute
When I try to pass a filter expression inside a component's attribute, e.g. (see this Plunker example as well, and the possible solutions listed below).

```<code><todo-list todos="$ctrl.todos | filter:{type:1}"></todo-list>
</code>```

I get an error on the infinite digest loop, I don't understand why:

```<code>Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…e%2C%22type%22%3A1%2C%22%24%24hashKey%22%3A%22object%3A5%22%7D%5D%7D%5D%5D
    at eval (angular.js:38)
    at m.$digest (angular.js:18048)
    at m.$apply (angular.js:18280)
    at eval (angular.js:1912)
    at Object.invoke (angular.js:5003)
    at c (angular.js:1910)
    at Object.Pc [as bootstrap] (angular.js:1930)
    at execute (VM877 main.ts!transpiled:21)
    at f (system.js:5)
    at Object.execute (system.js:5)
</code>```

Code, see Plnkr: http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

Screenshot / Image:

Workaround/solution:
I have several workarounds/solutions:

In the repo where I had the problem at first: I did <todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list>. For full source see here: https://github.com/aredfox/todo-angularjs-typescript/commit/e71900b96173b63ebcebb8e6c1fba00fe3997971. But I feel it's working around the problem, plus I don't understand why this triggers a $digest() cycle and why it shouldn't just work.

Answer by @Mistalis https://stackoverflow.com/a/43120388/1155847 whogave a somehwat similar solution.

答:
The goal of filter is to get an array as input and return another
array based on some rules and conditions, where array items have the
same structure as input.

The reason that causes an infinite loop in the $digest cycle is that
in a filter, each digest cycle filter returns a different object that
causes an additional cycle. - Source

I would suggest you to move the filter to the todoList directive:

```<code><div ng-repeat="todo in $ctrl.todos | filter: {type:1}">
    <span>{{todo.name}}</span>
</div>
</code>```

If type needs to be dynamic, pass it as a parameter/attribute to the directive.

Forked your Plunker

Body:
When I try to pass a filter expression inside a component's attribute, e.g. (see this Plunker example as well, and the possible solutions listed below).

<todo-list todos="$ctrl.todos | filter:{type:1}"></todo-list>

I get an error on the infinite digest loop, I don't understand why:

Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…e%2C%22type%22%3A1%2C%22%24%24hashKey%22%3A%22object%3A5%22%7D%5D%7D%5D%5D
    at eval (angular.js:38)
    at m.$digest (angular.js:18048)
    at m.$apply (angular.js:18280)
    at eval (angular.js:1912)
    at Object.invoke (angular.js:5003)
    at c (angular.js:1910)
    at Object.Pc [as bootstrap] (angular.js:1930)
    at execute (VM877 main.ts!transpiled:21)
    at f (system.js:5)
    at Object.execute (system.js:5)

Code, see Plnkr: http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

Screenshot / Image:

Workaround/solution:
I have several workarounds/solutions:

In the repo where I had the problem at first: I did <todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list>. For full source see here: https://github.com/aredfox/todo-angularjs-typescript/commit/e71900b96173b63ebcebb8e6c1fba00fe3997971. But I feel it's working around the problem, plus I don't understand why this triggers a $digest() cycle and why it shouldn't just work.

Answer by @Mistalis https://stackoverflow.com/a/43120388/1155847 whogave a somehwat similar solution.

Body:
The goal of filter is to get an array as input and return another
array based on some rules and conditions, where array items have the
same structure as input.

The reason that causes an infinite loop in the $digest cycle is that
in a filter, each digest cycle filter returns a different object that
causes an additional cycle. - Source

I would suggest you to move the filter to the todoList directive:

<div ng-repeat="todo in $ctrl.todos | filter: {type:1}">
    <span>{{todo.name}}</span>
</div>

If type needs to be dynamic, pass it as a parameter/attribute to the directive.

Forked your Plunker


问:
Kafka Consumer default Group Id
I'm working with Apache Kafka and its Java client and I see that messages are load balanced across different Kafka Consumers belonging to the same group (i.e. sharing the same group id).

In my application I need all consumers to read all messages.

So I have several questions:

if I don't set any group id in the Consumer Properties, what group id will the Kafka Consumer be given?

Is there a single default value?

Does the client create a random value each time?

Do I need to create a different id for each consumer to be sure that each one receives all messages?

EDIT:
Thank you for your answers.

You are correct: if one doesn't set the consumer group id, Kafka should complain.

However, I have found out that if the group id is null, the Java client sets it to the empty string "" to avoid problems.
So apparently that is the default value I was looking for.

Surprising all my consumers, even if I don't set their groupIds (and so they are all with groupId == "") seem to receive all the messages the producer writes.

I still can't explain this: any suggestions?

答:
If don't set group.id,you will get error when consume topic data.</p>

```<code>org.apache.kafka.common.errors.InvalidGroupIdException: The configured groupId is invalid
22:08:14.132 [testAuto-kafka-consumer-1] INFO org.apache.kafka.clients.consumer.internals.AbstractCoordinator - (Re-)joining group
22:08:14.132 [testAuto-kafka-consumer-1] DEBUG org.apache.kafka.clients.consumer.internals.AbstractCoordinator - Sending JoinGroup ({group_id=,session_timeout=15000,rebalance_timeout=300000,member_id=,protocol_type=consumer,group_protocols=[{protocol_name=range,protocol_metadata=java.nio.HeapByteBuffer[pos=0 lim=18 cap=18]}]}) to coordinator bogon:9092 (id: 2147483647 rack: null)
22:08:14.132 [testAuto-kafka-consumer-1] ERROR org.apache.kafka.clients.consumer.internals.AbstractCoordinator - Attempt to join group  failed due to fatal error: The configured groupId is invalid
22:08:14.132 [testAuto-kafka-consumer-1] ERROR org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer - Container exception
</code>```

Title: Kafka Consumer default Group Id

Body:
If don't set group.id,you will get error when consume topic data.

org.apache.kafka.common.errors.InvalidGroupIdException: The configured groupId is invalid
22:08:14.132 [testAuto-kafka-consumer-1] INFO org.apache.kafka.clients.consumer.internals.AbstractCoordinator - (Re-)joining group
22:08:14.132 [testAuto-kafka-consumer-1] DEBUG org.apache.kafka.clients.consumer.internals.AbstractCoordinator - Sending JoinGroup ({group_id=,session_timeout=15000,rebalance_timeout=300000,member_id=,protocol_type=consumer,group_protocols=[{protocol_name=range,protocol_metadata=java.nio.HeapByteBuffer[pos=0 lim=18 cap=18]}]}) to coordinator bogon:9092 (id: 2147483647 rack: null)
22:08:14.132 [testAuto-kafka-consumer-1] ERROR org.apache.kafka.clients.consumer.internals.AbstractCoordinator - Attempt to join group  failed due to fatal error: The configured groupId is invalid
22:08:14.132 [testAuto-kafka-consumer-1] ERROR org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer - Container exception


问:
Selecting by details with MySQL, after join
First I'll introduce what I'm trying to achieve and how I'm doing it.

I have three tables, Posts, Details, and Posts_Details.

Posts is the table where I keep the basic post data, Details is keeping the detail instances, with information about the title of the detail, possible values and some information if the detail is required for input, display flags etc. Posts_Details is the entity that represents the M->N relation which keeps one value of the detail, so it has three attributes, the id pairs of the post and detail and a value.

What I'm trying to setup is, a search functionality.

The first part of the search is simple, I use Posts.title LIKE '%?%' and the client is happy with the way it functions, I know its limitations, but this is really basic search functionality for now. The next feature is what brings me the troubles, as I don't feel like I know how to form the relation properly and I'm already behind the schedule to stop working and read up on relations.

I need to create a feature like "advanced search" where the user could not only pick the category and title keyword, but also match the details with drop-down inputs. I'm working with PHP and PDO, but I don't think that's too much relevant here as my problem is more SQL-related.

How I tried to solve this - I'm parsing the get data and collecting it in an associative array with details id as keys and the values as value, so I thought to iterate over the array and append the rules in the WHERE part of the SQL string. I kind of get some result with this approach after I parse the mashed columns, but it doesn't feel right, I feel like I'm doing just a hack-around.

Is there a "righter" way to implement this kind of search by details where I'll make a rule for selecting posts with values from the list of details after the three tables are joined?

答:
You can use a subselect.</p>

```<code>SELECT p.*, d.* FROM ... -- Existing Join
WHERE ... -- Existing Criteria
OR p.id IN (SELECT posts_id FROM Posts_Details WHERE detail like ?)
</code>```

Body:
You can use a subselect.

SELECT p.*, d.* FROM ... -- Existing Join
WHERE ... -- Existing Criteria
OR p.id IN (SELECT posts_id FROM Posts_Details WHERE detail like ?)


问:
Copy contents of one List into another List (not reference)
I have two List :

```<code>List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();
</code>```

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

答:
Just use the constructor public ArrayList(Collection  c) to construct your second list by passing the first. It initializes your list with all the items in your first list in the order given by your iterator.

You can use Reflection to deep copy all the elements of one list to another. See the example code below which can be extended to cover your needs, more (deeper) cases etc.

```<code>import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {

        List<Object> listA = new ArrayList<>();

        listA.add(false);
        listA.add(123);
        listA.add("test");
        listA.add(new Foo(1, "foo", 7, new Bar(2)));

        System.out.println("==ListA==");
        listA.forEach(x -> System.out.println(x));

        List<Object> listB = new ArrayList<>(listA.size());

        for (Object obj : listA) {
            try {
                Object o = null;
                if (isPrimitiveWrapperClassOrString(obj.getClass())) {
                    o = newInstance(obj);
                } else {
                    o = obj.getClass().newInstance();
                    copyValues(obj, o);
                }
                listB.add(o);
            } catch (NoSuchMethodException e) {
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        System.out.println("\n==ListB==");
        listB.forEach(x -> System.out.println(x));

        // Modify listB
        listB.set(0, true);
        listB.set(1, 456);
        ((Foo)listB.get(3)).setId(2);
        ((Bar)((Foo)listB.get(3)).getBar()).setId(9);

        System.out.println("\n==ListA after modifying listB==");
        listA.forEach(x -> System.out.println(x));

        System.out.println("\n==ListB==");
        listB.forEach(x -> System.out.println(x));
    }

    private static Object newInstance(Object obj) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class classType = obj.getClass();
        Object o = null;

        if (classType == Boolean.class) {
            Method method = classType.getDeclaredMethod("booleanValue", null);
            boolean value = (boolean) method.invoke(obj, null);
            o = classType.getConstructor(boolean.class).newInstance(value);
        } else if (classType == Byte.class) {
            Method method = classType.getDeclaredMethod("byteValue", null);
            byte value = (byte) method.invoke(obj, null);
            o = classType.getConstructor(byte.class).newInstance(value);
        } else if (classType == Short.class) {
            Method method = classType.getDeclaredMethod("shortValue", null);
            short value = (short) method.invoke(obj, null);
            o = classType.getConstructor(short.class).newInstance(value);
        } else if (classType == Integer.class) {
            Method method = classType.getDeclaredMethod("intValue", null);
            int value = (int) method.invoke(obj, null);
            o = classType.getConstructor(int.class).newInstance(value);
        } else if (classType == Long.class) {
            Method method = classType.getDeclaredMethod("longValue", null);
            long value = (long) method.invoke(obj, null);
            o = classType.getConstructor(long.class).newInstance(value);
        } else if (classType == Float.class) {
            Method method = classType.getDeclaredMethod("floatValue", null);
            float value = (float) method.invoke(obj, null);
            o = classType.getConstructor(float.class).newInstance(value);
        } else if (classType == Double.class) {
            Method method = classType.getDeclaredMethod("doubleValue", null);
            double value = (double) method.invoke(obj, null);
            o = classType.getConstructor(double.class).newInstance(value);
        } else if (classType == Character.class) {
            Method method = classType.getDeclaredMethod("charValue", null);
            char value = (char) method.invoke(obj, null);
            o = classType.getConstructor(char.class).newInstance(value);
        } else if (classType == String.class) {
            Method method = classType.getDeclaredMethod("toString", null);
            String value = (String) method.invoke(obj, null);
            o = classType.getConstructor(String.class).newInstance(value);
        }

        return o;
    }

    private static void copyValues(Object objF, Object objT) throws IllegalAccessException, InstantiationException {
        Class classType = objF.getClass();
        for (Field field : classType.getDeclaredFields()) {
            field.setAccessible(true);
            Class fieldType = field.getType();
            if (isPrimitiveWrapperClassOrString(fieldType)) {
                field.set(objT, field.get(objF));
            } else {
                Object objN = field.get(objT);
                if (Objects.isNull(objN)) objN = field.getType().newInstance();
                copyValues(field.get(objF), objN);
                field.set(objT, objN);
            }
        }
    }

    private static boolean isPrimitiveWrapperClassOrString(Class classType) {
        return classType == Boolean.class || classType == boolean.class ||
                classType == Byte.class || classType == byte.class ||
                classType == Short.class || classType == short.class ||
                classType == Integer.class || classType == int.class ||
                classType == Long.class || classType == long.class ||
                classType == Float.class || classType == float.class ||
                classType == Double.class || classType == double.class ||
                classType == Character.class || classType == char.class ||
                classType == String.class;
    }
}

class Foo {
    private int id;
    private String label;
    private Integer stock;
    private Bar bar;

    public Foo() { }
    public Foo(int id, String label, Integer stock, Bar bar) {
        this.id = id;
        this.label = label;
        this.stock = stock;
        this.bar = bar;
    }

    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }
    public String getLabel() { return this.label; }
    public void setLabel() { this.label = label; }
    public Integer getStock() { return this.stock; }
    public void setStock(Integer stock) { this.stock = stock; }
    public Bar getBar() { return this.bar; }
    public void setBar(Bar bar) { this.bar = bar; }

    @Override
    public String toString() {
        return String.format("%s | %d | %d | %s", this.label, this.id, this.stock, this.bar);
    }
}

class Bar {
    private int id;

    public Bar() {}
    public Bar(int id) { this.id = id; }

    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }

    @Override
    public String toString() { return "Bar: " + this.id; }
}
</code>```

Which outputs

```<code>==ListA==
false
123
test
foo | 1 | 7 | Bar: 2

==ListB==
false
123
test
foo | 1 | 7 | Bar: 2

==ListA after modifying listB==
false
123
test
foo | 1 | 7 | Bar: 2

==ListB==
true
456
test
foo | 2 | 7 | Bar: 9
</code>```

Body:
I have two List :

List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

Body:
Just use the constructor public ArrayList(Collection  c) to construct your second list by passing the first. It initializes your list with all the items in your first list in the order given by your iterator.

You can use Reflection to deep copy all the elements of one list to another. See the example code below which can be extended to cover your needs, more (deeper) cases etc.

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {

        List<Object> listA = new ArrayList<>();

        listA.add(false);
        listA.add(123);
        listA.add("test");
        listA.add(new Foo(1, "foo", 7, new Bar(2)));

        System.out.println("==ListA==");
        listA.forEach(x -> System.out.println(x));

        List<Object> listB = new ArrayList<>(listA.size());

        for (Object obj : listA) {
            try {
                Object o = null;
                if (isPrimitiveWrapperClassOrString(obj.getClass())) {
                    o = newInstance(obj);
                } else {
                    o = obj.getClass().newInstance();
                    copyValues(obj, o);
                }
                listB.add(o);
            } catch (NoSuchMethodException e) {
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        System.out.println("\n==ListB==");
        listB.forEach(x -> System.out.println(x));

        // Modify listB
        listB.set(0, true);
        listB.set(1, 456);
        ((Foo)listB.get(3)).setId(2);
        ((Bar)((Foo)listB.get(3)).getBar()).setId(9);

        System.out.println("\n==ListA after modifying listB==");
        listA.forEach(x -> System.out.println(x));

        System.out.println("\n==ListB==");
        listB.forEach(x -> System.out.println(x));
    }

    private static Object newInstance(Object obj) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class classType = obj.getClass();
        Object o = null;

        if (classType == Boolean.class) {
            Method method = classType.getDeclaredMethod("booleanValue", null);
            boolean value = (boolean) method.invoke(obj, null);
            o = classType.getConstructor(boolean.class).newInstance(value);
        } else if (classType == Byte.class) {
            Method method = classType.getDeclaredMethod("byteValue", null);
            byte value = (byte) method.invoke(obj, null);
            o = classType.getConstructor(byte.class).newInstance(value);
        } else if (classType == Short.class) {
            Method method = classType.getDeclaredMethod("shortValue", null);
            short value = (short) method.invoke(obj, null);
            o = classType.getConstructor(short.class).newInstance(value);
        } else if (classType == Integer.class) {
            Method method = classType.getDeclaredMethod("intValue", null);
            int value = (int) method.invoke(obj, null);
            o = classType.getConstructor(int.class).newInstance(value);
        } else if (classType == Long.class) {
            Method method = classType.getDeclaredMethod("longValue", null);
            long value = (long) method.invoke(obj, null);
            o = classType.getConstructor(long.class).newInstance(value);
        } else if (classType == Float.class) {
            Method method = classType.getDeclaredMethod("floatValue", null);
            float value = (float) method.invoke(obj, null);
            o = classType.getConstructor(float.class).newInstance(value);
        } else if (classType == Double.class) {
            Method method = classType.getDeclaredMethod("doubleValue", null);
            double value = (double) method.invoke(obj, null);
            o = classType.getConstructor(double.class).newInstance(value);
        } else if (classType == Character.class) {
            Method method = classType.getDeclaredMethod("charValue", null);
            char value = (char) method.invoke(obj, null);
            o = classType.getConstructor(char.class).newInstance(value);
        } else if (classType == String.class) {
            Method method = classType.getDeclaredMethod("toString", null);
            String value = (String) method.invoke(obj, null);
            o = classType.getConstructor(String.class).newInstance(value);
        }

        return o;
    }

    private static void copyValues(Object objF, Object objT) throws IllegalAccessException, InstantiationException {
        Class classType = objF.getClass();
        for (Field field : classType.getDeclaredFields()) {
            field.setAccessible(true);
            Class fieldType = field.getType();
            if (isPrimitiveWrapperClassOrString(fieldType)) {
                field.set(objT, field.get(objF));
            } else {
                Object objN = field.get(objT);
                if (Objects.isNull(objN)) objN = field.getType().newInstance();
                copyValues(field.get(objF), objN);
                field.set(objT, objN);
            }
        }
    }

    private static boolean isPrimitiveWrapperClassOrString(Class classType) {
        return classType == Boolean.class || classType == boolean.class ||
                classType == Byte.class || classType == byte.class ||
                classType == Short.class || classType == short.class ||
                classType == Integer.class || classType == int.class ||
                classType == Long.class || classType == long.class ||
                classType == Float.class || classType == float.class ||
                classType == Double.class || classType == double.class ||
                classType == Character.class || classType == char.class ||
                classType == String.class;
    }
}

class Foo {
    private int id;
    private String label;
    private Integer stock;
    private Bar bar;

    public Foo() { }
    public Foo(int id, String label, Integer stock, Bar bar) {
        this.id = id;
        this.label = label;
        this.stock = stock;
        this.bar = bar;
    }

    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }
    public String getLabel() { return this.label; }
    public void setLabel() { this.label = label; }
    public Integer getStock() { return this.stock; }
    public void setStock(Integer stock) { this.stock = stock; }
    public Bar getBar() { return this.bar; }
    public void setBar(Bar bar) { this.bar = bar; }

    @Override
    public String toString() {
        return String.format("%s | %d | %d | %s", this.label, this.id, this.stock, this.bar);
    }
}

class Bar {
    private int id;

    public Bar() {}
    public Bar(int id) { this.id = id; }

    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }

    @Override
    public String toString() { return "Bar: " + this.id; }
}

Which outputs

==ListA==
false
123
test
foo | 1 | 7 | Bar: 2

==ListB==
false
123
test
foo | 1 | 7 | Bar: 2

==ListA after modifying listB==
false
123
test
foo | 1 | 7 | Bar: 2

==ListB==
true
456
test
foo | 2 | 7 | Bar: 9


问:
Does I give instructions to Dji Phantom 4 using onboard sdk
I have Dji Phantom 4 and I need to track object using it so can I give instructions to it using onboard sdk as its only for Matrice 100 and if not is there any other way to five it instructions using ROS or with linux operating system.</p>

答:
With a Phantom 4, you can't use the OnboardSDK.

To achieve what you want your best chance is the MobileSDK.
It's available on iOS and Android though.

With it, you can get the video feed of the camera and do the tracking you want, convert it into virtual stick commands and have the drone track visually the subject you want.

Hope this helps.


问:
Output matching lines in linux
I want to match the numbers in the first file with the 2nd column of second file and get the matching lines in a separate output file. Kindly let me know what is wrong with the code?

I have a list of numbers in a file IDS.txt

```<code>10028615
1003
10096344
10100
10107393
10113978
10163178
118747520
</code>```

I have a second File  called src1src22.txt

```<code>From src:'1'    To src:'22'
CHEMBL3549542   118747520
CHEMBL548732    44526300
CHEMBL1189709   11740251
CHEMBL405440    44297517
CHEMBL310280    10335685
</code>```

expected newoutput.txt

```<code>CHEMBL3549542   118747520
</code>```

I have written this code

```<code>while read line; do cat src1src22.txt | grep -i -w "$line"  >> newoutput.txt done<IDS.txt
</code>```

答:
Try this -

```<code>awk 'NR==FNR{a[$2]=$1;next} $1 in a{print a[$1],$0}' f2 f1
CHEMBL3549542 118747520
</code>```

Where f2 is src1src22.txt

Title: Output matching lines in linux

Body:
I want to match the numbers in the first file with the 2nd column of second file and get the matching lines in a separate output file. Kindly let me know what is wrong with the code?

I have a list of numbers in a file IDS.txt

10028615
1003
10096344
10100
10107393
10113978
10163178
118747520

I have a second File  called src1src22.txt

From src:'1'    To src:'22'
CHEMBL3549542   118747520
CHEMBL548732    44526300
CHEMBL1189709   11740251
CHEMBL405440    44297517
CHEMBL310280    10335685

expected newoutput.txt

CHEMBL3549542   118747520

I have written this code

while read line; do cat src1src22.txt | grep -i -w "$line"  >> newoutput.txt done<IDS.txt

Body:
Try this -

awk 'NR==FNR{a[$2]=$1;next} $1 in a{print a[$1],$0}' f2 f1
CHEMBL3549542 118747520

Where f2 is src1src22.txt


问:
When I try running this class in eclipse, another class gets executed
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :</p>

```<code>package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}
</code>```

答: Right click either in your class file or the class itself and click Run As -> Java Application</p>

Body:
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :

package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}


问:
How can I best lay out these components in Swing?
What would be the best approach / LayoutManager for a JPanel that needed to display the components shown in the image?
(Note that the fields should resize horizontally when the size of the window is changed, but not the labels).

I'm currently trying (and struggling) to do it with a GridBagLayout.  Is this the correct approach or is there a better way?  Should I be trying to divide + conquer the seperate sections maybe?

Any thoughts or advice would be gratefully appreciated.  :-)

http://img261.imageshack.us/img261/2091/layouthb6.png

PS If you read this and there's no image, please bear with me whilst I fix it!

答:
Since Java SE 6 you can use GroupLayout

It's very easy and looks just like you want.

For this window:

alt text http://img165.imageshack.us/img165/8237/sampleusinggrouplayoutca2.png

I have this code:

```<code>    // Layout the components using the new GroupLayout added
    // in java 1.6.
    // Adding to the main frame
    private void layoutComponents(){
        JPanel panel = new JPanel();

        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        SequentialGroup hGroup = layout.createSequentialGroup();

        JLabel nameLbl  = new JLabel("Name");
        JLabel countLbl = new JLabel("Amount");
        JLabel dateLbl  = new JLabel("Date(dd/MM/yy)");
        hGroup.addGroup(layout.createParallelGroup().
                addComponent(nameLbl).
                addComponent(countLbl).
                addComponent(dateLbl).
                addComponent(go));

        hGroup.addGroup(layout.createParallelGroup().
                addComponent(name).
                addComponent(count).
                addComponent(date));

        layout.setHorizontalGroup(hGroup);

        SequentialGroup vGroup = layout.createSequentialGroup();

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(nameLbl).
                addComponent(name));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(countLbl).
                addComponent(count));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(dateLbl).
                addComponent(date));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(go));
        layout.setVerticalGroup(vGroup);

        frame.add( panel , BorderLayout.NORTH );
        frame.add( new JScrollPane( textArea ) );
    }
</code>```

OwnerDisplayName: cagcowboy

LastEditorDisplayName: John Topley

Body:
Since Java SE 6 you can use GroupLayout

It's very easy and looks just like you want.

For this window:

alt text http://img165.imageshack.us/img165/8237/sampleusinggrouplayoutca2.png

I have this code:

    // Layout the components using the new GroupLayout added
    // in java 1.6.
    // Adding to the main frame
    private void layoutComponents(){
        JPanel panel = new JPanel();

        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        SequentialGroup hGroup = layout.createSequentialGroup();

        JLabel nameLbl  = new JLabel("Name");
        JLabel countLbl = new JLabel("Amount");
        JLabel dateLbl  = new JLabel("Date(dd/MM/yy)");
        hGroup.addGroup(layout.createParallelGroup().
                addComponent(nameLbl).
                addComponent(countLbl).
                addComponent(dateLbl).
                addComponent(go));

        hGroup.addGroup(layout.createParallelGroup().
                addComponent(name).
                addComponent(count).
                addComponent(date));

        layout.setHorizontalGroup(hGroup);

        SequentialGroup vGroup = layout.createSequentialGroup();

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(nameLbl).
                addComponent(name));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(countLbl).
                addComponent(count));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(dateLbl).
                addComponent(date));

        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
                addComponent(go));
        layout.setVerticalGroup(vGroup);

        frame.add( panel , BorderLayout.NORTH );
        frame.add( new JScrollPane( textArea ) );
    }

OwnerDisplayName: Oscar Reyes