问:
JUnit/Mockito - How to capture changes in an argument's field?
I have an ObservableBoolean which is a pretty simple data container wrapping a primitive boolean. I want to use JUnit/Mockito to verify that the primitive boolean's value changes to true followed by false. I am setting up a mock OnPropertyChangedCallback like so:

```<code>Observable.OnPropertyChangedCallback loadingCallback = mock(Observable.OnPropertyChangedCallback.class);
viewModel.loading.addOnPropertyChangedCallback(loadingCallback);
</code>```

I am then running the code under test which does:

```<code>loading.set(true);
loading.set(false);
</code>```

Each of these calls fires the onPropertyChanged method on the loadingCallback, passing the same ObservableBoolean instance as an argument.

I've tried using an ArgumentCaptor and a custom ArgumentMatcher. Both methods successfully show that the onPropertyChange method has been called twice, however, neither of them maintain a history of what happened to the primitive boolean within the ObservableBoolean. Instead, I can only see the most recent value set on it, which is false.

How can I maintain a history of what happened to the primitive boolean within the ObservableBoolean? Again, I simply need to verify that it was set to true followed by false.

答:
You could create a stub which implements Observable.OnPropertyChangedCallback and records the invocations and then provides a public accessor to these recorded invocations. Your test would then use the public accessor to these recorded invocations when asserting.

For example:

```<code>    OnPropertyChangedCallbackStub loadingCallback = new OnPropertyChangedCallbackStub();
    viewModel.loading.addOnPropertyChangedCallback(loadingCallback);

    // invoke the code-under-test which, internally, invokes ...
    // loading.set(true);
    // loading.set(false);

    assertTrue(2, loadingCallback.recordedInvocations().size());
    assertTrue(loadingCallback.recordedInvocations().contains(true));
    assertTrue(loadingCallback.recordedInvocations().contains(false));
</code>```

Body:
I have an ObservableBoolean which is a pretty simple data container wrapping a primitive boolean. I want to use JUnit/Mockito to verify that the primitive boolean's value changes to true followed by false. I am setting up a mock OnPropertyChangedCallback like so:

Observable.OnPropertyChangedCallback loadingCallback = mock(Observable.OnPropertyChangedCallback.class);
viewModel.loading.addOnPropertyChangedCallback(loadingCallback);

I am then running the code under test which does:

loading.set(true);
loading.set(false);

Each of these calls fires the onPropertyChanged method on the loadingCallback, passing the same ObservableBoolean instance as an argument.

I've tried using an ArgumentCaptor and a custom ArgumentMatcher. Both methods successfully show that the onPropertyChange method has been called twice, however, neither of them maintain a history of what happened to the primitive boolean within the ObservableBoolean. Instead, I can only see the most recent value set on it, which is false.

How can I maintain a history of what happened to the primitive boolean within the ObservableBoolean? Again, I simply need to verify that it was set to true followed by false.

Body:
You could create a stub which implements Observable.OnPropertyChangedCallback and records the invocations and then provides a public accessor to these recorded invocations. Your test would then use the public accessor to these recorded invocations when asserting.

For example:

    OnPropertyChangedCallbackStub loadingCallback = new OnPropertyChangedCallbackStub();
    viewModel.loading.addOnPropertyChangedCallback(loadingCallback);

    // invoke the code-under-test which, internally, invokes ...
    // loading.set(true);
    // loading.set(false);

    assertTrue(2, loadingCallback.recordedInvocations().size());
    assertTrue(loadingCallback.recordedInvocations().contains(true));
    assertTrue(loadingCallback.recordedInvocations().contains(false));


来源: stackexchange

问:
java -update database by editing cells not working?
I'm having trouble updating data from the database by editing / changing cell values and clicking on the update button, but he can not change the database that I changed to the cell. it's still the same into the last value. </p>

<p>here is my code: </p>

```<code>    public void directlyup() {
       int col=tablesample.getSelectedColumn();
       int row=tablesample.getSelectedRow();
       int index;
       index = Integer.parseInt(tablesample.getModel().getValueAt(row, 0).toString());
        try {
            String sql ="UPDATE invoice SET description = ?,qty = ?,unitprice = ?"
                    + ",total = ? WHERE id ="+row;
            pst = conn.prepareStatement(sql);
            pst.setString(1, (String) tablesample.getValueAt(row, 1));
            pst.setString(2, (String) tablesample.getValueAt(row, 2));
            pst.setString(3, (String) tablesample.getValueAt(row, 3));
            pst.setString(4, (String) tablesample.getValueAt(row, 4));
            pst.execute();
            JOptionPane.showMessageDialog(null, "Successfully Updated");
        } catch (Exception e) {
         JOptionPane.showMessageDialog(null, e);
        }
    }
</code>```

答:
For CRUD operations on a data set, it is nice to use an intermediate table. This avoids the large number of queries being placed on large data sets.

Before giving my proposal to solve the problem, I would like to point out some remarks I have on the structure of the database:

The total field is obviously a calculated field. Such information is not good to put in the database. It is calculated upon request.

The whole set of data is obviously part of a document (invoice). So, there must be a field in the database that uniquely identifies the document to which the data relate.

Also, I want to say that such decisions are made for a specific database. In this case, my solution concerns mysql.

This is the DDL of the table on which the bottom code snippet runs

```<code>CREATE TABLE `invoice` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `invoice_id` int(10) unsigned NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `qty` double DEFAULT NULL,
  `unitprice` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB
</code>```

And this is the code that makes CRUD operations on a data set using the document id key (invoce_id).

```<code>public boolean save(long invoice_id, List<Invoice> list) throws SQLException {
    try(Connection connection = getConnection()) {
        try {
            connection.setAutoCommit(false);

            String query =
                    "create temporary table if not exists `invoice_tmp` (" +
                            "`id` int(10) unsigned NOT NULL," +
                            "`description` varchar(255) DEFAULT NULL," +
                            "`qty` double DEFAULT NULL," +
                            "`unitprice` double DEFAULT NULL)";

            connection.createStatement().executeUpdate(query);

            query = "insert into `invoice_tmp` values (?, ?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(query);
            for(Invoice invoice: list) {
                statement.setLong(1, invoice.getId());
                statement.setString(2, invoice.getDescription());
                statement.setDouble(3, invoice.getQty());
                statement.setDouble(4, invoice.getUnitPrice());

                statement.addBatch();
            }

            statement.executeBatch();
            statement.close();

            query =
                    "delete invoice from invoice " +
                    "left join invoice_tmp on (invoice.id = invoice_tmp.id) " +
                    "where invoice_id = ? and invoice_tmp.id is null";

            statement = connection.prepareStatement(query);
            statement.setLong(1, invoice_id);
            statement.executeUpdate();
            statement.close();

            query =
                    "update `invoice` " +
                    "join `invoice_tmp` using (`id`) " +
                    "set " +
                            "`invoice`.description = `invoice_tmp`.description, " +
                            "`invoice`.qty = `invoice_tmp`.qty, " +
                            "`invoice`.unitprice = `invoice_tmp`.unitprice";

            connection.createStatement().executeUpdate(query);

            query =
                    "insert into `invoice` (`invoice_id`, `description`, `qty`, `unitprice`) " +
                    "select ? as `invoice_id`, `description`, `qty`, `unitprice` from `invoice_tmp` where `id` = 0";

            statement = connection.prepareStatement(query);
            statement.setLong(1, invoice_id);
            statement.executeUpdate();
            statement.close();

            connection.createStatement().executeUpdate("drop table if exists `invoice_tmp`");

            connection.commit();
            return true;
        }
        catch (Exception e) {
            connection.rollback();
            throw e;
        }
    }
}
</code>```

