问:
Getting table from SQL failure
I have many queries which I am executing in my JAVA application. I am getting exceptions because of failures in SQL queries. I want to show the table name in the alert message on my Web Application after getting exception from SQL query. Is there any way to get the table name for which I got the exception. Thanks in advance.

And I asking about any kind of SQLException that comes because of some table.
I want to get the table name just below to System.out.println("exception1:::" + e); line.

Code:

```<code>        try {
                      System.out.println("DB     File : "+fileName);
                  fileData = readFile    (fileName);
                  String[] staticProperties = fileData.toString().split("\n");

              ipAddress = staticProperties[Constants.IP];
              port = staticProperties[Constants.PORT];
              datasource_name = staticProperties[Constants.DATASOURCE];

              Hashtable<String, String> env = new Hashtable<String, String>();
              env.put(Context.INITIAL_CONTEXT_FACTORY, Constants.JNDI_FACTORY);
              env.put(Context.PROVIDER_URL, "t3://" + ipAddress + ":"+port);
              datasource = (DataSource) new InitialContext(env).lookup(datasource_name);

              if (datasource != null) {

                    connection = datasource.getConnection();
                    statement = connection.createStatement();

                    rset = statement.executeQuery(query);
                    ResultSetMetaData  rsetMetaData = rset.getMetaData();

                    while (rset.next()) {
                        dataFromDB = new ArrayList<String>();
                           for (int i = 1; i <= rsetMetaData.getColumnCount(); i++) {

                                  dataFromDB.add(rset.getString(i));
                           }
                           inputDataFromDB.put(rset.getRow(), dataFromDB);
                    }
              }
       } catch (SQLException e) {
              System.out.println("exception1:::" + e);
              throw new SQLException(e);
       } catch (Exception e) {
              System.out.println("exception2:::" + e);
       } finally {

              if (rset != null) {
                    try {
                           rset.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }
              if (statement != null) {
                    try {
                           statement.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }
              if (connection != null) {
                    try {
                           connection.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }

       }
</code>```

答:
I understand you're wanting to extract he table name from an sql error message, and NOT how to get the sql to run. However, there are very few instances, if any you will be able to do that (at least without extreme effort and access to system tables - and maybe not even then). The basic issue you face being that Oracle issues error messages at the statement not the table level. Consider the following: (these all were run in SQL Developer, similar messages occur is SQL Plus, I suggest you try running the same through Java and see those results)</p>

```<code>create table table_that_exists ( te_id integer, description varchar2(200) );
/*
Table TABLE_THAT_EXISTS created.
*/

insert into able_that_exists( id, description) values (1, 'test1') ;
/*
Error starting at line : 6 in command -
insert into able_that_exists( id, description) values (1, 'test1')
Error at Command Line : 6 Column : 13
Error report -
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

The lines "Error starting ... Error Report" are added by my development environment.
I'm not all that familier with Java or what ever you useing to connect. But I would
guee hat all you'll ge back is:
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"

*/

insert into table_that_exists( id, description) values (1, 'test1') ;
/*
Error starting at line : 18 in command -
insert into table_that_exists( id, description) values (1, 'test1')
Error at Command Line : 18 Column : 32
Error report -
SQL Error: ORA-00904: "ID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:

Again I would guess all you'll get back in Jave is
SQL Error: ORA-00904: "ID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*/

insert into table_that_exists( te_id, description) values (1, 'test1') ;
/*
1 row inserted.

No message returned to Java (?)
*/
select * from table_that_exists where te_id = 2;
/*
   results in an 'empty' result' set. IE the values returned for td_id, description is NULL, NULL
   but no error generated

No message returned to Java (?)
*/

-- finally:
select *
  from table_that_exists         te
  join table_tha_does_not_exist  tne
       on te.te_id = tne.te_id ;

/*
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 44 Column: 8

Even my 'nice friendly' development environment doesn't tell me which table.
NOTE: You will get the same message if all tables do exist but you have not been granted access.
*/
</code>```

Title: Getting table from SQL failure

Body:
I have many queries which I am executing in my JAVA application. I am getting exceptions because of failures in SQL queries. I want to show the table name in the alert message on my Web Application after getting exception from SQL query. Is there any way to get the table name for which I got the exception. Thanks in advance.

And I asking about any kind of SQLException that comes because of some table.
I want to get the table name just below to System.out.println("exception1:::" + e); line.

Code:

        try {
                      System.out.println("DB     File : "+fileName);
                  fileData = readFile    (fileName);
                  String[] staticProperties = fileData.toString().split("\n");

              ipAddress = staticProperties[Constants.IP];
              port = staticProperties[Constants.PORT];
              datasource_name = staticProperties[Constants.DATASOURCE];

              Hashtable<String, String> env = new Hashtable<String, String>();
              env.put(Context.INITIAL_CONTEXT_FACTORY, Constants.JNDI_FACTORY);
              env.put(Context.PROVIDER_URL, "t3://" + ipAddress + ":"+port);
              datasource = (DataSource) new InitialContext(env).lookup(datasource_name);

              if (datasource != null) {

                    connection = datasource.getConnection();
                    statement = connection.createStatement();

                    rset = statement.executeQuery(query);
                    ResultSetMetaData  rsetMetaData = rset.getMetaData();

                    while (rset.next()) {
                        dataFromDB = new ArrayList<String>();
                           for (int i = 1; i <= rsetMetaData.getColumnCount(); i++) {

                                  dataFromDB.add(rset.getString(i));
                           }
                           inputDataFromDB.put(rset.getRow(), dataFromDB);
                    }
              }
       } catch (SQLException e) {
              System.out.println("exception1:::" + e);
              throw new SQLException(e);
       } catch (Exception e) {
              System.out.println("exception2:::" + e);
       } finally {

              if (rset != null) {
                    try {
                           rset.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }
              if (statement != null) {
                    try {
                           statement.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }
              if (connection != null) {
                    try {
                           connection.close();

                    } catch (Exception e) {
                           System.out.println("exception:::" + e);
                    }
              }

       }

Body:
I understand you're wanting to extract he table name from an sql error message, and NOT how to get the sql to run. However, there are very few instances, if any you will be able to do that (at least without extreme effort and access to system tables - and maybe not even then). The basic issue you face being that Oracle issues error messages at the statement not the table level. Consider the following: (these all were run in SQL Developer, similar messages occur is SQL Plus, I suggest you try running the same through Java and see those results)

create table table_that_exists ( te_id integer, description varchar2(200) );
/*
Table TABLE_THAT_EXISTS created.
*/

insert into able_that_exists( id, description) values (1, 'test1') ;
/*
Error starting at line : 6 in command -
insert into able_that_exists( id, description) values (1, 'test1')
Error at Command Line : 6 Column : 13
Error report -
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

The lines "Error starting ... Error Report" are added by my development environment.
I'm not all that familier with Java or what ever you useing to connect. But I would
guee hat all you'll ge back is:
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"

*/

insert into table_that_exists( id, description) values (1, 'test1') ;
/*
Error starting at line : 18 in command -
insert into table_that_exists( id, description) values (1, 'test1')
Error at Command Line : 18 Column : 32
Error report -
SQL Error: ORA-00904: "ID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:

Again I would guess all you'll get back in Jave is
SQL Error: ORA-00904: "ID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*/

insert into table_that_exists( te_id, description) values (1, 'test1') ;
/*
1 row inserted.

No message returned to Java (?)
*/
select * from table_that_exists where te_id = 2;
/*
   results in an 'empty' result' set. IE the values returned for td_id, description is NULL, NULL
   but no error generated

No message returned to Java (?)
*/

-- finally:
select *
  from table_that_exists         te
  join table_tha_does_not_exist  tne
       on te.te_id = tne.te_id ;

/*
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 44 Column: 8

Even my 'nice friendly' development environment doesn't tell me which table.
NOTE: You will get the same message if all tables do exist but you have not been granted access.
*/


来源: stackexchange

问:
split rows in the 4th column of a table with comma
My code to get data from the 4th column of my table.

```<code>function getColumn(table_id, col) {
var tab = document.getElementsByTagName("table")[4];
var n = tab.rows.length;
var i, s = null, tr, td;
if (col < 0) {
    return null;
}

for (i = 0; i < n; i++) {
    tr = tab.rows[i];
    if (tr.cells.length > col) { // Check that cell exists before you try
        td = tr.cells[col];      // to access it.
        s += ' ' + td.innerText;
    }
} return s; }
var txt = getColumn('partTable', 4);
</code>```

It is returning

"Jeans A Shirt B Pant T"

I would like it to return

"Jeans A, Shirt B, Pant T"

How is this possible in my code? I do not want to replace the space with ", " since i sometime would have spaces in the number

Thanks

答: try replacinig space (" ") with comma and space (, ).</p>

ContentLicense: CC BY-SA 3.0

Body:
My code to get data from the 4th column of my table.

function getColumn(table_id, col) {
var tab = document.getElementsByTagName("table")[4];
var n = tab.rows.length;
var i, s = null, tr, td;
if (col < 0) {
    return null;
}

for (i = 0; i < n; i++) {
    tr = tab.rows[i];
    if (tr.cells.length > col) { // Check that cell exists before you try
        td = tr.cells[col];      // to access it.
        s += ' ' + td.innerText;
    }
} return s; }
var txt = getColumn('partTable', 4);

It is returning

"Jeans A Shirt B Pant T"

I would like it to return

"Jeans A, Shirt B, Pant T"

How is this possible in my code? I do not want to replace the space with ", " since i sometime would have spaces in the number

Thanks


问:
How to pass arbitrary (non parameterized) data to a route in Angular?
First : it's not a dup. The linked dup question's answer uses service which i'm not after it.

I have a routing table :

```<code>const routes: Routes = [
  ...
  { path: 'comp1', loadChildren: './module1/module1.module.ts#Module1Module' },
  ...
  ];
</code>```

In the main component's ctor  ( app.component.ts) i'm navigating to :

```<code>constructor(private router: Router){
  router.navigate(['/comp1',{aaa:222,bbb:{ccc:3}}])
}
</code>```

However - it is serialized to a URL.

https://angular-iqfnre-router.stackblitz.io/comp1;aaa=222;bbb=%5Bobject%20Object%5D

Now - I don't want it to appear in url. (not to mention that the value is not valid)

Also - the remote route in the lazy module is :

```<code>const routes: Routes = [
  {
    path: '', component: Comp1Component,

    children: [{
      path: 'acomp', component: AComponent,
    }]

  }
];
</code>```

So it doesn't support parameters ( and i'm not talking about parameter but a complex data).

I don't want to change the route table.

Question:

How can I pass arbitrary (complex) data to the route - and how can I read it once i'm after routed ?

Stackblitz

NB

I don't want to use a service. I'm sure that there is another option to load the route with data. The docs mentioned  NavigationExtras But I think it's still using URL.
(please - no stringify).

答: For this kind of requirements I would suggest using a shared service. With that you can pass the type of data you want without causing any additional overhead on the route. </p>

Body:
First : it's not a dup. The linked dup question's answer uses service which i'm not after it.

I have a routing table :

const routes: Routes = [
  ...
  { path: 'comp1', loadChildren: './module1/module1.module.ts#Module1Module' },
  ...
  ];

In the main component's ctor  ( app.component.ts) i'm navigating to :

constructor(private router: Router){
  router.navigate(['/comp1',{aaa:222,bbb:{ccc:3}}])
}

However - it is serialized to a URL.

https://angular-iqfnre-router.stackblitz.io/comp1;aaa=222;bbb=%5Bobject%20Object%5D

Now - I don't want it to appear in url. (not to mention that the value is not valid)

Also - the remote route in the lazy module is :

const routes: Routes = [
  {
    path: '', component: Comp1Component,

    children: [{
      path: 'acomp', component: AComponent,
    }]

  }
];

So it doesn't support parameters ( and i'm not talking about parameter but a complex data).

