问:
NServiceBus unit testing: ExpectSend not fulfilled when bus.Send()
I'm using NServiceBus5.2.21, NServiceBus.Testing5.2.1, Moq4.0.1, NUnit3.2.0

Problem: ExpectSend<> keeps failing with

"ExpectedSendInvocation not fulfilled"

when _bus.Send() is called correctly. Not sure what I'm missing here.

Test:

```<code>[TestFixture]
public class GeneralLedgerHanlderTest
{
    private Mock<ISendGeneralLedgerToSap> _toSapMock;

    [SetUp]
    public void Setup()
    {
        _toSapMock = new Mock<ISendGeneralLedgerToSap>();
        _toSapMock.Setup(x => x.SendSoapMessageToSap(It.IsAny<GeneralLedgerSapCommand>()));
    }

    [Test]
    public void HandlerMustSendAuditLog()
    {
       NServiceBus.Testing.Test.Handler(bus => new GeneralLedgerToSapHandler(bus, _toSapMock.Object))
            .ExpectSend<GeneralLedgerAuditCommand>(command => command.SagaReferenceId == "ab")
            .OnMessage(new GeneralLedgerSapCommand { SagaReferenceId = "ab" });
    }
}
</code>```

Handler:

```<code>public class GeneralLedgerToSapHandler : IHandleMessages<GeneralLedgerSapCommand>
{
    private readonly IBus _bus;
    private readonly ISendGeneralLedgerToSap _sendSoapToSap;

    public GeneralLedgerToSapHandler(IBus bus, ISendGeneralLedgerToSap sendSoapToSap)
    {
        _bus = bus;
        _sendSoapToSap = sendSoapToSap;
    }

    public void Handle(GeneralLedgerSapCommand message)
    {
        _sendSoapToSap.SendSoapMessageToSap(message);

        var goodsReceiptAuditCommand = new GeneralLedgerAuditCommand
        {
            SagaReferenceId = message.SagaReferenceId,
        };

        _bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);
    }
}
</code>```

答:
This is a bit tricky to figure out, but the problem arises due to your usage of send:

```<code>_bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);
</code>```

You are sending to a specific destination (I'd recommend to rely on routing instead).

The testing framework has a specific "Expect" option for sends to specific destination. Your test should work correctly if you use ExpectSendToDestination instead:

```<code>.ExpectSendToDestination<GeneralLedgerAuditCommand>((command, destination) => command.SagaReferenceId == "ab")
</code>```

In NServiceBus.Testing v6 (relying on NServiceBus v6), this has been fixed and ExpectSend will also be invoked when sending to a specific destination.

edit: I raised an issue in NServiceBus.Testing about this confusing behavior, see https://github.com/Particular/NServiceBus.Testing/issues/122

Body:
I'm using NServiceBus5.2.21, NServiceBus.Testing5.2.1, Moq4.0.1, NUnit3.2.0

Problem: ExpectSend<> keeps failing with

"ExpectedSendInvocation not fulfilled"

when _bus.Send() is called correctly. Not sure what I'm missing here.

Test:

[TestFixture]
public class GeneralLedgerHanlderTest
{
    private Mock<ISendGeneralLedgerToSap> _toSapMock;

    [SetUp]
    public void Setup()
    {
        _toSapMock = new Mock<ISendGeneralLedgerToSap>();
        _toSapMock.Setup(x => x.SendSoapMessageToSap(It.IsAny<GeneralLedgerSapCommand>()));
    }

    [Test]
    public void HandlerMustSendAuditLog()
    {
       NServiceBus.Testing.Test.Handler(bus => new GeneralLedgerToSapHandler(bus, _toSapMock.Object))
            .ExpectSend<GeneralLedgerAuditCommand>(command => command.SagaReferenceId == "ab")
            .OnMessage(new GeneralLedgerSapCommand { SagaReferenceId = "ab" });
    }
}

Handler:

public class GeneralLedgerToSapHandler : IHandleMessages<GeneralLedgerSapCommand>
{
    private readonly IBus _bus;
    private readonly ISendGeneralLedgerToSap _sendSoapToSap;

    public GeneralLedgerToSapHandler(IBus bus, ISendGeneralLedgerToSap sendSoapToSap)
    {
        _bus = bus;
        _sendSoapToSap = sendSoapToSap;
    }

    public void Handle(GeneralLedgerSapCommand message)
    {
        _sendSoapToSap.SendSoapMessageToSap(message);

        var goodsReceiptAuditCommand = new GeneralLedgerAuditCommand
        {
            SagaReferenceId = message.SagaReferenceId,
        };

        _bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);
    }
}

Body:
This is a bit tricky to figure out, but the problem arises due to your usage of send:

_bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);