this is a test project that demonstrates how the code above works.

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble updating data from the database by editing / changing cell values and clicking on the update button, but he can not change the database that I changed to the cell. it's still the same into the last value.

here is my code:

    public void directlyup() {
       int col=tablesample.getSelectedColumn();
       int row=tablesample.getSelectedRow();
       int index;
       index = Integer.parseInt(tablesample.getModel().getValueAt(row, 0).toString());
        try {
            String sql ="UPDATE invoice SET description = ?,qty = ?,unitprice = ?"
                    + ",total = ? WHERE id ="+row;
            pst = conn.prepareStatement(sql);
            pst.setString(1, (String) tablesample.getValueAt(row, 1));
            pst.setString(2, (String) tablesample.getValueAt(row, 2));
            pst.setString(3, (String) tablesample.getValueAt(row, 3));
            pst.setString(4, (String) tablesample.getValueAt(row, 4));
            pst.execute();
            JOptionPane.showMessageDialog(null, "Successfully Updated");
        } catch (Exception e) {
         JOptionPane.showMessageDialog(null, e);
        }
    }

Body:
For CRUD operations on a data set, it is nice to use an intermediate table. This avoids the large number of queries being placed on large data sets.

Before giving my proposal to solve the problem, I would like to point out some remarks I have on the structure of the database:

The total field is obviously a calculated field. Such information is not good to put in the database. It is calculated upon request.

The whole set of data is obviously part of a document (invoice). So, there must be a field in the database that uniquely identifies the document to which the data relate.

Also, I want to say that such decisions are made for a specific database. In this case, my solution concerns mysql.

This is the DDL of the table on which the bottom code snippet runs

CREATE TABLE `invoice` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `invoice_id` int(10) unsigned NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `qty` double DEFAULT NULL,
  `unitprice` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

And this is the code that makes CRUD operations on a data set using the document id key (invoce_id).

public boolean save(long invoice_id, List<Invoice> list) throws SQLException {
    try(Connection connection = getConnection()) {
        try {
            connection.setAutoCommit(false);

            String query =
                    "create temporary table if not exists `invoice_tmp` (" +
                            "`id` int(10) unsigned NOT NULL," +
                            "`description` varchar(255) DEFAULT NULL," +
                            "`qty` double DEFAULT NULL," +
                            "`unitprice` double DEFAULT NULL)";

            connection.createStatement().executeUpdate(query);

            query = "insert into `invoice_tmp` values (?, ?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(query);
            for(Invoice invoice: list) {
                statement.setLong(1, invoice.getId());
                statement.setString(2, invoice.getDescription());
                statement.setDouble(3, invoice.getQty());
                statement.setDouble(4, invoice.getUnitPrice());

                statement.addBatch();
            }

            statement.executeBatch();
            statement.close();

            query =
                    "delete invoice from invoice " +
                    "left join invoice_tmp on (invoice.id = invoice_tmp.id) " +
                    "where invoice_id = ? and invoice_tmp.id is null";

            statement = connection.prepareStatement(query);
            statement.setLong(1, invoice_id);
            statement.executeUpdate();
            statement.close();

            query =
                    "update `invoice` " +
                    "join `invoice_tmp` using (`id`) " +
                    "set " +
                            "`invoice`.description = `invoice_tmp`.description, " +
                            "`invoice`.qty = `invoice_tmp`.qty, " +
                            "`invoice`.unitprice = `invoice_tmp`.unitprice";

            connection.createStatement().executeUpdate(query);

            query =
                    "insert into `invoice` (`invoice_id`, `description`, `qty`, `unitprice`) " +
                    "select ? as `invoice_id`, `description`, `qty`, `unitprice` from `invoice_tmp` where `id` = 0";

            statement = connection.prepareStatement(query);
            statement.setLong(1, invoice_id);
            statement.executeUpdate();
            statement.close();

            connection.createStatement().executeUpdate("drop table if exists `invoice_tmp`");

            connection.commit();
            return true;
        }
        catch (Exception e) {
            connection.rollback();
            throw e;
        }
    }
}

this is a test project that demonstrates how the code above works.


问:
How to stick div to bottom page no scrolling
I have the following html struct:

```<code><body>
<div class="content">
   ...here long content
</div>
<div class="footer">
    ...here some rows for footer
</div>
</body>
</code>```

i want to strick the footer part to bottom page and the content page need to be in all the other place in page with scroll only in his part. !important! not scrolling in all page - only in content part.

something like this:

Is it possible?

Thanks!

答:
Simply do this :

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.content {
  height: calc(100vh - 50px);
  overflow: auto;
  background: red;
  padding: 50px;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: blue;
  color: #fff;
  z-index: 99;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum
  lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem
  ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum
  lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</div>
<div class="footer">
  ...here some rows for footer
</div></code>```

Body:
I have the following html struct:

   ...here long content

    ...here some rows for footer

i want to strick the footer part to bottom page and the content page need to be in all the other place in page with scroll only in his part. !important! not scrolling in all page - only in content part.

something like this:

Is it possible?

Thanks!

Body:
Simply do this :

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.content {
  height: calc(100vh - 50px);
  overflow: auto;
  background: red;
  padding: 50px;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: blue;
  color: #fff;
  z-index: 99;
}

<div class="content">
  lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum
  lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem
  ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum
  lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  lorem ipsumlorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</div>
<div class="footer">
  ...here some rows for footer
</div>


问:
Align text vertically inside a Text in Bootstrap 3/4
This is my website html:

```<code><div class="row">
      <a href="#" class="btn btn-danger btn-lg">Text
      </a>
</div>
</code>```

Do I have to change my html? or add a class in my css?

答:
Little changes in your html structure are required

      Text

```

Body:
This is my website html:

      Text

Do I have to change my html? or add a class in my css?

Body:
Little changes in your html structure are required

<div class="row">
    <div class="col">
      <a href="#" class="btn btn-danger btn-lg">Text
      </a>
    </div>
</div>


问:
.Rprofile not invoked under cron
I am running Ubuntu 16.04.3 LTS on the cloud. When I run a program from the command line with Rscript everything goes as expected. However, when I run the same program with Rscript through cron it appears that my .Rprofile file is not invoked. I have written a small program to demonstrate this problem:

```<code>test_cron = function() {
    #The next 3 lines are base R.
    sink('~/test_cron.out')
    on.exit(sink())
    cat('The date and time are:', as.character(Sys.time()), '\n')
    #Now try to access a personal option, set by .Rprofile.
    root = getOption('root')
    cat('Option root:', root, '\n')
}
test_cron()
</code>```

I run this from the command line using this command:

```<code>Rscript test_cron.r
</code>```

The cron_test.out file contains the following:

```<code>The date and time are: 2017-11-14 06:15:46
Option root: /home/ubuntu/_algi/
</code>```

The relevant line in crontab is as follows:

```<code>20 6 * * * /usr/bin/Rscript ~/test_cron.r
</code>```

When this is run by cron, cron_test.out contains the following:

```<code>The date and time are: 2017-11-14 06:20:01
Option root:
</code>```

Evidently the program, when run by cron, could not access my personal option 'root'. This is one among a number of experiments I have run that convince me that .Rprofile is not invoked under cron. Is there a fix for this?

Note: The R_PROFILE_USER environment variable is set to point to my .Rprofile file. Apparently, Rscript under cron ignores it.

答:
By default R looks for and runs .Rprofile files in the three locations in a specific order which are:

R_HOME: the directory in which R is installed

HOME:   the user’s home directory

R’s current working directory

.Rprofile in you current project/wd will override .Rprofile in HOME and R_HOME and .Rprofile in HOME will override R_HOME.

So to to create a project-specific start-up script, simply create a .Rprofile file in the project’s root directory.

It looks like in your case that R uses a different .Rprofile file when a script is started by cron than starting a script from the command line.

Title: .Rprofile not invoked under cron

Body:
I am running Ubuntu 16.04.3 LTS on the cloud. When I run a program from the command line with Rscript everything goes as expected. However, when I run the same program with Rscript through cron it appears that my .Rprofile file is not invoked. I have written a small program to demonstrate this problem:

test_cron = function() {
    #The next 3 lines are base R.
    sink('~/test_cron.out')
    on.exit(sink())
    cat('The date and time are:', as.character(Sys.time()), '\n')
    #Now try to access a personal option, set by .Rprofile.
    root = getOption('root')
    cat('Option root:', root, '\n')
}
test_cron()

I run this from the command line using this command:

Rscript test_cron.r

The cron_test.out file contains the following:

The date and time are: 2017-11-14 06:15:46
Option root: /home/ubuntu/_algi/

The relevant line in crontab is as follows:

20 6 * * * /usr/bin/Rscript ~/test_cron.r

When this is run by cron, cron_test.out contains the following:

The date and time are: 2017-11-14 06:20:01
Option root:

Evidently the program, when run by cron, could not access my personal option 'root'. This is one among a number of experiments I have run that convince me that .Rprofile is not invoked under cron. Is there a fix for this?

Note: The R_PROFILE_USER environment variable is set to point to my .Rprofile file. Apparently, Rscript under cron ignores it.


问:
Send data WITHIN JSON via AJAX
I want to append another home_address within the array address.

```<code>  "fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    }
  ]
}
</code>```

The problem is the code gets added to end.

```<code>"fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    },
    {
      "aid": 4,
      "home_address": "5804",
      "id": 2
    }
  ]
}
</code>```

Here is my sample ajax code

```<code>var addnumber = {
                  "aid": 4,
                  "home_address": "5804"
            }

     $.ajax({
                    type:'POST',
                    url: 'http://localhost:3000/fieldlist',
                    data: JSON.stringify(addnumber),
                    contentType: 'application/json',
                    dataType: 'json'

        });
</code>```

Is there anyway I can append within the address array and not after the code block? Or should I change the structure of my JSON?

答: Thanks guys, I think I figured it out. I'm new to ajax, sorry. First off... I have to use a PUT request. I thought there was only post. 2nd, I have to use the correct route to the json url. I was lost until I posted this so thanks for the swift responses. </p>

Title: Send data WITHIN JSON via AJAX

Body:
I want to append another home_address within the array address.

  "fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    }
  ]
}

