问:
reduce output using SQL query
data in tables is:

Ticket table

```<code>Ticket_Nbr            ,  aaa.pnr_ticket_id
2303167095666         ,  5889503
2         ,  2345
3         ,  3456
4         ,  4567
5         ,  5678
</code>```

Coupon table

```<code>CPN_FRM_SER       ,  CPN_NUM,  FRM_CITY,  TO_CITY
2303167095666     ,  1      ,  SCL     ,  PTY
2303167095666     ,  2      ,  PTY     ,  SFO
2303167095666     ,  3      ,  SFO     ,  SEA
2303167095666     ,  4      ,  SEA     ,  SFO
</code>```

Query is:

```<code>    SELECT
    XMLElement
    (
        "Eticket",
        XMLElement("Ticket", XMLAttributes(t.ticket_nbr AS "NBR")),
        (
            SELECT XMLAGG(XMLElement("COUPON", XMLAttributes(c.cpn_num AS "COUPON_NUM", c.frm_city AS "FROM_CITY", c.to_city AS "TO_CITY")))
            FROM coupon c
            WHERE c.cpn_frm_ser = t.ticket_nbr
        ) AS "coupon"
    )
FROM ticket t,
    coupon c
WHERE c.cpn_frm_ser = t.ticket_nbr
    AND t.aaa_pnr_ticket_id = '5889503';
</code>```

Output generated is:

```<code><Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
</code>```

The same line of output data repeated 4 times.

I am looking for only one output line of data, instead of 4 lines, any help would be appreciated.

答:
You don't need to join the coupon table outside. Just the correlated subquery is enough.

```<code>select XMLElement("Eticket",
            XMLElement("Ticket", XMLAttributes(t.ticket_nbr as "NBR")),
            (
            select XMLAGG(
                XMLElement(
                    "COUPON",
                    XMLAttributes(
                        c.cpn_num as "COUPON_NUM",
                        c.frm_city as "FROM_CITY",
                        c.to_city as "TO_CITY"
                        )
                    )
                )
            from coupon c
            where c.cpn_frm_ser = t.ticket_nbr
            ) as "coupon")
from ticket t
where t.aaa_pnr_ticket_id = '5889503';
</code>```

Demo

Title: reduce output using SQL query

Body:
data in tables is:

Ticket table

Ticket_Nbr            ,  aaa.pnr_ticket_id
2303167095666         ,  5889503
2         ,  2345
3         ,  3456
4         ,  4567
5         ,  5678

Coupon table

CPN_FRM_SER       ,  CPN_NUM,  FRM_CITY,  TO_CITY
2303167095666     ,  1      ,  SCL     ,  PTY
2303167095666     ,  2      ,  PTY     ,  SFO
2303167095666     ,  3      ,  SFO     ,  SEA
2303167095666     ,  4      ,  SEA     ,  SFO

Query is:

    SELECT
    XMLElement
    (
        "Eticket",
        XMLElement("Ticket", XMLAttributes(t.ticket_nbr AS "NBR")),
        (
            SELECT XMLAGG(XMLElement("COUPON", XMLAttributes(c.cpn_num AS "COUPON_NUM", c.frm_city AS "FROM_CITY", c.to_city AS "TO_CITY")))
            FROM coupon c
            WHERE c.cpn_frm_ser = t.ticket_nbr
        ) AS "coupon"
    )
FROM ticket t,
    coupon c
WHERE c.cpn_frm_ser = t.ticket_nbr
    AND t.aaa_pnr_ticket_id = '5889503';

Output generated is:

<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>
<Eticket>
  <Ticket NBR="2302167019566"></Ticket>
  <AAA_PNR_TICKET ISSUE_DATE="2017-02-13" HA_CC="CM"></AAA_PNR_TICKET>
  <COUPON COUPON_NUM="1" FROM_CITY="SCL" TO_CITY="PTY"></COUPON>
  <COUPON COUPON_NUM="2" FROM_CITY="PTY" TO_CITY="SFO"></COUPON>
  <COUPON COUPON_NUM="3" FROM_CITY="SFO" TO_CITY="SEA"></COUPON>
  <COUPON COUPON_NUM="4" FROM_CITY="SEA" TO_CITY="SFO"></COUPON>
</Eticket>

The same line of output data repeated 4 times.

I am looking for only one output line of data, instead of 4 lines, any help would be appreciated.

Body:
You don't need to join the coupon table outside. Just the correlated subquery is enough.

select XMLElement("Eticket",
            XMLElement("Ticket", XMLAttributes(t.ticket_nbr as "NBR")),
            (
            select XMLAGG(
                XMLElement(
                    "COUPON",
                    XMLAttributes(
                        c.cpn_num as "COUPON_NUM",
                        c.frm_city as "FROM_CITY",
                        c.to_city as "TO_CITY"
                        )
                    )
                )
            from coupon c
            where c.cpn_frm_ser = t.ticket_nbr
            ) as "coupon")
from ticket t
where t.aaa_pnr_ticket_id = '5889503';

Demo


来源: stackexchange

问:
Minimising interpolation error between two data sets
In the top of the diagrams below we can see some value (y-axis) changing over time (x-axis).

As this happens we are sampling the value at different and unpredictable times, also we are alternating the sampling between two data sets, indicated by red and blue.

When computing the value at any time, we expect that both red and blue data sets will return similar values. However as shown in the three smaller boxes this is not the case. Viewed over time the values from each data set (red and blue) will appear to diverge and then converge about the original value.

Initially I used linear interpolation to obtain a value, next I tried using Catmull-Rom interpolation. The former results in a values come close together and then drift apart between each data point; the latter results in values which remain closer, but where the average error is greater.

Can anyone suggest another strategy or interpolation method which will provide greater smoothing (perhaps by using a greater number of sample points from each data set)?

答:
Try B-splines: Catmull-Rom interpolates (goes through the data points), B-spline does smoothing.

For example, for uniformly-spaced data (not your case)

```<code>Bspline(t) = (data(t-1) + 4*data(t) + data(t+1)) / 6
</code>```

Of course the interpolated red / blue curves depend on the spacing of the red / blue data points,
so cannot match perfectly.

ContentLicense: CC BY-SA 2.5

Body:
Try B-splines: Catmull-Rom interpolates (goes through the data points), B-spline does smoothing.

For example, for uniformly-spaced data (not your case)

Bspline(t) = (data(t-1) + 4*data(t) + data(t+1)) / 6

Of course the interpolated red / blue curves depend on the spacing of the red / blue data points,
so cannot match perfectly.


问:
Can I specify or select a member of a class (and use it as parameter )?
For example, let's say I have:

```<code>class AB { float a,b; };
</code>```

How do I write one function that can process either a or b, based on a parameter that's passed in, in a "proper" way? I want to do something like this:

```<code>float getSqrt(AB x, ClassMemberSelector s)
{ return sqrt(x.s); }

AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b
</code>```

答:
```<code>#include <iostream>
#include <cmath>

class AB
{
public:
    float a, b;
};

float getSqrt(AB x, float AB::*mem)
{
    return sqrt(x.*mem);
}

int main()
{
    AB x;
    x.a = 9;
    x.b = 16;
    std::cout << "sqrt x.a: " << getSqrt(x, &AB::a) << std::endl;
    std::cout << "sqrt x.b: " << getSqrt(x, &AB::b) << std::endl;
    system("pause");
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, let's say I have:

class AB { float a,b; };

How do I write one function that can process either a or b, based on a parameter that's passed in, in a "proper" way? I want to do something like this:

float getSqrt(AB x, ClassMemberSelector s)
{ return sqrt(x.s); }

AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b


问:
Display results only on search
I need the search results div to only show when results of a search have been returned (not when the user is searching a term), and then be able to clear the results divs when a new term is searched.

I should be able to use something like $(".results").empty(), but this will keep the results div always blank.

```<code>$("#searchterm").keyup(function(e) {
  var q = $("#searchterm").val();
  //Only begin search with at least 3 characters.
  if (q.length > 3) {
    ajax_search();
  }
  //Send search query
  function ajax_search() {
    $.getJSON("//url-to-search?q=" + q, {},
      //Get results and make 'em look good
      function(data) {
        console.log(data);
        //  $(".results").append("Results for <b> " + q + "</b>");
        $.each(data.data, function(i, data) {
          if (data.type === "category-1") {
            if ($(".category-1").text() == '') {
              $(".category-1-results-header, .category-1").hide()
            }
            $(".category-1").append("<li class='result-item'><a href=\"localhost:4000" + data.permalink + "\">" + data.title + "</a></li>");
          } else if (data.type === "category-2") {
            $(".category-2").append("<li class='result-item'><a href=\"localhost:4000" + data.permalink + "\">" + data.title + "</a></li>");
            if ($(".category-2").text() == '') {
              $(".category-2-results-header, .category-2").hide()
            }
          } else if (data.type === "category-3") {
            $(".category-3").append("<li class='result-item'><a href=\"localhost:4000" + data.permalink + "\">" + data.title + "</a></li>");
            if ($(".category-3").text() == '') {
              $(".category-3-results-header, .category-3").hide()
            }
          }
        });
      });
  }
});
</code>```

JSFIDDLE: LINK

答:
Try doing something like </p>

```<code>if (q.length > 3) {
    ajax_search();
} else {
    $(".results").empty();
}
</code>```

Title: Display results only on search

Body:
I need the search results div to only show when results of a search have been returned (not when the user is searching a term), and then be able to clear the results divs when a new term is searched.

I should be able to use something like $(".results").empty(), but this will keep the results div always blank.

$("#searchterm").keyup(function(e) {
  var q = $("#searchterm").val();
  //Only begin search with at least 3 characters.
  if (q.length > 3) {
    ajax_search();
  }
  //Send search query
  function ajax_search() {
    $.getJSON("//url-to-search?q=" + q, {},
      //Get results and make 'em look good
      function(data) {
        console.log(data);
        //  $(".results").append("Results for  " + q + "");
        $.each(data.data, function(i, data) {
          if (data.type === "category-1") {
            if ($(".category-1").text() == '') {
              $(".category-1-results-header, .category-1").hide()
            }
            $(".category-1").append("
" + data.title + "
");
          } else if (data.type === "category-2") {
            $(".category-2").append("
" + data.title + "
");
            if ($(".category-2").text() == '') {
              $(".category-2-results-header, .category-2").hide()
            }
          } else if (data.type === "category-3") {
            $(".category-3").append("
" + data.title + "
");
            if ($(".category-3").text() == '') {
              $(".category-3-results-header, .category-3").hide()
            }
          }
        });
      });
  }
});

JSFIDDLE: LINK

Body:
Try doing something like

if (q.length > 3) {
    ajax_search();
} else {
    $(".results").empty();
}


答:
To transform your dataframe, you can stack() it and then reset_index():

Code:

```<code>df = df.stack().reset_index().rename(
    columns={'level_0': 'ID', 'level_1': 'Date'})
