问:
R help - function on multiple data frame columns
I would like to use a function to repeat a set of procedures on four columns in a data frame. Ultimately I need a long data frame containing all the output. Here is my data frame:

```<code>> sample_data
# A tibble: 10 x 7
      REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
          <chr>  <dbl> <chr>       <chr>          <chr>           <chr>      <fctr>
 1 rev-24985629     30  FY18           S          Check            Mail     [25,50)
 2 rev-22812413      1  FY16           Q          Other      Canvassing   [0.01,10)
 3 rev-23508794    100  FY17           Q    Credit card             Web   [100,250)
 4 rev-23506121    300  FY17           S    Credit card            Mail   [250,500)
 5 rev-23550444    100  FY17           S    Credit card             Web   [100,250)
 6 rev-21508672     25  FY14           J          Check            Mail     [25,50)
 7 rev-24981769    500  FY18           S    Credit card             Web [500,1e+03)
 8 rev-23503684     50  FY17           R          Check            Mail     [50,75)
 9 rev-24982087     25  FY18           R          Check            Mail     [25,50)
10 rev-24979834     50  FY18           R    Credit card             Web     [50,75)
</code>```

Here is my code:

```<code>AMOUNT_CAT<- sample_data %>% group_by(AMOUNT_CAT,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=AMOUNT_CAT) %>% mutate(REPORT_CATEGORY="AMOUNT_CAT")
INBOUND_CHANNEL<- sample_data %>% group_by(INBOUND_CHANNEL,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=INBOUND_CHANNEL) %>% mutate(REPORT_CATEGORY="INBOUND_CHANNEL")
PAYMENT_METHOD<- sample_data %>% group_by(PAYMENT_METHOD,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=PAYMENT_METHOD) %>% mutate(REPORT_CATEGORY="PAYMENT_METHOD")
REPORT_CODE<- sample_data %>% group_by(REPORT_CODE,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=REPORT_CODE) %>% mutate(REPORT_CATEGORY="REPORT_CODE")
final_product<-bind_rows(REPORT_CODE,PAYMENT_METHOD,INBOUND_CHANNEL,AMOUNT_CAT)
</code>```

Here is the final product of that code:

```<code>       > final_product
        # A tibble: 27 x 5
        # Groups:   REPORT_VALUE [16]
           REPORT_CATEGORY REPORT_VALUE  YEAR   num total

                 <chr>        <chr> <chr> <int> <dbl>
     1     REPORT_CODE            J  FY14     1    25
     2     REPORT_CODE            Q  FY16     1     1
     3     REPORT_CODE            Q  FY17     1   100
     4     REPORT_CODE            R  FY17     1    50
     5     REPORT_CODE            R  FY18     2    75
     6     REPORT_CODE            S  FY17     2   400
     7     REPORT_CODE            S  FY18     2   530
     8  PAYMENT_METHOD        Check  FY14     1    25
     9  PAYMENT_METHOD        Check  FY17     1    50
    10  PAYMENT_METHOD        Check  FY18     2    55
    # ... with 17 more rows
</code>```