The problem is the code gets added to end.

"fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    },
    {
      "aid": 4,
      "home_address": "5804",
      "id": 2
    }
  ]
}

Here is my sample ajax code

var addnumber = {
                  "aid": 4,
                  "home_address": "5804"
            }

     $.ajax({
                    type:'POST',
                    url: 'http://localhost:3000/fieldlist',
                    data: JSON.stringify(addnumber),
                    contentType: 'application/json',
                    dataType: 'json'

        });

Is there anyway I can append within the address array and not after the code block? Or should I change the structure of my JSON?


问:
private initialized variable not initializing
I have a datacontract on an inherited, partial class like this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
    {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}
</code>```

For some reason, the _unproxized is never set to true;  Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.

答: My suspicion is you are using web/service references. In this case the code (private variable) never gets to the client.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a datacontract on an inherited, partial class like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
    {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}

For some reason, the _unproxized is never set to true;  Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.


问:
Poco::Path compiles with const wchar_t* but behaves unexpectedly
Working with Poco::Path I've found a very curious error. See following code:

```<code>#include <iostream>
#include <string>
#include <Poco/Path.h>

int main()
{
  std::wstring a_path = L"c:\\temp";

  //Poco::Path from_wstring(a_path); // ERROR: fails to compile, expected
  Poco::Path from_wchar_t(a_path.c_str()); // compiles... unexpected

  std::cout << from_wchar_t.toString() << std::endl;

  return 0;
}
</code>```

But the output of the above program is (in Windows):

\

instead of the expected:

c:\temp

Reviewing the Poco::Path documentation I see no constructor expecting std::wstring (that's why the first path fails) nor const wchar_t*, only from std::string and const char* (both UTF-8).

How is it compiling with const wchar_t* and why the unexpected output (wrong path)?

答:
When creating the mvce for this question I figured out the problem. I've decided to document it here in case it is helpful for somebody else.

The code snippet shown in the question is part of a huge project so I was missing a compilation warning:

warning C4800: 'const wchar_t *' : forcing value to bool 'true' or 'false' (performance warning)

Then I realized that there is a constructor Poco::Path::Path(bool absolute) and that the compiler was making the cast from pointer to bool automatically, producing then the unexpected behavior. The \ of the output corresponds to an empty absolute path, its initial value when using such constructor.

For those interested in a workaround, I'm now using a UTF-16 to UTF-8 conversion:

```<code>#include <boost/locale/encoding.hpp>
// ...
std::wstring a_path = L"c:\\temp";
Poco::Path utf8_path(boost::locale::conv::utf_to_utf<char>(a_path));
</code>```

Body:
Working with Poco::Path I've found a very curious error. See following code:

#include <iostream>
#include <string>
#include <Poco/Path.h>

int main()
{
  std::wstring a_path = L"c:\\temp";

  //Poco::Path from_wstring(a_path); // ERROR: fails to compile, expected
  Poco::Path from_wchar_t(a_path.c_str()); // compiles... unexpected

  std::cout << from_wchar_t.toString() << std::endl;

  return 0;
}

But the output of the above program is (in Windows):

\

instead of the expected:

c:\temp

Reviewing the Poco::Path documentation I see no constructor expecting std::wstring (that's why the first path fails) nor const wchar_t*, only from std::string and const char* (both UTF-8).

How is it compiling with const wchar_t* and why the unexpected output (wrong path)?

Body:
When creating the mvce for this question I figured out the problem. I've decided to document it here in case it is helpful for somebody else.

The code snippet shown in the question is part of a huge project so I was missing a compilation warning:

warning C4800: 'const wchar_t *' : forcing value to bool 'true' or 'false' (performance warning)

Then I realized that there is a constructor Poco::Path::Path(bool absolute) and that the compiler was making the cast from pointer to bool automatically, producing then the unexpected behavior. The \ of the output corresponds to an empty absolute path, its initial value when using such constructor.

For those interested in a workaround, I'm now using a UTF-16 to UTF-8 conversion:

#include <boost/locale/encoding.hpp>
// ...
std::wstring a_path = L"c:\\temp";
Poco::Path utf8_path(boost::locale::conv::utf_to_utf<char>(a_path));


问:
Is it possible to have multiple styles inside a TextView?
Is it possible to set multiple styles for different pieces of text inside a TextView?

For instance, I am setting the text as follows:

```<code>tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);
</code>```

Is it possible to have a different style for each text element? E.g., line1 bold, word1 italic, etc.

The developer guide's Common Tasks and How to Do Them in Android includes Selecting, Highlighting, or Styling Portions of Text:

```<code>// Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text);

// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");

// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.

// Get the EditText's internal text storage
Spannable str = vw.getText();

// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

But that uses explicit position numbers inside the text. Is there a cleaner way to do this?

答:
Me Too

How about using some beautiful markup with Kotlin and Anko -

```<code>import org.jetbrains.anko.*
override fun onCreate(savedInstanceState: Bundle?) {
    title = "Created with Beautiful Markup"
    super.onCreate(savedInstanceState)

    verticalLayout {
        editText {
            hint = buildSpanned {
                append("Italic, ", Italic)
                append("highlighted", backgroundColor(0xFFFFFF00.toInt()))
                append(", Bold", Bold)
            }
        }
    }
}
</code>```