print(df)
</code>```

Test Data:

```<code>csv_data = StringIO('\n'.join(x.strip() for x in u"""
    Group A,Group A,Group B,Group B,Group C,Group C
    Date1,Date2,Date1,Date2,Date1,Date2
    0.030626,0.494912,0.364742,0.320088,0.364742,0.364742
    0.178368,0.857469,0.628677,0.705226,0.364742,0.364742
""".split('\n')[1:-1]))

import pandas as pd
df = pd.read_csv(csv_data, sep=',', header=[0, 1])
</code>```

Results:

```<code>   ID   Date   Group A   Group B   Group C
0   0  Date1  0.030626  0.364742  0.364742
1   0  Date2  0.494912  0.320088  0.364742
2   1  Date1  0.178368  0.628677  0.364742
3   1  Date2  0.857469  0.705226  0.364742
</code>```

Test Data 2:

And if your data is not CSV and is actually formatted as in your question:

```<code>data = StringIO(
u"""           Group A             Group B             Group C
    ID Date1     Date2     Date1     Date2     Date1     Date2
    0  0.030626  0.494912  0.364742  0.320088  0.364742  0.364742
    1  0.178368  0.857469  0.628677  0.705226  0.364742  0.364742
""")

df = pd.read_fwf(data, colspecs='infer', header=[0, 1]).rename(
    columns={'Unnamed: 0_level_0': 'ID',
             'Unnamed: 2_level_0': 'Group A',
             'Unnamed: 4_level_0': 'Group B',
             'Unnamed: 6_level_0': 'Group C'})
del df['ID']
</code>```

Title: Pandas pivot a multi-line header CSV

Body:
I have a csv file that looks like:

   Group A             Group B             Group C
ID Date1     Date2     Date1     Date2     Date1     Date2
0  0.030626  0.494912  0.364742  0.320088  0.364742  0.364742
1  0.178368  0.857469  0.628677  0.705226  0.364742  0.364742

How do I read it into a dataframe and pivot such that the following table will result?

ID Date   Group A   Group B   Group C
0  Date1  0.030626  0.364742  0.364742
0  Date2  0.494912  0.320088  0.364742
1  Date1  0.178368  0.628677  0.364742
1  Date2  0.857469  0.705226  0.364742

Body:
To transform your dataframe, you can stack() it and then reset_index():

Code:

df = df.stack().reset_index().rename(
    columns={'level_0': 'ID', 'level_1': 'Date'})
print(df)

Test Data:

csv_data = StringIO('\n'.join(x.strip() for x in u"""
    Group A,Group A,Group B,Group B,Group C,Group C
    Date1,Date2,Date1,Date2,Date1,Date2
    0.030626,0.494912,0.364742,0.320088,0.364742,0.364742
    0.178368,0.857469,0.628677,0.705226,0.364742,0.364742
""".split('\n')[1:-1]))

import pandas as pd
df = pd.read_csv(csv_data, sep=',', header=[0, 1])

Results:

   ID   Date   Group A   Group B   Group C
0   0  Date1  0.030626  0.364742  0.364742
1   0  Date2  0.494912  0.320088  0.364742
2   1  Date1  0.178368  0.628677  0.364742
3   1  Date2  0.857469  0.705226  0.364742

Test Data 2:

And if your data is not CSV and is actually formatted as in your question:

data = StringIO(
u"""           Group A             Group B             Group C
    ID Date1     Date2     Date1     Date2     Date1     Date2
    0  0.030626  0.494912  0.364742  0.320088  0.364742  0.364742
    1  0.178368  0.857469  0.628677  0.705226  0.364742  0.364742
""")

df = pd.read_fwf(data, colspecs='infer', header=[0, 1]).rename(
    columns={'Unnamed: 0_level_0': 'ID',
             'Unnamed: 2_level_0': 'Group A',
             'Unnamed: 4_level_0': 'Group B',
             'Unnamed: 6_level_0': 'Group C'})
del df['ID']


问:
How to split the given format into date and time in android
Given Format:
2017-03-08 13:27:00

I want to spilt it into 2 strings
1 for date and 1 for time
for

E.g.

08-03-2017

13:27:00

答:
First if your date in String format then Parse it to Date and then try it.

```<code>    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class Main {

        public static void main(String[] args) {
            Date today = new Date();
            DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
            DateFormat dateFormat = SimpleDateFormat.getDateInstance();
            timeFormat.format(today);
            dateFormat.format(today);
            System.out.println("Time: " + timeFormat.format(today));
            System.out.println("Date: " + dateFormat.format(today));
        }
    }
</code>```

Output:

```<code>Time: 1:25:31 AM
Date: 31 Mar, 2017
</code>```

Hope this help !

Body:
First if your date in String format then Parse it to Date and then try it.

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class Main {

        public static void main(String[] args) {
            Date today = new Date();
            DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
            DateFormat dateFormat = SimpleDateFormat.getDateInstance();
            timeFormat.format(today);
            dateFormat.format(today);
            System.out.println("Time: " + timeFormat.format(today));
            System.out.println("Date: " + dateFormat.format(today));
        }
    }

Output:

Time: 1:25:31 AM
Date: 31 Mar, 2017

Hope this help !


问:
Inventory CD segment mask and selector
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

```<code>public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}
</code>```

(2) Page - InventoryCD (Copied from stock items IN202500):

```<code><px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>
</code>```

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference

答:
Ruslan's post is an answer if limited to using the standard framework attributes, there is not a way to trigger the display I need.

However, I had to create my own InventoryRawAttribute for other reasons not related to my question. In doing so I set the PXDimensionSelectorAttrbiute.SelectorMode to MaskAutocomplete and this made the field function exactly the way I need it to.

He is the stripped down basics to get this working. This is a copy of InventoryRawAttribute and added the attr.SelectorMode = PXSelectorMode.MaskAutocomplete.

```<code>/// <summary>
/// Copy of InventoryRawAttribute (sealed class)
/// </summary>
[PXDBString(InputMask = "", IsUnicode = true)]
[PXUIField(DisplayName = "Inventory ID", Visibility = PXUIVisibility.SelectorVisible)]
public sealed class TestInventoryRawAttribute : AcctSubAttribute
{
    public const string DimensionName = "INVENTORY";