Here is my attempt to condense the code to make it smarter and more efficient (it doesn't work):

```<code>cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")
repeat_procs <- lapply(cat.list, function(x) x <- sample_data %>% group_by(x,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=x) %>% mutate(REPORT_CATEGORY="x")
</code>```

Can someone please advise me on how to write "smarter" code that doesn't repeat as often?

Thanks!

答:
A purrr approach added to make your code a little conciser and smarter.

```<code>library(tidyverse)
library(rlang)
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

map_df(cat.list,
       function(report_cat) {
           sample_data %>%
               group_by(!!sym(report_cat), YEAR) %>%
               summarize(num=n(),total=sum(AMOUNT)) %>%
               rename(REPORT_VALUE = !!sym(report_cat)) %>%
               mutate(REPORT_CATEGORY = report_cat)
       }
      )
</code>```

As Hadley describes here (about halfway down):

map_df(x, f) is effectively the same as do.call("rbind", lapply(x, f)) but under the hood is much more efficient.

Full disclosure, Thank you @useR for showing me how to use the sym(!!() approach.  I had backed myself into a corner using the Programming in Dplyr vignette to construct what I believed was the most up to date approach to functionalizing dplyr.
I had gotten the main dplyr function to run smoothly enough using var <- enquo(var) then !!vars  but I could not find a way to then deal with running the quoted names in cat.list through map_df or lapply.
Thank you, useR for teaching me a better way to code in tidyverse

Edit: Thank you, G. Grothendieck for unlocking how to get a list of strings to smoothly be accepted by the dplyr function: here

That allows me to complete the alternative quosured approach I had developed earlier:

```<code>report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}
report_named <- function(x) {do.call("report", list(as.name(x)))}
map_df(cat.list, report_named)
</code>```

```<code>> map_df(cat.list, report_named)
    # A tibble: 27 x 5
    # Groups:   REPORT_VALUE [16]
       REPORT_VALUE  YEAR   num total REPORT_CATEGORY
              <chr> <chr> <int> <int>           <chr>
     1            J  FY14     1    25     REPORT_CODE
     2            Q  FY16     1     1     REPORT_CODE
     3            Q  FY17     1   100     REPORT_CODE
     4            R  FY17     1    50     REPORT_CODE
     5            R  FY18     2    75     REPORT_CODE
     6            S  FY17     2   400     REPORT_CODE
     7            S  FY18     2   530     REPORT_CODE
     8        Check  FY14     1    25  PAYMENT_METHOD
     9        Check  FY17     1    50  PAYMENT_METHOD
    10        Check  FY18     2    55  PAYMENT_METHOD
    # ... with 17 more rows
</code>```

NB: yutannihilation's tidy solution really is the optimal solution IMHO - I was just using this as an opportunity to expand my understanding of how we can carry along the split, apply, combine approach to include dplyr functions.

Body:
I would like to use a function to repeat a set of procedures on four columns in a data frame. Ultimately I need a long data frame containing all the output. Here is my data frame:

> sample_data
# A tibble: 10 x 7
      REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
          <chr>  <dbl> <chr>       <chr>          <chr>           <chr>      <fctr>
 1 rev-24985629     30  FY18           S          Check            Mail     [25,50)
 2 rev-22812413      1  FY16           Q          Other      Canvassing   [0.01,10)
 3 rev-23508794    100  FY17           Q    Credit card             Web   [100,250)
 4 rev-23506121    300  FY17           S    Credit card            Mail   [250,500)
 5 rev-23550444    100  FY17           S    Credit card             Web   [100,250)
 6 rev-21508672     25  FY14           J          Check            Mail     [25,50)
 7 rev-24981769    500  FY18           S    Credit card             Web [500,1e+03)
 8 rev-23503684     50  FY17           R          Check            Mail     [50,75)
 9 rev-24982087     25  FY18           R          Check            Mail     [25,50)
10 rev-24979834     50  FY18           R    Credit card             Web     [50,75)

Here is my code:

AMOUNT_CAT<- sample_data %>% group_by(AMOUNT_CAT,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=AMOUNT_CAT) %>% mutate(REPORT_CATEGORY="AMOUNT_CAT")
INBOUND_CHANNEL<- sample_data %>% group_by(INBOUND_CHANNEL,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=INBOUND_CHANNEL) %>% mutate(REPORT_CATEGORY="INBOUND_CHANNEL")
PAYMENT_METHOD<- sample_data %>% group_by(PAYMENT_METHOD,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=PAYMENT_METHOD) %>% mutate(REPORT_CATEGORY="PAYMENT_METHOD")
REPORT_CODE<- sample_data %>% group_by(REPORT_CODE,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=REPORT_CODE) %>% mutate(REPORT_CATEGORY="REPORT_CODE")
final_product<-bind_rows(REPORT_CODE,PAYMENT_METHOD,INBOUND_CHANNEL,AMOUNT_CAT)

Here is the final product of that code:

       > final_product
        # A tibble: 27 x 5
        # Groups:   REPORT_VALUE [16]
           REPORT_CATEGORY REPORT_VALUE  YEAR   num total

                 <chr>        <chr> <chr> <int> <dbl>
     1     REPORT_CODE            J  FY14     1    25
     2     REPORT_CODE            Q  FY16     1     1
     3     REPORT_CODE            Q  FY17     1   100
     4     REPORT_CODE            R  FY17     1    50
     5     REPORT_CODE            R  FY18     2    75
     6     REPORT_CODE            S  FY17     2   400
     7     REPORT_CODE            S  FY18     2   530
     8  PAYMENT_METHOD        Check  FY14     1    25
     9  PAYMENT_METHOD        Check  FY17     1    50
    10  PAYMENT_METHOD        Check  FY18     2    55
    # ... with 17 more rows

Here is my attempt to condense the code to make it smarter and more efficient (it doesn't work):

cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")
repeat_procs <- lapply(cat.list, function(x) x <- sample_data %>% group_by(x,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=x) %>% mutate(REPORT_CATEGORY="x")

Can someone please advise me on how to write "smarter" code that doesn't repeat as often?

Thanks!

Body:
A purrr approach added to make your code a little conciser and smarter.

library(tidyverse)
library(rlang)
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

map_df(cat.list,
       function(report_cat) {
           sample_data %>%
               group_by(!!sym(report_cat), YEAR) %>%
               summarize(num=n(),total=sum(AMOUNT)) %>%
               rename(REPORT_VALUE = !!sym(report_cat)) %>%
               mutate(REPORT_CATEGORY = report_cat)
       }
      )

As Hadley describes here (about halfway down):

map_df(x, f) is effectively the same as do.call("rbind", lapply(x, f)) but under the hood is much more efficient.

Full disclosure, Thank you @useR for showing me how to use the sym(!!() approach.  I had backed myself into a corner using the Programming in Dplyr vignette to construct what I believed was the most up to date approach to functionalizing dplyr.
I had gotten the main dplyr function to run smoothly enough using var <- enquo(var) then !!vars  but I could not find a way to then deal with running the quoted names in cat.list through map_df or lapply.
Thank you, useR for teaching me a better way to code in tidyverse

Edit: Thank you, G. Grothendieck for unlocking how to get a list of strings to smoothly be accepted by the dplyr function: here

That allows me to complete the alternative quosured approach I had developed earlier:

report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}
report_named <- function(x) {do.call("report", list(as.name(x)))}
map_df(cat.list, report_named)

> map_df(cat.list, report_named)
    # A tibble: 27 x 5
    # Groups:   REPORT_VALUE [16]
       REPORT_VALUE  YEAR   num total REPORT_CATEGORY
              <chr> <chr> <int> <int>           <chr>
     1            J  FY14     1    25     REPORT_CODE
     2            Q  FY16     1     1     REPORT_CODE
     3            Q  FY17     1   100     REPORT_CODE
     4            R  FY17     1    50     REPORT_CODE
     5            R  FY18     2    75     REPORT_CODE
     6            S  FY17     2   400     REPORT_CODE
     7            S  FY18     2   530     REPORT_CODE
     8        Check  FY14     1    25  PAYMENT_METHOD
     9        Check  FY17     1    50  PAYMENT_METHOD
    10        Check  FY18     2    55  PAYMENT_METHOD
    # ... with 17 more rows

NB: yutannihilation's tidy solution really is the optimal solution IMHO - I was just using this as an opportunity to expand my understanding of how we can carry along the split, apply, combine approach to include dplyr functions.


来源: stackexchange

问:
Eigen rowwise cross product between arrays
I have two Eigen::ArrayX3d objects, that's N rows and 3 columns. To make this concrete, the first array consists of 3d velocities of N particles. The other one consists of magnetic field vectors at the position of each of the particles. I'm trying to compute the Lorentz force, v x B - this means I have to take each pair of rows and compute the cross product. In Python, this would mean simply doing numpy.cross(v, B).

I'm trying to figure out how to do this in Eigen and failing hard. It seems as though cross is defined for Matrix and Vectors only, but it doesn't really make sense to me to keep my data as a Matrix (though I'm of course open to suggestions).

Is there any reasonable way to perform this operation? I'd be very grateful for any pointers.

This setup is a good example::

```<code>   ArrayX3d a(4,3);
   ArrayX3d b(4,3);
   a <<1,0,0,
       0,1,0,
       0,0,1,
       1,0,0;
   b <<0,1,0,
       0,0,1,
       1,0,0,
       0,1,0;
</code>```

A successful application of the a x b operation should just shift the 1's by 1 place to the right in each row.

答:
I can get the result using a matrix or array:

```<code>  MatrixX3d a(4, 3);
  MatrixX3d b(4, 3);
  a << 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0;
  b << 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0;
  for(int i = 0; i < a.rows(); i++){
      cout << a.row(i).cross(b.row(i)) << endl;
  }
</code>```

With an array:

```<code>  ArrayX3d a(4, 3);
  ArrayX3d b(4, 3);
  a << 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0;
  b << 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0;
  for(int i = 0; i < a.rows(); i++){
      cout << a.row(i).matrix().cross(b.matrix().row(i)) << endl;
  }
</code>```

The output:

```<code>0 0 1
1 0 0
0 1 0
0 0 1
</code>```

This result could be saved into a matrix or array for each row.

ContentLicense: CC BY-SA 3.0

Body:
I have two Eigen::ArrayX3d objects, that's N rows and 3 columns. To make this concrete, the first array consists of 3d velocities of N particles. The other one consists of magnetic field vectors at the position of each of the particles. I'm trying to compute the Lorentz force, v x B - this means I have to take each pair of rows and compute the cross product. In Python, this would mean simply doing numpy.cross(v, B).

I'm trying to figure out how to do this in Eigen and failing hard. It seems as though cross is defined for Matrix and Vectors only, but it doesn't really make sense to me to keep my data as a Matrix (though I'm of course open to suggestions).

Is there any reasonable way to perform this operation? I'd be very grateful for any pointers.

This setup is a good example::

   ArrayX3d a(4,3);
   ArrayX3d b(4,3);
   a <<1,0,0,
       0,1,0,
       0,0,1,
       1,0,0;
   b <<0,1,0,
       0,0,1,
       1,0,0,
       0,1,0;

A successful application of the a x b operation should just shift the 1's by 1 place to the right in each row.

Body:
I can get the result using a matrix or array:

  MatrixX3d a(4, 3);
  MatrixX3d b(4, 3);
  a << 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0;
  b << 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0;
  for(int i = 0; i < a.rows(); i++){
      cout << a.row(i).cross(b.row(i)) << endl;
  }

With an array:

  ArrayX3d a(4, 3);
  ArrayX3d b(4, 3);
  a << 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0;
  b << 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0;
  for(int i = 0; i < a.rows(); i++){
      cout << a.row(i).matrix().cross(b.matrix().row(i)) << endl;
  }

The output:

0 0 1
1 0 0
0 1 0
0 0 1

This result could be saved into a matrix or array for each row.


问:
C++ - functor vs inline function vs operator overload?
Based on various Stack Overflow posts, I put the following together in a license plate recognition program I did a while back:

PossiblePlate.h:

```<code>(lines omitted)

std::string strChars;

///////////////////////////////////////////////////////////////////////////////////////////////
static bool sortDescendingByNumberOfChars(const PossiblePlate &ppLeft, const PossiblePlate &ppRight) {
    return(ppLeft.strChars.length() > ppRight.strChars.length());
}

(lines omitted)
</code>```

Main.cpp

```<code>(lines omitted)

// sort the vector of possible plates in descending order (most number of chars to least number of chars)
std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(), PossiblePlate::sortDescendingByNumberOfChars);

(lines omitted)
</code>```

Here is the repo if more context would be helpful:

https://github.com/MicrocontrollersAndMore/OpenCV_3_License_Plate_Recognition_Cpp

This code is great for sorting a vector of objects in C++ based on any member variable, I've re-used it quite a few times since in various other projects.

My question is, what is this?  A functor, inline function, operator overload, or something else entirely?  How could I determine the difference?

答: Maybe i don't understand the question but if this refers to std::sort i would say it is a template function ref

Body:
Based on various Stack Overflow posts, I put the following together in a license plate recognition program I did a while back:

PossiblePlate.h:

(lines omitted)

std::string strChars;

///////////////////////////////////////////////////////////////////////////////////////////////
static bool sortDescendingByNumberOfChars(const PossiblePlate &ppLeft, const PossiblePlate &ppRight) {
    return(ppLeft.strChars.length() > ppRight.strChars.length());
}

(lines omitted)

Main.cpp

(lines omitted)

// sort the vector of possible plates in descending order (most number of chars to least number of chars)
std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(), PossiblePlate::sortDescendingByNumberOfChars);

(lines omitted)

Here is the repo if more context would be helpful:

https://github.com/MicrocontrollersAndMore/OpenCV_3_License_Plate_Recognition_Cpp

This code is great for sorting a vector of objects in C++ based on any member variable, I've re-used it quite a few times since in various other projects.

My question is, what is this?  A functor, inline function, operator overload, or something else entirely?  How could I determine the difference?


问:
Android ListView State List not showing default item background
Have read over a number of related questions here at SO, as well as looked through the Android docs and source to try to figure this out, but I am stumped, although given that the listSelector seems to only apply styles on selected items, I'm not shocked...

I have a Listview defined in main.xml here:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fadingEdgeLength="5dp"
    android:divider="#000000"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />
    <TextView
    android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:singleLine="false"
        android:text="@string/message_list_empty" />
</FrameLayout>
</code>```

The listSelector referenced is here (borrowed largely from the default Android State List found in the SDK: /android/platforms/android-8/data/res/drawable/list_selector_background.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- the window has lost focus, disable the items -->
    <item
        android:state_window_focused="false"
        android:drawable="@drawable/shape_row_disabled" />

    <!-- the list items are disabled -->
    <item
        android:state_enabled="false"
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_disabled" />
    <item
        android:state_enabled="false"
        android:state_focused="true"
        android:drawable="@drawable/shape_row_disabled" />
    <item
        android:state_enabled="false"
        android:drawable="@drawable/shape_row_disabled" />

    <!-- the list items are enabled and being pressed -->
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_transition" />
    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_transition" />

    <!-- the list items are enabled and being used -->
    <item
        android:state_focused="true"
        android:drawable="@drawable/shape_row_selected" />

    <!-- the default item -->
    <item
        android:drawable="@drawable/shape_row" />
</selector>
</code>```

The drawables referenced are shapes, rounded rectangles, like so:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <gradient
        android:startColor="#EF6100"
        android:centerColor="#FF8E00"
        android:endColor="#EF6100"
        android:angle="270" />
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />
</shape>
</code>```

So, the end result should be a ListView with items with a @drawable/shape_row background by default, and then different colored backgrounds depending on the state.  When I fire up my list, everything works fine in terms of when states are active, such as an item gets focus, is pressed, etc, but the items themselves have a transparent background when none are selected (i.e. the default view state).  I had hoped that the last rule of the State List,

```<code><item android:drawable="@drawable/shape_row" />
</code>```

would capture that state, but for some reason it is not working.  I have moved things around and tried different settings, and nothing.  If I edit the row.xml file which I use to define the list items in the ListView and try to add a specific android:background that points to @drawable/shape_row, every row gets the correct background, BUT on pressed, on focus, etc states fail to process (or at least, can't be seen as the background never changes).

Can anyone point me in the right direction here?  I am SO close to putting this one to bed, but after trying nearly everything, just can't get the ListView items to take a default background AND respond to the implemented State List via android:listSelector.

Thanks,

Paul

EDIT:

Also just tried adding android:itemBackground="@drawable/shape_row" to the ListView in main.xml, and unsurprisingly no luck (the docs state it should be used to specify menu items' backgrounds, but thought it was worth a shot with list items).

Another thing tried, adding android:visible="true" to each of the selector and item definitions.  The StateListDrawable docs seem to indicate that the "Provides initial visibility state of the drawable; the default value is false", but adding this changed nothing.

EDIT2: So, based on the research done below by Qberticus, it seems that there can be only one set of list selectors per view, which confirms the list selector behavior.  I can also confirm that setting the android:drawSelectorOnTop does move the selector IN FRONT of the selected item, but this of course obscures the item itself such that I only see the selector itself (which in my case is a colored shape).

Here is what the list looks like with backgrounds set:

Due to the set background, there is no change in appearance when items are selected.  If I change the android:drawSelectorOnTop directive to true and select an item, I get:

And finally, if I set no background image for the list items, the selector works as expected, but of course, there are no background images as the last rule of the StateSelector does not appear to be followed (shouldn't it act as a catchall?) for non-selected items meaning no nice custom rounded shapes:

So, my problem remains; if I don't set a background for each list item, I can see the selector working BUT the items have no background when not selected.  If I set a background for the item, they look great when not selected, but the background obscures the selector.  Is it simply not possible to have a uniquely shaped list item with working selectors?

Thanks for anyone else who can weight in.

答:
The listSelector is only used to specify a View that will be drawn in the same place as the selected item View. I.e., there is only one instance of the listSelector per ListView. You can specify if it can draw on top or not using drawSelectorOnTop.

If you want all your Views to use a state list then you should specify that where the child Views are defined.

I'm using the source for AbsListView as reference. Specifically AbsListView#setSelector(Drawable), AbsListView#positionSelector, AbsListView#drawSelector, and AbsListView#dispatchDraw

AbsListView#drawSelector:

```<code>private void drawSelector(Canvas canvas) {
        if (shouldShowSelector() && mSelectorRect != null && !mSelectorRect.isEmpty()) {
            final Drawable selector = mSelector;
            selector.setBounds(mSelectorRect);
            selector.draw(canvas);
        }
}
</code>```

AbsListView#positionSelector:

```<code>void positionSelector(View sel) {
    final Rect selectorRect = mSelectorRect;
    selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
    positionSelector(selectorRect.left, selectorRect.top, selectorRect.right,
            selectorRect.bottom);

    final boolean isChildViewEnabled = mIsChildViewEnabled;
    if (sel.isEnabled() != isChildViewEnabled) {
        mIsChildViewEnabled = !isChildViewEnabled;
        refreshDrawableState();
    }
}
</code>```

The source indicates that there is only one mSelector created/used and that it is positioned in the same bounding rect as the selected item.

ContentLicense: CC BY-SA 2.5

Body:
Have read over a number of related questions here at SO, as well as looked through the Android docs and source to try to figure this out, but I am stumped, although given that the listSelector seems to only apply styles on selected items, I'm not shocked...

I have a Listview defined in main.xml here:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fadingEdgeLength="5dp"
    android:divider="#000000"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />
    <TextView
    android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:singleLine="false"
        android:text="@string/message_list_empty" />
</FrameLayout>

The listSelector referenced is here (borrowed largely from the default Android State List found in the SDK: /android/platforms/android-8/data/res/drawable/list_selector_background.xml):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_window_focused="false"
        android:drawable="@drawable/shape_row_disabled" />

    <item
        android:state_enabled="false"
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_disabled" />
    <item
        android:state_enabled="false"
        android:state_focused="true"
        android:drawable="@drawable/shape_row_disabled" />
    <item
        android:state_enabled="false"
        android:drawable="@drawable/shape_row_disabled" />

    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_transition" />
    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/shape_row_transition" />

    <item
        android:state_focused="true"
        android:drawable="@drawable/shape_row_selected" />

    <item
        android:drawable="@drawable/shape_row" />
</selector>

The drawables referenced are shapes, rounded rectangles, like so:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <gradient
        android:startColor="#EF6100"
        android:centerColor="#FF8E00"
        android:endColor="#EF6100"
        android:angle="270" />
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />
</shape>

So, the end result should be a ListView with items with a @drawable/shape_row background by default, and then different colored backgrounds depending on the state.  When I fire up my list, everything works fine in terms of when states are active, such as an item gets focus, is pressed, etc, but the items themselves have a transparent background when none are selected (i.e. the default view state).  I had hoped that the last rule of the State List,

<item android:drawable="@drawable/shape_row" />

would capture that state, but for some reason it is not working.  I have moved things around and tried different settings, and nothing.  If I edit the row.xml file which I use to define the list items in the ListView and try to add a specific android:background that points to @drawable/shape_row, every row gets the correct background, BUT on pressed, on focus, etc states fail to process (or at least, can't be seen as the background never changes).

Can anyone point me in the right direction here?  I am SO close to putting this one to bed, but after trying nearly everything, just can't get the ListView items to take a default background AND respond to the implemented State List via android:listSelector.

Thanks,

Paul

EDIT:

Also just tried adding android:itemBackground="@drawable/shape_row" to the ListView in main.xml, and unsurprisingly no luck (the docs state it should be used to specify menu items' backgrounds, but thought it was worth a shot with list items).

Another thing tried, adding android:visible="true" to each of the selector and item definitions.  The StateListDrawable docs seem to indicate that the "Provides initial visibility state of the drawable; the default value is false", but adding this changed nothing.

EDIT2: So, based on the research done below by Qberticus, it seems that there can be only one set of list selectors per view, which confirms the list selector behavior.  I can also confirm that setting the android:drawSelectorOnTop does move the selector IN FRONT of the selected item, but this of course obscures the item itself such that I only see the selector itself (which in my case is a colored shape).

Here is what the list looks like with backgrounds set:

Due to the set background, there is no change in appearance when items are selected.  If I change the android:drawSelectorOnTop directive to true and select an item, I get:

And finally, if I set no background image for the list items, the selector works as expected, but of course, there are no background images as the last rule of the StateSelector does not appear to be followed (shouldn't it act as a catchall?) for non-selected items meaning no nice custom rounded shapes:

So, my problem remains; if I don't set a background for each list item, I can see the selector working BUT the items have no background when not selected.  If I set a background for the item, they look great when not selected, but the background obscures the selector.  Is it simply not possible to have a uniquely shaped list item with working selectors?

Thanks for anyone else who can weight in.

Body:
The listSelector is only used to specify a View that will be drawn in the same place as the selected item View. I.e., there is only one instance of the listSelector per ListView. You can specify if it can draw on top or not using drawSelectorOnTop.

If you want all your Views to use a state list then you should specify that where the child Views are defined.

I'm using the source for AbsListView as reference. Specifically AbsListView#setSelector(Drawable), AbsListView#positionSelector, AbsListView#drawSelector, and AbsListView#dispatchDraw

AbsListView#drawSelector:

private void drawSelector(Canvas canvas) {
        if (shouldShowSelector() && mSelectorRect != null && !mSelectorRect.isEmpty()) {
            final Drawable selector = mSelector;
            selector.setBounds(mSelectorRect);
            selector.draw(canvas);
        }
}

AbsListView#positionSelector:

void positionSelector(View sel) {
    final Rect selectorRect = mSelectorRect;
    selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
    positionSelector(selectorRect.left, selectorRect.top, selectorRect.right,
            selectorRect.bottom);

    final boolean isChildViewEnabled = mIsChildViewEnabled;
    if (sel.isEnabled() != isChildViewEnabled) {
        mIsChildViewEnabled = !isChildViewEnabled;
        refreshDrawableState();
    }
}

The source indicates that there is only one mSelector created/used and that it is positioned in the same bounding rect as the selected item.


问:
Reliably tracking changes made by Hibernate
I'm using a PostUpdateEventListener registered via

```<code>registry.appendListeners(EventType.POST_COMMIT_UPDATE, listener)
</code>```

and a few other listeners in order to track changes made by Hibernate. This works perfectly, however, I see a problem there:

Let's say, for tracking some amount by id, I simply execute

```<code> amountByIdConcurrentMap.put(id, amount);
</code>```

on every POST_COMMIT_UPDATE (let's ignore other operations). The problem is that this call happens some time after the commit. So with two commits  writing the same entity shortly one after the other, I can receive the events in the wrong order, ending up with the older amount stored.

Is this really possible or are the operations synchronized somehow?

Is there a way how to prevent or at least detect such situation?

答:
Two questions and a proposal later

Are you sure, that you need this optimization. Why not fetch the amount as it is written to the database by querying there. What gives you reason to work with caching.

How do you make sure, that the calculation of the amount before writing it to the database is properly synchronized, so that multiple threads or probably nodes do not use old data to calculate the amount and therefore overwrite the result of a later calculation?

I suppose you handle question number 2 right. Then you have to options:

Pessimistic locking, that means that immediatly before the commit you can exclusively update your cache without concurrency issues.

Optimistic locking: In that case you have a kind of timestamp or counter in your database-record you can also put into the cache together with the amount. This value you can use to find out, what the more recent value is.

Body:
I'm using a PostUpdateEventListener registered via

registry.appendListeners(EventType.POST_COMMIT_UPDATE, listener)

and a few other listeners in order to track changes made by Hibernate. This works perfectly, however, I see a problem there:

Let's say, for tracking some amount by id, I simply execute

 amountByIdConcurrentMap.put(id, amount);

on every POST_COMMIT_UPDATE (let's ignore other operations). The problem is that this call happens some time after the commit. So with two commits  writing the same entity shortly one after the other, I can receive the events in the wrong order, ending up with the older amount stored.

Is this really possible or are the operations synchronized somehow?

Is there a way how to prevent or at least detect such situation?


问:
Count minimum operations required to reach target number
I'm currently working on a function in JavaScript that takes an array of numbers, for example: [5, 10, 18, 25, 30] and then returns an array which contains the count of minimum operations required that it took to get from 0 to the target number, by only adding 1 or multiplying by 2.

For example, from the array, the number 5 would return 4 because you'd do 0 + 1 = 1 x 2 = 2 x 2 = 4 + 1 = 5.

If the array passed in was [5,5,5] the output array would be [4,4,4].

I've looked around at potential solutions to this problem, some of which used iteration and others recursion. I found an answer for a similar question here Code Review - Find sequence by adding 5 or multiplying by 3.

The only difference is this was adding 5 or multiplying by 2, and it starts from 1 as opposed to 0. I've attempted to adapt this solution to suit my needs, however, for some reason, the code will only ever add 1 and never times 2. So, for the input 5 I am returned with 0 + 1 = 1 + 1 = 2 + 1 = 3 + 1 = 4 + 1 = 5 which obviously isn't the shortest solution.

Eventually I do need this to return an array, as the input will also be an array, however I'm struggling to even get this adaptation of the above answer to work, just with taking a single integer as a parameter.

When I pass 5 into this function I am returned with 5 instead of the shortest solution which is 4, because it only ever adds 1.

The code I have at the moment is:

```<code>function findSequence(goal) {
  function find(start, history) {
    if (start == goal) {
      return history;
    }
    if (start > goal) {
      return null;
    }
    return find(start + 1, "(" + history + " + 1)") ||
             find(start * 2, "(" + history + " * 2)");
  }
  return find(0, "0");
}
</code>```

How can I make this work? I need to return the shortest sequence count to get from 0 to the target number by only adding 1 or multiplying 2

答:
How about something like this:

```<code>function findMoves(target)
{
    arr = [];
    while (target != 1)
    {
        if (target %2 == 0)
        {
            target /= 2;
            arr.unshift(target + " x " + 2);
            continue;
        }
        target -= 1;
        arr.unshift(target + " + " + 1);
    }
    arr.unshift("0 + 1");
    return arr;
}

res = findMoves(9);

console.log(
    "TotalMoves: " + res.length + "\n" +
    "What moves: " + res.join(', '));
</code>```

Prints:

```<code>TotalMoves: 5
What moves: 0 + 1, 1 x 2, 2 x 2, 4 x 2, 8 + 1
</code>```

Body:
I'm currently working on a function in JavaScript that takes an array of numbers, for example: [5, 10, 18, 25, 30] and then returns an array which contains the count of minimum operations required that it took to get from 0 to the target number, by only adding 1 or multiplying by 2.

For example, from the array, the number 5 would return 4 because you'd do 0 + 1 = 1 x 2 = 2 x 2 = 4 + 1 = 5.

If the array passed in was [5,5,5] the output array would be [4,4,4].

I've looked around at potential solutions to this problem, some of which used iteration and others recursion. I found an answer for a similar question here Code Review - Find sequence by adding 5 or multiplying by 3.

The only difference is this was adding 5 or multiplying by 2, and it starts from 1 as opposed to 0. I've attempted to adapt this solution to suit my needs, however, for some reason, the code will only ever add 1 and never times 2. So, for the input 5 I am returned with 0 + 1 = 1 + 1 = 2 + 1 = 3 + 1 = 4 + 1 = 5 which obviously isn't the shortest solution.

Eventually I do need this to return an array, as the input will also be an array, however I'm struggling to even get this adaptation of the above answer to work, just with taking a single integer as a parameter.

When I pass 5 into this function I am returned with 5 instead of the shortest solution which is 4, because it only ever adds 1.

The code I have at the moment is:

function findSequence(goal) {
  function find(start, history) {
    if (start == goal) {
      return history;
    }
    if (start > goal) {
      return null;
    }
    return find(start + 1, "(" + history + " + 1)") ||
             find(start * 2, "(" + history + " * 2)");
  }
  return find(0, "0");
}

How can I make this work? I need to return the shortest sequence count to get from 0 to the target number by only adding 1 or multiplying 2

Body:
How about something like this:

function findMoves(target)
{
    arr = [];
    while (target != 1)
    {
        if (target %2 == 0)
        {
            target /= 2;
            arr.unshift(target + " x " + 2);
            continue;
        }
        target -= 1;
        arr.unshift(target + " + " + 1);
    }
    arr.unshift("0 + 1");
    return arr;
}

res = findMoves(9);

console.log(
    "TotalMoves: " + res.length + "\n" +
    "What moves: " + res.join(', '));

Prints:

TotalMoves: 5
What moves: 0 + 1, 1 x 2, 2 x 2, 4 x 2, 8 + 1


问:
Arrays.deepEquals returning false on 2 identical arrays
I have a code

```<code>import java.util.*;
import java.io.*;

public class Dijkstra {

        public static int [][] Dijkstra_alg( int n, int e, int mat[][], int s)
        {
            s=s-1;
            int adj[][]=new int[n][n];
            for(int i=0;i<e;i++)
            {
                adj[mat[i][0]-1][mat[i][1]-1]=mat[i][2];
            }
            // for(int i=0;i<n;i++)
            // {
            //     for(int j=0;j<n;j++)
            //     {
            //         System.out.print(adj[i][j]+"\t\t");
            //     }
            //     System.out.println();
            // }
            int dist[][] = new int[n][n]; //dist[][1] holds USP value

            Boolean visited[] = new Boolean[n];

            for (int i = 0; i < n; i++)
            {
                dist[i][0] = Integer.MAX_VALUE;
                visited[i] = false;
                dist[i][1]=1;
            }

            dist[s][0] = 0;

            for (int i = 0; i < n-1; i++)
            {
                int min = Integer.MAX_VALUE;
                int u=-1;
                for (int v = 0; v < n; v++)
                if (visited[v] == false && dist[v][0] <= min)
                {
                    min = dist[v][0];
                    u = v;
                }

                visited[u] = true;

                //relax
                for (int v = 0; v < n; v++)
                {
                    if (!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] < dist[v][0])
                    {
                        dist[v][0] = dist[u][0] + adj[u][v];
                        dist[v][1]=1;
                    }
                    else if(!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] == dist[v][0])
                        dist[v][1]=0;
                }
            }
            return dist;

        }

        public static void main(String args[])
        {
            int[][] Mat = {  {1, 2, 9}, {1, 3, 6}, {1, 4, 5}, {1, 5, 3}, {3, 2, 2}, {3, 4, 4}  };
            int N = 5;
            int E = 6;
            int S = 1;
            int [][] ans = {{0, 1}, {8, 1}, {6, 1}, {5, 1}, {3, 1}};
            int [][] dist=Dijkstra_alg(N,E,Mat,S);
            System.out.println(dist.length);
            System.out.println(ans.length);
            for (int i = 0; i < N; i++)
            {
                System.out.println(dist[i][0]+"\t\t"+dist[i][1]);
                System.out.println(ans[i][0]+"\t\t"+ans[i][1]);
            }
            System.out.println((Arrays.deepEquals(dist,ans)));
        }

}
</code>```

dist and ans print exactly the same result, but even then, Arrays.deepEquals returns false. Cant figure out why is it displaying false

both these arrays are identical, but giving the result false

the output looks like :

```<code>5
5
0               1
0               1
8               1
8               1
6               1
6               1
5               1
5               1
3               1
3               1
false
</code>```

as you can see the output is exactly identical and shouldn't be giving such an error, but it still does. Cannot figure out why this is happening.

Does anyone know how to fix this?

答:
```<code>int dist[][] = new int[n][n];
</code>```

The second dimension of dist is n, while the second dimension of ans is 2.

Change it to

```<code>int dist[][] = new int[n][2];
</code>```

Body:
I have a code

import java.util.*;
import java.io.*;

public class Dijkstra {

        public static int [][] Dijkstra_alg( int n, int e, int mat[][], int s)
        {
            s=s-1;
            int adj[][]=new int[n][n];
            for(int i=0;i<e;i++)
            {
                adj[mat[i][0]-1][mat[i][1]-1]=mat[i][2];
            }
            // for(int i=0;i<n;i++)
            // {
            //     for(int j=0;j<n;j++)
            //     {
            //         System.out.print(adj[i][j]+"\t\t");
            //     }
            //     System.out.println();
            // }
            int dist[][] = new int[n][n]; //dist[][1] holds USP value

            Boolean visited[] = new Boolean[n];

            for (int i = 0; i < n; i++)
            {
                dist[i][0] = Integer.MAX_VALUE;
                visited[i] = false;
                dist[i][1]=1;
            }

            dist[s][0] = 0;

            for (int i = 0; i < n-1; i++)
            {
                int min = Integer.MAX_VALUE;
                int u=-1;
                for (int v = 0; v < n; v++)
                if (visited[v] == false && dist[v][0] <= min)
                {
                    min = dist[v][0];
                    u = v;
                }

                visited[u] = true;

                //relax
                for (int v = 0; v < n; v++)
                {
                    if (!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] < dist[v][0])
                    {
                        dist[v][0] = dist[u][0] + adj[u][v];
                        dist[v][1]=1;
                    }
                    else if(!visited[v] && adj[u][v]!=0 && dist[u][0] != Integer.MAX_VALUE &&dist[u][0]+adj[u][v] == dist[v][0])
                        dist[v][1]=0;
                }
            }
            return dist;

        }

        public static void main(String args[])
        {
            int[][] Mat = {  {1, 2, 9}, {1, 3, 6}, {1, 4, 5}, {1, 5, 3}, {3, 2, 2}, {3, 4, 4}  };
            int N = 5;
            int E = 6;
            int S = 1;
            int [][] ans = {{0, 1}, {8, 1}, {6, 1}, {5, 1}, {3, 1}};
            int [][] dist=Dijkstra_alg(N,E,Mat,S);
            System.out.println(dist.length);
            System.out.println(ans.length);
            for (int i = 0; i < N; i++)
            {
                System.out.println(dist[i][0]+"\t\t"+dist[i][1]);
                System.out.println(ans[i][0]+"\t\t"+ans[i][1]);
            }
            System.out.println((Arrays.deepEquals(dist,ans)));
        }

}

dist and ans print exactly the same result, but even then, Arrays.deepEquals returns false. Cant figure out why is it displaying false

both these arrays are identical, but giving the result false

the output looks like :

5
5
0               1
0               1
8               1
8               1
6               1
6               1
5               1
5               1
3               1
3               1
false

as you can see the output is exactly identical and shouldn't be giving such an error, but it still does. Cannot figure out why this is happening.

Does anyone know how to fix this?

Body:
int dist[][] = new int[n][n];

The second dimension of dist is n, while the second dimension of ans is 2.

Change it to

int dist[][] = new int[n][2];


问:
Does vscode support session setting?
I have default user settings configured, but I need to tweak the settings only for this opened vscode session. Does vscode support this?

or do we have any workaround for this?

答:
There is no way to change settings for a "session" of vscode; however, it is possible to specify settings for a workspace. A workspace is the current open folder.

Type Ctrl+Shift+P and search for Workspace Settings.

Title: Does vscode support session setting?


问:
How can I implement the deprecated full crosshair pointer functionality in MATLAB?
I'm trying to replace the pointer on a chart plot with a full crosshair (that is, a set of 2 perpendicular lines that stretch to the edges of the plot vertically and horizontally and follow the mouse cursor). Years ago, I was able to accomplish this with this line of code:

```<code>set(gcf,'Pointer','fullcross')
</code>```

However, when I try to run this line now, I get the following message:

```<code>Warning: Full crosshair pointer is no longer supported. A crosshair pointer will be used instead.
</code>```

I would really like to find an alternative way to implement this functionality, but have been unable to thus far. I have come across the following function: MYGINPUT, but it does not seem to accomplish what I'm looking for. Does anyone have any suggestions?

答:
You can actually do this by adding a 'WindowButtonMotionFcn' to your figure (assuming nothing else is using it) that will display crosshair lines in your axes when your mouse is over it. Here's a function that creates such functionality for all axes in a figure:

```<code>function full_crosshair(hFigure)

  % Find axes children:
  hAxes = findall(hFigure, 'Type', 'axes');

  % Get all axes limits:
  xLimits = get(hAxes, 'XLim');
  xLimits = vertcat(xLimits{:});
  yLimits = get(hAxes, 'YLim');
  yLimits = vertcat(yLimits{:});

  % Create lines (not displayed yet due to NaNs) and listeners:
  for iAxes = 1:numel(hAxes)
    hHoriz(iAxes) = line(xLimits(iAxes, :), nan(1, 2), 'Parent', hAxes(iAxes));
    hVert(iAxes) = line(nan(1, 2), yLimits(iAxes, :), 'Parent', hAxes(iAxes));
    listenObj(iAxes) = addlistener(hAxes(iAxes), {'XLim', 'YLim'}, ...
                                   'PostSet', @(~, ~) update_limits(iAxes));
  end

  % Set callback on the axes parent to the nested function below:
  set(hFigure, 'WindowButtonMotionFcn', @show_lines);

  function update_limits(axesIndex)
    xLimits(axesIndex, :) = get(hAxes(axesIndex), 'XLim');
    yLimits(axesIndex, :) = get(hAxes(axesIndex), 'YLim');
    set(hHoriz(axesIndex), 'XData', xLimits(axesIndex, :));
    set(hVert(axesIndex), 'YData', yLimits(axesIndex, :));
  end

  function show_lines(~, ~)

    % Get current cursor positions in axes:
    cursorPos = get(hAxes, 'CurrentPoint');
    cursorPos = vertcat(cursorPos{:});
    cursorPos = cursorPos(1:2:end, 1:2);

    % Determine if the cursor is within an axes:
    inAxes = (cursorPos(:, 1) >= xLimits(:, 1)) & ...
             (cursorPos(:, 1) <= xLimits(:, 2)) & ...
             (cursorPos(:, 2) >= yLimits(:, 1)) & ...
             (cursorPos(:, 2) <= yLimits(:, 2));

    % Update lines and cursor:
    if any(inAxes)  % Cursor within an axes
      set(hFigure, 'Pointer', 'custom', 'PointerShapeCData', nan(16));
      set(hHoriz(inAxes), {'YData'}, num2cell(cursorPos(inAxes, 2)*[1 1], 2));
      set(hVert(inAxes), {'XData'}, num2cell(cursorPos(inAxes, 1)*[1 1], 2));
      set(hHoriz(~inAxes), 'YData', nan(1, 2));
      set(hVert(~inAxes), 'XData', nan(1, 2));
    else  % Cursor outside axes
      set(hFigure, 'Pointer', 'arrow');
      set(hHoriz, 'YData', nan(1, 2));
      set(hVert, 'XData', nan(1, 2));
    end

  end

end
</code>```

If you do the following:

```<code>full_crosshair(gcf);
</code>```

Then as you move the cursor over each axes in your figure the cursor will disappear and you will see two lines appear and track the mouse position. If any of the axes limits change, then the event listeners in the above code will detect and account for it. If axes are added to or removed from the figure, you will need to call full_crosshair again to update 'WindowButtonMotionFcn' accordingly.

Finally, you can turn it off by just clearing 'WindowButtonMotionFcn':

```<code>set(gcf, 'WindowButtonMotionFcn', []);
</code>```

Body:
I'm trying to replace the pointer on a chart plot with a full crosshair (that is, a set of 2 perpendicular lines that stretch to the edges of the plot vertically and horizontally and follow the mouse cursor). Years ago, I was able to accomplish this with this line of code:

set(gcf,'Pointer','fullcross')

However, when I try to run this line now, I get the following message:

Warning: Full crosshair pointer is no longer supported. A crosshair pointer will be used instead.

I would really like to find an alternative way to implement this functionality, but have been unable to thus far. I have come across the following function: MYGINPUT, but it does not seem to accomplish what I'm looking for. Does anyone have any suggestions?

Body:
You can actually do this by adding a 'WindowButtonMotionFcn' to your figure (assuming nothing else is using it) that will display crosshair lines in your axes when your mouse is over it. Here's a function that creates such functionality for all axes in a figure:

function full_crosshair(hFigure)

  % Find axes children:
  hAxes = findall(hFigure, 'Type', 'axes');

  % Get all axes limits:
  xLimits = get(hAxes, 'XLim');
  xLimits = vertcat(xLimits{:});
  yLimits = get(hAxes, 'YLim');
  yLimits = vertcat(yLimits{:});

  % Create lines (not displayed yet due to NaNs) and listeners:
  for iAxes = 1:numel(hAxes)
    hHoriz(iAxes) = line(xLimits(iAxes, :), nan(1, 2), 'Parent', hAxes(iAxes));
    hVert(iAxes) = line(nan(1, 2), yLimits(iAxes, :), 'Parent', hAxes(iAxes));
    listenObj(iAxes) = addlistener(hAxes(iAxes), {'XLim', 'YLim'}, ...
                                   'PostSet', @(~, ~) update_limits(iAxes));
  end

  % Set callback on the axes parent to the nested function below:
  set(hFigure, 'WindowButtonMotionFcn', @show_lines);

  function update_limits(axesIndex)
    xLimits(axesIndex, :) = get(hAxes(axesIndex), 'XLim');
    yLimits(axesIndex, :) = get(hAxes(axesIndex), 'YLim');
    set(hHoriz(axesIndex), 'XData', xLimits(axesIndex, :));
    set(hVert(axesIndex), 'YData', yLimits(axesIndex, :));
  end

  function show_lines(~, ~)

    % Get current cursor positions in axes:
    cursorPos = get(hAxes, 'CurrentPoint');
    cursorPos = vertcat(cursorPos{:});
    cursorPos = cursorPos(1:2:end, 1:2);

    % Determine if the cursor is within an axes:
    inAxes = (cursorPos(:, 1) >= xLimits(:, 1)) & ...
             (cursorPos(:, 1) <= xLimits(:, 2)) & ...
             (cursorPos(:, 2) >= yLimits(:, 1)) & ...
             (cursorPos(:, 2) <= yLimits(:, 2));

    % Update lines and cursor:
    if any(inAxes)  % Cursor within an axes
      set(hFigure, 'Pointer', 'custom', 'PointerShapeCData', nan(16));
      set(hHoriz(inAxes), {'YData'}, num2cell(cursorPos(inAxes, 2)*[1 1], 2));
      set(hVert(inAxes), {'XData'}, num2cell(cursorPos(inAxes, 1)*[1 1], 2));
      set(hHoriz(~inAxes), 'YData', nan(1, 2));
      set(hVert(~inAxes), 'XData', nan(1, 2));
    else  % Cursor outside axes
      set(hFigure, 'Pointer', 'arrow');
      set(hHoriz, 'YData', nan(1, 2));
      set(hVert, 'XData', nan(1, 2));
    end

  end

end

If you do the following:

full_crosshair(gcf);

Then as you move the cursor over each axes in your figure the cursor will disappear and you will see two lines appear and track the mouse position. If any of the axes limits change, then the event listeners in the above code will detect and account for it. If axes are added to or removed from the figure, you will need to call full_crosshair again to update 'WindowButtonMotionFcn' accordingly.

Finally, you can turn it off by just clearing 'WindowButtonMotionFcn':

set(gcf, 'WindowButtonMotionFcn', []);


问:
How do I refactor a view to allow filtering of items bound to an observableArrayList inside a tornadofx app
I started with the gradle hello-world example found https://github.com:JetBrains/kotlin-examples.git and modified it to use TornadoFX.

This is an app that displays a list of items. You can add to the list, and the RequestView will automatically display all the items.

I have it working so that the items stored are bound to an observableArrayList but I now want to implement a filter using the TextView at the bottom. But, I'm struggling to understand whether this means I should create a new list which is managed internally in the RequestView, and filter from that, or how to do it.

```<code>package demo

import javafx.collections.FXCollections
import javafx.geometry.Pos
import javafx.scene.control.TextField
import javafx.scene.layout.VBox
import javafx.scene.text.FontWeight
import tornadofx.*

class helloWorldApp : App(HelloWorld::class) {
}

class HelloWorld : View() {

    override val root = VBox()

    var requestView: RequestView by singleAssign()
    var filterField: TextField by singleAssign()

    init {
        with(root) {
            requestView = RequestView()
            this += requestView
            filterField = TextField()
            this += filterField
        }

        requestView.items.add("Hi there")
        requestView.items.add("Another one")

    }

}

class RequestView() : View() {
    var items = FXCollections.observableArrayList<String>()

    override val root = listview(items) {
        cellFormat {
            graphic = cache {
                form {
                    fieldset {
                        label(it) {
                            alignment = Pos.CENTER_LEFT
                            style {
                                fontSize = 15.px
                                fontWeight = FontWeight.BOLD
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

Here is the build.gradle file, just in case it is helpful.

```<code>buildscript {
  ext.kotlin_version = '1.1.2'
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

apply plugin: 'kotlin'
apply plugin: 'application'

mainClassName = 'demo.helloWorldApp'

defaultTasks 'run'

repositories {
  mavenCentral()
}

tasks.compileKotlin.kotlinOptions.jvmTarget = "1.8"

dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  testCompile 'junit:junit:4.11'
  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  compile 'no.tornado:tornadofx:1.7.10'
}

task wrapper(type: Wrapper) {
  gradleVersion = "2.7"
}
</code>```

答:
You should use the SortedFilteredList which wraps an ObservableList and accepts a predicate which is used to discriminate the entries.

There is an unfortunate coupling between your two views, so you should consider firing an event instead, but here is a working solution with minimal changes to your example. I did move the data to a model, and cleaned up the ui code, as well as got rid of the singleAssign statements and applied some best practices to the builders :)

As you can see, the SortedFilteredList has a filterWhen function that will be called whenever the textProperty() of the textfield changes.

```<code>class HelloWorldApp : App(HelloWorld::class)

class HelloWorld : View() {
    val requestView: RequestView by inject()

    override val root = vbox {
        add(requestView)
        textfield {
            promptText = "Filter"
            requestView.data.filterWhen(textProperty()) { query, item ->
                item.contains(query, ignoreCase = true)
            }
        }
    }
}

class ItemsModel : ViewModel() {
    val items = FXCollections.observableArrayList<String>()

    fun addItem(item: String) = items.add(item)

    init {
        addItem("Hi there")
        addItem("Another one")
    }
}

class RequestView() : View() {
    val model: ItemsModel by inject()
    val data = SortedFilteredList(model.items)

    override val root = listview(data) {
        cellFormat {
            graphic = cache {
                form {
                    fieldset {
                        label(it) {
                            alignment = Pos.CENTER_LEFT
                            style {
                                fontSize = 15.px
                                fontWeight = FontWeight.BOLD
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

Body:
I started with the gradle hello-world example found https://github.com:JetBrains/kotlin-examples.git and modified it to use TornadoFX.

This is an app that displays a list of items. You can add to the list, and the RequestView will automatically display all the items.

I have it working so that the items stored are bound to an observableArrayList but I now want to implement a filter using the TextView at the bottom. But, I'm struggling to understand whether this means I should create a new list which is managed internally in the RequestView, and filter from that, or how to do it.

package demo

import javafx.collections.FXCollections
import javafx.geometry.Pos
import javafx.scene.control.TextField
import javafx.scene.layout.VBox
import javafx.scene.text.FontWeight
import tornadofx.*

class helloWorldApp : App(HelloWorld::class) {
}

class HelloWorld : View() {

    override val root = VBox()

    var requestView: RequestView by singleAssign()
    var filterField: TextField by singleAssign()

    init {
        with(root) {
            requestView = RequestView()
            this += requestView
            filterField = TextField()
            this += filterField
        }

        requestView.items.add("Hi there")
        requestView.items.add("Another one")

    }

}

class RequestView() : View() {
    var items = FXCollections.observableArrayList<String>()

    override val root = listview(items) {
        cellFormat {
            graphic = cache {
                form {
                    fieldset {
                        label(it) {
                            alignment = Pos.CENTER_LEFT
                            style {
                                fontSize = 15.px
                                fontWeight = FontWeight.BOLD
                            }
                        }
                    }
                }
            }
        }
    }
}

Here is the build.gradle file, just in case it is helpful.

buildscript {
  ext.kotlin_version = '1.1.2'
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

apply plugin: 'kotlin'
apply plugin: 'application'

mainClassName = 'demo.helloWorldApp'

defaultTasks 'run'

repositories {
  mavenCentral()
}

tasks.compileKotlin.kotlinOptions.jvmTarget = "1.8"

dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  testCompile 'junit:junit:4.11'
  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  compile 'no.tornado:tornadofx:1.7.10'
}

task wrapper(type: Wrapper) {
  gradleVersion = "2.7"
}

Body:
You should use the SortedFilteredList which wraps an ObservableList and accepts a predicate which is used to discriminate the entries.

There is an unfortunate coupling between your two views, so you should consider firing an event instead, but here is a working solution with minimal changes to your example. I did move the data to a model, and cleaned up the ui code, as well as got rid of the singleAssign statements and applied some best practices to the builders :)

As you can see, the SortedFilteredList has a filterWhen function that will be called whenever the textProperty() of the textfield changes.

class HelloWorldApp : App(HelloWorld::class)

class HelloWorld : View() {
    val requestView: RequestView by inject()

    override val root = vbox {
        add(requestView)
        textfield {
            promptText = "Filter"
            requestView.data.filterWhen(textProperty()) { query, item ->
                item.contains(query, ignoreCase = true)
            }
        }
    }
}

class ItemsModel : ViewModel() {
    val items = FXCollections.observableArrayList<String>()

    fun addItem(item: String) = items.add(item)

    init {
        addItem("Hi there")
        addItem("Another one")
    }
}

class RequestView() : View() {
    val model: ItemsModel by inject()
    val data = SortedFilteredList(model.items)

    override val root = listview(data) {
        cellFormat {
            graphic = cache {
                form {
                    fieldset {
                        label(it) {
                            alignment = Pos.CENTER_LEFT
                            style {
                                fontSize = 15.px
                                fontWeight = FontWeight.BOLD
                            }
                        }
                    }
                }
            }
        }
    }
}


问:
How to get rid of warning message that is displayed when user tries to open Excel spreadsheet?
I am using version 3.17 of the Apache POI library to create an Excel spreadsheet in Java. When the user downloads it from the server and attempts to open the spreadsheet, a warning message is displayed. I am thinking that the format of the spreadsheet is somehow not correct. How do I fix it so that the user will not see that message? It is important to note that the spreadsheet opens fine, and all the data is there.

```<code>XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet;

// Add rows and cells to spreadsheet

response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=sheet.xls");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
bos.close();

try (InputStream stream = new ByteArrayInputStream(bos.toByteArray())) {
  IOUtils.copy(stream, response.getOutputStream());
}
</code>```

答: The extension should be .xlsx, not .xls

Body:
I am using version 3.17 of the Apache POI library to create an Excel spreadsheet in Java. When the user downloads it from the server and attempts to open the spreadsheet, a warning message is displayed. I am thinking that the format of the spreadsheet is somehow not correct. How do I fix it so that the user will not see that message? It is important to note that the spreadsheet opens fine, and all the data is there.

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet;

// Add rows and cells to spreadsheet

response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=sheet.xls");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
bos.close();

try (InputStream stream = new ByteArrayInputStream(bos.toByteArray())) {
  IOUtils.copy(stream, response.getOutputStream());
}

Body: The extension should be .xlsx, not .xls


问:
How to make a border triangle using css?
How to create border triangle?

The only thing I can think of to make this is to make a triangle

```<code>    .triangle {
        width: 0;
        height: 0;
        border-left: 15px solid transparent;
        border-right: 15px solid transparent;
        border-bottom: 20px solid #8e8e8e;
    }
</code>```

But this is a solid triangle, is there a way to make it look like the triangle extends the border

答:
You need to move triangle element to under sub layout.
I added more triangle for the border design.

.balon {
  width: 350px;
  height: 120px;
  border: 5px solid #2C6DBF;
  margin: 50px auto;
  position: relative;
  border-radius: 8px;
}
.balon::after, .balon::before {
  width: 0;
  height: 0;
  content: '';
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 21px solid #fff;
  position: absolute;
  bottom: -19px;
  right: 0;
  left: 0;
  margin: auto;
}
.balon::before {
  border-left-width: 20px;
  border-right-width: 20px;
  border-top-width: 25px;
  border-top-color: #2C6DBF;
  bottom: -25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="balon">

</div></code>```

Body:
How to create border triangle?

The only thing I can think of to make this is to make a triangle

    .triangle {
        width: 0;
        height: 0;
        border-left: 15px solid transparent;
        border-right: 15px solid transparent;
        border-bottom: 20px solid #8e8e8e;
    }

But this is a solid triangle, is there a way to make it look like the triangle extends the border

Body:
You need to move triangle element to under sub layout.
I added more triangle for the border design.

.balon {
  width: 350px;
  height: 120px;
  border: 5px solid #2C6DBF;
  margin: 50px auto;
  position: relative;
  border-radius: 8px;
}
.balon::after, .balon::before {
  width: 0;
  height: 0;
  content: '';
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 21px solid #fff;
  position: absolute;
  bottom: -19px;
  right: 0;
  left: 0;
  margin: auto;
}
.balon::before {
  border-left-width: 20px;
  border-right-width: 20px;
  border-top-width: 25px;
  border-top-color: #2C6DBF;
  bottom: -25px;
}

<div class="balon">

</div>


问:
React Native Linking.addEventListener() Not Firing When App is in Tray
Using React Native Linking and Firebase to generate dynamic links. Everything is working as it should unless the app is open in the background or "tray" when you click the link. If the app is already open when someone clicks the link it does nothing.

My listener is set up in componentDidMount like the documentation says, but its not firing.

```<code>componentDidMount() {
  Linking.addEventListener('url', this._handleOpenURL);
},
</code>```

In fact, I've gone through and alerted componentWillMount(), componentDidMount(), componentWillUpdate(), componentWillUnmount(), componentWillReceiveNewProps(), and _handleOpenURL() and I get nothing when I click the link and it "re-opens" the app from the background? What am I doing wrong?

答:
Figured it out, I'll leave the question in case anyone else has the same issue.

Turns out I just needed to add this code block to my AppDelegate.m file.

```<code>- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
  return [RCTLinkingManager application:application
                   continueUserActivity:userActivity
                     restorationHandler:restorationHandler];
}
</code>```

Body:
Using React Native Linking and Firebase to generate dynamic links. Everything is working as it should unless the app is open in the background or "tray" when you click the link. If the app is already open when someone clicks the link it does nothing.

My listener is set up in componentDidMount like the documentation says, but its not firing.

componentDidMount() {
  Linking.addEventListener('url', this._handleOpenURL);
},

In fact, I've gone through and alerted componentWillMount(), componentDidMount(), componentWillUpdate(), componentWillUnmount(), componentWillReceiveNewProps(), and _handleOpenURL() and I get nothing when I click the link and it "re-opens" the app from the background? What am I doing wrong?

Body:
Figured it out, I'll leave the question in case anyone else has the same issue.

Turns out I just needed to add this code block to my AppDelegate.m file.

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
  return [RCTLinkingManager application:application
                   continueUserActivity:userActivity
                     restorationHandler:restorationHandler];
}


问:
separate first word in a string in python re
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

```<code>for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)
</code>```

Here are some examples of the strings:

```<code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
</code>```

what I need is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,
</code>```

what I am getting is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a
</code>```

答:
There are already good regex answers. You can achieve your goal with str.split alone, though. It accepts an argument specifying the maximum number of splits:

```<code>records = ["Aphis(Aphis)_asclepiadis", "Cinara_011", "Clydesmithia_canadensis_1a"]

for record in records:
    left, right = record.split('_', 1) # Split no more than once.
    left = left.split('(')[0]          # Remove anything after '('
    print(' '.join([left, right]))
# Aphis asclepiadis
# Cinara 011
# Clydesmithia canadensis_1a
</code>```

By the way, you shouldn't call re.compile inside the loop. It's an expensive operation and the pattern doesn't change between records.

Body:
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)

Here are some examples of the strings:

Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,

what I need is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,

what I am getting is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a

Body:
There are already good regex answers. You can achieve your goal with str.split alone, though. It accepts an argument specifying the maximum number of splits:

records = ["Aphis(Aphis)_asclepiadis", "Cinara_011", "Clydesmithia_canadensis_1a"]

for record in records:
    left, right = record.split('_', 1) # Split no more than once.
    left = left.split('(')[0]          # Remove anything after '('
    print(' '.join([left, right]))
# Aphis asclepiadis
# Cinara 011
# Clydesmithia canadensis_1a

By the way, you shouldn't call re.compile inside the loop. It's an expensive operation and the pattern doesn't change between records.


问:
Creating Web Application in Android
How to create an offline web application in Android using android.webkit package?</p>

答:
The following article talks about creating an offline web application in Android using android.webkit package.

http://www.linux-mag.com/id/7633/1/

Title: Creating Web Application in Android


问:
Modify loopback model before returning to client
I have a ServerFile model which stores various pieces of information about an uploaded file.

```<code>{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
}
</code>```

I would like to return a dynamically url property with the object, without storing it in a database.

```<code>{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
 url: 'uploads/images/blah.jpeg'
}
</code>```

How would I go about doing this?

答:
In your common/models/server-file.js file add a remote hook on find.

```<code>module.exports = function(ServerFile) {
....
ServerFile.afterRemote('find', function(ctx, modelInstance, next) {
    if (ctx.result) {
      if (Array.isArray(ctx.result)) {
        ctx.result.forEach(function(result) {
          result.url = new String(result.constructUrl());
        });
      } else {
        result.url = new String(result.constructUrl());
      }
    }
    next();
  });
</code>```

Additionally, if you wished to remove an attribute before sending it back you can use

result.unsetAttribute('password')

Body:
I have a ServerFile model which stores various pieces of information about an uploaded file.

{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
}

I would like to return a dynamically url property with the object, without storing it in a database.

{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
 url: 'uploads/images/blah.jpeg'
}

How would I go about doing this?

Body:
In your common/models/server-file.js file add a remote hook on find.

module.exports = function(ServerFile) {
....
ServerFile.afterRemote('find', function(ctx, modelInstance, next) {
    if (ctx.result) {
      if (Array.isArray(ctx.result)) {
        ctx.result.forEach(function(result) {
          result.url = new String(result.constructUrl());
        });
      } else {
        result.url = new String(result.constructUrl());
      }
    }
    next();
  });

Additionally, if you wished to remove an attribute before sending it back you can use

result.unsetAttribute('password')


答:
Create an :after or :before element that absolutely positions at the bottom of your div.

.box {
  position: relative;
  background-color: #F00;
  border: 1px solid #000;
  width: 50px;
  height: 50px;
}

.box:after {
  content: "";
  width: 16px;
  height: 16px;
  position: absolute;
  background-color: #FFF;
  bottom: -8px;  /* half of the elements width/height */
  left: 50%;
  transform: translateX(-50%) rotate(45deg);
  border-bottom: 1px solid #000;
  border-right: 1px solid #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></code>```

I've made the :after element white so you can see what's happening inside of it.

Title: How to make a border triangle using css?

Body:
Create an :after or :before element that absolutely positions at the bottom of your div.

.box {
  position: relative;
  background-color: #F00;
  border: 1px solid #000;
  width: 50px;
  height: 50px;
}

.box:after {
  content: "";
  width: 16px;
  height: 16px;
  position: absolute;
  background-color: #FFF;
  bottom: -8px;  /* half of the elements width/height */
  left: 50%;
  transform: translateX(-50%) rotate(45deg);
  border-bottom: 1px solid #000;
  border-right: 1px solid #000;
}

<div class="box">

I've made the :after element white so you can see what's happening inside of it.


问:
Angular and node js SPA- what happens behind the scenes when i navigate between components?
im having trouble to understand how the combination of angular and node js can create a SPA website.

my question will be better understanable with an example:
lets say im trying to build a spa website:

client side - angular 4:

i have several components in my app, and configured routes to all these components.

i used ng build from the angular cli, and it created the dist folder with index.html.

on the server side - node js:
i used a static route for the index.html file.

when accessing the server via browser i get the index.html,
all the angular routes are working and can navigate between components successfully.

but i cant understand really what is happening behind the scenes every time i navigate to a diffrent component,
do i get that component from the server?
(then it wont be SPA..)

when i access the static path the first time, does all the components get downloaded to the users browser, and from then on , the navigation only happens on the client?

what that index html contains ? what does the ng build command does ?

答:
No. The router removes the view of the current route component from the DOM, and replaces it by the view of the newly routed component. It also pushes a new entry in the navigation history of the browser to do "as if" you really downloaded a new page from the URL of the new route.

Yes.

The content of the index.html is exactly what you see when viewing the source of the page in the browser. Or when viewing the content of the index.html file in the dist directory. It's simply an HTML page, with the root component, and a few JS scripts. These JS scripts are bundles, created by ng build, which contain the result of the TypeScript compilation of all your files, JS modules of Angular that your app uses and, deending on how you build the app (i.e. without or with --aot), the templates of the components or the result of the compilation of these templates (+ the CSS files of the component). In short, the whole app is bundled in those JS scripts.


问:
How to join two dataframes with dplyr based on two columns with different names in each dataframe?
This is a really simple question, but can't find a suitable answer here.

How does one join two data.frames with dplyr based on two columns with different names in each data.frame?

With base::merge one can simply merge:

```<code>df3 <- merge(df1, df2, by.x=c("name1", "name2"), by.y=c("name3", "name4"))
</code>```

where df1$name1 == df2$name3 and df1$name2 == df2$name4.

How does one do this in dplyr?

I know that one can use the by function in dplyr to do join two data.frames with based on one column with a different name:

```<code>df3 <- dplyr::left_join(df1, df2, by=c("name1" = "name3"))
</code>```

答:
```<code>df3 <- dplyr::left_join(df1, df2, by=c("name1" = "name3", "name2" = "name4"))
</code>```

Body:
This is a really simple question, but can't find a suitable answer here.

How does one join two data.frames with dplyr based on two columns with different names in each data.frame?

With base::merge one can simply merge:

df3 <- merge(df1, df2, by.x=c("name1", "name2"), by.y=c("name3", "name4"))

where df1$name1 == df2$name3 and df1$name2 == df2$name4.

How does one do this in dplyr?

I know that one can use the by function in dplyr to do join two data.frames with based on one column with a different name:

df3 <- dplyr::left_join(df1, df2, by=c("name1" = "name3"))


问:
How can I arrange sorted data in UITableViewController
I used iphones address book data in my app ,i sorted that data and arranged in UITableViewController,but now i want to make same look as of address book means sorted in GroupedStyle having initial character as heading of section .and suggestion plz</p>

答:
Use something like following to sort the contacts:

```<code>    NSArray* tempArray = [jsonData objectForKey:@"contacts"];
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"first_name"
                                                 ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    contactsArray = [[NSArray alloc] initWithArray:[tempArray  sortedArrayUsingDescriptors:sortDescriptors]];
</code>```

From the use NSPredicate to pick the contacts and add them to section that you want.

Body:
Use something like following to sort the contacts:

    NSArray* tempArray = [jsonData objectForKey:@"contacts"];
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"first_name"
                                                 ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    contactsArray = [[NSArray alloc] initWithArray:[tempArray  sortedArrayUsingDescriptors:sortDescriptors]];

From the use NSPredicate to pick the contacts and add them to section that you want.


问:
Database with GUI on SharePoint
I need a rescue! I have database in MS Access which contains list of computers in company(number, RAM, CPU, department, location, name, surname etc) on my local computer. We created a few "user-friendly" forms e.g. "Add new computer", "Add new department", "Add Location" etc. My manager wants to have an access to this database via webpage (our company's site on Sharepoint). I have a huuuuuge problem with it. I read that MS Access isn't support anymore by Microsoft so they don't recommend publishing on Sharpoint Access aplications. My question is what can i do with this problem. I can make everything once again using different tools, but i have no idea how to start. I need database where i will have list of computers, i need also some GUI for users (with menu, for simple and "user-friendly" adding new computers, departmets etc.) and i need to have it on Sharepoint. Could you help me? I'm a begginer developer and i have nobody who could help me with the concept of this small project. I have no idea about sharepoint and unfortunatelly i even don't have any access to try do anything.</p>

答:
Classic Access is a Windows app.  Microsoft began but then ended & deprecated their attempt to have an Access Web app.

One can get remote connectivity to a Windows app (Access) a couple of different ways:
 + VPN, GoToMyPC, remote connection
 + SharePoint - the same as sharing any file i.e. Word, Excel, etc.

These aren't a multi user deployment - just allowing a single user to get to their app from a remote location.

For a browser based database with a small set of users - you probably don't want to build one from scratch and instead use a commercial service out there: Knack, AirTable, Soho.

Title: Database with GUI on SharePoint


问:
Java generic class cast exception thrown outside
When I execute this I get a ClassCastException on line 9. I'm wondering why the exception happens there. From what I understand about generics, I would expect type inference to cause the exception to be thrown in the try catch.

This is compiled using 1.7.

```<code>public class MyClass {
    private static Map<String, Object> map = new HashMap<>();

    public static void main(String args[]) {
        map.put("key", Integer.valueOf(1));
        Float c = method("key");
    }

    public static <T> T method(String k) {
        try {
            return (T) map.get(k);
        } catch (ClassCastException ex) {
            System.out.println(ex);
            return null;
        }
    }
}
</code>```

Is there any way to get the exception to be thrown within the method? I've seen usages below but I don't have access to the Float.class at time of call.

```<code>method(Float.class, "key")

public static <T> T method(Class<T> clazz, String k) {
    try {
        return clazz.cast(map.get(k));
...
</code>```

答:
This is because of type erasure

Actually your code after erasure will look as:

```<code>public static void main(String args[]) {
    map.put("key", Integer.valueOf(1));
    Float c = (Float) method("key");
}

public static Object method(String k) {
    try {
        return map.get(k);
    } catch (ClassCastException ex) {
        System.out.println(ex);
        return null;
    }
}
</code>```

That's why you got exception in a line which wasn't expected by you.

UPD: it seems you'll have to use reflection to inspect the actual type of the returned object.

Body:
When I execute this I get a ClassCastException on line 9. I'm wondering why the exception happens there. From what I understand about generics, I would expect type inference to cause the exception to be thrown in the try catch.

This is compiled using 1.7.

public class MyClass {
    private static Map<String, Object> map = new HashMap<>();

    public static void main(String args[]) {
        map.put("key", Integer.valueOf(1));
        Float c = method("key");
    }

    public static <T> T method(String k) {
        try {
            return (T) map.get(k);
        } catch (ClassCastException ex) {
            System.out.println(ex);
            return null;
        }
    }
}

Is there any way to get the exception to be thrown within the method? I've seen usages below but I don't have access to the Float.class at time of call.

method(Float.class, "key")

public static <T> T method(Class<T> clazz, String k) {
    try {
        return clazz.cast(map.get(k));
...

Body:
This is because of type erasure

Actually your code after erasure will look as:

public static void main(String args[]) {
    map.put("key", Integer.valueOf(1));
    Float c = (Float) method("key");
}

public static Object method(String k) {
    try {
        return map.get(k);
    } catch (ClassCastException ex) {
        System.out.println(ex);
        return null;
    }
}

That's why you got exception in a line which wasn't expected by you.

UPD: it seems you'll have to use reflection to inspect the actual type of the returned object.


问:
AnyLogic: Improving computational performance of a network model
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

```<code>int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;
</code>```

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?

答:
As the other answers cover, your question is really two questions:

the memory usage and 'underlying' model speed due to non-linearly-increasing total network connections as the number of agents increases (since each agent is connected to every other agent);

your stats gathering efficiency.

I'm surprised no-one mentioned it, but the main performance issue with the latter is because (it seems) you are re-calculating the statistic whenever it is needed (and you don't specify how often the calculation is needed) rather than just maintaining the counts as states change that affect them.

(This is a general programming trade-off of (a) minimising memory and avoiding potential bugs in not updating counts at all the appropriate times [as in your approach] vs. (b) speed by retaining counts and only updating them when events they depend on occur.)

So just have each agent update the count in its connected agents whenever it changes from non-infected to infected or vice versa.

As an illustration, imagine you have 10 agents, and so 9 connections per agent (90 connections total). Let's say an agent changes to/from infected every 10 simulated minutes (on average) and you run for 60 mins. And that you update the 'infected connections count' in each agent every minute. (If you were being efficient, this interval would be the minimum period between possible transitions but it may well be that you are querying it much more frequently than that, or that the minimum period is very small.)

With your method, you will check 90 connections 60 times (so 5400 accesses to agents, as well as the overhead of getting/looping through the connections for each agent).

With my method, there will be 6x10 = 60 relevant transitions, and so 60x9 = 540 accesses to agents (to increment/decrement counts), plus only getting/looping through an agent's connections 60 times instead of 60x10 = 600 times. So a >10x performance improvement.

The efficiency obviously improves the 'rarer' transitions are compared to how often you need to use the statistic (and vice versa) so, in some contexts, the two methods will be similar performance.

Body:
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?

ContentLicense: CC BY-SA 4.0


问:
OnFocus and onBlur get fired 3 Times without focusing or leaving input Field
I made a new component for my input field in this component i tried to give the input field a class when it is focused and remove it when the focus get´s lost.
Sidenote the form is in a Modal (npm react-responsive-modal). as soon as the modal and the input component gets loaded the onFocus and onBlur event get triggerd 3 Times each.

Here the form.js component

```<code>import React, { Component } from 'react';

class FormInput extends Component {

    constructor(props) {
        super(props);

        this.state = {
            selected: false,
        };
    }

    onFocus = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: true });
        console.log("Focus")
    };

    onBlur = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: false });
        console.log("Leave")
    };

    render() {
        return (
            <div className="input" >
                <input onFocus={this.onFocus()} onBlur={this.onBlur()} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
                <label className="input-label" htmlFor={this.props.id}>E-Mail</label>
            </div>
        );
    }
}

export default FormInput;
</code>```

The render function of the parent component.

```<code>render() {
    return (
        <Modal open={this.state.open} onClose={this.onCloseModal} little>
            <div className="App">
                {this.state.errors.map((error) => {
                    return <li key={error}>{error}</li>
                })}
                <form onSubmit={ this.onFormSubmit } autoComplete="off">
                    <FormInput placeholder="E-Mail" type="text" id="email"/>
                    <input type="submit" />
                </form>
                <button onClick={ this.logout }>Logout</button>
            </div>
        </Modal>
    );
}
</code>```

答:
When you are setting the onFocus and onBlur attribs, you are actually calling the function immediately. You need to remove the () after the function name:

```<code> <input onFocus={this.onFocus} onBlur={this.onBlur} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
</code>```

You see the functions being called three times because each time the component renders, it is calling those functions.

Body:
I made a new component for my input field in this component i tried to give the input field a class when it is focused and remove it when the focus get´s lost.
Sidenote the form is in a Modal (npm react-responsive-modal). as soon as the modal and the input component gets loaded the onFocus and onBlur event get triggerd 3 Times each.

Here the form.js component

import React, { Component } from 'react';

class FormInput extends Component {

    constructor(props) {
        super(props);

        this.state = {
            selected: false,
        };
    }

    onFocus = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: true });
        console.log("Focus")
    };

    onBlur = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: false });
        console.log("Leave")
    };

    render() {
        return (

                <input onFocus={this.onFocus()} onBlur={this.onBlur()} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
                E-Mail

        );
    }
}

export default FormInput;

The render function of the parent component.

render() {
    return (
        <Modal open={this.state.open} onClose={this.onCloseModal} little>

                {this.state.errors.map((error) => {
                    return
{error}

                })}
                <form onSubmit={ this.onFormSubmit } autoComplete="off">
                    <FormInput placeholder="E-Mail" type="text" id="email"/>
                    <input type="submit" />
                </form>
                <button onClick={ this.logout }>Logout</button>

        </Modal>
    );
}

Body:
When you are setting the onFocus and onBlur attribs, you are actually calling the function immediately. You need to remove the () after the function name:

 <input onFocus={this.onFocus} onBlur={this.onBlur} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />

You see the functions being called three times because each time the component renders, it is calling those functions.


问:
How to setup Filezilla Pro to access to my s3 bucket?
I bought Filezilla Pro that supports Amazon S3, so pls how to setup Filezilla Pro to access into my bucket? Thank you</p>

答:
When using Filezilla Pro to connect AWS S3 , do not forget to add the Bucket name (and any sub folders under the bucket) in "Default remote directory" section of Advanced tab.
Please refer the screen shot.