You are sending to a specific destination (I'd recommend to rely on routing instead).

The testing framework has a specific "Expect" option for sends to specific destination. Your test should work correctly if you use ExpectSendToDestination instead:

.ExpectSendToDestination<GeneralLedgerAuditCommand>((command, destination) => command.SagaReferenceId == "ab")

In NServiceBus.Testing v6 (relying on NServiceBus v6), this has been fixed and ExpectSend will also be invoked when sending to a specific destination.

edit: I raised an issue in NServiceBus.Testing about this confusing behavior, see https://github.com/Particular/NServiceBus.Testing/issues/122


来源: stackexchange

问:
How to build Oauth 2.0 using Appcelerator Titanium in Android
How to build Oauth2.0 using Appcelerator Titanium in Andriod any one please help me.</p>

答:
Oauth can be implemented using normal createHTTPClient requests. You have to use a standard login-flow and provide needed headers/parameters (see the Oauth specifications).

If you don't want to create a module on your own you can have a look at the
commonjs module available at https://github.com/appcelerator-modules/ti.oauth

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Products are not showed under catalog page
My problem is when I add a product from catalog-product and associate it with a specific category. This product is not displayed on the category page.

For example: if I add a product and associate it with furniture section. When I click furniture page, there is no any product displayed on the furniture page.

I can't find a bug log online. But it is working on my localhost. Just no works for my live site.

Does anyone find the same problem before? And how can I fix it?

I turn on the debug mode and got this error:

```<code>[PrestaShopDatabaseException]
Access denied for user 'XXXXXX'@'%' to database 'XXXX'

CREATE TEMPORARY TABLE ps_cat_restriction ENGINE=MEMORY SELECT DISTINCT cp.id_product, p.id_manufacturer, product_shop.condition, p.weight FROM ps_category c STRAIGHT_JOIN ps_category_product cp ON (c.id_category = cp.id_category AND c.nleft >= 35 AND c.nright <= 52 AND c.active = 1) STRAIGHT_JOIN ps_product_shop product_shop ON (product_shop.id_product = cp.id_product AND product_shop.id_shop = 1) STRAIGHT_JOIN ps_product p ON (p.id_product=cp.id_product) WHERE product_shop.`active` = 1 AND product_shop.`visibility` IN ("both", "catalog")
</code>```

答: Try to regenerate .htaccess file. Go to Prefereneces -> SEO and URLs, set Friendly URL to No and save. Then enable it back and save again.

Body:
My problem is when I add a product from catalog-product and associate it with a specific category. This product is not displayed on the category page.

For example: if I add a product and associate it with furniture section. When I click furniture page, there is no any product displayed on the furniture page.

I can't find a bug log online. But it is working on my localhost. Just no works for my live site.

Does anyone find the same problem before? And how can I fix it?

I turn on the debug mode and got this error:

[PrestaShopDatabaseException]
Access denied for user 'XXXXXX'@'%' to database 'XXXX'

CREATE TEMPORARY TABLE ps_cat_restriction ENGINE=MEMORY SELECT DISTINCT cp.id_product, p.id_manufacturer, product_shop.condition, p.weight FROM ps_category c STRAIGHT_JOIN ps_category_product cp ON (c.id_category = cp.id_category AND c.nleft >= 35 AND c.nright <= 52 AND c.active = 1) STRAIGHT_JOIN ps_product_shop product_shop ON (product_shop.id_product = cp.id_product AND product_shop.id_shop = 1) STRAIGHT_JOIN ps_product p ON (p.id_product=cp.id_product) WHERE product_shop.`active` = 1 AND product_shop.`visibility` IN ("both", "catalog")


问:
Keep global constants in some files in Node.js
I would like to define some global constants in Node.js. After careful study, I guess this is a proper way:

```<code>module.exports = Object.freeze({
    A_LEN: 10,
    B_LEN: 10,
)};
</code>```

But I ran into a problem, can I define a constant using the values that have been defined above, like this:

```<code>module.exports = Object.freeze({
    A_LEN: 10,
    B_LEN: 10,
    C_LEN: A_LEN + B_LEN,
)};
</code>```

How could this be implemented? Or is there any more decent way in Node?

答:
You can define these constants just adding some lines:

```<code>const A_LEN = 10;
const B_LEN = 10;
const C_LEN = A_LEN + B_LEN;
module.exports = Object.freeze({
    A_LEN,
    B_LEN,
    C_LEN,
)};
</code>```

In case you don't know, these snippets are equivalent:

```<code>const x = 14;
{ x };     // This is equivalent to
{ x: 14 }; // this
{ x: x };  // or this
</code>```

Body:
I would like to define some global constants in Node.js. After careful study, I guess this is a proper way:

module.exports = Object.freeze({
    A_LEN: 10,
    B_LEN: 10,
)};

But I ran into a problem, can I define a constant using the values that have been defined above, like this:

module.exports = Object.freeze({
    A_LEN: 10,
    B_LEN: 10,
    C_LEN: A_LEN + B_LEN,
)};

How could this be implemented? Or is there any more decent way in Node?

Body:
You can define these constants just adding some lines:

const A_LEN = 10;
const B_LEN = 10;
const C_LEN = A_LEN + B_LEN;
module.exports = Object.freeze({
    A_LEN,
    B_LEN,
    C_LEN,
)};

In case you don't know, these snippets are equivalent:

const x = 14;
{ x };     // This is equivalent to
{ x: 14 }; // this
{ x: x };  // or this


问:
delete duplicate rows from table row number partition by
delete duplicates per com_id:

I have to write a generic DELETE that will remove vald records to the end of the world (vald_to = 9999-01-01)
if:

tar_id = -1

vald_from = 0001-01-01

there is another record for this com_id with vald_to = 9999-01-01

The query is:

```<code>  delete from C
  where (COM_ID, VALD_TO) in
   (
    select
    COM_ID,
    VALD_TO,
    row_number()
        over
        (partition by COM_IDorder by VALD_TO DESC) dup
     from C
        where
    tar_id=-1
        and
    vald_from = 0001-01-01
        and
    dup > 1
    );
</code>```

The script removes all records for the com_id

答:
I don't really understand what you consider a duplicate you want removed. So just guessing: You are considering a record a duplicate, when its range is covered by another record. E.g.:

```
COM_ID   vald_from    vald_to
123      0001-01-01   9999-01-01
123      0001-01-01   2017-01-01
```

The second record is superfluous, because its range is only part of the larger range of the first record. But the same would be true for:

```
COM_ID   vald_from    vald_to
123      2016-01-01   2017-01-01
123      2016-02-01   2016-03-01
```

Again, the second record's range is only part of the first one's.

A query to remove those superfluous records would be:

```<code>delete from c
where exists
(
  select *
  from c other
  where other.com_id = c.com_id
  and other.vald_from <= c.vald_from
  and other.vald_to >= c.vald_to
  and other.rowid <> c.rowid
)
and tar_id = -1;
</code>```

I don't know, whether you want tar_id = -1 inside the subquery, too. And maybe you still want to restrict this somehow to dates date '0001-01-01' and date '9999-01-01'. If so, adjust the statement accordingly.

Body:
delete duplicates per com_id:

I have to write a generic DELETE that will remove vald records to the end of the world (vald_to = 9999-01-01)
if:

tar_id = -1

vald_from = 0001-01-01

there is another record for this com_id with vald_to = 9999-01-01

The query is:

  delete from C
  where (COM_ID, VALD_TO) in
   (
    select
    COM_ID,
    VALD_TO,
    row_number()
        over
        (partition by COM_IDorder by VALD_TO DESC) dup
     from C
        where
    tar_id=-1
        and
    vald_from = 0001-01-01
        and
    dup > 1
    );

The script removes all records for the com_id

Body:
I don't really understand what you consider a duplicate you want removed. So just guessing: You are considering a record a duplicate, when its range is covered by another record. E.g.:

COM_ID   vald_from    vald_to
123      0001-01-01   9999-01-01
123      0001-01-01   2017-01-01

The second record is superfluous, because its range is only part of the larger range of the first record. But the same would be true for:

COM_ID   vald_from    vald_to
123      2016-01-01   2017-01-01
123      2016-02-01   2016-03-01

Again, the second record's range is only part of the first one's.

A query to remove those superfluous records would be:

delete from c
where exists
(
  select *
  from c other
  where other.com_id = c.com_id
  and other.vald_from <= c.vald_from
  and other.vald_to >= c.vald_to
  and other.rowid <> c.rowid
)
and tar_id = -1;

I don't know, whether you want tar_id = -1 inside the subquery, too. And maybe you still want to restrict this somehow to dates date '0001-01-01' and date '9999-01-01'. If so, adjust the statement accordingly.


问:
Issues with gridview
I created a gridview with filter and everything fine but when I do gridview.databind(); nothing happen and with I change the page index nothing happen too.

I used scriptmanger,updatepanel and a little of javascript markup code:

```<code><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
<asp:GridView ID="GridView1" ClientIDMode="Static" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    onload="GridView1_Load" OnRowCreated="OnRowCreated" Width="614px" CellPadding="4" ForeColor="#333333"
    GridLines="Both" EmptyDataText="No Data To Show">
    <Columns>
        <asp:BoundField DataField="areacode" HeaderText="areacode"
            SortExpression="areacode" />
        <asp:BoundField DataField="areaename" HeaderText="areaename"
            SortExpression="areaename" />
        <asp:BoundField DataField="areaaname" HeaderText="areaaname"
            SortExpression="areaaname" />
        <asp:BoundField DataField="areazipcode" HeaderText="areazipcode"
            SortExpression="areazipcode" />
        <asp:BoundField DataField="districtcode" HeaderText="districtcode"
            SortExpression="districtcode" />
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"/>
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#ffffff" ForeColor="#333333" />
</asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NetCareConnectionString %>"
    SelectCommand="SELECT * FROM [areadata]"></asp:SqlDataSource>

<script language="javascript" type="text/javascript">
    var gridViewCtlId = '<%=GridView1.ClientID%>';
    var gridViewCtl = null;
    var curSelRow = null;

    function onchange(evt) {
        PageMethods.getControlData(evt.target.id, document.getElementById(evt.target.id).value);
    }
    function getGridViewControl() {
        if (null == gridViewCtl) {
            gridViewCtl = document.getElementById(gridViewCtlId);
        }
    }

    function onGridViewRowSelected(rowIdx, isfiltered) {
        var selRow;
        //filter one
        if (rowIdx == '1' & isfiltered == 'True')
            selRow = null;
        else
            selRow = getSelectedRow(rowIdx);

        if (curSelRow != null) {
            curSelRow.style.backgroundColor = '#ffffff';
        }

        if (selRow != null) {
            curSelRow = selRow;
            curSelRow.style.backgroundColor = '#8098B3';
        }

    }

    function getSelectedRow(rowIdx) {
        getGridViewControl();
        PageMethods.getRowSelected(rowIdx - 1);
        if (null != gridViewCtl) {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }
</code>```

code behind:

```<code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    static string controlID, controlValue, selectedRowIndex;
    #region WebMethods
    [System.Web.Services.WebMethod]
    public static void getControlData(string controlIDP, string controlValueP)
    {
        controlID = controlIDP;
        controlValue = controlValueP;
        _Default d = new _Default();
        d.textboxes_TextChanged();
    }
    [System.Web.Services.WebMethod]
    public static void getRowSelected(string rowIndex)
    {
        selectedRowIndex = rowIndex;
    }
    #endregion
    private void SetInitialRow(GridView inputGridView,SqlDataSource inputSqlDataSource)
    {
        if (inputGridView != null)
        {
            DataView dv = (DataView)inputSqlDataSource.Select(DataSourceSelectArguments.Empty);
            object [] session=new object[2];
            session[0]=dv;
            session[1] = inputGridView;
            Session["GridView"] = session;
            TextBox[] tb = new TextBox[inputGridView.Columns.Count];
            DataTable dt = dv.Table.Clone();
            dt.Rows.Add(dt.NewRow());
            for (int row = 0; row < dv.Table.Rows.Count; row++)
            {
                DataRow newRow = dt.NewRow();
                newRow = dv.Table.Rows[row];
                dt.ImportRow(newRow);
            }
            inputGridView.DataSource = dt;
            inputGridView.DataBind();
            for (int i = 0; i < inputGridView.Columns.Count; i++)
            {
                tb[i] = new TextBox();
                tb[i].Attributes.Add("id", i.ToString());
                if (!inputGridView.Rows[0].Cells[i].HasControls())
                    inputGridView.Rows[0].Cells[i].Controls.Add(tb[i]);
                else
                    inputGridView.Rows[0].Cells[i].Controls.Clear();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        SetInitialRow(GridView1, SqlDataSource1);
    }
    public void textboxes_TextChanged()
    {
        if (!string.IsNullOrWhiteSpace(controlValue))
        {
            object[] session = (object[])Session["GridView"];
            DataView dv = (DataView)session[0];
            GridView1 = (GridView)session[1];
            String strexpr = string.Format("{0}={1}", dv.Table.Columns[int.Parse(controlID)], controlValue);
            DataRow[] rows = dv.Table.Select(strexpr);
            DataTable dt = dv.Table.Clone();
            foreach (DataRow row in rows)
                dt.ImportRow(row);
            System.Windows.Forms.MessageBox.Show(dt.Rows.Count.ToString());
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + (e.Row.RowIndex + 1).ToString() + "','" + true + "')");
        }
    }
    protected void GridView1_Load(object sender, EventArgs e)
    {

    }
}
</code>```

答:
Set breakpoints in your code on the DataBind() lines. When it hits the line, check the bound DataTable and make sure it contains information. The symptoms you are experiencing suggest that the filter is causing no data to be delivered to the Grid. If I am correct, it is not suprising you see nothing. I would be surprised if you have data just before bind.

The next step is to determine whether or not you have data initially.

One other option I can think of is you are doing an initial bind, but not rebinding after a change in values (resubmit, etc.). If this is the case, you need to set up a "cache" to hold the table and then filter as needed. Either that or make a return trip to the database.

Title: Issues with gridview

Body:
I created a gridview with filter and everything fine but when I do gridview.databind(); nothing happen and with I change the page index nothing happen too.

I used scriptmanger,updatepanel and a little of javascript markup code:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
<asp:GridView ID="GridView1" ClientIDMode="Static" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    onload="GridView1_Load" OnRowCreated="OnRowCreated" Width="614px" CellPadding="4" ForeColor="#333333"
    GridLines="Both" EmptyDataText="No Data To Show">
    <Columns>
        <asp:BoundField DataField="areacode" HeaderText="areacode"
            SortExpression="areacode" />
        <asp:BoundField DataField="areaename" HeaderText="areaename"
            SortExpression="areaename" />
        <asp:BoundField DataField="areaaname" HeaderText="areaaname"
            SortExpression="areaaname" />
        <asp:BoundField DataField="areazipcode" HeaderText="areazipcode"
            SortExpression="areazipcode" />
        <asp:BoundField DataField="districtcode" HeaderText="districtcode"
            SortExpression="districtcode" />
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"/>
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#ffffff" ForeColor="#333333" />
</asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NetCareConnectionString %>"
    SelectCommand="SELECT * FROM [areadata]"></asp:SqlDataSource>

ContentLicense: CC BY-SA 2.5


问:
Minimizing MYSQL connection from webhook callback
I am working on a project that requires my server xyz.com to receive POST/GET responses to xyz.com/callback.php  from abc.com(SMS gateway providers).

Below is how i currently handle the responses on callback.php

1. Receive the POST data from abc.com (This post contains a unique ID)

2. Connect to mysql database and UPDATE users WHERE messageId=Same_ID_from_POST_data

This works and data is being updated. However it is causing CPU overload due to the thousands of MYSQL connections. This is because whenever there is a delivery receipt from the api server for each individual message, callback.php connects to mysql and updates the database.

Is there a best practice to minimize the amount of times i connect to MYSQL?

I was thinking of doing the following, i however doubt if it makes any sense.

1. Receive post data from api server as before.

2. Instead of updating mysql, i simply write to a .txt file with the following code

$query.="Update users set status='$post_data_for_status' where unique='$post_unique';

Then after about 10mins i use cron to run a php file that uses mysqli_multi_query($connection, $query) to update the table thereby making it a single connection. After the update i simply unlink the .txt file

Even if the above method will work, i don't know how to do it. I am sure there is a better alternative.

Any ideas please and sorry for long epistle.

答:
What you are looking for sounds like avoiding connection churning, which is one of the benefits we get from using a "connection pool", commonly used in Java/J2EE web applications.

PHP doesn't provide connection pooling (AFAIK). But PDO and mysqli do provide for "persistent" connections, which give some of the same benefit as connection pool (avoiding connection churning.)

For mysqli, prepend "p:" to the hostname in the mysqli_connect.

http://php.net/manual/en/mysqli.persistconns.php

For PDO, include PDO::ATTR_PERSISTENT => true in the connection.

http://php.net/manual/en/pdo.connections.php

Be aware that with persisted connections, the MySQL connection maintains it's state (session variables, temporary tables, user defined variables, et al.) For example, if a client issues a statement such as SET time_zone = '+00:00'; or SET @foo = 'bar';, a subsequent client reusing that MySQL connection is going to inherit the time_zone setting or the user defined variable @foo value; whatever changes to the MySQL session state the previous clients made.


问:
Is it possible to use Spring to create a console application?
Currently researching this topic. Is it possible to use the benefits of Spring to form a Console application? I mean, with scopes, autowiring and etc(found a bunch of examples of a basic "Set the context, init and go", but nothing more)?

Can't find any tutorials or helpful information on this topic.

答:
Here are links to the Spring docs:

3. Developing Spring Shell Applications

4. Simple sample application using the Spring Shell


问:
Load/Fetch initial list if selected item not found
I'm kinda new to the ngrx/rxjs world and trying to figure out how to set up my effects in my Angular app in a proper way, using ngrx.

I have two working scenarios:

Load/Fetch list – load list from api and store to state

Select item – get item by id from previously loaded list

Now, the effect logic I'm looking for is:

If selected item is not found in state param entities: Item[] – AND the state param initialLoaded===false – then run action LIST_LOAD before trying to select by id (again).

Or simply:

If initialLoaded===false, then run LIST_LOAD before doing the usual  ITEM_SELECT.

.

.

My current code for the ITEM_SELECT effect, to get us started:

@Effect() selectItemEffect: Observable<Action> = this.actions$
        .ofType(MyActions.ActionTypes.ITEM_SELECT)
        .withLatestFrom(this.store$)
        .map(([action, state]) => {

            const id = (<MyActions.ItemSelectAction>action).id;
            const selectedItem = state.myItems.entities.find(x => x.id === id);

            if(selectedItem){
                return new MyActions.SelectSuccessAction(selectedItem);

            } else {
                /*
                if(!state.myItems.initialLoaded) {
                     // run MyActions.ListLoadAction()?
                     // should be a nicer rxjs method for these scenarios?
                }
                */
                return new MyActions.ItemSelectFailureAction(new Error('Item not found'));

            }
        })
```

答:
Set up an easier solution. Set up a 3 different actions, 2 loading the item list and another one returning a selected item.

If the item is not found, simply trigger another action that calls a service that performs an api call to fetch that item by its id.

But, anyways, I feel like you are handling it in a tricky way, you can separate action handling in this way:

Effect: only LOAD_ITEMS

Reducer: LOAD_SUCCESS, SELECT

Let's suppse you have a Item class that models one of your items and that your item.id is a string, you should have an action like:

```<code>import { Action } from '@ngrx/store';

/** App Models **/
import { Item } from '../models/item.model';

export const LOAD = '[Item] Load';
export const LOAD_SUCCESS = '[Item] Load Success';
export const SELECT = '[Item] Select';

export class LoadAction implements Action {
  readonly type = LOAD;
  constructor() { }
}

export class LoadActionSuccess implements Action {
  readonly type = LOAD_SUCCESS;
  constructor(public payload: Item[]) { }
}

export class SelectAction implements Action {
  readonly type = SELECT;
  constructor(public payload: string) {}
}

export type All
  = LoadAction
  | LoadActionSuccess
  | SelectAction;
</code>```

Then, you need an effect to perform an api call using a service to return the first list of items:

```<code>import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';

/** rxjs **/
import {map} from 'rxjs/operators/map';
import {mergeMap} from 'rxjs/operators/mergeMap';
import {catchError} from 'rxjs/operators/catchError';

/** ngrx **/
import * as itemsActions from '../actions/items.actions';
/** App Services **/
import { ItemService } from '../services/item.service';
/** App Model **/
import {Item} from '../models/content.model';

@Injectable()
export class ItemsEffects {

  @Effect() load$ = this.actions$
    .ofType(itemsActions.LOAD)
      .pipe(
        mergeMap(() => {
          return this.itemsService.getItemsFromApi()
            .pipe(
              map((items: Item[]) => {
                return new itemsActions.LoadActionSuccess(items);
              }),
              catchError((error: Error) => {
                // handle error here
              })
            );
        })
    )
  ;

  constructor(private itemsService: ItemsService, private actions$: Actions) { }
}
</code>```

And then you'll need to have a reducer to handle both Success and Select:

```<code>/** ngrx **/
import {createFeatureSelector} from '@ngrx/store';
import {createSelector} from '@ngrx/store';

/** App Models **/
import { Item } from '../models/item.model';

/** ngrx **/
import * as itemsActions from '../actions/items.actions';

export type Action = itemsActions.All;

export interface ItemsState {
  items: Item[];
  selectedItem: Item;
}

export const initialState: ContentsState = {
  items: [],
  selectedItem: new Item()
};

export const selectItems = createFeatureSelector<ItemsState>('items');
export const getItems    = createSelector(selectItems, (state: ItemsState) => {
  return state.items;
});
export const getItemById = createSelector(selectItems, (state: ItemsState) => {
  return state.selectedItem;
});

export function itemsReducer(state: ItemsState = initialState, action: Action): ItemsState {
  switch (action.type) {
    case itemsActions.LOAD_SUCCESS:
      const loadedItems = action.payload.map(item => new Item(item));
      return {
               ...state,
               items: loadedItems,
               selectedItem: state.selectedItem
      };
    case itemsActions.SELECT:
      // Find one item containing id equals to the one we passed
      const filteredItem = state.items.filter((item) => {
          return item.id === action.payload
      })[0];
      return {
               ...state,
               items: state.items,
               selectedItem: filteredItem
      };
    default: {
      return state;
    }
  }
}
</code>```

Of course, on your component you should get new values with something like:

```<code>import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

/** ngrx **/
import {AppState} from '../../shared/app-state.interface';
import * as itemsActions from './actions/items.actions';
import {getItemById, getItems} from './reducers/items.reducer';

/** App Models **/
import { Item } from './models/item.model';

@Component({
  selector: 'app-items',
  templateUrl: './items.component.html'
})

export class ItemsComponent implements OnInit {

    items$: Observable<Array<Item>>;
    selectedItems$: Observable<Item>;
    selectItemById$ = new Subject<string>();

    constructor(private store: Store<AppState>) {
        this.items$ = this.store.select(getItems);
        this.selectedItems$ = this.store.select(getItemById);
        this.selectItemById$
            .switchMap(id => this.store.dispatch(new itemsActions.SelectAction(id)));
    }

    ngOnInit() {
         this.store.dispatch(new itemsActions.LoadAction());
    }

}
</code>```

And the selection gets done in your template with something like:

```<code><... (input)="selectItemById$.next(id)"/>
</code>```

AppState is just an interface like:

```<code>import {ItemsState} from './items/reducers/items.reducers';

export interface AppState {
  items: ItemsState;
}
</code>```

Or in any other way you wish.

Body:
Set up an easier solution. Set up a 3 different actions, 2 loading the item list and another one returning a selected item.

If the item is not found, simply trigger another action that calls a service that performs an api call to fetch that item by its id.

But, anyways, I feel like you are handling it in a tricky way, you can separate action handling in this way:

Effect: only LOAD_ITEMS

Reducer: LOAD_SUCCESS, SELECT

Let's suppse you have a Item class that models one of your items and that your item.id is a string, you should have an action like:

import { Action } from '@ngrx/store';

/** App Models **/
import { Item } from '../models/item.model';

export const LOAD = '[Item] Load';
export const LOAD_SUCCESS = '[Item] Load Success';
export const SELECT = '[Item] Select';

export class LoadAction implements Action {
  readonly type = LOAD;
  constructor() { }
}

export class LoadActionSuccess implements Action {
  readonly type = LOAD_SUCCESS;
  constructor(public payload: Item[]) { }
}

export class SelectAction implements Action {
  readonly type = SELECT;
  constructor(public payload: string) {}
}

export type All
  = LoadAction
  | LoadActionSuccess
  | SelectAction;

Then, you need an effect to perform an api call using a service to return the first list of items:

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';

/** rxjs **/
import {map} from 'rxjs/operators/map';
import {mergeMap} from 'rxjs/operators/mergeMap';
import {catchError} from 'rxjs/operators/catchError';

/** ngrx **/
import * as itemsActions from '../actions/items.actions';
/** App Services **/
import { ItemService } from '../services/item.service';
/** App Model **/
import {Item} from '../models/content.model';

@Injectable()
export class ItemsEffects {

  @Effect() load$ = this.actions$
    .ofType(itemsActions.LOAD)
      .pipe(
        mergeMap(() => {
          return this.itemsService.getItemsFromApi()
            .pipe(
              map((items: Item[]) => {
                return new itemsActions.LoadActionSuccess(items);
              }),
              catchError((error: Error) => {
                // handle error here
              })
            );
        })
    )
  ;

  constructor(private itemsService: ItemsService, private actions$: Actions) { }
}

And then you'll need to have a reducer to handle both Success and Select:

/** ngrx **/
import {createFeatureSelector} from '@ngrx/store';
import {createSelector} from '@ngrx/store';

/** App Models **/
import { Item } from '../models/item.model';

/** ngrx **/
import * as itemsActions from '../actions/items.actions';

export type Action = itemsActions.All;

export interface ItemsState {
  items: Item[];
  selectedItem: Item;
}

export const initialState: ContentsState = {
  items: [],
  selectedItem: new Item()
};

export const selectItems = createFeatureSelector<ItemsState>('items');
export const getItems    = createSelector(selectItems, (state: ItemsState) => {
  return state.items;
});
export const getItemById = createSelector(selectItems, (state: ItemsState) => {
  return state.selectedItem;
});

export function itemsReducer(state: ItemsState = initialState, action: Action): ItemsState {
  switch (action.type) {
    case itemsActions.LOAD_SUCCESS:
      const loadedItems = action.payload.map(item => new Item(item));
      return {
               ...state,
               items: loadedItems,
               selectedItem: state.selectedItem
      };
    case itemsActions.SELECT:
      // Find one item containing id equals to the one we passed
      const filteredItem = state.items.filter((item) => {
          return item.id === action.payload
      })[0];
      return {
               ...state,
               items: state.items,
               selectedItem: filteredItem
      };
    default: {
      return state;
    }
  }
}

Of course, on your component you should get new values with something like:

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

/** ngrx **/
import {AppState} from '../../shared/app-state.interface';
import * as itemsActions from './actions/items.actions';
import {getItemById, getItems} from './reducers/items.reducer';

/** App Models **/
import { Item } from './models/item.model';

@Component({
  selector: 'app-items',
  templateUrl: './items.component.html'
})

export class ItemsComponent implements OnInit {

    items$: Observable<Array<Item>>;
    selectedItems$: Observable<Item>;
    selectItemById$ = new Subject<string>();

    constructor(private store: Store<AppState>) {
        this.items$ = this.store.select(getItems);
        this.selectedItems$ = this.store.select(getItemById);
        this.selectItemById$
            .switchMap(id => this.store.dispatch(new itemsActions.SelectAction(id)));
    }

    ngOnInit() {
         this.store.dispatch(new itemsActions.LoadAction());
    }

}

And the selection gets done in your template with something like:

<... (input)="selectItemById$.next(id)"/>

AppState is just an interface like:

import {ItemsState} from './items/reducers/items.reducers';

export interface AppState {
  items: ItemsState;
}

Or in any other way you wish.


问:
How to refresh components
First of all, sorry if my question is too silly, I'm still new with Polymer 2.

I'm facing a little issue. I've created a custom component, where I load some dynamic data via xhr.
Everything seems to work correctly, but I've noticed that when I leave and come back to this view, the component has not changed, even if it raises all the xhr to get new data.

I'm wondering if the issue is that the data is updated, but the DOM is still the same.

Is it possible to force the system to "reload" the component each time I visit the page?

Thanks in advance.

答:
I see you are doing this.notifyPath('tree', this.assets); in fullAssets(), but I think the syntax is not correct.

From the docs:

When calling notifyPath, you need to use the exact path that changed.
  For example, calling this.notifyPath('profile') doesn't pick up a
  change to profile.name because the profile object itself hasn't
  changed.

So try to do this:

```<code>this.notifyPath('tree.property_you_want_to_be_changed');
</code>```

Or maybe would be better to you to use MutableData mixin. This mixin allows the array to be updated and the UI be notified simpley doing

```<code>this.notifyPath('tree');
</code>```

Title: How to refresh components

Body:
I see you are doing this.notifyPath('tree', this.assets); in fullAssets(), but I think the syntax is not correct.

From the docs:

When calling notifyPath, you need to use the exact path that changed.
  For example, calling this.notifyPath('profile') doesn't pick up a
  change to profile.name because the profile object itself hasn't
  changed.

So try to do this:

this.notifyPath('tree.property_you_want_to_be_changed');

Or maybe would be better to you to use MutableData mixin. This mixin allows the array to be updated and the UI be notified simpley doing

this.notifyPath('tree');


问:
Importing date from HTML into Django views
I'm fairly new to Django and I am facing a bit of a problem. I have my html template in which I have two html date fields - start_date and end_date. I want to pass the contents of those field into my views.py and then display data for that time period, but I am having trouble making it work. Any help will be greatly appreciated. Relevant code:

home.html

```<code>  Select time period:
  <br>
  From:
  <input id = "start_date" type="date" name="From" value="{{data.start_date|date:"d/m/Y"}}">
  To:
  <input id = "end_date" type="date" name="To" value="{{data.end_date|date:"d/m/Y"}}">
  <input type = "submit">

{% for data in data.all %}
      {% if data.profile.user.username == user.username %}

      <tr>
        <td>{{data.profile.user.username}}</td>
        <td>{{data.date}}</td>
      </tr>

      {% endif %}
      {% endfor  %}
</code>```

views.py

```<code>import datetime
from datetime import date

@login_required
def home(request):
    if request.user.is_authenticated():
            user = request.user.username

    start_date = request.GET.get['start_date']
    end_date = request.GET.get['end_date']

    data = Data.objects.filter(date__range=[start_date, end_date])

    context = {

            'data': data,
            'cpu_hours_all': cpu_hours_all,
    }
</code>```

models.py

```<code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE

def __str__(self):
    return self.user.username

class Data(models.Model):
    date = models.DateField(blank=True)
    profile = models.ForeignKey(Profile , on_delete=models.CASCADE)
</code>```

Thanks in advance!

答:
You failed to explain what "I am having trouble making it work" actually means, so this will be at most a partial and kind of a "wild guess" answer, but anyway:

First you need to put your fields and submit in a  tag, with the proper HTTP method, and your fields "name" attribute (not the "id" attribute) must match what you're looking up in your view:

```<code><form method="GET">
  <legend>Select time period:</legend>
  <br>
  From:
  <input id="start_date" type="date" name="start_date" value="{{start_date|date:"d/m/Y"}}">
  To:
  <input id="end_date" type="date" name="end_date" value="{{end_date|date:"d/m/Y"}}">
  <input type="submit">
</form>
</code>```

Also note that we're filling the fields with {{ start_date }} and {{ end_date }} - in your template's context, data is a Queryset and has no start_date nor end_date attributes.

Then in your view you have to use request.GET.get() properly:

```<code>@login_required
def home(request):
    # ...
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
</code>```

.get() is a method, it must be called, not subscripted (parens, not brackets). Note that until the user actually submits the form, those fields won't be in the querystring and GET.get(...) will return None, so you have to handle this case, either by providing default values to .get() or by testing if the form was submitted and not returning a queryset at all (or returning an empty queryset, or returning the whole unfiltered queryset etc, choice is yours).  Here's a version returning an empty queryset.

Also, since you're not using a Django forms.Form, what you will get here are raw unsanitized strings, while Queryset.filter() expects Python datetime.date or datetime.datetime objects, so you'll have to validate and convert those values manually:

```<code># ...
parsed_start_date = None
parsed_end_date = None
if start_date and end_date:
    errors = {}
    try:
        parsed_start_date = datetime.datetime.strptime(start_date, "%d/%m/%Y")
    except ValueError:
        errors["start_date"] = "Invalid date" # etc..
    try:
        parsed_end_date = datetime.datetime.strptime(end_date, "%d/%m/%Y")
    except ValueError:
        errors["end_date"] = "Invalid date" # etc..

if parsed_start_date and parsed_end_date:
    data = Data.objects.filter(date__range=[parsed_start_date, parsed_end_date])
else:
    data = Data.objects.none()  # empty queryset

context = {
        'data': data,
        'errors': errors,
        'start_date': start_date,
        'end_date': end_date
       }

# etc
</code>```

And then you have to change your template to accomodate those changes (don't try to apply the |date filter to strings, display errors...):

```<code><form method="GET">
  Select time period:
  <br>
  From:
  <input id="start_date" type="date" name="start_date" value="{{start_date}}">
  {% if errors.start_date %}
      <span class="error">{{ errors.start_date }}</span>
  {% endif %}
  To:
  <input id="end_date" type="date" name="end_date" value="{{end_date}}">
  {% if errors.end_date %}
      <span class="error">{{ errors.end_date }}</span>
  {% endif %}

  <input type="submit">
</form>
</code>```

Note that using a Django form would make it much less painfull (and much more robust too).

Also, it seems you are not really proficient with HTML nor Python. Django is a very handy python web framework but it still requires you to have at least a basic knowledge of HTTP, HTML and, of course, Python. I kindly suggest you take some time learning those topics if you hope to get anything done.

Body:
I'm fairly new to Django and I am facing a bit of a problem. I have my html template in which I have two html date fields - start_date and end_date. I want to pass the contents of those field into my views.py and then display data for that time period, but I am having trouble making it work. Any help will be greatly appreciated. Relevant code:

home.html

  Select time period:

  From:
  <input id = "start_date" type="date" name="From" value="{{data.start_date|date:"d/m/Y"}}">
  To:
  <input id = "end_date" type="date" name="To" value="{{data.end_date|date:"d/m/Y"}}">
  <input type = "submit">

{% for data in data.all %}
      {% if data.profile.user.username == user.username %}

        {{data.profile.user.username}}
        {{data.date}}

      {% endif %}
      {% endfor  %}

views.py

import datetime
from datetime import date

@login_required
def home(request):
    if request.user.is_authenticated():
            user = request.user.username

    start_date = request.GET.get['start_date']
    end_date = request.GET.get['end_date']

    data = Data.objects.filter(date__range=[start_date, end_date])

    context = {

            'data': data,
            'cpu_hours_all': cpu_hours_all,
    }

models.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE

def __str__(self):
    return self.user.username

class Data(models.Model):
    date = models.DateField(blank=True)
    profile = models.ForeignKey(Profile , on_delete=models.CASCADE)

Thanks in advance!

Body:
You failed to explain what "I am having trouble making it work" actually means, so this will be at most a partial and kind of a "wild guess" answer, but anyway:

First you need to put your fields and submit in a  tag, with the proper HTTP method, and your fields "name" attribute (not the "id" attribute) must match what you're looking up in your view:

<form method="GET">
  <legend>Select time period:</legend>
  <br>
  From:
  <input id="start_date" type="date" name="start_date" value="{{start_date|date:"d/m/Y"}}">
  To:
  <input id="end_date" type="date" name="end_date" value="{{end_date|date:"d/m/Y"}}">
  <input type="submit">
</form>

Also note that we're filling the fields with {{ start_date }} and {{ end_date }} - in your template's context, data is a Queryset and has no start_date nor end_date attributes.

Then in your view you have to use request.GET.get() properly:

@login_required
def home(request):
    # ...
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')

.get() is a method, it must be called, not subscripted (parens, not brackets). Note that until the user actually submits the form, those fields won't be in the querystring and GET.get(...) will return None, so you have to handle this case, either by providing default values to .get() or by testing if the form was submitted and not returning a queryset at all (or returning an empty queryset, or returning the whole unfiltered queryset etc, choice is yours).  Here's a version returning an empty queryset.

Also, since you're not using a Django forms.Form, what you will get here are raw unsanitized strings, while Queryset.filter() expects Python datetime.date or datetime.datetime objects, so you'll have to validate and convert those values manually:

# ...
parsed_start_date = None
parsed_end_date = None
if start_date and end_date:
    errors = {}
    try:
        parsed_start_date = datetime.datetime.strptime(start_date, "%d/%m/%Y")
    except ValueError:
        errors["start_date"] = "Invalid date" # etc..
    try:
        parsed_end_date = datetime.datetime.strptime(end_date, "%d/%m/%Y")
    except ValueError:
        errors["end_date"] = "Invalid date" # etc..

if parsed_start_date and parsed_end_date:
    data = Data.objects.filter(date__range=[parsed_start_date, parsed_end_date])
else:
    data = Data.objects.none()  # empty queryset

context = {
        'data': data,
        'errors': errors,
        'start_date': start_date,
        'end_date': end_date
       }

# etc

And then you have to change your template to accomodate those changes (don't try to apply the |date filter to strings, display errors...):

<form method="GET">
  Select time period:
  <br>
  From:
  <input id="start_date" type="date" name="start_date" value="{{start_date}}">
  {% if errors.start_date %}
      <span class="error">{{ errors.start_date }}</span>
  {% endif %}
  To:
  <input id="end_date" type="date" name="end_date" value="{{end_date}}">
  {% if errors.end_date %}
      <span class="error">{{ errors.end_date }}</span>
  {% endif %}

  <input type="submit">
</form>

Note that using a Django form would make it much less painfull (and much more robust too).

Also, it seems you are not really proficient with HTML nor Python. Django is a very handy python web framework but it still requires you to have at least a basic knowledge of HTTP, HTML and, of course, Python. I kindly suggest you take some time learning those topics if you hope to get anything done.


问:
How to display name onmouseover in a marker : Google Map API
I have added multiple marker in my google map using google map library.It's working properly but my issue is that, i want to display a name onmouseover of a marker.And i have tried like this.

Code:

```<code>    $config['zoom'] = 'auto';
    $this->googlemaps->initialize($config);
    $i = 0;
    while($i < $rs){
    $marker = array();
    $marker['position'] = $data['tunnelsname'][$i]->name;
    $marker['onmouseover'] = 'hii';
    $x = $data['tunnelsname'][$i]->name;
    $name = strtolower(str_replace(' ','-',$data['tunnelsname'][$i]->name));
    $id = $data['tunnelsname'][$i]->id;
    $marker['infowindow_content'] = '<a href = "'.BASEURL.'tunnel/'.$name.'/'.$id.'">'.$x.'</a>';
    $marker['clickable'] = TRUE;
    $this->googlemaps->add_marker($marker);
    $i++;
    }
    $data['map'] = $this->googlemaps->create_map();
</code>```

I am trying to display hii onmouseover on each marker.But unable to get a desirable result.Please help me to get this.

Any help will be appreciated. Thanks in advance.

答:
The easy, already implemented way to display a short text onmouseover is to use the marker "title" property. You can use it direct in the basic marker definition:

```<code>var marker = new google.maps.Marker({
  position: {lat: x.x, lng: x.x},
      title: 'hii',
  map: map
});
</code>```

or do it later using the property:

```<code>marker.setTitle('hii')
</code>```

Body:
I have added multiple marker in my google map using google map library.It's working properly but my issue is that, i want to display a name onmouseover of a marker.And i have tried like this.

Code:

    $config['zoom'] = 'auto';
    $this->googlemaps->initialize($config);
    $i = 0;
    while($i < $rs){
    $marker = array();
    $marker['position'] = $data['tunnelsname'][$i]->name;
    $marker['onmouseover'] = 'hii';
    $x = $data['tunnelsname'][$i]->name;
    $name = strtolower(str_replace(' ','-',$data['tunnelsname'][$i]->name));
    $id = $data['tunnelsname'][$i]->id;
    $marker['infowindow_content'] = ''.$x.'';
    $marker['clickable'] = TRUE;
    $this->googlemaps->add_marker($marker);
    $i++;
    }
    $data['map'] = $this->googlemaps->create_map();

I am trying to display hii onmouseover on each marker.But unable to get a desirable result.Please help me to get this.

Any help will be appreciated. Thanks in advance.

Body:
The easy, already implemented way to display a short text onmouseover is to use the marker "title" property. You can use it direct in the basic marker definition:

var marker = new google.maps.Marker({
  position: {lat: x.x, lng: x.x},
      title: 'hii',
  map: map
});

or do it later using the property:

marker.setTitle('hii')


问:
How to Set a Custom Font in the ActionBar Title?
How (if possible) could I set a custom font in a ActionBar title text(only - not the tab text) with a font in my assets folder? I don't want to use the android:logo option. </p>

答:
From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!

Follow these steps to change the font of Toolbar Title:

Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to res > font as per Fonts in XML

In res > values > styles, paste the following (use your imagination here!)

```<code><style name="TitleBarTextAppearance" parent="android:TextAppearance">
    <item name="android:fontFamily">@font/your_desired_font</item>
    <item name="android:textSize">23sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@android:color/white</item>
</style>
</code>```

Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont" as shown below

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:titleTextAppearance="@style/TitleBarTextAppearance"
    app:popupTheme="@style/AppTheme.PopupOverlay"/>
</code>```

Enjoy Custom Actionbar Title font styling!!

Body:
From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!

Follow these steps to change the font of Toolbar Title:

Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to res > font as per Fonts in XML

In res > values > styles, paste the following (use your imagination here!)

<style name="TitleBarTextAppearance" parent="android:TextAppearance">
    <item name="android:fontFamily">@font/your_desired_font</item>
    <item name="android:textSize">23sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@android:color/white</item>
</style>

Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont" as shown below

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:titleTextAppearance="@style/TitleBarTextAppearance"
    app:popupTheme="@style/AppTheme.PopupOverlay"/>

Enjoy Custom Actionbar Title font styling!!


问:
Parsing an XML file with a DTD schema on a relative path
I have the following java code:

```
<code>
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(new File("/opt/myfile"));
</code>
```

And /opt/myfile contains something like:

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE archive SYSTEM "../../schema/xml/schema.dtd">
...
```

I get the following error:

```
java.io.FileNotFoundException: /../schema/xml/schema.dtd (No such file or directory)
```

This is a large java framework that consumes an XML file produced elsewhere.  I think the relative path is the problem.  I don't think it will be acceptable to change the cwd before the JVM starts (the path comes from a config file that is read by the JVM itself) and I have not found a way to change the cwd while the JVM is running.  How do I parse this XML file with the appropriate DTD?

答:
You need to use a custom EntityResolver to tweak the path of the DTD so that it can be found. For example:

```<code>db.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId.contains("schema.dtd")) {
            return new InputSource(new FileReader("/path/to/schema.dtd"));
        } else {
            return null;
        }
    }
});
</code>```

If schema.dtd is on your classpath, you can just use getResourceAsStream to load it, without specifying the full path:

```<code>return new InputSource(Foo.class.getResourceAsStream("schema.dtd"));
</code>```

Body:
I have the following java code:

DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(new File("/opt/myfile"));

And /opt/myfile contains something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE archive SYSTEM "../../schema/xml/schema.dtd">
...

I get the following error:

java.io.FileNotFoundException: /../schema/xml/schema.dtd (No such file or directory)

This is a large java framework that consumes an XML file produced elsewhere.  I think the relative path is the problem.  I don't think it will be acceptable to change the cwd before the JVM starts (the path comes from a config file that is read by the JVM itself) and I have not found a way to change the cwd while the JVM is running.  How do I parse this XML file with the appropriate DTD?

Body:
You need to use a custom EntityResolver to tweak the path of the DTD so that it can be found. For example:

db.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId.contains("schema.dtd")) {
            return new InputSource(new FileReader("/path/to/schema.dtd"));
        } else {
            return null;
        }
    }
});

If schema.dtd is on your classpath, you can just use getResourceAsStream to load it, without specifying the full path:

return new InputSource(Foo.class.getResourceAsStream("schema.dtd"));


问:
MATLAB For loop optimization
I'm completely new to MATLAB, and I still don't know the functions and way of programming with it.

I have a 3D matrix : 19*1000*134 with data that I want to filter with a butterworth.
I did a code with a double for loop that works perfectly well:

```<code>%% Filtering
w1 = 1/(fs/2);
w2 = 45/(fs/2);
[b, a] = butter(6, [w1 w2], 'bandpass');