I don't want to change the route table.

Question:

How can I pass arbitrary (complex) data to the route - and how can I read it once i'm after routed ?

Stackblitz

NB

I don't want to use a service. I'm sure that there is another option to load the route with data. The docs mentioned  NavigationExtras But I think it's still using URL.
(please - no stringify).


问:
How to find/delete duplicated records in the same row
It's possible to make a query to see if there is duplicated records in the same row?

I tried to find a solution but all I can find is to detected duplicated fields in columns, not in rows.

example, let's say I have a table with rows and items:

```<code>| id | item1 | item2 | item3 | item4 | item5 | upvotes | downvotes |
--------------------------------------------------------------------
| 1  |  red  | blue  |  red  | black | white |   12    |    5      |
</code>```

So I want to see if is possible to make a query to detect the fields with the same record (in this case red) and delete them, and/or how to redesign my structure to not allow the duplicates.

Thanks.

答:
With redesign:

You may redesign the layout to something like this:

```<code>| id | item |
</code>```

With (id, item) as primary key, this will forbid having twice the same item for a given id.

So the data will looks like this:

```<code>| id | item |
| 1  | red  |
| 1  | blue |
...
</code>```

Trying to insert a | 1  | red  | again will throw an error.

Without redesign:

If you don't want to change the layout, this query will find rows in which one of the fieldX field equals an other fieldX of the same row:

```<code>SELECT t.id FROM (select 1) dummy
JOIN (SELECT id, item1 as item FROM table
      UNION SELECT id, item2 as item FROM table
      UNION SELECT id, item3 as item FROM table
      UNION SELECT id, item4 as item FROM table
      UNION SELECT id, item5 as item FROM table) t
GROUP BY t.id
HAVING count(*) < 5
</code>```

(Assuming you have 5 of those fieldX columns.)

This actually counts the different fieldX values for each id. If the count is different than the number of fields, then there is a duplicate. The query returns the ids of the rows in which there is a duplicate.

After testing you can delete rows with

```<code>DELETE FROM table WHERE id IN ( <the previous query here> )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's possible to make a query to see if there is duplicated records in the same row?

I tried to find a solution but all I can find is to detected duplicated fields in columns, not in rows.

example, let's say I have a table with rows and items:

| id | item1 | item2 | item3 | item4 | item5 | upvotes | downvotes |
--------------------------------------------------------------------
| 1  |  red  | blue  |  red  | black | white |   12    |    5      |

So I want to see if is possible to make a query to detect the fields with the same record (in this case red) and delete them, and/or how to redesign my structure to not allow the duplicates.

Thanks.

Body:
With redesign:

You may redesign the layout to something like this:

| id | item |

With (id, item) as primary key, this will forbid having twice the same item for a given id.

So the data will looks like this:

| id | item |
| 1  | red  |
| 1  | blue |
...

Trying to insert a | 1  | red  | again will throw an error.

Without redesign:

If you don't want to change the layout, this query will find rows in which one of the fieldX field equals an other fieldX of the same row:

SELECT t.id FROM (select 1) dummy
JOIN (SELECT id, item1 as item FROM table
      UNION SELECT id, item2 as item FROM table
      UNION SELECT id, item3 as item FROM table
      UNION SELECT id, item4 as item FROM table
      UNION SELECT id, item5 as item FROM table) t
GROUP BY t.id
HAVING count(*) < 5

(Assuming you have 5 of those fieldX columns.)

This actually counts the different fieldX values for each id. If the count is different than the number of fields, then there is a duplicate. The query returns the ids of the rows in which there is a duplicate.

After testing you can delete rows with

DELETE FROM table WHERE id IN ( <the previous query here> )


问:
Can't get an item's attributes from a DynamoDB table
I have an iOS app written in Swift. In this app I'm trying to load an item from a DynamoDB table, but for some reason, I couldn't load any item, even though all the details were correct.

I have installed the AWS SDK using CocoaPods, after I followed all the instructions in order to correctly install it. I have installed the following libraries: AWSCognito, AWSCognitoIdentityProvider, AWSDynamoDB, AWSS3, AWSSNS.

After that, I have added my AWS credentials in the Info.plist file:

```<code><key>AWS</key>
<dict>
    <key>DynamoDBObjectMapper</key>
    <dict>
        <key>Default</key>
        <dict>
            <key>Region</key>
            <string>USEast1</string>
        </dict>
    </dict>
    <key>DynamoDB</key>
    <dict>
        <key>Default</key>
        <dict>
            <key>Region</key>
            <string>USEast1</string>
        </dict>
    </dict>
    <key>CredentialsProvider</key>
    <dict>
        <key>CognitoIdentity</key>
        <dict>
            <key>Default</key>
            <dict>
                <key>Region</key>
                <string>USEast1</string>
                <key>PoolId</key>
                <string>myPoolId</string>
            </dict>
        </dict>
    </dict>
</dict>
</code>```

I've created a mapper file called Contact.swift:

```<code>import UIKit
import AWSDynamoDB

class Contact: AWSDynamoDBObjectModel, AWSDynamoDBModeling {

    var id: String?
    var name: String?

    class func dynamoDBTableName() -> String {
        return "Contacts"
    }

    class func hashKeyAttribute() -> String {
        return "id"
    }
}
</code>```

Then, I've added the following code in ViewController.swift file, inside the viewDidLoad method. The code should get an item from a table, save its attributes, and set its name attribute to be the title of the screen:

```<code>import UIKit
import AWSDynamoDB

class ViewController: UIViewController {

    //MARK: Properties
    struct GlobalVars {
        static let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
        static let id: String = "id"