Body:
Is it possible to set multiple styles for different pieces of text inside a TextView?

For instance, I am setting the text as follows:

tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);

Is it possible to have a different style for each text element? E.g., line1 bold, word1 italic, etc.

The developer guide's Common Tasks and How to Do Them in Android includes Selecting, Highlighting, or Styling Portions of Text:

// Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text);

// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");

// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.

// Get the EditText's internal text storage
Spannable str = vw.getText();

// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

But that uses explicit position numbers inside the text. Is there a cleaner way to do this?

Body:
Me Too

How about using some beautiful markup with Kotlin and Anko -

import org.jetbrains.anko.*
override fun onCreate(savedInstanceState: Bundle?) {
    title = "Created with Beautiful Markup"
    super.onCreate(savedInstanceState)

    verticalLayout {
        editText {
            hint = buildSpanned {
                append("Italic, ", Italic)
                append("highlighted", backgroundColor(0xFFFFFF00.toInt()))
                append(", Bold", Bold)
            }
        }
    }
}


问:
How do I wrap a function with an object in a class in javascript?
Let's say I have a class named Human.

```<code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}
</code>```

and I have some functions for the class such as greeting and introduce. So I create them like this:

```<code>Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}
</code>```

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

```<code>Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}
</code>```

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

```<code>var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();
</code>```

答:
You can bind the context of this in the function in its constructor

```<code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.speak.introduce = this.speak.introduce.bind(this);
}
</code>```

This way, this in your introduce function will always be the current instance of Human

Body:
Let's say I have a class named Human.

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}

and I have some functions for the class such as greeting and introduce. So I create them like this:

Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();

Body:
You can bind the context of this in the function in its constructor

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.speak.introduce = this.speak.introduce.bind(this);
}

This way, this in your introduce function will always be the current instance of Human


问:
In spring why the interface is injected?
In spring why the interface is injected rather than the class implementing the interface?</p>

答:
In fact even if you use interface a class is injected. Spring looks for a bean - class which implements the interface.

In some cases like e.g. Spring Data dynamic proxy is created for the interfaces which in fact a class to listen interface's methods calls and do some logic on the calls.

If you set a breakpoint and check what is really injected you will find a class (either your class or some Proxy object)


问:
CommandError: You appear to have guava-jdk5 on your project buildScript or buildSrc classpath
Hi i had updated my IDE "Android Studio 3.0" and Build.gradle too but i encountered a problem in Build Build.gradle (Module APP)

Build.gradle (Module APP) after Update it became like this

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.abdeljalilkchih.learnarabicforkids"
        minSdkVersion 12
        versionName "\n" +
                "        targetSdkVersion 26\n" +
                "        versionCode 1515.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.akexorcist:RoundCornerProgressBar:2.0.3'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Message Gradle sync

```<code>    Error:(1, 0) You appear to have guava-jdk5 on your project buildScript or buildSrc classpath.
This is likely a transitive dependency of another gradle plugin.Run the buildEnvironment task to find out more.
See https://issuetracker.google.com/38419426#comment8 for a workaround.
</code>```

答:
Hi You should update the application level gradle file. By doing this, the issue will come. </p>

```<code>classpath ('com.google.firebase:firebase-plugins:1.0.5') {
   exclude group: 'com.google.guava', module: 'guava-jdk5'
}
</code>```

Body:
Hi i had updated my IDE "Android Studio 3.0" and Build.gradle too but i encountered a problem in Build Build.gradle (Module APP)

Build.gradle (Module APP) after Update it became like this

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.abdeljalilkchih.learnarabicforkids"
        minSdkVersion 12
        versionName "\n" +
                "        targetSdkVersion 26\n" +
                "        versionCode 1515.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.akexorcist:RoundCornerProgressBar:2.0.3'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Message Gradle sync

    Error:(1, 0) You appear to have guava-jdk5 on your project buildScript or buildSrc classpath.
This is likely a transitive dependency of another gradle plugin.Run the buildEnvironment task to find out more.
See https://issuetracker.google.com/38419426#comment8 for a workaround.

Body:
Hi You should update the application level gradle file. By doing this, the issue will come.

classpath ('com.google.firebase:firebase-plugins:1.0.5') {
   exclude group: 'com.google.guava', module: 'guava-jdk5'
}


问:
3rd party jar which can not be put in any repository works with maven project
There is a 3rd party jar which is dependent by many programs on the target machine. That jar file is named as abc.jar.

I can add the jar file to the local repository as abc-1.0.jar and package my project. But that means I must manually replace abc-1.0.jar when abc.jar updates. Here are my questions:

1.Is it possible to just use abc.jar when development with Intellij IDEA? I tried add the abc.jar to the External Libraries with dependency adding. But the editor can not recognize classes within abc.jar

2.If the answer is yes, What should I do to let the war file use the system level's abc.jar not the bundled within the ear?

Many thanks

答:
Find this?

correct-way-to-add-external-jars-lib-jar-to-an-intellij-idea-project

or compile files in Gradle

```<code>compile files("src/main/resources/libs/sqljdbc4.jar")
</code>```

put jar file to path

Body:
Find this?

correct-way-to-add-external-jars-lib-jar-to-an-intellij-idea-project

or compile files in Gradle

compile files("src/main/resources/libs/sqljdbc4.jar")

put jar file to path


问:
SQL - check if column exists within stored procedure (table is variable)
This doesn't seem to have been answered anywhere (although very similar cases have been answered)...

I have an issue where I am trying to update a column's value in a table within a stored procedure. However, I pass more than one table to this stored procedure and some tables have a certain column and others don't. Thus I need to check if the column exists before I run this update. Now, because it's in a stored procedure, SQL seems to be parsing the entire chunk of code up front and complains that this column doesn't exist.

Code:

```<code>IF COL_LENGTH(''DBName' + @date+ '..' + @TableName + @date+''', ''ColumnName' + @specifictocolumn + 'restofcolumnname'') IS NOT NULL
    update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0
</code>```

Alternatively

```<code>IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''ColumnName' + @specifictocolumn + 'restofcolumnname '' AND Object_ID = Object_ID(N''DBName' + @date+ '..' + @TableName + @date+'''))
    update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0
</code>```

Both of these give the error (column name removed for IP purposes):

Msg 207, Level 16, State 1, Line 6
  Invalid column name 'ColumnName'.

There is a question on stack overflow called "Disable TSQL script check" that I looked at, but they suggest that you call the check of the column outside of the dynamic sql and then only execute if it passes the check. This won't work for me because part of the if-statement has variables in it that need to be in dynamic sql.

答:
You can still split the dynamic SQL in 2 parts:

check if the column exists

do the actual update when 1. returns true

you'll probably want to use sp_executesql for this and an OUTPUT parameter.

Something along the lines of this:

```<code>DECLARE @sql nvarchar(max),
        @result int

SELECT @sql = 'SELECT @col_length = COL_LENGTH(''DBName' + @date + '..' + @TableName + @date + ''', ''ColumnName' + @specifictocolumn + 'restofcolumnname'')'

EXEC sp_executesql @stmt = @sql,
                   @params = N'@col_length int OUTPUT',
                   @col_length = @result OUTPUT

IF @result IS NOT NULL
    BEGIN
        EXEC ('update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0')
    END
</code>```

Or you could go 'dynamic inside dynamic', but will become a mess very quickly.

Body:
This doesn't seem to have been answered anywhere (although very similar cases have been answered)...