for i=1:channel
    for j=1:nb_epoch
        Data_filtered(i,:,j) = filtfilt(b, a, s_EEG.data(i,:,j));
    end
end
</code>```

Is there any other way of doing the same thing better or not ? Since I don't know MATLAB, I'm not sure it's the best way of implementing this bandpass filter.

Thanks!

答:
The only optimization I can figure out is using parfors:

```<code>w1 = 1/(fs/2);
w2 = 45/(fs/2);
[b, a] = butter(6, [w1 w2], 'bandpass');

parfor i=1:channel
    parfor j=1:nb_epoch
        Data_filtered(i,:,j) = filtfilt(b, a, s_EEG.data(i,:,j));
    end
end
</code>```

Keep in mind that the first time you run parfors, since the workers pool is empty, the script will be much much slower because workers must be instantiated and initialized. Multithreading should help.

Title: MATLAB For loop optimization

Body:
I'm completely new to MATLAB, and I still don't know the functions and way of programming with it.

I have a 3D matrix : 19*1000*134 with data that I want to filter with a butterworth.
I did a code with a double for loop that works perfectly well:

%% Filtering
w1 = 1/(fs/2);
w2 = 45/(fs/2);
[b, a] = butter(6, [w1 w2], 'bandpass');

for i=1:channel
    for j=1:nb_epoch
        Data_filtered(i,:,j) = filtfilt(b, a, s_EEG.data(i,:,j));
    end
end

Is there any other way of doing the same thing better or not ? Since I don't know MATLAB, I'm not sure it's the best way of implementing this bandpass filter.

Thanks!

Body:
The only optimization I can figure out is using parfors:

w1 = 1/(fs/2);
w2 = 45/(fs/2);
[b, a] = butter(6, [w1 w2], 'bandpass');

parfor i=1:channel
    parfor j=1:nb_epoch
        Data_filtered(i,:,j) = filtfilt(b, a, s_EEG.data(i,:,j));
    end
end

Keep in mind that the first time you run parfors, since the workers pool is empty, the script will be much much slower because workers must be instantiated and initialized. Multithreading should help.


问:
Argument missing (syntax errors)
Can someone please help me with this syntax which I have broken. I just can't see the error.

using UnityEngine;
using System.Collections;

public class website : MonoBehaviour {
    public void OnActivation()
    {

        InAppBrowser.OpenURL(http://stolepersteine.jimbo.com);
    }
}
```