        static var name: String?
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        GlobalVars.dynamoDBObjectMapper.load(Contact.self, hashKey: GlobalVars.id, rangeKey: nil).continueWith(block: {(task: AWSTask<AnyObject>!) -> Any? in
            if let error = task.error as NSError? {
                print("The request failed. Error: \(error)")
            } else if let taskResult = task.result as? Contact {
                // Save the information
                GlobalVars.name = taskResult.name

                // Set title to the name
                self.navigationItem.title = GlobalVars.name!
            }
            return nil
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

The problem is that the app crashes when I'm trying to assign the GlobalVars.name variable to the navigation bar title. It crashes with the following message: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I've tried to print taskResult.name instead, but it just printed nil.

But it didn't print anything to the console. I've added the following code to the Info.plist file, but that didn't work also:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>amazonaws.com</key>
        <dict>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
      </dict>
      <key>amazonaws.com.cn</key>
      <dict>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
      </dict>
  </dict>
</code>```

When I'm checking in the variables area at the bottom of the editor, I can see that all of the item's attributes are nil.

After a deep search, I've noticed something very weird. When I changed the name of the table to a table which doesn't exist, I have received the following message in the console:

```<code>The request failed. Error: Error Domain=com.amazonaws.AWSDynamoDBErrorDomain Code=7 "(null)" UserInfo={__type=com.amazonaws.dynamodb.v20120810#ResourceNotFoundException, message=Requested resource not found}
</code>```

When I'm running it with a correct table name, but with a wrong hash key which refers to an item which doesn't exist in the table, I don't get anything. It doesn't crashes or prints a message to the console. It just keeps running like I'm don't asking for anything from the DynamoDB table.

What can I do about it? I've already searched all over the internet but I couldn't find anything about it yet... Could you please help me solving that?

答: So apparently, due to a change in Swift 4 behavior change of inferencing @objc, I was supposed to add @objcMembers before the class declaration in the Contact.swift file

Body:
I have an iOS app written in Swift. In this app I'm trying to load an item from a DynamoDB table, but for some reason, I couldn't load any item, even though all the details were correct.

I have installed the AWS SDK using CocoaPods, after I followed all the instructions in order to correctly install it. I have installed the following libraries: AWSCognito, AWSCognitoIdentityProvider, AWSDynamoDB, AWSS3, AWSSNS.

After that, I have added my AWS credentials in the Info.plist file:

<key>AWS</key>
<dict>
    <key>DynamoDBObjectMapper</key>
    <dict>
        <key>Default</key>
        <dict>
            <key>Region</key>
            <string>USEast1</string>
        </dict>
    </dict>
    <key>DynamoDB</key>
    <dict>
        <key>Default</key>
        <dict>
            <key>Region</key>
            <string>USEast1</string>
        </dict>
    </dict>
    <key>CredentialsProvider</key>
    <dict>
        <key>CognitoIdentity</key>
        <dict>
            <key>Default</key>
            <dict>
                <key>Region</key>
                <string>USEast1</string>
                <key>PoolId</key>
                <string>myPoolId</string>
            </dict>
        </dict>
    </dict>
</dict>

I've created a mapper file called Contact.swift:

import UIKit
import AWSDynamoDB

class Contact: AWSDynamoDBObjectModel, AWSDynamoDBModeling {

    var id: String?
    var name: String?

    class func dynamoDBTableName() -> String {
        return "Contacts"
    }

    class func hashKeyAttribute() -> String {
        return "id"
    }
}

Then, I've added the following code in ViewController.swift file, inside the viewDidLoad method. The code should get an item from a table, save its attributes, and set its name attribute to be the title of the screen:

import UIKit
import AWSDynamoDB

class ViewController: UIViewController {

    //MARK: Properties
    struct GlobalVars {
        static let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
        static let id: String = "id"

        static var name: String?
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        GlobalVars.dynamoDBObjectMapper.load(Contact.self, hashKey: GlobalVars.id, rangeKey: nil).continueWith(block: {(task: AWSTask<AnyObject>!) -> Any? in
            if let error = task.error as NSError? {
                print("The request failed. Error: \(error)")
            } else if let taskResult = task.result as? Contact {
                // Save the information
                GlobalVars.name = taskResult.name

                // Set title to the name
                self.navigationItem.title = GlobalVars.name!
            }
            return nil
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

The problem is that the app crashes when I'm trying to assign the GlobalVars.name variable to the navigation bar title. It crashes with the following message: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I've tried to print taskResult.name instead, but it just printed nil.

But it didn't print anything to the console. I've added the following code to the Info.plist file, but that didn't work also:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>amazonaws.com</key>
        <dict>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
      </dict>
      <key>amazonaws.com.cn</key>
      <dict>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
      </dict>
  </dict>

When I'm checking in the variables area at the bottom of the editor, I can see that all of the item's attributes are nil.

After a deep search, I've noticed something very weird. When I changed the name of the table to a table which doesn't exist, I have received the following message in the console:

The request failed. Error: Error Domain=com.amazonaws.AWSDynamoDBErrorDomain Code=7 "(null)" UserInfo={__type=com.amazonaws.dynamodb.v20120810#ResourceNotFoundException, message=Requested resource not found}

When I'm running it with a correct table name, but with a wrong hash key which refers to an item which doesn't exist in the table, I don't get anything. It doesn't crashes or prints a message to the console. It just keeps running like I'm don't asking for anything from the DynamoDB table.

What can I do about it? I've already searched all over the internet but I couldn't find anything about it yet... Could you please help me solving that?


问:
MySQL Workbench drops connection when idle
I'm using MySQL Workbench 6.3 on my OS X 10.9.5 to manage several cloud databases (hosted on Rackspace), and I get the following issue:

When inactive for 5 minutes, the following problems happen:

I cannot run any query (error 2013: Lost connection to MySQL server during query)

when trying to browse tables on my db, I'm getting messages like "Tables could not be fetched", "Views could not be fetched", and so on

when refreshing the left panel, I get a "Error Code: 2006 MySQL server has gone away"

So basically the connection is gone.

This is really annoying since it happens after only 5 minutes of inactivity. Therefore I need to close the connection and reopen it each time.

I also tried this: MySQL Workbench: How to keep the connection alive, which didn't change anything.
In my Workbench Preferences tab, I have the following setup:

DBMS connection keep-alive interval (in seconds): 600

DBMS connection read time out (in seconds): 600

DBMS connection time out (in seconds): 60

Notice that this issue happens precisely after 5 minutes of inactivity! If I run two queries in a 4'59 minutes interval it works perfectly fine.
Also my colleagues who connect to the same database on their Workbench don't have this issue.

Does anybody have a solution for this?

答:
This had driven me mental for months. My connections were to a Hostgator server. I'd connect and could edit a table for only 10 seconds or so after connecting, then I'd do, say, a table commit and the table would change to "Read Only" with a mouse-over message of, "Could not determine a unique row identifier (MySQL server has gone away) or "(Lost connection to MySQL server during query).

The solution was, as per other suggestions here, to REDUCE the keep-alive setting. In my case, it had to come down to 10s (obviously, Hostgator if fairly miserly with their bandwidth!)

First I tried reducing SSH KeepAlive (under Preferences/Others/Timeouts) but this didn't work.

What did the trick was reducing the DBMS connection keep-alive interval (under Preferences/SQL Editor/MySQL Session). I had to take it all the way down to 10s until the connection would remain stable. Your host might be different.

Finally, no more "Refresh All", wait, do something, rinse and repeat.


问:
PHP Array: Calculate difference among values in same array
I am trying to compute the difference between all values in an array and store them (the differences) in a single array.

An ideal example would be something like this:

```<code><?php

$data = array('1', '5', '12');

// Compute the difference between each value with another value.

?>
</code>```

And then I like to have the following results in an array:

```<code>4, 11, 7
</code>```

How can I achieve it?

答:
Try by having double for loops one for iterating current array and another to start comparing and store it in result array.
I am not very sure about your output as information is less but you can try as follow:

var a= ["1","5","12"]
for(i=0;i<3;i++){for(j=0;j<3;j++){if(i>j)console.log(a[i]-a[j])}}```

Body:
I am trying to compute the difference between all values in an array and store them (the differences) in a single array.

An ideal example would be something like this:

<?php

$data = array('1', '5', '12');

// Compute the difference between each value with another value.

?>

And then I like to have the following results in an array:

4, 11, 7

How can I achieve it?


问:
ASP.NET Identity - Modify default connection string name
I'm using EF6 and Identity, and configuring 2 separate connection strings:

```<code><connectionStrings>
    <add name="AppDbContext" providerName="System.Data.SqlClient" connectionString="Server=localhost;Database=db_entity;Trusted_Connection=True;" />
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Server=localhost;Database=db_identity;Trusted_Connection=True;" />
</connectionStrings>
</code>```

It works fine, my entities are stored in db_entity, and user information (just 5 default aspnet identity tables) are stored in db_identity.
my database

I can see that AspNet Identity is using DefaultConnection, and I want to modify that name. I tried to create this custom class (I've not use any custom class for identity before):

```<code>public class IdentityContext : IdentityDbContext<IdentityUser>
{
        public IdentityContext() : base("IdentityContext")
        {

        }

        public static IdentityContext Create()
        {
            return new IdentityContext();
        }
}
</code>```

And change DefaultConnection in web.config to IdentityContext.
But it doesn't work, when I run app, it throws an exception:

SqlException: Cannot attach the file 'C:\Users\thang\Documents\GitHub\GSSPHN\EmptyWeb\App_Data\DefaultConnection.mdf' as database 'DefaultConnection'.

It's still looking for DefaultConnection that I've changed to IdentityContext. How can I modify that connection name?

SOLVED: I modified that custom class:

```<code>public class IdentityContext : IdentityDbContext<IdentityUser>
{
        public IdentityContext() : base("IdentityContext")
        {
            UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(this));
            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this));
        }

        public UserManager<IdentityUser> UserManager { get; set; }
        public RoleManager<IdentityRole> RoleManager { get; set; }
}
</code>```

Now I can access UserManager and RoleManager from IdentityContext that pointing to my specified connection name.

答:
You should change Startup.Auth.cs or somewhere that initialized the UserManager;

```<code>UserManagerFactory = () => new UserManager<IdentityUser>(new IdentityDbContext<IdentityUser>());
</code>```

to

```<code>UserManagerFactory = () => new UserManager<IdentityUser>(new IdentityContext());
</code>```

Body:
I'm using EF6 and Identity, and configuring 2 separate connection strings:

<connectionStrings>
    <add name="AppDbContext" providerName="System.Data.SqlClient" connectionString="Server=localhost;Database=db_entity;Trusted_Connection=True;" />
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Server=localhost;Database=db_identity;Trusted_Connection=True;" />
</connectionStrings>

It works fine, my entities are stored in db_entity, and user information (just 5 default aspnet identity tables) are stored in db_identity.
my database

I can see that AspNet Identity is using DefaultConnection, and I want to modify that name. I tried to create this custom class (I've not use any custom class for identity before):

public class IdentityContext : IdentityDbContext<IdentityUser>
{
        public IdentityContext() : base("IdentityContext")
        {

        }

        public static IdentityContext Create()
        {
            return new IdentityContext();
        }
}

And change DefaultConnection in web.config to IdentityContext.
But it doesn't work, when I run app, it throws an exception:

SqlException: Cannot attach the file 'C:\Users\thang\Documents\GitHub\GSSPHN\EmptyWeb\App_Data\DefaultConnection.mdf' as database 'DefaultConnection'.

It's still looking for DefaultConnection that I've changed to IdentityContext. How can I modify that connection name?

SOLVED: I modified that custom class:

public class IdentityContext : IdentityDbContext<IdentityUser>
{
        public IdentityContext() : base("IdentityContext")
        {
            UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(this));
            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this));
        }

        public UserManager<IdentityUser> UserManager { get; set; }
        public RoleManager<IdentityRole> RoleManager { get; set; }
}

Now I can access UserManager and RoleManager from IdentityContext that pointing to my specified connection name.

Body:
You should change Startup.Auth.cs or somewhere that initialized the UserManager;

UserManagerFactory = () => new UserManager<IdentityUser>(new IdentityDbContext<IdentityUser>());

to

UserManagerFactory = () => new UserManager<IdentityUser>(new IdentityContext());


问:
Why is "this" NULL? C++ Segmentation fault

I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

```<code>void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}
</code>```

Here's the BaseAlgorithm header

```<code>#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};
</code>```

And here's the implementation and where the problem happens

```<code>#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}
</code>```

答:
In C++, it is perfectly possible to call a method via a null pointer to an object. As long as this is not actually dereferenced, the function would work fine.

UPDATE: The behavior is what is often exhibited by implementations, as this is usually treated as just another parameter in the compiled code. However, as @manni66 points out, the standard doesn't actually mandate the result of calling a method on a nullptr.

Body:
I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}

Here's the BaseAlgorithm header

#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};

And here's the implementation and where the problem happens

#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}


答:
try this

```<code>$data = array('1', '5', '12');
$differences=[];
for($i=0;$i<count($data);$i++){
    for($j=$i+1;$j<count($data);$j++){
        $differences[]=abs($data[$i]-$data[$j]);
    }
}
print_r($differences);
</code>```

results in

```<code>Array
(
    [0] => 4
    [1] => 11
    [2] => 7
)
</code>```

Title: PHP Array: Calculate difference among values in same array

Body:
try this

$data = array('1', '5', '12');
$differences=[];
for($i=0;$i<count($data);$i++){
    for($j=$i+1;$j<count($data);$j++){
        $differences[]=abs($data[$i]-$data[$j]);
    }
}
print_r($differences);

results in

Array
(
    [0] => 4
    [1] => 11
    [2] => 7
)


问:
How to get unique values excluding values from 1 of 2 tables
I need to get unique values from 2 tables, but exclude the values from the second table. I mean, I need all the values from the first table that are not in the second table and are greater than 9. The tables look like:

```
Table Gr:           Table Ak:
Idgr | TextGr       Idak | Grid | TextAk
1    | Aa           1    | 11   | R
11   | Bb           2    | 14   | P
12   | Cc           3    | 16   | P
13   | Dd           4    | 13   | P
14   | Ee
15   | Ff
16   | Gg
17   | Hh
18   | Ii
```

Grid on table Ak is the same ID from Idgr on table Gr.
I need to get result like this:

```
Results:
Idgr | TextGr
12   | Cc
15   | Ff
17   | Hh
18   | Ii
```

I tried with LEFT OUTER JOIN, but I get almost all values from table Gr. Check out SQLfiddle demo

答:
You're looking for the keyword EXCEPT.

```<code>(SELECT Idgr AS Idgr FROM Gr WHERE Idgr > 9)
EXCEPT
(SELECT Grid AS Idgr FROM Ak);
</code>```

This will provide a list of all values from Gr then subtract the values that match from Ak. In Mariadb it's called EXCEPT in other SQL variants it is often called MINUS.

Body:
I need to get unique values from 2 tables, but exclude the values from the second table. I mean, I need all the values from the first table that are not in the second table and are greater than 9. The tables look like:

Table Gr:           Table Ak:
Idgr | TextGr       Idak | Grid | TextAk
1    | Aa           1    | 11   | R
11   | Bb           2    | 14   | P
12   | Cc           3    | 16   | P
13   | Dd           4    | 13   | P
14   | Ee
15   | Ff
16   | Gg
17   | Hh
18   | Ii

Grid on table Ak is the same ID from Idgr on table Gr.
I need to get result like this:

Results:
Idgr | TextGr
12   | Cc
15   | Ff
17   | Hh
18   | Ii

I tried with LEFT OUTER JOIN, but I get almost all values from table Gr. Check out SQLfiddle demo

Body:
You're looking for the keyword EXCEPT.

(SELECT Idgr AS Idgr FROM Gr WHERE Idgr > 9)
EXCEPT
(SELECT Grid AS Idgr FROM Ak);

This will provide a list of all values from Gr then subtract the values that match from Ak. In Mariadb it's called EXCEPT in other SQL variants it is often called MINUS.


问:
OpenGL generate triangle mesh
I am a beginner at OpenGl and I am trying to draw a triangle mesh in OpenGL like this and my problem is that it is not drawing and I cannot see why. Also if I print the array of vertices the x- and y-coordinate remain the same for all vertices. Both the x- and z-coordinates should lie between +1 and -1. The coordinates seem to be correct when m_meshResolution = 1 but not otherwise. I assume that there is a much easier way to try to do this so all advice is welcome.

```<code>int size = m_meshResolution * m_meshResolution * 2 * 3 * 3;
float* positions = new float[size]();

double triangleWidth = 2 / m_meshResolution;
float startX = -1.0f;
float startZ = 1.0f;
float x1 = 0;
float x2 = 0;
float z1 = 0;
float z2 = 0;
int index = 0;
//For each row
for (int r = 0; r < m_meshResolution; r++) {
    //For each column
    for (int c = 0; c < m_meshResolution; c++) {
        x1 = startX + c*divider;
        x2 = startX + (c+1)*divider;
        z1 = startZ - r*divider;
        z2 = startZ -(r+1)*divider;
        //Generate one triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z1;
        //Generate other triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
    }

//Set buffers
glGenBuffers(1, &m_positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/);
glEnableVertexAttribArray(0);

//Draw
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, m_meshResolution*m_meshResolution*2*3);
</code>```

答:
positions is a pointer, and sizeof(positions) returns 4 or 8 bytes, it depends on architecture, but the second parameter of glBufferData tells us

size
         Specifies the size in bytes of the buffer object's new data store.

you should use sizeof(float) * size as second parameter.

Title: OpenGL generate triangle mesh

Body:
I am a beginner at OpenGl and I am trying to draw a triangle mesh in OpenGL like this and my problem is that it is not drawing and I cannot see why. Also if I print the array of vertices the x- and y-coordinate remain the same for all vertices. Both the x- and z-coordinates should lie between +1 and -1. The coordinates seem to be correct when m_meshResolution = 1 but not otherwise. I assume that there is a much easier way to try to do this so all advice is welcome.

int size = m_meshResolution * m_meshResolution * 2 * 3 * 3;
float* positions = new float[size]();

double triangleWidth = 2 / m_meshResolution;
float startX = -1.0f;
float startZ = 1.0f;
float x1 = 0;
float x2 = 0;
float z1 = 0;
float z2 = 0;
int index = 0;
//For each row
for (int r = 0; r < m_meshResolution; r++) {
    //For each column
    for (int c = 0; c < m_meshResolution; c++) {
        x1 = startX + c*divider;
        x2 = startX + (c+1)*divider;
        z1 = startZ - r*divider;
        z2 = startZ -(r+1)*divider;
        //Generate one triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z1;
        //Generate other triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
    }

//Set buffers
glGenBuffers(1, &m_positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/);
glEnableVertexAttribArray(0);

//Draw
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, m_meshResolution*m_meshResolution*2*3);


问:
Print ArrayList data using Stream
I am using below code, but it does not prints the list member  line by line, rather prints the entire list.
ArrayList aList=new ArrayList<>();

```<code>    aList.add("Pink");
    aList.add("Green");
    aList.add("Red");
    aList.add("Yellow");

    Stream.of(aList).forEach(s -> System.out.println(s));
</code>```

output that i get
[Pink, Green, Red, Yellow]

I require to print each of these elements in a new line.

答:
Write it like this :

```<code>aList.forEach(System.out::println);
</code>```

Stream.of(T... values) takes an array as parameter, for Collections you can call the forEach method directly on the instance (like above).

Title: Print ArrayList data using Stream

Body:
I am using below code, but it does not prints the list member  line by line, rather prints the entire list.
ArrayList aList=new ArrayList<>();

    aList.add("Pink");
    aList.add("Green");
    aList.add("Red");
    aList.add("Yellow");

    Stream.of(aList).forEach(s -> System.out.println(s));

output that i get
[Pink, Green, Red, Yellow]

I require to print each of these elements in a new line.

Body:
Write it like this :

aList.forEach(System.out::println);

Stream.of(T... values) takes an array as parameter, for Collections you can call the forEach method directly on the instance (like above).


问:
Using Maven, how can a child module inherit the parent module's repository?
Currently my web app has a spring-boot/java backend and an angular5/node frontend. I am using a Maven wrapper to encapsulate the projects such that the backend and frontend are both linked via the parent pom.

I am now configuring my database and I am putting the repository information in the parent pom. "I have heard that this is best practice because it enables you to access the db from other future projects. Ex Android app"

What do I need to include in my parent/child pom so that my backend module is reading from the parent repository?

Thank you!

答:
This might be possible but not sure because not too familiar how Spring is configured.

In the parent projects pom.xml all the main or profile related <properties /> are usable in child projects also.

With proper filtering you can use properties set in parents pom.xml to be set in your child project configuration files.

So for a dummy and abstract (totally Spring configuration unrelated but jsut to show how it could work) example, with

pom.xml (parent)

```<code><properties>
   <db.url>jdbc:postgresql://127.0.0.1:5432/MyDb</db.url>
   ...
<properties>
</code>```

and

some configuration / property file

```<code>db.url=${db.url}
</code>```

the result for filtering would be

```<code>db.url=jdbc:postgresql://127.0.0.1:5432/MyDb
</code>```

See also this filtering related post.

Body:
This might be possible but not sure because not too familiar how Spring is configured.

In the parent projects pom.xml all the main or profile related <properties /> are usable in child projects also.

With proper filtering you can use properties set in parents pom.xml to be set in your child project configuration files.

So for a dummy and abstract (totally Spring configuration unrelated but jsut to show how it could work) example, with

pom.xml (parent)

<properties>
   <db.url>jdbc:postgresql://127.0.0.1:5432/MyDb</db.url>
   ...
<properties>

and

some configuration / property file

db.url=${db.url}

the result for filtering would be

db.url=jdbc:postgresql://127.0.0.1:5432/MyDb

See also this filtering related post.


问:
Stateful implementation of yaml.v2 Unmarshaller interface?
This could either be a file path question, or a question on how to best implement an interface.

Given the following very simple yaml:

```<code>name: MyYamlName
data: some/relative/path.txt
</code>```

I would like to unmarshal it to the following struct:

```<code>type VerySimple struct {
    name string
    data io.Reader
}
</code>```

I'm already using the yaml.v2 library, and know that for simple types, I can implement the Unmarshaller interface. However, in my program, I can't assume an absolute root from which to base the relative path in the data field.

Is there a way to implement the Unmarshaller interface to pass a working directory, or maybe a different way to handle relative paths in Go?

答:
It's pretty clear from the API documentation that this isn't supported. The natural way to support it, IMO, would be with a Decoder type, analogous to the json.Decoder type. It could be initialized with a root include path, or a list of include paths to search.

There is already a request for such a feature. It does mention working with multiple documents, which probably implies including an include path, although that specific feature has not yet been explicitly mentioned. I suggest offering your ideas in that thread.

Body:
This could either be a file path question, or a question on how to best implement an interface.

Given the following very simple yaml:

name: MyYamlName
data: some/relative/path.txt

I would like to unmarshal it to the following struct:

type VerySimple struct {
    name string
    data io.Reader
}

I'm already using the yaml.v2 library, and know that for simple types, I can implement the Unmarshaller interface. However, in my program, I can't assume an absolute root from which to base the relative path in the data field.

Is there a way to implement the Unmarshaller interface to pass a working directory, or maybe a different way to handle relative paths in Go?


问:
Beego orm orderby rand()
I just ran into some problem in beego orm.
how to make a query with random order?

something like:

orm.NewOrm().QueryTable("tbl").OrderBy("rand()").Limit(1).All(&table)

but it gives panic result

I look at the documentation, but can't find that work for random result. any help is much appreciated.

Thank you in advance!

答:
BeeGo ORM doesn't support ordering by methods, only by mapped fields:

https://github.com/astaxie/beego/blob/master/orm/db_tables.go#L434

Title: Beego orm orderby rand()


问:
pandas.to_datetime return NaT starting from 2270-12-31
I am using python 3.5.3 with pandas 0.21.0

The following date in the future is working:

```<code>pandas.to_datetime('2260-12-31', format='%Y-%m-%d', errors='coerce')
Timestamp('2260-12-31 00:00:00')
</code>```

but for starting fron 2270 it is not accepted anymore:

```<code>pandas.to_datetime('2270-12-31', format='%Y-%m-%d', errors='coerce')
NaT
</code>```

If I use datetime.strptime it works in all cases:

```<code>datetime.datetime.strptime('2270-12-31', '%Y-%m-%d')
datetime.datetime(2270, 12, 31, 0, 0)
</code>```

or

```<code>datetime.datetime.strptime('9999-12-31-23.59.59.999999', '%Y-%m-%d-%H.%M.%S.%f')
datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
</code>```

Is it because pandas return a Timestamp and the second one a datetime.datetime ?

In the pandas documentation I see the following but I don't know what is the value for Timestamp.max. With other option it in the best case return the initial string.

In case when it is not possible to return designated types (e.g. when
  any element of input is before Timestamp.min or after Timestamp.max)
  return will have datetime.datetime type (or correspoding
  array/Series).

Is there a way to have it working with to_datetime ? It is very convenient when you have many columns all with different date and timestamp pattern and when you want to transform all of them from object to datetime64[ns] in your pandas dataframe.

答: It's working as intended. The reason for this is that timestamps are actually integers under the hood. They represent a 64 bit integer + an offset time. In this case '2270-12-31' is too far from the offset to fit inside a 64 bit integer so it says not a time. </p>

Body:
I am using python 3.5.3 with pandas 0.21.0

The following date in the future is working:

pandas.to_datetime('2260-12-31', format='%Y-%m-%d', errors='coerce')
Timestamp('2260-12-31 00:00:00')

but for starting fron 2270 it is not accepted anymore:

pandas.to_datetime('2270-12-31', format='%Y-%m-%d', errors='coerce')
NaT

If I use datetime.strptime it works in all cases:

datetime.datetime.strptime('2270-12-31', '%Y-%m-%d')
datetime.datetime(2270, 12, 31, 0, 0)

or

datetime.datetime.strptime('9999-12-31-23.59.59.999999', '%Y-%m-%d-%H.%M.%S.%f')
datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

Is it because pandas return a Timestamp and the second one a datetime.datetime ?

In the pandas documentation I see the following but I don't know what is the value for Timestamp.max. With other option it in the best case return the initial string.

In case when it is not possible to return designated types (e.g. when
  any element of input is before Timestamp.min or after Timestamp.max)
  return will have datetime.datetime type (or correspoding
  array/Series).

Is there a way to have it working with to_datetime ? It is very convenient when you have many columns all with different date and timestamp pattern and when you want to transform all of them from object to datetime64[ns] in your pandas dataframe.


问:
AudioKit how to update plot to change color or prototype

I have used the AudioKit example code for microphone analysis, but I can't figure out how to make changes to the plot/graph.

```<code> func setupPlot() {

    let plot = AKNodeOutputPlot(mic, frame: audioInputPlot.bounds)
    plot.plotType = .buffer
    plot.shouldFill = false
    plot.shouldMirror = false
    plot.color = color
    audioInputPlot.addSubview(plot)

}
</code>```

I want to change the plot.color when I press a button. How can I do this?

答: I think the only issue here is that you're declaring plot as a local variable and can't access it from outside the setupPlot function. declare it as instance variable to the class and you should be able to change its color at any point.</p>

Body:
I have used the AudioKit example code for microphone analysis, but I can't figure out how to make changes to the plot/graph.

 func setupPlot() {

    let plot = AKNodeOutputPlot(mic, frame: audioInputPlot.bounds)
    plot.plotType = .buffer
    plot.shouldFill = false
    plot.shouldMirror = false
    plot.color = color
    audioInputPlot.addSubview(plot)

}

I want to change the plot.color when I press a button. How can I do this?


问:
how to update using nested query in SQL
I have a query that runs on a table, and pulls out 2 fields.
I want to take them, and using UPDATE sentence, to use their values as WHERE and SET.

For example:

```<code>select name, address from xxx.....
</code>```

I want to take the name & address and do this

```<code>update yyy
set fullname=(name I pulled before)
where address=(address I pulled before)
</code>```

thanks

答:
Give this a try

```<code>Update t
Set t.yyyy = q.Name
From TableToUpdate t
Join AddressTable q on q.Address = t.Address
</code>```

This assumes that Address field (which you are joining on) is a one to one relationship with the Address field in the table you are updating

This can also be written

```<code>Update TableToUpdate
Set yyyy = q.Name
From AddressTable q
WHERE q.Address = TableToUpdate.Address
</code>```

Since the update table is accessible in the FROM/WHERE clauses, except it cannot be aliased.

Title: how to update using nested query in SQL

Body:
I have a query that runs on a table, and pulls out 2 fields.
I want to take them, and using UPDATE sentence, to use their values as WHERE and SET.

For example:

select name, address from xxx.....

I want to take the name & address and do this

update yyy
set fullname=(name I pulled before)
where address=(address I pulled before)

thanks

Body:
Give this a try

Update t
Set t.yyyy = q.Name
From TableToUpdate t
Join AddressTable q on q.Address = t.Address

This assumes that Address field (which you are joining on) is a one to one relationship with the Address field in the table you are updating

This can also be written

Update TableToUpdate
Set yyyy = q.Name
From AddressTable q
WHERE q.Address = TableToUpdate.Address

Since the update table is accessible in the FROM/WHERE clauses, except it cannot be aliased.


问:
Why I need any type in typescript?
We have a simple method in typescript

```<code>function identity(arg) {
    return arg;
}
</code>```

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).
We can also declare this method in another way:

```<code> function identity(arg:any):any {
        return arg;
    }
</code>```

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).

What is the difference between the two ways? In other word what is benefit using of any type?

答:
any is like an anonymous type, not like Object. When using any, the compiler does minimal type checking since it doesn't know your variable's members.

Example:

```<code>var var1: any;
var var2: Object;

var1.whatever(); // The compiler trusts you
var2.whatever(); // Compiler throws an error
</code>```

As you can see in the example, you can handle var1 however you want, but you can't mess with var2 except for its official members.

In your function, you can whatever you want with your arg, but if you specify a type for it then you'll be bound to use that type's members.

Title: Why I need any type in typescript?

Body:
We have a simple method in typescript

function identity(arg) {
    return arg;
}

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).
We can also declare this method in another way:

 function identity(arg:any):any {
        return arg;
    }

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).