    public TestInventoryRawAttribute()
        : base()
    {
        Type SearchType = typeof(Search<InventoryItem.inventoryCD, Where<Match<Current<AccessInfo.userName>>>>);
        PXDimensionSelectorAttribute attr = new PXDimensionSelectorAttribute(DimensionName, SearchType, typeof(InventoryItem.inventoryCD));
        attr.CacheGlobal = true;
        // This is the secret sauce - MaskAutocomplete
        attr.SelectorMode = PXSelectorMode.MaskAutocomplete;
        _Attributes.Add(attr);
        _SelAttrIndex = _Attributes.Count - 1;
    }
}
</code>```

The secret sauce in action...

Title: Inventory CD segment mask and selector

Body:
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}

(2) Page - InventoryCD (Copied from stock items IN202500):

<px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference

Body:
Ruslan's post is an answer if limited to using the standard framework attributes, there is not a way to trigger the display I need.

However, I had to create my own InventoryRawAttribute for other reasons not related to my question. In doing so I set the PXDimensionSelectorAttrbiute.SelectorMode to MaskAutocomplete and this made the field function exactly the way I need it to.

He is the stripped down basics to get this working. This is a copy of InventoryRawAttribute and added the attr.SelectorMode = PXSelectorMode.MaskAutocomplete.

/// <summary>
/// Copy of InventoryRawAttribute (sealed class)
/// </summary>
[PXDBString(InputMask = "", IsUnicode = true)]
[PXUIField(DisplayName = "Inventory ID", Visibility = PXUIVisibility.SelectorVisible)]
public sealed class TestInventoryRawAttribute : AcctSubAttribute
{
    public const string DimensionName = "INVENTORY";

    public TestInventoryRawAttribute()
        : base()
    {
        Type SearchType = typeof(Search<InventoryItem.inventoryCD, Where<Match<Current<AccessInfo.userName>>>>);
        PXDimensionSelectorAttribute attr = new PXDimensionSelectorAttribute(DimensionName, SearchType, typeof(InventoryItem.inventoryCD));
        attr.CacheGlobal = true;
        // This is the secret sauce - MaskAutocomplete
        attr.SelectorMode = PXSelectorMode.MaskAutocomplete;
        _Attributes.Add(attr);
        _SelAttrIndex = _Attributes.Count - 1;
    }
}

The secret sauce in action...


问:
Android - new intent and activity problems
I'm developing an android app, and have developed a game, but I now have stupid problem. You control a UFO and when it's health will be reduced to zero the game should be over. How should I contruct gameOver?

Previous I've used an intent to open a new activity but this requires the class to extend Activity, and since I want the mainthread to look up when the UFO has his health reduced to zero I can't just call GameActivity.gameOver since it want to use a static method to be called, and since a static method can't contain a new intent I can't figure it out.

答:
A static method can contain an intent.

Pass a Context in a param of the static method and use that to launch a new Context.


问:
How to find the smallest count in my BST
What I'm trying to do right now is find the minimum value of repeat count in my binary search tree (BST).

What this means is that the BST is normal when inserting values, but then when it gets the same value twice it instead will increment the value of repeat count, which the tree isn't dependent on (so I can't just go left for the minimum value).

I have tried getting the minimum value but it always comes up short. The function trying to get the smallest is findSmallest

```<code>public static void main(String[] args) {

    int x = 0; //random number

    Random rnum = new Random();
    SBT sbt = new SBT();

    for(int i = 0; i < 100; i++){
        x = rnum.nextInt(20) + 1;
        sbt.insert(x);
    }

    sbt.printLargestCount();
    sbt.printSmallestCount();
    sbt.FS();
    sbt.deleteBoth();
    System.out.println("Sum of the key values is:   " + sbt.sumKeyValue());
    System.out.println("Sum of the repeat counts is: " + sbt.sumReapeatCount());

    sbt.inorder();
}
</code>```

Here is the function trying to get the value I am right now trying to go through all the node in the tree and comparing them to the current smallest value.
If the nodes repeatCount is smaller that value it will change value and a global node smallestCount.

I have added those globals below.

```<code>private BSTNode root;
private BSTNode largestCount;
private BSTNode smallestCount;
private int sumKeyVal;
public void FS(){
    findSmallest(root, 0);
    System.out.println("data is: " + smallestCount.data + " repeatCount is: " + smallestCount.repeatCount);
}
private void findSmallest(BSTNode r, int val){
    if(r == null) return;
    if(r == root)val = r.repeatCount;

    if(r.repeatCount < val){
        val = r.repeatCount;
        smallestCount = r;
        System.out.println(val);
    }
    if(r.right == null && r.left == null)
        return;
    else if(r.left != null)
        findSmallest(r.left,val);
    else if(r.right != null)
        findSmallest(r.right,val);
}

private BSTNode insert(int x, BSTNode t){
    if (t == null){
        t = new BSTNode(x);
        smallestCount = t;
    }
    else if (x < t.data)
        t.left = insert( x, t.left );
    else if (x > t.data)
        t.right = insert( x, t.right );
    else
        t.height = max( height( t.left ), height( t.right ) ) + 1;
    return t;
}
private int height(BSTNode t ) {
    return t == null ? -1 : t.height;
}
// Function to max of left/right node
private int max(int lhs, int rhs) {
    return lhs > rhs ? lhs : rhs;
}
</code>```

Here is the node class used:

```<code>public class BSTNode {

    BSTNode left, right;
    int data;
    int height;
    int repeatCount;

    /* Constructor */
    public BSTNode(){
        left = null;
        right = null;
        data = 0;
        height = 0;
        repeatCount = 0;
    }
    /* Constructor */
    public BSTNode(int n){
        left = null;
        right = null;
        data = n;
        height = 0;
        repeatCount = 0;
    }
}
</code>```

答:
I figured it out and tested the code seems to work. Below is the block of code changed.

```<code>public void FS(){
             findSmallest(root, 0);
         }
         private int findSmallest(BSTNode r, int val){
             if(r == null) return val;
             if(r == root)val = r.repeatCount;

             if(r.repeatCount < val){
                 val = r.repeatCount;
                 smallestCount = r;
             }

             val = findSmallest(r.left,val);
             val = findSmallest(r.right,val);

             return val;

     }
</code>```

Getting rid of the if else statements and going with a check for null at the begging traversed through the tree and kept the smallest along the way.

Body:
What I'm trying to do right now is find the minimum value of repeat count in my binary search tree (BST).

What this means is that the BST is normal when inserting values, but then when it gets the same value twice it instead will increment the value of repeat count, which the tree isn't dependent on (so I can't just go left for the minimum value).

I have tried getting the minimum value but it always comes up short. The function trying to get the smallest is findSmallest

public static void main(String[] args) {

    int x = 0; //random number

    Random rnum = new Random();
    SBT sbt = new SBT();

    for(int i = 0; i < 100; i++){
        x = rnum.nextInt(20) + 1;
        sbt.insert(x);
    }

    sbt.printLargestCount();
    sbt.printSmallestCount();
    sbt.FS();
    sbt.deleteBoth();
    System.out.println("Sum of the key values is:   " + sbt.sumKeyValue());
    System.out.println("Sum of the repeat counts is: " + sbt.sumReapeatCount());

    sbt.inorder();
}

Here is the function trying to get the value I am right now trying to go through all the node in the tree and comparing them to the current smallest value.
If the nodes repeatCount is smaller that value it will change value and a global node smallestCount.

I have added those globals below.

private BSTNode root;
private BSTNode largestCount;
private BSTNode smallestCount;
private int sumKeyVal;
public void FS(){
    findSmallest(root, 0);
    System.out.println("data is: " + smallestCount.data + " repeatCount is: " + smallestCount.repeatCount);
}
private void findSmallest(BSTNode r, int val){
    if(r == null) return;
    if(r == root)val = r.repeatCount;

    if(r.repeatCount < val){
        val = r.repeatCount;
        smallestCount = r;
        System.out.println(val);
    }
    if(r.right == null && r.left == null)
        return;
    else if(r.left != null)
        findSmallest(r.left,val);
    else if(r.right != null)
        findSmallest(r.right,val);
}

private BSTNode insert(int x, BSTNode t){
    if (t == null){
        t = new BSTNode(x);
        smallestCount = t;
    }
    else if (x < t.data)
        t.left = insert( x, t.left );
    else if (x > t.data)
        t.right = insert( x, t.right );
    else
        t.height = max( height( t.left ), height( t.right ) ) + 1;
    return t;
}
private int height(BSTNode t ) {
    return t == null ? -1 : t.height;
}
// Function to max of left/right node
private int max(int lhs, int rhs) {
    return lhs > rhs ? lhs : rhs;
}

Here is the node class used:

public class BSTNode {

    BSTNode left, right;
    int data;
    int height;
    int repeatCount;

    /* Constructor */
    public BSTNode(){
        left = null;
        right = null;
        data = 0;
        height = 0;
        repeatCount = 0;
    }
    /* Constructor */
    public BSTNode(int n){
        left = null;
        right = null;
        data = n;
        height = 0;
        repeatCount = 0;
    }
}

Body:
I figured it out and tested the code seems to work. Below is the block of code changed.

public void FS(){
             findSmallest(root, 0);
         }
         private int findSmallest(BSTNode r, int val){
             if(r == null) return val;
             if(r == root)val = r.repeatCount;

             if(r.repeatCount < val){
                 val = r.repeatCount;
                 smallestCount = r;
             }

             val = findSmallest(r.left,val);
             val = findSmallest(r.right,val);

             return val;

     }

Getting rid of the if else statements and going with a check for null at the begging traversed through the tree and kept the smallest along the way.


问:
Angular Directive and Childrens
I wan't to make a Directive for Angular 1.x. I'm thinking in something like this:

```<code><myDirective>
     <div class="title">Header</div>
     <div class="content>Content here</div>
</myDirective>
</code>```

So my question if it's posible access to "title" and "content" class of the html and change, for example, the background color for "title" element..

Anyone can help me?

答:
Hi you can do it by normal css as you would do for any other html content.
here is a working link to see how it works https://plnkr.co/edit/WaqTKb4IhjlWZsE5Q7Cb?p=preview

so if your directive was :

```<code><my-directive>
 <div class="title">Header</div>
 <div class="content>Content here</div>
</my-directive>
</code>```

you could access the elements like so (these styles go where you're defining styles for the rest of the normal html)

```<code>my-directive > .title
{
background-color:red;
}

my-directive > .content
{
background-color:red;
}
</code>```

Title: Angular Directive and Childrens

Body:
I wan't to make a Directive for Angular 1.x. I'm thinking in something like this:

<myDirective>

Header

Content here

</myDirective>

So my question if it's posible access to "title" and "content" class of the html and change, for example, the background color for "title" element..

Anyone can help me?

Body:
Hi you can do it by normal css as you would do for any other html content.
here is a working link to see how it works https://plnkr.co/edit/WaqTKb4IhjlWZsE5Q7Cb?p=preview

so if your directive was :

<my-directive>
 <div class="title">Header</div>
 <div class="content>Content here</div>
</my-directive>

you could access the elements like so (these styles go where you're defining styles for the rest of the normal html)

my-directive > .title
{
background-color:red;
}

my-directive > .content
{
background-color:red;
}


问:
Can not find or load main class - classloader issue
I know this question has been asked before, but I’ve read through most of them and still can’t figure out my problem.

I’ve compiled the below code into "HelloWorld.class" located in the directory shown below.

```<code>package helloworld;

    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }
</code>```

But I cannot get the .class file to run using the Java command on Window Command Prompt:

I believe my PATH and CLASSPATH are set correctly (as shown below).  But I still can’t find the class.  Any ideas why?

答:
The name of the class is not HelloWorld. It goes like:

```<code> java helloworld.HelloWorld
</code>```

and you have to call that from the directory above helloworld.

In other words: the package name is part of the class name. When you invoke java; you have to provide that full name; and the classpath needs to point to the directory that contains that package.

Body:
I know this question has been asked before, but I’ve read through most of them and still can’t figure out my problem.

I’ve compiled the below code into "HelloWorld.class" located in the directory shown below.

package helloworld;

    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }

But I cannot get the .class file to run using the Java command on Window Command Prompt:

I believe my PATH and CLASSPATH are set correctly (as shown below).  But I still can’t find the class.  Any ideas why?

Body:
The name of the class is not HelloWorld. It goes like:

 java helloworld.HelloWorld

and you have to call that from the directory above helloworld.

In other words: the package name is part of the class name. When you invoke java; you have to provide that full name; and the classpath needs to point to the directory that contains that package.


问:
yii2 gridview not showing all the left join values using hasMany retionship
Model Search :

```<code>$query = Countries::find()->joinWith(['states']);
$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$dataProvider->setSort([
    'defaultOrder' => ['doc_date'=>SORT_DESC],
]);

if (!($this->load($params) && $this->validate())) {
    return $dataProvider;
}
</code>```

Model :

```<code>public function getStates()
{
    return $this->hasMany(States::className(), ['state_id' => 'state_id']);
}
</code>```

I need result like

```<code>Id      Country     State
1       India       State 1
2       India       State 2
3       India       State 3
4       USA         USA State1
5       USA         USA State2
</code>```

When I'm using gridview I'm getting following result

```<code>Id      Country     State
1       India       State 1
4       USA         USA State1
</code>```

Please give solutions to fix this issue.

答:
If you explicitly specify the selected columns using the select() method, you can achieve the same result, without messing with raw sql queries

```<code>$query->select(['countries.*','states.*']);
</code>```

Body:
Model Search :

$query = Countries::find()->joinWith(['states']);
$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$dataProvider->setSort([
    'defaultOrder' => ['doc_date'=>SORT_DESC],
]);

if (!($this->load($params) && $this->validate())) {
    return $dataProvider;
}

Model :

public function getStates()
{
    return $this->hasMany(States::className(), ['state_id' => 'state_id']);
}

I need result like

Id      Country     State
1       India       State 1
2       India       State 2
3       India       State 3
4       USA         USA State1
5       USA         USA State2

When I'm using gridview I'm getting following result

Id      Country     State
1       India       State 1
4       USA         USA State1

Please give solutions to fix this issue.

Body:
If you explicitly specify the selected columns using the select() method, you can achieve the same result, without messing with raw sql queries

$query->select(['countries.*','states.*']);


问:
Mask based on two different Pandas Dataframes?
Suppose I have two pandas dataframes:

```<code>In [1]: dates = pd.date_range('20170101',periods=6)
df1 = pd.DataFrame(np.empty([len(dates),2]),index=dates,columns=['foo','bar'])
df1['foo'].loc[0:2] = 'A'
df1['bar'].loc[0:3] = 'A'
df1['foo'].loc[2:6] = 'B'
df1['bar'].loc[3:6] = 'B'
df2 = pd.DataFrame(np.random.randint(10,size=(6,2)),index=dates,columns=df1.columns)
print(df1)
print(df2)

Out [1]:
           foo bar
2017-01-01   A   A
2017-01-02   A   A
2017-01-03   B   A
2017-01-04   B   B
2017-01-05   B   B
2017-01-06   B   B

            foo  bar
2017-01-01    5    3
2017-01-02    6    9
2017-01-03    5    9
2017-01-04    7    5
2017-01-05    0    2
2017-01-06    0    0
</code>```

I'm interested in a creating a 3rd df populated with the max of df2 based on df1.  For example, the output would look something like this:

```<code>            foo  bar
2017-01-01    6    9
2017-01-02    6    9
2017-01-03    7    9
2017-01-04    7    5
2017-01-05    7    5
2017-01-06    7    5
</code>```

Surely there's a succinct way to do this, right?

答:
One option is to concatenate the two data frames and assign a key to each one, transform the resulting data frame to long format, and then calculate the max grouped by the key and the column names:

```<code>(pd.concat([df1, df2], keys=["one", "two"], axis=1)
 .stack(level=1).groupby(level=1)
 .apply(lambda g: g.groupby("one",as_index=False)["two"].transform("max"))
 .two.unstack(level=1))
</code>```

Body:
Suppose I have two pandas dataframes:

In [1]: dates = pd.date_range('20170101',periods=6)
df1 = pd.DataFrame(np.empty([len(dates),2]),index=dates,columns=['foo','bar'])
df1['foo'].loc[0:2] = 'A'
df1['bar'].loc[0:3] = 'A'
df1['foo'].loc[2:6] = 'B'
df1['bar'].loc[3:6] = 'B'
df2 = pd.DataFrame(np.random.randint(10,size=(6,2)),index=dates,columns=df1.columns)
print(df1)
print(df2)

Out [1]:
           foo bar
2017-01-01   A   A
2017-01-02   A   A
2017-01-03   B   A
2017-01-04   B   B
2017-01-05   B   B
2017-01-06   B   B

            foo  bar
2017-01-01    5    3
2017-01-02    6    9
2017-01-03    5    9
2017-01-04    7    5
2017-01-05    0    2
2017-01-06    0    0

I'm interested in a creating a 3rd df populated with the max of df2 based on df1.  For example, the output would look something like this:

            foo  bar
2017-01-01    6    9
2017-01-02    6    9
2017-01-03    7    9
2017-01-04    7    5
2017-01-05    7    5
2017-01-06    7    5

Surely there's a succinct way to do this, right?

Body:
One option is to concatenate the two data frames and assign a key to each one, transform the resulting data frame to long format, and then calculate the max grouped by the key and the column names:

(pd.concat([df1, df2], keys=["one", "two"], axis=1)
 .stack(level=1).groupby(level=1)
 .apply(lambda g: g.groupby("one",as_index=False)["two"].transform("max"))
 .two.unstack(level=1))


问:
std::shared_ptr<Parent> to std::shared_ptr<Child>
I have an "interface" as .h file that has a virtual method like this:

```<code>class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}
</code>```

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

```<code>class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}
</code>```

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(

答:
This is possible.

Now, naively, this isn't allowed in C++.  Covariant return types in C++ don't work this way.

But this is C++.  C++ doesn't stop and give up just because the language doesn't support a feature.  We can simply write the feature ourselves.

The trick is you don't actually care if getX is actually virtual; you just want it to have virtual behavior.

We create a series of non-virtual getX with a series of getX_impl virtual functions it dispatches to.  We use final and pointer based dispatching to make it resistant against small typos.

From the user side, it acts like covariant return types.  Implementation wise, you have to write two short bits of boilerplate.

An important part of this design is that it does no possibly unsafe casts.  An easy shortcut is to do away with the final and new getX_impl methods; the cost is that we cannot guarantee that a further-derived child will actually put a shared_ptr<Child>.

The final parent dispatches to the public interface.  The public interface dispatches to a new virtual function that retunrs shared_ptr<Child>.  Children who want to change behavior must override the one that returns shared_ptr<Child>; they have no choice, the compiler enforces it.

```<code>class ISomeInterface {
  virtual std::shared_ptr<Parent> getX_impl(ISomeInterface *) = 0;
public:
  std::shared_ptr<Parent> getX() { return getX_impl(this); }
};

class Implementor : public ISomeInterface {
  std::shared_ptr<Child> x = std::make_shared<Child>();

  virtual std::shared_ptr<Parent> getX_impl(ISomeInterface*) final override { return getX(); }
  virtual std::shared_ptr<Child> getX_impl(Implementor*) { return this->x; }
public:
  std::shared_ptr<Child> getX() { return getX_impl(this); }
};
</code>```

users just call getX().  It acts almost exactly like a virtual method with a covariant shared pointer return type.  It even works with member function pointers!

Every class you implement with a new type finalizes the parent method, creates a new private virtual getX_impl method returning the new type, has the new parent call getX(), and exposes a public getX() { return getX_impl(this); } which dispatches to the correct overload.

Live example.

You could probably marginally simplify this with the CRTP, but... it would be harder to understand.

```<code>template<class D, class Child, class B>
struct getX_CRTP : B {