答:
you forgot to put quotes around your string : </p>

```<code>InAppBrowser.OpenURL("http://stolepersteine.jimbo.com");
</code>```

Title: Argument missing (syntax errors)

Body:
you forgot to put quotes around your string :

InAppBrowser.OpenURL("http://stolepersteine.jimbo.com");


问:
Create natural disaster model in unity3D
I am working on a application where, I would like to make a 3D terrain model of my country in unity3D in clusive of hills, mountains and rivers. So far I've been able to use mapbox to import the country map because unity wrld sdk doesn't yet support my country.

However the end goal is to create an application capable of representing natural disasters. Example, I have the country. I would like to know how would one go about causing rain to occurred that would essentially affect the "water levels"  of the river and essentially show a flood. Basically, after I bring in the terrain how do I "act" on it to cause a landslide.

Any help or tutorial pointing to such would be welcomed.

答:
You will need different models for each natural disaster. You will always only get a rough estimate of what may happen as your data will never represent the actual terrain. (For example earthquake, you may be able to reproduce damage to structures but never be able to predict if there will be a drift in the earth itself)

Rain/ Flood

A really simple simulation of rising ground water is slowly moving a "water" plane up. This crude approach will demonstrate which areas are going to be under water quite easily. For a detailed flood simulation you will need a fluid simulation of any kind (there are quite a few on the asset store)