What is the difference between the two ways? In other word what is benefit using of any type?

Body:
any is like an anonymous type, not like Object. When using any, the compiler does minimal type checking since it doesn't know your variable's members.

Example:

var var1: any;
var var2: Object;

var1.whatever(); // The compiler trusts you
var2.whatever(); // Compiler throws an error

As you can see in the example, you can handle var1 however you want, but you can't mess with var2 except for its official members.

In your function, you can whatever you want with your arg, but if you specify a type for it then you'll be bound to use that type's members.


问:
firebase functions check sub child name is exists?
Hello i am trying to write a function that find all username below userid and decide the username already exists or not

my json looks like this

```<code>    {
  "ali": {
    "AccessToken": "asdadas",
    "CreatedAt": "2017/12/09",
    "DeletedAt": -1,
    "Email": "sadadada",
    "FirstName": "asdad",
    "LastName": "asdadad",
    "LoginType": 0,
    "Phone": "",
    "ThumbNailUrl": "",
    "UpdatedAt": -1,
    "UserName": "asdada"
  },
  "asdadad": {
    "AccessToken": "asdadas",
    "CreatedAt": "2017/12/09",
    "DeletedAt": -1,
    "Email": "asdadadada",
    "FirstName": "asdada",
    "LastName": "asdada",
    "LoginType": 0,
    "Phone": "",
    "ThumbNailUrl": "",
    "UpdatedAt": -1,
    "UserName": "asdadadada"
  }
}
</code>```