  std::shared_ptr<Child> getX() { return static_cast<D*>(this)->getX_impl(static_cast<D*>(this)); }
private:
  virtual decltype( std::declval<B&>().getX() ) getX_impl( B* ) final override { return getX(); }
  virtual std::shared_ptr<Child> getX_impl( D* ) = 0;
};
</code>```

Now Implementor looks like:

```<code>class Implementor : public getX_CRTP<Implementor, Cihld, ISomeInterface>
{
  std::shared_ptr<Child> x = std::make_shared<Child>();
  virtual std::shared_ptr<Child> getX_impl(Implementor*) override { return this->x; }
};
</code>```

which is shorter per derived class, but not really clearer.

We could probably also replace the pointer-to-own-type with a tag of some kind, reducing the bytes pointlessly pushed on the stack from sizeof(ptr) to 1, and that left unintialized.  Let me know if you spot it in your profiled build.  ;)

Body:
I have an "interface" as .h file that has a virtual method like this:

class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(

Body:
This is possible.

Now, naively, this isn't allowed in C++.  Covariant return types in C++ don't work this way.

But this is C++.  C++ doesn't stop and give up just because the language doesn't support a feature.  We can simply write the feature ourselves.

The trick is you don't actually care if getX is actually virtual; you just want it to have virtual behavior.

We create a series of non-virtual getX with a series of getX_impl virtual functions it dispatches to.  We use final and pointer based dispatching to make it resistant against small typos.

From the user side, it acts like covariant return types.  Implementation wise, you have to write two short bits of boilerplate.

An important part of this design is that it does no possibly unsafe casts.  An easy shortcut is to do away with the final and new getX_impl methods; the cost is that we cannot guarantee that a further-derived child will actually put a shared_ptr<Child>.

The final parent dispatches to the public interface.  The public interface dispatches to a new virtual function that retunrs shared_ptr<Child>.  Children who want to change behavior must override the one that returns shared_ptr<Child>; they have no choice, the compiler enforces it.

class ISomeInterface {
  virtual std::shared_ptr<Parent> getX_impl(ISomeInterface *) = 0;
public:
  std::shared_ptr<Parent> getX() { return getX_impl(this); }
};

class Implementor : public ISomeInterface {
  std::shared_ptr<Child> x = std::make_shared<Child>();

  virtual std::shared_ptr<Parent> getX_impl(ISomeInterface*) final override { return getX(); }
  virtual std::shared_ptr<Child> getX_impl(Implementor*) { return this->x; }
public:
  std::shared_ptr<Child> getX() { return getX_impl(this); }
};

users just call getX().  It acts almost exactly like a virtual method with a covariant shared pointer return type.  It even works with member function pointers!

Every class you implement with a new type finalizes the parent method, creates a new private virtual getX_impl method returning the new type, has the new parent call getX(), and exposes a public getX() { return getX_impl(this); } which dispatches to the correct overload.

Live example.

You could probably marginally simplify this with the CRTP, but... it would be harder to understand.

template<class D, class Child, class B>
struct getX_CRTP : B {

  std::shared_ptr<Child> getX() { return static_cast<D*>(this)->getX_impl(static_cast<D*>(this)); }
private:
  virtual decltype( std::declval<B&>().getX() ) getX_impl( B* ) final override { return getX(); }
  virtual std::shared_ptr<Child> getX_impl( D* ) = 0;
};

Now Implementor looks like:

class Implementor : public getX_CRTP<Implementor, Cihld, ISomeInterface>
{
  std::shared_ptr<Child> x = std::make_shared<Child>();
  virtual std::shared_ptr<Child> getX_impl(Implementor*) override { return this->x; }
};

which is shorter per derived class, but not really clearer.

We could probably also replace the pointer-to-own-type with a tag of some kind, reducing the bytes pointlessly pushed on the stack from sizeof(ptr) to 1, and that left unintialized.  Let me know if you spot it in your profiled build.  ;)


问:
Is it possible to call API Gateway resource from AWS Step function?
I have a step function which should call an API Gateway resource instead of a lambda. What is the syntax to do that ?

```<code>{"Comment": "A Hello World example of the Amazon States Language using a Pass state",
  "StartAt": "QueueProducts",
  "States": {
    "GetProductsFromDb": {
      "Type": "Task",
      "Resource":"some-lambda",
      "Next": "InvokeAPIGatewayWorkers"
    }
  },
 "InvokeAPIGatewayWorkers":{
    "Type": "Parallel",
    "Branches": [
     ....]
}
}
</code>```

My question is, Is it possible to invoke an API Gateway in the Resource instead of "some-lamda"

答:
No, this is not possible.

You would have to use a Lambda function to make the call to API Gateway.

Body:
I have a step function which should call an API Gateway resource instead of a lambda. What is the syntax to do that ?

{"Comment": "A Hello World example of the Amazon States Language using a Pass state",
  "StartAt": "QueueProducts",
  "States": {
    "GetProductsFromDb": {
      "Type": "Task",
      "Resource":"some-lambda",
      "Next": "InvokeAPIGatewayWorkers"
    }
  },
 "InvokeAPIGatewayWorkers":{
    "Type": "Parallel",
    "Branches": [
     ....]
}
}

My question is, Is it possible to invoke an API Gateway in the Resource instead of "some-lamda"


问:
Does kernel32 always load from System32?

Copy kernel32.dll from System32 (or SysWOW64 if you're testing with a 32-bit application) to the directory containing your EXE file

Run the EXE file

Process Monitor shows it doesn't even bother to check the local folder for kernel32.dll first

This seems to contradict what I've always thought is the default behaviour of DLLs, that is to load from the local application directory first and if it's not there load from the PATH environment variable. However, for certain DLLs like ntdll or kernel32, Windows always seems to check System32 first. Is this expected behaviour? Can it be overridden?

(I'm aware that overriding this would be bad practice, but want to know if it's actually possible, for science!)

答:
After more research, I found that the reason certain DLLs such as kernel32.dll or user32.dll cannot be overridden normally is because they are Known DLLs - Windows has a list of commonly used DLLs like these which automatically default to the System32 versions, rather than the default behaviour of checking the folder of the application first.

If you want to work around this, for example to make a proxy DLL, you need to include two files in the application directory: applicationName.exe.local and applicationName.exe.manifest where applicationName is the name of your EXE file.

These need to be the contents of the manifest file:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity version="1.0.0.0" name="redirector" type="win32" />
    <file name="kernel32.dll" />
</assembly>
</code>```

The assemblyIdentity tag is intended to give information about your application's version number and name, but we can basically just ignore it. The important part is the file tag which specifies a file to load locally. Replace kernel32.dll with DLL you'd like to load locally.

Also, Windows only refreshes the contents of .manifest files either upon restart, or when the EXE file is modified, so you could just open the EXE file in some hex editor, erase the first character and add it back and save... etc. to refresh the manifest file. Do this if you manifest file seems to be ignored.

On Windows 2000 and below, adding a .local file will be enough to
convince it to load the local version of kernel32.dll .

On Windows XP and above, you need to use the .manifest file.

It's possible for an application to have a .manifest file embedded within
it. In this case, you can delete the resource with a tool like Stud_PE.

Body:
After more research, I found that the reason certain DLLs such as kernel32.dll or user32.dll cannot be overridden normally is because they are Known DLLs - Windows has a list of commonly used DLLs like these which automatically default to the System32 versions, rather than the default behaviour of checking the folder of the application first.

If you want to work around this, for example to make a proxy DLL, you need to include two files in the application directory: applicationName.exe.local and applicationName.exe.manifest where applicationName is the name of your EXE file.

These need to be the contents of the manifest file:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity version="1.0.0.0" name="redirector" type="win32" />
    <file name="kernel32.dll" />
</assembly>

The assemblyIdentity tag is intended to give information about your application's version number and name, but we can basically just ignore it. The important part is the file tag which specifies a file to load locally. Replace kernel32.dll with DLL you'd like to load locally.

Also, Windows only refreshes the contents of .manifest files either upon restart, or when the EXE file is modified, so you could just open the EXE file in some hex editor, erase the first character and add it back and save... etc. to refresh the manifest file. Do this if you manifest file seems to be ignored.

On Windows 2000 and below, adding a .local file will be enough to
convince it to load the local version of kernel32.dll .

On Windows XP and above, you need to use the .manifest file.

It's possible for an application to have a .manifest file embedded within
it. In this case, you can delete the resource with a tool like Stud_PE.


问:
Using \verbatim as part of an argument for a macro?
Most things I've wanted to do in LaTeX have either been straight-forward, or easily found on the web, but this one has been stumping me.

I have a macro 'solution': to apply some common formatting to each solution:

```<code>\newcommand\solution[1]{{\\ \\* \bf Solution.}#1\qed \newpage}
</code>```

Which has worked nicely so far, but now I wanted to include a drawing which I've done quickly using 'ASCII Art' so I'd like to use \verbatim. But it doesn't work, it produces the following errors:

```<code>Runaway argument?
...
! File ended while scanning use of \@xverbatim.
</code>```

From what I read in the "Not So Short introduction to LaTeX", \verbatim can't be used this way. I assume there is a better way to do what I'm trying to do?

答:
Use the package cprotect

e.g. ( with tcolorbox but it is working with most of the newcommand created)

```<code>\usepackage{tcolorbox}
\usepackage{cprotect}

\newcommand{\tcb}[1] {
 \begin{tcolorbox}   [arc=0mm,colback=bginf,coltitle=black!70!black,colframe=black!30!white,width=\linewidth,fontupper=\bfseries\small,halign title=flush center,halign upper=center]
#1
\end{tcolorbox}
}

\cprotect\tcb{\scriptsize
     \begin{verbatim}
...
     \end{verbatim}
}
</code>```

OwnerDisplayName: Feaelin Moilar

Body:
Most things I've wanted to do in LaTeX have either been straight-forward, or easily found on the web, but this one has been stumping me.

I have a macro 'solution': to apply some common formatting to each solution:

\newcommand\solution[1]{{\\ \\* \bf Solution.}#1\qed \newpage}

Which has worked nicely so far, but now I wanted to include a drawing which I've done quickly using 'ASCII Art' so I'd like to use \verbatim. But it doesn't work, it produces the following errors:

Runaway argument?
...
! File ended while scanning use of \@xverbatim.

From what I read in the "Not So Short introduction to LaTeX", \verbatim can't be used this way. I assume there is a better way to do what I'm trying to do?

LastEditorDisplayName: Ferruccio

Body:
Use the package cprotect

e.g. ( with tcolorbox but it is working with most of the newcommand created)

\usepackage{tcolorbox}
\usepackage{cprotect}

\newcommand{\tcb}[1] {
 \begin{tcolorbox}   [arc=0mm,colback=bginf,coltitle=black!70!black,colframe=black!30!white,width=\linewidth,fontupper=\bfseries\small,halign title=flush center,halign upper=center]
#1
\end{tcolorbox}
}

\cprotect\tcb{\scriptsize
     \begin{verbatim}
...
     \end{verbatim}
}


问:
Dropping multiple tables with same prefix in Hive
I have few tables in hive that has same prefix like below..

```<code>temp_table_name
temp_table_add
temp_table_area
</code>```

There are few hundreds of tables like this in my database along with many other tables.
I want to delete tables that starts with "temp_table".
Do any of you know any query that can do this work in Hive?

答:
Below command will also work.</p>

```<code> hive -e 'show tables' | grep table_prefix |  while read line; do hive -e "drop table $line"; done
</code>```

Body:
I have few tables in hive that has same prefix like below..

temp_table_name
temp_table_add
temp_table_area

There are few hundreds of tables like this in my database along with many other tables.
I want to delete tables that starts with "temp_table".
Do any of you know any query that can do this work in Hive?

Body:
Below command will also work.

 hive -e 'show tables' | grep table_prefix |  while read line; do hive -e "drop table $line"; done


问:
why is my SMS verification code not working properly?
I think I'm in a bit of a catch 22 situation. I'm making an app that verifies the user's phone number by sending a text message to the number the user entered and then checking - that way it's definitely the user's phone number. This activity should only appear once, at the beginning - for the user to verify, and from then on activity 2 should be loaded.

I am trying to do this with :

```<code>//  when the form loads, check to see if phoneNo is in there
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String phoneNoCheck = sharedPreferences.getString("phonenumber","");

if (phoneNoCheck != null) {
    //  if it is in there, start the new Activity
    Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
    MainActivity.this.startActivity(myIntent);

}
</code>```

But it doesn't seem to be working properly. For a start, I'm not even sure it should be null. When I turn off my phone and on again, it starts back at activity 1, asking for verification.

And I can't test it. I need to run the app on my device as I can't send an SMS from the emulator, and I'm unable to get to the files where sharedPreferences exist on my device, so I can't even see if it's being written correctly.

Any advice on how I might be able to see the MyData.xml on my phone and proceed with testing my app, or tell my how I may be able to improve my code ? I downloaded the Astro app but still couldn't find it.

Here's my code :

```<code>package com.example.chris.tutorialspoint;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.tutorialspoint.R;

public class MainActivity extends Activity {
    Button sendBtn;
    EditText txtphoneNo;

    String phoneNo;
    String origNumber;

    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendBtn = (Button) findViewById(R.id.btnSendSMS);
        txtphoneNo = (EditText) findViewById(R.id.editText);

        //  when the form loads, check to see if phoneNo is in there
        SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String phoneNoCheck = sharedPreferences.getString("phonenumber","");

        if (phoneNoCheck != null) {
            //  if it is in there, start the new Activity
            Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
            MainActivity.this.startActivity(myIntent);

        }

        //if it is not in there, proceed with phone number verification

        else {
            sendBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    sendSMSMessage();
                }
            });

            IntentFilter filter = new IntentFilter();
//        the thing we're looking out for is received SMSs
            filter.addAction("android.provider.Telephony.SMS_RECEIVED");

            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent)

                {
                    Bundle extras = intent.getExtras();

                    if (extras == null)
                        return;

                    Object[] pdus = (Object[]) extras.get("pdus");
                    SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]);
                    origNumber = msg.getOriginatingAddress();

                    Toast.makeText(getApplicationContext(), "Originating number" + origNumber, Toast.LENGTH_LONG).show();
                    Toast.makeText(getApplicationContext(), "Sent to number" + phoneNo, Toast.LENGTH_LONG).show();

                }

            };
            registerReceiver(receiver, filter);
        }
    }

    protected void sendSMSMessage() {
        phoneNo = txtphoneNo.getText().toString();

        //this is the SMS received
        String message = "Verification test code. Please ignore this message. Thank you.";

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();

            //if originating phone number is the same as the sent to number, save
            //and go to the next activity
            if (origNumber.equals(phoneNo)) {
                //save the phone number
                SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("phonenumber", phoneNo);
                editor.commit();

                Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
                MainActivity.this.startActivity(myIntent);
            }
        }

        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        super.onDestroy();
    }
</code>```

答:
What do you expect to happen here:

```<code>String phoneNoCheck = sharedPreferences.getString("phonenumber","");

if (phoneNoCheck != null) {

    ...
}
</code>```

The method that you are calling, getString(String, String), uses the second parameter as the default value, that is, if no property is found, it will default to, as you have defined, an empty string, "".

You then try and compare this to null, which will never be equal.

Try changing it up to something like this:

```<code>String phoneNoCheck = sharedPreferences.getString("phonenumber", null);

// check if null or empty
if ( null == phoneNoCheck || phoneNoCheck.equals("") ) {

    // unregistered
}
</code>```

Body:
I think I'm in a bit of a catch 22 situation. I'm making an app that verifies the user's phone number by sending a text message to the number the user entered and then checking - that way it's definitely the user's phone number. This activity should only appear once, at the beginning - for the user to verify, and from then on activity 2 should be loaded.

I am trying to do this with :

//  when the form loads, check to see if phoneNo is in there
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String phoneNoCheck = sharedPreferences.getString("phonenumber","");

if (phoneNoCheck != null) {
    //  if it is in there, start the new Activity
    Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
    MainActivity.this.startActivity(myIntent);

}

But it doesn't seem to be working properly. For a start, I'm not even sure it should be null. When I turn off my phone and on again, it starts back at activity 1, asking for verification.

And I can't test it. I need to run the app on my device as I can't send an SMS from the emulator, and I'm unable to get to the files where sharedPreferences exist on my device, so I can't even see if it's being written correctly.

Any advice on how I might be able to see the MyData.xml on my phone and proceed with testing my app, or tell my how I may be able to improve my code ? I downloaded the Astro app but still couldn't find it.

Here's my code :

package com.example.chris.tutorialspoint;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.tutorialspoint.R;

public class MainActivity extends Activity {
    Button sendBtn;
    EditText txtphoneNo;

    String phoneNo;
    String origNumber;

    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendBtn = (Button) findViewById(R.id.btnSendSMS);
        txtphoneNo = (EditText) findViewById(R.id.editText);

        //  when the form loads, check to see if phoneNo is in there
        SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String phoneNoCheck = sharedPreferences.getString("phonenumber","");

        if (phoneNoCheck != null) {
            //  if it is in there, start the new Activity
            Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
            MainActivity.this.startActivity(myIntent);

        }

        //if it is not in there, proceed with phone number verification

        else {
            sendBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    sendSMSMessage();
                }
            });

            IntentFilter filter = new IntentFilter();
//        the thing we're looking out for is received SMSs
            filter.addAction("android.provider.Telephony.SMS_RECEIVED");

            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent)

                {
                    Bundle extras = intent.getExtras();

                    if (extras == null)
                        return;

                    Object[] pdus = (Object[]) extras.get("pdus");
                    SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]);
                    origNumber = msg.getOriginatingAddress();

                    Toast.makeText(getApplicationContext(), "Originating number" + origNumber, Toast.LENGTH_LONG).show();
                    Toast.makeText(getApplicationContext(), "Sent to number" + phoneNo, Toast.LENGTH_LONG).show();

                }

            };
            registerReceiver(receiver, filter);
        }
    }

    protected void sendSMSMessage() {
        phoneNo = txtphoneNo.getText().toString();

        //this is the SMS received
        String message = "Verification test code. Please ignore this message. Thank you.";

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();

            //if originating phone number is the same as the sent to number, save
            //and go to the next activity
            if (origNumber.equals(phoneNo)) {
                //save the phone number
                SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("phonenumber", phoneNo);
                editor.commit();

                Intent myIntent = new Intent(MainActivity.this, PopulistoContactList.class);
                MainActivity.this.startActivity(myIntent);
            }
        }

        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        super.onDestroy();
    }

Body:
What do you expect to happen here:

String phoneNoCheck = sharedPreferences.getString("phonenumber","");

if (phoneNoCheck != null) {

    ...
}

The method that you are calling, getString(String, String), uses the second parameter as the default value, that is, if no property is found, it will default to, as you have defined, an empty string, "".

You then try and compare this to null, which will never be equal.

Try changing it up to something like this:

String phoneNoCheck = sharedPreferences.getString("phonenumber", null);

// check if null or empty
if ( null == phoneNoCheck || phoneNoCheck.equals("") ) {

    // unregistered
}


问:
Xamarin New Bindable Picker Control
https://blog.xamarin.com/new-bindable-picker-control-for-xamarin-forms/

Im pretty new to xamarin and c#
Somehow it isnt working for me...