Avalanche

Treat it as a fluid system with a strong resistance.

Vulcan

Almost the same as a flood, just with more viscosity.

Earthquake

You may be able to simulate the damage of an earthquake if all your objects have some kind of break point and the earthquake is added force to an area. A set force has an certain chance to destroy the object in the area. (Think of it in terms like any castle destroy game aka Flappy Bird, the bullet is your local earthquake and the castle your terrain + building/ trees)

Fire

You will need something like a burn value. Higher value = the longer it burns, harder to put out, faster spread. If a fire starts at any given point, it grows around. A river would have a value of 0, same as mountains. A forest would have a high value, a grass plain a low value. If you want to simulate a hot dry summer, your terrain could add a fixed value to everything, grass gets drying and thus has a higher chance to spread fire.


问:
unminify pug using plugin ExtractTextPlugin
When I extract a .pug file with ExtractTextPlugin, it converts it to html but minify, as it unminify??</p>

```<code>const extractHTML = new ExtractTextPlugin('[name]-pug.html');

....

{
    test: /\.pug$/,
    use: extractHTML.extract({
        fallback: "style-loader",
        use: ['html-loader' ,'pug-html-loader'],
        options: {
            pretty: true
        }
    })
}
</code>```

答:
This is what I used to output unminified HTML:</p>