my functions looks like this

```<code>    exports.CheckUserName = functions.https.onRequest((req,res) => {
    const userName = req.query.userName;
    if (userName == "" || userName == null) {
        return res.json({
            result: "UserName can not be null or empty"
        })
    } else {
        // what i have to do in here :(
    }
})
</code>```

i tried a lot of way but i couldn't do it

答:
I'm java developer so i'll tell you the logic. you can implement in your javascript

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("userId");

rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  void onDataChange(DataSnapshot snapshot) {
    if (snapshot.hasChild("your username")) {
      // run some code
    }
  }
});
</code>```

Now you can find all username under id.
If exists print something according to your need

If you don't know id
you can save all usernames in separate node called usernames
and put all usernames in there and always check from there if usernames exists in that node or not. pretty simple :)

Body:
Hello i am trying to write a function that find all username below userid and decide the username already exists or not

my json looks like this

    {
  "ali": {
    "AccessToken": "asdadas",
    "CreatedAt": "2017/12/09",
    "DeletedAt": -1,
    "Email": "sadadada",
    "FirstName": "asdad",
    "LastName": "asdadad",
    "LoginType": 0,
    "Phone": "",
    "ThumbNailUrl": "",
    "UpdatedAt": -1,
    "UserName": "asdada"
  },
  "asdadad": {
    "AccessToken": "asdadas",
    "CreatedAt": "2017/12/09",
    "DeletedAt": -1,
    "Email": "asdadadada",
    "FirstName": "asdada",
    "LastName": "asdada",
    "LoginType": 0,
    "Phone": "",
    "ThumbNailUrl": "",
    "UpdatedAt": -1,
    "UserName": "asdadadada"
  }
}

my functions looks like this

    exports.CheckUserName = functions.https.onRequest((req,res) => {
    const userName = req.query.userName;
    if (userName == "" || userName == null) {
        return res.json({
            result: "UserName can not be null or empty"
        })
    } else {
        // what i have to do in here :(
    }
})

i tried a lot of way but i couldn't do it

Body:
I'm java developer so i'll tell you the logic. you can implement in your javascript

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("userId");

rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  void onDataChange(DataSnapshot snapshot) {
    if (snapshot.hasChild("your username")) {
      // run some code
    }
  }
});

Now you can find all username under id.
If exists print something according to your need

If you don't know id
you can save all usernames in separate node called usernames
and put all usernames in there and always check from there if usernames exists in that node or not. pretty simple :)


问:
Scatter plot for every pairs in a two column matrix
I have a matrix which contains the atom numbers of the pairs of atoms which are in contact with each other. My matrix is like this:

```<code>column 1: atom number i;
column 2: atom number j
</code>```

i,j runs from 1 to 800.

If there is a pair i-j in the matrix, place a dot corresponding to the position (i,j) of the matrix.
How do I plot such matrix?

Example:

```<code>A= [1,3; 3,8; 3,1; 6,2; 2,6; 1,2; 5,2; 8,3; 2,5; 2,1]
</code>```

I want to Plot the matrix A, where X and Y-axis run from 1 to 8. Place a dot for every combination of X and Y which are present in A.

I want a plot like this:

答:
Isn't this just a scatter plot?

If your m x 2 matrix is saved in a text file then this is trivial.
Here are the contents of an example data file "input.dat":

```<code>4 3
3 4
5 3
3 5
8 2
2 8
</code>```

All you need to do is open the data file in xmgrace using xmgrace input.dat.
Now, initially it will be a line plot, but if you do 'Plot' > 'Set Appearance' and then with the only set already being selected you can set the 'Symbol Properties' 'Type:' to Diamond and 'Line Properties' 'Type:' to None you will already be on your way. Setting the symbol fill to solid red, tweaking the axis ranges and showing major tick grid lines will give a plot like the one you gave as an example.

You can save a parameters file and in future load the parameters at the beginning using

xmgrace -param template.par input2.dat.

But, having said all this, why not just plot it in matlab?

Body:
I have a matrix which contains the atom numbers of the pairs of atoms which are in contact with each other. My matrix is like this:

column 1: atom number i;
column 2: atom number j

i,j runs from 1 to 800.

If there is a pair i-j in the matrix, place a dot corresponding to the position (i,j) of the matrix.
How do I plot such matrix?

Example:

A= [1,3; 3,8; 3,1; 6,2; 2,6; 1,2; 5,2; 8,3; 2,5; 2,1]

I want to Plot the matrix A, where X and Y-axis run from 1 to 8. Place a dot for every combination of X and Y which are present in A.

I want a plot like this:

Body:
Isn't this just a scatter plot?

If your m x 2 matrix is saved in a text file then this is trivial.
Here are the contents of an example data file "input.dat":

4 3
3 4
5 3
3 5
8 2
2 8

All you need to do is open the data file in xmgrace using xmgrace input.dat.
Now, initially it will be a line plot, but if you do 'Plot' > 'Set Appearance' and then with the only set already being selected you can set the 'Symbol Properties' 'Type:' to Diamond and 'Line Properties' 'Type:' to None you will already be on your way. Setting the symbol fill to solid red, tweaking the axis ranges and showing major tick grid lines will give a plot like the one you gave as an example.

You can save a parameters file and in future load the parameters at the beginning using

xmgrace -param template.par input2.dat.

But, having said all this, why not just plot it in matlab?


问:
How to use 'cp' command to exclude a specific directory?
I want to copy all files in a directory except some files in a specific sub-directory.
I have noticed that cp command didn't have the --exclude option.
So, how can I achieve this?

答:
rsync is actually quite tricky. have to do multiple tests to make it work.

Let's say you want to copy /var/www/html to /var/www/dev but need to exclude /var/www/html/site/video/ directory maybe due to its size. The command would be:

rsync -av --exclude 'sites/video' /var/www/html/ /var/www/dev

Some caveat:

The last slash / in the source is needed, otherwise it will also copy the source directory rather than its content and becomes /var/www/dev/html/xxxx, which maybe is not what you want.

The the --exclude path is relative to the source directly. Even if you put full absolute path, it will not work.

-v is for verbose, -a is for archive mode which means you want recursion and want to preserve almost everything.

ContentLicense: CC BY-SA 4.0


问:
How I can pass nested promises to async await
I have a function that downloads a file from endpoint using filesaver.js the problem is that I need to pass the function to async await method

```<code>fileDownload = () => {
    fetch('http://localhost:3000/api/buildings/1/assets.xlsx')
        .then(res => res.blob())
        .then(blob => saveAs(blob, 'assets.xlsx'))
}
</code>```

How can change this to async await with this nested promises? (the function is ok)

答:
You can use the code: </p>

```<code>fileDownload = async () => {
    let response = await fetch('http://localhost:3000/api/buildings/1/assets.xlsx');
    let blob = await response.blob();
    await saveAs(blob, 'assets.xlxs');
};
</code>```

Body:
I have a function that downloads a file from endpoint using filesaver.js the problem is that I need to pass the function to async await method

fileDownload = () => {
    fetch('http://localhost:3000/api/buildings/1/assets.xlsx')
        .then(res => res.blob())
        .then(blob => saveAs(blob, 'assets.xlsx'))
}

How can change this to async await with this nested promises? (the function is ok)

Body:
You can use the code:

fileDownload = async () => {
    let response = await fetch('http://localhost:3000/api/buildings/1/assets.xlsx');
    let blob = await response.blob();
    await saveAs(blob, 'assets.xlxs');
};


问:
Having services in React application
I'm coming from the angular world where I could extract logic to a service/factory and consume them in my controllers.

I'm trying to understand how can I achieve the same in a React application.

Let's say that I have a component that validates user's password input (it's strength). It's logic is pretty complex hence I don't want to write it in the component it self.

Where should I write this logic? In a store if I'm using flux? Or is there a better option?

答:
I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for
  reusing component logic. HOCs are not part of the React API, per se.
  They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

```<code>const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)
</code>```

Then write a HOC that does validate and style wrapped component:

```<code>function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}
</code>```

Now those HOCs share the same validating behavior:

```<code>const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));
</code>```

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

```<code><InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />
</code>```

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

```<code>const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}
</code>```

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js

Title: Having services in React application

Body:
I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for
  reusing component logic. HOCs are not part of the React API, per se.
  They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)

Then write a HOC that does validate and style wrapped component:

function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}

Now those HOCs share the same validating behavior:

const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js


问:
Laravel get last inserted data
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

```<code>    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }
</code>```

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

答:
After executing save() you'll get model with it's ID. You can access it with $model->id. So, you can do something like this:

```<code>$country = new Country;