I have an issue where I am trying to update a column's value in a table within a stored procedure. However, I pass more than one table to this stored procedure and some tables have a certain column and others don't. Thus I need to check if the column exists before I run this update. Now, because it's in a stored procedure, SQL seems to be parsing the entire chunk of code up front and complains that this column doesn't exist.

Code:

IF COL_LENGTH(''DBName' + @date+ '..' + @TableName + @date+''', ''ColumnName' + @specifictocolumn + 'restofcolumnname'') IS NOT NULL
    update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0

Alternatively

IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N''ColumnName' + @specifictocolumn + 'restofcolumnname '' AND Object_ID = Object_ID(N''DBName' + @date+ '..' + @TableName + @date+'''))
    update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0

Both of these give the error (column name removed for IP purposes):

Msg 207, Level 16, State 1, Line 6
  Invalid column name 'ColumnName'.

There is a question on stack overflow called "Disable TSQL script check" that I looked at, but they suggest that you call the check of the column outside of the dynamic sql and then only execute if it passes the check. This won't work for me because part of the if-statement has variables in it that need to be in dynamic sql.

Body:
You can still split the dynamic SQL in 2 parts:

check if the column exists

do the actual update when 1. returns true

you'll probably want to use sp_executesql for this and an OUTPUT parameter.

Something along the lines of this:

DECLARE @sql nvarchar(max),
        @result int