```<code>  {
    test: /\.pug$/,
    include: path.join(__dirname, 'src'),
    use: [{
      loader: 'pug-loader',
      options: { pretty: true },
    }],
  },
</code>```

Body:
When I extract a .pug file with ExtractTextPlugin, it converts it to html but minify, as it unminify??

const extractHTML = new ExtractTextPlugin('[name]-pug.html');

....

{
    test: /\.pug$/,
    use: extractHTML.extract({
        fallback: "style-loader",
        use: ['html-loader' ,'pug-html-loader'],
        options: {
            pretty: true
        }
    })
}

Body:
This is what I used to output unminified HTML:

  {
    test: /\.pug$/,
    include: path.join(__dirname, 'src'),
    use: [{
      loader: 'pug-loader',
      options: { pretty: true },
    }],
  },


问:
background gps location in react native
I want to track my location when app is background state, i can track my location when it foreground, but i want to track even in background also, i need to pass the my gps location to the my server, for that one i used some module like :
https://www.npmjs.com/package/react-native-mauron85-background-geolocation
but it is not showing any location like that,

even i checked the example also for this one but i didn't got the correct response for it,

Here is the link for example:
https://github.com/mauron85/react-native-background-geolocation-example

when i run this example and click on play button it is showing an error alert and undefined,

can any one give me suggestions that how to resolve this error.

Any help much appreciated.

答:
Changes to location tracking in iOS 11

iOS 11 also makes some major changes to existing APIs. One of the affected areas is location tracking. If your app only uses location while the app is in the foreground, as most apps do, you might not have to change anything at all; however, if it’s one of those apps that continuously track user’s location throughout the day, you should probably book some time this summer for making some changes in how you do the tracking and testing possible usage scenarios.

follow this link: https://mackuba.eu/2017/07/13/changes-to-location-tracking-in-ios-11/

Hope will helpful to you!!

Title: background gps location in react native


问:
How can I delete Docker images by tag, preferably with wildcarding?
I have some automated processes that spew a bunch of Docker images tagged with meaningful labels.  The labels follow a structured pattern.

Is there a way to find and delete images by tag?  So assume I have images:

```<code>REPOSITORY                  TAG
junk/root                   stuff_687805
junk/root                   stuff_384962
</code>```

Ideally I'd like to be able to do:  docker rmi -tag stuff_*

Any good way to simulate that?

答:
Using only docker filtering:

```<code> docker rmi $(docker images --filter=reference="*:stuff_*" -q)
</code>```

reference="*:stuff_*" filter allows you to filter images using a wildcard;

-q option is for displaying only image IDs.

Update: Wildcards are matched like paths. That means if your image id is my-company/my-project/my-service:v123 then the * won't match it, but the */*/* will. See the github issue for description.

Body:
I have some automated processes that spew a bunch of Docker images tagged with meaningful labels.  The labels follow a structured pattern.

Is there a way to find and delete images by tag?  So assume I have images:

REPOSITORY                  TAG
junk/root                   stuff_687805
junk/root                   stuff_384962

Ideally I'd like to be able to do:  docker rmi -tag stuff_*

Any good way to simulate that?

Body:
Using only docker filtering:

 docker rmi $(docker images --filter=reference="*:stuff_*" -q)

reference="*:stuff_*" filter allows you to filter images using a wildcard;

-q option is for displaying only image IDs.

Update: Wildcards are matched like paths. That means if your image id is my-company/my-project/my-service:v123 then the * won't match it, but the */*/* will. See the github issue for description.


问:
how to close connection/datareader when using SqlDataSource or ObjectDataSource
during beta testing we discovered connection pooling error messages . Therefore I have been going through the code and closing down the SqlDataReader objects wherever they have been left unclosed. What I need to know is how to close a datareader (or if there is a need at all to close) that is specified in the SelectStatement attribute of the SqlDataSource or ObjectDataSource tags. Could there be connection leak if they are not handled?

Thanks in advance !