$country->name = $request->post('country-name');
$country->xyz  = $request->post('xyz');

$dimentionIds = [];

if ($country->save()) {
    $n = count($request->post('bname'));

    for ($i = 0; $i < $n; $i++) {
        $dimention = new BoxDimentions;

        $dimention->name = $request->post('bname')[$i];
        $dimention->xyz  = $request->post('xyz')[$i];
        $dimention->cid  = $country->id;

        $dimention->save();

        $dimentionIds[] = $dimention->id;
    }
}

dd($dimentionIds, $country->id);
</code>```

If you need all the data, just save whole object:

```<code> $dimentions[] = $dimention;
</code>```

Title: Laravel get last inserted data

Body:
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

Body:
After executing save() you'll get model with it's ID. You can access it with $model->id. So, you can do something like this:

$country = new Country;

$country->name = $request->post('country-name');
$country->xyz  = $request->post('xyz');

$dimentionIds = [];

if ($country->save()) {
    $n = count($request->post('bname'));

    for ($i = 0; $i < $n; $i++) {
        $dimention = new BoxDimentions;

        $dimention->name = $request->post('bname')[$i];
        $dimention->xyz  = $request->post('xyz')[$i];
        $dimention->cid  = $country->id;

        $dimention->save();

        $dimentionIds[] = $dimention->id;
    }
}

dd($dimentionIds, $country->id);

If you need all the data, just save whole object:

 $dimentions[] = $dimention;


问:
What are good ways to test a login page?
I get asked this question very frequently in my interviews. They draw username and password text fields and ask me what test cases I can come up with to ensure that this page works fine. My answers on this for some reason never seem to satisfy them. So what tests can we have to ensure that this page is working fine besides the ones mentioned below?

My answers normally include:

check whether the login works with correct credentials

check that it doesn't work with wrong credentials

check text field limits - whether the browser accepts more than the allowed database limits

check whether password text is hidden

答:
Check that the underlying queries are sql injection safe. You don't want hackers to drop your tables using injection.

http://sqlzoo.net/hack/ . This page describes one way in which sql injection can be used in login form.


问:
What is the correct format for creating the creative of an MPA Advertisement on facebook?
I've been trying to create a MPA(multi-product ad) for some time now, but it keeps giving me the following error "Call to action link should be same as link of the post".
I've used the following format:

```<code>{
  "object_story_spec" => {
    "page_id" => 321954304600161,
    "instagram_actor_id" => "874410812666052",
    "link_data" => {
      "multi_share_optimized" => true,
      "multi_share_end_card" => true,
      "message" => "Test message ad in adset",
      "caption" => nil,
      "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
      "child_attachments" => [{
        "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=Test for Json-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_test ad in adset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
        "name" => "TEst ad in adset",
        "description" => nil,
        "picture" => "https://adcreation-m.s3-ap-south-1.amazonaws.com/1512559029_test.jpg",
        "call_to_action" => {
          "type" => "SHOP_NOW",
          "value" => {
            "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92"
          }
        }
      }, {
        "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=Test for Json-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_test ad in adset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
        "name" => "TEst",
        "description" => nil,
        "picture" => "https://adcreation-m.s3-ap-south-1.amazonaws.com/1512559033_test.jpg",
        "call_to_action" => {
          "type" => "SHOP_NOW",
          "value" => {
            "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92"
          }
        }
      }]
    }
  }
}
</code>```

I've made sure that in "child_attachments". "link" and "call_to_action.value.link" have the same value, but I keep getting the same error. I've also tried escaping the links, removing spaces etc. I've been seeing this behaviour since 10 hours or so.

答:
Despite's OP incorrect link values in the child_attachment and call_to_action, this has been confirmed by Facebook as a valid bug:
https://developers.facebook.com/bugs/310154929502029/
https://developers.facebook.com/bugs/1909897769263210/

I'm guessing OP was testing a lot of different combinations and this one he posted happened to have different values.

Hopefully this will be fixed soon.

Body:
I've been trying to create a MPA(multi-product ad) for some time now, but it keeps giving me the following error "Call to action link should be same as link of the post".
I've used the following format:

{
  "object_story_spec" => {
    "page_id" => 321954304600161,
    "instagram_actor_id" => "874410812666052",
    "link_data" => {
      "multi_share_optimized" => true,
      "multi_share_end_card" => true,
      "message" => "Test message ad in adset",
      "caption" => nil,
      "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
      "child_attachments" => [{
        "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=Test for Json-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_test ad in adset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
        "name" => "TEst ad in adset",
        "description" => nil,
        "picture" => "https://adcreation-m.s3-ap-south-1.amazonaws.com/1512559029_test.jpg",
        "call_to_action" => {
          "type" => "SHOP_NOW",
          "value" => {
            "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92"
          }
        }
      }, {
        "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=Test for Json-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_test ad in adset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92",
        "name" => "TEst",
        "description" => nil,
        "picture" => "https://adcreation-m.s3-ap-south-1.amazonaws.com/1512559033_test.jpg",
        "call_to_action" => {
          "type" => "SHOP_NOW",
          "value" => {
            "link" => "http://www.adwyze.com?utm_source=facebook&utm_medium=ocpm&utm_campaign=TestforJson-06Dec2017-16h48m&utm_term=all-MF-18-65-06Dec2017-16h48m&utm_content=test_testadinadset-00-CarouselAd-06Dec2017-19h44m&utm_id=2b301660-01c2-4c21-9fe1-06863dbaac92"
          }
        }
      }]
    }
  }
}

I've made sure that in "child_attachments". "link" and "call_to_action.value.link" have the same value, but I keep getting the same error. I've also tried escaping the links, removing spaces etc. I've been seeing this behaviour since 10 hours or so.


问:
"ilc.exe" exit code 1104 when compiling in "Release" mode
I'm getting only this error (1104) when I build my UWP app in "Release" mode (only in x86) so I can't create app packages...In debug and Release (x64) modes works perfectly.
Any idea of what's causing this issue and how can I solve it?

Thanks!

答:
Okay, problem solved. I took the following steps:

Clean solution

Delete "bin" and "obj" directories completely

Recompile and run the app without problem

Regards and "thanks" for the downvote...


问:
Google Maps Tiles Skewed with Flexbox
I'm trying to create a layout with a scrolling left column (with images as links) and a fixed full screen right column displaying Google maps. I can't figure out why the map is displaying as skewed.
Here's a screnshot of my problem.

$(window)
  .resize(function() {
    var h = $(window).height(),
      offsetTop = 40; // Calculate the top offset

    $("#map-canvas").css("height", h - offsetTop);
  })
  .resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  height: 100%;
  font-family: sans-serif;
  padding: 0px;
  margin: 0px;
}

body {
  height: 100%;
  overflow: hidden;
  margin: 0px;
  display: flex;
  padding-left: 0px;
}

.column {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-left: 0px;
  margin: 0px;
}

#left {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 40%;
  background-color: white;
  padding: 0px;
  margin: 0px;
}

#right {
  background-color: #f3f3f3;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 60%;
  flex: 1;
}

.top-left {
  flex-shrink: 0;
  background-color: #333;
  color: white;
  padding: 20px;
}

.top-right {
  display: inline-flex;
  flex-shrink: 0;
  background-color: #333;
  color: white;
  padding: 20px;
}

.bottom {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0px;
  margin: 0px;
}

ul {
  display: inline-flex;
  list-style: none;
  padding: 0px;
  margin: 0px;
}

li {
  display: flex;
  padding: 0px;
  margin: 0px;
}

img {
  min-width: 450px;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map_canvas {
  flex: 2;
}</code>```