SELECT @sql = 'SELECT @col_length = COL_LENGTH(''DBName' + @date + '..' + @TableName + @date + ''', ''ColumnName' + @specifictocolumn + 'restofcolumnname'')'

EXEC sp_executesql @stmt = @sql,
                   @params = N'@col_length int OUTPUT',
                   @col_length = @result OUTPUT

IF @result IS NOT NULL
    BEGIN
        EXEC ('update  DBName' + @date+ '..' + @TableName + @date+ ' set ColumnName' + @specifictocolumn + 'restofcolumnname = 0')
    END

Or you could go 'dynamic inside dynamic', but will become a mess very quickly.


答:
Make Speak to A Class

Make Speak to a class, because logical grouping of variables and functionality in OOP are classes.

Speak

```<code>function Speak(human) {
    this.human = human
}

Speak.prototype.greeting = function () {
    // ...
}

Speak.prototype.introduce = function () {
    // ..
}
</code>```

Human

```<code>function Human(name, gender, age, personality, greetWord) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.speak  = new Speak(this)
}
</code>```

Example

function Human(name, gender, age, personality, greetWord) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.greetWord = greetWord;
    this.speak  = new Speak(this)
}

function Speak(human) {
    this.human = human
}

Speak.prototype.greeting = function () {
    alert(this.human.greetWord + "!");
}

Speak.prototype.introduce = function () {
    var _gender = { "M": "Boy", "F": "Girl" };
    switch (this.human.personality) {
        case "passionate":
            alert("Hi, how are you? My name is " + this.human.name + ". I'm " + this.human.age + " years old " + _gender[this.human.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.human.name + ". What you want? ");
            break;
    }
}

var peter = new Human('Peter', 'M', 35, 'aggressive', 'Hi')
peter.speak.greeting()
peter.speak.introduce()```
</div>
</div>
</p>

<hr>

<p>An other way to solve the solution would be to use apply.</p>

<h1>Apply</h1>

<blockquote>
  <p>The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).</p>
</blockquote>

<h2>Code</h2>

```var peter = new Human('Peter', 'M', 35, 'aggressive')
console.log(peter.speak.introduce.apply(peter))
```

<h2>Example</h2>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}

Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}

var peter = new Human('Peter', 'M', 35, 'aggressive')
console.log(peter.speak.introduce.apply(peter))</code>```

Title: How do I wrap a function with an object in a class in javascript?

Body:
Make Speak to A Class

Make Speak to a class, because logical grouping of variables and functionality in OOP are classes.

Speak

function Speak(human) {
    this.human = human
}

Speak.prototype.greeting = function () {
    // ...
}

Speak.prototype.introduce = function () {
    // ..
}

Human

function Human(name, gender, age, personality, greetWord) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.speak  = new Speak(this)
}

Example

function Human(name, gender, age, personality, greetWord) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
    this.greetWord = greetWord;
    this.speak  = new Speak(this)
}

function Speak(human) {
    this.human = human
}

Speak.prototype.greeting = function () {
    alert(this.human.greetWord + "!");
}

Speak.prototype.introduce = function () {
    var _gender = { "M": "Boy", "F": "Girl" };
    switch (this.human.personality) {
        case "passionate":
            alert("Hi, how are you? My name is " + this.human.name + ". I'm " + this.human.age + " years old " + _gender[this.human.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.human.name + ". What you want? ");
            break;
    }
}

var peter = new Human('Peter', 'M', 35, 'aggressive', 'Hi')
peter.speak.greeting()
peter.speak.introduce()

An other way to solve the solution would be to use apply.

Apply

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

Code

var peter = new Human('Peter', 'M', 35, 'aggressive')
console.log(peter.speak.introduce.apply(peter))

Example

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}

Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}

var peter = new Human('Peter', 'M', 35, 'aggressive')
console.log(peter.speak.introduce.apply(peter))


问:
Google Maps PHP CURL issue "Your client has issued a malformed or illegal request. That’s all we know."
I have a function which returns the coordinates of an address using CURL and the Google Maps API.

The code is as follows:

```<code>function get_coordinates($address_string) {

    $address = urlencode($address_string);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&key=" . $api_key;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response);
    $status = $response_a->status;

    return $response;

}
</code>```

The code works fine for me and 99% of the web servers I use it on - but for around 1% of servers Google returns the error message:

```<code>Your client has issued a malformed or illegal request. That’s all we know.
</code>```

I've checked and the Google API key is correct, PHP CURL is enabled and the PHP version matches PHP versions it is working on.

Can anyone think of any other things which could be causing Google to return this message?

答:
Its Because of your $address variable has address with white space, use str_replace and replace the white space with + sign.

It will work, i was facing same problem and fixed this way.

Body:
I have a function which returns the coordinates of an address using CURL and the Google Maps API.

The code is as follows:

function get_coordinates($address_string) {

    $address = urlencode($address_string);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&key=" . $api_key;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response);
    $status = $response_a->status;

    return $response;

}

The code works fine for me and 99% of the web servers I use it on - but for around 1% of servers Google returns the error message:

Your client has issued a malformed or illegal request. That’s all we know.

I've checked and the Google API key is correct, PHP CURL is enabled and the PHP version matches PHP versions it is working on.

Can anyone think of any other things which could be causing Google to return this message?


问:
Sub-domain as sub-directory in URL
We need solution for our new server, we have one main domain e.g. example.com and its hosted on VPS this website is in ASP.Net with blog e.g. example.com/blog , The blog is in sub-directory and using Wordpress. We got new server and we want to move our blog on new VPS so we created sub-domain on main domain e.g. blog.example.com and change the A Record in control panel and blog.example.com is working fine, but we want to show URL like this example.com/blog/ is there a any way we can show sub-domain as a sub-directory ? The main website will remain host on main server we only need to work with sub-domain. So it shows all links like, example.com/blog/post-name/</p>

答:
Try this in your .htaccess:

```<code>RewriteEngine On
RewriteRule ^blog/(.*) http://blog.example.com/$1 [P,L]
</code>```

It uses mod_proxy (and will fail if it's not available) to reverse proxy the traffic beneath /blog/. Obviously, if you have a lot of traffic or bad connection between the two servers, you will want something that does cache, but usually works quite good.

You will probably have to set

```<code>define('WP_HOME',    'http://example.com/blog');
define('WP_SITEURL', 'http://example.com/blog');
</code>```

in your wp-config.php so the internal links point to the URL you want them to work as.

Title: Sub-domain as sub-directory in URL

Body:
Try this in your .htaccess:

RewriteEngine On
RewriteRule ^blog/(.*) http://blog.example.com/$1 [P,L]

It uses mod_proxy (and will fail if it's not available) to reverse proxy the traffic beneath /blog/. Obviously, if you have a lot of traffic or bad connection between the two servers, you will want something that does cache, but usually works quite good.

You will probably have to set

define('WP_HOME',    'http://example.com/blog');
define('WP_SITEURL', 'http://example.com/blog');

in your wp-config.php so the internal links point to the URL you want them to work as.


问:
Reading integers from scanner to array Java
i'm having problems with a simple exercise, i need to create a  method
readArray
that should read (using a scanner)
n
integers and return an array of length
n
storing the integers in the order they were read. Before reading integers, the method should print
n
to indicate how many integers are expected. The method main should be created in a way that x , y and z are produced by calls to read array

I am getting a compilation error "The method readArray(int) in the type ReadCompareArrays is not applicable for the arguments ()" how should I correct the code?

```<code>import java.util.Scanner;
public class ReadCompareArrays {
    public static int[] readArray(int n)
    {
        System.out.println("Insert 3 integers");
        Scanner s = new Scanner(System.in);
        int count = s.nextInt();
        int[] array = new int[count];
        return array;
    }
    public static boolean equalArrays (int [] a, int [] b)
    {
        boolean result = true;
        for(int i = 0; i < b.length; i++)
            {
                if (a[i] == b[i++] && a.length == b.length) {
                    result = true;
                }
                else {result = false;}
            }
        return result;
    }
    public static void main (String[] args)
    {
        int[] x = readArray();
        int[] y = readArray();
        int[] z = readArray();
        System.out.print(equalArrays(x,y));
        System.out.print(equalArrays(y,z));
    }
}
</code>```

答:
Your readArray method is wrong. It just instantiates the array with how many elements you set count up to and then just returns it, you also need to read the elements before returning the array. Also the equalArrays can be much simpler.
 What the code should look like is similar to this:</p>

```<code>import java.util.Scanner;
import java.util.Arrays;
    public class ReadCompareArrays {
    public static int[] readArray()
    {
        Scanner s = new Scanner(System.in);
        System.out.println("hoW many integeres do you want in the array?");
        int count = s.nextInt();
        System.out.println("count is: " + count);
        int[] array = new int[count];
        for(int i = 0; i < count; i++)
        array[i] = s.nextInt();
        return array;
    }
        public static boolean equalArrays (int [] a, int [] b)
        {
            if(Arrays.equals(a,b))
               return true;
            return false;
        }
        public static void main (String[] args)
        {
            int[] x = readArray();
            int[] y = readArray();
            int[] z = readArray();
            System.out.print(equalArrays(x,y));
            System.out.print(equalArrays(y,z));
        }
    }
</code>```

Body:
i'm having problems with a simple exercise, i need to create a  method
readArray
that should read (using a scanner)
n
integers and return an array of length
n
storing the integers in the order they were read. Before reading integers, the method should print
n
to indicate how many integers are expected. The method main should be created in a way that x , y and z are produced by calls to read array

I am getting a compilation error "The method readArray(int) in the type ReadCompareArrays is not applicable for the arguments ()" how should I correct the code?

import java.util.Scanner;
public class ReadCompareArrays {
    public static int[] readArray(int n)
    {
        System.out.println("Insert 3 integers");
        Scanner s = new Scanner(System.in);
        int count = s.nextInt();
        int[] array = new int[count];
        return array;
    }
    public static boolean equalArrays (int [] a, int [] b)
    {
        boolean result = true;
        for(int i = 0; i < b.length; i++)
            {
                if (a[i] == b[i++] && a.length == b.length) {
                    result = true;
                }
                else {result = false;}
            }
        return result;
    }
    public static void main (String[] args)
    {
        int[] x = readArray();
        int[] y = readArray();
        int[] z = readArray();
        System.out.print(equalArrays(x,y));
        System.out.print(equalArrays(y,z));
    }
}

Body:
Your readArray method is wrong. It just instantiates the array with how many elements you set count up to and then just returns it, you also need to read the elements before returning the array. Also the equalArrays can be much simpler.
 What the code should look like is similar to this:

import java.util.Scanner;
import java.util.Arrays;
    public class ReadCompareArrays {
    public static int[] readArray()
    {
        Scanner s = new Scanner(System.in);
        System.out.println("hoW many integeres do you want in the array?");
        int count = s.nextInt();
        System.out.println("count is: " + count);
        int[] array = new int[count];
        for(int i = 0; i < count; i++)
        array[i] = s.nextInt();
        return array;
    }
        public static boolean equalArrays (int [] a, int [] b)
        {
            if(Arrays.equals(a,b))
               return true;
            return false;
        }
        public static void main (String[] args)
        {
            int[] x = readArray();
            int[] y = readArray();
            int[] z = readArray();
            System.out.print(equalArrays(x,y));
            System.out.print(equalArrays(y,z));
        }
    }


问:
Reset scroll position on component re-render
Have a look at this pen: https://codepen.io/segmentationfaulter/pen/XzgJyV

I am also pasting the code here for convenience. Upon opening the pen above, you will see that a slider is rendered. Scroll the slider right, and the click on change slides button, you will see that slider is re-rendered with different numbers, but the scroll position of the slider is not reset. Why is the scroll position not reset? Thanks

function SliderElement({
  elementContent
}) {
  return (
 {
      elementContent
    }

  )
}

class Slider extends React.Component {
    render() {
        return ( <
          div className = 'slider' > {
            this.props.sliderContentArray.map(elementContent => < SliderElement elementContent = {
                elementContent
              }
              />)} <
              /div>
            )
          }
        }

        class SliderContainer extends React.Component {
          constructor() {
            super()
            this.slidersContent = [
              [1, 2, 3, 4, 5, 6, 7, 8],
              [9, 10, 11, 12, 13, 14, 15, 16]
            ]

            this.state = {
              currentSliderIndex: 0
            }
          }
          switchSlider() {
            this.setState((prevState) => {
              if (prevState.currentSliderIndex === 0) {
                return {
                  currentSliderIndex: 1
                }
              } else {
                return {
                  currentSliderIndex: 0
                }
              }
            })
          }
          render() {
            return ( <
              div >
              <
              Slider sliderContentArray = {
                this.slidersContent[this.state.currentSliderIndex]
              }
              /> <
              button className = 'slider-switch-button'
              onClick = {
                this.switchSlider.bind(this)
              } >
              change slides <
              /button> <
              /div>
            )
          }
        }

        ReactDOM.render( <
          SliderContainer / > ,
          document.getElementById('root')
        );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider {
  display: flex;
  overflow: scroll;
}

.slider-element {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 20%;
  height: 100px;
  background: yellow;
}

.slider-element+.slider-element {
  margin-left: 10px;
}

.slider-switch-button {
  margin-top: 10px;
}</code>```

```

答:
You need to manually update the scroll position using the scrollLeft property each time the component is updated. You can do this inside the componentDidUpdate of the Slider component:

```<code>  componentDidUpdate() {
    ReactDOM.findDOMNode(this).scrollLeft = 0;
  }
</code>```

Find the working pen here: https://codepen.io/danegit/pen/xPrayY?editors=0010

Body:
Have a look at this pen: https://codepen.io/segmentationfaulter/pen/XzgJyV

I am also pasting the code here for convenience. Upon opening the pen above, you will see that a slider is rendered. Scroll the slider right, and the click on change slides button, you will see that slider is re-rendered with different numbers, but the scroll position of the slider is not reset. Why is the scroll position not reset? Thanks

function SliderElement({
  elementContent
}) {
  return (
 {
      elementContent
    }

  )
}

class Slider extends React.Component {
    render() {
        return ( <
          div className = 'slider' > {
            this.props.sliderContentArray.map(elementContent => < SliderElement elementContent = {
                elementContent
              }
              />)} <
              /div>
            )
          }
        }

        class SliderContainer extends React.Component {
          constructor() {
            super()
            this.slidersContent = [
              [1, 2, 3, 4, 5, 6, 7, 8],
              [9, 10, 11, 12, 13, 14, 15, 16]
            ]

            this.state = {
              currentSliderIndex: 0
            }
          }
          switchSlider() {
            this.setState((prevState) => {
              if (prevState.currentSliderIndex === 0) {
                return {
                  currentSliderIndex: 1
                }
              } else {
                return {
                  currentSliderIndex: 0
                }
              }
            })
          }
          render() {
            return ( <
              div >
              <
              Slider sliderContentArray = {
                this.slidersContent[this.state.currentSliderIndex]
              }
              /> <
              button className = 'slider-switch-button'
              onClick = {
                this.switchSlider.bind(this)
              } >
              change slides <
              /button> <
              /div>
            )
          }
        }

        ReactDOM.render( <
          SliderContainer / > ,
          document.getElementById('root')
        );

.slider {
  display: flex;
  overflow: scroll;
}

.slider-element {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 20%;
  height: 100px;
  background: yellow;
}

.slider-element+.slider-element {
  margin-left: 10px;
}

.slider-switch-button {
  margin-top: 10px;
}

Body:
You need to manually update the scroll position using the scrollLeft property each time the component is updated. You can do this inside the componentDidUpdate of the Slider component:

  componentDidUpdate() {
    ReactDOM.findDOMNode(this).scrollLeft = 0;
  }

Find the working pen here: https://codepen.io/danegit/pen/xPrayY?editors=0010


问:
How to change mat-icon size in Material
This question comes from the Material2 Github repo.

I still have problems to style a Material component that is wrapped in a custom component.

I have a <logo> component that contains <md-icon svgIcon="logo"></md-icon>

Adding:

```<code>:host {
   .mat-icon {
    width: 100px;
    height: 100px;
    font-size: 56px;
  }
}
</code>```

Will not apply to the Material component inside my custom component.

答:
UPDATE: 2019-05-22

Newer versions of Material Design has the option to set [inline]="true" as a property on the HTML element.

I would recommend using that approach instead.

```<code><mat-icon svgIcon="thumbs-up" inline="true"></mat-icon>
</code>```

When using this, the icon will inherit from the parent container!

GLHF! :)

I have been getting some questions about this so I just wanted to make a clearer example of how to use it...

/* 1. Add this mixin to a "global" scss */

@mixin md-icon-size($size: 24px) {
  font-size: $size;
  height: $size;
  width: $size;
  line-height: $size;
}

/* 2. Then use it like this in you component scss */

mat-icon {
  @include md-icon-size(32px);
}
```

<p>example usage</p>

<pre class="lang-html prettyprint-override"><code><mat-icon class="myIcon" svgIcon="search"></mat-icon>
</code>```

:host {
  .myIcon {
    &mat-icon {
      @include md-icon-size(32px);
    }
  }
}
```

ContentLicense: CC BY-SA 4.0

Title: How to change mat-icon size in Material

Body:
This question comes from the Material2 Github repo.

I still have problems to style a Material component that is wrapped in a custom component.

I have a <logo> component that contains <md-icon svgIcon="logo"></md-icon>

Adding:

:host {
   .mat-icon {
    width: 100px;
    height: 100px;
    font-size: 56px;
  }
}

Will not apply to the Material component inside my custom component.

Body:
UPDATE: 2019-05-22

Newer versions of Material Design has the option to set [inline]="true" as a property on the HTML element.

I would recommend using that approach instead.

<mat-icon svgIcon="thumbs-up" inline="true"></mat-icon>

When using this, the icon will inherit from the parent container!

GLHF! :)

I have been getting some questions about this so I just wanted to make a clearer example of how to use it...

/* 1. Add this mixin to a "global" scss */

@mixin md-icon-size($size: 24px) {
  font-size: $size;
  height: $size;
  width: $size;
  line-height: $size;
}

/* 2. Then use it like this in you component scss */

mat-icon {
  @include md-icon-size(32px);
}

example usage

<mat-icon class="myIcon" svgIcon="search"></mat-icon>

:host {
  .myIcon {
    &mat-icon {
      @include md-icon-size(32px);
    }
  }
}


问:
Crontab - "bad day-of-week" error, when trying to schedule a task to run each other day-of-week using "dow/2"
I try to schedule a task in Ubuntu 16.04 using crontab:

```<code>45 2 * * 4/2 sh /var/lib/libvirt/images/backups/backup_res.sh
</code>```

I want it to be executed every other Thursday at 2:45AM.
However, I keep getting bad day-of-week error.
If I remove /2, it works fine.
What could be the problem?

答:
I think the best way is:

```<code>45 2 * * Thu expr `date +\%s` / 604800 \% 2 >/dev/null || sh /var/lib/libvirt/images/backups/backup_res.sh
</code>```

please see this Q&A

Body:
I try to schedule a task in Ubuntu 16.04 using crontab:

45 2 * * 4/2 sh /var/lib/libvirt/images/backups/backup_res.sh

I want it to be executed every other Thursday at 2:45AM.
However, I keep getting bad day-of-week error.
If I remove /2, it works fine.
What could be the problem?

Body:
I think the best way is:

45 2 * * Thu expr `date +\%s` / 604800 \% 2 >/dev/null || sh /var/lib/libvirt/images/backups/backup_res.sh

please see this Q&A


问:
Result of GAMMA underflows its kind
I would like to calculate gamma(-170.1) using the program below:

```<code>program arithmetic
! program to do a calculation
real(8) :: x
x = GAMMA(-170.1)
print *, x
end program
</code>```

but I get the error:

test.f95:4.10:

x = GAMMA(-170.1)
           1
  Error: Result of GAMMA underflows its kind at (1)

when I compile with gfortran. According to Maple gamma(-170.1) = 5.191963205*10^(-172) which I think should be within the range of the exponent of the variable x as I've defined it.

答:
The below modification of your program should work. Remember that in Fortran the RHS is evaluated before assigning to the LHS, and that floating point literals are of default kind, that is single precision. Thus, making the argument to GAMMA double precision the compiler chooses the double precision GAMMA.</p>

```
<code>
program arithmetic
! program to do a calculation
integer, parameter :: dp = kind(1.0d0)
real(dp) :: x
x = GAMMA(-170.1_dp)
print *, x
end program
</code>
```

Title: Result of GAMMA underflows its kind

Body:
I would like to calculate gamma(-170.1) using the program below:

program arithmetic
! program to do a calculation
real(8) :: x
x = GAMMA(-170.1)
print *, x
end program

but I get the error:

test.f95:4.10:

x = GAMMA(-170.1)
           1
  Error: Result of GAMMA underflows its kind at (1)

when I compile with gfortran. According to Maple gamma(-170.1) = 5.191963205*10^(-172) which I think should be within the range of the exponent of the variable x as I've defined it.

Body:
The below modification of your program should work. Remember that in Fortran the RHS is evaluated before assigning to the LHS, and that floating point literals are of default kind, that is single precision. Thus, making the argument to GAMMA double precision the compiler chooses the double precision GAMMA.

program arithmetic
! program to do a calculation
integer, parameter :: dp = kind(1.0d0)
real(dp) :: x
x = GAMMA(-170.1_dp)
print *, x
end program


问:
Angular 2: blur contenteditable div on enter
I have a contenteditable div that looks like this:

```<code> <div class="wall-title col-sm-12"
        [attr.contenteditable]="wall.title && wall.title !== 'Favorites'"
        (blur)="wallNameChanged($event.target.outerText)"
        (keyup.enter)="wallNameChanged($event.target.outerText)">
           {{wall.title}}
 </div>
</code>```

When the user presses enter after editing the div content, I want to blur the div. Currently, a new line character is getting added and a new line is visible in the UI.

How do I achieve this?

答:
You can achieve this by temporarily change value of you model wall.title (by adding space at the end and remove it after 0ms :P ) which force angular to refresh div DOM element:

So change template to this:

```<code><div class="wall-title col-sm-12"
     [attr.contenteditable]="wall.title && wall.title !== 'Favorites'"
     [textContent]="wall.title"
     (input)="wall.title=$event.target.textContent"
     (keyup.enter)="wallNameChanged($event)"
     (blur)="wallNameChanged($event)"
></div>
</code>```

And in component code:

```<code>public finishEditTeamName(event)
{
    event.target.blur();
    let str = this.wall.title;
    this.wall.title = str + ' ';
    setTimeout( () => {
        this.wall.title = str;
    }, 0);
}
</code>```

Body:
I have a contenteditable div that looks like this:

           {{wall.title}}

When the user presses enter after editing the div content, I want to blur the div. Currently, a new line character is getting added and a new line is visible in the UI.

How do I achieve this?

Body:
You can achieve this by temporarily change value of you model wall.title (by adding space at the end and remove it after 0ms :P ) which force angular to refresh div DOM element:

So change template to this:

<div class="wall-title col-sm-12"
     [attr.contenteditable]="wall.title && wall.title !== 'Favorites'"
     [textContent]="wall.title"
     (input)="wall.title=$event.target.textContent"
     (keyup.enter)="wallNameChanged($event)"
     (blur)="wallNameChanged($event)"
></div>

And in component code:

public finishEditTeamName(event)
{
    event.target.blur();
    let str = this.wall.title;
    this.wall.title = str + ' ';
    setTimeout( () => {
        this.wall.title = str;
    }, 0);
}


问:
what kinda of SQL is it? TODATE(), TOCHAR(), isdateformat()
I am working on a aggregator and it contain build in functions which are I am not familiar with. Few are these I listed here, does anyone know what SQL format is it?

TODATE(string, in_format[, out_format])

ISDATEFORMAT(value[,date_format])

TOCHAR(numeric_value)

Also, here is how I use it, it does accepting my syntax, but it didn't return correct value.

```<code>count(where text_column != TODATE('date_format','YYYY-MM-DD', 'yyyymm'))
</code>```

答:
for TODATE(string, in_format[, out_format])you can use TODATE('20171114','YYYYMMDD')

for ISDATEFORMAT(value[,date_format]) ISDATEFORMAT("2017-06-15", "%M %d %Y")

and tochar function converts a number or date to a string. e.g

TO_CHAR(1210.73, '9,999.99')

Result: ' 1,210.73'

Body:
I am working on a aggregator and it contain build in functions which are I am not familiar with. Few are these I listed here, does anyone know what SQL format is it?

TODATE(string, in_format[, out_format])

ISDATEFORMAT(value[,date_format])

TOCHAR(numeric_value)

Also, here is how I use it, it does accepting my syntax, but it didn't return correct value.

count(where text_column != TODATE('date_format','YYYY-MM-DD', 'yyyymm'))


问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
I'd also use the datetime module, convert all the timestamps into a datetime object and use than the timedelta.

```<code>import datetime

inputarr = [[], [], ['17:03:22', '17:08:54', '17:50:33', '17:55:20'], []]

for currList in inputarr:
    dates = []
    for currTime in currList:
        dates.append(datetime.datetime.strptime(currTime, "%H:%M:%S"))
    elemDiff = [(j-i).seconds for i,j in zip(dates, dates[1:])]
    elemDiff.append(0) #added a 0 for same length of the lists
    for element in range(len(currList)):
        if elemDiff[element] > datetime.timedelta(minutes=5).seconds:
            print(currList[element])
</code>```

Output:

```<code>17:03:22
17:08:54
</code>```

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Body:
I'd also use the datetime module, convert all the timestamps into a datetime object and use than the timedelta.

import datetime

inputarr = [[], [], ['17:03:22', '17:08:54', '17:50:33', '17:55:20'], []]

for currList in inputarr:
    dates = []
    for currTime in currList:
        dates.append(datetime.datetime.strptime(currTime, "%H:%M:%S"))
    elemDiff = [(j-i).seconds for i,j in zip(dates, dates[1:])]
    elemDiff.append(0) #added a 0 for same length of the lists
    for element in range(len(currList)):
        if elemDiff[element] > datetime.timedelta(minutes=5).seconds:
            print(currList[element])

Output:

17:03:22
17:08:54


问:
Wrapping a div with Noscript tag programatically
I have a div inside noscript tags

```<code> <noscript>
        <div id="googleImg" style="display:inline;">
        </div>
 </noscript>
</code>```

In a ajax call success I remove the noscript tags, add an element inside the div.  This is how I add the element inside;

```<code>var a = $jq("noscript").text();
            $jq("noscript").remove();
            $jq("body").append(a);

            $jq("#googleImg").append(adwordsImg);
</code>```

but I failed to put the noscript tags back around. How can I do it? I tried jquery.wrap but couldn't get it done.

PS: Reason for this is; I'm trying to implement Adwords to a website and because of caching mechanism, I can't just add the code into html and forget. I need to make some dynamic changes on some parameters. That's why I remove the noscript first and then try to put it back again.

答:
Using .html() will only get the content of the element. You can add the no script element around it by creating a new noscript element.

```<code>        var a = $jq("noscript").text();
        $jq("noscript").remove();
        var noscript = document.createElement("noscript");
        $jq(noscript).append(a);
        $jq("body").append(noscript);
        $jq("#googleImg").append(adwordsImg);
</code>```

Body:
I have a div inside noscript tags

In a ajax call success I remove the noscript tags, add an element inside the div.  This is how I add the element inside;

var a = $jq("noscript").text();
            $jq("noscript").remove();
            $jq("body").append(a);

            $jq("#googleImg").append(adwordsImg);

but I failed to put the noscript tags back around. How can I do it? I tried jquery.wrap but couldn't get it done.

PS: Reason for this is; I'm trying to implement Adwords to a website and because of caching mechanism, I can't just add the code into html and forget. I need to make some dynamic changes on some parameters. That's why I remove the noscript first and then try to put it back again.

Body:
Using .html() will only get the content of the element. You can add the no script element around it by creating a new noscript element.

        var a = $jq("noscript").text();
        $jq("noscript").remove();
        var noscript = document.createElement("noscript");
        $jq(noscript).append(a);
        $jq("body").append(noscript);
        $jq("#googleImg").append(adwordsImg);


问:
Does IL Merge work with .NET Compact Framework
Does anyone have experience using IL Merge and the .NET CF? Does IL Merge work with CF? Are there any known problems?</p>

答:
Yes, IL merge does support the Compact Framework platform.  By default it will attempt to target the desktop CLR.  You must pass the path to the Compact framework install to the /targetplatform parameter though.

For Example

ilmerge /t:winexe /targetplatform:v2,"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\Debugger\BCL"

This blog post has an excellent breakdown of this process:

http://blog.opennetcf.com/ncowburn/2007/01/30/UsingILMergeOnCompactFrameworkApplications.aspx

LastEditorDisplayName: ctacke

OwnerDisplayName: JaredPar