答:
We had the same problems here in a production environment.

Solved the issue. The problem first was, there were no using statements at all in my code.
(It was build a few years ago, with some less knowledge).

I then tried putting the SqlDataSource in a using clause. But this didn't help either.

The trick here is, just like tvanfosson and Mischa are suggesting, putting the reader in a using clause.  This is the object that actually closes the connection.

The number of connections shrunk to the minimum pool size of 10 at medium load.

OwnerDisplayName: Aamir


问:
How to display test images with prediction
I want display my test images with predicted label for it.

```<code>train_step.run(feed_dict={x: images32, y_: one_hot_lables})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval(feed_dict={x: test_images32, y_: T_one_hot_lables}))
</code>```

I only print result, but i want display every images in test_images32 and predicted label

答:
This naturally depends on the shape of the data, but for general deep learning problems I use the following method using matplotlib. You might want to extend this using plt.ion() to make this interactive and wait after each image shown.

```<code>import matplotlib.pyplot as plt

predictions = sess.run(y, {feed_dict={x: test_images32}})
for i, image in enumerate(test_images32):
     plt.imshow(image) # depending on being RGB or gray this might need to be reshaped
     print(np.argmax(predictions[i]))
</code>```

Body:
I want display my test images with predicted label for it.

train_step.run(feed_dict={x: images32, y_: one_hot_lables})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval(feed_dict={x: test_images32, y_: T_one_hot_lables}))

I only print result, but i want display every images in test_images32 and predicted label

Body:
This naturally depends on the shape of the data, but for general deep learning problems I use the following method using matplotlib. You might want to extend this using plt.ion() to make this interactive and wait after each image shown.

import matplotlib.pyplot as plt

predictions = sess.run(y, {feed_dict={x: test_images32}})
for i, image in enumerate(test_images32):
     plt.imshow(image) # depending on being RGB or gray this might need to be reshaped
     print(np.argmax(predictions[i]))


问:
Doctrine query builder "leftJoin" in many to many relationship
I have two entities Message and Skill, and many to many relationship between them. I am trying to get all messages with skill=5 or without any skills.

```<code>$queryBuilder = $repository->createQueryBuilder('entity');
$queryBuilder->leftJoin('entity.skills', 'skill');
$queryBuilder->andWhere(
    $criteria->expr()->orX(
        $criteria->expr()->eq('skill.id', 5),
        $criteria->expr()->isNull('skill.id')
  )
)
</code>```

But in results I have question ONLY with skill=5.
How can I select questions without skill or with skill=5 is SINGLE query?

答:
```<code>$queryBuilder = $repository->createQueryBuilder('entity');
$queryBuilder->leftJoin('entity.skills', 'skill');
$queryBuilder->where('skill.id = 5');
$queryBuilder->orWhere('skill.id IS NULL');
</code>```

Body:
I have two entities Message and Skill, and many to many relationship between them. I am trying to get all messages with skill=5 or without any skills.

$queryBuilder = $repository->createQueryBuilder('entity');
$queryBuilder->leftJoin('entity.skills', 'skill');
$queryBuilder->andWhere(
    $criteria->expr()->orX(
        $criteria->expr()->eq('skill.id', 5),
        $criteria->expr()->isNull('skill.id')
  )
)

But in results I have question ONLY with skill=5.
How can I select questions without skill or with skill=5 is SINGLE query?


问:
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

答:
The code goes like this:

```<code>i = 2;
while (i <= sqrt(static_cast<double>(n)) {
  if (n % i == 0) is_prime = false;
  i++;
}
</code>```

So the loop is checking if n is divisible by i without remainder. Obviously, only has to check this up to (and including) the square root of n (because if n / p = q then also n / q = p).

Title: while (i<=sqrt(static_cast<double>(n))

Body:
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

while (i<=sqrt(static_cast<double>(n))

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

Body:
The code goes like this:

i = 2;
while (i <= sqrt(static_cast<double>(n)) {
  if (n % i == 0) is_prime = false;
  i++;
}

So the loop is checking if n is divisible by i without remainder. Obviously, only has to check this up to (and including) the square root of n (because if n / p = q then also n / q = p).


问:
Invalid argument type when trying to download specific files from S3 bucket to EC2 using subprocess
I am trying to download certain files from S3 to local machine by running the following code:

```<code>import subprocess, os
ec2_root = '/home/'
s3_root_path = "S3://bucket-name/"
s3_download_command = ["aws", "s3", "cp", os.path.join(s3_root_path, 'my_video.mp4'), os.path.join(local_root)]
p = subprocess.Popen(s3_download_command)
p.communicate()
</code>```

But I get the following error:
usage: aws s3 cp <LocalPath> <S3Uri> or <S3Uri> <LocalPath> or <S3Uri> <S3Uri> Error: Invalid argument type

答: It turned out that I used S3:// with a capital S instead of small s.

Body:
I am trying to download certain files from S3 to local machine by running the following code:

import subprocess, os
ec2_root = '/home/'
s3_root_path = "S3://bucket-name/"
s3_download_command = ["aws", "s3", "cp", os.path.join(s3_root_path, 'my_video.mp4'), os.path.join(local_root)]
p = subprocess.Popen(s3_download_command)
p.communicate()

But I get the following error:
usage: aws s3 cp <LocalPath> <S3Uri> or <S3Uri> <LocalPath> or <S3Uri> <S3Uri> Error: Invalid argument type


问:
Slider binded to two different Textbox with different range
I have a Slider in WPF and I want to bind the same slider to two different Values. But each of these values have different range. For example the first one represents time and changes between 0 to 1.5 second and the second value represent percentage that ranges from 0 to 100. Is it possible to bind the value of the Slider to both of them in a way that user can also type any value within the range and both slider and other value get updated. For example if the user put the time value to 1, the Slider should move and also the value of the percentage should be set to 66.66 %.

Thanks in advance

答:
Your solution might be something like this:

MainWindow.xaml

```<code><Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfApp1="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        d:DataContext="{d:DesignInstance d:Type=wpfApp1:SampleViewModel}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <TextBlock Text="0-1.5" Grid.Column="0" Grid.Row="0"/>
        <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Value1, Mode=TwoWay}"/>

        <TextBlock Text="0-100" Grid.Column="0" Grid.Row="1"/>
        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Value2, Mode=TwoWay}"/>

        <Slider Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" Height="25" Minimum="0" Maximum="100" Value="{Binding Value2}"/>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs

```<code>using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;

namespace WpfApp1
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new SampleViewModel();
        }
    }

    public sealed class SampleViewModel : INotifyPropertyChanged
    {
        private double _value1;
        private double _value2;

        public event PropertyChangedEventHandler PropertyChanged;

        public double Value1
        {
            get { return _value1; }
            set
            {
                if (_value1 == value)
                    return;

                _value1 = value;
                OnPropertyChanged(nameof(Value1));
                _value2 = Math.Round(100 / 1.5 * value, 1);
                OnPropertyChanged(nameof(Value2));
            }
        }

        public double Value2
        {
            get { return _value2; }
            set
            {
                if (_value2 == value)
                    return;

                _value2 = value;
                OnPropertyChanged(nameof(Value2));
                _value1 = Math.Round(1.5 /100* value, 1);
                OnPropertyChanged(nameof(Value1));
            }
        }
    private void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

However its for a 'well-known' min/max values. If you need dynamic ones (you dont know min/max on compile time, and it would be the only right solution to avoid any hardcoded stuff) you need to do some math.
Also you can achieve the same result using multibinding, just pass min/max and values and do all the math inside.

Body:
Your solution might be something like this:

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfApp1="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        d:DataContext="{d:DesignInstance d:Type=wpfApp1:SampleViewModel}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <TextBlock Text="0-1.5" Grid.Column="0" Grid.Row="0"/>
        <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Value1, Mode=TwoWay}"/>

        <TextBlock Text="0-100" Grid.Column="0" Grid.Row="1"/>
        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Value2, Mode=TwoWay}"/>

        <Slider Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" Height="25" Minimum="0" Maximum="100" Value="{Binding Value2}"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;