```

Here's my codepen link, if that's helpful.

I'd like it to look something like this, but I couldn't figure out what exactly I am doing wrong.

Any ideas? Thanks in advance for helping out a beginner!

答:
Google Maps uses HTML  tag to render the map.

In your code you have:

```<code>img {
  min-width: 450px;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
</code>```

You are overwriting the styles of Google Maps  tags when you run the code.

The proper way is limiting to the zone where the image is going to render, by using:

```<code>.container-content img {
  margin: 0px;
  min-width: 450px;
  padding: 0px;
  width: 100%;
}
</code>```

By the way, you're missing the
 tags in the HTML.

See this demo is according to your link.

ul {
  margin: 0;
  padding: 0;
}

ul li {
  margin: 0;
  padding: 0;
}

.flexbox-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 100vh;
}

.flexbox-container #left_container {
  flex: 1;
  padding: 0;
}

.container-content {
  overflow-y: auto;
  height: 100vh;
}

.flexbox-container #map_container {
  margin: 0;
}

#map_canvas {
  flex: 2;
}

.container-content img {
  margin: 0;
  min-width: 450px;
  padding: 0;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="flexbox-container">
  <div id="left_container">
    <div class="container-content">
      <ul>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
      </ul>
    </div>
  </div>
  <div id="map_canvas"></div>
</div>

<script>
  function initMap() {
    // Styles a map in night mode.
    var map = new google.maps.Map(document.getElementById("map_canvas"), {
      center: {
        lat: 40.674,
        lng: -73.945
      },
      zoom: 12
    });
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAK1QRzq4tKEN63PxIA6jKfyypkoRn326M&callback=initMap" async></script></code>```

Title: Google Maps Tiles Skewed with Flexbox

Body:
I'm trying to create a layout with a scrolling left column (with images as links) and a fixed full screen right column displaying Google maps. I can't figure out why the map is displaying as skewed.
Here's a screnshot of my problem.

$(window)
  .resize(function() {
    var h = $(window).height(),
      offsetTop = 40; // Calculate the top offset

    $("#map-canvas").css("height", h - offsetTop);
  })
  .resize();

html {
  height: 100%;
  font-family: sans-serif;
  padding: 0px;
  margin: 0px;
}

body {
  height: 100%;
  overflow: hidden;
  margin: 0px;
  display: flex;
  padding-left: 0px;
}

.column {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-left: 0px;
  margin: 0px;
}

#left {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 40%;
  background-color: white;
  padding: 0px;
  margin: 0px;
}