```<code> public class RegistrationPageViewModel : INotifyPropertyChanged
    {

        List<string> _countries = new List<string>
{
    "Afghanistan",
    "Albania",
    "Algeria",
    "Andorra",
    "Angola",

};
        public List<string> Countries => _countries;

        public event PropertyChangedEventHandler PropertyChanged;

    }
    public partial class RegistrationPage : ContentPage
    {
        RegistrationPageViewModel vm;

        public RegistrationPage()
        {
            InitializeComponent();
            this.BindingContext = vm = new RegistrationPageViewModel();
        }

        private void InitializeComponent()
        {
            throw new NotImplementedException();
        }
    }

    int countriesSelectedIndex;
            public int CountriesSelectedIndex
            {
                get
                {
                    return countriesSelectedIndex;
                }
                set
                {
                    if (countriesSelectedIndex != value)
                    {
                        countriesSelectedIndex = value;

                        // trigger some action to take such as updating other labels or fields
                        OnPropertyChanged(nameof(CountriesSelectedIndex));
                        SelectedCountry = Countries[countriesSelectedIndex];
                    }
                }
            }

        public string SelectedCountry { get; private set; }
    }
</code>```

Im getting an error:The name 'Countries' does not exist in the current context

What Im doing wrong? And does someone have an working example

答:
Here is how I would write it (use Fody rather than bother with INotifyPropertyChanged):

```<code>public class Country
    {
        public string Name { get; }
        public Country(string name) => Name = name;
        public static Country Afghanistan = new Country("Afghanistan");
        public static Country Albania = new Country("Albania");
        public static Country Algeria = new Country("Algeria");
        public static Country Andorra = new Country("Andorra");
        public static Country Angola = new Country("Angola");

        public static IList<Country> Countries = new List<Country> { Afghanistan, Albania, Algeria, Andorra, Andorra, Angola };
    }

    [ImplementPropertyChanged]
    public class RegistrationPageViewModel
    {
        public Country SelectedCountry { get; set; }
    }

    public class RegistrationPage : ContentPage
    {
        public RegistrationPage()
        {
            var vm = new RegistrationPageViewModel();
            BindingContext = vm;
            var picker = new Picker();
            foreach (var country in Country.Countries) picker.Items.Add(country.Name);
            picker.SetBinding<RegistrationPageViewModel>(Picker.SelectedIndexProperty, x => x.SelectedCountry, converter: new PickerItemsToTypeConverter<Country>(Country.Countries));
            Content = picker;
        }
    }

    public class PickerItemsToTypeConverter<T> : IValueConverter
    {
        private readonly IList<T> _pickerItemsList;

        public PickerItemsToTypeConverter(IList<T> pickerItemsList) => _pickerItemsList = pickerItemsList;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var itemType = (T)value;
            return _pickerItemsList.IndexOf(itemType);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var selectedIndex = value as int?;
            if (selectedIndex == null) throw new Exception("No selection");
            return _pickerItemsList[selectedIndex.Value];
        }
    }
</code>```

Title: Xamarin New Bindable Picker Control

Body:
https://blog.xamarin.com/new-bindable-picker-control-for-xamarin-forms/

Im pretty new to xamarin and c#
Somehow it isnt working for me...

 public class RegistrationPageViewModel : INotifyPropertyChanged
    {

        List<string> _countries = new List<string>
{
    "Afghanistan",
    "Albania",
    "Algeria",
    "Andorra",
    "Angola",

};
        public List<string> Countries => _countries;

        public event PropertyChangedEventHandler PropertyChanged;

    }
    public partial class RegistrationPage : ContentPage
    {
        RegistrationPageViewModel vm;

        public RegistrationPage()
        {
            InitializeComponent();
            this.BindingContext = vm = new RegistrationPageViewModel();
        }

        private void InitializeComponent()
        {
            throw new NotImplementedException();
        }
    }

    int countriesSelectedIndex;
            public int CountriesSelectedIndex
            {
                get
                {
                    return countriesSelectedIndex;
                }
                set
                {
                    if (countriesSelectedIndex != value)
                    {
                        countriesSelectedIndex = value;

                        // trigger some action to take such as updating other labels or fields
                        OnPropertyChanged(nameof(CountriesSelectedIndex));
                        SelectedCountry = Countries[countriesSelectedIndex];
                    }
                }
            }

        public string SelectedCountry { get; private set; }
    }

Im getting an error:The name 'Countries' does not exist in the current context

What Im doing wrong? And does someone have an working example

Body:
Here is how I would write it (use Fody rather than bother with INotifyPropertyChanged):

public class Country
    {
        public string Name { get; }
        public Country(string name) => Name = name;
        public static Country Afghanistan = new Country("Afghanistan");
        public static Country Albania = new Country("Albania");
        public static Country Algeria = new Country("Algeria");
        public static Country Andorra = new Country("Andorra");
        public static Country Angola = new Country("Angola");

        public static IList<Country> Countries = new List<Country> { Afghanistan, Albania, Algeria, Andorra, Andorra, Angola };
    }

    [ImplementPropertyChanged]
    public class RegistrationPageViewModel
    {
        public Country SelectedCountry { get; set; }
    }

    public class RegistrationPage : ContentPage
    {
        public RegistrationPage()
        {
            var vm = new RegistrationPageViewModel();
            BindingContext = vm;
            var picker = new Picker();
            foreach (var country in Country.Countries) picker.Items.Add(country.Name);
            picker.SetBinding<RegistrationPageViewModel>(Picker.SelectedIndexProperty, x => x.SelectedCountry, converter: new PickerItemsToTypeConverter<Country>(Country.Countries));
            Content = picker;
        }
    }

    public class PickerItemsToTypeConverter<T> : IValueConverter
    {
        private readonly IList<T> _pickerItemsList;

        public PickerItemsToTypeConverter(IList<T> pickerItemsList) => _pickerItemsList = pickerItemsList;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var itemType = (T)value;
            return _pickerItemsList.IndexOf(itemType);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var selectedIndex = value as int?;
            if (selectedIndex == null) throw new Exception("No selection");
            return _pickerItemsList[selectedIndex.Value];
        }
    }


问:
How to set up angular-cli with Visual Studio 2015 in MVC 5?
I'm looking for some best practices and instructions on how to set up and integrate angular-cli (webpack) with Visual Studio 2015 in MVC 5 (not Core).

I realize there's a similar question asked here (how to set up asp.net angular 2 project using Angular-Cli with ASP.NET Core in Visual Studio 2015?), but that was for Asp.net Core only. My project could not move over to Core yet due to server technical issues.

答:
My approach to integrating Angular/CLI and MVC:
The idea here is to separate the front end development experience from the MVC part, so you don’t have to deal with any of the Visual Studio BS, and enjoy the benefits of the Angular CLI and VS Code.

My app is a hybrid app - most pages and main navigation is classic MVC, but some views are in fact single page applications, where the NG app is embedded into an existing view.

I created a new project in the solution to store the SPAs. (You can exclude this project from the solution build)

In the new project, I created a directory for each SPA. Each one of these folders is a standard CLI project (created using ng new)

Development of the ng stuff is done with VS Code, serving the app using ng serve. The development experience with VS Code is awesome!

When we want to embed the app into the MVC view, we first build it for prod using ng build --prod. This creates the bundles in the dist folder.

In the MVC app, I prepared a folder under Scripts\Frontend for each SPA

A gulp task in the MVC project is responsible for copying the bundles from the SPAs' dist folders into the appropriate folders under Scripts\Frontend. Using Task Runner, the task was bound to to Before Build, so it is automatically executed whenever the app is built.
The important gulp command is:

```<code>gulp.src('../FrontEndProj/spa1/dist/*bundle.*')
    .pipe(gulp.dest('Scripts/Frontend/spa1'));
</code>```

of course, you need to delete the existing files etc.

In bundles config, I've created a bundle for the styles and a bundle for the scripts. Since prod bundle names are generated with hash by the CLI, I use wildcards:

```<code>bundles.add(new script("~/Scripts/spa1/js")
  .IncludeDirectory("~/Scripts/Frontend/spa1", inline.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "polyfills.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "vendor.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "main.*"));
</code>```

(Note that the order you add the files to the bundle is important!)

```<code>bundles.add(
  new StyleBundle("/Scripts/spa1.css")
    .IncludeDirectory("~/Scripts/Frontend/spa1", "*.css")
</code>```

In your view, add the ng app directive and use the bundles:

```<code>@section head {
  @Styles.Render("~Scripts/spa1/css")
}

<app-root>Loading...</app-root>

@Scripts.Render("~/Scripts/spa1/js")
</code>```

Body:
My approach to integrating Angular/CLI and MVC:
The idea here is to separate the front end development experience from the MVC part, so you don’t have to deal with any of the Visual Studio BS, and enjoy the benefits of the Angular CLI and VS Code.

My app is a hybrid app - most pages and main navigation is classic MVC, but some views are in fact single page applications, where the NG app is embedded into an existing view.

I created a new project in the solution to store the SPAs. (You can exclude this project from the solution build)

In the new project, I created a directory for each SPA. Each one of these folders is a standard CLI project (created using ng new)

Development of the ng stuff is done with VS Code, serving the app using ng serve. The development experience with VS Code is awesome!

When we want to embed the app into the MVC view, we first build it for prod using ng build --prod. This creates the bundles in the dist folder.

In the MVC app, I prepared a folder under Scripts\Frontend for each SPA

A gulp task in the MVC project is responsible for copying the bundles from the SPAs' dist folders into the appropriate folders under Scripts\Frontend. Using Task Runner, the task was bound to to Before Build, so it is automatically executed whenever the app is built.
The important gulp command is:

gulp.src('../FrontEndProj/spa1/dist/*bundle.*')
    .pipe(gulp.dest('Scripts/Frontend/spa1'));

of course, you need to delete the existing files etc.

In bundles config, I've created a bundle for the styles and a bundle for the scripts. Since prod bundle names are generated with hash by the CLI, I use wildcards:

bundles.add(new script("~/Scripts/spa1/js")
  .IncludeDirectory("~/Scripts/Frontend/spa1", inline.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "polyfills.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "vendor.*")
  .IncludeDirectory("~/Scripts/Frontend/spa1", "main.*"));

(Note that the order you add the files to the bundle is important!)

bundles.add(
  new StyleBundle("/Scripts/spa1.css")
    .IncludeDirectory("~/Scripts/Frontend/spa1", "*.css")

In your view, add the ng app directive and use the bundles:

@section head {
  @Styles.Render("~Scripts/spa1/css")
}

<app-root>Loading...</app-root>

@Scripts.Render("~/Scripts/spa1/js")


问:
How to get values from Dtype object in a dataframe
I have a dataframe with this column structure:

```<code>```
In [179]: df.dtypes
Out[179]:
layer         int32
row           int32
column        int32
segment       int32
reach         int32
Qin         float64
Qaquifer    float64
Qout        float64
Qovr        float64
Qprecip     float64
Qet         float64
stage       float64
depth       float64
width       float64
Cond        float64
Qwt         float64
deltaUZ     float64
GWh         float64
kstpkper     object
k             int32
i             int32
j             int32
dtype: object

In [180]: df.kstpkper
Out[180]:
0          (0, 0)
1          (0, 0)
2          (0, 0)
3          (0, 0)
4          (0, 0)
5          (0, 0)
            ...
18207    (35, 10)
18208    (35, 10)
18209    (35, 10)
18210    (35, 10)
18211    (35, 10)
18212    (35, 10)
Name: kstpkper, dtype: object
```
</code>```

I would like to split kstpkper variable in two and add them to my dataframe.  Is it possible?

How can I call each element in kstpkper variable?

Any help would be appreciated.

答:
List comprehension is one way:</p>

```<code>df['kstpkper1'] = [x[0] for x in df.kstpkper.values]
df['kstpkper2'] = [x[1] for x in df.kstpkper.values]
</code>```

Body:
I have a dataframe with this column structure:

In [179]: df.dtypes
Out[179]:
layer         int32
row           int32
column        int32
segment       int32
reach         int32
Qin         float64
Qaquifer    float64
Qout        float64
Qovr        float64
Qprecip     float64
Qet         float64
stage       float64
depth       float64
width       float64
Cond        float64
Qwt         float64
deltaUZ     float64
GWh         float64
kstpkper     object
k             int32
i             int32
j             int32
dtype: object

In [180]: df.kstpkper
Out[180]:
0          (0, 0)
1          (0, 0)
2          (0, 0)
3          (0, 0)
4          (0, 0)
5          (0, 0)
            ...
18207    (35, 10)
18208    (35, 10)
18209    (35, 10)
18210    (35, 10)
18211    (35, 10)
18212    (35, 10)
Name: kstpkper, dtype: object

I would like to split kstpkper variable in two and add them to my dataframe.  Is it possible?

How can I call each element in kstpkper variable?

Any help would be appreciated.

Body:
List comprehension is one way:

df['kstpkper1'] = [x[0] for x in df.kstpkper.values]
df['kstpkper2'] = [x[1] for x in df.kstpkper.values]


问:
How can I programmatically change the background in Mac OS X?
How would I go about programmatically changing the desktop background in Mac OS X?  I'd like to use python, but I'm interested in any way possible.  Could I hook up to Terminal and call a certain command?</p>

答:
You can call "defaults write com.apple.Desktop Background ..." as described in this article: http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/

The article also goes into scripting this to run automatically, but the first little bit should get you started.

You might also be interested in the defaults man pages: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html

OwnerDisplayName: stalepretzel

OwnerDisplayName: Matt Miller


问:
JSON data format changed & function building unordered list out of it stopped working?
I pass some data converting it into json & json outputs like;

```<code>[{"msg":"1: AVAILABLE: should be publicly available"},{"msg":"1: API USAGE: Uses api
of twitter to develop messaging service \n PUBLICALLY AVAILABLE: Should be publically
available"},{"msg":"1: EX_DES_EXP: Help novice users to exchange \n design experiences
through specifications messages"}]
</code>```

I use following script to build an unordered list using this json data:

```<code> <script type="text/javascript" language="javascript">
 jQuery(document).ready(function() {
 jQuery.getJSON("http://127.0.0.1/conn_msg2_qua.php", function (jsonData) {
 var markup;
 markup = [];
 jQuery.each(jsonData, function (i, j) {
    markup.push("<li>");
    markup.push(j.msg);
    markup.push("</li>");
 });
 jQuery('#msg_q').append(markup.join(""));
 });});
 </script>

  <script>
</code>```

Now I change implementation of data that was converted to json as bit & json appears like

```<code>["1 AVAILABLE: should be publicly available","2 API USAGE: Uses api of twitter to
 develop messaging service \n PUBLICALLY AVAILABLE: Should be publically available","3
 EX_DES_EXP: Help novice users to exchange \n design experiences through
 specifications messages"]
</code>```

and my function stopped printing it as unordered list. Whats the problem causes this. How do I again make it work.

答:
Since it's just an array of strings, you need just the j from your loop (the string), not the .msg property (which a string doesn't have), like this:

```<code>jQuery.each(jsonData, function (i, j) {
  markup.push("<li>");
  markup.push(j);
  markup.push("</li>");
});
</code>```

Body:
I pass some data converting it into json & json outputs like;

[{"msg":"1: AVAILABLE: should be publicly available"},{"msg":"1: API USAGE: Uses api
of twitter to develop messaging service \n PUBLICALLY AVAILABLE: Should be publically
available"},{"msg":"1: EX_DES_EXP: Help novice users to exchange \n design experiences
through specifications messages"}]

I use following script to build an unordered list using this json data:

Body:
Since it's just an array of strings, you need just the j from your loop (the string), not the .msg property (which a string doesn't have), like this:

jQuery.each(jsonData, function (i, j) {
  markup.push("<li>");
  markup.push(j);
  markup.push("</li>");
});


问:
QMainWindow doesn't .show() but .showFullScreen() works
I have a desktop application that I'm building which checks a QSetting value and if it isn't set shows one QMainWindow class but if it is, shows a different QMainWindow class. The two classes are literally identical at this point as it's early on and don't really contain anything.

In my main function this is what I've got:

```<code>int main (int argc, char *argv[]) {
    ...

    if (userToken == "NO_USER") {
       LoginWindow w;
       w.show();
    } else {
       MainWindow w;
       w.show();
    }

    return a.exec();
}
</code>```

The only difference in this between the default project set up from when I created the project is the addition of the conditional window load. Both MainWindow and LoginWindow don't have anything loading other than the ui file associated with them, they're functionally the same.

The weirdness is if I do w.showFullScreen() for the LoginWindow it will show up and take up the whole screen, if I do w.show() nothing at all happens, no compiler warnings|errors, application runs fine, just no window displays.

If I remove the conditional statements and LoginWindow references, MainWindow shows up fine.

Any idea why a call to .showFullScreen() would work but a call to .show() on the same class wouldn't?

答:
I am not sure if this solves you problem, but there definitely is a bug in your code. You are instanciating the window objects on the stack inside a a tight scope, and as you know those objects will be destructed as soon as they go out of that scope. What you are doing is letting them go out of scope before the application is ever started.

Please try this instead:

```<code>int main (int argc, char *argv[]) {
    ...

    if (userToken == "NO_USER") {
       LoginWindow w;
       w.show();
      return a.exec();
    } else {
       MainWindow w;
       w.show();
      return a.exec();
    }

}
</code>```

Body:
I have a desktop application that I'm building which checks a QSetting value and if it isn't set shows one QMainWindow class but if it is, shows a different QMainWindow class. The two classes are literally identical at this point as it's early on and don't really contain anything.

In my main function this is what I've got:

int main (int argc, char *argv[]) {
    ...

    if (userToken == "NO_USER") {
       LoginWindow w;
       w.show();
    } else {
       MainWindow w;
       w.show();
    }

    return a.exec();
}

The only difference in this between the default project set up from when I created the project is the addition of the conditional window load. Both MainWindow and LoginWindow don't have anything loading other than the ui file associated with them, they're functionally the same.

The weirdness is if I do w.showFullScreen() for the LoginWindow it will show up and take up the whole screen, if I do w.show() nothing at all happens, no compiler warnings|errors, application runs fine, just no window displays.

If I remove the conditional statements and LoginWindow references, MainWindow shows up fine.

Any idea why a call to .showFullScreen() would work but a call to .show() on the same class wouldn't?

Body:
I am not sure if this solves you problem, but there definitely is a bug in your code. You are instanciating the window objects on the stack inside a a tight scope, and as you know those objects will be destructed as soon as they go out of that scope. What you are doing is letting them go out of scope before the application is ever started.

Please try this instead:

int main (int argc, char *argv[]) {
    ...

    if (userToken == "NO_USER") {
       LoginWindow w;
       w.show();
      return a.exec();
    } else {
       MainWindow w;
       w.show();
      return a.exec();
    }

}