namespace WpfApp1
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new SampleViewModel();
        }
    }

    public sealed class SampleViewModel : INotifyPropertyChanged
    {
        private double _value1;
        private double _value2;

        public event PropertyChangedEventHandler PropertyChanged;

        public double Value1
        {
            get { return _value1; }
            set
            {
                if (_value1 == value)
                    return;

                _value1 = value;
                OnPropertyChanged(nameof(Value1));
                _value2 = Math.Round(100 / 1.5 * value, 1);
                OnPropertyChanged(nameof(Value2));
            }
        }

        public double Value2
        {
            get { return _value2; }
            set
            {
                if (_value2 == value)
                    return;

                _value2 = value;
                OnPropertyChanged(nameof(Value2));
                _value1 = Math.Round(1.5 /100* value, 1);
                OnPropertyChanged(nameof(Value1));
            }
        }
    private void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

However its for a 'well-known' min/max values. If you need dynamic ones (you dont know min/max on compile time, and it would be the only right solution to avoid any hardcoded stuff) you need to do some math.
Also you can achieve the same result using multibinding, just pass min/max and values and do all the math inside.


问:
In jQuery Ajax, dataType: jsonp gives "SyntaxError: unterminated string literal" while dataType:json works fine?
Below is the AJAX call using jsonp, I get "SyntaxError: unterminated string literal" in console.

this.API_DOMAIN is the 3rd party website. Thus using jsonp for cross domain. However same AJAX works fine with dataType: json.

The response has description which contains '‘LIVE’“' which the console gives an error.

But why does it work fine with dataType : 'json' and not with dataType: 'jsonp' ?

What can be the problem ?

```<code>var ajaxlink = this.API_DOMAIN+'callJson.php';
$.ajax({
  url: ajaxlink,
  type: 'GET',
  data:{
    oauth_token: this.API_KEY,
    id:eventId,
    moreInfo:'artistinfo,booking,multiplebooking',
    lang:LANG_DEFAULT
  },
  jsonpCallback: "aaaaa",
  cache: true,
  dataType:"jsonp",
  success: function(data){
    console.log("similar event success");
    console.log(data);
  },
  error: function(){
    console.log("error");
  }
});
</code>```

答:
Is your string delimited by single quote or double quotes?
Special char should be escaped, and if it's multiline concatenatewith plus sign or backslash sign.
var s = "This is a very long string  \
the second part od the string";</p>

Body:
Below is the AJAX call using jsonp, I get "SyntaxError: unterminated string literal" in console.

this.API_DOMAIN is the 3rd party website. Thus using jsonp for cross domain. However same AJAX works fine with dataType: json.

The response has description which contains '‘LIVE’“' which the console gives an error.

But why does it work fine with dataType : 'json' and not with dataType: 'jsonp' ?

What can be the problem ?

var ajaxlink = this.API_DOMAIN+'callJson.php';
$.ajax({
  url: ajaxlink,
  type: 'GET',
  data:{
    oauth_token: this.API_KEY,
    id:eventId,
    moreInfo:'artistinfo,booking,multiplebooking',
    lang:LANG_DEFAULT
  },
  jsonpCallback: "aaaaa",
  cache: true,
  dataType:"jsonp",
  success: function(data){
    console.log("similar event success");
    console.log(data);
  },
  error: function(){
    console.log("error");
  }
});


问:
Plugin Error: required plugin "Android Support" is disabled
I have a plugin error in my logcat

```<code>   10:08:28 PM Plugin Error
        Problems found loading plugins:
        Plugin "Google Analytics Uploader" was not loaded: required plugin "Android Support" is disabled.
        Plugin "SDK Updater" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google App Indexing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Testing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
        Disable not loaded plugins
        Enable Android Support
        Open plugin manager
 10:08:32 PM Error Loading Project: Cannot load 3 facets Details...
</code>```

This happened after I left my laptop to sleep and when I opened android studio, this error popped out. Now I cannot run my project.

答:
Go to Settings->Plugins->IDE Settings and just disable and enable again needed plugins.
Apply changes when you enable/disable.

Body:
I have a plugin error in my logcat

   10:08:28 PM Plugin Error
        Problems found loading plugins:
        Plugin "Google Analytics Uploader" was not loaded: required plugin "Android Support" is disabled.
        Plugin "SDK Updater" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google App Indexing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Cloud Testing" was not loaded: required plugin "Android Support" is disabled.
        Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
        Disable not loaded plugins
        Enable Android Support
        Open plugin manager
 10:08:32 PM Error Loading Project: Cannot load 3 facets Details...

This happened after I left my laptop to sleep and when I opened android studio, this error popped out. Now I cannot run my project.


问:
Multiple material on single obj file with three.js
I'm using three.js to load an obj file, a ring with some pearls. I haven't got an mtl file, as the software we use to export the obj (rhinoceros(?)) won't generate it with an obj file (this is what I was told by the graphic designer).

I need to set a metallic material ONLY for the ring, and glass material ONLY for the stone/pearls.

This is a link to the test page where I actually load the file:
jaaxlab.com/test_youring

...for the rest I don't know how to set a single material and also multiple.

Link to obj file jaaxlab.com/test_youring/obj/prova1.obj

答:
Your object has several children. The child with index 0 is the ring. Also, its name is sezione_B_misura13_Riviera_mix_full anello_sezione_B_misura13.

So, you can access it like:

```<code>obj.children[0].material = new THREE.MeshStandardMaterial(...);
</code>```

or

```<code>obj.getObjectByName('sezione_B_misura13_Riviera_mix_full anello_sezione_B_misura13').material = new THREE.MeshStandardMaterial(...);
</code>```

Given that obj is the object, loaded with you loader.

Take a look at this jsfiddle. Load your file, then check the console log. You can also click any part of the object and see its id and name in the console.

Body:
Your object has several children. The child with index 0 is the ring. Also, its name is sezione_B_misura13_Riviera_mix_full anello_sezione_B_misura13.

So, you can access it like:

obj.children[0].material = new THREE.MeshStandardMaterial(...);

or

obj.getObjectByName('sezione_B_misura13_Riviera_mix_full anello_sezione_B_misura13').material = new THREE.MeshStandardMaterial(...);

Given that obj is the object, loaded with you loader.

Take a look at this jsfiddle. Load your file, then check the console log. You can also click any part of the object and see its id and name in the console.


问:
SSIS error calling Script task in child package
I have a child package that runs perfectly when executed in isolation. When I call the same package from a Parent package via an Execute Package Task I get the error:

0xC000F427 To run a SSIS package outside of SQL Server Data Tools you must install Standard Edition of Integration Services or higher.

The parent package also has a script task prior to calling the child and this runs successfully.

Note: I am developing and testing on my workstation.

答:
Try : Select the Execute Package Task, hit F4 (properties) and change ExecuteOutOfprocess to false. https://learn.microsoft.com/en-us/sql/integration-services/control-flow/execute-package-task
"If you set the property to True, you cannot debug the package in a tools-only install. You must install Integration Services. "
 Let us know if it worked.</p>


问:
Select from mysql table unique records according to a Field
I have a table in MySQL which I store registrations info.

I need to select all rows but only the latest according to email field and ID field

My table:

and I need

答:
```<code>select *
from yourTablename
where (id,email) in
        (select max(id),email from yourTablename group by email);
</code>```

Another approach with Inner Join:(As suggested by Tim)

```<code>SELECT t1.*
FROM t t1
INNER JOIN
(
    SELECT email, MAX(id) AS max_id
    FROM t t2
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.id  = t2.max_id;
</code>```

DEMO

Body:
select *
from yourTablename
where (id,email) in
        (select max(id),email from yourTablename group by email);

Another approach with Inner Join:(As suggested by Tim)

SELECT t1.*
FROM t t1
INNER JOIN
(
    SELECT email, MAX(id) AS max_id
    FROM t t2
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.id  = t2.max_id;

DEMO


问:
Flask: passing Python variables on the server to React component
I am practicing Flask + React in this repo.

I currently have the same issue,
I am unable to pass variables from Flask to React components through props.
I have found this older post but it didn't provide more insight.

My code boils down to:

server.py

```<code>def index():
return render_template('index.html', bar='hello')
</code>```

index.jsx

```<code>ReactDOM.render(<App foo={ bar } />, document.getElementById('content'));
</code>```

Console Error

```<code>index.jsx?3769:5 Uncaught ReferenceError: bar is not defined
</code>```

What is the appropriate way of passing information from the server to the components?

Thank you very much in advance

UPDATE

I figured out a solution, here are the changes.

Is that the "scotch-taped" way of passing data? or that is as good as it gets?

答:
Your problem is that you are trying to access to template variable directly from your javascript code. you cannot have a direct access.

There is multiple ways to pass variables from your html template to your React DOM. Here are two options that you can use :

in your template index.html, the variable bar passed through attributes :

in your index.jsx:

ReactDOM.render(
  <App{...(content.dataset)} test={test}/>,
  document.getElementById('content')
);

Here is a jsfiddle with an example of code in jsfiddle

Body:
I am practicing Flask + React in this repo.

I currently have the same issue,
I am unable to pass variables from Flask to React components through props.
I have found this older post but it didn't provide more insight.

My code boils down to:

server.py

def index():
return render_template('index.html', bar='hello')

index.jsx

ReactDOM.render(<App foo={ bar } />, document.getElementById('content'));

Console Error

index.jsx?3769:5 Uncaught ReferenceError: bar is not defined

What is the appropriate way of passing information from the server to the components?

Thank you very much in advance

UPDATE

I figured out a solution, here are the changes.

Is that the "scotch-taped" way of passing data? or that is as good as it gets?

Body:
Your problem is that you are trying to access to template variable directly from your javascript code. you cannot have a direct access.

There is multiple ways to pass variables from your html template to your React DOM. Here are two options that you can use :

in your template index.html, the variable bar passed through attributes :

<div id="content" data-foo={bar}></div>
<script>
  window.test = { bar }; // the variable bar passed in a script tag
</script>

in your index.jsx:

ReactDOM.render(
  <App{...(content.dataset)} test={test}/>,
  document.getElementById('content')
);

Here is a jsfiddle with an example of code in jsfiddle


问:
Visual Studio 2008 unit testing using the same file resource
I am using the built-in unit testing framework of Visual Studio 2008 to get my feet wet with TDD of a C# WinForms application. The application works with proprietary image data formats and I've broken up sample files into their component sections (header, metadata, single frames, all frames, etc) to allow for testing. Several of my test methods use the same data chunk and when I choose the 'Run All Tests in Solution' option, the tests using the same data chunk fail with "System.IO.IOException: The process cannot access the file 'datachunk.dat' because it is being used by another process." These tests pass when they are run individually. Is there a way I can tell Visual Studio not to try and run these tests at the same time or am I going about this the wrong way?</p>

答: Read it once in a TestInitialize function, reading into a field, so it is available to all the tests in the class.


问:
Eclipse/Java9: how to access internal javafx packages?
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

```<code>import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}
</code>```

won't compile due to

```<code>The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible
</code>```

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error
</code>```

The error is similar to the one in Eclipse. Works fine with --add-exports:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java
</code>```

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?

答:
In Project > Properties: Java Build Path, Libraries tab, select the node Modulepath/JRE System Library[JavaSE-9]/Is modular and click Edit...

In the Module Properties dialog, in the Details tab, in the Added exports section click Add... and enter the following:

Source module: javafx.controls

Package: com.sun.javafx.scene.control

Click OK twice to close the Add-exports configuration and the Module Properties dialogs and Apply and Close to close the Properties dialog

Body:
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}

won't compile due to

The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error

The error is similar to the one in Eclipse. Works fine with --add-exports:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?