#right {
  background-color: #f3f3f3;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 60%;
  flex: 1;
}

.top-left {
  flex-shrink: 0;
  background-color: #333;
  color: white;
  padding: 20px;
}

.top-right {
  display: inline-flex;
  flex-shrink: 0;
  background-color: #333;
  color: white;
  padding: 20px;
}

.bottom {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0px;
  margin: 0px;
}

ul {
  display: inline-flex;
  list-style: none;
  padding: 0px;
  margin: 0px;
}

li {
  display: flex;
  padding: 0px;
  margin: 0px;
}

img {
  min-width: 450px;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map_canvas {
  flex: 2;
}

Here's my codepen link, if that's helpful.

I'd like it to look something like this, but I couldn't figure out what exactly I am doing wrong.

Any ideas? Thanks in advance for helping out a beginner!

Body:
Google Maps uses HTML <img /> tag to render the map.

In your code you have:

img {
  min-width: 450px;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

You are overwriting the styles of Google Maps <img /> tags when you run the code.

The proper way is limiting to the zone where the image is going to render, by using:

.container-content img {
  margin: 0px;
  min-width: 450px;
  padding: 0px;
  width: 100%;
}

By the way, you're missing the <ul> tags in the HTML.

See this demo is according to your link.

ul {
  margin: 0;
  padding: 0;
}

ul li {
  margin: 0;
  padding: 0;
}

.flexbox-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 100vh;
}

.flexbox-container #left_container {
  flex: 1;
  padding: 0;
}

.container-content {
  overflow-y: auto;
  height: 100vh;
}

.flexbox-container #map_container {
  margin: 0;
}

#map_canvas {
  flex: 2;
}

.container-content img {
  margin: 0;
  min-width: 450px;
  padding: 0;
  width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="flexbox-container">
  <div id="left_container">
    <div class="container-content">
      <ul>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
        <li><img class="img-responsive" src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" data-src="http://s3.india.com/travel/wp-content/uploads/2014/09/Mumbai-Gateway-625x470.jpg" style="opacity: 0.5;"></li>
      </ul>
    </div>
  </div>
  <div id="map_canvas"></div>
</div>

<script>
  function initMap() {
    // Styles a map in night mode.
    var map = new google.maps.Map(document.getElementById("map_canvas"), {
      center: {
        lat: 40.674,
        lng: -73.945
      },
      zoom: 12
    });
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAK1QRzq4tKEN63PxIA6jKfyypkoRn326M&callback=initMap" async></script>